termdock 1.4.351 → 1.4.353

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.
Files changed (444) hide show
  1. package/dist/client/assets/AndroidMirrorView-C39BgFa_.js +3 -0
  2. package/dist/client/assets/AndroidMirrorView-C39BgFa_.js.br +0 -0
  3. package/dist/client/assets/AndroidMirrorView-C39BgFa_.js.gz +0 -0
  4. package/dist/client/assets/App-AjjtXg93.js +178 -0
  5. package/dist/client/assets/App-AjjtXg93.js.br +0 -0
  6. package/dist/client/assets/App-AjjtXg93.js.gz +0 -0
  7. package/dist/client/assets/ArchitecturePanel-Xi_R4Tso.js +9 -0
  8. package/dist/client/assets/ArchitecturePanel-Xi_R4Tso.js.br +0 -0
  9. package/dist/client/assets/ArchitecturePanel-Xi_R4Tso.js.gz +0 -0
  10. package/dist/client/assets/ChangeWalkthroughPanel-BH1Una8m.js +2 -0
  11. package/dist/client/assets/ChangeWalkthroughPanel-BH1Una8m.js.br +0 -0
  12. package/dist/client/assets/ChangeWalkthroughPanel-BH1Una8m.js.gz +0 -0
  13. package/dist/client/assets/CollaborationMainWorkspace-CA9ZGT5N.js +1 -0
  14. package/dist/client/assets/CollaborationMainWorkspace-CA9ZGT5N.js.br +0 -0
  15. package/dist/client/assets/CollaborationMainWorkspace-CA9ZGT5N.js.gz +0 -0
  16. package/dist/client/assets/CollaborationTaskContent-D_NDzA-t.js +2 -0
  17. package/dist/client/assets/ComputerControlView-BGvF5NeQ.js +6 -0
  18. package/dist/client/assets/ComputerControlView-BGvF5NeQ.js.br +0 -0
  19. package/dist/client/assets/ComputerControlView-BGvF5NeQ.js.gz +0 -0
  20. package/dist/client/assets/DagPlayground-CKqB6zap.js +1 -0
  21. package/dist/client/assets/DagPlayground-CKqB6zap.js.br +0 -0
  22. package/dist/client/assets/DagPlayground-CKqB6zap.js.gz +0 -0
  23. package/dist/client/assets/{DiffLab-DFut8ZHi.js → DiffLab-CDt8EP6I.js} +2 -2
  24. package/dist/client/assets/DiffLab-CDt8EP6I.js.br +0 -0
  25. package/dist/client/assets/DiffLab-CDt8EP6I.js.gz +0 -0
  26. package/dist/client/assets/DiffReview-YADkwVd6.js +1 -0
  27. package/dist/client/assets/DiffReview-YADkwVd6.js.br +0 -0
  28. package/dist/client/assets/DiffReview-YADkwVd6.js.gz +0 -0
  29. package/dist/client/assets/{DiffReviewLab-Y9JlI5DQ.js → DiffReviewLab-YqgsRn_K.js} +2 -2
  30. package/dist/client/assets/DiffReviewLab-YqgsRn_K.js.br +0 -0
  31. package/dist/client/assets/DiffReviewLab-YqgsRn_K.js.gz +0 -0
  32. package/dist/client/assets/DiffViewer-CT5_YwM2.js +34 -0
  33. package/dist/client/assets/DiffViewer-CT5_YwM2.js.br +0 -0
  34. package/dist/client/assets/DiffViewer-CT5_YwM2.js.gz +0 -0
  35. package/dist/client/assets/GitLoadingSkeleton-DfWzAnA2.js +1 -0
  36. package/dist/client/assets/GitLoadingSkeleton-DfWzAnA2.js.br +0 -0
  37. package/dist/client/assets/GitLoadingSkeleton-DfWzAnA2.js.gz +0 -0
  38. package/dist/client/assets/MarkdownPreview-DHLp5cqt.js +19 -0
  39. package/dist/client/assets/MarkdownPreview-DHLp5cqt.js.br +0 -0
  40. package/dist/client/assets/MarkdownPreview-DHLp5cqt.js.gz +0 -0
  41. package/dist/client/assets/{ModelPreview-Cv6JgunE.js → ModelPreview-DymFzc55.js} +166 -166
  42. package/dist/client/assets/ModelPreview-DymFzc55.js.br +0 -0
  43. package/dist/client/assets/ModelPreview-DymFzc55.js.gz +0 -0
  44. package/dist/client/assets/RecordingSaveDialog-CxSN76bp.js +1 -0
  45. package/dist/client/assets/RecordingSaveDialog-CxSN76bp.js.br +0 -0
  46. package/dist/client/assets/RecordingSaveDialog-CxSN76bp.js.gz +0 -0
  47. package/dist/client/assets/RightSidebar-eIuDnhJn.js +1662 -0
  48. package/dist/client/assets/RightSidebar-eIuDnhJn.js.br +0 -0
  49. package/dist/client/assets/RightSidebar-eIuDnhJn.js.gz +0 -0
  50. package/dist/client/assets/SessionChatView-C5wXAt7h.js +13 -0
  51. package/dist/client/assets/SessionChatView-C5wXAt7h.js.br +0 -0
  52. package/dist/client/assets/SessionChatView-C5wXAt7h.js.gz +0 -0
  53. package/dist/client/assets/SessionChatView-D8GoESjb.css +1 -0
  54. package/dist/client/assets/SessionChatView-D8GoESjb.css.br +0 -0
  55. package/dist/client/assets/SessionChatView-D8GoESjb.css.gz +0 -0
  56. package/dist/client/assets/SessionResourceSidebar-Czai5Bt3.js +2 -0
  57. package/dist/client/assets/SessionResourceSidebar-Czai5Bt3.js.br +0 -0
  58. package/dist/client/assets/SessionResourceSidebar-Czai5Bt3.js.gz +0 -0
  59. package/dist/client/assets/TodoWorkspace-BftnnEU0.js +1 -0
  60. package/dist/client/assets/TodoWorkspace-BftnnEU0.js.br +0 -0
  61. package/dist/client/assets/TodoWorkspace-BftnnEU0.js.gz +0 -0
  62. package/dist/client/assets/{abnfDiagram-VCTEODGH-CcCffdpj.js → abnfDiagram-VCTEODGH-DI1Y-QAP.js} +1 -1
  63. package/dist/client/assets/abnfDiagram-VCTEODGH-DI1Y-QAP.js.br +0 -0
  64. package/dist/client/assets/abnfDiagram-VCTEODGH-DI1Y-QAP.js.gz +0 -0
  65. package/dist/client/assets/app-DvMXSNN7.js +36 -0
  66. package/dist/client/assets/app-DvMXSNN7.js.br +0 -0
  67. package/dist/client/assets/app-DvMXSNN7.js.gz +0 -0
  68. package/dist/client/assets/{arc-CXcCuzb3.js → arc-QdJAJx_D.js} +1 -1
  69. package/dist/client/assets/arc-QdJAJx_D.js.br +0 -0
  70. package/dist/client/assets/arc-QdJAJx_D.js.gz +0 -0
  71. package/dist/client/assets/{architectureDiagram-5GKGNRK7-CmR7whZz.js → architectureDiagram-5GKGNRK7-Bw2CvoGg.js} +1 -1
  72. package/dist/client/assets/architectureDiagram-5GKGNRK7-Bw2CvoGg.js.br +0 -0
  73. package/dist/client/assets/architectureDiagram-5GKGNRK7-Bw2CvoGg.js.gz +0 -0
  74. package/dist/client/assets/arrow-down-CZKuaGwN.js +1 -0
  75. package/dist/client/assets/arrow-up-CYLC6_to.js +1 -0
  76. package/dist/client/assets/{blockDiagram-I7D4REHJ-DODhUpHm.js → blockDiagram-I7D4REHJ-CM2GI6sC.js} +1 -1
  77. package/dist/client/assets/blockDiagram-I7D4REHJ-CM2GI6sC.js.br +0 -0
  78. package/dist/client/assets/blockDiagram-I7D4REHJ-CM2GI6sC.js.gz +0 -0
  79. package/dist/client/assets/{c4Diagram-7LVT6UL2-BF9eEb2Y.js → c4Diagram-7LVT6UL2-BAB2TKr4.js} +1 -1
  80. package/dist/client/assets/c4Diagram-7LVT6UL2-BAB2TKr4.js.br +0 -0
  81. package/dist/client/assets/c4Diagram-7LVT6UL2-BAB2TKr4.js.gz +0 -0
  82. package/dist/client/assets/channel-CcDRt0AM.js +1 -0
  83. package/dist/client/assets/chevron-left-BNby2AjR.js +1 -0
  84. package/dist/client/assets/{chunk-2Q5K7J3B-CB7-8Zex.js → chunk-2Q5K7J3B-DI2pKKMQ.js} +1 -1
  85. package/dist/client/assets/{chunk-5VM5RSS4-8Uxe2lki.js → chunk-5VM5RSS4-D5l5zyYl.js} +1 -1
  86. package/dist/client/assets/{chunk-F27PBJKO-Bv45U-az.js → chunk-F27PBJKO-Japl432v.js} +1 -1
  87. package/dist/client/assets/{chunk-F27PBJKO-Bv45U-az.js.br → chunk-F27PBJKO-Japl432v.js.br} +0 -0
  88. package/dist/client/assets/chunk-F27PBJKO-Japl432v.js.gz +0 -0
  89. package/dist/client/assets/{chunk-IMKFNOWR-CfEErbEd.js → chunk-IMKFNOWR-CDJoLgpw.js} +1 -1
  90. package/dist/client/assets/chunk-IMKFNOWR-CDJoLgpw.js.br +0 -0
  91. package/dist/client/assets/chunk-IMKFNOWR-CDJoLgpw.js.gz +0 -0
  92. package/dist/client/assets/{chunk-JWPE2WC7-CjUqcCSL.js → chunk-JWPE2WC7-BQ2cpPDE.js} +1 -1
  93. package/dist/client/assets/{chunk-POPQ4Y6H-BHbP3O75.js → chunk-POPQ4Y6H-CWjI0yRx.js} +1 -1
  94. package/dist/client/assets/{chunk-SVP7TREG-CbyJW-OT.js → chunk-SVP7TREG-BzEphMpl.js} +1 -1
  95. package/dist/client/assets/chunk-SVP7TREG-BzEphMpl.js.br +0 -0
  96. package/dist/client/assets/chunk-SVP7TREG-BzEphMpl.js.gz +0 -0
  97. package/dist/client/assets/{chunk-TICWLB2K-t93EivmS.js → chunk-TICWLB2K-B2hsw7jN.js} +1 -1
  98. package/dist/client/assets/chunk-TICWLB2K-B2hsw7jN.js.br +0 -0
  99. package/dist/client/assets/chunk-TICWLB2K-B2hsw7jN.js.gz +0 -0
  100. package/dist/client/assets/{chunk-XXDRQBXY-C_Pe8Osb.js → chunk-XXDRQBXY-BEWjHo7s.js} +1 -1
  101. package/dist/client/assets/classDiagram-ZZMXUADV-Dz0qH9Hg.js +1 -0
  102. package/dist/client/assets/classDiagram-v2-VYDZK3BY-Dz0qH9Hg.js +1 -0
  103. package/dist/client/assets/clipboard-6kE6vzDi.js +1 -0
  104. package/dist/client/assets/clipboardText-B7202UNa.js +1 -0
  105. package/dist/client/assets/clipboardText-B7202UNa.js.br +0 -0
  106. package/dist/client/assets/clipboardText-B7202UNa.js.gz +0 -0
  107. package/dist/client/assets/{cose-bilkent-JH36ORCC-CksG0bvP.js → cose-bilkent-JH36ORCC-DpS77pec.js} +1 -1
  108. package/dist/client/assets/cose-bilkent-JH36ORCC-DpS77pec.js.br +0 -0
  109. package/dist/client/assets/cose-bilkent-JH36ORCC-DpS77pec.js.gz +0 -0
  110. package/dist/client/assets/{cynefin-OW5HDTMX-CV3T078G.js → cynefin-OW5HDTMX-D1y5kNwR.js} +1 -1
  111. package/dist/client/assets/cynefin-OW5HDTMX-D1y5kNwR.js.br +0 -0
  112. package/dist/client/assets/cynefin-OW5HDTMX-D1y5kNwR.js.gz +0 -0
  113. package/dist/client/assets/{cynefinDiagram-5FMLGOSQ-BQnJabEs.js → cynefinDiagram-5FMLGOSQ-CqTCLyMC.js} +1 -1
  114. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-CqTCLyMC.js.br +0 -0
  115. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-CqTCLyMC.js.gz +0 -0
  116. package/dist/client/assets/{dagre-GXQ25YYZ-BeIQp5Pv.js → dagre-GXQ25YYZ-DkJ-kRn6.js} +1 -1
  117. package/dist/client/assets/dagre-GXQ25YYZ-DkJ-kRn6.js.br +0 -0
  118. package/dist/client/assets/dagre-GXQ25YYZ-DkJ-kRn6.js.gz +0 -0
  119. package/dist/client/assets/{diagram-S7CK7UJ4-D-Mibxiq.js → diagram-S7CK7UJ4-DenrrE_C.js} +1 -1
  120. package/dist/client/assets/diagram-S7CK7UJ4-DenrrE_C.js.br +0 -0
  121. package/dist/client/assets/diagram-S7CK7UJ4-DenrrE_C.js.gz +0 -0
  122. package/dist/client/assets/{diagram-UQ7AKVKN-eiIMWp9t.js → diagram-UQ7AKVKN-B2ikSD8K.js} +1 -1
  123. package/dist/client/assets/diagram-UQ7AKVKN-B2ikSD8K.js.br +0 -0
  124. package/dist/client/assets/diagram-UQ7AKVKN-B2ikSD8K.js.gz +0 -0
  125. package/dist/client/assets/{diagram-VSXAHHWV-CTVOWtNL.js → diagram-VSXAHHWV-CQcNoZDC.js} +1 -1
  126. package/dist/client/assets/diagram-VSXAHHWV-CQcNoZDC.js.br +0 -0
  127. package/dist/client/assets/diagram-VSXAHHWV-CQcNoZDC.js.gz +0 -0
  128. package/dist/client/assets/{diagram-VX7I27RA-NKKk6uh7.js → diagram-VX7I27RA-Cq3FaI-1.js} +1 -1
  129. package/dist/client/assets/diagram-VX7I27RA-Cq3FaI-1.js.br +0 -0
  130. package/dist/client/assets/diagram-VX7I27RA-Cq3FaI-1.js.gz +0 -0
  131. package/dist/client/assets/{diagram-Z3DM3KII-DKYdBuNs.js → diagram-Z3DM3KII-BcWReLM8.js} +1 -1
  132. package/dist/client/assets/diagram-Z3DM3KII-BcWReLM8.js.br +0 -0
  133. package/dist/client/assets/diagram-Z3DM3KII-BcWReLM8.js.gz +0 -0
  134. package/dist/client/assets/{ebnfDiagram-PWID7BFC-DaM3D5Ed.js → ebnfDiagram-PWID7BFC-DwwFkjaL.js} +1 -1
  135. package/dist/client/assets/ebnfDiagram-PWID7BFC-DwwFkjaL.js.br +0 -0
  136. package/dist/client/assets/ebnfDiagram-PWID7BFC-DwwFkjaL.js.gz +0 -0
  137. package/dist/client/assets/{erDiagram-RLTQ6QDP-Df9kQwWg.js → erDiagram-RLTQ6QDP-B1MNvouo.js} +1 -1
  138. package/dist/client/assets/erDiagram-RLTQ6QDP-B1MNvouo.js.br +0 -0
  139. package/dist/client/assets/erDiagram-RLTQ6QDP-B1MNvouo.js.gz +0 -0
  140. package/dist/client/assets/{flowDiagram-HODETNUW-CWjDvpsN.js → flowDiagram-HODETNUW-B_tIl0Vb.js} +1 -1
  141. package/dist/client/assets/flowDiagram-HODETNUW-B_tIl0Vb.js.br +0 -0
  142. package/dist/client/assets/flowDiagram-HODETNUW-B_tIl0Vb.js.gz +0 -0
  143. package/dist/client/assets/{ganttDiagram-EL5Y4UJY-mKt-CgrH.js → ganttDiagram-EL5Y4UJY-CV0YyZHk.js} +1 -1
  144. package/dist/client/assets/ganttDiagram-EL5Y4UJY-CV0YyZHk.js.br +0 -0
  145. package/dist/client/assets/ganttDiagram-EL5Y4UJY-CV0YyZHk.js.gz +0 -0
  146. package/dist/client/assets/gestureArbiter-DszagC-d.js +1 -0
  147. package/dist/client/assets/gestureArbiter-DszagC-d.js.br +0 -0
  148. package/dist/client/assets/gestureArbiter-DszagC-d.js.gz +0 -0
  149. package/dist/client/assets/git-compare-CGiJqTYP.js +1 -0
  150. package/dist/client/assets/{gitGraphDiagram-WWUBYQGX-BqnaVVZ0.js → gitGraphDiagram-WWUBYQGX-DZvnSoyE.js} +1 -1
  151. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-DZvnSoyE.js.br +0 -0
  152. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-DZvnSoyE.js.gz +0 -0
  153. package/dist/client/assets/index-CA1fR_jI.css +1 -0
  154. package/dist/client/assets/index-CA1fR_jI.css.br +0 -0
  155. package/dist/client/assets/index-CA1fR_jI.css.gz +0 -0
  156. package/dist/client/assets/{infoDiagram-27XIBGKW-CkniyUX9.js → infoDiagram-27XIBGKW-G1OS50nR.js} +1 -1
  157. package/dist/client/assets/{ishikawaDiagram-5VMMS53U-CKo9urjS.js → ishikawaDiagram-5VMMS53U-C0-s6pfy.js} +1 -1
  158. package/dist/client/assets/ishikawaDiagram-5VMMS53U-C0-s6pfy.js.br +0 -0
  159. package/dist/client/assets/ishikawaDiagram-5VMMS53U-C0-s6pfy.js.gz +0 -0
  160. package/dist/client/assets/{journeyDiagram-3NMN7TZE-Cd4jK-oI.js → journeyDiagram-3NMN7TZE-B-9Omdit.js} +1 -1
  161. package/dist/client/assets/journeyDiagram-3NMN7TZE-B-9Omdit.js.br +0 -0
  162. package/dist/client/assets/journeyDiagram-3NMN7TZE-B-9Omdit.js.gz +0 -0
  163. package/dist/client/assets/{kanban-definition-UXKFOSKX-BuulZGO-.js → kanban-definition-UXKFOSKX-BS_qXegp.js} +1 -1
  164. package/dist/client/assets/kanban-definition-UXKFOSKX-BS_qXegp.js.br +0 -0
  165. package/dist/client/assets/kanban-definition-UXKFOSKX-BS_qXegp.js.gz +0 -0
  166. package/dist/client/assets/{layout-BpJ2ofrz.js → layout-0NYin1Qz.js} +1 -1
  167. package/dist/client/assets/{layout-BpJ2ofrz.js.br → layout-0NYin1Qz.js.br} +0 -0
  168. package/dist/client/assets/layout-0NYin1Qz.js.gz +0 -0
  169. package/dist/client/assets/{linear-CaSbGLIA.js → linear-CTVKrsxK.js} +1 -1
  170. package/dist/client/assets/linear-CTVKrsxK.js.br +0 -0
  171. package/dist/client/assets/linear-CTVKrsxK.js.gz +0 -0
  172. package/dist/client/assets/link-C5oPMHMJ.js +8 -0
  173. package/dist/client/assets/link-C5oPMHMJ.js.br +0 -0
  174. package/dist/client/assets/link-C5oPMHMJ.js.gz +0 -0
  175. package/dist/client/assets/list-tree-BPg9QdiM.js +1 -0
  176. package/dist/client/assets/loader-circle-CTtHKNWd.js +1 -0
  177. package/dist/client/assets/maximize-2-32OfQ0kG.js +1 -0
  178. package/dist/client/assets/{mermaid.core-BlkorXd6.js → mermaid.core-BgCZP9ke.js} +5 -5
  179. package/dist/client/assets/mermaid.core-BgCZP9ke.js.br +0 -0
  180. package/dist/client/assets/mermaid.core-BgCZP9ke.js.gz +0 -0
  181. package/dist/client/assets/{mindmap-definition-YA3MSWOX-BqKhK1NJ.js → mindmap-definition-YA3MSWOX-BjSZRjkg.js} +2 -2
  182. package/dist/client/assets/mindmap-definition-YA3MSWOX-BjSZRjkg.js.br +0 -0
  183. package/dist/client/assets/mindmap-definition-YA3MSWOX-BjSZRjkg.js.gz +0 -0
  184. package/dist/client/assets/passwordBootstrap-CXQgj5nw.js +2 -0
  185. package/dist/client/assets/passwordBootstrap-CXQgj5nw.js.br +0 -0
  186. package/dist/client/assets/passwordBootstrap-CXQgj5nw.js.gz +0 -0
  187. package/dist/client/assets/{pegDiagram-XKGWAZYB-BlWgUklx.js → pegDiagram-XKGWAZYB-qDU0sU6m.js} +1 -1
  188. package/dist/client/assets/pegDiagram-XKGWAZYB-qDU0sU6m.js.br +0 -0
  189. package/dist/client/assets/pegDiagram-XKGWAZYB-qDU0sU6m.js.gz +0 -0
  190. package/dist/client/assets/{pieDiagram-E7YTZNPT-Bp32kHHQ.js → pieDiagram-E7YTZNPT-CZF3MEOJ.js} +1 -1
  191. package/dist/client/assets/pieDiagram-E7YTZNPT-CZF3MEOJ.js.br +0 -0
  192. package/dist/client/assets/pieDiagram-E7YTZNPT-CZF3MEOJ.js.gz +0 -0
  193. package/dist/client/assets/{quadrantDiagram-AXDQQJYC-0qeSh9-W.js → quadrantDiagram-AXDQQJYC-DcZW4RMG.js} +1 -1
  194. package/dist/client/assets/quadrantDiagram-AXDQQJYC-DcZW4RMG.js.br +0 -0
  195. package/dist/client/assets/quadrantDiagram-AXDQQJYC-DcZW4RMG.js.gz +0 -0
  196. package/dist/client/assets/quote-CuTMveNr.js +1 -0
  197. package/dist/client/assets/{railroadDiagram-O6MQD6OU-COmWghVD.js → railroadDiagram-O6MQD6OU-DtQROK31.js} +1 -1
  198. package/dist/client/assets/railroadDiagram-O6MQD6OU-DtQROK31.js.br +0 -0
  199. package/dist/client/assets/railroadDiagram-O6MQD6OU-DtQROK31.js.gz +0 -0
  200. package/dist/client/assets/rdpSession-a1ZvAyiW.js +1 -0
  201. package/dist/client/assets/rdpSession-a1ZvAyiW.js.br +0 -0
  202. package/dist/client/assets/rdpSession-a1ZvAyiW.js.gz +0 -0
  203. package/dist/client/assets/{requirementDiagram-BXWQKSXE-CeohDJAC.js → requirementDiagram-BXWQKSXE-B8yR39lm.js} +1 -1
  204. package/dist/client/assets/requirementDiagram-BXWQKSXE-B8yR39lm.js.br +0 -0
  205. package/dist/client/assets/requirementDiagram-BXWQKSXE-B8yR39lm.js.gz +0 -0
  206. package/dist/client/assets/{sankeyDiagram-P5KCCOFB-rA5x9iOw.js → sankeyDiagram-P5KCCOFB-D27zuIFg.js} +1 -1
  207. package/dist/client/assets/sankeyDiagram-P5KCCOFB-D27zuIFg.js.br +0 -0
  208. package/dist/client/assets/sankeyDiagram-P5KCCOFB-D27zuIFg.js.gz +0 -0
  209. package/dist/client/assets/{sequenceDiagram-WJ2MYXX4-Cw2BZ0po.js → sequenceDiagram-WJ2MYXX4-BI3gSsUa.js} +1 -1
  210. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-BI3gSsUa.js.br +0 -0
  211. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-BI3gSsUa.js.gz +0 -0
  212. package/dist/client/assets/settings-2-GFFo5UwO.js +1 -0
  213. package/dist/client/assets/{sizeCapture-INFHLROL-Dz1ykd8a.js → sizeCapture-INFHLROL-NBzIIRER.js} +1 -1
  214. package/dist/client/assets/sizeCapture-INFHLROL-NBzIIRER.js.br +0 -0
  215. package/dist/client/assets/sizeCapture-INFHLROL-NBzIIRER.js.gz +0 -0
  216. package/dist/client/assets/{sparkles-0HeBLLwx.js → sparkles-ZXBp-KvJ.js} +1 -1
  217. package/dist/client/assets/{stateDiagram-D77RDMKH-DHfjTfLj.js → stateDiagram-D77RDMKH-D-D0FB4D.js} +1 -1
  218. package/dist/client/assets/stateDiagram-D77RDMKH-D-D0FB4D.js.br +0 -0
  219. package/dist/client/assets/stateDiagram-D77RDMKH-D-D0FB4D.js.gz +0 -0
  220. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-Dk-QpCnJ.js +1 -0
  221. package/dist/client/assets/sun-CO5F9zS4.js +1 -0
  222. package/dist/client/assets/{swimlanes-42K2YHIH-CAJkSUVz.js → swimlanes-42K2YHIH-CH_jxbV3.js} +1 -1
  223. package/dist/client/assets/swimlanes-42K2YHIH-CH_jxbV3.js.br +0 -0
  224. package/dist/client/assets/swimlanes-42K2YHIH-CH_jxbV3.js.gz +0 -0
  225. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-C4E5FOdv.js +8 -0
  226. package/dist/client/assets/swiper-DJjq1TYT.js +1 -0
  227. package/dist/client/assets/swiper-DJjq1TYT.js.br +0 -0
  228. package/dist/client/assets/swiper-DJjq1TYT.js.gz +0 -0
  229. package/dist/client/assets/syntaxHighlight-C9PKWUqs.js +4 -0
  230. package/dist/client/assets/syntaxHighlight-C9PKWUqs.js.br +0 -0
  231. package/dist/client/assets/syntaxHighlight-C9PKWUqs.js.gz +0 -0
  232. package/dist/client/assets/{timeline-definition-24CTP7MA-plr9yv12.js → timeline-definition-24CTP7MA-DuiaCBON.js} +1 -1
  233. package/dist/client/assets/timeline-definition-24CTP7MA-DuiaCBON.js.br +0 -0
  234. package/dist/client/assets/timeline-definition-24CTP7MA-DuiaCBON.js.gz +0 -0
  235. package/dist/client/assets/triangle-alert-CuGUScPU.js +1 -0
  236. package/dist/client/assets/unplug-C0pb-BKU.js +1 -0
  237. package/dist/client/assets/use-gesture-react.esm-DYpdiE_k.js +1 -0
  238. package/dist/client/assets/use-gesture-react.esm-DYpdiE_k.js.br +0 -0
  239. package/dist/client/assets/use-gesture-react.esm-DYpdiE_k.js.gz +0 -0
  240. package/dist/client/assets/v4-EwEgHOG0.js +1 -0
  241. package/dist/client/assets/{vennDiagram-4TSXK5OY-Cz04de3S.js → vennDiagram-4TSXK5OY-DUEZFEzo.js} +1 -1
  242. package/dist/client/assets/vennDiagram-4TSXK5OY-DUEZFEzo.js.br +0 -0
  243. package/dist/client/assets/vennDiagram-4TSXK5OY-DUEZFEzo.js.gz +0 -0
  244. package/dist/client/assets/videoCompression-JAcp0atl.js +3 -0
  245. package/dist/client/assets/videoCompression-JAcp0atl.js.br +0 -0
  246. package/dist/client/assets/videoCompression-JAcp0atl.js.gz +0 -0
  247. package/dist/client/assets/{wardleyDiagram-VM6X3IG4-DnT-q6At.js → wardleyDiagram-VM6X3IG4-CnHmIbot.js} +1 -1
  248. package/dist/client/assets/wardleyDiagram-VM6X3IG4-CnHmIbot.js.br +0 -0
  249. package/dist/client/assets/wardleyDiagram-VM6X3IG4-CnHmIbot.js.gz +0 -0
  250. package/dist/client/assets/{xychartDiagram-S5SC5T6Z-C0y08MEX.js → xychartDiagram-S5SC5T6Z-CDAoHQTr.js} +1 -1
  251. package/dist/client/assets/xychartDiagram-S5SC5T6Z-CDAoHQTr.js.br +0 -0
  252. package/dist/client/assets/xychartDiagram-S5SC5T6Z-CDAoHQTr.js.gz +0 -0
  253. package/dist/client/index.html +2 -2
  254. package/dist/client/index.html.br +0 -0
  255. package/dist/client/index.html.gz +0 -0
  256. package/dist/client/sw.js +1 -1
  257. package/dist/client/sw.js.br +0 -0
  258. package/dist/client/sw.js.gz +0 -0
  259. package/dist/server/agent/collaborationDeliveryWorker.js +11 -0
  260. package/dist/server/agent/collaborationPrompt.js +4 -2
  261. package/dist/server/agent/collaborationStore.js +7 -1
  262. package/dist/server/agent/sessionAttachmentRoutes.js +39 -0
  263. package/dist/server/agent/sessionChatRoutes.js +64 -0
  264. package/dist/server/agent/sessionViewModeRoutes.js +72 -0
  265. package/dist/server/android/recording.js +19 -17
  266. package/dist/server/cli.js +34 -0
  267. package/dist/server/entry.js +25 -17
  268. package/dist/server/federation/accessPolicy.js +8 -3
  269. package/dist/server/federation/authorization.js +26 -3
  270. package/dist/server/federation/invitations.js +27 -6
  271. package/dist/server/federation/requestContext.js +5 -1
  272. package/dist/server/federation/resourceAccess.js +63 -0
  273. package/dist/server/federation/runtime.js +60 -17
  274. package/dist/server/federation/sessionSharing.js +39 -0
  275. package/dist/server/routes/android.js +36 -7
  276. package/dist/server/routes/computer.js +14 -4
  277. package/dist/server/routes/filesystem.js +6 -3
  278. package/dist/server/routes/rdp.js +4 -3
  279. package/dist/server/routes/sharedFiles.js +51 -0
  280. package/dist/server/routes/terminal.js +83 -14
  281. package/dist/server/routes/vncReadOnly.js +134 -0
  282. package/dist/server/shared/shareResources.js +37 -0
  283. package/dist/server/todos/cli.js +91 -0
  284. package/dist/server/todos/routes.js +73 -0
  285. package/dist/server/todos/store.js +240 -0
  286. package/dist/server/todos/types.js +1 -0
  287. package/dist/server/utils/autoUpdate.js +7 -2
  288. package/dist/server/utils/clientSnapshotMaintenance.js +200 -0
  289. package/dist/server/utils/runtimeClient.js +79 -0
  290. package/dist/server/utils/serverCleanup.js +24 -0
  291. package/dist/server/utils/storageMaintenance.js +60 -0
  292. package/dist/server/utils/workspaceCacheMaintenance.js +158 -0
  293. package/package.json +1 -1
  294. package/runtime-manifest.json +3 -3
  295. package/dist/client/assets/App-BiDKeTpx.js +0 -187
  296. package/dist/client/assets/App-BiDKeTpx.js.br +0 -0
  297. package/dist/client/assets/App-BiDKeTpx.js.gz +0 -0
  298. package/dist/client/assets/ArchitecturePanel-DfRsqSBx.js +0 -9
  299. package/dist/client/assets/ArchitecturePanel-DfRsqSBx.js.br +0 -0
  300. package/dist/client/assets/ArchitecturePanel-DfRsqSBx.js.gz +0 -0
  301. package/dist/client/assets/ChangeWalkthroughPanel-DksecDp5.js +0 -2
  302. package/dist/client/assets/ChangeWalkthroughPanel-DksecDp5.js.br +0 -0
  303. package/dist/client/assets/ChangeWalkthroughPanel-DksecDp5.js.gz +0 -0
  304. package/dist/client/assets/CollaborationMainWorkspace-D-TgDrxX.js +0 -1
  305. package/dist/client/assets/CollaborationMainWorkspace-D-TgDrxX.js.br +0 -0
  306. package/dist/client/assets/CollaborationMainWorkspace-D-TgDrxX.js.gz +0 -0
  307. package/dist/client/assets/CollaborationTaskContent-Ce6gFw26.js +0 -2
  308. package/dist/client/assets/ComputerControlView-BKwuceeG.js +0 -6
  309. package/dist/client/assets/ComputerControlView-BKwuceeG.js.br +0 -0
  310. package/dist/client/assets/ComputerControlView-BKwuceeG.js.gz +0 -0
  311. package/dist/client/assets/DagPlayground-Cshoqo5l.js +0 -1
  312. package/dist/client/assets/DagPlayground-Cshoqo5l.js.br +0 -0
  313. package/dist/client/assets/DagPlayground-Cshoqo5l.js.gz +0 -0
  314. package/dist/client/assets/DiffLab-DFut8ZHi.js.br +0 -0
  315. package/dist/client/assets/DiffLab-DFut8ZHi.js.gz +0 -0
  316. package/dist/client/assets/DiffReview-DkEi5c3c.js +0 -1
  317. package/dist/client/assets/DiffReview-DkEi5c3c.js.br +0 -0
  318. package/dist/client/assets/DiffReview-DkEi5c3c.js.gz +0 -0
  319. package/dist/client/assets/DiffReviewLab-Y9JlI5DQ.js.br +0 -0
  320. package/dist/client/assets/DiffReviewLab-Y9JlI5DQ.js.gz +0 -0
  321. package/dist/client/assets/DiffViewer-3JGF6U0m.js +0 -37
  322. package/dist/client/assets/DiffViewer-3JGF6U0m.js.br +0 -0
  323. package/dist/client/assets/DiffViewer-3JGF6U0m.js.gz +0 -0
  324. package/dist/client/assets/ModelPreview-Cv6JgunE.js.br +0 -0
  325. package/dist/client/assets/ModelPreview-Cv6JgunE.js.gz +0 -0
  326. package/dist/client/assets/RightSidebar-akYx_nRq.js +0 -1679
  327. package/dist/client/assets/RightSidebar-akYx_nRq.js.br +0 -0
  328. package/dist/client/assets/RightSidebar-akYx_nRq.js.gz +0 -0
  329. package/dist/client/assets/abnfDiagram-VCTEODGH-CcCffdpj.js.br +0 -0
  330. package/dist/client/assets/abnfDiagram-VCTEODGH-CcCffdpj.js.gz +0 -0
  331. package/dist/client/assets/app-BB0CAQ8D.js +0 -35
  332. package/dist/client/assets/app-BB0CAQ8D.js.br +0 -0
  333. package/dist/client/assets/app-BB0CAQ8D.js.gz +0 -0
  334. package/dist/client/assets/arc-CXcCuzb3.js.br +0 -0
  335. package/dist/client/assets/arc-CXcCuzb3.js.gz +0 -0
  336. package/dist/client/assets/architectureDiagram-5GKGNRK7-CmR7whZz.js.br +0 -0
  337. package/dist/client/assets/architectureDiagram-5GKGNRK7-CmR7whZz.js.gz +0 -0
  338. package/dist/client/assets/blockDiagram-I7D4REHJ-DODhUpHm.js.br +0 -0
  339. package/dist/client/assets/blockDiagram-I7D4REHJ-DODhUpHm.js.gz +0 -0
  340. package/dist/client/assets/c4Diagram-7LVT6UL2-BF9eEb2Y.js.br +0 -0
  341. package/dist/client/assets/c4Diagram-7LVT6UL2-BF9eEb2Y.js.gz +0 -0
  342. package/dist/client/assets/channel-BKkTA-X_.js +0 -1
  343. package/dist/client/assets/chunk-F27PBJKO-Bv45U-az.js.gz +0 -0
  344. package/dist/client/assets/chunk-IMKFNOWR-CfEErbEd.js.br +0 -0
  345. package/dist/client/assets/chunk-IMKFNOWR-CfEErbEd.js.gz +0 -0
  346. package/dist/client/assets/chunk-SVP7TREG-CbyJW-OT.js.br +0 -0
  347. package/dist/client/assets/chunk-SVP7TREG-CbyJW-OT.js.gz +0 -0
  348. package/dist/client/assets/chunk-TICWLB2K-t93EivmS.js.br +0 -0
  349. package/dist/client/assets/chunk-TICWLB2K-t93EivmS.js.gz +0 -0
  350. package/dist/client/assets/classDiagram-ZZMXUADV-D9nwA51-.js +0 -1
  351. package/dist/client/assets/classDiagram-v2-VYDZK3BY-D9nwA51-.js +0 -1
  352. package/dist/client/assets/cose-bilkent-JH36ORCC-CksG0bvP.js.br +0 -0
  353. package/dist/client/assets/cose-bilkent-JH36ORCC-CksG0bvP.js.gz +0 -0
  354. package/dist/client/assets/cynefin-OW5HDTMX-CV3T078G.js.br +0 -0
  355. package/dist/client/assets/cynefin-OW5HDTMX-CV3T078G.js.gz +0 -0
  356. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-BQnJabEs.js.br +0 -0
  357. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-BQnJabEs.js.gz +0 -0
  358. package/dist/client/assets/dagre-GXQ25YYZ-BeIQp5Pv.js.br +0 -0
  359. package/dist/client/assets/dagre-GXQ25YYZ-BeIQp5Pv.js.gz +0 -0
  360. package/dist/client/assets/diagram-S7CK7UJ4-D-Mibxiq.js.br +0 -0
  361. package/dist/client/assets/diagram-S7CK7UJ4-D-Mibxiq.js.gz +0 -0
  362. package/dist/client/assets/diagram-UQ7AKVKN-eiIMWp9t.js.br +0 -0
  363. package/dist/client/assets/diagram-UQ7AKVKN-eiIMWp9t.js.gz +0 -0
  364. package/dist/client/assets/diagram-VSXAHHWV-CTVOWtNL.js.br +0 -0
  365. package/dist/client/assets/diagram-VSXAHHWV-CTVOWtNL.js.gz +0 -0
  366. package/dist/client/assets/diagram-VX7I27RA-NKKk6uh7.js.br +0 -0
  367. package/dist/client/assets/diagram-VX7I27RA-NKKk6uh7.js.gz +0 -0
  368. package/dist/client/assets/diagram-Z3DM3KII-DKYdBuNs.js.br +0 -0
  369. package/dist/client/assets/diagram-Z3DM3KII-DKYdBuNs.js.gz +0 -0
  370. package/dist/client/assets/ebnfDiagram-PWID7BFC-DaM3D5Ed.js.br +0 -0
  371. package/dist/client/assets/ebnfDiagram-PWID7BFC-DaM3D5Ed.js.gz +0 -0
  372. package/dist/client/assets/erDiagram-RLTQ6QDP-Df9kQwWg.js.br +0 -0
  373. package/dist/client/assets/erDiagram-RLTQ6QDP-Df9kQwWg.js.gz +0 -0
  374. package/dist/client/assets/flowDiagram-HODETNUW-CWjDvpsN.js.br +0 -0
  375. package/dist/client/assets/flowDiagram-HODETNUW-CWjDvpsN.js.gz +0 -0
  376. package/dist/client/assets/ganttDiagram-EL5Y4UJY-mKt-CgrH.js.br +0 -0
  377. package/dist/client/assets/ganttDiagram-EL5Y4UJY-mKt-CgrH.js.gz +0 -0
  378. package/dist/client/assets/gestureArbiter-C8TBuoU3.js +0 -1
  379. package/dist/client/assets/gestureArbiter-C8TBuoU3.js.br +0 -0
  380. package/dist/client/assets/gestureArbiter-C8TBuoU3.js.gz +0 -0
  381. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-BqnaVVZ0.js.br +0 -0
  382. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-BqnaVVZ0.js.gz +0 -0
  383. package/dist/client/assets/index-3lPto_1X.css +0 -1
  384. package/dist/client/assets/index-3lPto_1X.css.br +0 -0
  385. package/dist/client/assets/index-3lPto_1X.css.gz +0 -0
  386. package/dist/client/assets/ishikawaDiagram-5VMMS53U-CKo9urjS.js.br +0 -0
  387. package/dist/client/assets/ishikawaDiagram-5VMMS53U-CKo9urjS.js.gz +0 -0
  388. package/dist/client/assets/journeyDiagram-3NMN7TZE-Cd4jK-oI.js.br +0 -0
  389. package/dist/client/assets/journeyDiagram-3NMN7TZE-Cd4jK-oI.js.gz +0 -0
  390. package/dist/client/assets/kanban-definition-UXKFOSKX-BuulZGO-.js.br +0 -0
  391. package/dist/client/assets/kanban-definition-UXKFOSKX-BuulZGO-.js.gz +0 -0
  392. package/dist/client/assets/layout-BpJ2ofrz.js.gz +0 -0
  393. package/dist/client/assets/linear-CaSbGLIA.js.br +0 -0
  394. package/dist/client/assets/linear-CaSbGLIA.js.gz +0 -0
  395. package/dist/client/assets/mermaid.core-BlkorXd6.js.br +0 -0
  396. package/dist/client/assets/mermaid.core-BlkorXd6.js.gz +0 -0
  397. package/dist/client/assets/mindmap-definition-YA3MSWOX-BqKhK1NJ.js.br +0 -0
  398. package/dist/client/assets/mindmap-definition-YA3MSWOX-BqKhK1NJ.js.gz +0 -0
  399. package/dist/client/assets/passwordBootstrap-DLUamTjd.js +0 -2
  400. package/dist/client/assets/passwordBootstrap-DLUamTjd.js.br +0 -0
  401. package/dist/client/assets/passwordBootstrap-DLUamTjd.js.gz +0 -0
  402. package/dist/client/assets/pegDiagram-XKGWAZYB-BlWgUklx.js.br +0 -0
  403. package/dist/client/assets/pegDiagram-XKGWAZYB-BlWgUklx.js.gz +0 -0
  404. package/dist/client/assets/pieDiagram-E7YTZNPT-Bp32kHHQ.js.br +0 -0
  405. package/dist/client/assets/pieDiagram-E7YTZNPT-Bp32kHHQ.js.gz +0 -0
  406. package/dist/client/assets/quadrantDiagram-AXDQQJYC-0qeSh9-W.js.br +0 -0
  407. package/dist/client/assets/quadrantDiagram-AXDQQJYC-0qeSh9-W.js.gz +0 -0
  408. package/dist/client/assets/railroadDiagram-O6MQD6OU-COmWghVD.js.br +0 -0
  409. package/dist/client/assets/railroadDiagram-O6MQD6OU-COmWghVD.js.gz +0 -0
  410. package/dist/client/assets/rdpSession-Bbycnmly.js +0 -1
  411. package/dist/client/assets/rdpSession-Bbycnmly.js.br +0 -0
  412. package/dist/client/assets/rdpSession-Bbycnmly.js.gz +0 -0
  413. package/dist/client/assets/referenceLongPress-CQ9ote5C.js +0 -1
  414. package/dist/client/assets/referenceLongPress-CQ9ote5C.js.br +0 -0
  415. package/dist/client/assets/referenceLongPress-CQ9ote5C.js.gz +0 -0
  416. package/dist/client/assets/requirementDiagram-BXWQKSXE-CeohDJAC.js.br +0 -0
  417. package/dist/client/assets/requirementDiagram-BXWQKSXE-CeohDJAC.js.gz +0 -0
  418. package/dist/client/assets/sankeyDiagram-P5KCCOFB-rA5x9iOw.js.br +0 -0
  419. package/dist/client/assets/sankeyDiagram-P5KCCOFB-rA5x9iOw.js.gz +0 -0
  420. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-Cw2BZ0po.js.br +0 -0
  421. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-Cw2BZ0po.js.gz +0 -0
  422. package/dist/client/assets/sizeCapture-INFHLROL-Dz1ykd8a.js.br +0 -0
  423. package/dist/client/assets/sizeCapture-INFHLROL-Dz1ykd8a.js.gz +0 -0
  424. package/dist/client/assets/stateDiagram-D77RDMKH-DHfjTfLj.js.br +0 -0
  425. package/dist/client/assets/stateDiagram-D77RDMKH-DHfjTfLj.js.gz +0 -0
  426. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-B9AqPaxQ.js +0 -1
  427. package/dist/client/assets/swimlanes-42K2YHIH-CAJkSUVz.js.br +0 -0
  428. package/dist/client/assets/swimlanes-42K2YHIH-CAJkSUVz.js.gz +0 -0
  429. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-DPbqRuWV.js +0 -8
  430. package/dist/client/assets/timeline-definition-24CTP7MA-plr9yv12.js.br +0 -0
  431. package/dist/client/assets/timeline-definition-24CTP7MA-plr9yv12.js.gz +0 -0
  432. package/dist/client/assets/triangle-alert-ibl6FV9I.js +0 -1
  433. package/dist/client/assets/vennDiagram-4TSXK5OY-Cz04de3S.js.br +0 -0
  434. package/dist/client/assets/vennDiagram-4TSXK5OY-Cz04de3S.js.gz +0 -0
  435. package/dist/client/assets/videoCompression-DCsUD6X6.js +0 -3
  436. package/dist/client/assets/videoCompression-DCsUD6X6.js.br +0 -0
  437. package/dist/client/assets/videoCompression-DCsUD6X6.js.gz +0 -0
  438. package/dist/client/assets/wardleyDiagram-VM6X3IG4-DnT-q6At.js.br +0 -0
  439. package/dist/client/assets/wardleyDiagram-VM6X3IG4-DnT-q6At.js.gz +0 -0
  440. package/dist/client/assets/xychartDiagram-S5SC5T6Z-C0y08MEX.js.br +0 -0
  441. package/dist/client/assets/xychartDiagram-S5SC5T6Z-C0y08MEX.js.gz +0 -0
  442. /package/dist/client/assets/{gestureArbiter-C2J0D0kV.css → swiper-C2J0D0kV.css} +0 -0
  443. /package/dist/client/assets/{gestureArbiter-C2J0D0kV.css.br → swiper-C2J0D0kV.css.br} +0 -0
  444. /package/dist/client/assets/{gestureArbiter-C2J0D0kV.css.gz → swiper-C2J0D0kV.css.gz} +0 -0
@@ -1,35 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/passwordBootstrap-DLUamTjd.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-Dea8wJF3.js","assets/App-BiDKeTpx.js","assets/gestureArbiter-C8TBuoU3.js","assets/gestureArbiter-C2J0D0kV.css","assets/triangle-alert-ibl6FV9I.js","assets/referenceLongPress-CQ9ote5C.js","assets/DagPlayground-Cshoqo5l.js","assets/ChangeWalkthroughPanel-DksecDp5.js","assets/sparkles-0HeBLLwx.js","assets/DiffLab-DFut8ZHi.js","assets/DiffViewer-3JGF6U0m.js","assets/DiffViewer-T3uj2-aP.css","assets/DiffReviewLab-Y9JlI5DQ.js","assets/DiffReview-DkEi5c3c.js"])))=>i.map(i=>d[i]);
2
- import{r as Ol,a as iy,g as Uh}from"./react-XDCjal2T.js";import{b as P,R as vt,r as Pi}from"./dnd-BCFAPC0L.js";import{T as ay,l as cy}from"./terminal-Dea8wJF3.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(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"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(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 r(o){if(o.ep)return;o.ep=!0;const s=n(o);fetch(o.href,s)}})();const ly="modulepreload",dy=function(e){return"/"+e},Zd={},An=function(t,n,r){let o=Promise.resolve();if(n&&n.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(n.map(l=>{if(l=dy(l),l in Zd)return;Zd[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":ly,d||(f.as="script"),f.crossOrigin="",f.href=l,a&&f.setAttribute("nonce",a),document.head.appendChild(f),d)return new Promise((p,g)=>{f.addEventListener("load",p),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 t().catch(s)})};var da={exports:{}},Xr={};var Jd;function uy(){if(Jd)return Xr;Jd=1;var e=Ol(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=e.__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,p=null;l!==void 0&&(f=""+l),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(p=c.ref);for(d in c)r.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:t,type:a,key:f,ref:p,props:u,_owner:o.current}}return Xr.Fragment=n,Xr.jsx=i,Xr.jsxs=i,Xr}var Qd;function fy(){return Qd||(Qd=1,da.exports=uy()),da.exports}var h=fy();const Hn="termdock-secure-target-v1",Fl="termdock-secure-entry-v1",hy=new Set([Hn,Fl,"termdock-color-theme","termdock:locale","termdock.federation.connections.v1"]),rs=typeof Storage>"u"?void 0:Storage.prototype.getItem,ua=typeof Storage>"u"?void 0:Storage.prototype.setItem,eu="termdock-secure-legacy-owner",Ni=typeof window<"u"&&window.parent!==window&&location.pathname==="/workspace.html";function py(){if(typeof window>"u")return null;try{if(Ni){const t=new URLSearchParams(location.search).get("termdock-workspace"),n=JSON.parse(localStorage.getItem("termdock.federation.connections.v1")||"[]"),r=Array.isArray(n)?n.find(o=>o?.targetPeerId===t):void 0;return r&&typeof r.url=="string"&&typeof r.targetPeerId=="string"?{...r,serviceName:r.label||r.serviceName}:null}const e=JSON.parse(sessionStorage.getItem(Hn)??localStorage.getItem(Hn)??"null");return e&&typeof e.url=="string"&&typeof e.targetPeerId=="string"?e:null}catch{return null}}let zo=py();const Ec=new Set,yr=zo?.targetPeerId??"unpaired";function at(){return zo}function P2(e){return Ec.add(e),()=>Ec.delete(e)}function Hh(){for(const e of Ec)e(zo)}function $h(e){if(zo=e,Hh(),Ni)return;const t=JSON.stringify(e);sessionStorage.setItem(Hn,t),localStorage.setItem(Hn,t)}function gy(){zo=null,Hh(),!Ni&&(localStorage.removeItem(Hn),sessionStorage.removeItem(Hn),localStorage.removeItem(Fl))}function Ao(e,t=yr){return hy.has(e)||e.startsWith("termdock-secure-")?e:`termdock-service:${t}:${e}`}function my(e){if(!(!rs||!ua))try{if(rs.call(localStorage,eu))return;ua.call(localStorage,eu,e);for(const n of[localStorage,sessionStorage]){const r=Array.from({length:n.length},(o,s)=>n.key(s)).filter(o=>!!o);for(const o of r){if(o.startsWith("termdock-service:")||Ao(o,e)===o)continue;const s=Ao(o,e),i=rs.call(n,o);i!==null&&rs.call(n,s)===null&&ua.call(n,s,i)}}}catch{}}let tu=!1;function wy(){if(tu||typeof Storage>"u")return;tu=!0;const e=Storage.prototype.getItem,t=Storage.prototype.setItem,n=Storage.prototype.removeItem;Storage.prototype.getItem=function(r){return e.call(this,Ao(String(r)))},Storage.prototype.setItem=function(r,o){t.call(this,Ao(String(r)),o)},Storage.prototype.removeItem=function(r){n.call(this,Ao(String(r)))}}wy();const xc=8,qh=128,Ml=2e4,Li="termdock.federation.connections.v1",Ic="termdock:services-changed",jl="termdock-secure-removed-services",Gs=e=>[e.id,e.targetPeerId,e.serviceOrigin||e.url].filter(t=>!!t);function Ul(){try{const e=JSON.parse(localStorage.getItem(jl)||"[]");return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}catch{return[]}}function Ne(e){const t=e.trim();if(!t)throw new Error("请输入服务地址。");const n=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(t)?t:`https://${t}`);n.protocol==="wss:"&&(n.protocol="https:"),n.protocol==="ws:"&&(n.protocol="http:");const r=["localhost","127.0.0.1","[::1]"].includes(n.hostname);if(!["https:","http:"].includes(n.protocol)||n.protocol==="http:"&&!r)throw new Error("请使用 HTTPS 服务地址。");if(n.username||n.password||n.search||n.hash||!["/","/api/federation/secure"].includes(n.pathname))throw new Error("请输入服务首页地址,不要包含账号或额外参数。");return n.origin}function Bi(e){if(!e||typeof e!="object")return;const t=e;if(typeof t.url=="string")try{const n=Ne(t.url),r=typeof t.targetPeerId=="string"&&t.targetPeerId?t.targetPeerId:void 0,o=(typeof t.label=="string"?t.label:typeof t.serviceName=="string"?t.serviceName:"").trim().slice(0,120)||new URL(n).host;return{id:typeof t.id=="string"&&t.id?t.id:r||n,url:n,label:o,...r?{targetPeerId:r}:{},...typeof t.serviceOrigin=="string"?{serviceOrigin:Ne(t.serviceOrigin)}:{},...typeof t.entryServiceId=="string"&&t.entryServiceId?{entryServiceId:t.entryServiceId}:{},...Array.isArray(t.routes)?{routes:t.routes.slice(0,4).flatMap(s=>{try{return s&&typeof s.targetPeerId=="string"&&s.targetPeerId?[{url:Ne(s.url),targetPeerId:s.targetPeerId}]:[]}catch{return[]}})}:{}}}catch{return}}function Jt(e,t){return e.targetPeerId&&t.targetPeerId?e.targetPeerId===t.targetPeerId:(e.serviceOrigin||e.url)===(t.serviceOrigin||t.url)}function Kh(e){const t=[];for(const n of e){const r=t.findIndex(o=>Jt(o,n));r<0?t.push(n):t[r]={...t[r],...n,id:t[r].id}}return t}function Wo(){return typeof window>"u"?void 0:window.termdockDesktop}function $n(){try{const e=JSON.parse(localStorage.getItem(Li)||"[]");return Array.isArray(e)?Kh(e.map(Bi).filter(t=>!!t)):[]}catch{return[]}}function zh(e){localStorage.setItem(Li,JSON.stringify(e.map(t=>({...t,serviceName:t.label})))),window.dispatchEvent(new Event(Ic))}let Zr;async function Ve(){const e=Wo();if(!e?.serviceConnections||!e.saveServiceConnection)return $n();if(Zr)return Zr;Zr=(async()=>{let t=await e.serviceConnections();const n=$n();for(const r of n)t.some(o=>Jt(o,r))||(t=await(e.importServiceConnection||e.saveServiceConnection)(r));return n.length&&localStorage.removeItem(Li),t})();try{return await Zr}finally{Zr=void 0}}async function on(e){if(e.entryServiceId&&e.entryServiceId===e.targetPeerId)throw new Error("不能保存服务到自身的中转;请将其它地址添加为备用地址。");const t=Bi(e);if(!t)throw new Error("服务地址无效。");const n=Wo();if(n?.saveServiceConnection)return n.saveServiceConnection(t);const r=$n(),o=r.find(a=>a.id===t.id||Jt(a,t)),s=new Set([...Gs(t),...o?Gs(o):[]]);localStorage.setItem(jl,JSON.stringify(Ul().filter(a=>!s.has(a))));const i=Kh([...r.filter(a=>a!==o),{...o,...t,id:o?.id||t.id}]);return zh(i),i}async function yy(e){if(e.entryServiceId&&e.entryServiceId===e.targetPeerId)throw new Error("不能保存服务到自身的中转;请将其它地址添加为备用地址。");const t=Bi(e);if(!t)throw new Error("服务地址无效。");const n=Wo();if(n?.importServiceConnection)return n.importServiceConnection(t);if(n?.serviceConnections){const r=await n.serviceConnections();return r.some(o=>Jt(o,t))?on(t):r}return Gs(t).some(r=>Ul().includes(r))?$n():on(t)}async function by(e){const t=Wo();if(t?.removeServiceConnection)return t.removeServiceConnection(e);const n=$n(),r=n.find(s=>s.id===e);r&&localStorage.setItem(jl,JSON.stringify([...new Set([...Ul(),...Gs(r)])].slice(-768)));const o=n.filter(s=>s.id!==e);return zh(o),o}function Di(e){const t=r=>{(r.key===Li||r.key===null)&&e()};window.addEventListener(Ic,e),window.addEventListener("storage",t);const n=Wo()?.onServiceConnections?.(e);return()=>{window.removeEventListener(Ic,e),window.removeEventListener("storage",t),n?.()}}class vy extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}}let Sy=class extends Error{static name="InvalidCryptoExchangeError";constructor(t="Invalid crypto exchange"){super(t),this.name="InvalidCryptoExchangeError"}},Nt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};class Wh extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}}class Gh extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}}class Ey extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}}class xy extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}}class _i extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}}const Vh=Symbol.for("@libp2p/peer-id");function Iy(e){return typeof e?.handleEvent=="function"}function Ay(e){return e===!0||e===!1}function Cy(e){return Ay(e)?e:e?.capture??!1}function Ac(e){const t={capture:Cy(e),once:!!e?.once};return e?.passive!=null&&(t.passive=e?.passive),e?.signal!=null&&(t.signal=e?.signal),t}function nu(e,t){return Ac(e).capture===Ac(t).capture}class Ry extends EventTarget{#e=new Map;constructor(){super()}listenerCount(t){const n=this.#e.get(t);return n==null?0:n.length}addEventListener(t,n,r){const o=Ac(r);if(o?.signal?.aborted===!0)return;const s=l=>{o.once&&this.removeEventListener(t,n,o),Iy(n)?n.handleEvent(l):n(l)};let i=this.#e.get(t);if(i==null&&(i=[],this.#e.set(t,i)),i.some(l=>l.callback!==n?!1:nu(l.options,o)))return;super.addEventListener(t,s,o);const c=()=>{this.removeEventListener(t,n,o)};o.signal?.addEventListener("abort",c),i.push({callback:n,wrapper:s,options:o,onAbort:c})}removeEventListener(t,n,r){const o=this.#e.get(t);if(o==null){super.removeEventListener(t,n??null,r);return}this.#e.set(t,o.filter(s=>s.callback===n&&nu(s.options,r)?(super.removeEventListener(t,s.wrapper,r),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(t,n={}){return this.dispatchEvent(new CustomEvent(t,n))}}const ky=Symbol.for("@libp2p/service-capabilities");function Ty(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0}function Oi(e){if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}function Py(e){return new TextEncoder().encode(e)}function Ny(e){return new TextDecoder().decode(e)}function Ly(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var o=0;o<e.length;o++){var s=e.charAt(o),i=s.charCodeAt(0);if(n[i]!==255)throw new TypeError(s+" is ambiguous");n[i]=o}var a=e.length,c=e.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,b=0,y=0,x=g.length;y!==x&&g[y]===0;)y++,m++;for(var w=(x-y)*d+1>>>0,I=new Uint8Array(w);y!==x;){for(var R=g[y],S=0,A=w-1;(R!==0||S<b)&&A!==-1;A--,S++)R+=256*I[A]>>>0,I[A]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");b=S,y++}for(var T=w-b;T!==w&&I[T]===0;)T++;for(var v=c.repeat(m);T<w;++T)v+=e.charAt(I[T]);return v}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 b=0,y=0;g[m]===c;)b++,m++;for(var x=(g.length-m)*l+1>>>0,w=new Uint8Array(x);g[m];){var I=n[g.charCodeAt(m)];if(I===255)return;for(var R=0,S=x-1;(I!==0||R<y)&&S!==-1;S--,R++)I+=a*w[S]>>>0,w[S]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");y=R,m++}if(g[m]!==" "){for(var A=x-y;A!==x&&w[A]===0;)A++;for(var T=new Uint8Array(b+(x-A)),v=b;A!==x;)T[v++]=w[A++];return T}}}function p(g){var m=f(g);if(m)return m;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:f,decode:p}}var By=Ly,Dy=By;class _y{name;prefix;baseEncode;constructor(t,n,r){this.name=t,this.prefix=n,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}}class Oy{name;prefix;baseDecode;prefixCodePoint;constructor(t,n,r){this.name=t,this.prefix=n;const o=n.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Yh(this,t)}}class Fy{decoders;constructor(t){this.decoders=t}or(t){return Yh(this,t)}decode(t){const n=t[0],r=this.decoders[n];if(r!=null)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function Yh(e,t){return new Fy({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}class My{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,n,r,o){this.name=t,this.prefix=n,this.baseEncode=r,this.baseDecode=o,this.encoder=new _y(t,n,r),this.decoder=new Oy(t,n,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}function Fi({name:e,prefix:t,encode:n,decode:r}){return new My(e,t,n,r)}function Go({name:e,prefix:t,alphabet:n}){const{encode:r,decode:o}=Dy(n,e);return Fi({prefix:t,name:e,encode:r,decode:s=>Oi(o(s))})}function jy(e,t,n,r){let o=e.length;for(;e[o-1]==="=";)--o;const s=new Uint8Array(o*n/8|0);let i=0,a=0,c=0;for(let l=0;l<o;++l){const d=t[e[l]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<n|d,i+=n,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=n||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Uy(e,t,n){const r=t[t.length-1]==="=",o=(1<<n)-1;let s="",i=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],i+=8;i>n;)i-=n,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<n-i]),r)for(;(s.length*n&7)!==0;)s+="=";return s}function Hy(e){const t={};for(let n=0;n<e.length;++n)t[e[n]]=n;return t}function Je({name:e,prefix:t,bitsPerChar:n,alphabet:r}){const o=Hy(r);return Fi({prefix:t,name:e,encode(s){return Uy(s,r,n)},decode(s){return jy(s,o,n,e)}})}const it=Go({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),$y=Go({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),qy=Object.freeze(Object.defineProperty({__proto__:null,base58btc:it,base58flickr:$y},Symbol.toStringTag,{value:"Module"})),Co=Je({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ky=Je({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),zy=Je({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Wy=Je({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Gy=Je({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Vy=Je({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Yy=Je({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Xy=Je({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Zy=Je({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Jy=Object.freeze(Object.defineProperty({__proto__:null,base32:Co,base32hex:Gy,base32hexpad:Yy,base32hexpadupper:Xy,base32hexupper:Vy,base32pad:zy,base32padupper:Wy,base32upper:Ky,base32z:Zy},Symbol.toStringTag,{value:"Module"})),Ns=Go({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Qy=Go({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),eb=Object.freeze(Object.defineProperty({__proto__:null,base36:Ns,base36upper:Qy},Symbol.toStringTag,{value:"Module"}));var tb=Xh,ru=128,nb=-128,rb=Math.pow(2,31);function Xh(e,t,n){t=t||[],n=n||0;for(var r=n;e>=rb;)t[n++]=e&255|ru,e/=128;for(;e&nb;)t[n++]=e&255|ru,e>>>=7;return t[n]=e|0,Xh.bytes=n-r+1,t}var ob=Cc,sb=128,ou=127;function Cc(e,r){var n=0,r=r||0,o=0,s=r,i,a=e.length;do{if(s>=a)throw Cc.bytes=0,new RangeError("Could not decode varint");i=e[s++],n+=o<28?(i&ou)<<o:(i&ou)*Math.pow(2,o),o+=7}while(i>=sb);return Cc.bytes=s-r,n}var ib=Math.pow(2,7),ab=Math.pow(2,14),cb=Math.pow(2,21),lb=Math.pow(2,28),db=Math.pow(2,35),ub=Math.pow(2,42),fb=Math.pow(2,49),hb=Math.pow(2,56),pb=Math.pow(2,63),gb=function(e){return e<ib?1:e<ab?2:e<cb?3:e<lb?4:e<db?5:e<ub?6:e<fb?7:e<hb?8:e<pb?9:10},mb={encode:tb,decode:ob,encodingLength:gb},Vs=mb;function Rc(e,t=0){return[Vs.decode(e,t),Vs.decode.bytes]}function Ys(e,t,n=0){return Vs.encode(e,t,n),t}function Xs(e){return Vs.encodingLength(e)}function Vo(e,t){const n=t.byteLength,r=Xs(e),o=r+Xs(n),s=new Uint8Array(o+n);return Ys(e,s,0),Ys(n,s,r),s.set(t,o),new Hl(e,n,t,s)}function Zh(e){const t=Oi(e),[n,r]=Rc(t),[o,s]=Rc(t.subarray(r)),i=t.subarray(r+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Hl(n,o,i,t)}function wb(e,t){if(e===t)return!0;{const n=t;return e.code===n.code&&e.size===n.size&&n.bytes instanceof Uint8Array&&Ty(e.bytes,n.bytes)}}class Hl{code;size;digest;bytes;constructor(t,n,r,o){this.code=t,this.size=n,this.digest=r,this.bytes=o}}function su(e,t){const{bytes:n,version:r}=e;return r===0?bb(n,kc(e),t??it.encoder):vb(n,kc(e),t??Co.encoder)}const iu=new WeakMap;function kc(e){const t=iu.get(e);if(t==null){const n=new Map;return iu.set(e,n),n}return t}class Le{code;version;multihash;bytes;"/";constructor(t,n,r,o){this.code=n,this.version=t,this.multihash=r,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:t,multihash:n}=this;if(t!==Jr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==Sb)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Le.createV0(n)}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:t,digest:n}=this.multihash,r=Vo(t,n);return Le.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return Le.equals(this,t)}static equals(t,n){const r=n;return r!=null&&t.code===r.code&&t.version===r.version&&wb(t.multihash,r.multihash)}toString(t){return su(this,t)}toJSON(){return{"/":su(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;const n=t;if(n instanceof Le)return n;if(n["/"]!=null&&n["/"]===n.bytes||n.asCID===n){const{version:r,code:o,multihash:s,bytes:i}=n;return new Le(r,o,s,i??au(r,o,s.bytes))}else if(n[Eb]===!0){const{version:r,multihash:o,code:s}=n,i=Zh(o);return Le.create(r,s,i)}else return null}static create(t,n,r){if(typeof n!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(n!==Jr)throw new Error(`Version 0 CID must use dag-pb (code: ${Jr}) block encoding`);return new Le(t,n,r,r.bytes)}case 1:{const o=au(t,n,r.bytes);return new Le(t,n,r,o)}default:throw new Error("Invalid version")}}static createV0(t){return Le.create(0,Jr,t)}static createV1(t,n){return Le.create(1,t,n)}static decode(t){const[n,r]=Le.decodeFirst(t);if(r.length!==0)throw new Error("Incorrect length");return n}static decodeFirst(t){const n=Le.inspectBytes(t),r=n.size-n.multihashSize,o=Oi(t.subarray(r,r+n.multihashSize));if(o.byteLength!==n.multihashSize)throw new Error("Incorrect length");const s=o.subarray(n.multihashSize-n.digestSize),i=new Hl(n.multihashCode,n.digestSize,s,o);return[n.version===0?Le.createV0(i):Le.createV1(n.codec,i),t.subarray(n.size)]}static inspectBytes(t){let n=0;const r=()=>{const[u,f]=Rc(t.subarray(n));return n+=f,u};let o=r(),s=Jr;if(o===18?(o=0,n=0):s=r(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);const i=n,a=r(),c=r(),l=n+c,d=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:l}}static parse(t,n){const[r,o]=yb(t,n),s=Le.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return kc(s).set(r,t),s}}function yb(e,t){switch(e[0]){case"Q":{const n=t??it;return[it.prefix,n.decode(`${it.prefix}${e}`)]}case it.prefix:{const n=t??it;return[it.prefix,n.decode(e)]}case Co.prefix:{const n=t??Co;return[Co.prefix,n.decode(e)]}case Ns.prefix:{const n=t??Ns;return[Ns.prefix,n.decode(e)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function bb(e,t,n){const{prefix:r}=n;if(r!==it.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);const o=t.get(r);if(o==null){const s=n.encode(e).slice(1);return t.set(r,s),s}else return o}function vb(e,t,n){const{prefix:r}=n,o=t.get(r);if(o==null){const s=n.encode(e);return t.set(r,s),s}else return o}const Jr=112,Sb=18;function au(e,t,n){const r=Xs(e),o=r+Xs(t),s=new Uint8Array(o+n.byteLength);return Ys(e,s,0),Ys(t,s,r),s.set(n,o),s}const Eb=Symbol.for("@ipld/js-cid/CID"),Jh=0,xb="identity",Qh=Oi;function Ib(e,t){if(t?.truncate!=null&&t.truncate!==e.byteLength){if(t.truncate<0||t.truncate>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,t.truncate)}return Vo(Jh,Qh(e))}const Yo={code:Jh,name:xb,encode:Qh,digest:Ib};function Lt(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0}function ft(e=0){return new Uint8Array(e)}function sn(e=0){return new Uint8Array(e)}function Tc(e,t){t==null&&(t=e.reduce((o,s)=>o+s.length,0));const n=sn(t);let r=0;for(const o of e)n.set(o,r),r+=o.length;return n}const ep=Symbol.for("@achingbrain/uint8arraylist");function cu(e,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let n=0;for(const r of e){const o=n+r.byteLength;if(t<o)return{buf:r,index:t-n};n=o}throw new RangeError("index is out of bounds")}function os(e){return!!e?.[ep]}class ye{bufs;length;[ep]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let n=0;for(const r of t)if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.push(r);else if(os(r)){n+=r.byteLength;for(const o of r.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=n}prepend(...t){this.prependAll(t)}prependAll(t){let n=0;for(const r of t.reverse())if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.unshift(r);else if(os(r))n+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=n}get(t){const n=cu(this.bufs,t);return n.buf[n.index]}set(t,n){const r=cu(this.bufs,t);r.buf[r.index]=n}write(t,n=0){if(t instanceof Uint8Array)for(let r=0;r<t.length;r++)this.set(n+r,t[r]);else if(os(t))for(let r=0;r<t.length;r++)this.set(n+r,t.get(r));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,n){const{bufs:r,length:o}=this._subList(t,n);return Tc(r,o)}subarray(t,n){const{bufs:r,length:o}=this._subList(t,n);return r.length===1?r[0]:Tc(r,o)}sublist(t,n){const{bufs:r,length:o}=this._subList(t,n),s=new ye;return s.length=o,s.bufs=r,s}_subList(t,n){if(t=t??0,n=n??this.length,t<0&&(t=this.length+t),n<0&&(n=this.length+n),t<0||n>this.length)throw new RangeError("index is out of bounds");if(t===n)return{bufs:[],length:0};if(t===0&&n===this.length)return{bufs:[...this.bufs],length:this.length};const r=[];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,t>=c)continue;const l=t>=a&&t<c,d=n>a&&n<=c;if(l&&d){if(t===a&&n===c){r.push(i);break}const u=t-a;r.push(i.subarray(u,u+(n-t)));break}if(l){if(t===0){r.push(i);continue}r.push(i.subarray(t-a));continue}if(d){if(n===c){r.push(i);break}r.push(i.subarray(0,n-a));break}r.push(i)}return{bufs:r,length:n-t}}indexOf(t,n=0){if(!os(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=t instanceof Uint8Array?t:t.subarray();if(n=Number(n??0),isNaN(n)&&(n=0),n<0&&(n=this.length+n),n<0&&(n=0),t.length===0)return n>this.length?this.length:n;const o=r.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[r[u]]=u;const a=i,c=this.byteLength-r.byteLength,l=r.byteLength-1;let d;for(let u=n;u<=c;u+=d){d=0;for(let f=l;f>=0;f--){const p=this.get(u+f);if(r[f]!==p){d=Math.max(1,f-a[p]);break}}if(d===0)return u}return-1}getInt8(t){const n=this.subarray(t,t+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt8(0)}setInt8(t,n){const r=sn(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,n),this.write(r,t)}getInt16(t,n){const r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,n)}setInt16(t,n,r){const o=ft(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,n,r),this.write(o,t)}getInt32(t,n){const r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,n)}setInt32(t,n,r){const o=ft(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,n,r),this.write(o,t)}getBigInt64(t,n){const r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,n)}setBigInt64(t,n,r){const o=ft(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,n,r),this.write(o,t)}getUint8(t){const n=this.subarray(t,t+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint8(0)}setUint8(t,n){const r=sn(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,n),this.write(r,t)}getUint16(t,n){const r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,n)}setUint16(t,n,r){const o=ft(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,n,r),this.write(o,t)}getUint32(t,n){const r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,n)}setUint32(t,n,r){const o=ft(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,n,r),this.write(o,t)}getBigUint64(t,n){const r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,n)}setBigUint64(t,n,r){const o=ft(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,n,r),this.write(o,t)}getFloat32(t,n){const r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,n)}setFloat32(t,n,r){const o=ft(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,n,r),this.write(o,t)}getFloat64(t,n){const r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,n)}setFloat64(t,n,r){const o=ft(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,n,r),this.write(o,t)}equals(t){if(t==null||!(t instanceof ye)||t.bufs.length!==this.bufs.length)return!1;for(let n=0;n<this.bufs.length;n++)if(!Lt(this.bufs[n],t.bufs[n]))return!1;return!0}static fromUint8Arrays(t,n){const r=new ye;return r.bufs=t,n==null&&(n=t.reduce((o,s)=>o+s.byteLength,0)),r.length=n,r}}const Ab=Go({prefix:"9",name:"base10",alphabet:"0123456789"}),Cb=Object.freeze(Object.defineProperty({__proto__:null,base10:Ab},Symbol.toStringTag,{value:"Module"})),Rb=Je({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),kb=Je({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Tb=Object.freeze(Object.defineProperty({__proto__:null,base16:Rb,base16upper:kb},Symbol.toStringTag,{value:"Module"})),Pb=Je({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Nb=Object.freeze(Object.defineProperty({__proto__:null,base2:Pb},Symbol.toStringTag,{value:"Module"})),tp=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Lb=tp.reduce((e,t,n)=>(e[n]=t,e),[]),Bb=tp.reduce((e,t,n)=>{const r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);return e[r]=n,e},[]);function Db(e){return e.reduce((t,n)=>(t+=Lb[n],t),"")}function _b(e){const t=[];for(const n of e){const r=n.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${n}`);const o=Bb[r];if(o==null)throw new Error(`Non-base256emoji character: ${n}`);t.push(o)}return new Uint8Array(t)}const Ob=Fi({prefix:"🚀",name:"base256emoji",encode:Db,decode:_b}),Fb=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:Ob},Symbol.toStringTag,{value:"Module"})),Mb=Je({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),jb=Je({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ub=Je({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Hb=Je({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),$b=Object.freeze(Object.defineProperty({__proto__:null,base64:Mb,base64pad:jb,base64url:Ub,base64urlpad:Hb},Symbol.toStringTag,{value:"Module"})),qb=Je({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Kb=Object.freeze(Object.defineProperty({__proto__:null,base8:qb},Symbol.toStringTag,{value:"Module"})),zb=Fi({prefix:"\0",name:"identity",encode:e=>Ny(e),decode:e=>Py(e)}),Wb=Object.freeze(Object.defineProperty({__proto__:null,identity:zb},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const Gb=20;function Vb({name:e,code:t,encode:n,minDigestLength:r,maxDigestLength:o}){return new Yb(e,t,n,r,o)}class Yb{name;code;encode;minDigestLength;maxDigestLength;constructor(t,n,r,o,s){this.name=t,this.code=n,this.encode=r,this.minDigestLength=o??Gb,this.maxDigestLength=s}digest(t,n){if(n?.truncate!=null){if(n.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&n.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){const r=this.encode(t);return r instanceof Uint8Array?lu(r,this.code,n?.truncate):r.then(o=>lu(o,this.code,n?.truncate))}else throw Error("Unknown type, must be binary type")}}function lu(e,t,n){if(n!=null&&n!==e.byteLength){if(n>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,n)}return Vo(t,e)}function Xb(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}const $l=Vb({name:"sha2-256",code:18,encode:Xb("SHA-256")}),du={...Wb,...Nb,...Kb,...Cb,...Tb,...Jy,...eb,...qy,...$b,...Fb};function np(e,t,n,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:n},decoder:{decode:r}}}const uu=np("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),fa=np("ascii","a",e=>{let t="a";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t},e=>{e=e.substring(1);const t=sn(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}),rp={utf8:uu,"utf-8":uu,hex:du.base16,latin1:fa,ascii:fa,binary:fa,...du};function Ue(e,t="utf8"){const n=rp[t];if(n==null)throw new Error(`Unsupported encoding "${t}"`);return n.decoder.decode(`${n.prefix}${e}`)}function le(e,t="utf8"){const n=rp[t];if(n==null)throw new Error(`Unsupported encoding "${t}"`);return n.encoder.encode(e).substring(1)}const Zb=parseInt("11111",2),Pc=parseInt("10000000",2),Jb=parseInt("01111111",2),fu={0:Qr,1:Qr,2:Qb,3:nv,4:rv,5:tv,6:ev,16:Qr,22:Qr,48:Qr};function Kr(e,t={offset:0}){const n=e[t.offset]&Zb;if(t.offset++,fu[n]!=null)return fu[n](e,t);throw new Error("No decoder for tag "+n)}function Xo(e,t){let n=0;if((e[t.offset]&Pc)===Pc){const r=e[t.offset]&Jb;let o="0x";t.offset++;for(let s=0;s<r;s++,t.offset++)o+=e[t.offset].toString(16).padStart(2,"0");n=parseInt(o,16)}else n=e[t.offset],t.offset++;return n}function Qr(e,t){Xo(e,t);const n=[];for(;!(t.offset>=e.byteLength);){const r=Kr(e,t);if(r===null)break;n.push(r)}return n}function Qb(e,t){const n=Xo(e,t),r=t.offset,o=t.offset+n,s=[];for(let i=r;i<o;i++)i===r&&e[i]===0||s.push(e[i]);return t.offset+=n,Uint8Array.from(s)}function ev(e,t){const n=Xo(e,t),r=t.offset+n,o=e[t.offset];t.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(;t.offset<r;){const l=e[t.offset];if(t.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 tv(e,t){return t.offset++,null}function nv(e,t){const n=Xo(e,t),r=e[t.offset];t.offset++;const o=e.subarray(t.offset,t.offset+n-1);if(t.offset+=n,r!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function rv(e,t){const n=Xo(e,t),r=e.subarray(t.offset,t.offset+n);return t.offset+=n,r}function ov(e){let t=e.toString(16);t.length%2===1&&(t="0"+t);const n=new ye;for(let r=0;r<t.length;r+=2)n.append(Uint8Array.from([parseInt(`${t[r]}${t[r+1]}`,16)]));return n}function Mi(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);const t=ov(e.byteLength);return new ye(Uint8Array.from([t.byteLength|Pc]),t)}function bt(e){const t=new ye,n=128;return(e.subarray()[0]&n)===n&&t.append(Uint8Array.from([0])),t.append(e),new ye(Uint8Array.from([2]),Mi(t),t)}function ql(e){const t=Uint8Array.from([0]),n=new ye(t,e);return new ye(Uint8Array.from([3]),Mi(n),n)}function sv(e){return new ye(Uint8Array.from([4]),Mi(e),e)}function nn(e,t=48){const n=new ye;for(const r of e)n.append(r);return new ye(Uint8Array.from([t]),Mi(n),n)}async function iv(e,t,n){const r=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["sign"]);n?.signal?.throwIfAborted();const o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,t.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function av(e,t,n,r){const o=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();const s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,n.subarray());return r?.signal?.throwIfAborted(),s}const cv=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),lv=Uint8Array.from([6,5,43,129,4,0,34]),dv=Uint8Array.from([6,5,43,129,4,0,35]),op={ext:!0,kty:"EC",crv:"P-256"},sp={ext:!0,kty:"EC",crv:"P-384"},ip={ext:!0,kty:"EC",crv:"P-521"},br=32,vr=48,Sr=66;function uv(e){const t=Kr(e);return fv(t)}function fv(e){const t=e[1],n=le(t,"base64url"),r=e[2][1][0],o=1;let s,i;if(t.byteLength===br)return s=le(r.subarray(o,o+br),"base64url"),i=le(r.subarray(o+br),"base64url"),new ha({...op,key_ops:["sign"],d:n,x:s,y:i});if(t.byteLength===vr)return s=le(r.subarray(o,o+vr),"base64url"),i=le(r.subarray(o+vr),"base64url"),new ha({...sp,key_ops:["sign"],d:n,x:s,y:i});if(t.byteLength===Sr)return s=le(r.subarray(o,o+Sr),"base64url"),i=le(r.subarray(o+Sr),"base64url"),new ha({...ip,key_ops:["sign"],d:n,x:s,y:i});throw new Nt(`Private key length was wrong length, got ${t.byteLength}, expected 32, 48 or 66`)}function ap(e){const t=Kr(e);return hv(t)}function hv(e){const t=e[1][1][0],n=1;let r,o;if(t.byteLength===br*2+1)return r=le(t.subarray(n,n+br),"base64url"),o=le(t.subarray(n+br),"base64url"),new Ls({...op,key_ops:["verify"],x:r,y:o});if(t.byteLength===vr*2+1)return r=le(t.subarray(n,n+vr),"base64url"),o=le(t.subarray(n+vr),"base64url"),new Ls({...sp,key_ops:["verify"],x:r,y:o});if(t.byteLength===Sr*2+1)return r=le(t.subarray(n,n+Sr),"base64url"),o=le(t.subarray(n+Sr),"base64url"),new Ls({...ip,key_ops:["verify"],x:r,y:o});throw new Nt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function pv(e){return nn([bt(Uint8Array.from([1])),sv(Ue(e.d??"","base64url")),nn([cp(e.crv)],160),nn([ql(new ye(Uint8Array.from([4]),Ue(e.x??"","base64url"),Ue(e.y??"","base64url")))],161)]).subarray()}function gv(e){return nn([bt(Uint8Array.from([1])),nn([cp(e.crv)],160),nn([ql(new ye(Uint8Array.from([4]),Ue(e.x??"","base64url"),Ue(e.y??"","base64url")))],161)]).subarray()}function cp(e){if(e==="P-256")return cv;if(e==="P-384")return lv;if(e==="P-521")return dv;throw new Nt(`Invalid curve ${e}`)}class Ls{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=gv(this.jwk)),this._raw}toMultihash(){return Yo.digest(Ki(this))}toCID(){return Le.createV1(114,this.toMultihash())}toString(){return it.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Lt(this.raw,t.raw)}async verify(t,n,r){return av(this.jwk,n,t,r)}}class ha{type="ECDSA";jwk;publicKey;_raw;constructor(t){this.jwk=t,this.publicKey=new Ls({crv:t.crv,ext:t.ext,key_ops:["verify"],kty:"EC",x:t.x,y:t.y})}get raw(){return this._raw==null&&(this._raw=pv(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Lt(this.raw,t.raw)}async sign(t,n){return iv(this.jwk,t,n)}}const sr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Zo(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Nc(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Yn(e,...t){if(!Zo(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function lp(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Nc(e.outputLen),Nc(e.blockLen)}function Zs(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function mv(e,t){Yn(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Dr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function pa(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ft(e,t){return e<<32-t|e>>>t}const dp=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",wv=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function On(e){if(Yn(e),dp)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=wv[e[n]];return t}const zt={_0:48,_9:57,A:65,F:70,a:97,f:102};function hu(e){if(e>=zt._0&&e<=zt._9)return e-zt._0;if(e>=zt.A&&e<=zt.F)return e-(zt.A-10);if(e>=zt.a&&e<=zt.f)return e-(zt.a-10)}function Js(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(dp)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){const i=hu(e.charCodeAt(s)),a=hu(e.charCodeAt(s+1));if(i===void 0||a===void 0){const c=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a}return r}function yv(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function Kl(e){return typeof e=="string"&&(e=yv(e)),Yn(e),e}function Ht(...e){let t=0;for(let r=0;r<e.length;r++){const o=e[r];Yn(o),t+=o.length}const n=new Uint8Array(t);for(let r=0,o=0;r<e.length;r++){const s=e[r];n.set(s,o),o+=s.length}return n}class up{}function fp(e){const t=r=>e().update(Kl(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function zl(e=32){if(sr&&typeof sr.getRandomValues=="function")return sr.getRandomValues(new Uint8Array(e));if(sr&&typeof sr.randomBytes=="function")return Uint8Array.from(sr.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function bv(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const o=BigInt(32),s=BigInt(4294967295),i=Number(n>>o&s),a=Number(n&s),c=r?4:0,l=r?0:4;e.setUint32(t+c,i,r),e.setUint32(t+l,a,r)}function vv(e,t,n){return e&t^~e&n}function Sv(e,t,n){return e&t^e&n^t&n}let hp=class extends up{constructor(t,n,r,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(t),this.view=pa(this.buffer)}update(t){Zs(this),t=Kl(t),Yn(t);const{view:n,buffer:r,blockLen:o}=this,s=t.length;for(let i=0;i<s;){const a=Math.min(o-this.pos,s-i);if(a===o){const c=pa(t);for(;o<=s-i;i+=o)this.process(c,i);continue}r.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Zs(this),mv(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:o,isLE:s}=this;let{pos:i}=this;n[i++]=128,Dr(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(r,0),i=0);for(let u=i;u<o;u++)n[u]=0;bv(r,o-8,BigInt(this.length*8),s),this.process(r,0);const a=pa(t),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:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:r,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}};const dn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),tt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),ss=BigInt(2**32-1),pu=BigInt(32);function Ev(e,t=!1){return t?{h:Number(e&ss),l:Number(e>>pu&ss)}:{h:Number(e>>pu&ss)|0,l:Number(e&ss)|0}}function xv(e,t=!1){const n=e.length;let r=new Uint32Array(n),o=new Uint32Array(n);for(let s=0;s<n;s++){const{h:i,l:a}=Ev(e[s],t);[r[s],o[s]]=[i,a]}return[r,o]}const gu=(e,t,n)=>e>>>n,mu=(e,t,n)=>e<<32-n|t>>>n,ir=(e,t,n)=>e>>>n|t<<32-n,ar=(e,t,n)=>e<<32-n|t>>>n,is=(e,t,n)=>e<<64-n|t>>>n-32,as=(e,t,n)=>e>>>n-32|t<<64-n;function Wt(e,t,n,r){const o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:o|0}}const Iv=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Av=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Cv=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Rv=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,kv=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Tv=(e,t,n,r,o,s)=>t+n+r+o+s+(e/2**32|0)|0,Pv=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]),un=new Uint32Array(64);class Nv extends hp{constructor(t=32){super(64,t,8,!1),this.A=dn[0]|0,this.B=dn[1]|0,this.C=dn[2]|0,this.D=dn[3]|0,this.E=dn[4]|0,this.F=dn[5]|0,this.G=dn[6]|0,this.H=dn[7]|0}get(){const{A:t,B:n,C:r,D:o,E:s,F:i,G:a,H:c}=this;return[t,n,r,o,s,i,a,c]}set(t,n,r,o,s,i,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,n){for(let u=0;u<16;u++,n+=4)un[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const f=un[u-15],p=un[u-2],g=Ft(f,7)^Ft(f,18)^f>>>3,m=Ft(p,17)^Ft(p,19)^p>>>10;un[u]=m+un[u-7]+g+un[u-16]|0}let{A:r,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=Ft(a,6)^Ft(a,11)^Ft(a,25),p=d+f+vv(a,c,l)+Pv[u]+un[u]|0,m=(Ft(r,2)^Ft(r,13)^Ft(r,22))+Sv(r,o,s)|0;d=l,l=c,c=a,a=i+p|0,i=s,s=o,o=r,r=p+m|0}r=r+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(r,o,s,i,a,c,l,d)}roundClean(){Dr(un)}destroy(){this.set(0,0,0,0,0,0,0,0),Dr(this.buffer)}}const pp=xv(["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(e=>BigInt(e))),Lv=pp[0],Bv=pp[1],fn=new Uint32Array(80),hn=new Uint32Array(80);class Dv extends hp{constructor(t=64){super(128,t,16,!1),this.Ah=tt[0]|0,this.Al=tt[1]|0,this.Bh=tt[2]|0,this.Bl=tt[3]|0,this.Ch=tt[4]|0,this.Cl=tt[5]|0,this.Dh=tt[6]|0,this.Dl=tt[7]|0,this.Eh=tt[8]|0,this.El=tt[9]|0,this.Fh=tt[10]|0,this.Fl=tt[11]|0,this.Gh=tt[12]|0,this.Gl=tt[13]|0,this.Hh=tt[14]|0,this.Hl=tt[15]|0}get(){const{Ah:t,Al:n,Bh:r,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:f,Gh:p,Gl:g,Hh:m,Hl:b}=this;return[t,n,r,o,s,i,a,c,l,d,u,f,p,g,m,b]}set(t,n,r,o,s,i,a,c,l,d,u,f,p,g,m,b){this.Ah=t|0,this.Al=n|0,this.Bh=r|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=p|0,this.Gl=g|0,this.Hh=m|0,this.Hl=b|0}process(t,n){for(let w=0;w<16;w++,n+=4)fn[w]=t.getUint32(n),hn[w]=t.getUint32(n+=4);for(let w=16;w<80;w++){const I=fn[w-15]|0,R=hn[w-15]|0,S=ir(I,R,1)^ir(I,R,8)^gu(I,R,7),A=ar(I,R,1)^ar(I,R,8)^mu(I,R,7),T=fn[w-2]|0,v=hn[w-2]|0,E=ir(T,v,19)^is(T,v,61)^gu(T,v,6),C=ar(T,v,19)^as(T,v,61)^mu(T,v,6),B=Cv(A,C,hn[w-7],hn[w-16]),k=Rv(B,S,E,fn[w-7],fn[w-16]);fn[w]=k|0,hn[w]=B|0}let{Ah:r,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:f,Fh:p,Fl:g,Gh:m,Gl:b,Hh:y,Hl:x}=this;for(let w=0;w<80;w++){const I=ir(u,f,14)^ir(u,f,18)^is(u,f,41),R=ar(u,f,14)^ar(u,f,18)^as(u,f,41),S=u&p^~u&m,A=f&g^~f&b,T=kv(x,R,A,Bv[w],hn[w]),v=Tv(T,y,I,S,Lv[w],fn[w]),E=T|0,C=ir(r,o,28)^is(r,o,34)^is(r,o,39),B=ar(r,o,28)^as(r,o,34)^as(r,o,39),k=r&s^r&a^s&a,N=o&i^o&c^i&c;y=m|0,x=b|0,m=p|0,b=g|0,p=u|0,g=f|0,{h:u,l:f}=Wt(l|0,d|0,v|0,E|0),l=a|0,d=c|0,a=s|0,c=i|0,s=r|0,i=o|0;const L=Iv(E,B,N);r=Av(L,v,C,k),o=L|0}({h:r,l:o}=Wt(this.Ah|0,this.Al|0,r|0,o|0)),{h:s,l:i}=Wt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Wt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=Wt(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:f}=Wt(this.Eh|0,this.El|0,u|0,f|0),{h:p,l:g}=Wt(this.Fh|0,this.Fl|0,p|0,g|0),{h:m,l:b}=Wt(this.Gh|0,this.Gl|0,m|0,b|0),{h:y,l:x}=Wt(this.Hh|0,this.Hl|0,y|0,x|0),this.set(r,o,s,i,a,c,l,d,u,f,p,g,m,b,y,x)}roundClean(){Dr(fn,hn)}destroy(){Dr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const gp=fp(()=>new Nv),_v=fp(()=>new Dv);const Wl=BigInt(0),Lc=BigInt(1);function qn(e,t=""){if(typeof e!="boolean"){const n=t&&`"${t}"`;throw new Error(n+"expected boolean, got type="+typeof e)}return e}function Tt(e,t,n=""){const r=Zo(e),o=e?.length,s=t!==void 0;if(!r||s&&o!==t){const i=n&&`"${n}" `,a=s?` of length ${t}`:"",c=r?`length=${o}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function cs(e){const t=e.toString(16);return t.length&1?"0"+t:t}function mp(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?Wl:BigInt("0x"+e)}function ji(e){return mp(On(e))}function Oo(e){return Yn(e),mp(On(Uint8Array.from(e).reverse()))}function Gl(e,t){return Js(e.toString(16).padStart(t*2,"0"))}function wp(e,t){return Gl(e,t).reverse()}function Fe(e,t,n){let r;if(typeof t=="string")try{r=Js(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(Zo(t))r=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");const o=r.length;if(typeof n=="number"&&o!==n)throw new Error(e+" of length "+n+" expected, got "+o);return r}function wu(e){return Uint8Array.from(e)}const ga=e=>typeof e=="bigint"&&Wl<=e;function Ov(e,t,n){return ga(e)&&ga(t)&&ga(n)&&t<=e&&e<n}function Bc(e,t,n,r){if(!Ov(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function yp(e){let t;for(t=0;e>Wl;e>>=Lc,t+=1);return t}const Jo=e=>(Lc<<BigInt(e))-Lc;function Fv(e,t,n){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=p=>new Uint8Array(p),o=p=>Uint8Array.of(p);let s=r(e),i=r(e),a=0;const c=()=>{s.fill(1),i.fill(0),a=0},l=(...p)=>n(i,s,...p),d=(p=r(0))=>{i=l(o(0),p),s=l(),p.length!==0&&(i=l(o(1),p),s=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0;const g=[];for(;p<t;){s=l();const m=s.slice();g.push(m),p+=s.length}return Ht(...g)};return(p,g)=>{c(),d(p);let m;for(;!(m=g(u()));)d();return c(),m}}function Qo(e,t,n={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function r(o,s,i){const a=e[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(t).forEach(([o,s])=>r(o,s,!1)),Object.entries(n).forEach(([o,s])=>r(o,s,!0))}function Qs(e){const t=new WeakMap;return(n,...r)=>{const o=t.get(n);if(o!==void 0)return o;const s=e(n,...r);return t.set(n,s),s}}const ht=BigInt(0),Ze=BigInt(1),Pn=BigInt(2),bp=BigInt(3),vp=BigInt(4),Sp=BigInt(5),Mv=BigInt(7),Ep=BigInt(8),jv=BigInt(9),xp=BigInt(16);function He(e,t){const n=e%t;return n>=ht?n:t+n}function Oe(e,t,n){let r=e;for(;t-- >ht;)r*=r,r%=n;return r}function yu(e,t){if(e===ht)throw new Error("invert: expected non-zero number");if(t<=ht)throw new Error("invert: expected positive modulus, got "+t);let n=He(e,t),r=t,o=ht,s=Ze;for(;n!==ht;){const a=r/n,c=r%n,l=o-s*a;r=n,n=c,o=s,s=l}if(r!==Ze)throw new Error("invert: does not exist");return He(o,t)}function Vl(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function Ip(e,t){const n=(e.ORDER+Ze)/vp,r=e.pow(t,n);return Vl(e,r,t),r}function Uv(e,t){const n=(e.ORDER-Sp)/Ep,r=e.mul(t,Pn),o=e.pow(r,n),s=e.mul(t,o),i=e.mul(e.mul(s,Pn),o),a=e.mul(s,e.sub(i,e.ONE));return Vl(e,a,t),a}function Hv(e){const t=Xn(e),n=Ap(e),r=n(t,t.neg(t.ONE)),o=n(t,r),s=n(t,t.neg(r)),i=(e+Mv)/xp;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,r);const u=a.mul(l,o),f=a.mul(l,s),p=a.eql(a.sqr(d),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,d,p),d=a.cmov(f,u,g);const m=a.eql(a.sqr(d),c),b=a.cmov(l,d,m);return Vl(a,b,c),b}}function Ap(e){if(e<bp)throw new Error("sqrt is not defined for small field");let t=e-Ze,n=0;for(;t%Pn===ht;)t/=Pn,n++;let r=Pn;const o=Xn(e);for(;bu(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Ip;let s=o.pow(r,t);const i=(t+Ze)/Pn;return function(c,l){if(c.is0(l))return l;if(bu(c,l)!==1)throw new Error("Cannot find square root");let d=n,u=c.mul(c.ONE,s),f=c.pow(l,t),p=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 b=Ze<<BigInt(d-g-1),y=c.pow(u,b);d=g,u=c.sqr(y),f=c.mul(f,u),p=c.mul(p,y)}return p}}function $v(e){return e%vp===bp?Ip:e%Ep===Sp?Uv:e%xp===jv?Hv(e):Ap(e)}const qv=(e,t)=>(He(e,t)&Ze)===Ze,Kv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function zv(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=Kv.reduce((r,o)=>(r[o]="function",r),t);return Qo(e,n),e}function Wv(e,t,n){if(n<ht)throw new Error("invalid exponent, negatives unsupported");if(n===ht)return e.ONE;if(n===Ze)return t;let r=e.ONE,o=t;for(;n>ht;)n&Ze&&(r=e.mul(r,o)),o=e.sqr(o),n>>=Ze;return r}function Cp(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(r[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(r[c]=e.mul(i,r[c]),e.mul(i,a)),s),r}function bu(e,t){const n=(e.ORDER-Ze)/Pn,r=e.pow(t,n),o=e.eql(r,e.ONE),s=e.eql(r,e.ZERO),i=e.eql(r,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function Rp(e,t){t!==void 0&&Nc(t);const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Xn(e,t,n=!1,r={}){if(e<=ht)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,s,i=!1,a;if(typeof t=="object"&&t!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const f=t;f.BITS&&(o=f.BITS),f.sqrt&&(s=f.sqrt),typeof f.isLE=="boolean"&&(n=f.isLE),typeof f.modFromBytes=="boolean"&&(i=f.modFromBytes),a=f.allowedLengths}else typeof t=="number"&&(o=t),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:l}=Rp(e,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:Jo(c),ZERO:ht,ONE:Ze,allowedLengths:a,create:f=>He(f,e),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return ht<=f&&f<e},is0:f=>f===ht,isValidNot0:f=>!u.is0(f)&&u.isValid(f),isOdd:f=>(f&Ze)===Ze,neg:f=>He(-f,e),eql:(f,p)=>f===p,sqr:f=>He(f*f,e),add:(f,p)=>He(f+p,e),sub:(f,p)=>He(f-p,e),mul:(f,p)=>He(f*p,e),pow:(f,p)=>Wv(u,f,p),div:(f,p)=>He(f*yu(p,e),e),sqrN:f=>f*f,addN:(f,p)=>f+p,subN:(f,p)=>f-p,mulN:(f,p)=>f*p,inv:f=>yu(f,e),sqrt:s||(f=>(d||(d=$v(e)),d(u,f))),toBytes:f=>n?wp(f,l):Gl(f,l),fromBytes:(f,p=!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,n?0:m.length-f.length),f=m}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let g=n?Oo(f):ji(f);if(i&&(g=He(g,e)),!p&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:f=>Cp(u,f),cmov:(f,p,g)=>g?p:f});return Object.freeze(u)}function kp(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Tp(e){const t=kp(e);return t+Math.ceil(t/2)}function Gv(e,t,n=!1){const r=e.length,o=kp(t),s=Tp(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const i=n?Oo(e):ji(e),a=He(i,t-Ze)+Ze;return n?wp(a,o):Gl(a,o)}const _r=BigInt(0),Nn=BigInt(1);function ei(e,t){const n=t.negate();return e?n:t}function Ln(e,t){const n=Cp(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function Pp(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function ma(e,t){Pp(e,t);const n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,s=Jo(e),i=BigInt(e);return{windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function vu(e,t,n){const{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n;let a=Number(e&o),c=e>>i;a>r&&(a-=s,c+=Nn);const l=t*r,d=l+Math.abs(a)-1,u=a===0,f=a<0,p=t%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:f,isNegF:p,offsetF:l}}function Vv(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function Yv(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((n,r)=>{if(!t.isValid(n))throw new Error("invalid scalar at index "+r)})}const wa=new WeakMap,Np=new WeakMap;function ya(e){return Np.get(e)||1}function Su(e){if(e!==_r)throw new Error("invalid wNAF")}class Lp{constructor(t,n){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=n}_unsafeLadder(t,n,r=this.ZERO){let o=t;for(;n>_r;)n&Nn&&(r=r.add(o)),o=o.double(),n>>=Nn;return r}precomputeWindow(t,n){const{windows:r,windowSize:o}=ma(n,this.bits),s=[];let i=t,a=i;for(let c=0;c<r;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(t,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE;const i=ma(t,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:f,offsetF:p}=vu(r,a,i);r=c,d?s=s.add(ei(f,n[p])):o=o.add(ei(u,n[l]))}return Su(r),{p:o,f:s}}wNAFUnsafe(t,n,r,o=this.ZERO){const s=ma(t,this.bits);for(let i=0;i<s.windows&&r!==_r;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=vu(r,i,s);if(r=a,!l){const u=n[c];o=o.add(d?u.negate():u)}}return Su(r),o}getPrecomputes(t,n,r){let o=wa.get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(o=r(o)),wa.set(n,o))),o}cached(t,n,r){const o=ya(t);return this.wNAF(o,this.getPrecomputes(o,t,r),n)}unsafe(t,n,r,o){const s=ya(t);return s===1?this._unsafeLadder(t,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,r),n,o)}createCache(t,n){Pp(n,this.bits),Np.set(t,n),wa.delete(t)}hasCache(t){return ya(t)!==1}}function Xv(e,t,n,r){let o=t,s=e.ZERO,i=e.ZERO;for(;n>_r||r>_r;)n&Nn&&(s=s.add(o)),r&Nn&&(i=i.add(o)),o=o.double(),n>>=Nn,r>>=Nn;return{p1:s,p2:i}}function Bp(e,t,n,r){Vv(n,e),Yv(r,t);const o=n.length,s=r.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");const i=e.ZERO,a=yp(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Jo(c),d=new Array(Number(l)+1).fill(i),u=Math.floor((t.BITS-1)/c)*c;let f=i;for(let p=u;p>=0;p-=c){d.fill(i);for(let m=0;m<s;m++){const b=r[m],y=Number(b>>BigInt(p)&l);d[y]=d[y].add(n[m])}let g=i;for(let m=d.length-1,b=i;m>0;m--)b=b.add(d[m]),g=g.add(b);if(f=f.add(g),p!==0)for(let m=0;m<c;m++)f=f.double()}return f}function Eu(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return zv(t),t}else return Xn(e,{isLE:n})}function Dp(e,t,n={},r){if(r===void 0&&(r=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(const c of["p","n","h"]){const l=t[c];if(!(typeof l=="bigint"&&l>_r))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Eu(t.p,n.Fp,r),s=Eu(t.n,n.Fn,r),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(const c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}const pn=BigInt(0),ze=BigInt(1),ba=BigInt(2),Zv=BigInt(8);function Jv(e,t,n,r){const o=e.sqr(n),s=e.sqr(r),i=e.add(e.mul(t.a,o),s),a=e.add(e.ONE,e.mul(t.d,e.mul(o,s)));return e.eql(i,a)}function Qv(e,t={}){const n=Dp("edwards",e,t,t.FpFnLE),{Fp:r,Fn:o}=n;let s=n.CURVE;const{h:i}=s;Qo(t,{},{uvRatio:"function"});const a=ba<<BigInt(o.BYTES*8)-ze,c=b=>r.create(b),l=t.uvRatio||((b,y)=>{try{return{isValid:!0,value:r.sqrt(r.div(b,y))}}catch{return{isValid:!1,value:pn}}});if(!Jv(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(b,y,x=!1){const w=x?ze:pn;return Bc("coordinate "+b,y,w,a),y}function u(b){if(!(b instanceof g))throw new Error("ExtendedPoint expected")}const f=Qs((b,y)=>{const{X:x,Y:w,Z:I}=b,R=b.is0();y==null&&(y=R?Zv:r.inv(I));const S=c(x*y),A=c(w*y),T=r.mul(I,y);if(R)return{x:pn,y:ze};if(T!==ze)throw new Error("invZ was invalid");return{x:S,y:A}}),p=Qs(b=>{const{a:y,d:x}=s;if(b.is0())throw new Error("bad point: ZERO");const{X:w,Y:I,Z:R,T:S}=b,A=c(w*w),T=c(I*I),v=c(R*R),E=c(v*v),C=c(A*y),B=c(v*c(C+T)),k=c(E+c(x*c(A*T)));if(B!==k)throw new Error("bad point: equation left != right (1)");const N=c(w*I),L=c(R*S);if(N!==L)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(y,x,w,I){this.X=d("x",y),this.Y=d("y",x),this.Z=d("z",w,!0),this.T=d("t",I),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof g)throw new Error("extended point not allowed");const{x,y:w}=y||{};return d("x",x),d("y",w),new g(x,w,ze,c(x*w))}static fromBytes(y,x=!1){const w=r.BYTES,{a:I,d:R}=s;y=wu(Tt(y,w,"point")),qn(x,"zip215");const S=wu(y),A=y[w-1];S[w-1]=A&-129;const T=Oo(S),v=x?a:r.ORDER;Bc("point.y",T,pn,v);const E=c(T*T),C=c(E-ze),B=c(R*E-I);let{isValid:k,value:N}=l(C,B);if(!k)throw new Error("bad point: invalid y coordinate");const L=(N&ze)===ze,D=(A&128)!==0;if(!x&&N===pn&&D)throw new Error("bad point: x=0 and x_0=1");return D!==L&&(N=c(-N)),g.fromAffine({x:N,y:T})}static fromHex(y,x=!1){return g.fromBytes(Fe("point",y),x)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,x=!0){return m.createCache(this,y),x||this.multiply(ba),this}assertValidity(){p(this)}equals(y){u(y);const{X:x,Y:w,Z:I}=this,{X:R,Y:S,Z:A}=y,T=c(x*A),v=c(R*I),E=c(w*A),C=c(S*I);return T===v&&E===C}is0(){return this.equals(g.ZERO)}negate(){return new g(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:y}=s,{X:x,Y:w,Z:I}=this,R=c(x*x),S=c(w*w),A=c(ba*c(I*I)),T=c(y*R),v=x+w,E=c(c(v*v)-R-S),C=T+S,B=C-A,k=T-S,N=c(E*B),L=c(C*k),D=c(E*k),F=c(B*C);return new g(N,L,F,D)}add(y){u(y);const{a:x,d:w}=s,{X:I,Y:R,Z:S,T:A}=this,{X:T,Y:v,Z:E,T:C}=y,B=c(I*T),k=c(R*v),N=c(A*w*C),L=c(S*E),D=c((I+R)*(T+v)-B-k),F=L-N,O=L+N,_=c(k-x*B),H=c(D*F),q=c(O*_),j=c(D*_),K=c(F*O);return new g(H,q,K,j)}subtract(y){return this.add(y.negate())}multiply(y){if(!o.isValidNot0(y))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:x,f:w}=m.cached(this,y,I=>Ln(g,I));return Ln(g,[x,w])[0]}multiplyUnsafe(y,x=g.ZERO){if(!o.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===pn?g.ZERO:this.is0()||y===ze?this:m.unsafe(this,y,w=>Ln(g,w),x)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(y){return f(this,y)}clearCofactor(){return i===ze?this:this.multiplyUnsafe(i)}toBytes(){const{x:y,y:x}=this.toAffine(),w=r.toBytes(x);return w[w.length-1]|=y&ze?128:0,w}toHex(){return On(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(y){return Ln(g,y)}static msm(y,x){return Bp(g,o,y,x)}_setWindowSize(y){this.precompute(y)}toRawBytes(){return this.toBytes()}}g.BASE=new g(s.Gx,s.Gy,ze,c(s.Gx*s.Gy)),g.ZERO=new g(pn,ze,ze,pn),g.Fp=r,g.Fn=o;const m=new Lp(g,o.BITS);return g.BASE.precompute(8),g}function eS(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is required');Qo(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:o,Fp:s,Fn:i}=e,a=n.randomBytes||zl,c=n.adjustScalarBytes||(v=>v),l=n.domain||((v,E,C)=>{if(qn(C,"phflag"),E.length||C)throw new Error("Contexts/pre-hash are not supported");return v});function d(v){return i.create(Oo(v))}function u(v){const E=w.secretKey;v=Fe("private key",v,E);const C=Fe("hashed private key",t(v),2*E),B=c(C.slice(0,E)),k=C.slice(E,2*E),N=d(B);return{head:B,prefix:k,scalar:N}}function f(v){const{head:E,prefix:C,scalar:B}=u(v),k=o.multiply(B),N=k.toBytes();return{head:E,prefix:C,scalar:B,point:k,pointBytes:N}}function p(v){return f(v).pointBytes}function g(v=Uint8Array.of(),...E){const C=Ht(...E);return d(t(l(C,Fe("context",v),!!r)))}function m(v,E,C={}){v=Fe("message",v),r&&(v=r(v));const{prefix:B,scalar:k,pointBytes:N}=f(E),L=g(C.context,B,v),D=o.multiply(L).toBytes(),F=g(C.context,D,N,v),O=i.create(L+F*k);if(!i.isValid(O))throw new Error("sign failed: invalid s");const _=Ht(D,i.toBytes(O));return Tt(_,w.signature,"result")}const b={zip215:!0};function y(v,E,C,B=b){const{context:k,zip215:N}=B,L=w.signature;v=Fe("signature",v,L),E=Fe("message",E),C=Fe("publicKey",C,w.publicKey),N!==void 0&&qn(N,"zip215"),r&&(E=r(E));const D=L/2,F=v.subarray(0,D),O=Oo(v.subarray(D,L));let _,H,q;try{_=e.fromBytes(C,N),H=e.fromBytes(F,N),q=o.multiplyUnsafe(O)}catch{return!1}if(!N&&_.isSmallOrder())return!1;const j=g(k,H.toBytes(),_.toBytes(),E);return H.add(_.multiplyUnsafe(j)).subtract(q).clearCofactor().is0()}const x=s.BYTES,w={secretKey:x,publicKey:x,signature:2*x,seed:x};function I(v=a(w.seed)){return Tt(v,w.seed,"seed")}function R(v){const E=T.randomSecretKey(v);return{secretKey:E,publicKey:p(E)}}function S(v){return Zo(v)&&v.length===i.BYTES}function A(v,E){try{return!!e.fromBytes(v,E)}catch{return!1}}const T={getExtendedPublicKey:f,randomSecretKey:I,isValidSecretKey:S,isValidPublicKey:A,toMontgomery(v){const{y:E}=e.fromBytes(v),C=w.publicKey,B=C===32;if(!B&&C!==57)throw new Error("only defined for 25519 and 448");const k=B?s.div(ze+E,ze-E):s.div(E-ze,E+ze);return s.toBytes(k)},toMontgomerySecret(v){const E=w.secretKey;Tt(v,E);const C=t(v.subarray(0,E));return c(C).subarray(0,E)},randomPrivateKey:I,precompute(v=8,E=e.BASE){return E.precompute(v,!1)}};return Object.freeze({keygen:R,getPublicKey:p,sign:m,verify:y,utils:T,Point:e,lengths:w})}function tS(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp,r=Xn(t.n,e.nBitLength,!0),o={Fp:n,Fn:r,uvRatio:e.uvRatio},s={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:o,hash:e.hash,eddsaOpts:s}}function nS(e,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function rS(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:o}=tS(e),s=Qv(t,n),i=eS(s,r,o);return nS(e,i)}const oS=BigInt(1),xu=BigInt(2);BigInt(3);const sS=BigInt(5),iS=BigInt(8),Yl=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),_p={p:Yl,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:iS,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function aS(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=Yl,a=e*e%s*e%s,c=Oe(a,xu,s)*a%s,l=Oe(c,oS,s)*e%s,d=Oe(l,sS,s)*l%s,u=Oe(d,t,s)*d%s,f=Oe(u,n,s)*u%s,p=Oe(f,r,s)*f%s,g=Oe(p,o,s)*p%s,m=Oe(g,o,s)*p%s,b=Oe(m,t,s)*d%s;return{pow_p_5_8:Oe(b,xu,s)*e%s,b2:a}}function cS(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Iu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function lS(e,t){const n=Yl,r=He(t*t*t,n),o=He(r*r*t,n),s=aS(e*o).pow_p_5_8;let i=He(e*r*s,n);const a=He(t*i*i,n),c=i,l=He(i*Iu,n),d=a===e,u=a===He(-e,n),f=a===He(-e*Iu,n);return d&&(i=c),(u||f)&&(i=l),qv(i,n)&&(i=He(-i,n)),{isValid:d||u,value:i}}const dS=Xn(_p.p,{isLE:!0}),uS={..._p,Fp:dS,hash:_v,adjustScalarBytes:cS,uvRatio:lS},ti=rS(uS);class Au extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}}class Cu extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}}class fS extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}}const an={get(e=globalThis){const t=e.crypto;if(t?.subtle==null)throw new fS("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 t}},ni=32,Xt=64,Dc=32;let Er;const Op=(async()=>{try{return await an.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function hS(){const e=ti.utils.randomPrivateKey(),t=ti.getPublicKey(e);return{privateKey:vS(e,t),publicKey:t}}async function pS(e,t){let n;e.length===Xt?n=e.subarray(0,32):n=e;const r={crv:"Ed25519",kty:"OKP",x:le(e.subarray(32),"base64url"),d:le(n,"base64url"),ext:!0,key_ops:["sign"]},o=await an.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),s=await an.get().subtle.sign({name:"Ed25519"},o,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(s,0,s.byteLength)}function gS(e,t){const n=e.subarray(0,Dc);return ti.sign(t instanceof Uint8Array?t:t.subarray(),n)}async function mS(e,t){return Er==null&&(Er=await Op),Er?pS(e,t):gS(e,t)}async function wS(e,t,n){if(e.buffer instanceof ArrayBuffer){const r=await an.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await an.get().subtle.verify({name:"Ed25519"},r,t,n instanceof Uint8Array?n:n.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function yS(e,t,n){return ti.verify(t,n instanceof Uint8Array?n:n.subarray(),e)}async function bS(e,t,n){return Er==null&&(Er=await Op),Er?wS(e,t,n):yS(e,t,n)}function vS(e,t){const n=new Uint8Array(Xt);for(let r=0;r<Dc;r++)n[r]=e[r],n[Dc+r]=t[r];return n}function Ui(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}class Fp{type="Ed25519";raw;constructor(t){this.raw=Fo(t,ni)}toMultihash(){return Yo.digest(Ki(this))}toCID(){return Le.createV1(114,this.toMultihash())}toString(){return it.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Lt(this.raw,t.raw)}verify(t,n,r){r?.signal?.throwIfAborted();const o=bS(this.raw,n,t);return Ui(o)?o.then(s=>(r?.signal?.throwIfAborted(),s)):o}}class _c{type="Ed25519";raw;publicKey;constructor(t,n){this.raw=Fo(t,Xt),this.publicKey=new Fp(n)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Lt(this.raw,t.raw)}sign(t,n){n?.signal?.throwIfAborted();const r=mS(this.raw,t);return Ui(r)?r.then(o=>(n?.signal?.throwIfAborted(),o)):(n?.signal?.throwIfAborted(),r)}}function SS(e){if(e.length>Xt){e=Fo(e,Xt+ni);const r=e.subarray(0,Xt),o=e.subarray(Xt,e.length);return new _c(r,o)}e=Fo(e,Xt);const t=e.subarray(0,Xt),n=e.subarray(ni);return new _c(t,n)}function Mp(e){return e=Fo(e,ni),new Fp(e)}async function ES(){const{privateKey:e,publicKey:t}=hS();return new _c(e,t)}function Fo(e,t){if(e=Uint8Array.from(e??[]),e.length!==t)throw new Nt(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}const xS=Math.pow(2,7),IS=Math.pow(2,14),AS=Math.pow(2,21),Xl=Math.pow(2,28),Zl=Math.pow(2,35),Jl=Math.pow(2,42),Ql=Math.pow(2,49),ge=128,nt=127;function Zn(e){if(e<xS)return 1;if(e<IS)return 2;if(e<AS)return 3;if(e<Xl)return 4;if(e<Zl)return 5;if(e<Jl)return 6;if(e<Ql)return 7;if(Number.MAX_SAFE_INTEGER!=null&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function jp(e,t,n=0){switch(Zn(e)){case 8:t[n++]=e&255|ge,e/=128;case 7:t[n++]=e&255|ge,e/=128;case 6:t[n++]=e&255|ge,e/=128;case 5:t[n++]=e&255|ge,e/=128;case 4:t[n++]=e&255|ge,e>>>=7;case 3:t[n++]=e&255|ge,e>>>=7;case 2:t[n++]=e&255|ge,e>>>=7;case 1:{t[n++]=e&255,e>>>=7;break}default:throw new Error("unreachable")}return t}function CS(e,t,n=0){switch(Zn(e)){case 8:t.set(n++,e&255|ge),e/=128;case 7:t.set(n++,e&255|ge),e/=128;case 6:t.set(n++,e&255|ge),e/=128;case 5:t.set(n++,e&255|ge),e/=128;case 4:t.set(n++,e&255|ge),e>>>=7;case 3:t.set(n++,e&255|ge),e>>>=7;case 2:t.set(n++,e&255|ge),e>>>=7;case 1:{t.set(n++,e&255),e>>>=7;break}default:throw new Error("unreachable")}return t}function Up(e,t){let n=e[t],r=0;if(r+=n&nt,n<ge||(n=e[t+1],r+=(n&nt)<<7,n<ge)||(n=e[t+2],r+=(n&nt)<<14,n<ge)||(n=e[t+3],r+=(n&nt)<<21,n<ge)||(n=e[t+4],r+=(n&nt)*Xl,n<ge)||(n=e[t+5],r+=(n&nt)*Zl,n<ge)||(n=e[t+6],r+=(n&nt)*Jl,n<ge)||(n=e[t+7],r+=(n&nt)*Ql,n<ge))return r;throw new RangeError("Could not decode varint")}function RS(e,t){let n=e.get(t),r=0;if(r+=n&nt,n<ge||(n=e.get(t+1),r+=(n&nt)<<7,n<ge)||(n=e.get(t+2),r+=(n&nt)<<14,n<ge)||(n=e.get(t+3),r+=(n&nt)<<21,n<ge)||(n=e.get(t+4),r+=(n&nt)*Xl,n<ge)||(n=e.get(t+5),r+=(n&nt)*Zl,n<ge)||(n=e.get(t+6),r+=(n&nt)*Jl,n<ge)||(n=e.get(t+7),r+=(n&nt)*Ql,n<ge))return r;throw new RangeError("Could not decode varint")}function kS(e,t,n=0){return t==null&&(t=sn(Zn(e))),t instanceof Uint8Array?jp(e,t,n):CS(e,t,n)}function Hp(e,t=0){return e instanceof Uint8Array?Up(e,t):RS(e,t)}const ed=new Float32Array([-0]),Sn=new Uint8Array(ed.buffer);function TS(e,t,n){ed[0]=e,t[n]=Sn[0],t[n+1]=Sn[1],t[n+2]=Sn[2],t[n+3]=Sn[3]}function PS(e,t){return Sn[0]=e[t],Sn[1]=e[t+1],Sn[2]=e[t+2],Sn[3]=e[t+3],ed[0]}const td=new Float64Array([-0]),rt=new Uint8Array(td.buffer);function NS(e,t,n){td[0]=e,t[n]=rt[0],t[n+1]=rt[1],t[n+2]=rt[2],t[n+3]=rt[3],t[n+4]=rt[4],t[n+5]=rt[5],t[n+6]=rt[6],t[n+7]=rt[7]}function LS(e,t){return rt[0]=e[t],rt[1]=e[t+1],rt[2]=e[t+2],rt[3]=e[t+3],rt[4]=e[t+4],rt[5]=e[t+5],rt[6]=e[t+6],rt[7]=e[t+7],td[0]}const BS=BigInt(Number.MAX_SAFE_INTEGER),DS=BigInt(Number.MIN_SAFE_INTEGER);class ot{lo;hi;constructor(t,n){this.lo=t|0,this.hi=n|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){const n=~this.lo+1>>>0;let r=~this.hi>>>0;return n===0&&(r=r+1>>>0),-(n+r*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){const n=~this.lo+1>>>0;let r=~this.hi>>>0;return n===0&&(r=r+1>>>0),-(BigInt(n)+(BigInt(r)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){const t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){const t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){const t=this.lo,n=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?n===0?t<16384?t<128?1:2:t<2097152?3:4:n<16384?n<128?5:6:n<2097152?7:8:r<128?9:10}static fromBigInt(t){if(t===0n)return Fn;if(t<BS&&t>DS)return this.fromNumber(Number(t));const n=t<0n;n&&(t=-t);let r=t>>32n,o=t-(r<<32n);return n&&(r=~r|0n,o=~o|0n,++o>Ru&&(o=0n,++r>Ru&&(r=0n))),new ot(Number(o),Number(r))}static fromNumber(t){if(t===0)return Fn;const n=t<0;n&&(t=-t);let r=t>>>0,o=(t-r)/4294967296>>>0;return n&&(o=~o>>>0,r=~r>>>0,++r>4294967295&&(r=0,++o>4294967295&&(o=0))),new ot(r,o)}static from(t){return typeof t=="number"?ot.fromNumber(t):typeof t=="bigint"?ot.fromBigInt(t):typeof t=="string"?ot.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new ot(t.low>>>0,t.high>>>0):Fn}}const Fn=new ot(0,0);Fn.toBigInt=function(){return 0n};Fn.zzEncode=Fn.zzDecode=function(){return this};Fn.length=function(){return 1};const Ru=4294967296n;function _S(e){let t=0,n=0;for(let r=0;r<e.length;++r)n=e.charCodeAt(r),n<128?t+=1:n<2048?t+=2:(n&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320?(++r,t+=4):t+=3;return t}function OS(e,t,n){if(n-t<1)return"";let o;const s=[];let i=0,a;for(;t<n;)a=e[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(e[t++]&63)<<6|e[t++]&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 $p(e,t,n){const r=n;let o,s;for(let i=0;i<e.length;++i)o=e.charCodeAt(i),o<128?t[n++]=o:o<2048?(t[n++]=o>>6|192,t[n++]=o&63|128):(o&64512)===55296&&((s=e.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=o&63|128):(t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=o&63|128);return n-r}function Rt(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function ls(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class FS{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Rt(this,10);return t}int32(){return this.uint32()|0}sint32(){const t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Rt(this,4);return ls(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Rt(this,4);return ls(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Rt(this,4);const t=PS(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Rt(this,4);const t=LS(this.buf,this.pos);return this.pos+=8,t}bytes(){const t=this.uint32(),n=this.pos,r=this.pos+t;if(r>this.len)throw Rt(this,t);return this.pos+=t,n===r?new Uint8Array(0):this.buf.subarray(n,r)}string(){const t=this.bytes();return OS(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Rt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Rt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){const t=new ot(0,0);let n=0;if(this.len-this.pos>4){for(;n<4;++n)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<n*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;n=0}else{for(;n<3;++n){if(this.pos>=this.len)throw Rt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<n*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<n*7)>>>0,t}if(this.len-this.pos>4){for(;n<5;++n)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<n*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;n<5;++n){if(this.pos>=this.len)throw Rt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<n*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Rt(this,8);const t=ls(this.buf,this.pos+=4),n=ls(this.buf,this.pos+=4);return new ot(t,n)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const t=Up(this.buf,this.pos);return this.pos+=Zn(t),t}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 MS(e){return new FS(e instanceof Uint8Array?e:e.subarray())}function Hi(e,t,n){const r=MS(e);return t.decode(r,void 0,n)}function jS(e){let r,o=8192;return function(i){if(i<1||i>4096)return sn(i);o+i>8192&&(r=sn(8192),o=0);const a=r.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}class wo{fn;len;next;val;constructor(t,n,r){this.fn=t,this.len=n,this.next=void 0,this.val=r}}function va(){}class US{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}}const HS=jS();function $S(e){return globalThis.Buffer!=null?sn(e):HS(e)}class Oc{len;head;tail;states;constructor(){this.len=0,this.head=new wo(va,0,0),this.tail=this.head,this.states=null}_push(t,n,r){return this.tail=this.tail.next=new wo(t,n,r),this.len+=n,this}uint32(t){return this.len+=(this.tail=this.tail.next=new KS((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(ds,10,ot.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){const n=ot.fromBigInt(t);return this._push(ds,n.length(),n)}uint64Number(t){return this._push(jp,Zn(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){const n=ot.fromBigInt(t).zzEncode();return this._push(ds,n.length(),n)}sint64Number(t){const n=ot.fromNumber(t).zzEncode();return this._push(ds,n.length(),n)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Sa,1,t?1:0)}fixed32(t){return this._push(eo,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){const n=ot.fromBigInt(t);return this._push(eo,4,n.lo)._push(eo,4,n.hi)}fixed64Number(t){const n=ot.fromNumber(t);return this._push(eo,4,n.lo)._push(eo,4,n.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(TS,4,t)}double(t){return this._push(NS,8,t)}bytes(t){const n=t.length>>>0;return n===0?this._push(Sa,1,0):this.uint32(n)._push(zS,n,t)}string(t){const n=_S(t);return n!==0?this.uint32(n)._push($p,n,t):this._push(Sa,1,0)}fork(){return this.states=new US(this),this.head=this.tail=new wo(va,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 wo(va,0,0),this.len=0),this}ldelim(){const t=this.head,n=this.tail,r=this.len;return this.reset().uint32(r),r!==0&&(this.tail.next=t.next,this.tail=n,this.len+=r),this}finish(){let t=this.head.next;const n=$S(this.len);let r=0;for(;t!=null;)t.fn(t.val,n,r),r+=t.len,t=t.next;return n}}function Sa(e,t,n){t[n]=e&255}function qS(e,t,n){for(;e>127;)t[n++]=e&127|128,e>>>=7;t[n]=e}class KS extends wo{next;constructor(t,n){super(qS,t,n),this.next=void 0}}function ds(e,t,n){for(;e.hi!==0;)t[n++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=e.lo&127|128,e.lo=e.lo>>>7;t[n++]=e.lo}function eo(e,t,n){t[n]=e&255,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function zS(e,t,n){t.set(e,n)}globalThis.Buffer!=null&&(Oc.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(WS,t,e),this},Oc.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(GS,t,e),this});function WS(e,t,n){t.set(e,n)}function GS(e,t,n){e.length<40?$p(e,t,n):t.utf8Write!=null?t.utf8Write(e,n):t.set(Ue(e),n)}function VS(){return new Oc}function $i(e,t){const n=VS();return t.encode(e,n,{lengthDelimited:!1}),n.finish()}var ri;(function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(ri||(ri={}));function qp(e,t,n,r){return{name:e,type:t,encode:n,decode:r}}function YS(e){function t(o){if(e[o.toString()]==null)throw new Error("Invalid enum value");return e[o]}const n=function(s,i){const a=t(s);i.int32(a)},r=function(s){const i=s.int32();return t(i)};return qp("enum",ri.VARINT,n,r)}function qi(e,t){return qp("message",ri.LENGTH_DELIMITED,e,t)}class ku extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var Be;(function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(Be||(Be={}));var Fc;(function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(Fc||(Fc={}));(function(e){e.codec=()=>YS(Fc)})(Be||(Be={}));var Kn;(function(e){let t;e.codec=()=>(t==null&&(t=qi((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),Be.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{s.Type=Be.codec().decode(n);break}case 2:{s.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return s})),t),e.encode=n=>$i(n,e.codec()),e.decode=(n,r)=>Hi(n,e.codec(),r)})(Kn||(Kn={}));var oi;(function(e){let t;e.codec=()=>(t==null&&(t=qi((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),Be.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{s.Type=Be.codec().decode(n);break}case 2:{s.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return s})),t),e.encode=n=>$i(n,e.codec()),e.decode=(n,r)=>Hi(n,e.codec(),r)})(oi||(oi={}));const Kp=gp;class zp{type="RSA";jwk;_raw;_multihash;constructor(t,n){this.jwk=t,this._multihash=n}get raw(){return this._raw==null&&(this._raw=Gp(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Le.createV1(114,this._multihash)}toString(){return it.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Lt(this.raw,t.raw)}verify(t,n,r){return d0(this.jwk,n,t,r)}}class XS{type="RSA";jwk;_raw;publicKey;constructor(t,n){this.jwk=t,this.publicKey=n}get raw(){return this._raw==null&&(this._raw=t0(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Lt(this.raw,t.raw)}sign(t,n){return l0(this.jwk,t,n)}}const ZS=8192,Wp=18,JS=1062,QS=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function e0(e){return{n:le(e[1],"base64url"),e:le(e[2],"base64url"),d:le(e[3],"base64url"),p:le(e[4],"base64url"),q:le(e[5],"base64url"),dp:le(e[6],"base64url"),dq:le(e[7],"base64url"),qi:le(e[8],"base64url"),kty:"RSA"}}function t0(e){if(e.n==null||e.e==null||e.d==null||e.p==null||e.q==null||e.dp==null||e.dq==null||e.qi==null)throw new Nt("JWK was missing components");return nn([bt(Uint8Array.from([0])),bt(Ue(e.n,"base64url")),bt(Ue(e.e,"base64url")),bt(Ue(e.d,"base64url")),bt(Ue(e.p,"base64url")),bt(Ue(e.q,"base64url")),bt(Ue(e.dp,"base64url")),bt(Ue(e.dq,"base64url")),bt(Ue(e.qi,"base64url"))]).subarray()}function n0(e){const t=Kr(e[1],{offset:0});return{kty:"RSA",n:le(t[0],"base64url"),e:le(t[1],"base64url")}}function Gp(e){if(e.n==null||e.e==null)throw new Nt("JWK was missing components");return nn([QS,ql(nn([bt(Ue(e.n,"base64url")),bt(Ue(e.e,"base64url"))]))]).subarray()}function r0(e){const t=Kr(e);return o0(t)}function o0(e){const t=e0(e);return a0(t)}function s0(e,t){if(e.byteLength>=JS)throw new Wh("Key size is too large");const n=Kr(e,{offset:0});return i0(n,e,t)}function i0(e,t,n){const r=n0(e);if(n==null){const o=Kp(Kn.encode({Type:Be.RSA,Data:t}));n=Vo(Wp,o)}return new zp(r,n)}function a0(e){if(u0(e)>ZS)throw new Nt("Key size is too large");const t=c0(e),n=Kp(Kn.encode({Type:Be.RSA,Data:Gp(t.publicKey)})),r=Vo(Wp,n);return new XS(t.privateKey,new zp(t.publicKey,r))}function c0(e){if(e==null)throw new Nt("Missing key parameter");return{privateKey:e,publicKey:{kty:e.kty,n:e.n,e:e.e}}}async function l0(e,t,n){const r=await an.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);n?.signal?.throwIfAborted();const o=await an.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function d0(e,t,n,r){const o=await an.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const s=await an.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,n instanceof Uint8Array?n:n.subarray());return r?.signal?.throwIfAborted(),s}function u0(e){if(e.kty!=="RSA")throw new Nt("invalid key type");if(e.n==null)throw new Nt("invalid key modulus");return Ue(e.n,"base64url").length*8}class Vp extends up{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,lp(t);const r=Kl(n);if(this.iHash=t.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(r.length>o?t.create().update(r).digest():r);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),Dr(s)}update(t){return Zs(this),this.iHash.update(t),this}digestInto(t){Zs(this),Yn(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Yp=(e,t,n)=>new Vp(e,t).update(n).digest();Yp.create=(e,t)=>new Vp(e,t);const Tu=(e,t)=>(e+(e>=0?t:-t)/Xp)/t;function f0(e,t,n){const[[r,o],[s,i]]=t,a=Tu(i*e,n),c=Tu(-o*e,n);let l=e-a*r-c*s,d=-a*o-c*i;const u=l<Qt,f=d<Qt;u&&(l=-l),f&&(d=-d);const p=Jo(Math.ceil(yp(n)/2))+xr;if(l<Qt||l>=p||d<Qt||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:u,k1:l,k2neg:f,k2:d}}function Mc(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Ea(e,t){const n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return qn(n.lowS,"lowS"),qn(n.prehash,"prehash"),n.format!==void 0&&Mc(n.format),n}class h0 extends Error{constructor(t=""){super(t)}}const Zt={Err:h0,_tlv:{encode:(e,t)=>{const{Err:n}=Zt;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length&1)throw new n("tlv.encode: unpadded data");const r=t.length/2,o=cs(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?cs(o.length/2|128):"";return cs(e)+s+o+t},decode(e,t){const{Err:n}=Zt;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const o=t[r++],s=!!(o&128);let i=0;if(!s)i=o;else{const c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const l=t.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(r+=c,i<128)throw new n("tlv.decode(long): not minimal encoding")}const a=t.subarray(r,r+i);if(a.length!==i)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+i)}}},_int:{encode(e){const{Err:t}=Zt;if(e<Qt)throw new t("integer: negative integers are not allowed");let n=cs(e);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=Zt;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return ji(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Zt,o=Fe("signature",e),{v:s,l:i}=r.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:l,l:d}=r.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(e){const{_tlv:t,_int:n}=Zt,r=t.encode(2,n.encode(e.r)),o=t.encode(2,n.encode(e.s)),s=r+o;return t.encode(48,s)}},Qt=BigInt(0),xr=BigInt(1),Xp=BigInt(2),us=BigInt(3),p0=BigInt(4);function mr(e,t){const{BYTES:n}=e;let r;if(typeof t=="bigint")r=t;else{let o=Fe("private key",t);try{r=e.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function g0(e,t={}){const n=Dp("weierstrass",e,t),{Fp:r,Fn:o}=n;let s=n.CURVE;const{h:i,n:a}=s;Qo(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Jp(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(B,k,N){const{x:L,y:D}=k.toAffine(),F=r.toBytes(L);if(qn(N,"isCompressed"),N){d();const O=!r.isOdd(D);return Ht(Zp(O),F)}else return Ht(Uint8Array.of(4),F,r.toBytes(D))}function f(B){Tt(B,void 0,"Point");const{publicKey:k,publicKeyUncompressed:N}=l,L=B.length,D=B[0],F=B.subarray(1);if(L===k&&(D===2||D===3)){const O=r.fromBytes(F);if(!r.isValid(O))throw new Error("bad point: is not on curve, wrong x");const _=m(O);let H;try{H=r.sqrt(_)}catch(K){const G=K instanceof Error?": "+K.message:"";throw new Error("bad point: is not on curve, sqrt error"+G)}d();const q=r.isOdd(H);return(D&1)===1!==q&&(H=r.neg(H)),{x:O,y:H}}else if(L===N&&D===4){const O=r.BYTES,_=r.fromBytes(F.subarray(0,O)),H=r.fromBytes(F.subarray(O,O*2));if(!b(_,H))throw new Error("bad point: is not on curve");return{x:_,y:H}}else throw new Error(`bad point: got length ${L}, expected compressed=${k} or uncompressed=${N}`)}const p=t.toBytes||u,g=t.fromBytes||f;function m(B){const k=r.sqr(B),N=r.mul(k,B);return r.add(r.add(N,r.mul(B,s.a)),s.b)}function b(B,k){const N=r.sqr(k),L=m(B);return r.eql(N,L)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const y=r.mul(r.pow(s.a,us),p0),x=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(y,x)))throw new Error("bad curve params: a or b");function w(B,k,N=!1){if(!r.isValid(k)||N&&r.is0(k))throw new Error(`bad point coordinate ${B}`);return k}function I(B){if(!(B instanceof v))throw new Error("ProjectivePoint expected")}function R(B){if(!c||!c.basises)throw new Error("no endo");return f0(B,c.basises,o.ORDER)}const S=Qs((B,k)=>{const{X:N,Y:L,Z:D}=B;if(r.eql(D,r.ONE))return{x:N,y:L};const F=B.is0();k==null&&(k=F?r.ONE:r.inv(D));const O=r.mul(N,k),_=r.mul(L,k),H=r.mul(D,k);if(F)return{x:r.ZERO,y:r.ZERO};if(!r.eql(H,r.ONE))throw new Error("invZ was invalid");return{x:O,y:_}}),A=Qs(B=>{if(B.is0()){if(t.allowInfinityPoint&&!r.is0(B.Y))return;throw new Error("bad point: ZERO")}const{x:k,y:N}=B.toAffine();if(!r.isValid(k)||!r.isValid(N))throw new Error("bad point: x or y not field elements");if(!b(k,N))throw new Error("bad point: equation left != right");if(!B.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function T(B,k,N,L,D){return N=new v(r.mul(N.X,B),N.Y,N.Z),k=ei(L,k),N=ei(D,N),k.add(N)}class v{constructor(k,N,L){this.X=w("x",k),this.Y=w("y",N,!0),this.Z=w("z",L),Object.freeze(this)}static CURVE(){return s}static fromAffine(k){const{x:N,y:L}=k||{};if(!k||!r.isValid(N)||!r.isValid(L))throw new Error("invalid affine point");if(k instanceof v)throw new Error("projective point not allowed");return r.is0(N)&&r.is0(L)?v.ZERO:new v(N,L,r.ONE)}static fromBytes(k){const N=v.fromAffine(g(Tt(k,void 0,"point")));return N.assertValidity(),N}static fromHex(k){return v.fromBytes(Fe("pointHex",k))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(k=8,N=!0){return C.createCache(this,k),N||this.multiply(us),this}assertValidity(){A(this)}hasEvenY(){const{y:k}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(k)}equals(k){I(k);const{X:N,Y:L,Z:D}=this,{X:F,Y:O,Z:_}=k,H=r.eql(r.mul(N,_),r.mul(F,D)),q=r.eql(r.mul(L,_),r.mul(O,D));return H&&q}negate(){return new v(this.X,r.neg(this.Y),this.Z)}double(){const{a:k,b:N}=s,L=r.mul(N,us),{X:D,Y:F,Z:O}=this;let _=r.ZERO,H=r.ZERO,q=r.ZERO,j=r.mul(D,D),K=r.mul(F,F),G=r.mul(O,O),W=r.mul(D,F);return W=r.add(W,W),q=r.mul(D,O),q=r.add(q,q),_=r.mul(k,q),H=r.mul(L,G),H=r.add(_,H),_=r.sub(K,H),H=r.add(K,H),H=r.mul(_,H),_=r.mul(W,_),q=r.mul(L,q),G=r.mul(k,G),W=r.sub(j,G),W=r.mul(k,W),W=r.add(W,q),q=r.add(j,j),j=r.add(q,j),j=r.add(j,G),j=r.mul(j,W),H=r.add(H,j),G=r.mul(F,O),G=r.add(G,G),j=r.mul(G,W),_=r.sub(_,j),q=r.mul(G,K),q=r.add(q,q),q=r.add(q,q),new v(_,H,q)}add(k){I(k);const{X:N,Y:L,Z:D}=this,{X:F,Y:O,Z:_}=k;let H=r.ZERO,q=r.ZERO,j=r.ZERO;const K=s.a,G=r.mul(s.b,us);let W=r.mul(N,F),Y=r.mul(L,O),M=r.mul(D,_),$=r.add(N,L),X=r.add(F,O);$=r.mul($,X),X=r.add(W,Y),$=r.sub($,X),X=r.add(N,D);let Q=r.add(F,_);return X=r.mul(X,Q),Q=r.add(W,M),X=r.sub(X,Q),Q=r.add(L,D),H=r.add(O,_),Q=r.mul(Q,H),H=r.add(Y,M),Q=r.sub(Q,H),j=r.mul(K,X),H=r.mul(G,M),j=r.add(H,j),H=r.sub(Y,j),j=r.add(Y,j),q=r.mul(H,j),Y=r.add(W,W),Y=r.add(Y,W),M=r.mul(K,M),X=r.mul(G,X),Y=r.add(Y,M),M=r.sub(W,M),M=r.mul(K,M),X=r.add(X,M),W=r.mul(Y,X),q=r.add(q,W),W=r.mul(Q,X),H=r.mul($,H),H=r.sub(H,W),W=r.mul($,Y),j=r.mul(Q,j),j=r.add(j,W),new v(H,q,j)}subtract(k){return this.add(k.negate())}is0(){return this.equals(v.ZERO)}multiply(k){const{endo:N}=t;if(!o.isValidNot0(k))throw new Error("invalid scalar: out of range");let L,D;const F=O=>C.cached(this,O,_=>Ln(v,_));if(N){const{k1neg:O,k1:_,k2neg:H,k2:q}=R(k),{p:j,f:K}=F(_),{p:G,f:W}=F(q);D=K.add(W),L=T(N.beta,j,G,O,H)}else{const{p:O,f:_}=F(k);L=O,D=_}return Ln(v,[L,D])[0]}multiplyUnsafe(k){const{endo:N}=t,L=this;if(!o.isValid(k))throw new Error("invalid scalar: out of range");if(k===Qt||L.is0())return v.ZERO;if(k===xr)return L;if(C.hasCache(this))return this.multiply(k);if(N){const{k1neg:D,k1:F,k2neg:O,k2:_}=R(k),{p1:H,p2:q}=Xv(v,L,F,_);return T(N.beta,H,q,D,O)}else return C.unsafe(L,k)}multiplyAndAddUnsafe(k,N,L){const D=this.multiplyUnsafe(N).add(k.multiplyUnsafe(L));return D.is0()?void 0:D}toAffine(k){return S(this,k)}isTorsionFree(){const{isTorsionFree:k}=t;return i===xr?!0:k?k(v,this):C.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:k}=t;return i===xr?this:k?k(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(k=!0){return qn(k,"isCompressed"),this.assertValidity(),p(v,this,k)}toHex(k=!0){return On(this.toBytes(k))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(k=!0){return this.toBytes(k)}_setWindowSize(k){this.precompute(k)}static normalizeZ(k){return Ln(v,k)}static msm(k,N){return Bp(v,o,k,N)}static fromPrivateKey(k){return v.BASE.multiply(mr(o,k))}}v.BASE=new v(s.Gx,s.Gy,r.ONE),v.ZERO=new v(r.ZERO,r.ONE,r.ZERO),v.Fp=r,v.Fn=o;const E=o.BITS,C=new Lp(v,t.endo?Math.ceil(E/2):E);return v.BASE.precompute(8),v}function Zp(e){return Uint8Array.of(e?2:3)}function Jp(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function m0(e,t={}){const{Fn:n}=e,r=t.randomBytes||zl,o=Object.assign(Jp(e.Fp,n),{seed:Tp(n.ORDER)});function s(p){try{return!!mr(n,p)}catch{return!1}}function i(p,g){const{publicKey:m,publicKeyUncompressed:b}=o;try{const y=p.length;return g===!0&&y!==m||g===!1&&y!==b?!1:!!e.fromBytes(p)}catch{return!1}}function a(p=r(o.seed)){return Gv(Tt(p,o.seed,"seed"),n.ORDER)}function c(p,g=!0){return e.BASE.multiply(mr(n,p)).toBytes(g)}function l(p){const g=a(p);return{secretKey:g,publicKey:c(g)}}function d(p){if(typeof p=="bigint")return!1;if(p instanceof e)return!0;const{secretKey:g,publicKey:m,publicKeyUncompressed:b}=o;if(n.allowedLengths||g===m)return;const y=Fe("key",p).length;return y===m||y===b}function u(p,g,m=!0){if(d(p)===!0)throw new Error("first arg must be private key");if(d(g)===!1)throw new Error("second arg must be public key");const b=mr(n,p);return e.fromHex(g).multiply(b).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:e,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:p=>mr(n,p),precompute(p=8,g=e.BASE){return g.precompute(p,!1)}},lengths:o})}function w0(e,t,n={}){lp(t),Qo(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||zl,o=n.hmac||((N,...L)=>Yp(t,N,Ht(...L))),{Fp:s,Fn:i}=e,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:p}=m0(e,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function b(N){const L=a>>xr;return N>L}function y(N,L){if(!i.isValidNot0(L))throw new Error(`invalid signature ${N}: out of range 1..Point.Fn.ORDER`);return L}function x(N,L){Mc(L);const D=p.signature,F=L==="compact"?D:L==="recovered"?D+1:void 0;return Tt(N,F,`${L} signature`)}class w{constructor(L,D,F){this.r=y("r",L),this.s=y("s",D),F!=null&&(this.recovery=F),Object.freeze(this)}static fromBytes(L,D=m){x(L,D);let F;if(D==="der"){const{r:q,s:j}=Zt.toSig(Tt(L));return new w(q,j)}D==="recovered"&&(F=L[0],D="compact",L=L.subarray(1));const O=i.BYTES,_=L.subarray(0,O),H=L.subarray(O,O*2);return new w(i.fromBytes(_),i.fromBytes(H),F)}static fromHex(L,D){return this.fromBytes(Js(L),D)}addRecoveryBit(L){return new w(this.r,this.s,L)}recoverPublicKey(L){const D=s.ORDER,{r:F,s:O,recovery:_}=this;if(_==null||![0,1,2,3].includes(_))throw new Error("recovery id invalid");if(a*Xp<D&&_>1)throw new Error("recovery id is ambiguous for h>1 curve");const q=_===2||_===3?F+a:F;if(!s.isValid(q))throw new Error("recovery id 2 or 3 invalid");const j=s.toBytes(q),K=e.fromBytes(Ht(Zp((_&1)===0),j)),G=i.inv(q),W=R(Fe("msgHash",L)),Y=i.create(-W*G),M=i.create(O*G),$=e.BASE.multiplyUnsafe(Y).add(K.multiplyUnsafe(M));if($.is0())throw new Error("point at infinify");return $.assertValidity(),$}hasHighS(){return b(this.s)}toBytes(L=m){if(Mc(L),L==="der")return Js(Zt.hexFromSig(this));const D=i.toBytes(this.r),F=i.toBytes(this.s);if(L==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Ht(Uint8Array.of(this.recovery),D,F)}return Ht(D,F)}toHex(L){return On(this.toBytes(L))}assertValidity(){}static fromCompact(L){return w.fromBytes(Fe("sig",L),"compact")}static fromDER(L){return w.fromBytes(Fe("sig",L),"der")}normalizeS(){return this.hasHighS()?new w(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return On(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return On(this.toBytes("compact"))}}const I=n.bits2int||function(L){if(L.length>8192)throw new Error("input is too large");const D=ji(L),F=L.length*8-c;return F>0?D>>BigInt(F):D},R=n.bits2int_modN||function(L){return i.create(I(L))},S=Jo(c);function A(N){return Bc("num < 2^"+c,N,Qt,S),i.toBytes(N)}function T(N,L){return Tt(N,void 0,"message"),L?Tt(t(N),void 0,"prehashed message"):N}function v(N,L,D){if(["recovered","canonical"].some(Y=>Y in D))throw new Error("sign() legacy options not supported");const{lowS:F,prehash:O,extraEntropy:_}=Ea(D,g);N=T(N,O);const H=R(N),q=mr(i,L),j=[A(q),A(H)];if(_!=null&&_!==!1){const Y=_===!0?r(p.secretKey):_;j.push(Fe("extraEntropy",Y))}const K=Ht(...j),G=H;function W(Y){const M=I(Y);if(!i.isValidNot0(M))return;const $=i.inv(M),X=e.BASE.multiply(M).toAffine(),Q=i.create(X.x);if(Q===Qt)return;const oe=i.create($*i.create(G+Q*q));if(oe===Qt)return;let de=(X.x===Q?0:2)|Number(X.y&xr),z=oe;return F&&b(oe)&&(z=i.neg(oe),de^=1),new w(Q,z,de)}return{seed:K,k2sig:W}}function E(N,L,D={}){N=Fe("message",N);const{seed:F,k2sig:O}=v(N,L,D);return Fv(t.outputLen,i.BYTES,o)(F,O)}function C(N){let L;const D=typeof N=="string"||Zo(N),F=!D&&N!==null&&typeof N=="object"&&typeof N.r=="bigint"&&typeof N.s=="bigint";if(!D&&!F)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(F)L=new w(N.r,N.s);else if(D){try{L=w.fromBytes(Fe("sig",N),"der")}catch(O){if(!(O instanceof Zt.Err))throw O}if(!L)try{L=w.fromBytes(Fe("sig",N),"compact")}catch{return!1}}return L||!1}function B(N,L,D,F={}){const{lowS:O,prehash:_,format:H}=Ea(F,g);if(D=Fe("publicKey",D),L=T(Fe("message",L),_),"strict"in F)throw new Error("options.strict was renamed to lowS");const q=H===void 0?C(N):w.fromBytes(Fe("sig",N),H);if(q===!1)return!1;try{const j=e.fromBytes(D);if(O&&q.hasHighS())return!1;const{r:K,s:G}=q,W=R(L),Y=i.inv(G),M=i.create(W*Y),$=i.create(K*Y),X=e.BASE.multiplyUnsafe(M).add(j.multiplyUnsafe($));return X.is0()?!1:i.create(X.x)===K}catch{return!1}}function k(N,L,D={}){const{prehash:F}=Ea(D,g);return L=T(L,F),w.fromBytes(N,"recovered").recoverPublicKey(L).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:p,Point:e,sign:E,verify:B,recoverPublicKey:k,Signature:w,hash:t})}function y0(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp;let r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0;const o=Xn(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),s={Fp:n,Fn:o,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:s}}function b0(e){const{CURVE:t,curveOpts:n}=y0(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function v0(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Rp(n.Fn.ORDER,n.Fn.BITS))})}function S0(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:o}=b0(e),s=g0(t,n),i=w0(s,r,o);return v0(e,i)}function E0(e,t){const n=r=>S0({...e,hash:r});return{...n(t),create:n}}const nd={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},x0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Pu=BigInt(2);function I0(e){const t=nd.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,d=l*l*e%t,u=Oe(d,n,t)*d%t,f=Oe(u,n,t)*d%t,p=Oe(f,Pu,t)*l%t,g=Oe(p,o,t)*p%t,m=Oe(g,s,t)*g%t,b=Oe(m,a,t)*m%t,y=Oe(b,c,t)*b%t,x=Oe(y,a,t)*m%t,w=Oe(x,n,t)*d%t,I=Oe(w,i,t)*g%t,R=Oe(I,r,t)*l%t,S=Oe(R,Pu,t);if(!jc.eql(jc.sqr(S),e))throw new Error("Cannot find square root");return S}const jc=Xn(nd.p,{sqrt:I0}),In=E0({...nd,Fp:jc,lowS:!0,endo:x0},gp);function A0(e,t,n){const r=$l.digest(t instanceof Uint8Array?t:t.subarray());if(Ui(r))return r.then(({digest:o})=>(n?.signal?.throwIfAborted(),In.sign(o,e).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new Au(String(o))});try{return In.sign(r.digest,e).toDERRawBytes()}catch(o){throw new Au(String(o))}}function C0(e,t,n,r){const o=$l.digest(n instanceof Uint8Array?n:n.subarray());if(Ui(o))return o.then(({digest:s})=>(r?.signal?.throwIfAborted(),In.verify(t,s,e))).catch(s=>{throw s.name==="AbortError"?s:new Cu(String(s))});try{return r?.signal?.throwIfAborted(),In.verify(t,o.digest,e)}catch(s){throw new Cu(String(s))}}class Qp{type="secp256k1";raw;_key;constructor(t){this._key=N0(t),this.raw=T0(this._key)}toMultihash(){return Yo.digest(Ki(this))}toCID(){return Le.createV1(114,this.toMultihash())}toString(){return it.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Lt(this.raw,t.raw)}verify(t,n,r){return C0(this._key,n,t,r)}}class R0{type="secp256k1";raw;publicKey;constructor(t,n){this.raw=P0(t),this.publicKey=new Qp(n??L0(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Lt(this.raw,t.raw)}sign(t,n){return A0(this.raw,t,n)}}function k0(e){return new R0(e)}function eg(e){return new Qp(e)}function T0(e){return In.ProjectivePoint.fromHex(e).toRawBytes(!0)}function P0(e){try{return In.getPublicKey(e,!0),e}catch(t){throw new Gh(String(t))}}function N0(e){try{return In.ProjectivePoint.fromHex(e),e}catch(t){throw new Wh(String(t))}}function L0(e){try{return In.getPublicKey(e,!0)}catch(t){throw new Gh(String(t))}}async function B0(e,t){return ES()}function Uc(e,t){const{Type:n,Data:r}=Kn.decode(e),o=r??new Uint8Array;switch(n){case Be.RSA:return s0(o,t);case Be.Ed25519:return Mp(o);case Be.secp256k1:return eg(o);case Be.ECDSA:return ap(o);default:throw new _i}}function D0(e){const{Type:t,Data:n}=Kn.decode(e.digest),r=n??new Uint8Array;switch(t){case Be.Ed25519:return Mp(r);case Be.secp256k1:return eg(r);case Be.ECDSA:return ap(r);default:throw new _i}}function Ki(e){return Kn.encode({Type:Be[e.type],Data:e.raw})}function _0(e){const t=oi.decode(e),n=t.Data??new Uint8Array;switch(t.Type){case Be.RSA:return r0(n);case Be.Ed25519:return SS(n);case Be.secp256k1:return k0(n);case Be.ECDSA:return uv(n);default:throw new _i}}function O0(e){return oi.encode({Type:Be[e.type],Data:e.raw})}const tg=Symbol.for("nodejs.util.inspect.custom"),F0=114;class rd{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Vh]=!0;toString(){return this.string==null&&(this.string=it.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Le.createV1(F0,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Lt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Lt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[tg](){return`PeerId(${this.toString()})`}}class ng extends rd{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}}class rg extends rd{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}}class og extends rd{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}}const M0=2336;class sg{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Yo.digest(Ue(this.url))}[tg](){return`PeerId(${this.url})`}[Vh]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Le.createV1(M0,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=le(t)),t.toString()===this.toString())}}const j0=114,Nu=2336;function U0(e,t){let n;if(e.charAt(0)==="1"||e.charAt(0)==="Q")n=Zh(it.decode(`z${e}`));else{if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return H0(Le.parse(e));throw new Nt('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return ig(n)}function Or(e){if(e.type==="Ed25519")return new rg({multihash:e.toCID().multihash,publicKey:e});if(e.type==="secp256k1")return new og({multihash:e.toCID().multihash,publicKey:e});if(e.type==="RSA")return new ng({multihash:e.toCID().multihash,publicKey:e});throw new _i}function ig(e){if(q0(e))return new ng({multihash:e});if($0(e))try{const t=D0(e);if(t.type==="Ed25519")return new rg({multihash:e,publicKey:t});if(t.type==="secp256k1")return new og({multihash:e,publicKey:t})}catch{const n=le(e.digest);return new sg(new URL(n))}throw new xy("Supplied PeerID Multihash is invalid")}function H0(e){if(e?.multihash==null||e.version==null||e.version===1&&e.code!==j0&&e.code!==Nu)throw new Ey("Supplied PeerID CID is invalid");if(e.code===Nu){const t=le(e.multihash.digest);return new sg(new URL(t))}return ig(e.multihash)}function $0(e){return e.code===Yo.code}function q0(e){return e.code===$l.code}class ag extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}}class K0 extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}}class to extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}}class Lu extends Error{static name="StreamBufferError";constructor(t="The stream buffer was full"){super(t),this.name="StreamBufferError"}}class z0 extends Event{data;constructor(t,n){super("message",n),this.data=t}}class od extends Event{error;local;constructor(t,n,r){super("close",r),this.error=n,this.local=t}}class W0 extends od{constructor(t,n){super(!0,t,n)}}class G0 extends od{constructor(t,n){super(!1,t,n)}}const V0=e=>e/2**32|0,Y0=e=>e>>>0;function X0(e,t,n,r){const o=V0(n),s=Y0(n);e.setUint32(t,r?s:o,r),e.setUint32(t+4,r?o:s,r)}function Hc(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}const $c=e=>e?`"${e}" `:"";function cn(e,t=""){if(typeof e!="number")throw new TypeError($c(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError($c(t)+"expected integer >= 0, got "+e);return e}function ln(e,t,n=""){if(Hc(e)&&(t===void 0||e.length===t))return e;t!==void 0&&cn(t,"length");const r=Hc(e),o=t!==void 0?` of length ${t}`:"",s=r?`length=${e.length}`:`type=${typeof e}`,i=$c(n)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}function sd(e){if(typeof e!="function"||typeof e.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(cn(e.outputLen),cn(e.blockLen),e.outputLen<1||e.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}const Z0=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Bu=(e,t)=>{Z0(e,t);const n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function si(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function cg(e,t){ln(e,void 0,"output");const n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function D2(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Mn(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function xa(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Mt(e,t){return e<<32-t|e>>>t}function _2(e,t){return e<<t|e>>>32-t>>>0}const J0=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Q0(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function eE(e){for(let t=0;t<e.length;t++)e[t]=Q0(e[t]);return e}const O2=J0?e=>e:eE,lg=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",tE=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function id(e){if(ln(e),lg)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=tE[e[n]];return t}function Du(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function dg(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(lg)try{return Uint8Array.fromHex(e)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}const t=e.length,n=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){const i=Du(e.charCodeAt(s)),a=Du(e.charCodeAt(s+1));if(i===void 0||a===void 0){const c=e[s]+e[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a}return r}function nE(e){const t=globalThis;if(typeof t.scheduler?.yield=="function"){const n=t.scheduler.yield();return e&&n.catch(e),n}return new Promise(n=>t.setTimeout(n,0))}async function F2(e,t,n,r){if(cn(e,"iters"),cn(t,"tick"),typeof n!="function")throw new TypeError("callback must be a function");let o=Date.now();for(let s=0;s<e;s++){n(s);const i=Date.now()-o;i>=0&&i<t||(await nE(r),o=Date.now())}}function rE(e){if(typeof e!="string")throw new TypeError("string expected");const t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{Mn(t)}}function M2(e,t=""){return typeof e=="string"?rE(e):ln(e,void 0,t)}function oE(e,t,n="opts"){return Bu(e,"defaults"),t!==void 0&&Bu(t,n),Object.assign(Object.create(null),e,t)}function sE(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=oE({},t,"info");const n=(o,s)=>e(s).update(o).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>e(o),Object.assign(n,t),Object.freeze(n)}function iE(e=32){cn(e,"bytesLength");const t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}const aE=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function cE(e,t,n){return e&t^~e&n}function lE(e,t,n){return e&t^e&n^t&n}class dE{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,n,r,o){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(t),this.view=xa(this.buffer)}update(t){si(this),ln(t);const{view:n,buffer:r,blockLen:o}=this,s=t.length;let i=!1;for(let a=0;a<s;){const c=Math.min(o-this.pos,s-a);if(c===o){const l=xa(t);for(;o<=s-a;a+=o)this.process(l,a);i=!0;continue}r.set(a===0&&c===s?t:t.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(n,0),this.pos=0,i=!0)}return this.length+=t.length,i&&this.roundClean(),this}digestInto(t){si(this),cg(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:o,isLE:s}=this;let{pos:i}=this;n[i++]=128,n.fill(0,i),this.padOffset>o-i&&(this.process(r,0),n.fill(0)),X0(r,o-8,this.length*8,s),this.process(r,0),this.roundClean();const a=t===n?r:xa(t),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:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){const{buffer:n,length:r,finished:o,destroyed:s,pos:i}=this;return t.destroyed=s,t.finished=o,t.length=r,t.pos=i,i&&t.buffer.set(n),t}clone(){return this._cloneInto()}}const uE=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),fE=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]),gn=new Uint32Array(64);class hE extends dE{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(t,n){super(64,t,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){const{A:t,B:n,C:r,D:o,E:s,F:i,G:a,H:c}=this;return[t,n,r,o,s,i,a,c]}set(t,n,r,o,s,i,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let u=0;u<16;u++,n+=4)gn[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const f=gn[u-15],p=gn[u-2],g=Mt(f,7)^Mt(f,18)^f>>>3,m=Mt(p,17)^Mt(p,19)^p>>>10;gn[u]=m+gn[u-7]+g+gn[u-16]|0}let{A:r,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=Mt(a,6)^Mt(a,11)^Mt(a,25),p=d+f+cE(a,c,l)+fE[u]+gn[u]|0,m=(Mt(r,2)^Mt(r,13)^Mt(r,22))+lE(r,o,s)|0;d=l,l=c,c=a,a=i+p|0,i=s,s=o,o=r,r=p+m|0}r=r+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(r,o,s,i,a,c,l,d)}roundClean(){Mn(gn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Mn(this.buffer)}}class pE extends hE{constructor(){super(32,uE)}}const Ia=sE(()=>new pE,aE(1));function ug(e,t,n=()=>{}){if(!Array.isArray(e))throw new TypeError(`"${t}" expected array, got type=${typeof e}`);for(let r=0;r<e.length;r++)n(e[r],`${t}[${r}]`);return e}const Ir=(e,t,n)=>ln(e,t,n),fg=cn;function Ar(e,t="object"){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`);return e}function Ro(e,t){if(typeof e!="function")throw new TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}const gE=id,mE=e=>dg(e),hg=Hc,pg=e=>iE(e),ii=BigInt(0),_u=BigInt(1),wE=e=>e?`"${e}" `:"";function zi(e,t=""){if(typeof e!="boolean")throw new TypeError(wE(t)+"expected boolean, got type="+typeof e);return e}function yE(e){if(typeof e=="bigint"){if(!jn(e))throw new RangeError("positive bigint expected, got "+e)}else fg(e);return e}function qc(e,t=""){if(typeof e!="number"){const n=t&&`"${t}" `;throw new TypeError(n+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){const n=t&&`"${t}" `;throw new RangeError(n+"expected safe integer, got "+e)}}function gg(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?ii:BigInt("0x"+e)}function mg(e){return gg(id(e))}function ai(e){return gg(id(Mo(ln(e)).reverse()))}function wg(e,t){if(cn(t),t===0)throw new Error("zero output length is invalid");e=yE(e);const n=t*2,r=e.toString(16);if(r.length>n)throw new RangeError("number is too large");return dg(r.padStart(n,"0"))}function yg(e,t){return wg(e,t).reverse()}function Mo(e){return Uint8Array.from(Ir(e))}function jn(e){return typeof e=="bigint"&&ii<=e}function bg(e,t,n){return jn(e)&&jn(t)&&jn(n)&&t<=e&&e<n}function ko(e,t,n,r){if(!bg(t,n,r))throw new RangeError("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function bE(e){if(e<ii)throw new Error("expected non-negative bigint, got "+e);return e===ii?0:e.toString(2).length}const vE=e=>(qc(e,"n"),(_u<<BigInt(e))-_u);function ci(e,t={},n={},r="object"){Ar(e,r),Ar(t,"fields"),Ar(n,"optFields");function o(i,a,c){const l=r==="object"?`param "${String(i)}"`:`"${r}.${String(i)}"`,d=e[i];if(!Object.hasOwn(e,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(t,!1),s(n,!0)}const Ge=BigInt(0),Pe=BigInt(1),Bn=BigInt(2),vg=BigInt(3),ad=BigInt(4),Sg=BigInt(5),SE=BigInt(7),Eg=BigInt(8),EE=BigInt(9),xE=BigInt(15),xg=BigInt(16),IE=BigInt("0x10000000000000000");function Te(e,t){if(t<=Ge)throw new Error("mod: expected positive modulus, got "+t);const n=e%t;return n>=Ge?n:t+n}function AE(e,t,n){if(n<=Pe)throw new Error("pow: expected modulus > 1, got "+n);if(typeof t!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof t);if(t<Ge)throw new Error("invalid exponent, negatives unsupported");if(t===Ge)return Pe;if(t===Pe)return e;let r=e%n;if(r<Ge&&(r+=n),t<IE){let a=Pe;for(;t>Ge;)t&Pe&&(a=a*r%n),r=r*r%n,t>>=Pe;return a}const o=[];for(;t>Ge;)o.push(Number(t&xE)),t>>=ad;const s=new Array(16);s[0]=Pe,s[1]=r;for(let a=2;a<16;a++)s[a]=s[a-1]*r%n;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%n,i=i*i%n,i=i*i%n,i=i*i%n;const c=o[a];c!==0&&(i=i*s[c]%n)}return i}function kt(e,t,n){if(n<=Pe)throw new Error("pow2: expected modulus > 1, got "+n);if(t<Ge)throw new Error("pow2: expected non-negative exponent, got "+t);let r=e;for(;t-- >Ge;)r*=r,r%=n;return r}function Ou(e,t){if(e===Ge)throw new Error("invert: expected non-zero number");if(t<=Pe)throw new Error("invert: expected modulus > 1, got "+t);let n=Te(e,t),r=t,o=Ge,s=Pe;for(;n!==Ge;){const a=r/n,c=r-n*a,l=o-s*a;r=n,n=c,o=s,s=l}if(r!==Pe)throw new Error("invert: does not exist");return Te(o,t)}function cd(e,t,n){const r=e;if(!r.eql(r.sqr(t),n))throw new Error("Cannot find square root")}function ld(e,t){if((e&Pe)===Ge)throw new Error(t+": expected odd modulus, got "+e)}function Ig(e,t){const n=e,r=(n.ORDER+Pe)/ad,o=n.pow(t,r);return cd(n,o,t),o}function CE(e,t){const n=e,r=(n.ORDER-Sg)/Eg,o=n.mul(t,Bn),s=n.pow(o,r),i=n.mul(t,s),a=n.mul(n.mul(i,Bn),s),c=n.mul(i,n.sub(a,n.ONE));return cd(n,c,t),c}function RE(e){const t=dd(e),n=Ag(e),r=n(t,t.neg(t.ONE)),o=n(t,r),s=n(t,t.neg(r)),i=(e+SE)/xg;return((a,c)=>{const l=a;let d=l.pow(c,i),u=l.mul(d,r);const f=l.mul(d,o),p=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(p,f,m);const b=l.eql(l.sqr(u),c),y=l.cmov(d,u,b);return cd(l,y,c),y})}function Ag(e){if(e<vg)throw new Error("sqrt is not defined for small field");ld(e,"tonelliShanks");let t=e-Pe,n=0;for(;t%Bn===Ge;)t/=Bn,n++;let r=Bn;const o=dd(e);for(;li(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Ig;let s=o.pow(r,t);const i=(t+Pe)/Bn;return function(c,l){const d=c;if(d.is0(l))return l;if(li(d,l)!==1)throw new Error("Cannot find square root");let u=n,f=d.mul(d.ONE,s),p=d.pow(l,t),g=d.pow(l,i);for(;!d.eql(p,d.ONE);){if(d.is0(p))throw new Error("Cannot find square root: probably non-prime P");let m=1,b=d.sqr(p);for(;!d.eql(b,d.ONE);)if(m++,b=d.sqr(b),m===u)throw new Error("Cannot find square root");const y=Pe<<BigInt(u-m-1),x=d.pow(f,y);u=m,f=d.sqr(x),p=d.mul(p,f),g=d.mul(g,x)}return g}}function kE(e){return ld(e,"Fp.sqrt"),e%ad===vg?Ig:e%Eg===Sg?CE:e%xg===EE?RE(e):Ag(e)}const TE=(e,t)=>(Te(e,t)&Pe)===Pe,PE=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function jo(e){if(Ar(e,"field"),typeof e.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof e.ORDER);qc(e.BYTES,"BYTES"),qc(e.BITS,"BITS");for(const t of PE)Ro(e[t],"field."+t);if(e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=Pe)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Cg(e,t,n=!1){jo(e),ug(t,"nums"),zi(n,"passZero");const r=e,o=new Array(t.length).fill(n?r.ZERO:void 0),s=t.reduce((a,c,l)=>r.is0(c)?a:(o[l]=a,r.mul(a,c)),r.ONE),i=r.inv(s);return t.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),i),o}function li(e,t){jo(e);const n=e;ld(n.ORDER,"FpLegendre");const r=(n.ORDER-Pe)/Bn,o=n.pow(t,r),s=n.eql(o,n.ONE),i=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function NE(e,t){if(t!==void 0&&fg(t),e<=Ge)throw new Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);const n=bE(e);if(t!==void 0&&t<n)throw new Error(`invalid n length: expected nBitLength (${t}) >= bitLen(n) (${n})`);const r=t!==void 0?t:n,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}const Fu=new WeakMap;class Mu{ORDER;BITS;BYTES;isLE;ZERO=Ge;ONE=Pe;_lengths;_mod;constructor(t,n={}){if(t<=Pe)throw new Error("invalid field: expected ORDER > 1, got "+t);let r;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:!0}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));const{nBitLength:o,nByteLength:s}=NE(t,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(t){return Te(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return Ge<=t&&t<this.ORDER}is0(t){return t===Ge}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&Pe)===Pe}neg(t){return Te(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){return Te(t*t,this.ORDER)}add(t,n){return Te(t+n,this.ORDER)}sub(t,n){return Te(t-n,this.ORDER)}mul(t,n){return Te(t*n,this.ORDER)}pow(t,n){return AE(t,n,this.ORDER)}div(t,n){return Te(t*Ou(n,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,n){return t+n}subN(t,n){return t-n}mulN(t,n){return t*n}inv(t){return Ou(t,this.ORDER)}sqrt(t){let n=Fu.get(this);return n||Fu.set(this,n=kE(this.ORDER)),n(this,t)}toBytes(t){return this.isLE?yg(t,this.BYTES):wg(t,this.BYTES)}fromBytes(t,n=!1){Ir(t);const{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(r){if(t.length<1||!r.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+t.length);const l=new Uint8Array(o);l.set(t,s?0:l.length-t.length),t=l}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?ai(t):mg(t);if(a&&(c=Te(c,i)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Cg(this,t,!0)}cmov(t,n,r){return zi(r,"condition"),r?n:t}}function dd(e,t={}){return Object.freeze(Mu.prototype),new Mu(e,t)}const ud=BigInt(0),Uo=BigInt(1),LE=BigInt(4),Aa=16,ju=128,BE=5,Uu=2**31;function fd(e){const t=e;if(typeof t!="function")throw new TypeError('"Point" expected constructor, got type='+typeof e);Ro(t.fromAffine,"Point.fromAffine"),Ro(t.fromBytes,"Point.fromBytes"),Ro(t.fromHex,"Point.fromHex"),Ar(t.BASE,"Point.BASE"),Ar(t.ZERO,"Point.ZERO"),jo(t.Fp),jo(t.Fn)}function DE(e,t){fd(e),Rg(t,e);const n=Cg(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function _E(e,t,n=1){if(!Number.isSafeInteger(e)||e<n||e>t)throw new Error("invalid window size, expected ["+n+".."+t+"], got W="+e)}function OE(e,t){const n=e*(4*t+128);if(n>Uu)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+Uu/2**20+" MiB")}function FE(e,t){if(e!==void 0){Ro(e,"randomBytes");try{const n=e(t);if(!hg(n)||n.length!==t)return}catch{return}return e}}function Rg(e,t){ug(e,"points"),e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function ME(e,t,n){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,o)=>{if(!(n===void 0?t.isValid(r):jn(r)&&r<n))throw new Error("invalid scalar at index "+o)})}const kg=new WeakMap;function Ca(e){return kg.get(e)||1}function jE(e,t){const n=e.double(),r=[e];for(let o=1;o<t;o++)r.push(r[o-1].add(n));return r}function UE(e,t){const n=2**t,r=n/2,o=BigInt(n-1),s=[];for(;e>ud;){let i=0;e&Uo&&(i=Number(e&o),i>=r&&(i-=n),e-=BigInt(i)),s.push(i),e>>=Uo}return s}function HE(e,t,n){const r=2**t,o=r/2,s=BigInt(r-1),i=BigInt(t),a=[];for(let c=0;c<n;c++){let l=Number(e&s);e>>=i,l>o&&(l-=r,e+=Uo),a.push(l)}if(e!==ud)throw new Error("invalid wnaf");return a}function $E(e,t,n){let r=0;for(const s of n)r=Math.max(r,s.length);let o=e;for(let s=r-1;s>=0;s--){s!==r-1&&(o=o.double());for(let i=0;i<n.length;i++){const a=n[i][s];if(a){const c=t[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}class qE{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(t,n){fd(t),this.randomBytes=FE(n,Aa),this.Point=t,this.BASE=t.BASE,this.ZERO=t.ZERO,this.bits=t.Fn.BITS}buildWnafTable(t,n,r){const o=Math.ceil(r/n)+1,s=2**(n-1),i=[];let a=t;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:n,bits:r,windows:o,comp:i}}wnafCachedCT(t,n){const{W:r,windows:o,comp:s}=t,i=2**(r-1),a=HE(n,r,o);let c=this.ZERO,l=this.BASE;for(let d=0;d<o;d++){const u=a[d],f=d*i,p=Math.abs(u)-1;let g=s[f];for(let b=1;b<i;b++)g=b===p?s[f+b]: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(t,n,r,o){let s=this.wnafPrecomputes.get(n),i=s?.find(a=>a.W===t&&a.bits===r);return i||(i=this.buildWnafTable(n,t,r),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(n,s)),s.push(i)),i}assertPoint(t){if(!(t instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof t)}validateMulInput(t,n){if(this.assertPoint(t),!bg(n,Uo,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(t,n,r,o){const s=Ca(t);return s===1?this.fixedWindowCT(t,n,r):this.wnafCachedCT(this.getWnafPrecomputes(s,t,r,o),n)}mulCT(t,n,r){return this.validateMulInput(t,n),this.runCT(t,n,this.bits,r)}mulCTBlinded(t,n,r){if(this.validateMulInput(t,n),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");const o=this.Point.Fn.BITS+ju,s=this.randomBytes(Aa);if(!hg(s)||s.length!==Aa)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;const i=n+mg(s)*this.Point.Fn.ORDER;return this.runCT(t,i,o,r)}fixedWindowCT(t,n,r){const o=BE,s=1<<o,i=vE(o),a=new Array(s);a[0]=this.ZERO;for(let d=1;d<s;d++)a[d]=a[d-1].add(t);const c=Math.ceil(r/o);let l=this.ZERO;for(let d=c-1;d>=0;d--){if(d!==c-1)for(let p=0;p<o;p++)l=l.double();const u=Number(n>>BigInt(d*o)&i);let f=a[0];for(let p=1;p<s;p++)f=p===u?a[p]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(t,n){return this.randomBytes===void 0?!1:n===Uo?!0:t!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(t,n,r,o){return this.shouldBlind(t,r)?this.mulCTBlinded(t,n,o):this.mulCT(t,n,o)}mulUnsafe(t,n,r){if(this.assertPoint(t),!jn(n))throw new Error("invalid scalar");const o=Ca(t);if(o===1||n>=this.Point.Fn.ORDER)return KE(this.Point,[t],[n],!0);const s=this.getWnafPrecomputes(o,t,this.bits,r);return this.wnafCachedCT(s,n).p}setWindowSize(t,n){this.assertPoint(t),_E(n,this.bits);const r=Math.ceil((this.bits+ju)/n)+1;OE(r*2**(n-1),this.Point.Fp.BYTES),kg.set(t,n),this.wnafPrecomputes.delete(t)}hasWindowSize(t){return Ca(t)!==1}}function KE(e,t,n,r=!1){if(fd(e),Rg(t,e),zi(r,"allowOversized"),ME(n,e.Fn,r?e.Fn.ORDER**LE:void 0),t.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const o=t.map(i=>jE(i,4)),s=n.map(i=>UE(i,4));return $E(e.ZERO,o,s)}function Hu(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return jo(t),t}else return dd(e,{isLE:n})}function zE(e,t,n={},r){if(r===void 0&&(r=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);ci(n);for(const c of["p","n","h"]){const l=t[c];if(!(jn(l)&&l!==ud))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Hu(t.p,n.Fp,r),s=Hu(t.n,n.Fn,r),a=["Gx","Gy","a","d"];for(const c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function WE(e,t){return function(r){const o=e(r);return{secretKey:o,publicKey:t(o)}}}const fs=BigInt(0),hs=BigInt(1),ps=BigInt(2),GE=BigInt(4),$u=BigInt(8);function VE(e,t,n,r){const o=e.sqr(n),s=e.sqr(r),i=e.add(e.mul(t.a,o),s),a=e.add(e.ONE,e.mul(t.d,e.mul(o,s)));return e.eql(i,a)}function YE(e,t={}){ci(t,{},{},"extraOpts");const n=t,r=zE("edwards",e,n,n.FpFnLE),{Fp:o,Fn:s}=r;let i=r.CURVE;const{h:a}=i;if(li(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(li(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");ci(n,{},{uvRatio:"function",randomBytes:"function"});const c=n.randomBytes===void 0?pg:n.randomBytes,l=ps<<BigInt(o.BYTES*8)-hs;function d(x){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(x)}const u=n.uvRatio===void 0?(x,w)=>{try{return{isValid:!0,value:o.sqrt(o.div(x,w))}}catch{return{isValid:!1,value:fs}}}:n.uvRatio;if(!VE(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");const f=o.eql(i.a,o.neg(o.ONE))?x=>o.neg(x):o.eql(i.a,o.ONE)?x=>x:x=>o.mul(i.a,x);function p(x,w,I=!1){const R=I?hs:fs;return ko("coordinate "+x,w,R,l),w}function g(x){if(!(x 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(w,I,R,S){this.X=p("x",w),this.Y=p("y",I),this.Z=p("z",R,!0),this.T=p("t",S),Object.freeze(this)}static CURVE(){return i}static fromAffine(w){if(w instanceof m)throw new Error("extended point not allowed");const{x:I,y:R}=w||{};return p("x",I),p("y",R),new m(I,R,o.ONE,o.mul(I,R))}static fromBytes(w,I=!1){const R=o.BYTES,{a:S,d:A}=i;w=Mo(Ir(w,R,"point")),zi(I,"zip215");const T=Mo(w),v=w[R-1];T[R-1]=v&-129;const E=ai(T),C=I?l:o.ORDER;ko("point.y",E,fs,C);const B=o.sqr(E),k=o.sub(B,o.ONE),N=o.sub(o.mulN(A,B),S);let{isValid:L,value:D}=u(k,N);if(!L)throw new Error("bad point: invalid y coordinate");const F=d(D),O=(v&128)!==0;if(!I&&o.is0(D)&&O)throw new Error("bad point: x=0 and x_0=1");return O!==F&&(D=o.neg(D)),m.fromAffine({x:D,y:E})}static fromHex(w,I=!1){return m.fromBytes(mE(w),I)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=6,I=!0){return y.setWindowSize(this,w),I||this.multiply(ps),this}assertValidity(){const w=this,{a:I,d:R}=i;if(w.is0())throw new Error("bad point: ZERO");const{X:S,Y:A,Z:T,T:v}=w,E=o.sqr(S),C=o.sqr(A),B=o.sqr(T),k=o.sqr(B),N=o.mul(E,I),L=o.mul(o.add(N,C),B),D=o.add(k,o.mul(R,o.mul(E,C)));if(!o.eql(L,D))throw new Error("bad point: equation left != right (1)");const F=o.mul(S,A),O=o.mul(T,v);if(!o.eql(F,O))throw new Error("bad point: equation left != right (2)")}equals(w){g(w);const{X:I,Y:R,Z:S}=this,{X:A,Y:T,Z:v}=w,E=o.mul(I,v),C=o.mul(A,S),B=o.mul(R,v),k=o.mul(T,S);return o.eql(E,C)&&o.eql(B,k)}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:w,Y:I,Z:R}=this,S=o.sqr(w),A=o.sqr(I),T=o.mul(o.sqr(R),ps),v=f(S),E=o.addN(w,I),C=o.sub(o.subN(o.sqr(E),S),A),B=o.addN(v,A),k=o.subN(B,T),N=o.subN(v,A),L=o.mul(C,k),D=o.mul(B,N),F=o.mul(C,N),O=o.mul(k,B);return new m(L,D,O,F)}add(w){g(w);const{d:I}=i,{X:R,Y:S,Z:A,T}=this,{X:v,Y:E,Z:C,T:B}=w,k=o.mul(R,v),N=o.mul(S,E),L=o.mul(o.mulN(T,I),B),D=o.mul(A,C),F=o.sub(o.subN(o.mulN(o.addN(R,S),o.addN(v,E)),k),N),O=o.subN(D,L),_=o.addN(D,L),H=o.sub(N,f(k)),q=o.mul(F,O),j=o.mul(_,H),K=o.mul(F,H),G=o.mul(O,_);return new m(q,j,G,K)}subtract(w){return g(w),this.add(w.negate())}multiply(w){if(!s.isValidNot0(w))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");const{p:I,f:R}=y.mulSecret(this,w,a,b);return b([I,R])[0]}multiplyUnsafe(w){if(!s.isValid(w))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return w===fs?m.ZERO:this.is0()||w===hs?this:y.mulUnsafe(this,w,b)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return y.mulUnsafe(this,i.n).is0()}toAffine(w){const I=this;let R=w;if(R!=null&&typeof R!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof R);const{X:S,Y:A,Z:T}=I,v=I.is0();R==null&&(R=v?o.create($u):o.inv(T));const E=o.mul(S,R),C=o.mul(A,R),B=o.mul(T,R);if(v)return{x:o.ZERO,y:o.ONE};if(!o.eql(B,o.ONE))throw new Error("invZ was invalid");return{x:E,y:C}}clearCofactor(){return a===hs?this:a===ps?this.double():a===GE?this.double().double():a===$u?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){const{x:w,y:I}=this.toAffine(),R=o.toBytes(I);return R[R.length-1]|=d(w)?128:0,R}toHex(){return gE(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const b=x=>DE(m,x),y=new qE(m,c);return y.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}const Rn=BigInt(0),xt=BigInt(1),gs=BigInt(2);function qu(e,t){return e+t-(t>>xt<<xt)}function XE(e){const t=BigInt(6)*e;return(n,r,o)=>{const s=r+o,a=((t+o-r)*n+r)%e;return{x_2:a,x_3:s-a}}}function ZE(e){return ci(e,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...e})}function JE(e){const t=ZE(e),{P:n,type:r,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=t,a=t.scalarMultBase,c=r==="x25519";if(!c&&r!=="x448")throw new Error("invalid type");const l=i===void 0?pg:i,d=c?255:448,u=XE(n),f=c?32:56,p=BigInt(c?9:5),g=BigInt(c?121665:39081),m=c?gs**BigInt(254):gs**BigInt(447),b=c?BigInt(8)*(gs**BigInt(251)-xt):BigInt(4)*(gs**BigInt(445)-xt),y=m+b+xt,x=D=>Te(D,n),w=I(p);function I(D){return yg(x(D),f)}function R(D){const F=Mo(Ir(D,f,"uCoordinate"));return c&&(F[31]&=127),x(ai(F))}function S(D){return ai(o(Mo(Ir(D,f,"scalar"))))}const A=new Set(c?[Rn,xt,n-xt,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[Rn,xt,n-xt]);function T(D,F){const O=R(F);if(A.has(O))throw new Error("invalid private or public key received");const _=B(O,S(D));if(_===Rn)throw new Error("invalid private or public key received");return I(_)}function v(D){if(a===void 0)return T(D,w);const F=S(D);ko("scalar",F,m,y);const O=x(a(F));if(O===Rn)throw new Error("invalid private or public key received");return I(O)}const E=v,C=T;function B(D,F){ko("u",D,Rn,n),ko("scalar",F,m,y);const O=F,_=D;let H=xt,q=Rn,j=D,K=xt;const G=O^O>>xt;for(let M=BigInt(d-1);M>=Rn;M--){const $=qu(n,G>>M);({x_2:H,x_3:j}=u($,H,j)),{x_2:q,x_3:K}=u($,q,K);const X=H+q,Q=x(X*X),oe=H-q,de=x(oe*oe),z=Q-de,J=j+K,se=j-K,Se=x(se*X),Re=x(J*oe),me=Se+Re,Ee=Se-Re;j=x(me*me),K=x(_*x(Ee*Ee)),H=x(Q*de),q=x(z*(Q+x(g*z)))}const W=qu(n,O);({x_2:H,x_3:j}=u(W,H,j)),{x_2:q,x_3:K}=u(W,q,K);const Y=s(q);return x(H*Y)}const k={secretKey:f,publicKey:f,seed:f},N=D=>(D=D===void 0?l(f):D,Ir(D,k.seed,"seed"),D),L={randomSecretKey:N};return Object.freeze(k),Object.freeze(L),Object.freeze({keygen:WE(N,E),getSharedSecret:C,getPublicKey:E,scalarMult:T,scalarMultBase:v,utils:L,GuBytes:w.slice(),lengths:k})}const Ku=BigInt(0),QE=BigInt(1),zu=BigInt(2),ex=BigInt(3),tx=BigInt(5),nx=BigInt(8),Wi=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),rx={p:Wi,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:nx,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Tg(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=Wi,a=e*e%s*e%s,c=kt(a,zu,s)*a%s,l=kt(c,QE,s)*e%s,d=kt(l,tx,s)*l%s,u=kt(d,t,s)*d%s,f=kt(u,n,s)*u%s,p=kt(f,r,s)*f%s,g=kt(p,o,s)*p%s,m=kt(g,o,s)*p%s,b=kt(m,t,s)*d%s;return{pow_p_5_8:kt(b,zu,s)*e%s,b2:a}}function ox(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Wu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function sx(e,t){const n=Wi,r=Te(t*t*t,n),o=Te(r*r*t,n),s=Tg(e*o).pow_p_5_8;let i=Te(e*r*s,n);const a=Te(t*i*i,n),c=i,l=Te(i*Wu,n),d=a===e,u=a===Te(-e,n),f=a===Te(-e*Wu,n);return d&&(i=c),(u||f)&&(i=l),TE(i,n)&&(i=Te(-i,n)),{isValid:d||u,value:i}}const Gu=YE(rx,{uvRatio:sx}),ms=(()=>{const e=Wi,t=n=>{const{pow_p_5_8:r,b2:o}=Tg(n);return Te(kt(r,ex,e)*o,e)};return JE({P:e,type:"x25519",powPminus2:t,adjustScalarBytes:ox,scalarMultBase:n=>{const r=Te(n,Gu.Fn.ORDER);if(r===Ku)return Ku;const o=Gu.BASE.multiply(r);return Te((o.Z+o.Y)*t(Te(o.Z-o.Y,e)),e)}})})();class Vu{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,n){if(sd(t),ln(n,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?t.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Mn(o)}update(t){return si(this),this.iHash.update(t),this}digestInto(t){si(this),cg(t,this),this.finished=!0;const n=t.subarray(0,this.outputLen);this.iHash.digestInto(n),this.oHash.update(n),this.oHash.digestInto(n),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});const{oHash:n,iHash:r,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.canXOF=c,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Pg=(()=>{const e=((t,n,r)=>new Vu(t,n).update(r).digest());return e.create=(t,n)=>new Vu(t,n),e})();function Yu(){const e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}class Xu{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){const t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}}class Ra{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Xu(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){const n=this.head;this.head=n.next=new Xu(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){const n=this.tail.next;this.tail.next=null,this.tail=n,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}}class ix extends Error{type;code;constructor(t,n){super(t??"The operation was aborted"),this.type="aborted",this.code=n??"ABORT_ERR"}}function ax(e={}){return cx(n=>{const r=n.shift();if(r==null)return{done:!0};if(r.error!=null)throw r.error;return{done:r.done===!0,value:r.value}},e)}function cx(e,t){t=t??{};let n=t.onEnd,r=new Ra,o,s,i,a=Yu();const c=async()=>{try{return r.isEmpty()?i?{done:!0}:await new Promise((b,y)=>{s=x=>{s=null,r.push(x);try{b(e(r))}catch(w){y(w)}return o}}):e(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Yu()})}},l=b=>s!=null?s(b):(r.push(b),o),d=b=>(r=new Ra,s!=null?s({error:b}):(r.push({error:b}),o)),u=b=>{if(i)return o;if(t?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:b})},f=b=>i?o:(i=!0,b!=null?d(b):l({done:!0})),p=()=>(r=new Ra,f(),{done:!0}),g=b=>(f(b),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:g,push:u,end:f,get readableLength(){return r.size},onEmpty:async b=>{const y=b?.signal;if(y?.throwIfAborted(),r.isEmpty())return;let x,w;y!=null&&(x=new Promise((I,R)=>{w=()=>{R(new ix)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,x])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},n==null)return o;const m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(b){return m.throw(b),n!=null&&(n(b),n=void 0),{done:!0}},return(){return m.return(),n!=null&&(n(),n=void 0),{done:!0}},push:u,end(b){return m.end(b),n!=null&&(n(b),n=void 0),o},get readableLength(){return m.readableLength},onEmpty:b=>m.onEmpty(b)},o}class hd extends Error{name="TimeoutError";constructor(t,n){super(t,n),Error.captureStackTrace?.(this,hd)}}const Zu=e=>e.reason??new DOMException("This operation was aborted.","AbortError");function lx(e,t){const{milliseconds:n,fallback:r,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=t;let a,c;const d=new Promise((u,f)=>{if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(i?.aborted){f(Zu(i));return}if(i&&(c=()=>{f(Zu(i))},i.addEventListener("abort",c,{once:!0})),e.then(u,f),n===Number.POSITIVE_INFINITY)return;const p=new hd;a=s.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){f(g)}return}typeof e.cancel=="function"&&e.cancel(),o===!1?u():o instanceof Error?f(o):(p.message=o??`Promise timed out after ${n} milliseconds`,f(p))},n)}).finally(()=>{d.clear(),c&&i&&i.removeEventListener("abort",c)});return d.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},d}const dx=e=>{const t=e.addEventListener||e.on||e.addListener,n=e.removeEventListener||e.off||e.removeListener;if(!t||!n)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:n.bind(e)}};function ux(e,t,n){let r;const o=new Promise((s,i)=>{if(n={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...n},!(n.count>=0&&(n.count===Number.POSITIVE_INFINITY||Number.isInteger(n.count))))throw new TypeError("The `count` option should be at least 0 or more");n.signal?.throwIfAborted();const a=[t].flat(),c=[],{addListener:l,removeListener:d}=dx(e),u=async(...p)=>{const g=n.multiArgs?p:p[0];if(n.filter)try{if(!await n.filter(g))return}catch(m){r(),i(m);return}c.push(g),n.count===c.length&&(r(),s(c))},f=(...p)=>{r(),i(n.rejectionMultiArgs?p:p[0])};r=()=>{for(const p of a)d(p,u);for(const p of n.rejectionEvents)a.includes(p)||d(p,f)};for(const p of a)l(p,u);for(const p of n.rejectionEvents)a.includes(p)||l(p,f);n.signal&&n.signal.addEventListener("abort",()=>{f(n.signal.reason)},{once:!0}),n.resolveImmediately&&s(c)});if(o.cancel=r,typeof n.timeout=="number"){const s=lx(o,{milliseconds:n.timeout});return s.cancel=()=>{r(),s.clear()},s}return o}function fx(e,t,n){typeof n=="function"&&(n={filter:n}),n={...n,count:1,resolveImmediately:!1};const r=ux(e,t,n),o=r.then(s=>s[0]);return o.cancel=r.cancel,o}class di extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class hx extends Error{static name="StreamClosedError";name="StreamClosedError"}function px(e){return e.reason}function Ng(e,t,n){if(t==null||e==null)return e;const r=px;if(t.aborted)return e.catch(()=>{}),Promise.reject(r(t));let o;return Promise.race([e,new Promise((s,i)=>{o=()=>{i(r(t))},t.addEventListener("abort",o)})]).finally(()=>{o!=null&&t.removeEventListener("abort",o)})}const gx=Math.pow(2,20)*4;class Lg extends Ry{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(t){super(),this.status="open",this.log=t.log,this.direction=t.direction??"outbound",this.inactivityTimeout=t.inactivityTimeout??12e4,this.maxReadBufferLength=t.maxReadBufferLength??gx,this.maxWriteBufferLength=t.maxWriteBufferLength,this.maxMessageSize=t.maxMessageSize,this.readBuffer=new ye,this.writeBuffer=new ye,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 n=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",n);const r=o=>{this.onDrainPromise?.reject(o.error??new hx)};this.addEventListener("close",r)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(t){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Ng(this.onDrainPromise.promise,t?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;const t=ax(),n=s=>{t.push(s.data)};this.addEventListener("message",n);const r=s=>{t.end(s.error)};this.addEventListener("close",r);const o=()=>{t.end()};this.addEventListener("remoteCloseWrite",o);try{yield*t}finally{this.removeEventListener("message",n),this.removeEventListener("close",r),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(t){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new to(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",t.byteLength),this.writeBuffer.append(t),this.processSendQueue()}abort(t){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",t),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(t)}catch(n){this.log("failed to send reset to remote - %e",n)}this.dispatchEvent(new W0(t))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new to("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 to("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new to(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.append(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new to(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.prepend(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(t){if(t.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(t),this.dispatchReadBuffer()}}addEventListener(...t){super.addEventListener.apply(this,t),t[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 t=new K0;this.dispatchEvent(new G0(t))}onTransportClosed(t){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"),t!=null?this.abort(t):(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 od))}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 t=!0;const n=this.writeBuffer.byteLength;let r=0;for(;this.writeBuffer.byteLength>0;){const o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){t=!1;break}const s=this.writeBuffer.sublist(0,o),i=new ye(s);this.writeBuffer.consume(s.byteLength);const a=this.sendData(s);if(t=a.canSendMore,r+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!t)break}return t||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",r,n,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),t}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 t=this.readBuffer.sublist();this.readBuffer.consume(t.byteLength),this.dispatchEvent(new z0(t))}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 Lu(`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 Lu(`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 mx=4194304;class Ju extends Error{static name="UnwrappedError";name="UnwrappedError"}class Bg extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class wx extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class yx extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function bx(e){return typeof e?.closeRead=="function"}function vx(e){return typeof e?.close=="function"}function ka(e){return bx(e)?e.remoteWriteStatus!=="writable"&&e.readBufferLength===0:vx(e)?e.status!=="open":!1}function Sx(e){return e?.addEventListener!=null&&e?.removeEventListener!=null&&e?.send!=null&&e?.push!=null&&e?.log!=null}function Ex(e,t){const n=t?.maxBufferSize??mx,r=new ye;let o,s=!1;if(!Sx(e))throw new ag("Argument should be a Stream or a Multiaddr");const i=d=>{if(r.append(d.data),r.byteLength>n){const u=r.byteLength;r.consume(r.byteLength),o?.reject(new Error(`Read buffer overflow - ${u} > ${n}`))}o?.resolve()};e.addEventListener("message",i);const a=d=>{d.error!=null?o?.reject(d.error):o?.resolve()};e.addEventListener("close",a);const c=()=>{o?.resolve()};e.addEventListener("remoteCloseWrite",c);const l={readBuffer:r,async read(d){if(s===!0)throw new Ju("Stream was unwrapped");if(ka(e)){if(d?.bytes==null)return null;if(r.byteLength<d.bytes)throw e.log.error("closed after reading %d/%d bytes",r.byteLength,d.bytes),new di(`Unexpected EOF - stream closed after reading ${r.byteLength}/${d.bytes} bytes`)}const u=d?.bytes??1;for(o=Promise.withResolvers();;){if(r.byteLength>=u){o.resolve();break}if(await Ng(o.promise,d?.signal),ka(e)){if(r.byteLength===0&&d?.bytes==null)return null;break}o=Promise.withResolvers()}const f=d?.bytes??r.byteLength;if(r.byteLength<f){if(ka(e))throw e.log.error("closed while reading %d/%d bytes",r.byteLength,f),new di(`Unexpected EOF - stream closed while reading ${r.byteLength}/${f} bytes`);return l.read(d)}const p=r.sublist(0,f);return r.consume(f),p},async write(d,u){if(s===!0)throw new Ju("Stream was unwrapped");e.send(d)||await fx(e,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,e.removeEventListener("message",i),e.removeEventListener("close",a),e.removeEventListener("remoteCloseWrite",c),r.byteLength>0&&(e.log("stream unwrapped with %d unread bytes",r.byteLength),e.push(r))),e}};return l}function Qu(e,t={}){const n=Ex(e,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=Zn(t.maxDataLength));const r=t?.lengthDecoder??Hp,o=t?.lengthEncoder??kS;return{async read(i){let a=-1;const c=new ye;for(;;){const d=await n.read({...i,bytes:1});if(d==null)break;c.append(d);try{a=r(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Bg("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new yx(`Message length length too long - ${c.byteLength} > ${t.maxLengthLength}`);if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new wx(`Message length too long - ${a} > ${t.maxDataLength}`);const l=await n.read({...i,bytes:a});if(l==null)throw e.log.error("tried to read %d bytes but the stream closed",a),new di(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw e.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new di(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await n.write(new ye(o(i.byteLength),i),a)},async writeV(i,a){const c=new ye(...i.flatMap(l=>[o(l.byteLength),l]));await n.write(c,a)},unwrap(){return n.unwrap()}}}const xx=1024*1024*4,Ix=1024*1024*4;class Ax{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(t={}){this.buffer=new ye,this.maxBufferSize=t.maxBufferSize??xx,this.maxDataLength=t.maxDataLength??Ix,this.lengthDecoder=t.lengthDecoder??Hp,this.encodingLength=t.encodingLength??Zn}*decode(t){if(this.buffer.append(t),this.buffer.byteLength>this.maxBufferSize)throw new ag(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let n;try{n=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(n<0||n>this.maxDataLength)throw new Bg("Invalid message length");const r=this.encodingLength(n),o=r+n;if(this.buffer.byteLength>=o){const s=this.buffer.sublist(r,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}}var Cx={};const Ho=65535,ef=Ho-16,es=!!Cx?.DUMP_SESSION_KEYS,tf=16;function Kc(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}const ui=e=>e?`"${e}" `:"";function zc(e,t=""){if(typeof e!="boolean")throw new TypeError(ui(t)+"expected boolean, got type="+typeof e);return e}function Cr(e,t=""){if(typeof e!="number")throw new TypeError(ui(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(ui(t)+"expected integer >= 0, got "+e);return e}function We(e,t,n=""){if(Kc(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Cr(t,"length");const r=Kc(e),o=t!==void 0?` of length ${t}`:"",s=r?`length=${e.length}`:`type=${typeof e}`,i=ui(n)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}const nf=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`)};function rf(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Rx(e,t){We(e,void 0,"output");const n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function en(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function En(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function kx(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}const Rr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Tx(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Px(e){for(let t=0;t<e.length;t++)e[t]=Tx(e[t]);return e}const Dn=Rr?e=>e:Px;function Nx(e,t){return!e.byteLength||!t.byteLength?!1:e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function Lx(e,t){if(Nx(e,t)&&e.byteOffset<t.byteOffset)throw new Error("complex overlap of input and output is not supported")}function Bx(e,t){return nf(e,"defaults"),nf(t,"opts"),Object.assign(e,t)}function Dx(e,t){if(e=We(e),t=We(t),e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function _x(e,t,n){const r=t,o=(()=>[]),s=(a,c)=>r(c,...o(a)).update(a).digest(),i=r(new Uint8Array(e),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>r(a,...c),s}const Ox=(e,t)=>{function n(r,...o){if(We(r,void 0,"key"),e.nonceLength!==void 0){const u=o[0];We(u,e.varSizeNonce?void 0:e.nonceLength,"nonce")}const s=e.tagLength,i=e.nonceLength!==void 0?1:0;if(!e.withAAD){for(let u=i;u<o.length;u++)if(Kc(o[u]))throw new Error("AAD not supported")}e.withAAD&&o[i]!==void 0&&We(o[i],void 0,"AAD");const a=t(r,...o),c=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");We(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,We(u,void 0,"data"),c(a.encrypt.length,f),a.encrypt(u,f)},decrypt(u,f){if(We(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(n,e),n};function Wc(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(We(t,e,"output"),n&&!fi(t))throw new Error("invalid output, must be aligned");return t}function Fx(e,t,n){Cr(e),Cr(t),zc(n);const r=new Uint8Array(16),o=kx(r);return o.setBigUint64(0,BigInt(t),n),o.setBigUint64(8,BigInt(e),n),r}function fi(e){return e.byteOffset%4===0}function hi(e){return Uint8Array.from(We(e))}const Dg=e=>Uint8Array.from(e.split(""),t=>t.charCodeAt(0)),Mx=Dn(en(Dg("expand 16-byte k"))),jx=Dn(en(Dg("expand 32-byte k")));function he(e,t){return e<<t|e>>>32-t}const no=64,Ux=16,Gc=2**32-1,of=Uint32Array.of();function Hx(e,t,n,r,o,s,i,a){const c=o.length,l=new Uint8Array(no),d=en(l),u=Rr&&fi(o)&&fi(s),f=u?en(o):of,p=u?en(s):of;if(!Rr){for(let g=0;g<c;i++){if(e(t,n,r,d,i,a),Dn(d),i>=Gc)throw new Error("arx: counter overflow");const m=Math.min(no,c-g);for(let b=0,y;b<m;b++)y=g+b,s[y]=o[y]^l[b];g+=m}return}for(let g=0;g<c;i++){if(e(t,n,r,d,i,a),i>=Gc)throw new Error("arx: counter overflow");const m=Math.min(no,c-g);if(u&&m===no){const b=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let y=0,x;y<Ux;y++)x=b+y,p[x]=f[x]^d[y];g+=no;continue}for(let b=0,y;b<m;b++)y=g+b,s[y]=o[y]^l[b];g+=m}}function $x(e,t){const{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:s,rounds:i}=Bx({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return Cr(o),Cr(i),zc(s),zc(n),(a,c,l,d,u=0)=>{We(a,void 0,"key"),We(c,void 0,"nonce"),We(l,void 0,"data");const f=l.length,p=d!==void 0;if(d=Wc(f,d,!1),p&&Lx(l,d),Cr(u),u<0||u>=Gc)throw new Error("arx: counter overflow");const g=[];let m=a.length,b,y;if(m===32)g.push(b=hi(a)),y=jx;else if(m===16&&n)b=new Uint8Array(32),b.set(a),b.set(a,16),y=Mx,g.push(b);else throw We(a,32,"arx key"),new Error("invalid key size");(!Rr||!fi(c))&&g.push(c=hi(c));let x=en(b);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");const R=c.subarray(0,16);if(Rr)r(y,x,en(R),x);else{const S=Dn(Uint32Array.from(y));r(S,x,en(R),x),En(S),Dn(x)}c=c.subarray(16)}else Rr||Dn(x);const w=16-o;if(w!==c.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(w!==12){const R=new Uint8Array(12);R.set(c,s?0:12-c.length),c=R,g.push(c)}const I=Dn(en(c));try{return Hx(e,y,x,I,l,d,u,i),d}finally{En(...g)}}}function Ye(e,t){return e[t++]&255|(e[t++]&255)<<8}class qx{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(t){t=hi(We(t,32,"key"));const n=Ye(t,0),r=Ye(t,2),o=Ye(t,4),s=Ye(t,6),i=Ye(t,8),a=Ye(t,10),c=Ye(t,12),l=Ye(t,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>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]=Ye(t,16+2*d)}process(t,n,r=!1){const o=r?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],p=i[6],g=i[7],m=i[8],b=i[9],y=Ye(t,n+0),x=Ye(t,n+2),w=Ye(t,n+4),I=Ye(t,n+6),R=Ye(t,n+8),S=Ye(t,n+10),A=Ye(t,n+12),T=Ye(t,n+14);let v=s[0]+(y&8191),E=s[1]+((y>>>13|x<<3)&8191),C=s[2]+((x>>>10|w<<6)&8191),B=s[3]+((w>>>7|I<<9)&8191),k=s[4]+((I>>>4|R<<12)&8191),N=s[5]+(R>>>1&8191),L=s[6]+((R>>>14|S<<2)&8191),D=s[7]+((S>>>11|A<<5)&8191),F=s[8]+((A>>>8|T<<8)&8191),O=s[9]+(T>>>5|o),_=0,H=_+v*a+E*(5*b)+C*(5*m)+B*(5*g)+k*(5*p);_=H>>>13,H&=8191,H+=N*(5*f)+L*(5*u)+D*(5*d)+F*(5*l)+O*(5*c),_+=H>>>13,H&=8191;let q=_+v*c+E*a+C*(5*b)+B*(5*m)+k*(5*g);_=q>>>13,q&=8191,q+=N*(5*p)+L*(5*f)+D*(5*u)+F*(5*d)+O*(5*l),_+=q>>>13,q&=8191;let j=_+v*l+E*c+C*a+B*(5*b)+k*(5*m);_=j>>>13,j&=8191,j+=N*(5*g)+L*(5*p)+D*(5*f)+F*(5*u)+O*(5*d),_+=j>>>13,j&=8191;let K=_+v*d+E*l+C*c+B*a+k*(5*b);_=K>>>13,K&=8191,K+=N*(5*m)+L*(5*g)+D*(5*p)+F*(5*f)+O*(5*u),_+=K>>>13,K&=8191;let G=_+v*u+E*d+C*l+B*c+k*a;_=G>>>13,G&=8191,G+=N*(5*b)+L*(5*m)+D*(5*g)+F*(5*p)+O*(5*f),_+=G>>>13,G&=8191;let W=_+v*f+E*u+C*d+B*l+k*c;_=W>>>13,W&=8191,W+=N*a+L*(5*b)+D*(5*m)+F*(5*g)+O*(5*p),_+=W>>>13,W&=8191;let Y=_+v*p+E*f+C*u+B*d+k*l;_=Y>>>13,Y&=8191,Y+=N*c+L*a+D*(5*b)+F*(5*m)+O*(5*g),_+=Y>>>13,Y&=8191;let M=_+v*g+E*p+C*f+B*u+k*d;_=M>>>13,M&=8191,M+=N*l+L*c+D*a+F*(5*b)+O*(5*m),_+=M>>>13,M&=8191;let $=_+v*m+E*g+C*p+B*f+k*u;_=$>>>13,$&=8191,$+=N*d+L*l+D*c+F*a+O*(5*b),_+=$>>>13,$&=8191;let X=_+v*b+E*m+C*g+B*p+k*f;_=X>>>13,X&=8191,X+=N*u+L*d+D*l+F*c+O*a,_+=X>>>13,X&=8191,_=(_<<2)+_|0,_=_+H|0,H=_&8191,_=_>>>13,q+=_,s[0]=H,s[1]=q,s[2]=j,s[3]=K,s[4]=G,s[5]=W,s[6]=Y,s[7]=M,s[8]=$,s[9]=X}finalize(){const{h:t,pad:n}=this,r=new Uint16Array(10);let o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,r[0]=t[0]+5,o=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=t[a]+o,o=r[a]>>>13,r[a]&=8191;r[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)r[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|r[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+n[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+n[a]|0)+(i>>>16)|0,t[a]=i&65535;En(r)}update(t){rf(this),We(t),t=hi(t);const{buffer:n,blockLen:r}=this,o=t.length;for(let s=0;s<o;){const i=Math.min(r-this.pos,o-s);if(i===r){for(;r<=o-s;s+=r)this.process(t,s);continue}n.set(t.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,En(this.h,this.r,this.buffer,this.pad)}digestInto(t){rf(this),Rx(t,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:o}=this;if(o){for(n[o++]=1;o<16;o++)n[o]=0;this.process(n,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)t[s++]=r[i]>>>0,t[s++]=r[i]>>>8}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}}const Kx=_x(32,e=>new qx(e));function zx(e,t,n,r,o,s=20){let i=e[0],a=e[1],c=e[2],l=e[3],d=t[0],u=t[1],f=t[2],p=t[3],g=t[4],m=t[5],b=t[6],y=t[7],x=o,w=n[0],I=n[1],R=n[2],S=i,A=a,T=c,v=l,E=d,C=u,B=f,k=p,N=g,L=m,D=b,F=y,O=x,_=w,H=I,q=R;for(let K=0;K<s;K+=2)S=S+E|0,O=he(O^S,16),N=N+O|0,E=he(E^N,12),S=S+E|0,O=he(O^S,8),N=N+O|0,E=he(E^N,7),A=A+C|0,_=he(_^A,16),L=L+_|0,C=he(C^L,12),A=A+C|0,_=he(_^A,8),L=L+_|0,C=he(C^L,7),T=T+B|0,H=he(H^T,16),D=D+H|0,B=he(B^D,12),T=T+B|0,H=he(H^T,8),D=D+H|0,B=he(B^D,7),v=v+k|0,q=he(q^v,16),F=F+q|0,k=he(k^F,12),v=v+k|0,q=he(q^v,8),F=F+q|0,k=he(k^F,7),S=S+C|0,q=he(q^S,16),D=D+q|0,C=he(C^D,12),S=S+C|0,q=he(q^S,8),D=D+q|0,C=he(C^D,7),A=A+B|0,O=he(O^A,16),F=F+O|0,B=he(B^F,12),A=A+B|0,O=he(O^A,8),F=F+O|0,B=he(B^F,7),T=T+k|0,_=he(_^T,16),N=N+_|0,k=he(k^N,12),T=T+k|0,_=he(_^T,8),N=N+_|0,k=he(k^N,7),v=v+E|0,H=he(H^v,16),L=L+H|0,E=he(E^L,12),v=v+E|0,H=he(H^v,8),L=L+H|0,E=he(E^L,7);let j=0;r[j++]=i+S|0,r[j++]=a+A|0,r[j++]=c+T|0,r[j++]=l+v|0,r[j++]=d+E|0,r[j++]=u+C|0,r[j++]=f+B|0,r[j++]=p+k|0,r[j++]=g+N|0,r[j++]=m+L|0,r[j++]=b+D|0,r[j++]=y+F|0,r[j++]=x+O|0,r[j++]=w+_|0,r[j++]=I+H|0,r[j++]=R+q|0}const Wx=$x(zx,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Gx=new Uint8Array(16),sf=(e,t)=>{e.update(t);const n=t.length%16;n&&e.update(Gx.subarray(n))},Vx=new Uint8Array(32);function af(e,t,n,r,o){o!==void 0&&We(o,void 0,"AAD");const s=e(t,n,Vx),i=Fx(r.length,o?o.length:0,!0),a=Kx.create(s);o&&sf(a,o),sf(a,r),a.update(i);const c=a.digest();return En(s,i),c}const Yx=e=>(t,n,r)=>({encrypt(s,i){const a=s.length;i=Wc(a+16,i,!1),i.set(s);const c=i.subarray(0,-16);e(t,n,c,c,1);const l=af(e,t,n,c,r);return i.set(l,a),En(l),i},decrypt(s,i){i=Wc(s.length-16,i,!1);const a=s.subarray(0,-16),c=s.subarray(-16),l=af(e,t,n,a,r);if(!Dx(c,l))throw En(l),new Error("invalid tag");return i.set(s.subarray(0,-16)),e(t,n,i,i,1),En(l),i}}),cf=Ox({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},Yx(Wx));function Xx(e,t,n){return sd(e),n===void 0&&(n=new Uint8Array(e.outputLen)),Pg(e,n,t)}const ro=Uint8Array.of(0),Zx=Uint8Array.of();function Jx(e,t,n,r=32,o){sd(e),cn(r,"length"),ln(t,void 0,"prk");const s=e.outputLen;if(t.length<s)throw new Error('"prk" must be at least HashLen octets');if(r>255*s)throw new Error("Length must be <= 255*HashLen");const i=Math.ceil(r/s);if(n===void 0?n=Zx:ln(n,void 0,"info"),!i)return new Uint8Array;const a=new Uint8Array(i*s),{iHash:c,oHash:l}=Pg.create(e,t),d=new Uint8Array(s),u=i>1?e.create():void 0;for(let p=0;p<i-1;p++){ro[0]=p+1;const g=c._cloneInto(u);p&&g.update(d),g.update(n).update(ro).digestInto(d),l._cloneInto(u).update(d).digestInto(d),a.set(d,s*p)}if(ro[0]=i,i>1&&c.update(d),c.update(n).update(ro).digestInto(d),l.update(d).digestInto(d),a.set(d,s*(i-1)),c.destroy(),l.destroy(),u?.destroy(),d!==a&&Mn(d),Mn(ro),r===a.length)return a;const f=a.slice(0,r);return Mn(a),f}const _g={hashSHA256(e){return Ia(e.subarray())},getHKDF(e,t){const n=Xx(Ia,t,e),o=Jx(Ia,n,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){const e=ms.utils.randomSecretKey();return{publicKey:ms.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed(e){return{publicKey:ms.getPublicKey(e),privateKey:e}},generateX25519SharedKey(e,t){return ms.getSharedSecret(e.subarray(),t.subarray())},chaCha20Poly1305Encrypt(e,t,n,r){return cf(r,t,n).encrypt(e.subarray())},chaCha20Poly1305Decrypt(e,t,n,r,o){return cf(r,t,n).decrypt(e.subarray(),o)}},Qx=_g;function e1(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,n)=>e.generateX25519SharedKey(t.privateKey,n).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}const pi=e=>{const t=sn(2);return t[0]=e>>8,t[1]=e,t};pi.bytes=2;const gi=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};gi.bytes=2;function t1(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Og(e,t){!t.enabled||!es||(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${le(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${le(e.privateKey,"hex")}`)):t("Missing local static keys."))}function Fg(e,t){!t.enabled||!es||(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${le(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${le(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function n1(e,t){!t.enabled||!es||t(e?`REMOTE_STATIC_PUBLIC_KEY ${le(e.subarray(),"hex")}`:"Missing remote static public key.")}function Mg(e,t){!t.enabled||!es||t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${le(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function jg(e,t,n){!n.enabled||!es||(n(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&le(e.k,"hex")}`),n(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&le(t.k,"hex")}`))}class To extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=To.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}const r1=0,o1=4294967295,s1="Cipherstate has reached maximum n, a new handshake must be performed";class i1{n;bytes;view;constructor(t=r1){this.n=t,this.bytes=ft(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>o1)throw new Error(s1)}}const kr=ft(0);class ws{k;n;crypto;constructor(t,n=void 0,r=0){this.crypto=t,this.k=n,this.n=new i1(r)}hasKey(){return!!this.k}encryptWithAd(t,n){if(!this.hasKey())return n;this.n.assertValue();const r=this.crypto.encrypt(n,this.n.getBytes(),t,this.k);return this.n.increment(),r}decryptWithAd(t,n,r){if(!this.hasKey())return n;this.n.assertValue();const o=this.crypto.decrypt(n,this.n.getBytes(),t,this.k,r);return this.n.increment(),o}}class a1{cs;ck;h;crypto;constructor(t,n){this.crypto=t;const r=Ue(n,"utf-8");this.h=l1(t,r),this.ck=this.h,this.cs=new ws(t)}mixKey(t){const[n,r]=this.crypto.hkdf(this.ck,t);this.ck=n,this.cs=new ws(this.crypto,r)}mixHash(t){this.h=this.crypto.hash(new ye(this.h,t))}encryptAndHash(t){const n=this.cs.encryptWithAd(this.h,t);return this.mixHash(n),n}decryptAndHash(t){const n=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),n}split(){const[t,n]=this.crypto.hkdf(this.ck,kr);return[new ws(this.crypto,t),new ws(this.crypto,n)]}}class c1{ss;s;e;rs;re;initiator;crypto;constructor(t){const{crypto:n,protocolName:r,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=t;this.crypto=n,this.ss=new a1(n,r),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 t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.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(t,n=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<n+32)throw new Error("message is not long enough");this.re=t.sublist(n,n+32),this.ss.mixHash(this.re)}readS(t,n=0){if(this.rs)throw new Error("remote static public key is already set");const r=32+(this.ss.cs.hasKey()?16:0);if(t.byteLength<n+r)throw new Error("message is not long enough");const o=t.sublist(n,n+r);return this.rs=this.ss.decryptAndHash(o),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class Ug extends c1{writeMessageA(t){return new ye(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){const n=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new ye(n,r,this.ss.encryptAndHash(t))}writeMessageC(t){const n=this.writeS();return this.writeSE(),new ye(n,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(n){throw new To(`handshake stage 0 validation fail: ${n.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();const n=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+n))}catch(n){throw new To(`handshake stage 1 validation fail: ${n.message}`)}}readMessageC(t){try{const n=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(n))}catch(n){throw new To(`handshake stage 2 validation fail: ${n.message}`)}}}function l1(e,t){if(t.length<=32){const n=ft(32);return n.set(t),n}else return e.hash(t)}var mi;(function(e){let t;e.codec=()=>(t==null&&(t=qi((n,r,o={})=>{if(o.lengthDelimited!==!1&&r.fork(),n.webtransportCerthashes!=null)for(const s of n.webtransportCerthashes)r.uint32(10),r.bytes(s);if(n.streamMuxers!=null)for(const s of n.streamMuxers)r.uint32(18),r.string(s);o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={webtransportCerthashes:[],streamMuxers:[]},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new ku('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(n.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new ku('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(n.string());break}default:{n.skipType(a&7);break}}}return s})),t),e.encode=n=>$i(n,e.codec()),e.decode=(n,r)=>Hi(n,e.codec(),r)})(mi||(mi={}));var wi;(function(e){let t;e.codec=()=>(t==null&&(t=qi((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.identityKey!=null&&n.identityKey.byteLength>0&&(r.uint32(10),r.bytes(n.identityKey)),n.identitySig!=null&&n.identitySig.byteLength>0&&(r.uint32(18),r.bytes(n.identitySig)),n.extensions!=null&&(r.uint32(34),mi.codec().encode(n.extensions,r)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={identityKey:ft(0),identitySig:ft(0)},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{s.identityKey=n.bytes();break}case 2:{s.identitySig=n.bytes();break}case 4:{s.extensions=mi.codec().decode(n,n.uint32(),{limits:o.limits?.extensions});break}default:{n.skipType(a&7);break}}}return s})),t),e.encode=n=>$i(n,e.codec()),e.decode=(n,r)=>Hi(n,e.codec(),r)})(wi||(wi={}));async function Hg(e,t,n){const r=await e.sign(qg(t));return wi.encode({identityKey:Ki(e.publicKey),identitySig:r,extensions:n})}async function $g(e,t,n){try{const r=wi.decode(e),o=Uc(r.identityKey);if(n?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${n}`);if(!t)throw new Error("Remote static does not exist");const s=qg(t);if(!await o.verify(s,r.identitySig))throw new Error("Invalid payload signature");return r}catch(r){throw new vy(r.message)}}function qg(e){const t=Ue("noise-libp2p-static-key:");return e instanceof Uint8Array?Tc([t,e],t.length+e.length):(e.prepend(t),e)}class d1 extends Lg{stream;handshake;metrics;decoder;constructor(t,n,r){super({log:t.log,inactivityTimeout:t.inactivityTimeout,maxReadBufferLength:t.maxReadBufferLength,direction:t.direction}),this.stream=t,this.handshake=n,this.metrics=r,this.decoder=new Ax({lengthDecoder:gi,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(t){const n=new ye;for(let r=0;r<t.byteLength;r+=ef){let o=r+ef;o>t.byteLength&&(o=t.byteLength);let s;t instanceof Uint8Array?s=this.handshake.encrypt(t.subarray(r,o)):s=this.handshake.encrypt(t.sublist(r,o)),this.metrics?.encryptedPackets.increment(),n.append(pi(s.byteLength)),n.append(s)}return n}decrypt(t){const n=new ye;for(let r=0;r<t.byteLength;r+=Ho){let o=r+Ho;if(o>t.byteLength&&(o=t.byteLength),o-tf<r)throw new Error("Invalid chunk");let s;t instanceof Uint8Array?s=t.subarray(r,o):s=t.sublist(r,o);const i=t.subarray(r,o-tf);try{const a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),n.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return n}close(t){return this.stream.close(t)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(t){this.stream.abort(t)}sendData(t){return{sentBytes:t.byteLength,canSendMore:this.stream.send(this.encrypt(t))}}}function lf(e,t,n){return new d1(e,t,n)}async function u1(e,t){const{log:n,connection:r,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=e,d=await Hg(s,a.publicKey,l),u=new Ug({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Og(u.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(u.writeMessageA(kr),t),n.trace("Stage 0 - Initiator finished sending first message."),Fg(u.e,n),n.trace("Stage 1 - Initiator waiting to receive first message from responder...");const f=u.readMessageB(await r.read(t));n.trace("Stage 1 - Initiator received the message."),Mg(u.re,n),n1(u.rs,n),n.trace("Initiator going to check remote's signature...");const p=await $g(f,u.rs,c);n.trace("All good with the signature!"),n.trace("Stage 2 - Initiator sending third handshake message."),await r.write(u.writeMessageC(d),t),n.trace("Stage 2 - Initiator sent message with signed payload.");const[g,m]=u.ss.split();return jg(g,m,n),{payload:p,encrypt:b=>g.encryptWithAd(kr,b),decrypt:(b,y)=>m.decryptWithAd(kr,b,y)}}async function f1(e,t){const{log:n,connection:r,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=e,d=await Hg(s,a.publicKey,l),u=new Ug({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Og(u.s,n),n.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await r.read(t)),n.trace("Stage 0 - Responder received first message."),Mg(u.re,n),n.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await r.write(u.writeMessageB(d),t),n.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Fg(u.e,n),n.trace("Stage 2 - Responder waiting for third handshake message...");const f=u.readMessageC(await r.read(t));n.trace("Stage 2 - Responder received the message, finished handshake.");const p=await $g(f,u.rs,c),[g,m]=u.ss.split();return jg(g,m,n),{payload:p,encrypt:b=>m.encryptWithAd(kr,b),decrypt:(b,y)=>g.decryptWithAd(kr,b,y)}}class h1{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(t,n={}){const{staticNoiseKey:r,extensions:o,crypto:s,prologueBytes:i}=n,{metrics:a}=t;this.components=t,this.log=t.logger.forComponent("libp2p:noise");const c=s??Qx;this.crypto=e1(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?t1(a):void 0,r?this.staticKey=c.generateX25519KeyPairFromSeed(r):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??ft(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[ky]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,n){const r=t.log?.newScope("noise")??this.log,o=Qu(t,{lengthEncoder:pi,lengthDecoder:gi,maxDataLength:Ho}),s=await this.performHandshakeInitiator(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=Uc(s.payload.identityKey);return{connection:lf(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Or(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(t){if(t==null||t.length===0)return;const n=this.components.upgrader.getStreamMuxers();if(n!=null)for(const r of t){const o=n.get(r);if(o!=null)return o}if(t.length)throw new Sy("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(t,n){const r=t.log?.newScope("noise")??this.log,o=Qu(t,{lengthEncoder:pi,lengthDecoder:gi,maxDataLength:Ho}),s=await this.performHandshakeResponder(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=Uc(s.payload.identityKey);return{connection:lf(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Or(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(t,n,r,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await u1({connection:t,privateKey:n,remoteIdentityKey:o,log:r.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(t,n,r,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await f1({connection:t,privateKey:n,remoteIdentityKey:o,log:r.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 p1(e={}){return t=>new h1(t,e)}const g1="termdock-e2ee-v1",Vc=3600*1e3,df=512*1024*1024,Yc=4*1024*1024,Bs=()=>{},Gi=Object.assign(Bs,{enabled:!1,error:Bs,trace:Bs,newScope:()=>Gi});Object.freeze(Gi);async function Kg(){const e=await B0();return{privateKey:e,peerId:Or(e.publicKey).toString()}}function m1(e){return btoa(String.fromCharCode(...O0(e.privateKey)))}function uf(e){if(e.length>512||!/^[A-Za-z0-9+/]+={0,2}$/.test(e))throw new Error("Invalid identity encoding");const t=_0(Uint8Array.from(atob(e),n=>n.charCodeAt(0)));if(t.type!=="Ed25519")throw new Error("Only Ed25519 device identities are supported");return{privateKey:t,peerId:Or(t.publicKey).toString()}}class zg{constructor(t=Bs){this.consumed=t}consumed;chunks=[];size=0;ended=!1;error;wake;push(t){if(this.ended)throw this.error??new Error("Byte stream closed");if(this.size+t.byteLength>Yc)throw new Error("Secure stream buffer limit exceeded");this.chunks.push(t.slice()),this.size+=t.byteLength,this.wake?.()}end(t){this.ended=!0,this.error??=t,this.wake?.()}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const t=this.chunks.shift();if(t)this.size-=t.byteLength,yield t,this.consumed();else{if(this.ended)return;await new Promise(n=>{this.wake=n})}}}}class w1 extends Lg{constructor(t,n){super({log:Gi,direction:n?"outbound":"inbound",maxReadBufferLength:Yc,maxWriteBufferLength:Yc}),this.duplex=t,this.finished=t.sink(this.outgoing).catch(r=>{this.abort(Fr(r))}),this.readTransport()}duplex;outgoing=new zg(()=>this.onMuxerDrain());finished;async readTransport(){try{for await(const t of this.duplex.source)this.onData(t.slice());this.onTransportClosed()}catch(t){this.onTransportClosed(Fr(t))}}sendData(t){return this.outgoing.push(t.subarray()),{sentBytes:t.byteLength,canSendMore:!1}}sendReset(t){this.outgoing.end(t),this.duplex.close?.(t)}sendPause(){}sendResume(){}async close(){this.outgoing.end(),this.duplex.close?.(),this.onTransportClosed(),await this.finished}}function Fr(e){return e instanceof Error?e:new Error("Secure transport failed")}class y1 extends Error{code="E2EE_REHANDSHAKE_REQUIRED";constructor(){super("Encrypted connection lifetime reached; establish a new handshake without replaying pending input")}}function b1(e){const t=e?.maxAgeMs??Vc,n=e?.maxBytesPerDirection??df;if(!Number.isSafeInteger(t)||t<=0||t>Vc||!Number.isSafeInteger(n)||n<=0||n>df)throw new Error("Encrypted connection limits cannot exceed the production maximum");return{maxAgeMs:t,maxBytesPerDirection:n}}async function Wg(e){const{identity:t,duplex:n,initiator:r,targetPinnedPeerId:o,signal:s}=e,i=b1(e.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(r&&!o)throw new Error("A pinned target identity is required");const a=o?U0(o):void 0;if(a&&a.type!=="Ed25519")throw new Error("Only Ed25519 target identities are supported");if(t.peerId!==Or(t.privateKey.publicKey).toString())throw new Error("Local identity mismatch");if(s?.aborted)throw s.reason??new Error("Connection aborted");const c=new w1(n,r),l=new AbortController,d=setTimeout(()=>{const p=new Error("Encrypted handshake timed out");l.abort(p),c.abort(p)},15e3),u=()=>{l.abort(s?.reason),c.abort(Fr(s?.reason))};s?.addEventListener("abort",u,{once:!0}),c.addEventListener("close",()=>s?.removeEventListener("abort",u),{once:!0});const f=p1({crypto:_g,prologueBytes:new TextEncoder().encode(g1)})({privateKey:t.privateKey,peerId:Or(t.privateKey.publicKey),logger:{forComponent:()=>Gi},upgrader:{getStreamMuxers:()=>new Map}});try{const p=await(r?f.secureOutbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}):f.secureInbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}));if(p.remotePeer.type!=="Ed25519")throw new Error("Unsupported remote identity");return{authenticatedPeerId:p.remotePeer.toString(),duplex:v1(p.connection,i)}}catch(p){throw c.abort(Fr(p)),p}finally{clearTimeout(d),s?.removeEventListener("abort",u)}}function v1(e,t){const n=new zg,r=performance.now(),o=Date.now();let s=0,i=0,a;const c=()=>(a??=new y1,n.end(a),e.abort(a),a),l=setTimeout(c,t.maxAgeMs);typeof l=="object"&&l.unref?.();const d=(f,p)=>{if(a)throw a;if(Math.max(performance.now()-r,Date.now()-o)>=t.maxAgeMs||f+p>=t.maxBytesPerDirection)throw c()};e.addEventListener("message",f=>{try{d(i,f.data.byteLength),i+=f.data.byteLength,n.push(f.data.subarray())}catch(p){e.abort(Fr(p))}}),e.addEventListener("close",f=>{clearTimeout(l),n.end(f.error)},{once:!0});let u=!1;return{source:n,async sink(f){if(u)throw new Error("Secure sink already consumed");u=!0;try{for await(const p of f)d(s,p.byteLength),s+=p.byteLength,e.send(p)||await e.onDrain()}catch(p){throw e.abort(Fr(p)),p}},close(f){f?e.abort(f):e.close()}}}const Xc=1012,Zc="Encrypted transport renewed",Gg=2*1024*1024,S1=new TextEncoder,E1=new TextDecoder("utf-8",{fatal:!0});async function Vg(e,t){const r=new Blob([e]).stream().pipeThrough(t).getReader(),o=[];let s=0;try{for(;;){const{done:c,value:l}=await r.read();if(c)break;if(s+=l.byteLength,s>Gg)throw new Error("Expanded record exceeds budget");o.push(l)}}catch(c){throw await r.cancel(c).catch(()=>{}),c}finally{r.releaseLock()}const i=new Uint8Array(s);let a=0;for(const c of o)i.set(c,a),a+=c.byteLength;return i}async function x1(e,t){if(e.byteLength<4096||typeof CompressionStream>"u")return e;const n=await Vg(e.subarray(4),new CompressionStream("gzip"));let r="";for(let i=0;i<n.length;i+=8192)r+=String.fromCharCode(...n.subarray(i,i+8192));const o=S1.encode(JSON.stringify({type:"compressed",id:t,encoding:"gzip",data:btoa(r)}));if(o.byteLength+4>=e.byteLength*.9)return e;const s=new Uint8Array(o.byteLength+4);return new DataView(s.buffer).setUint32(0,o.byteLength),s.set(o,4),s}async function I1(e){if(typeof e!="string"||e.length>Math.ceil(Gg/3)*4)throw new Error("Invalid compressed record");const t=Uint8Array.from(atob(e),r=>r.charCodeAt(0)),n=await Vg(t,new DecompressionStream("gzip"));return JSON.parse(E1.decode(n))}const pd=64*1024,Yg=8;function A1(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1?Math.min(e,Yg):1}const C1=2147483648,R1=new TextEncoder,k1=new TextDecoder("utf-8",{fatal:!0});function T1(e){if(!(e.bytes instanceof Uint8Array))return;if(!["upload","chunk"].includes(e.type))throw new Error("Invalid binary record type");const t=R1.encode(e.id);if(!t.length||t.length>128||e.bytes.length>pd)throw new Error("Invalid binary record size");const n=new Uint8Array(2+t.length+e.bytes.length);return n[0]=e.type==="upload"?1:2,n[1]=t.length,n.set(t,2),n.set(e.bytes,2+t.length),n}function P1(e){const t=e[0],n=e[1];if(![1,2].includes(t)||!n||n>128||e.length<2+n||e.length-2-n>pd)throw new Error("Invalid binary record");return{type:t===1?"upload":"chunk",id:k1.decode(e.subarray(2,2+n)),bytes:e.slice(2+n)}}class gd{constructor(t=64){this.limit=t}limit;items=[];wake;ended=!1;error;tryPush(t){if(this.ended)throw new Error("Channel closed");return this.items.length>=this.limit?!1:(this.items.push(t),this.wake?.(),!0)}push(t){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(t),this.wake?.()}get size(){return this.items.length}end(t){this.ended=!0,this.error??=t,this.wake?.()}clear(){this.items.length=0}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const t=this.items.shift();if(t!==void 0){yield t;continue}if(this.ended)return;await new Promise(n=>{this.wake=n}),this.wake=void 0}}}class ys extends Error{code="PACKET_QUEUE_BACKPRESSURE";constructor(t="Record queue capacity exceeded"){super(t),this.name="PacketQueueBackpressureError"}}const Ds=2*1024*1024,N1=Ds*2+8,ff=64*1024,L1=new TextEncoder,B1=new TextDecoder("utf-8",{fatal:!0});class Xg{constructor(t){this.duplex=t;const n=this;this.done=t.sink((async function*(){for await(const r of n.outgoing)try{yield r.compress?await x1(r.bytes,r.id):r.bytes}finally{n.releaseQueuedPacket(r)}})()),this.done.then(()=>this.discardPending(),r=>this.discardPending(r instanceof Error?r:new Error("Transport failed")))}duplex;outgoing=new gd(256);outgoingBytes=0;queuedBytesById=new Map;writeWaiters=new Set;closed=!1;get hasPendingWrites(){return this.outgoingBytes>0}queuedBytesFor(t){return this.queuedBytesById.get(t)??0}done;send(t,n=!1){if(this.closed)throw new Error("Channel closed");if(this.outgoing.size>=256)throw new ys("Record queue item limit exceeded");const r=T1(t),o=r??L1.encode(JSON.stringify(t));if(o.length>Ds)throw new Error("Record too large");const s=new Uint8Array(o.length+4);if(new DataView(s.buffer).setUint32(0,r?o.length+C1:o.length),s.set(o,4),this.outgoingBytes+s.byteLength>4*1024*1024)throw new ys("Record queue byte budget exceeded");const i={id:t.id,bytes:s,compress:n};if(!this.outgoing.tryPush(i))throw new ys("Record queue item limit exceeded");this.outgoingBytes+=s.byteLength,this.queuedBytesById.set(t.id,this.queuedBytesFor(t.id)+s.byteLength)}async sendBulk(t,n,r){const o=Date.now();for(;;){if(n.aborted)throw n.reason??new Error("CANCELLED");if(this.closed)throw new Error("Channel closed");if(this.outgoingBytes<512*1024&&this.outgoing.size<128){r?.();try{this.send(t);return}catch(s){if(!(s instanceof ys))throw s}}if(Date.now()-o>=3e4)throw new Error("Encrypted transport congested");await new Promise((s,i)=>{const a=()=>{clearTimeout(d),n.removeEventListener("abort",c),this.writeWaiters.delete(l)},c=()=>{a(),i(n.reason??new Error("CANCELLED"))},l=()=>{a(),s()},d=setTimeout(()=>{a(),i(new Error("Encrypted transport congested"))},Math.max(1,3e4-(Date.now()-o)));this.writeWaiters.add(l),n.addEventListener("abort",c,{once:!0}),n.aborted&&c()})}}releaseQueuedPacket(t){this.outgoingBytes=Math.max(0,this.outgoingBytes-t.bytes.byteLength);for(const o of this.writeWaiters)o();const n=this.queuedBytesById.get(t.id);if(n===void 0)return;const r=n-t.bytes.byteLength;r>0?this.queuedBytesById.set(t.id,r):this.queuedBytesById.delete(t.id)}close(t){this.discardPending(t)}abort(t){this.discardPending(t)}discardPending(t){if(!this.closed){this.closed=!0,this.outgoing.clear(),this.outgoing.end(t),this.outgoingBytes=0,this.queuedBytesById.clear();for(const n of this.writeWaiters)n();this.duplex.close?.(t)}}async*read(){const t=[];let n=0,r=0,o;const s=d=>{if(d[0]&128)return P1(d.subarray(4));const u=JSON.parse(B1.decode(d.subarray(4)));if(!u||typeof u!="object"||typeof u.id!="string"||typeof u.type!="string")throw new Error("Invalid record");return u},i=d=>{let u=0;for(;u<d.byteLength;){let f=t[t.length-1];(!f||f.end===f.bytes.byteLength)&&(f={bytes:o??new Uint8Array(ff),start:0,end:0},o=void 0,t.push(f));const p=Math.min(d.byteLength-u,f.bytes.byteLength-f.end);f.bytes.set(d.subarray(u,u+p),f.end),f.end+=p,u+=p}r+=d.byteLength},a=d=>{let u=n,f=d;for(;u<t.length;){const p=t[u];if(!p){u++;continue}const g=p.end-p.start;if(f<g)return p.bytes[p.start+f];f-=g,u++}throw new Error("Incomplete record header")},c=d=>{for(r-=d;d>0;){const u=t[n];if(!u){n++;continue}const f=Math.min(d,u.end-u.start);u.start+=f,d-=f,u.start===u.end&&(!o&&u.bytes.byteLength===ff&&(o=u.bytes),t[n]=void 0,n++)}r===0?(t.length=0,n=0,o=void 0):n>=64&&n*2>=t.length&&(t.splice(0,n),n=0)},l=d=>{const u=t[n];if(!u)throw new Error("Incomplete record body");if(u.end-u.start>=d){const b=u.bytes.subarray(u.start,u.start+d);return c(d),b}const p=new Uint8Array(d);let g=n,m=0;for(;m<d;){const b=t[g];if(!b){g++;continue}const y=Math.min(d-m,b.end-b.start);p.set(b.bytes.subarray(b.start,b.start+y),m),m+=y,g++}return c(d),p};for await(const d of this.duplex.source){if(r+d.byteLength>N1)throw new Error("Record buffer exceeded");if(r===0&&d.byteLength>=5){const u=(d[0]&127)*16777216+(d[1]<<16)+(d[2]<<8)+d[3]>>>0;if(u>Ds||u===0)throw new Error("Invalid record size");if(d.byteLength===u+4){yield s(d);continue}}for(d.byteLength&&i(d);r>=4;){const u=(a(0)&127)*16777216+(a(1)<<16)+(a(2)<<8)+a(3)>>>0;if(u>Ds||u===0)throw new Error("Invalid record size");if(r<u+4)break;const f=l(u+4);yield s(f)}}if(r)throw new Error("Truncated record")}}function Zg(e){let t="";for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return btoa(t)}function Jg(e){const t=atob(e);return Uint8Array.from(t,n=>n.charCodeAt(0))}function D1(e){const t=new gd(64);e.binaryType="arraybuffer";const n=r=>{t.end(r),e.close(1e3)};return e.addEventListener("message",r=>{try{if(!(r.data instanceof ArrayBuffer)||r.data.byteLength>1024*1024)throw new Error("Invalid encrypted frame");t.push(new Uint8Array(r.data))}catch{n(new Error("Encrypted transport rejected frame"))}}),e.addEventListener("close",()=>t.end(e.transportFailure)),e.addEventListener("error",()=>t.end(e.transportFailure||new Error("Encrypted transport disconnected"))),{source:t,close:n,async sink(r){try{for await(const o of r)for(let s=0;s<o.length;s+=64*1024){const i=Date.now();for(;e.bufferedAmount>256*1024;){if(e.readyState!==1||Date.now()-i>15e3)throw new Error("Encrypted transport congested");await new Promise(a=>setTimeout(a,10))}if(e.readyState!==1)throw e.transportFailure||new Error("Encrypted transport closed");e.send(o.subarray(s,s+64*1024))}}catch(o){throw n(o instanceof Error?o:new Error("Encrypted transport failed")),o}}}}const hf="/api/federation/transport",_1=4e3,O1=4e3;function F1(e,t=Date.now()){if(!e||typeof e!="object")return;const n=e;if(!(n.version!==1||n.path!==hf||!Number.isSafeInteger(n.port)||n.port<1||n.port>65535||typeof n.certificateHash!="string"||!/^[a-f0-9]{64}$/.test(n.certificateHash)||!Number.isSafeInteger(n.expiresAt)||n.expiresAt<=t||n.expiresAt>t+14*864e5))return{version:1,path:hf,port:n.port,certificateHash:n.certificateHash,expiresAt:n.expiresAt}}async function pf(e,t,n){return new Promise((r,o)=>{const s=()=>{n(),o(t.reason??new Error("Transport aborted"))};t.addEventListener("abort",s,{once:!0}),e.then(i=>{t.removeEventListener("abort",s),r(i)},i=>{t.removeEventListener("abort",s),o(i)}),t.aborted&&s()})}function gf(e){const t=e.readable.getReader(),n=e.writable.getWriter();let r=!1,o=0;const s=i=>{r||(r=!0,t.cancel(i).catch(()=>{}),(i?n.abort(i):n.close()).catch(()=>{}))};return{close:s,bufferedBytes:()=>o,source:{async*[Symbol.asyncIterator](){try{for(;!r;){const{done:i,value:a}=await t.read();if(i)return;if(!(a instanceof Uint8Array))throw new Error("Invalid transport stream bytes");yield a}}finally{t.releaseLock()}}},async sink(i){try{for await(const a of i)for(let c=0;c<a.byteLength;c+=64*1024){if(r)throw new Error("Transport stream closed");const l=a.subarray(c,c+64*1024);o=l.byteLength;try{await n.write(l)}finally{o=0}}await n.close()}catch(a){throw s(a instanceof Error?a:new Error("Transport stream failed")),a}finally{n.releaseLock()}}}}function M1(){const e=globalThis.WebTransport;return e?(t,n)=>new e(t,n):void 0}async function j1(e){const t=new URL(e.baseUrl);if(!["wss:","https:"].includes(t.protocol))throw new Error("QUIC requires a secure service origin");t.protocol="https:",t.port=String(e.descriptor.port),t.pathname=e.descriptor.path,t.search="",t.hash="",t.hostname==="localhost"&&(t.hostname="127.0.0.1");const n=Uint8Array.from(e.descriptor.certificateHash.match(/../g),f=>parseInt(f,16)),r=performance.now(),o=e.factory(t.href,{serverCertificateHashes:[{algorithm:"sha-256",value:n.buffer}]});let s=!1,i=!1;const a=new Set,c=new AbortController,l=()=>{if(!i){i=!0,s=!1,c.abort(new Error("QUIC session closed")),e.signal?.removeEventListener("abort",l);for(const f of a)f.close?.(new Error("QUIC session closed"));o.close({closeCode:0,reason:"Secure session closed"})}};o.closed.then(l,l),e.signal?.addEventListener("abort",l,{once:!0});const d=AbortSignal.any([c.signal,AbortSignal.timeout(_1),...e.signal?[e.signal]:[]]);try{await pf(o.ready,d,l)}catch(f){throw l(),f}s=!0;const u=performance.now()-r;return{get available(){return s&&!i&&e.descriptor.expiresAt>Date.now()},closed:o.closed.then(()=>{},()=>{}),close:l,async open(f,p){if(!s||i)throw new Error("QUIC session unavailable");const g=AbortSignal.any([c.signal,AbortSignal.timeout(O1),...p?[p]:[]]),m=o.createBidirectionalStream({sendOrder:f==="socket"?10:0});m.then(I=>{g.aborted&&gf(I).close?.(new Error("Stream cancelled"))},()=>{});const b=await pf(m,g,()=>{}),y=gf(b),x=y.close;y.close=I=>{a.delete(y),x?.(I)},a.add(y);const w=performance.now();try{const I=await Wg({identity:e.identity,initiator:!0,targetPinnedPeerId:e.targetPeerId,duplex:y,signal:g});return{duplex:{...I.duplex,bufferedBytes:y.bufferedBytes},diagnostics:{endpoint:t.host,path:"direct",targetPeerId:I.authenticatedPeerId,transport:"webtransport",transportOpenMs:u,handshakeMs:performance.now()-w,establishedAt:Date.now(),bufferedBytes:0,pendingWrites:!1,activeRequests:0,waitingRequests:0}}}catch(I){throw y.close?.(I instanceof Error?I:new Error("Secure stream failed")),I}}}}const Qg={RELAY_AUTHORIZATION_REQUIRED:"没有有效中转授权",TARGET_AUTHORIZATION_REQUIRED:"目标服务需要重新登录",PERMISSION_DENIED:"当前权限不允许此操作",TARGET_IDENTITY_MISMATCH:"服务身份与保存的身份不一致",RELAY_SELF_TARGET:"不能通过服务中转到其自身;同一服务的其它地址请添加为备用地址。"};class ct extends Error{constructor(t,n={}){super(Qg[t]),this.code=t,this.context=n}code;context;name="ConnectionAccessError"}function yi(e,t={}){if(e instanceof ct)return Object.assign(e.context,{...t,...e.context}),e;if(e instanceof Error&&e.name==="ConnectionAccessError"&&"code"in e&&typeof e.code=="string"&&Object.hasOwn(Qg,e.code))return new ct(e.code,t);if(e instanceof Error&&e.name==="UnexpectedPeerError")return new ct("TARGET_IDENTITY_MISMATCH",t)}function em(e,t){return e instanceof Error&&(e.message==="AUTHORIZATION_DENIED"||e instanceof ct&&e.code==="PERMISSION_DENIED")?new ct("RELAY_AUTHORIZATION_REQUIRED",t):e instanceof Error?e:new Error("中转连接暂不可用")}class gt extends ct{constructor(){super("TARGET_AUTHORIZATION_REQUIRED")}}const bs=new WeakMap;function zr(e,t={}){const n=bs.get(e);if(!e.closed&&n&&(!n.settled||Date.now()-n.at<(t.maxAgeMs??1e3)))return n.pending;const r={at:Date.now(),settled:!1,pending:void 0},o=U1(e,t.timeoutMs??5e3).then(s=>(r.at=Date.now(),r.settled=!0,s),s=>{throw bs.get(e)===r&&bs.delete(e),s});return r.pending=o,bs.set(e,r),o}async function U1(e,t){const n=await e.request({type:"permissions"},{timeoutMs:t});if(n.type!=="result"||typeof n.fullService!="boolean"||!Array.isArray(n.grants))throw new Error("Invalid permission response");const r=n.grants,o=n.fullService===!0;if(!o&&r.length===0)throw new gt;return{fullService:o,grants:r,canManage:o&&r.length>0||r.some(s=>s.actions.includes("authorization.manage"))}}const H1=5*1024*1024,$1=qh+xc+8,q1=256,vs=3e4,Ss=pd;function wt(e){return e instanceof Error?e:new Error(String(e??"Secure connection closed"))}function Ta(e){if(!e.startsWith("/")||e.startsWith("//")||e.includes("#"))throw new Error("A local API path is required");return e}class Jc extends EventTarget{constructor(t,n,r,o=()=>0){super(),this.url=t,this.transmit=n,this.disconnect=r,this.pendingBytes=o}url;transmit;disconnect;pendingBytes;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;binaryType="arraybuffer";get bufferedAmount(){return this.pendingBytes()}protocol="termdock-e2ee-v1";extensions="";getConnectionDiagnostics;createdAt=performance.now();openedAfterMs;readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;send(t){if(this.readyState!==1)throw new Error("Secure socket is not open");if(typeof t!="string"||new TextEncoder().encode(t).length>1024*1024)throw new Error("Unsupported socket payload");this.transmit(t)}close(t=1e3,n=""){this.readyState!==3&&(this.disconnect(),this.finish(t,n))}accept(t){if(this.readyState!==3)if(t.type==="ws-ready"){this.openedAfterMs=performance.now()-this.createdAt,this.readyState=1;const n=new Event("open");this.dispatchEvent(n),this.onopen?.(n)}else if(t.type==="ws-data"&&typeof t.data=="string"){const n=new MessageEvent("message",{data:t.data});this.dispatchEvent(n),this.onmessage?.(n)}else t.type==="ws-close"?this.finish(typeof t.code=="number"?t.code:1e3,typeof t.reason=="string"?t.reason:""):t.type==="error"&&this.fail(wt(t.error))}fail(t){if(this.readyState===3)return;const n=new Event("error");this.dispatchEvent(n),this.onerror?.(n),this.finish(1006,t.message)}finish(t,n){if(this.readyState===3)return;this.readyState=3;const r=new CloseEvent("close",{code:t,reason:n,wasClean:t===1e3});this.dispatchEvent(r),this.onclose?.(r)}}class md{constructor(t,n,r){this.channel=t,this.identity=n,this.targetPeerId=r,this.read().catch(o=>this.sharedConnectionFailed(wt(o))),t.done.catch(o=>this.sharedConnectionFailed(wt(o)))}channel;identity;targetPeerId;transportDiagnostics;establishedAt=performance.now();establishedWallTime=Date.now();lastInputAt=-1/0;pending=new Map;waiting=[];stopped=!1;closeReason;httpWindow=1;binaryChunks=!1;streamConnector;streamPool;streamDescriptor;streamConnecting=!1;streamRetryAt=0;streamFailure;get webTransportFailure(){return this.streamFailure?.message}streamAbort=new AbortController;streamChildren=new Set;idleHttpStreams=[];operationGeneration=0;quicControl;sharedTransportClosed=!1;socketUpgradeTimer;idleHook;closedHook;get transport(){return this.streamPool?.available?"webtransport":this.transportDiagnostics?.().transport??"websocket"}get canSwitchTransport(){return!this.channel.hasPendingWrites&&performance.now()-this.lastInputAt>=2e3&&![...this.pending.values()].some(t=>t.kind!=="socket")&&!this.waiting.some(t=>t.kind!=="socket")&&[...this.streamChildren].every(t=>t.canSwitchTransport)}get renewalDue(){return!this.stopped&&Math.max(performance.now()-this.establishedAt,Date.now()-this.establishedWallTime)>=Vc-5*6e4}get closed(){return this.stopped}configureWebTransport(t){this.streamConnector=t}sharedConnectionFailed(t){if(!this.stopped){if(this.sharedTransportClosed=!0,!this.streamPool?.available||!this.quicControl||this.quicControl.closed){this.close(t);return}for(const[n,r]of this.pending)r.delegated||(r.queue.end(t),r.cancelUpload?.(),r.socket?.fail(t),this.release(n))}}streamClient(t){const n=new md(new Xg(t.duplex),this.identity,this.targetPeerId);return n.httpWindow=this.httpWindow,n.binaryChunks=this.binaryChunks,n.transportDiagnostics=()=>({...t.diagnostics,bufferedBytes:t.duplex.bufferedBytes?.()??0}),this.streamChildren.add(n),n.closedHook=()=>{this.streamChildren.delete(n)},n}recordCapabilities(t){this.httpWindow=A1(t.httpWindow),this.binaryChunks=t.binaryChunks===!0;const n=F1(t.webTransport);n&&(this.streamDescriptor=n,this.startStreams())}startStreams(){if(!this.streamConnector||!this.streamDescriptor||this.stopped||this.streamPool?.available||this.streamConnecting||Date.now()<this.streamRetryAt)return;this.streamConnecting=!0;const t=this.streamDescriptor;(async()=>{let n,r;try{n=await this.streamConnector(t,this.streamAbort.signal),r=this.streamClient(await n.open("socket",this.streamAbort.signal));const o=await r.request({type:"permissions"},{timeoutMs:4e3});if(o.type!=="result"||typeof o.fullService!="boolean"||!Array.isArray(o.grants))throw new Error("Invalid permission response");if(!o.fullService&&!o.grants.length)throw new gt;if(this.stopped)throw new Error("Secure connection closed");this.quicControl=r,this.streamPool=n,this.streamFailure=void 0;const s=n,i=r.closedHook;r.closedHook=()=>{i?.(),!this.stopped&&this.quicControl===r&&s.close()},n.closed.then(()=>{this.streamPool!==s||this.stopped||(this.streamPool=void 0,this.quicControl?.close(),this.quicControl=void 0,this.streamRetryAt=Date.now()+3e4,this.sharedTransportClosed&&this.close(new Error("Secure connection closed")))}),this.renewSharedSockets()}catch(o){this.streamFailure=wt(o),r?.close(),n?.close(),this.streamRetryAt=Date.now()+3e4,(o instanceof gt||o instanceof Error&&o.name==="UnexpectedPeerError")&&this.close(wt(o))}finally{this.streamConnecting=!1}})()}renewSharedSockets(){if(!(this.stopped||!this.streamPool?.available)){if(performance.now()-this.lastInputAt<2e3||this.channel.hasPendingWrites){this.socketUpgradeTimer=setTimeout(()=>this.renewSharedSockets(),250);return}for(const[t,n]of this.pending)if(!(!n.socket||n.delegated)){n.socket.accept({type:"ws-close",id:t,code:Xc,reason:Zc});try{this.channel.send({type:"ws-close",id:t})}catch{}this.release(t)}}}async operationStream(t,n){if(this.stopped)throw this.closeReason??new Error("Secure connection closed");this.startStreams();const r=this.streamPool;if(!r?.available){if(this.sharedTransportClosed)throw new Error("Secure connection closed");return}const o=await this.reserve(t,n);this.pending.get(o.id).delegated=!0;try{let s;if(t==="http")for(;this.idleHttpStreams.length;){const d=this.idleHttpStreams.pop();if(!d.closed&&!d.renewalDue){s=d;break}d.close()}if(s||(s=this.streamClient(await r.open(t,AbortSignal.any([this.streamAbort.signal,...n?[n]:[]])))),this.stopped||n?.aborted)throw s.close(),n?.reason??new Error("Secure connection closed");const i=s,a=i.operationGeneration+1;let c=!1;const l=()=>{c||(c=!0,this.release(o.id))};return i.closedHook=()=>{this.streamChildren.delete(i),this.idleHttpStreams=this.idleHttpStreams.filter(d=>d!==i),l()},i.idleHook=()=>{queueMicrotask(()=>{c||i.pending.size||i.operationGeneration<a||(l(),t==="http"&&!i.closed&&!i.renewalDue&&r===this.streamPool&&r.available&&this.idleHttpStreams.length<xc?this.idleHttpStreams.push(i):i.close())})},s}catch(s){if(this.release(o.id),s instanceof Error&&s.name==="UnexpectedPeerError"&&this.close(s),n?.aborted||this.stopped||s instanceof Error&&s.name==="UnexpectedPeerError"||this.sharedTransportClosed)throw s;return}}hasCapacity(t){if(this.pending.size>=$1)return!1;const n=[...this.pending.values()].filter(r=>r.kind===t).length;return t==="http"?n<xc:t==="socket"?n<qh:!0}allocate(t){if(this.stopped)throw this.closeReason??new Error("Secure connection closed");const n=crypto.randomUUID(),r=new gd(t==="http"?Yg+4:4);return this.operationGeneration++,this.pending.set(n,{queue:r,kind:t}),{id:n,queue:r}}reserve(t,n){return n?.aborted?Promise.reject(n.reason):this.stopped?Promise.reject(this.closeReason??new Error("Secure connection closed")):this.hasCapacity(t)?Promise.resolve(this.allocate(t)):this.waiting.length>=q1?Promise.reject(new Error("连接繁忙,请稍后重试。")):new Promise((r,o)=>{const s=l=>{this.waiting=this.waiting.filter(d=>d!==c),c.cleanup(),o(l)},i=()=>s(n?.reason??new Error("Request aborted")),a=setTimeout(()=>s(new Error("连接等待超时,请重试。")),vs),c={kind:t,resolve:r,reject:o,cleanup:()=>{clearTimeout(a),n?.removeEventListener("abort",i)}};this.waiting.push(c),n?.addEventListener("abort",i,{once:!0})})}dispatchWaiting(){if(!this.stopped)for(let t=0;t<this.waiting.length;){const n=this.waiting[t];if(!this.hasCapacity(n.kind)){t++;continue}this.waiting.splice(t,1),n.cleanup(),n.resolve(this.allocate(n.kind))}}async read(){try{for await(let t of this.channel.read()){if(t.type==="compressed"){if(t.encoding!=="gzip")throw new Error("Invalid record encoding");const r=await I1(t.data);if(!r||r.type!=="ws-data"||r.id!==t.id||typeof r.data!="string")throw new Error("Invalid compressed socket record");t=r}const n=this.pending.get(t.id);n&&(n.socket?(n.socket.accept(t),(t.type==="ws-close"||t.type==="error")&&this.release(t.id)):(n.queue.push(t),(t.type==="end"||t.type==="error")&&(n.cancelUpload?.(),this.release(t.id))))}}catch(t){this.sharedConnectionFailed(wt(t))}finally{this.sharedConnectionFailed(new Error("Secure connection closed"))}}release(t){this.pending.get(t)?.queue.end(),this.pending.delete(t),this.dispatchWaiting(),this.idleHook?.()}async request(t,n){if(this.quicControl&&!this.quicControl.closed){const i=await this.quicControl.request(t,n);return t.type==="permissions"&&i.type==="result"&&this.recordCapabilities(i),i}const{id:r,queue:o}=await this.reserve("request"),s=setTimeout(()=>this.close(new Error("Secure connection timed out")),Math.max(1e3,Math.min(vs,n?.timeoutMs??vs)));try{if(this.stopped)throw this.closeReason;this.channel.send({...t,id:r});const i=(await o[Symbol.asyncIterator]().next()).value;if(!i)throw new Error("Secure request closed");if(i.type==="error")throw i.error==="AUTHORIZATION_DENIED"?new ct("PERMISSION_DENIED",{targetServiceId:this.targetPeerId}):wt(i.error);return t.type==="permissions"&&i.type==="result"&&this.recordCapabilities(i),i}finally{clearTimeout(s),this.release(r)}}openSocket(t){if(Ta(t),!this.streamPool?.available)return this.startStreams(),this.openSharedSocket(t);const n=new AbortController;let r;const o=new Jc(t,s=>r?.send(s),()=>{n.abort(),r?.close()},()=>r?.bufferedAmount??0);return this.operationStream("socket",n.signal).then(s=>{if(o.readyState===3){s?.close();return}r=(s??this).openSharedSocket(t),o.getConnectionDiagnostics=()=>r?.getConnectionDiagnostics?.(),r.onopen=()=>o.accept({type:"ws-ready",id:""}),r.onmessage=i=>o.accept({type:"ws-data",id:"",data:i.data}),r.onclose=i=>o.accept({type:"ws-close",id:"",code:i.code,reason:i.reason}),r.onerror=()=>o.fail(new Error("Encrypted stream unavailable"))}).catch(s=>o.fail(wt(s))),o}openSharedSocket(t){Ta(t);let n;const r=new AbortController,o=new Jc(t,i=>{if(n){try{JSON.parse(i)?.type==="input"&&(this.lastInputAt=performance.now())}catch{}this.channel.send({id:n,type:"ws-data",data:i})}},()=>{if(r.abort(),n)try{this.channel.send({id:n,type:"ws-close"})}finally{this.release(n)}},()=>n?this.channel.queuedBytesFor(n):0);let s;return o.getConnectionDiagnostics=()=>{const i=this.transportDiagnostics?.();return i?{...i,socketOpenMs:o.openedAfterMs,socketQueueMs:s,pendingWrites:this.channel.hasPendingWrites,activeRequests:[...this.pending.values()].filter(a=>a.kind!=="socket").length,waitingRequests:this.waiting.length}:void 0},this.reserve("socket",r.signal).then(i=>{if(s=performance.now()-o.createdAt,n=i.id,o.readyState===3){this.release(n);return}const a=this.pending.get(n);if(!a)throw new Error("Secure connection closed");a.socket=o,this.channel.send({id:n,type:"ws-open",path:t,compression:typeof DecompressionStream<"u"?"gzip":void 0})}).catch(i=>{n&&this.release(n),o.fail(wt(i))}),o}async fetch(t,n){const r=typeof location>"u"?"https://termdock.invalid":location.origin,o=t instanceof Request?t:null,s=new URL(o?.url??String(t),r);if(s.origin!==r)throw new Error("Only current-service API requests are supported");const i=new Request(s,o?new Request(o,n):n),a=i.method.toUpperCase(),c=Ta(s.pathname+s.search),l=s.pathname==="/api/terminal/fs/upload"?110*1024*1024:H1;if(i.signal.aborted)throw i.signal.reason;const d=await this.operationStream("http",i.signal);if(d)try{return await d.fetch(i,{onUploadProgress:n?.onUploadProgress})}catch(R){throw d.close(wt(R)),R}const u={};i.headers.forEach((R,S)=>{["cookie","authorization","host","connection","content-length"].includes(S)||(u[S]=R)});const{id:f,queue:p}=await this.reserve("http",i.signal),g=p[Symbol.asyncIterator]();let m;const b=()=>{m?.cancel().catch(()=>{})},y=this.pending.get(f);if(!y)throw new Error("Secure connection closed");y.cancelUpload=b;const x=()=>{b();try{this.channel.send({id:f,type:"cancel"})}catch{}p.end(wt(i.signal.reason??"Request aborted")),this.release(f)};i.signal.addEventListener("abort",x,{once:!0});const w=()=>{i.signal.removeEventListener("abort",x),this.release(f)},I=async()=>{let R;try{const S=(await Promise.race([g.next(),new Promise((A,T)=>{R=setTimeout(()=>T(new Error("服务响应超时,请重试。")),vs)})])).value;if(!S)throw new Error("Secure response ended unexpectedly");if(S.type==="error")throw wt(S.error);return S}finally{clearTimeout(R)}};try{if(i.signal.aborted)throw i.signal.reason;const R=this.httpWindow,S=this.binaryChunks;if(this.channel.send({id:f,type:"http",method:a,path:c,headers:u,window:R,binaryChunks:S}),i.body){const C=i.body.getReader();m=C;let B=0,k=0;const N=[],L=async()=>{if((await I()).type!=="upload-ack")throw new Error("Invalid upload acknowledgement");k+=N.shift(),n?.onUploadProgress?.(k)};try{for(;;){const{done:D,value:F}=await C.read();if(D)break;if(B+=F.byteLength,B>l)throw new Error("Request body exceeds upload limit");for(let O=0;O<F.byteLength;O+=Ss){N.length>=R&&await L();const _=F.subarray(O,O+Ss);await this.channel.sendBulk({id:f,type:"upload",...S?{bytes:_}:{data:Zg(_)}},i.signal),N.push(_.byteLength)}}for(;N.length;)await L()}catch(D){throw await C.cancel(D).catch(()=>{}),D}finally{m=void 0,C.releaseLock()}}if(i.signal.aborted||this.stopped)throw new Error("Request aborted");this.channel.send({id:f,type:"upload-end"});const A=await I();if(A.type!=="head"||typeof A.status!="number")throw new Error("Invalid response header");const T=new Headers(A.headers);if(a==="HEAD"||[204,205,304].includes(A.status)){if((await I()).type!=="end")throw new Error("Unexpected response body");return w(),new Response(null,{status:A.status,headers:T})}let v=!1;const E=new ReadableStream({pull:async C=>{try{v&&(this.channel.send({id:f,type:"ack"}),v=!1);const B=await I();if(B.type==="end"){C.close(),w();return}if(B.type!=="chunk"||!(S&&B.bytes instanceof Uint8Array)&&typeof B.data!="string")throw new Error("Invalid response chunk");const k=S&&B.bytes instanceof Uint8Array?B.bytes:Jg(B.data);if(k.length>Ss)throw new Error("Response chunk exceeds budget");C.enqueue(k),v=!0}catch(B){C.error(B),x(),w()}},cancel:()=>{x(),w()}},{highWaterMark:Ss,size:C=>C.byteLength});return new Response(E,{status:A.status,headers:T})}catch(R){throw x(),w(),R}}retire(){for(const t of this.streamChildren)t.retire();for(const t of this.pending.values())t.socket?.accept({id:"",type:"ws-close",code:Xc,reason:Zc});this.close()}close(t=new Error("Secure connection closed")){if(!this.stopped){this.stopped=!0,this.closeReason=t,clearTimeout(this.socketUpgradeTimer),this.streamAbort.abort(t);for(const n of this.streamChildren)n.close(t);this.streamPool?.close();for(const n of this.waiting.splice(0))n.cleanup(),n.reject(t);for(const n of this.pending.values())n.queue.end(t),n.cancelUpload?.(),n.socket?.fail(t);this.pending.clear(),this.channel.close(t),this.closedHook?.()}}}async function zn(e){const t=new URL(e.url);if(!["wss:","ws:"].includes(t.protocol))throw new Error("A WebSocket endpoint is required");if(t.protocol==="ws:"&&!["127.0.0.1","localhost","[::1]"].includes(t.hostname))throw new Error("Remote secure channels require WSS");const n=e.identity??await Kg(),r=performance.now(),o=(e.socketFactory??(l=>new WebSocket(l)))(t.href),s=D1(o),i=new AbortController,a=setTimeout(()=>i.abort(new Error("Secure handshake timed out")),2e4),c=e.signal?AbortSignal.any([e.signal,i.signal]):i.signal;try{await new Promise((b,y)=>{if(c.aborted){y(c.reason);return}const x=()=>{c.removeEventListener("abort",R),o.removeEventListener("open",w),o.removeEventListener("error",I),o.removeEventListener("close",I)},w=()=>{x(),b()},I=()=>{x(),y(o.transportFailure||new Error("Secure transport unavailable"))},R=()=>{x(),y(c.reason)};c.addEventListener("abort",R,{once:!0}),o.addEventListener("open",w),o.addEventListener("error",I),o.addEventListener("close",I),o.readyState===1&&w()});const l=performance.now(),d=await Wg({identity:n,duplex:s,initiator:!0,targetPinnedPeerId:e.targetPeerId,signal:c}),u=new md(new Xg(d.duplex),n,d.authenticatedPeerId),f=performance.now(),p=Date.now(),g=o.connectionTimings;u.transportDiagnostics=()=>({endpoint:t.host,path:g?"relay":"direct",targetPeerId:d.authenticatedPeerId,transport:"websocket",transportOpenMs:l-r,handshakeMs:f-l,establishedAt:p,relay:g?{...g}:void 0,bufferedBytes:o.bufferedAmount,pendingWrites:!1,activeRequests:0,waitingRequests:0});const m=e.webTransportFactory??M1();if(e.webTransport!==!1&&!g&&t.protocol==="wss:"&&m&&u.configureWebTransport((b,y)=>j1({baseUrl:t.href,descriptor:b,identity:n,targetPeerId:d.authenticatedPeerId,factory:m,signal:y})),e.pairingCode)try{await u.request({type:"pair",code:e.pairingCode})}catch(b){throw u.close(wt(b)),b}return u}catch(l){throw o.close(),l}finally{clearTimeout(a)}}const mf=256*1024,K1=1024*1024;class z1 extends EventTarget{constructor(t,n,r=s=>new WebSocket(s),o={}){if(super(),this.url=t,!/^[a-zA-Z0-9_.:-]{1,160}$/.test(n))throw new Error("Invalid target identity");const s=performance.now();let i;this.upstream=r(t),this.upstream.addEventListener("open",()=>{this.connectionTimings.entryOpenMs=performance.now()-s}),this.deadline=setTimeout(()=>this.fail("Relay connection timed out"),Ml),this.upstream.addEventListener("message",a=>{if(this.readyState!==3)try{if(typeof a.data!="string"||new TextEncoder().encode(a.data).length>mf)throw new Error("Invalid relay envelope");const c=JSON.parse(a.data);if(c.type==="ready"&&!this.requested){i=performance.now(),this.requested=!0,this.transmit({type:"open",streamId:this.streamId,serviceId:n});return}if(c.streamId!==this.streamId)return;if(c.type==="opened"&&this.readyState===0){this.connectionTimings.routeOpenMs=i===void 0?null:performance.now()-i,clearTimeout(this.deadline),this.readyState=1;const f=new Event("open");this.dispatchEvent(f),this.onopen?.(f);return}if(c.type==="close"){(c.code==="RELAY_AUTHORIZATION_REQUIRED"||c.reason==="Authorization revoked")&&(this.transportFailure=new ct("RELAY_AUTHORIZATION_REQUIRED",{...o,targetServiceId:n})),c.code==="RELAY_SELF_TARGET"&&(this.transportFailure=new ct("RELAY_SELF_TARGET",{...o,targetServiceId:n})),this.finish(1001,this.transportFailure?.message||"Relay route closed"),this.upstream.close();return}if(c.type!=="data"||this.readyState!==1||c.encoding!=="base64"||typeof c.payload!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(c.payload))throw new Error("Invalid ciphertext relay frame");const l=Jg(c.payload),d=this.binaryType==="blob"?new Blob([l]):l.buffer,u=new MessageEvent("message",{data:d});this.dispatchEvent(u),this.onmessage?.(u)}catch{this.fail("Relay protocol rejected frame")}}),this.upstream.addEventListener("close",a=>this.finish(a.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;transportFailure;onopen=null;onmessage=null;onerror=null;onclose=null;connectionTimings={entryOpenMs:null,routeOpenMs:null};upstream;streamId=crypto.randomUUID();requested=!1;deadline;get bufferedAmount(){return this.upstream.bufferedAmount}transmit(t){const n=JSON.stringify(t);if(this.upstream.readyState!==1||this.upstream.bufferedAmount+n.length>K1||n.length>mf)throw new Error("Relay unavailable or congested");this.upstream.send(n)}send(t){if(this.readyState!==1)throw new Error("Relay socket is not open");let n;if(ArrayBuffer.isView(t))n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);else if(t instanceof ArrayBuffer)n=new Uint8Array(t);else throw new Error("Relay secure transport requires binary bytes");try{this.transmit({type:"data",streamId:this.streamId,encoding:"base64",payload:Zg(n)})}catch(r){throw this.fail("Relay transport congested"),r}}close(t=1e3,n=""){if(this.readyState!==3){try{this.requested&&this.transmit({type:"close",streamId:this.streamId})}catch{}this.finish(t,n),this.upstream.close()}}fail(t){if(this.readyState===3)return;const n=new Event("error");this.dispatchEvent(n),this.onerror?.(n),this.finish(1006,t),this.upstream.close()}finish(t,n){if(this.readyState===3)return;clearTimeout(this.deadline),this.readyState=3;const r=new CloseEvent("close",{code:t,reason:n,wasClean:t===1e3});this.dispatchEvent(r),this.onclose?.(r)}}function tm(e,t={}){return n=>new z1(n,e,void 0,t)}function W1(e){if(typeof e!="string"||!e.startsWith("/api/")||/[\\\x00-\x20\x7f#]/.test(e))return null;const t=e.split("?")[0];if(t.includes("//"))return null;try{const r=t.split("/").map((o,s)=>{if(s===0||o===""&&s===t.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 r.endsWith("/")&&!r.startsWith("/api/terminal/fs/preview/")?null:r}catch{return null}}function G1(e){if(!("serviceWorker"in navigator))return()=>{};const t=new Set,n=r=>{if(r.source!==navigator.serviceWorker.controller||r.data?.type!=="termdock-secure-fetch"||r.ports.length!==1)return;const o=r.ports[0],{path:s,method:i,headers:a,body:c,expectedTargetPeerId:l,previewPrefix:d}=r.data;let u;try{u=new URL(s,location.origin)}catch{o.close();return}if(u.origin!==location.origin||!u.pathname.startsWith("/api/")||t.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)||!W1(u.pathname)?.startsWith(d))){o.postMessage({type:"error"}),o.close();return}const f=new AbortController;let p,g,m=!1,b=!1;const y=()=>{b||(b=!0,t.delete(y),f.abort(),p?.cancel().catch(()=>{}),o.close())};t.add(y),o.onmessage=x=>{if(x.data?.type==="cancel"){y();return}x.data?.type!=="pull"||m||b||(m=!0,(async()=>{if(!p){o.postMessage({type:"end"}),y();return}if(!g?.length){const I=await p.read();if(I.done){o.postMessage({type:"end"}),y();return}g=I.value}const w=g.slice(0,64*1024);g=g.subarray(w.length),o.postMessage({type:"chunk",data:w.buffer},[w.buffer])})().catch(()=>{o.postMessage({type:"error"}),y()}).finally(()=>{m=!1}))},o.onmessageerror=y,o.start(),(async()=>{const x=await e();if(b)return;if(l&&l!==x.targetPeerId)throw new Error("Preview target changed");const w=await x.fetch(u.pathname+u.search,{method:i,headers:a,body:["GET","HEAD"].includes(i)?void 0:c,signal:f.signal});if(b){await w.body?.cancel();return}p=w.body?.getReader();const I={};w.headers.forEach((R,S)=>{I[S]=R}),o.postMessage({type:"head",status:w.status,headers:I,bodyless:!p,targetPeerId:x.targetPeerId})})().catch(()=>{b||(o.postMessage({type:"error"}),y())})};return navigator.serviceWorker.addEventListener("message",n),()=>{navigator.serviceWorker.removeEventListener("message",n);for(const r of[...t])r()}}const nm="termdock-secure-last-path:",V1=10*6e4;function rm(e){try{const t=JSON.parse(sessionStorage.getItem(nm+e)||"null");return t&&typeof t.key=="string"&&Date.now()-t.at<V1?t.key:void 0}catch{return}}function Qc(e,t){try{sessionStorage.setItem(nm+e,JSON.stringify({key:t,at:Date.now()}))}catch{}}function om(e,t,n=!1){return new Promise((r,o)=>{let s=0,i=0,a=!1,c,l,d,u;const f=new Set,p=()=>{clearTimeout(u);for(const m of f)m.abort();f.clear()},g=()=>{if(a)return;if(s>=e.length){i||(a=!0,p(),o(l||d||c||new Error("没有可用的连接路线。")));return}if(i>=(n?1:2))return;const m=e[s++],b=performance.now(),y=w=>{performance.getEntriesByName("termdock:connection-path").length>64&&performance.clearMeasures("termdock:connection-path"),performance.measure("termdock:connection-path",{start:b,end:performance.now(),detail:{path:m.key.startsWith("relay:")?"relay":"direct",ok:w}})},x=new AbortController;f.add(x),i++,m.run(x.signal).then(w=>{if(y(!0),f.delete(x),a){t(w);return}a=!0,p(),r({value:w,key:m.key})},w=>{if(y(!1),f.delete(x),i--,!a){if(c=w,w instanceof Error&&w.name==="UnexpectedPeerError"&&(l=w),w instanceof ct&&["TARGET_IDENTITY_MISMATCH","RELAY_SELF_TARGET"].includes(w.code)&&(l=w),w instanceof ct&&w.code==="RELAY_AUTHORIZATION_REQUIRED"&&(d=w),w instanceof gt||w instanceof ct&&w.code==="TARGET_AUTHORIZATION_REQUIRED"){a=!0,p(),o(w);return}g()}}),clearTimeout(u),!n&&s<e.length&&(u=setTimeout(g,400))};g()})}const Y1=3,X1=1/0,Z1=10,sm="termdock-secure-workspace-limit";function im(e){return e===1/0||Number.isInteger(e)&&e>=3&&e<=Z1}function J1(){try{const e=localStorage.getItem(sm),t=e==="unlimited"?1/0:Number(e);if(im(t))return t}catch{}return navigator.maxTouchPoints>0?Y1:X1}function Q1(e,t,n,r){if(e.length<=r)return e;const o=new Set(["root",t,...n?[n]:[]]),s=[...e].reverse().sort((i,a)=>a.touchedAt-i.touchedAt);for(const i of s){if(o.size>=r)break;o.add(i.key)}return e.filter(i=>o.has(i.key))}const am="termdock-workspace",$o="termdock:workspace-visibility",el="termdock:workspace-activate";function Vi(){return window.parent!==window&&location.pathname==="/workspace.html"&&new URLSearchParams(location.search).get(am)||"root"}let wf,yf;function $t(){try{if(window.parent===window)return window.__termdockWorkspaceHost;const e=window.parent.__termdockWorkspaceHost;return e&&e!==wf&&(wf=e,yf={...e,subscribe(t){const n=e.subscribe(t,Vi()),r=o=>{o.persisted||n()};return window.addEventListener("pagehide",r),()=>{n(),window.removeEventListener("pagehide",r)}}}),e?yf:void 0}catch{return}}function _s(){const e=$t();return!e||e.snapshot().activeKey===Vi()}function bi(e,t=!0){return $t()?.activate(e,t)??!1}function hr(e){$t()?.report(Vi(),e)}const tl="termdock-secure-workspace-session:",cm="termdock-secure-last-workspace";function eI(){for(const e of["sessionStorage","localStorage"])try{const t=window[e].getItem(cm);if(t)return t}catch{}return null}function tI(e){for(const t of["sessionStorage","localStorage"])try{window[t].setItem(cm,e)}catch{}}function j2(e){if(e)try{const t=JSON.parse(localStorage.getItem(tl+e)||"null");return localStorage.removeItem(tl+e),t&&typeof t.sessionId=="string"&&Date.now()-t.at<6e4?t.sessionId:void 0}catch{return}}function nI(e){if(window.parent!==window||window.termdockDesktop)return;if(window.__termdockWorkspaceHost)return window.__termdockWorkspaceHost;let t={activeKey:"root",items:[{key:"root",service:e,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]};try{const u=eI(),f=e&&u!==e.targetPeerId?$n().find(p=>p.targetPeerId===u):void 0;f?.targetPeerId&&(t={activeKey:f.targetPeerId,items:[...t.items,{key:f.targetPeerId,service:f,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]})}catch{}let n=J1(),r=t.activeKey==="root"?"root":null;const o=new Map,s=new Map([["root",window]]),i=new Set,a=()=>{for(const u of[...o.keys()])u()},c=()=>{const u=Q1(t.items,t.activeKey,r,n),f=new Set(u.map(p=>p.key));t={...t,items:u};for(const[p,g]of o)g&&!f.has(g)&&o.delete(p);for(const p of s.keys())f.has(p)||s.delete(p);for(const p of i)f.has(p)||i.delete(p)},l=(u,f)=>{try{const p=f.document.createEvent("CustomEvent");if(p.initCustomEvent($o,!1,!1,{active:t.activeKey===u}),f.dispatchEvent(p),t.activeKey===u){const g=f.document.createEvent("Event");if(g.initEvent("resize",!1,!1),f.dispatchEvent(g),i.delete(u)){const m=f.document.createEvent("Event");m.initEvent(el,!1,!1),f.dispatchEvent(m)}}else f.document.activeElement?.blur?.()}catch{}},d={snapshot:()=>t,subscribe:(u,f)=>(o.set(u,f),()=>{o.delete(u)}),present(u){r=u},retentionLimit:()=>n,setRetentionLimit(u){if(im(u)){n=u;try{localStorage.setItem(sm,u===1/0?"unlimited":String(u))}catch{}c(),a()}},activate(u,f=!0){const p=Bi(u);if(!p?.targetPeerId)return!1;const g=t.items.find(y=>y.service?.targetPeerId===p.targetPeerId),m=g?.key||p.targetPeerId,b=g?{...g,service:p,touchedAt:Date.now()}:{key:m,service:p,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()};t={activeKey:m,items:g?t.items.map(y=>y===g?b:y):[...t.items,b]},c(),tI(p.targetPeerId),f&&i.add(m),a();for(const[y,x]of s)l(y,x);return!0},report(u,f){const p=t.items.find(m=>m.key===u);if(!p||f.service&&p.service?.targetPeerId&&f.service.targetPeerId!==p.service.targetPeerId)return;const g={...p,...f};JSON.stringify(g)!==JSON.stringify(p)&&(t={...t,items:t.items.map(m=>m===p?g:m)},a())},attach(u,f){f&&t.items.some(p=>p.key===u)?(s.set(u,f),l(u,f)):s.delete(u)},focusSession(u,f){const p=$n().find(m=>m.targetPeerId===u);if(!p)return!1;try{localStorage.setItem(tl+u,JSON.stringify({sessionId:f,at:Date.now()}))}catch{return!1}d.activate(p,!1);const g=s.get(t.activeKey);if(g){const m=g.document.createEvent("CustomEvent");m.initCustomEvent("termdock:workspace-session",!1,!1,null),g.dispatchEvent(m)}return!0}};return window.__termdockWorkspaceHost=d,d}let Pa;async function Ct(){return Pa||(Pa=(async()=>{const e=await new Promise((t,n)=>{const r=indexedDB.open("termdock-device-identity",1);r.onupgradeneeded=()=>r.result.createObjectStore("keys"),r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)});try{const t=await new Promise((o,s)=>{const i=e.transaction("keys").objectStore("keys").get("identity");i.onsuccess=()=>o(i.result),i.onerror=()=>s(i.error)});if(t)return uf(t);const n=await Kg();let r=n;return await new Promise((o,s)=>{const i=e.transaction("keys","readwrite"),a=i.objectStore("keys"),c=a.get("identity");c.onsuccess=()=>{typeof c.result=="string"?r=uf(c.result):a.put(m1(n),"identity")},i.oncomplete=()=>o(),i.onerror=()=>s(i.error)}),r}finally{e.close()}})()),Pa}const rI="termdock:secure-ready";let nl="ready";const rl=new Set;function Po(e){if(e!==nl){nl=e;for(const t of rl)t();e==="ready"&&window.dispatchEvent(new Event(rI))}}function U2(){return P.useSyncExternalStore(e=>(rl.add(e),()=>{rl.delete(e)}),()=>nl)}function lm(e){const t=e instanceof Error?e.message:String(e);return/^(Secure connection closed|Secure connection timed out|Secure request closed|Secure response ended unexpectedly|Encrypted connection unavailable|Encrypted transport disconnected|Secure transport unavailable|Secure handshake timed out|WebSocket closed|WebSocket connection failed)$/.test(t)}const vi={CONNECTION_FAILED:{reason:"connectionFailed",status:503,message:"暂时连不上这台服务,请检查地址和网络后重试。"},INVALID_PASSWORD:{reason:"invalidPassword",status:401,message:"密码不正确,或服务身份无法验证。请检查后重试。"},IDENTITY_MISMATCH:{reason:"identityMismatch",status:409,message:"服务身份与已保存的记录不一致,请确认目标服务。"},RATE_LIMITED:{reason:"rateLimited",status:429,message:"尝试次数较多,请稍后再试。"},LOGIN_UNAVAILABLE:{reason:"unavailable",status:503,message:"暂时无法登录这台服务,请稍后重试。"},DEVICE_AUTHORIZATION_REQUIRED:{reason:"authorizationRequired",status:403,message:"请检查目标服务与入口的设备授权后重试。"}};function bf(e){return typeof e=="string"&&Object.hasOwn(vi,e)?vi[e].reason:void 0}class It extends Error{constructor(t,n){super(vi[t].message),this.code=t,this.retryAfterMs=n,this.status=vi[t].status}code;retryAfterMs;status}function Yi(e){if(e instanceof It)return e;if(e instanceof gt)return new It("DEVICE_AUTHORIZATION_REQUIRED");if(e instanceof ct)return new It(e.code==="TARGET_IDENTITY_MISMATCH"?"IDENTITY_MISMATCH":"DEVICE_AUTHORIZATION_REQUIRED");if(e instanceof Error){if(e.name==="UnexpectedPeerError"||e.message==="PEER_IDENTITY_MISMATCH")return new It("IDENTITY_MISMATCH");if(e.message==="LOGIN_RATE_LIMIT"||e.message==="Too many password login attempts")return new It("RATE_LIMITED");if(e.message==="AUTHORIZATION_DENIED")return new It("DEVICE_AUTHORIZATION_REQUIRED");if(e instanceof TypeError||["TimeoutError","AbortError"].includes(e.name)||lm(e)||e.message==="Encrypted handshake timed out"||e.message==="Encrypted transport failed")return new It("CONNECTION_FAILED");if(e.message==="Password authentication failed"||e.message==="Password login expired"||e.message==="INVALID_LOGIN")return new It("INVALID_PASSWORD")}return new It("LOGIN_UNAVAILABLE")}const Et="termdock:secure-state";let ae,pr,st,Mr="direct",Os=!1,vf=0,Fs=!1,Sf=-1/0;const xn=new Map;function ol(e){const t=e.context.targetServiceId||te()?.targetPeerId;t&&(xn.size>32&&xn.clear(),xn.set(t,e))}function oI(){const e=te()?.targetPeerId;e&&xn.delete(e)}const jr=globalThis.fetch.bind(globalThis);function te(){return at()}function At(){return ae}function sI(){return st}function wd(){ae?.close(),st?.close(),ae=void 0,st=void 0}class Na extends Error{constructor(){super("Secure read target changed"),this.name="SecureReadTargetChanged"}}function iI(e){if(lm(e))return!0;if(!e||typeof e!="object")return!1;const t=e;return t.name==="UnexpectedEOFError"&&typeof t.message=="string"&&/^Unexpected EOF - stream closed while reading \d+\/\d+ bytes$/.test(t.message)}async function aI(e,t){const n=te(),r=n?.targetPeerId,o=JSON.stringify(n),s=()=>JSON.stringify(te())===o,i=At(),a=c=>{if(!s())throw new Na;if(t?.aborted)throw new DOMException("The operation was aborted","AbortError");return c};try{return a(await e())}catch(c){if(c instanceof Na||t?.aborted||c instanceof Error&&c.name==="AbortError"||c&&typeof c=="object"&&"status"in c||!r||!s()||!i?.closed&&!iI(c))throw c;if(Po(navigator.onLine===!1?"offline":"reconnecting"),i&&At()===i&&wd(),window.dispatchEvent(new Event(Et)),await hm(t),!s())throw new Na;const l=a(await e());return Po("ready"),l}}async function dm(){const e=await jr("/api/auth/status",{signal:AbortSignal.timeout(5e3)});if(!e.ok)throw new Error("Failed to query auth status");return e.json()}async function cI(){if(te()){await St();return}if((await dm()).enabled)return;const e=await jr("/api/auth/open/parameters",{cache:"no-store"});if(!e.ok)throw new Error("Open service unavailable");const{serviceIdentity:t}=await e.json();if(typeof t!="string"||!t)throw new Error("Invalid service identity");await Pt({url:location.origin,targetPeerId:t,serviceName:location.hostname})}async function lI(e,t){const{startPasswordBootstrap:n,finishPasswordBootstrap:r}=await An(async()=>{const{startPasswordBootstrap:u,finishPasswordBootstrap:f}=await import("./passwordBootstrap-DLUamTjd.js");return{startPasswordBootstrap:u,finishPasswordBootstrap:f}},__vite__mapDeps([0,1,2,3])),o=typeof window<"u"?window.termdockDesktop:void 0;let s=location.origin;if(o?.previewCapabilities&&o.passwordBootstrapOrigin){const u=o.passwordBootstrapOrigin(e),f=new URL(u);if(f.origin!==u||e!==location.origin&&f.origin!==e||!["http:","https:"].includes(f.protocol)||f.username||f.password)throw new It("LOGIN_UNAVAILABLE");s=u}const i=u=>e===location.origin?u:new URL(u,e).href,a=async(u,f)=>{const p=await jr(i(u),{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(15e3),...f?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)}:{}});if(!p.ok){const g=await p.json().catch(()=>null),m=typeof g?.retryAfterMs=="number"&&Number.isFinite(g.retryAfterMs)&&g.retryAfterMs>=0?g.retryAfterMs:void 0;throw new It(p.status===429?"RATE_LIMITED":p.status===401?"INVALID_PASSWORD":"LOGIN_UNAVAILABLE",m)}return p.json()},{saltHex:c}=await a("/api/auth/password/parameters"),l=await Ct(),d=await n(t,c);try{const u=await a("/api/auth/password/start",{startLoginRequest:d.startLoginRequest,clientIdentity:l.peerId}),f=await r(d,u,{clientIdentity:l.peerId,origin:s});await a("/api/auth/password/finish",{attemptId:f.attemptId,finishLoginRequest:f.finishLoginRequest});const p=s===location.origin?e:s;return{url:p,targetPeerId:f.serverIdentity,serviceName:new URL(p).host,serviceOrigin:p}}finally{d.passwordKey=""}}async function yd(e,t){const n=te();if(n&&(n.serviceOrigin||n.url)===e)return await sl(n,t),n;try{return await lI(e,t)}catch(r){if(!(r instanceof TypeError)&&!(r instanceof DOMException))throw r;const o=(await Ve()).find(i=>i.targetPeerId&&(i.serviceOrigin||i.url)===e);if(!o?.targetPeerId)throw Yi(r);const s={...o,targetPeerId:o.targetPeerId,serviceName:o.label};return await sl(s,t),s}}async function sl(e,t){const n=await Xi(e),{startPasswordBootstrap:r,finishPasswordBootstrap:o}=await An(async()=>{const{startPasswordBootstrap:i,finishPasswordBootstrap:a}=await import("./passwordBootstrap-DLUamTjd.js");return{startPasswordBootstrap:i,finishPasswordBootstrap:a}},__vite__mapDeps([0,1,2,3]));let s;try{const i=await n.request({type:"password-parameters"},{timeoutMs:5e3});s=await r(t,String(i.saltHex));const a=await n.request({type:"password-start",startLoginRequest:s.startLoginRequest,origin:location.origin}),c=await o(s,a,{clientIdentity:(await Ct()).peerId,origin:location.origin});if(c.serverIdentity!==e.targetPeerId)throw new It("IDENTITY_MISMATCH");await n.request({type:"password-finish",attemptId:c.attemptId,finishLoginRequest:c.finishLoginRequest})}catch(i){throw Yi(i)}finally{s&&(s.passwordKey=""),n.close()}}async function dI(e){try{const t=te(),n=t?.serviceOrigin||location.origin,r=await yd(n,e);return await Pt({...r,routes:t?.routes,serviceName:t?.serviceName||r.serviceName}),Response.json({ok:!0})}catch(t){const n=Yi(t);return Response.json({error:n.message,code:n.code,retryAfterMs:n.retryAfterMs},{status:n.status})}}async function Ef(e,t){const n=Ne(e),r=(await Ve()).find(i=>(i.serviceOrigin||i.url)===n&&i.targetPeerId);if(t===void 0&&r?.targetPeerId)try{return await Pt({...r,targetPeerId:r.targetPeerId,serviceName:r.label}),{}}catch(i){if(!(i instanceof gt))throw i}if(t!==void 0){const i=await yd(n,t);if(r?.targetPeerId&&r.targetPeerId!==i.targetPeerId)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await Pt({...i,routes:r?.routes,serviceName:r?.label||i.serviceName}),{}}const o=await jr(new URL("/api/auth/open/parameters",n).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(r?.targetPeerId&&r.targetPeerId!==s)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await Pt({url:n,targetPeerId:s,serviceName:r?.label||new URL(n).host,serviceOrigin:n}),{}}function Bt(e){const t=[...e.routes||[]];if(e.entryServiceId&&e.entryServiceId!==e.targetPeerId&&t.unshift({url:e.url,targetPeerId:e.entryServiceId}),!t.length&&e.routes===void 0)try{const r=JSON.parse(localStorage.getItem(Fl)||"null");r&&r.targetPeerId!==e.targetPeerId&&new URL(r.url).host===new URL(e.url).host&&t.push(r)}catch{}const n=new Set;return t.flatMap(r=>{try{if(!r.targetPeerId||r.targetPeerId===e.targetPeerId)return[];const o=Ne(r.url),s=JSON.stringify([r.targetPeerId,o]);return n.has(s)?[]:(n.add(s),[{url:o,targetPeerId:r.targetPeerId}])}catch{return[]}}).slice(0,4)}const No=e=>`relay:${e.targetPeerId}:${e.url}`;async function um(e){const t=Bt(e),n=new Set(t.map(No)),r=[],o=await Ve(),s=o.some(i=>i.targetPeerId===e.targetPeerId);for(const i of o)if(!(!i.targetPeerId||i.targetPeerId===e.targetPeerId||!s&&!Bt({...i,targetPeerId:i.targetPeerId}).some(a=>a.targetPeerId===e.targetPeerId)))for(const a of Jn({...i,targetPeerId:i.targetPeerId})){const c={url:a,targetPeerId:i.targetPeerId};n.has(No(c))||(n.add(No(c)),r.push(c))}return r.slice(0,Math.max(0,4-Math.max(e.routes?.length??0,t.length)))}function Jn(e){const t=Bt(e),n=[e.serviceOrigin||e.url,...(e.routes||[]).slice(0,4).filter(o=>o.targetPeerId===e.targetPeerId).map(o=>o.url)],r=new Set;for(const o of n)try{const s=Ne(o);t.some(i=>i.url===s)||r.add(s)}catch{}return[...r]}function Wn(e){const t=new URL("/api/federation/secure",Ne(e));return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.href}async function fm(e,t){return zn({url:Wn(e.url),targetPeerId:e.targetPeerId,identity:await Ct(),signal:t?AbortSignal.any([t,AbortSignal.timeout(5e3)]):AbortSignal.timeout(5e3)})}async function Xi(e,t,n){const r=await Ct(),o=Jn(e).map(c=>({key:`direct:${c}`,run:l=>zn({url:Wn(c),targetPeerId:e.targetPeerId,identity:r,signal:AbortSignal.any([l,AbortSignal.timeout(8e3),...t?[t]:[]])})})),s=n?[]:await um(e);for(const c of[...Bt(e),...s])o.push({key:No(c),run:async l=>{t&&(l=AbortSignal.any([l,t]));const d=[ae,st].find(f=>f&&!f.closed&&f.targetPeerId===c.targetPeerId),u=d||await fm(c,l);try{if(l.aborted)throw l.reason;const f=await u.request({type:"route-ticket",serviceId:e.targetPeerId},{timeoutMs:5e3}).catch(g=>{throw em(g,{targetServiceId:e.targetPeerId,entryServiceId:c.targetPeerId,entryUrl:c.url})});if(l.aborted)throw l.reason;if(typeof f.routeToken!="string")throw new Error("入口未允许此设备连接该服务。");const p=new URL(Wn(c.url));return p.pathname="/api/federation/relay",p.searchParams.set("routeToken",f.routeToken),await zn({url:p.href,targetPeerId:e.targetPeerId,identity:r,socketFactory:tm(e.targetPeerId,{entryServiceId:c.targetPeerId,entryUrl:c.url}),signal:AbortSignal.any([l,AbortSignal.timeout(Ml)])})}finally{d||u.close()}}});const i=rm(e.targetPeerId);o.sort((c,l)=>+(l.key===i)-+(c.key===i));const a=await om(o,c=>c.close());return n?n.connected(a.key):Qc(e.targetPeerId,a.key),a.value}async function uI(e,t){const n=await Xi(e,t);try{const o=(await n.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node;if(o?.serviceId!==e.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");return{...o,serviceId:e.targetPeerId}}finally{n.close()}}async function fI(e,t){const n=await Xi(e,t),r=()=>n.close();t.addEventListener("abort",r,{once:!0});try{if(t.aborted||(await zr(n,{timeoutMs:3e3}),t.aborted))throw t.reason;return n}catch(o){throw n.close(),o}finally{t.removeEventListener("abort",r)}}async function Pt(e,t={}){e.entryServiceId&&Ur(e.entryServiceId,e.targetPeerId);const n=ae,r=st,o=await Ct(),s=Ne(e.serviceOrigin||e.url),i=(await Ve()).find(x=>x.targetPeerId===e.targetPeerId),a={...e,routes:e.routes??i?.routes},c=await um(a),l=[...Bt(a),...c],d=Jn(a);let u,f,p=e.pairingCode,g="direct";const m=new Set,b=new Map,y=async(x,w)=>{if(n&&!n.closed&&n.targetPeerId===x.targetPeerId)return n;if(r&&!r.closed&&r.targetPeerId===x.targetPeerId)return r;const I=JSON.stringify([x.targetPeerId,x.url]),R=b.get(I);if(R&&!R.closed)return R;const S=await fm(x,w);return m.add(S),b.set(I,S),S};try{if(e.routeCode&&e.entryServiceId){const C=l.find(N=>N.targetPeerId===e.entryServiceId);if(!C)throw new Error("邀请缺少入口信息。");if((await(await y(C)).request({type:"route-pair",code:e.routeCode})).serviceId!==e.targetPeerId)throw new Error("邀请的目标服务不一致。");e.routeOnly&&await on({id:e.targetPeerId,url:s,label:e.serviceName||new URL(s).host,targetPeerId:e.targetPeerId,serviceOrigin:s,routes:l})}const x=[],w=async(C,B)=>{const k=()=>C.close();B.addEventListener("abort",k,{once:!0});try{if(B.aborted||(await zr(C),B.aborted))throw B.reason}catch(N){throw C.close(),N}finally{B.removeEventListener("abort",k)}};for(const C of d)x.push({key:`direct:${C}`,run:async B=>{const k=await zn({url:Wn(C),targetPeerId:e.targetPeerId,pairingCode:p,identity:o,signal:AbortSignal.any([B,AbortSignal.timeout(8e3)])});return p=void 0,await w(k,B),{client:k,path:"direct"}}});for(const C of l)x.push({key:`relay:${C.targetPeerId}:${C.url}`,run:async B=>{let k,N;try{if(k=await y(C,B),B.aborted)throw B.reason;const L=await k.request({type:"route-ticket",serviceId:e.targetPeerId},{timeoutMs:5e3}).catch(F=>{throw em(F,{targetServiceId:e.targetPeerId,entryServiceId:C.targetPeerId,entryUrl:C.url})});if(B.aborted)throw B.reason;if(typeof L.routeToken!="string"||!L.routeToken)throw new Error("入口未允许此设备连接该服务。");const D=new URL(Wn(C.url));return D.pathname="/api/federation/relay",D.searchParams.set("routeToken",L.routeToken),N=await zn({url:D.href,targetPeerId:e.targetPeerId,pairingCode:p,identity:o,socketFactory:tm(e.targetPeerId,{entryServiceId:C.targetPeerId,entryUrl:C.url}),signal:AbortSignal.any([B,AbortSignal.timeout(Ml)])}),p=void 0,await w(N,B),{client:N,entry:k,path:"relay"}}catch(L){throw N?.close(),k&&k!==r&&k!==n&&k.close(),yi(L,{targetServiceId:e.targetPeerId,...L instanceof ct&&L.code==="RELAY_AUTHORIZATION_REQUIRED"?{entryServiceId:C.targetPeerId,entryUrl:C.url}:{}})||L}}});const I=rm(e.targetPeerId);x.sort((C,B)=>+(B.key===I)-+(C.key===I));const R=await om(x,C=>{C.client.close(),C.entry&&C.entry!==n&&C.entry!==r&&C.entry.close()},!!p);if(u=R.value.client,f=R.value.entry,g=R.value.path,t.renewIfCurrent){if(ae!==t.renewIfCurrent||n!==t.renewIfCurrent||n.closed||!n.canSwitchTransport||te()?.targetPeerId!==e.targetPeerId){u.close();for(const C of m)C!==st&&C!==ae&&C.close();return ae??n}ae=u,Mr=g,st=f,Qc(e.targetPeerId,R.key),n.retire();for(const C of new Set([r,...m]))C&&C!==n&&C!==u&&C!==f&&C.close();return window.dispatchEvent(new Event(Et)),u}if(Qc(e.targetPeerId,R.key),ae!==n&&ae&&!ae.closed&&ae.targetPeerId===e.targetPeerId){u.close();for(const C of m)C!==st&&C.close();return ae}g==="direct"&&new URL(s).host===location.host&&my(e.targetPeerId);const S=(await Ve()).find(C=>C.targetPeerId===e.targetPeerId||!C.targetPeerId&&(C.serviceOrigin||C.url)===s),A=S?.label||e.serviceName||new URL(s).host,T=c.find(C=>No(C)===R.key),v=a.routes??Bt(a),E={url:s,targetPeerId:e.targetPeerId,serviceName:A,serviceOrigin:s,routes:T?[...v,T]:v};if(await(t.rememberOnly?yy:on)({id:S?.id||e.targetPeerId,...E,label:A}),yr!=="unpaired"&&yr!==e.targetPeerId&&$t()&&bi({id:S?.id||e.targetPeerId,...E,label:A})){u.close();for(const C of m)C!==n&&C!==r&&C.close();return n||u}$h(E),ae=u,Mr=g,st=f;for(const C of new Set([n,r,...m]))C&&C!==u&&C!==f&&C.close();return yr!==e.targetPeerId?(location.reload(),new Promise(()=>{})):(window.dispatchEvent(new Event(Et)),u)}catch(x){u?.close();for(const w of m)w!==r&&w.close();throw x}}async function hI(){const e=ae,t=te();if(!(t&&xn.has(t.targetPeerId))&&!(Fs||Os||pr||!e?.renewalDue||!e.canSwitchTransport||!t||performance.now()-Sf<3e4)){Sf=performance.now(),Fs=!0;try{await Pt(t,{renewIfCurrent:e})}catch(n){console.debug("[connection] renewal deferred",{reason:n instanceof Error?n.message:"unknown"})}finally{Fs=!1}}}async function pI(){const e=ae,t=te();if(t&&xn.has(t.targetPeerId)||Date.now()-vf<6e4||Fs||Os||Mr!=="relay"||!e||e.closed||!e.canSwitchTransport||!t?.serviceOrigin)return;Os=!0,vf=Date.now();let n;try{for(const o of Jn(t))try{n=await zn({url:Wn(o),targetPeerId:t.targetPeerId,identity:await Ct(),signal:AbortSignal.timeout(3e3)}),await zr(n);break}catch(s){if(n?.close(),n=void 0,s instanceof gt)throw s}if(!n||ae!==e||!e.canSwitchTransport)return;const r=st;ae=n,n=void 0,st=void 0,Mr="direct",e.close(),r?.close(),window.dispatchEvent(new Event(Et))}catch(r){r instanceof gt&&ae===e&&(wd(),window.dispatchEvent(new Event("auth:unauthorized")))}finally{n?.close(),Os=!1}}function gI(){return Mr}async function hm(e){return e?(e.throwIfAborted(),new Promise((t,n)=>{const r=()=>n(e.reason);e.addEventListener("abort",r,{once:!0}),St().then(o=>{e.removeEventListener("abort",r),e.aborted?n(e.reason):t(o)},o=>{e.removeEventListener("abort",r),n(o)})})):St()}async function St(){const e=xn.get(te()?.targetPeerId||"");if(e)throw e;if(ae&&!ae.closed){const n=ae;return hI(),n}if(ae=void 0,pr)return pr;const t=te();if(!t)throw new Error("DEVICE_PAIRING_REQUIRED");return pr=Pt(t,{rememberOnly:!0}).catch(n=>{if(ae&&!ae.closed&&ae.targetPeerId===t.targetPeerId)return ae;const r=yi(n,{targetServiceId:t.targetPeerId});throw r?(ol(r),r):n}).finally(()=>{pr=void 0}),pr}function pm(e){const t=new URL(e,location.href);if(ae&&!ae.closed&&!xn.has(ae.targetPeerId))return ae.openSocket(t.pathname+t.search);let n;const r=new Jc(e,o=>n?.send(o),()=>n?.close(),()=>n?.bufferedAmount??0);return St().then(o=>{r.readyState!==3&&(n=o.openSocket(t.pathname+t.search),r.getConnectionDiagnostics=()=>{const s=n?.getConnectionDiagnostics?.();return s?{...s,socketOpenMs:r.openedAfterMs}:void 0},n.onopen=()=>r.accept({type:"ws-ready",id:""}),n.onmessage=s=>r.accept({type:"ws-data",id:"",data:s.data}),n.onclose=s=>r.accept({type:"ws-close",id:"",code:s.code,reason:s.reason}),n.onerror=()=>r.fail(new Error("Encrypted connection unavailable")))}).catch(o=>r.fail(o)),r}function mI(){G1(St),window.fetch=async(e,t)=>{const n=new URL(e instanceof Request?e.url:String(e),location.href);if(!n.pathname.startsWith("/api/"))return jr(e,t);if(n.origin!==location.origin)throw new Error("Remote business API requires a paired encrypted service");if(n.pathname==="/api/meta")return jr(e,t);if(n.pathname==="/api/auth/status"){if(!te()){const s=await dm();return Response.json({enabled:s.enabled,authenticated:!1})}try{const s=await zr(await St());return Response.json({enabled:s.grants.length>0,authenticated:!0})}catch(s){if(s instanceof gt)return Response.json({enabled:!0,authenticated:!1});throw s}}if(n.pathname==="/api/auth/login"){const i=await new Request(e instanceof Request?e:n.href,t).json();return dI(typeof i.password=="string"?i.password:"")}if(n.pathname==="/api/csrf-token")return Response.json({csrfToken:"encrypted-device-channel"});if(n.pathname==="/api/auth/logout")return ae&&!ae.closed&&await ae.request({type:"logout"}),ae?.close(),st?.close(),ae=void 0,st=void 0,gy(),location.reload(),Response.json({ok:!0});const r=t?.signal!==void 0?t.signal:e instanceof Request?e.signal:void 0,o=await hm(r);return e instanceof Request?o.fetch(e,t):o.fetch(n.pathname+n.search,t)}}function Ur(e,t){if(e===t)throw new ct("RELAY_SELF_TARGET",{entryServiceId:e,targetServiceId:t})}async function Wr(e,t){const n=Ne(e.url),r=[ae,st].find(c=>c&&!c.closed&&c.targetPeerId===e.targetPeerId);if(r)return{client:r,route:{...e,url:n},release(){}};const o=t??(await Ve()).find(c=>c.targetPeerId===e.targetPeerId),s=[...o?.routes??[]];o?.targetPeerId&&Ne(o.serviceOrigin||o.url)!==n&&s.push({url:o.serviceOrigin||o.url,targetPeerId:e.targetPeerId});let i={...e,url:n};const a=await Xi({url:n,targetPeerId:e.targetPeerId,routes:s},AbortSignal.timeout(15e3),{connected(c){c.startsWith("direct:")&&(i={...e,url:c.slice(7)})}});return{client:a,route:i,release(){a.close()}}}async function wI(e){if(!e.targetPeerId)throw new Error("请先连接这台服务,再查看可中转的服务。");const t=await Wr({url:e.serviceOrigin||e.url,targetPeerId:e.targetPeerId},e);try{const n=await t.client.request({type:"route-targets"},{timeoutMs:5e3});if(!Array.isArray(n.items))throw new Error("入口服务需要更新后才能查看中转列表。");const r=new Set,o=n.items.filter(s=>!s||typeof s.serviceId!="string"||!s.serviceId||s.serviceId===t.client.targetPeerId||r.has(s.serviceId)?!1:(r.add(s.serviceId),!0));return{route:t.route,canManage:n.canManage===!0,items:o}}catch(n){throw n instanceof Error&&/UNKNOWN|UNSUPPORTED/i.test(n.message)?new Error("入口服务需要更新后才能查看中转列表。",{cause:n}):n}finally{t.release()}}async function yI(e,t){Ur(e.targetPeerId,t);const n=await Wr(e),r=n.client;try{Ur(r.targetPeerId,t);const o=await r.request({type:"route-targets"},{timeoutMs:5e3}),s=(Array.isArray(o.items)?o.items:[]).find(l=>l.serviceId===t);if(!s)throw new Error("该服务已不可见,请刷新列表或请入口管理员授权。");if(!s.available)throw new Error("入口暂时无法中转到这台服务,请稍后重试。");const i=(await Ve()).find(l=>l.targetPeerId===s.serviceId),a=[e,...(i?.routes||[]).filter(l=>l.targetPeerId!==e.targetPeerId||Ne(l.url)!==Ne(e.url))];if(a.length>4)throw new Error("这台服务已保存 4 个备用连接,请先移除一个后重试。");if(!s.authorized){if(!o.canManage)throw new Error("请先让入口管理员授权此设备。");await r.request({type:"route-grant",serviceId:s.serviceId,subjectId:(await Ct()).peerId})}const c=i?.serviceOrigin||i?.url||s.url||e.url;return{url:c,serviceOrigin:c,targetPeerId:s.serviceId,serviceName:i?.label||s.label||(s.url?new URL(s.url).host:`中转服务 ${s.serviceId.slice(0,8)}`),routes:a}}finally{n.release()}}async function La(e,t){Ur(e.targetPeerId,t);const n=await Wr(e),r=n.client;try{const o=await r.request({type:"route-access"},{timeoutMs:5e3}),s=(await Ct()).peerId;return{canManage:o.canManage===!0,grants:(Array.isArray(o.grants)?o.grants:[]).filter(i=>i.subjectId===s&&i.targetServiceId===t)}}finally{n.release()}}async function xf(e,t,n){if(Ur(t.targetPeerId,e.targetPeerId),n!==void 0&&(await yd(Ne(t.url),n)).targetPeerId!==t.targetPeerId)throw new Error("入口服务的身份已改变,请重新连接并确认。");const r=await Wr(t),o=r.client;try{await o.request({type:"route-grant",serviceId:e.targetPeerId,subjectId:(await Ct()).peerId,url:Ne(e.serviceOrigin||e.url)})}finally{r.release()}}async function bI(e,t){const n=await Wr(t),r=n.client;try{const o=await r.request({type:"route-access"},{timeoutMs:5e3}),s=(await Ct()).peerId,i=(Array.isArray(o.grants)?o.grants:[]).filter(a=>a.subjectId===s&&a.targetServiceId===e&&a.active);for(const a of i)await r.request({type:"route-revoke",grantId:a.id})}finally{n.release()}}async function gm(e,t){Ur(t.targetPeerId,e.targetPeerId);const n=await Wr(t),r=n.client;try{const o=await r.request({type:"route-invite-create",serviceId:e.targetPeerId});if(typeof o.routeCode!="string"||typeof o.expiresAt!="number")throw new Error("暂时无法生成备用连接邀请。");return{routeCode:o.routeCode,expiresAt:o.expiresAt}}finally{n.release()}}async function Ms(e,t){const n=(await Ve()).find(o=>o.id===e.id||e.targetPeerId&&o.targetPeerId===e.targetPeerId)||e;await on({...n,url:n.serviceOrigin||n.url,entryServiceId:void 0,routes:t});const r=te();r&&r.targetPeerId===e.targetPeerId&&$h({...r,url:r.serviceOrigin||r.url,entryServiceId:void 0,routes:t})}async function vI(e,t){const n=e.targetPeerId;if(!n)throw new Error("请先连接这台服务,再添加备用地址。");let r;try{r=Ne(t)}catch{throw new Error("请输入有效的 HTTPS 地址,例如 https://电脑地址:9834。")}const o=async()=>(await Ve()).find(a=>a.targetPeerId===n)||e,s=a=>{const c=a.routes??Bt({...a,targetPeerId:n});if(Ne(a.serviceOrigin||a.url)===r||c.some(l=>Ne(l.url)===r))throw new Error("这个地址已经在连接列表中。");if(c.length>=4)throw new Error("最多保存 4 个备用地址或入口,请先移除不再使用的连接。");return[...c,{url:r,targetPeerId:n}]};s(await o());let i;try{try{i=await zn({url:Wn(r),targetPeerId:n,identity:await Ct(),signal:AbortSignal.timeout(5e3)}),await zr(i)}catch(l){throw l instanceof gt?new Error("这台服务尚未授权当前设备,请先恢复设备授权。"):new Error("无法验证这个地址。请确认能访问该地址、HTTPS 证书受信任,且运行的是同一台 Termdock 服务。")}const a=await o(),c=s(a);if(await Ms(a,c),te()?.targetPeerId===n&&yr===n&&(!ae||ae.closed)){const l=ae,d=st;ae=i,i=void 0,st=void 0,Mr="direct",l?.close(),d?.close(),window.dispatchEvent(new Event(Et))}return c}finally{i?.close()}}async function If(e,t){await sl(e,t),await Pt({...e,pairingCode:void 0,routeCode:void 0})}function SI(){let e=!1,t=!1,n=!1,r;const o=new Map,s=new Set,i=new Map,a=async(f,p,g)=>{const m=JSON.stringify(g);if(o.get(p.serviceId)===m)return;const b=AbortSignal.timeout(1e4),y=await f.fetch("/api/csrf-token",{signal:b});if(!y.ok)throw new Error("CONNECTION_AUTHORIZATION_REQUIRED");const x=await y.json();if(typeof x.csrfToken!="string")throw new Error("INVALID_CSRF_TOKEN");const w=await f.fetch("/api/terminal/operations/collaboration-connections",{method:"POST",signal:b,headers:{"Content-Type":"application/json","X-XSRF-TOKEN":x.csrfToken},body:JSON.stringify({origin:p.origin,nodes:g})});if(!w.ok){const I=await w.json().catch(()=>({}));throw new Error(I.error||`HTTP_${w.status}`)}o.set(p.serviceId,m)},c=async()=>{if(e){n=!0;return}const f=te(),p=At();if(!(t||!f||!p||p.closed)){e=!0,n=!1;try{let g;const m=await Promise.race([Ve(),new Promise((R,S)=>{g=setTimeout(()=>S(new Error("SERVICE_DIRECTORY_TIMEOUT")),8e3)})]).finally(()=>clearTimeout(g));m.some(R=>R.targetPeerId===f.targetPeerId)||m.push({...f,id:f.targetPeerId,label:f.serviceName||f.url});const b=[...new Map(m.filter(R=>!!R.targetPeerId).map(R=>[R.targetPeerId,R])).values()].slice(0,64);if(b.length<2)return;const y=[];for(const R of b)try{const S=`${R.targetPeerId}:${R.serviceOrigin||R.url}`;let A=i.get(S);if(!A){const T=R.targetPeerId===f.targetPeerId?(await p.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node:await uI({...R,targetPeerId:R.targetPeerId},AbortSignal.timeout(8e3));if(T?.serviceId!==R.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");const v=T.origin||R.serviceOrigin||R.url,E=new URL(v);if(E.protocol!=="https:"||E.origin!==v)throw new Error("INVALID_SERVICE_ORIGIN");A={serviceId:T.serviceId,origin:v,...T.caFingerprint256?{caFingerprint256:T.caFingerprint256}:{}},i.set(S,A)}y.push({service:R,node:A})}catch{}if(t||At()!==p||te()?.targetPeerId!==f.targetPeerId)return;const x=y.find(R=>R.node.serviceId===f.targetPeerId);if(!x||y.length<2){l(3e4);return}const w=y.map(R=>R.node).sort((R,S)=>R.serviceId.localeCompare(S.serviceId));await a(p,x.node,w);let I=y.length<b.length;for(const R of y){if(R===x||o.get(R.node.serviceId)===JSON.stringify(w))continue;let S;try{S=await fI({...R.service,targetPeerId:R.node.serviceId},AbortSignal.timeout(8e3)),await a(S,R.node,w)}catch{let A=s.has(R.node.serviceId);if(!A&&S)try{(await S.request({type:"collaboration-scoped-peer",origin:R.node.origin,node:x.node},{timeoutMs:8e3})).type==="result"&&(s.add(R.node.serviceId),A=!0)}catch{}A||(I=!0)}finally{S?.close()}}window.dispatchEvent(new CustomEvent("termdock:collaboration-enrollment",{detail:{ok:!0}})),I&&l(3e4)}catch(g){window.dispatchEvent(new CustomEvent("termdock:collaboration-enrollment",{detail:{ok:!1,error:g instanceof Error?g.message:"CONNECTION_ENROLLMENT_FAILED"}})),l(3e4)}finally{e=!1,n&&l(100)}}};function l(f=100){t||(clearTimeout(r),r=setTimeout(()=>{c()},f))}const d=()=>{l()},u=Di(d);window.addEventListener(Et,d),window.addEventListener("termdock:collaboration-enroll",d),window.addEventListener("online",d),window.addEventListener("pageshow",d),window.addEventListener("pagehide",f=>{f.persisted||(t=!0,clearTimeout(r),u(),window.removeEventListener("termdock:collaboration-enroll",d),window.removeEventListener(Et,d),window.removeEventListener("online",d),window.removeEventListener("pageshow",d))}),l()}var Es={},Af;function EI(){if(Af)return Es;Af=1;var e=iy();return Es.createRoot=e.createRoot,Es.hydrateRoot=e.hydrateRoot,Es}var xI=EI();const II=Uh(xI);function lt({size:e=16,className:t="",...n}){const r=!!(n["aria-label"]||n["aria-labelledby"]);return h.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none","aria-hidden":r?void 0:!0,role:r?"img":void 0,focusable:"false",...n,className:`td-loading-spinner animate-spin ${t.replace(/\b(?:animate-spin|service-spinning)\b/g,"")}`,children:h.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2.5",strokeDasharray:"18 44.8",strokeLinecap:"round"})})}function AI(){return h.jsx("span",{className:"td-loading-dots","aria-hidden":"true",children:[0,1,2].map(e=>h.jsx("span",{style:{animationDelay:`${(e-3)*400}ms`}},e))})}function H2({label:e,className:t="",dots:n=!1}){return h.jsxs("div",{role:"status","aria-live":"polite","aria-atomic":"true",className:`flex items-center justify-center gap-2 text-sm text-muted-foreground ${t}`,children:[n?h.jsx(AI,{}):h.jsx(lt,{size:18}),h.jsx("span",{children:e})]})}const mm=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();const CI=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const RI=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());const Cf=e=>{const t=RI(e);return t.charAt(0).toUpperCase()+t.slice(1)};var Ba={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 kI=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},TI=P.createContext({}),PI=()=>P.useContext(TI),NI=P.forwardRef(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:o="",children:s,iconNode:i,...a},c)=>{const{size:l=24,strokeWidth:d=2,absoluteStrokeWidth:u=!1,color:f="currentColor",className:p=""}=PI()??{},g=r??u?Number(n??d)*24/Number(t??l):n??d;return P.createElement("svg",{ref:c,...Ba,width:t??l??Ba.width,height:t??l??Ba.height,stroke:e??f,strokeWidth:g,className:mm("lucide",p,o),...!s&&!kI(a)&&{"aria-hidden":"true"},...a},[...i.map(([m,b])=>P.createElement(m,b)),...Array.isArray(s)?s:[s]])});const Qe=(e,t)=>{const n=P.forwardRef(({className:r,...o},s)=>P.createElement(NI,{ref:s,iconNode:t,className:mm(`lucide-${CI(Cf(e))}`,`lucide-${e}`,r),...o}));return n.displayName=Cf(e),n};const LI=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],wm=Qe("arrow-left",LI);const BI=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],DI=Qe("arrow-right",BI);const _I=[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]],OI=Qe("arrow-up-right",_I);const FI=[["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"}]],ym=Qe("bell-dot",FI);const MI=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Si=Qe("check",MI);const jI=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],bm=Qe("chevron-down",jI);const UI=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Gn=Qe("chevron-right",UI);const HI=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],$I=Qe("chevron-up",HI);const qI=[["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"}]],vm=Qe("copy",qI);const KI=[["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"}]],Sm=Qe("ellipsis",KI);const zI=[["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"}]],WI=Qe("monitor",zI);const GI=[["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"}]],VI=Qe("pencil",GI);const YI=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Em=Qe("plus",YI);const XI=[["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"}]],Zi=Qe("server",XI);const ZI=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],xm=Qe("smartphone",ZI);const JI=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],QI=Qe("terminal",JI);const eA=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Im=Qe("x",eA),tA={},Rf=e=>{let t;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(t):d;if(!Object.is(f,t)){const p=t;t=u??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(g=>g(t,p))}},o=()=>t,c={setState:r,getState:o,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(tA?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},l=t=e(r,o,c);return c},nA=e=>e?Rf(e):Rf;var Da={exports:{}},_a={},Oa={exports:{}},Fa={};var kf;function rA(){if(kf)return Fa;kf=1;var e=Ol();function t(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,s=e.useLayoutEffect,i=e.useDebugValue;function a(u,f){var p=f(),g=r({inst:{value:p,getSnapshot:f}}),m=g[0].inst,b=g[1];return s(function(){m.value=p,m.getSnapshot=f,c(m)&&b({inst:m})},[u,p,f]),o(function(){return c(m)&&b({inst:m}),u(function(){c(m)&&b({inst:m})})},[u]),i(p),p}function c(u){var f=u.getSnapshot;u=u.value;try{var p=f();return!n(u,p)}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 Fa.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:d,Fa}var Tf;function oA(){return Tf||(Tf=1,Oa.exports=rA()),Oa.exports}var Pf;function sA(){if(Pf)return _a;Pf=1;var e=Ol(),t=oA();function n(l,d){return l===d&&(l!==0||1/l===1/d)||l!==l&&d!==d}var r=typeof Object.is=="function"?Object.is:n,o=t.useSyncExternalStore,s=e.useRef,i=e.useEffect,a=e.useMemo,c=e.useDebugValue;return _a.useSyncExternalStoreWithSelector=function(l,d,u,f,p){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 y(S){if(!x){if(x=!0,w=S,S=f(S),p!==void 0&&m.hasValue){var A=m.value;if(p(A,S))return I=A}return I=S}if(A=I,r(w,S))return A;var T=f(S);return p!==void 0&&p(A,T)?(w=S,A):(w=S,I=T)}var x=!1,w,I,R=u===void 0?null:u;return[function(){return y(d())},R===null?void 0:function(){return y(R())}]},[d,u,f,p]);var b=o(l,g[0],g[1]);return i(function(){m.hasValue=!0,m.value=b},[b]),c(b),b},_a}var Nf;function iA(){return Nf||(Nf=1,Da.exports=sA()),Da.exports}var aA=iA();const cA=Uh(aA),Am={},{useDebugValue:lA}=vt,{useSyncExternalStoreWithSelector:dA}=cA;let Lf=!1;const uA=e=>e;function fA(e,t=uA,n){(Am?"production":void 0)!=="production"&&n&&!Lf&&(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"),Lf=!0);const r=dA(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return lA(r),r}const Bf=e=>{(Am?"production":void 0)!=="production"&&typeof e!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const t=typeof e=="function"?nA(e):e,n=(r,o)=>fA(t,r,o);return Object.assign(n,t),n},Ji=e=>e?Bf(e):Bf,Ei=e=>`@collaboration:${e}`,Cm=Ji(e=>({activePaneId:null,setActivePane:t=>e({activePaneId:t}),docks:{},hosts:{},setDock:(t,n)=>e(r=>{const o={...r.docks};return n?o[t]=n:delete o[t],{docks:o,...!n&&r.activePaneId===Ei(t)?{activePaneId:r.docks[t]?.sessionId??null}:{}}}),setHost:(t,n)=>e(r=>{const o={...r.hosts};return n?o[t]=n:delete o[t],{hosts:o}})})),_n=new Map;let xi;function Rm(){const e=Cm.getState().activePaneId,t=_n.get(xi??"");if(t?.requiresFocus&&e===Ei(t.paneKey))return t.receive;for(const n of _n.values())if(n.requiresFocus&&e===Ei(n.paneKey))return n.receive;return t&&!t.requiresFocus?t.receive:void 0}function hA(e){const t=_n.get(e);t&&(xi=e,Cm.getState().setActivePane(t.requiresFocus?Ei(t.paneKey):null))}function pA(e){const t=Rm();return!t||!e?!1:(t(e),!0)}function $2(e,t="default",n=!1,r=t){_n.set(t,{receive:e,requiresFocus:n,paneKey:r}),n||hA(t);const o=s=>{const{text:i,nonce:a}=s.detail??{};!i||Rm()!==e||(e(i),s.stopImmediatePropagation(),a&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:a,ok:!0}})))};return window.addEventListener("termdock-insert-reference",o,!0),()=>{_n.get(t)?.receive===e&&(_n.delete(t),xi===t&&(xi=[..._n.keys()].at(-1))),window.removeEventListener("termdock-insert-reference",o,!0)}}const gA=/^[A-Za-z0-9_@%+=:,./-]$/;function mA(e){return Array.from(e,t=>(t.codePointAt(0)??0)>127||gA.test(t)?t:`\\${t}`).join("")}let wA=0;function yA(e,t){if(!t)return!1;try{const n=new URL(t.serviceOrigin||t.url);return n.origin===e&&/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})$/.test(n.hostname)&&!(t.routes??[]).some(r=>r.targetPeerId!==t.targetPeerId)}catch{return!1}}function bA(e,t=!0){const n=new Set,r=new Set,o=new WeakMap,s=l=>l.target instanceof Element?l.target.closest("[data-termdock-terminal-dropzone]"):null,i=()=>!t||!yA(location.origin,at()),a=l=>{const d=s(l);!d||!i()||!l.dataTransfer?.types.includes("Files")||(l.preventDefault(),l.stopImmediatePropagation(),l.dataTransfer.dropEffect="copy",d.dataset.nativeFileDrag="true",d.dataset.nativeFileDropState="remote")},c=l=>{const d=s(l),u=Array.from(l.dataTransfer?.files??[]);if(!d||!u.length||!i())return;l.preventDefault(),l.stopImmediatePropagation(),o.get(d)?.abort();const f=new AbortController;o.set(d,f);const p=d.dataset.termdockTerminalDropzone??"",g=at(),m=d.dataset.termdockTerminalOwner,b=g?.targetPeerId??null,y=String(++wA),x=()=>!f.signal.aborted&&d.isConnected&&d.dataset.termdockTerminalDropzone===p&&d.dataset.nativeFileDropOperation===y&&at()===g&&at()?.targetPeerId===b&&d.dataset.termdockTerminalOwner===m,w=()=>x()?!1:(d.dataset.nativeFileDropOperation===y&&(delete d.dataset.nativeFileDrag,delete d.dataset.nativeFileDropState,delete d.dataset.nativeFileDropOperation,delete d.dataset.nativeFileDropProgress,delete d.dataset.nativeFileDropCancellable),!0);d.dataset.nativeFileDropOperation=y,d.dataset.nativeFileDrag="true",d.dataset.nativeFileDropState="uploading",d.dataset.nativeFileDropCancellable="true",delete d.dataset.nativeFileDropProgress;const I=v=>{(v?.type==="auth:unauthorized"||v?.type==="pagehide"||!x())&&(f.abort(),w())},R=new MutationObserver(()=>I());R.observe(d,{attributes:!0,attributeFilter:["data-termdock-terminal-dropzone","data-termdock-terminal-owner","data-native-file-drop-operation"]});const S=()=>{f.abort(),w(),T()},A=v=>{if(!(v.target instanceof Element)||v.target.closest("[data-termdock-terminal-dropzone]")!==d||!x())return;S(),d.dataset.nativeFileDrag="true",d.dataset.nativeFileDropOperation=y,d.dataset.nativeFileDropState="cancelled";const E=window.setTimeout(()=>{r.delete(E),d.dataset.nativeFileDropOperation===y&&d.dataset.nativeFileDropState==="cancelled"&&(delete d.dataset.nativeFileDrag,delete d.dataset.nativeFileDropState,delete d.dataset.nativeFileDropOperation)},3e3);r.add(E)};window.addEventListener("termdock:file-drop-cancel",A);const T=()=>{window.removeEventListener("termdock:file-drop-cancel",A),R.disconnect();for(const v of["termdock:secure-state","auth:unauthorized","pagehide"])window.removeEventListener(v,I);n.delete(S)};n.add(S);for(const v of["termdock:secure-state","auth:unauthorized","pagehide"])window.addEventListener(v,I);An(async()=>{const{uploadFiles:v}=await Promise.resolve().then(()=>Nk);return{uploadFiles:v}},void 0).then(({uploadFiles:v})=>{if(!x())throw new DOMException("Drop target changed","AbortError");return v("/tmp",u,f.signal,E=>{x()&&(d.dataset.nativeFileDropProgress=String(Math.round(E)))},x)}).then(v=>{if(v.files.length!==u.length||v.files.some(C=>!C.path))throw new Error("Upload did not return every file path");if(w())return;delete d.dataset.nativeFileDropCancellable,delete d.dataset.nativeFileDropProgress,e({sessionKey:p,paths:v.files.map(C=>C.path)}),d.dataset.nativeFileDropState="uploaded";const E=window.setTimeout(()=>{r.delete(E),x()&&d.dataset.nativeFileDropState==="uploaded"&&(delete d.dataset.nativeFileDrag,delete d.dataset.nativeFileDropState,delete d.dataset.nativeFileDropOperation)},3e3);r.add(E)}).catch(v=>{if(w())return;delete d.dataset.nativeFileDropCancellable,delete d.dataset.nativeFileDropProgress,d.dataset.nativeFileDropState="error",d.dispatchEvent(new CustomEvent("termdock:file-drop-error",{bubbles:!0,detail:v instanceof Error?v.message:"File upload failed"}));const E=window.setTimeout(()=>{r.delete(E),x()&&d.dataset.nativeFileDropState==="error"&&(delete d.dataset.nativeFileDrag,delete d.dataset.nativeFileDropState,delete d.dataset.nativeFileDropOperation)},3e3);r.add(E)}).finally(T)};return window.addEventListener("dragover",a,!0),window.addEventListener("drop",c,!0),()=>{window.removeEventListener("dragover",a,!0),window.removeEventListener("drop",c,!0);for(const l of n)l();for(const l of r)clearTimeout(l);r.clear()}}function mt(){return typeof window>"u"?null:window.termdockDesktop??null}const Ma=new Set;let Df=!1;function q2(e){const t=mt();if(Ma.add(e),!Df){const n=r=>{if(!pA(r.paths.map(mA).join(" ")+" "))for(const o of Ma)o(r)};bA(n,!!t),t?.onNativeFileDrop(n),Df=!0}return()=>{Ma.delete(e)}}function km(e=navigator.userAgent,t=navigator.maxTouchPoints){const n=/iPad/.test(e)||/Macintosh/.test(e)&&t>1?"iPad":/iPhone/.test(e)?"iPhone":/Android/.test(e)?"Android":/Windows/.test(e)?"Windows":/Macintosh|Mac OS X/.test(e)?"Mac":/Linux/.test(e)?"Linux":"设备",r=/Electron/.test(e)?"Termdock":/Edg\//.test(e)?"Edge":/Firefox|FxiOS/.test(e)?"Firefox":/Chrome|CriOS/.test(e)?"Chrome":/Safari/.test(e)?"Safari":"浏览器";return`${n} · ${r}`}let vA;function SA(){return vA??=(async()=>{const e=navigator.userAgent,[t,n]=km().split(" · "),r=/(?:Edg|Firefox|FxiOS|Chrome|CriOS|Version)\/([\d.]+)/g,o=[...e.matchAll(r)],s=/(?:CPU (?:iPhone )?OS |Mac OS X |Android )([\d._]+)/.exec(e)?.[1]?.replaceAll("_","."),i={system:`${t}${s?` ${s}`:""}`,client:`${n}${o.length?` ${o.at(-1)[1]}`:""}`,mode:matchMedia("(display-mode: standalone)").matches||navigator.standalone?"已安装的网页应用":"网页"},a=mt();if(a){i.mode="桌面客户端";const l=/Electron\/([\d.]+)/.exec(e)?.[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})()}const ut=[],il=new Set,_f=()=>il.forEach(e=>e()),EA=()=>ut.length>0,xA=()=>ut[ut.length-1]??null;function K2(e){const t=xA(),n=t?bd(t.element):[document.body];return e.isConnected&&!e.closest('[hidden], [inert], [aria-hidden="true"]')&&(!t||n.some(r=>r.contains(e)))&&Tm(e,n)}function z2(){return P.useSyncExternalStore(e=>(il.add(e),()=>{il.delete(e)}),EA,()=>!1)}function bd(e){const t=Array.from(document.querySelectorAll("[data-sidebar-composer-popover]")).filter(n=>e.id&&n.dataset.sidebarComposerPopover===e.id);return[e,...t]}function Tm(e,t){for(let n=e;n;n=n.parentElement){const r=getComputedStyle(n);if(r.display==="none"||r.visibility==="hidden")return!1;if(t.includes(n))break}return!0}function Of(e){const t=bd(e);return t.flatMap(n=>Array.from(n.querySelectorAll("button:not(:disabled), input:not(:disabled), textarea:not(:disabled), select:not(:disabled), a[href], summary, [tabindex]"))).filter(n=>{const r=n.closest("details:not([open])"),o=r?.querySelector("summary");return n.tabIndex>=0&&!n.matches(":disabled")&&!n.closest('[hidden], [inert], [aria-hidden="true"]')&&(!r||!!o?.contains(n))&&Tm(n,t)})}function Pm(e,t,n,r){const o=P.useRef(n);o.current=n;const s=P.useRef(r);s.current=r,P.useLayoutEffect(()=>{const i=e.current;if(!t||!i)return;const a=document.activeElement instanceof HTMLElement?document.activeElement:null,c={element:i},l=ut.findIndex(b=>i.contains(b.element));l<0?ut.push(c):ut.splice(l,0,c),_f();const d=()=>ut[ut.length-1]===c,u=b=>b instanceof Node&&bd(i).some(y=>y.contains(b)),f=()=>(Of(i)[0]??i).focus({preventScroll:!0});d()&&f();const p=b=>{d()&&!u(b.target)&&f()},g=b=>{if(!d()||b.key!=="Tab"||b.defaultPrevented)return;const y=Of(i),x=y[0],w=y[y.length-1];(!x||!u(document.activeElement)||(b.shiftKey?document.activeElement===x:document.activeElement===w))&&(b.preventDefault(),(b.shiftKey?w:x)?.focus({preventScroll:!0}))},m=b=>{!d()||b.key!=="Escape"||b.defaultPrevented||b.isComposing||(b.preventDefault(),b.stopImmediatePropagation(),o.current())};return document.addEventListener("focusin",p,!0),document.addEventListener("keydown",g,!0),document.addEventListener("keydown",m),()=>{const b=d();if(ut.splice(ut.indexOf(c),1),_f(),document.removeEventListener("focusin",p,!0),document.removeEventListener("keydown",g,!0),document.removeEventListener("keydown",m),b){const y=ut[ut.length-1];queueMicrotask(()=>{if(ut[ut.length-1]!==y)return;(a?.isConnected&&a!==document.body?a:s.current?.())?.focus({preventScroll:!0})})}}},[t,e])}function IA({service:e,onBusyChange:t,onConnect:n,onConnectWithPassword:r}){const[o,s]=P.useState(),[i,a]=P.useState(!0),[c,l]=P.useState(!1),[d,u]=P.useState(""),[f,p]=P.useState(0),[g,m]=P.useState(),[b,y]=P.useState("");P.useEffect(()=>{let I=!1,R=!1,S;a(!0),u(""),s(void 0);const A=async T=>{try{const v=await wI(e);if(I)return;R=!0,s(v),u("")}catch(v){!I&&(!R||T)&&u(v instanceof Error?v.message:"暂时无法读取中转列表,请重试。")}finally{I||(a(!1),S=setTimeout(()=>{A(!1)},2e3))}};return A(!0),()=>{I=!0,clearTimeout(S)}},[e.id,e.url,f]);const x=async I=>{if(!c){l(!0),t(!0),u("");try{await I()}catch(R){u(R instanceof Error?R.message:"暂时无法连接,请重试。")}finally{l(!1),t(!1)}}},w=async I=>{const R=await yI(o.route,I.serviceId);try{await n(R)}catch(S){if(!(S instanceof gt))throw S;m(R)}};return h.jsxs("div",{className:"service-form",children:[g?h.jsxs("form",{className:"service-form",onSubmit:I=>{I.preventDefault(),x(async()=>{try{await r?.(g,b)}finally{y("")}})},children:[h.jsxs("p",{className:"service-help",children:["已通过“",e.label,"”连接到“",g.serviceName,"”。请登录目标服务,完成此设备的访问授权。"]}),r?h.jsxs(h.Fragment,{children:[h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"目标服务密码"}),h.jsx("input",{type:"password",autoFocus:!0,required:!0,autoComplete:"current-password",value:b,disabled:c,onChange:I=>y(I.target.value)})]}),h.jsx("button",{type:"submit",className:"service-button service-primary",disabled:c||!b,children:c?"正在登录…":"登录并连接"})]}):h.jsx("p",{className:"service-help",children:"请让目标服务管理员邀请此设备后再连接。"}),h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>{m(void 0),y(""),u(""),p(I=>I+1)},children:"返回中转列表"})]}):h.jsxs(h.Fragment,{children:[h.jsxs("p",{className:"service-help",children:["通过“",e.label,"”连接下方服务。",o?.canManage?"选择未授权的服务会授权此设备使用该中转。":"这里只显示已授权给此设备的中转。","目标服务会单独验证访问权限。"]}),i?h.jsxs("p",{className:"service-feedback",role:"status",children:[h.jsx(lt,{size:16,className:"service-spinning"}),"正在读取可中转的服务…"]}):o&&h.jsxs("div",{className:"service-list",children:[o.items.map(I=>h.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:c||!I.available,onClick:()=>{x(()=>w(I))},children:[h.jsx("span",{className:"service-icon",children:h.jsx(Zi,{size:19})}),h.jsxs("span",{className:"service-row-copy",children:[h.jsx("span",{className:"service-name",children:I.label||(I.url?new URL(I.url).host:`中转服务 ${I.serviceId.slice(0,8)}`)}),h.jsx("span",{className:"service-description",children:I.available?I.authorized?"已获中转授权 · 连接":"授权此设备并连接":"中转暂不可用"})]}),h.jsx(Gn,{size:16})]},I.serviceId)),o.items.length===0&&h.jsx("p",{className:"service-empty",children:o.canManage?"暂无可中转的服务。可在本机 Mac 客户端连接目标服务,或在目标服务的“备用连接”中启用本入口。":"暂无已授权的中转服务,请让入口管理员分享备用连接邀请。"})]}),c&&h.jsxs("p",{className:"service-feedback",role:"status",children:[h.jsx(lt,{size:16,className:"service-spinning"}),"正在授权并连接目标服务…"]}),!i&&h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>p(I=>I+1),children:"刷新列表"})]}),d&&h.jsx("p",{className:"service-error",role:"alert",children:d})]})}const al="#termdock-invite=";function Nm(e){const t=new URL(e.entryUrl);t.hash="",t.search="",t.pathname="/";const n=new TextEncoder().encode(JSON.stringify(e));return t.hash=al.slice(1)+btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),t.href}function Un(e){const t=new URL(e);if(!["https:","http:"].includes(t.protocol)||!t.hash.startsWith(al))throw new Error("这不是有效的 Termdock 邀请链接");const n=t.hash.slice(al.length);if(n.length>8192)throw new Error("邀请链接过长");let r;try{const i=n.replace(/-/g,"+").replace(/_/g,"/");r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(atob(i),a=>a.charCodeAt(0))))}catch{throw new Error("邀请链接不完整,请重新复制")}if(r.v!==1||typeof r.serviceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(r.serviceId)||r.routeOnly!==!0&&(typeof r.code!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(r.code)))throw new Error("邀请信息无效或版本不兼容");const o=new URL(r.entryUrl);if(o.origin!==t.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(r.entryServiceId!==void 0&&(typeof r.entryServiceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(r.entryServiceId)))throw new Error("邀请入口身份无效");if(r.routeCode!==void 0&&(typeof r.routeCode!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(r.routeCode)||!r.entryServiceId))throw new Error("邀请入口权限无效");if(r.routeOnly===!0&&(!r.entryServiceId||!r.routeCode||r.code!==void 0))throw new Error("备用连接邀请不完整");let s=o.origin;if(r.serviceUrl!==void 0){const i=new URL(r.serviceUrl);if(!["https:","http:"].includes(i.protocol)||i.username||i.password)throw new Error("目标服务地址无效");s=r.entryServiceId&&r.entryServiceId!==r.serviceId?i.origin:o.origin}return{url:o.origin,targetPeerId:r.serviceId,pairingCode:r.code,...r.routeOnly===!0?{routeOnly:!0}:{},serviceOrigin:s,serviceName:typeof r.name=="string"?r.name.slice(0,120):void 0,entryServiceId:r.entryServiceId,routeCode:r.routeCode}}function Lm({service:e,onBusyChange:t,recoverEntry:n,onRecovered:r,onCancelRecovery:o}){const s={...e,targetPeerId:e.targetPeerId,serviceName:e.label},[i,a]=P.useState(()=>e.routes??Bt(s)),[c,l]=P.useState([]),[d,u]=P.useState(!0),[f,p]=P.useState(!1),[g,m]=P.useState(""),b=M=>{p(M),t(M)},[y,x]=P.useState(),[w,I]=P.useState(""),[R,S]=P.useState(""),[A,T]=P.useState(""),[v,E]=P.useState(!1),[C,B]=P.useState(),k=async()=>{const M=await La(n,s.targetPeerId),$={canManage:M.canManage,active:M.grants.some(X=>X.active)};return B($),$};P.useEffect(()=>{if(!n)return;let M=!1;return La(n,s.targetPeerId).then($=>{M||B({canManage:$.canManage,active:$.grants.some(X=>X.active)})}).catch(()=>{M||m("无法核对入口授权,请检查连接或联系入口管理员。")}),()=>{M=!0}},[n?.targetPeerId,n?.url,s.targetPeerId]);const[N,L]=P.useState(),[D,F]=P.useState(),[O,_]=P.useState(!1);P.useEffect(()=>{let M=!1;return Ve().then($=>{M||l($.filter(X=>X.targetPeerId&&X.targetPeerId!==e.targetPeerId))}).catch(()=>{M||m("暂时无法读取可用服务。")}).finally(()=>{M||u(!1)}),()=>{M=!0}},[e.targetPeerId]);const H=M=>c.find($=>$.targetPeerId===M.targetPeerId)?.label||new URL(M.url).host,q=async M=>{b(!0),m(""),T("");try{await M()}catch($){const X=$ instanceof Error?$.message:"";m(/AUTHORIZATION|DENIED/.test(X)?"当前设备没有入口管理权限。请让管理员分享备用连接邀请,或使用入口密码授权。":"暂时无法完成。请确认入口能连接目标服务,且目标地址、证书和授权有效。")}finally{b(!1)}},j=async(M,$)=>{const X={url:M.serviceOrigin||M.url,targetPeerId:M.targetPeerId};await q(async()=>{const Q=await La(X,s.targetPeerId);if(!Q.grants.some(de=>de.active)){if(!Q.canManage&&$===void 0){x(M);return}await xf(s,X,$)}const oe=[...i.filter(de=>de.targetPeerId!==X.targetPeerId||de.url!==X.url),X];await Ms(e,oe),a(oe),x(void 0),I("")})};if(n)return h.jsxs("div",{className:"service-form",children:[h.jsxs("p",{className:"service-help",children:["仅恢复此设备通过“",H(n),"”连接“",e.label,"”的中转权限。目标服务会单独验证访问权限。"]}),!C&&!g&&h.jsx("p",{role:"status",children:"正在核对入口授权…"}),C&&!C.active&&!C.canManage&&h.jsxs("p",{role:"status",className:"service-help",children:["当前设备没有此入口的授权管理权限。请让入口管理员授予此设备到“",e.label,"”的中转权限或分享对应的备用连接邀请。"]}),C&&(C.active||C.canManage)&&h.jsx("button",{className:"service-button service-primary",disabled:f,onClick:()=>{q(async()=>{const M=await k();if(!M.active){if(!M.canManage)throw new Error("AUTHORIZATION_DENIED");await xf(s,n)}if(!(await k()).active)throw new Error("AUTHORIZATION_DENIED");await r?.()})},children:f?"正在核对并连接…":C.active?"核对授权并重新连接":"授权此设备并重新连接"}),g&&h.jsx("p",{role:"alert",className:"service-error",children:g}),h.jsx("button",{className:"service-button service-secondary",disabled:f,onClick:o,children:"取消"})]});if(D)return h.jsxs("div",{className:"service-form",children:[h.jsxs("p",{className:"service-help",children:["把链接发给需要使用此备用连接的人。它只允许通过入口连接“",e.label,"”,对方仍需获得目标服务的访问权限。"]}),h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"备用连接邀请"}),h.jsx("input",{readOnly:!0,value:D,onFocus:M=>M.target.select()})]}),h.jsxs("button",{type:"button",className:"service-button service-primary",onClick:()=>{navigator.clipboard.writeText(D).then(()=>_(!0)).catch(()=>m("无法自动复制,请长按链接复制。"))},children:[h.jsx(vm,{size:16}),O?"已复制":"复制邀请链接"]}),h.jsx("button",{type:"button",className:"service-button service-secondary",onClick:()=>{F(void 0),_(!1)},children:"返回备用连接"}),g&&h.jsx("p",{role:"alert",className:"service-error",children:g})]});if(y)return h.jsxs("form",{className:"service-form",onSubmit:M=>{M.preventDefault(),j(y,w).finally(()=>I(""))},children:[h.jsxs("p",{className:"service-help",children:["需要“",y.label,"”的管理员授权。若这是你的服务,可以使用它的密码;否则请管理员分享备用连接邀请。"]}),h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"入口服务密码"}),h.jsx("input",{type:"password",required:!0,value:w,onChange:M=>I(M.target.value),autoComplete:"current-password",disabled:f,autoFocus:!0})]}),h.jsx("button",{type:"submit",className:"service-button service-primary",disabled:f||!w,children:f?"正在授权…":"授权并启用"}),h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:f,onClick:()=>{x(void 0),I("")},children:"取消"}),g&&h.jsx("p",{role:"alert",className:"service-error",children:g})]});const K=i.filter(M=>M.targetPeerId===s.targetPeerId),G=i.filter(M=>M.targetPeerId!==s.targetPeerId),W=c.flatMap(M=>Jn({...M,targetPeerId:M.targetPeerId}).map($=>({...M,id:JSON.stringify([M.id,$]),url:$,serviceOrigin:$}))),Y=async()=>{if(!f){b(!0),E(!0),m(""),T("");try{a(await vI({...e,routes:i},R)),S(""),T("备用地址已验证并保存。")}catch(M){m(M instanceof Error?M.message:"暂时无法添加地址,请重试。")}finally{b(!1),E(!1)}}};return h.jsxs("div",{className:"service-form",children:[h.jsx("p",{className:"service-help",children:"电脑换了网络?添加它在新网络下的地址,原地址连不上时会自动尝试。只接受同一台服务。"}),h.jsxs("form",{className:"service-form",onSubmit:M=>{M.preventDefault(),Y()},children:[h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"备用地址"}),h.jsx("input",{value:R,onChange:M=>{S(M.target.value),m(""),T("")},required:!0,disabled:f||i.length>=4,inputMode:"url",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:192.168.10.20:9834"})]}),h.jsx("button",{type:"submit",className:"service-button service-primary",disabled:f||i.length>=4||!R.trim(),children:v?h.jsxs(h.Fragment,{children:[h.jsx(lt,{size:16,className:"service-spinning"}),"正在验证…"]}):"验证并添加"})]}),g&&h.jsx("p",{role:"alert",className:"service-error",children:g}),A&&h.jsx("p",{role:"status",className:"service-help",children:A}),i.length>=4&&h.jsx("p",{className:"service-help",children:"已保存 4 个备用连接。移除不再使用的地址或入口后,可以继续添加。"}),h.jsxs("div",{children:[h.jsx("p",{className:"service-help",children:"首选地址"}),h.jsx("p",{className:"service-address",children:e.serviceOrigin||e.url})]}),K.length>0&&h.jsx("div",{className:"service-list",children:K.map(M=>h.jsxs("div",{className:"service-route-item",children:[h.jsxs("div",{className:"service-route-line",children:[h.jsx("span",{className:"service-address service-route-address",children:M.url}),h.jsx("button",{type:"button",className:"service-icon-button","aria-label":`移除地址 ${M.url}`,disabled:f,onClick:()=>L(M),children:"移除"})]}),N?.targetPeerId===M.targetPeerId&&N.url===M.url&&h.jsxs("div",{className:"service-form",children:[h.jsx("p",{className:"service-help",children:"从备用连接中移除此地址?不会停止正在运行的终端。"}),h.jsxs("div",{className:"service-actions service-actions-pair",children:[h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:f,onClick:()=>L(void 0),children:"取消"}),h.jsx("button",{type:"button",className:"service-button service-danger",disabled:f,onClick:()=>{q(async()=>{const $=i.filter(X=>X.targetPeerId!==M.targetPeerId||X.url!==M.url);await Ms(e,$),a($),L(void 0)})},children:"确认移除"})]})]})]},M.url))}),h.jsxs("details",{className:"service-relay-options",children:[h.jsxs("summary",{children:["通过其他服务中转",G.length?`(${G.length})`:""]}),h.jsxs("div",{className:"service-form",children:[h.jsx("p",{className:"service-help",children:"所有直连地址都不可用时,尝试下方已授权入口;直连恢复后自动切回。"}),G.length>0&&h.jsx("div",{className:"service-list",children:G.map(M=>h.jsxs("div",{className:"service-route-item",children:[h.jsxs("div",{className:"service-route-line",children:[h.jsx("span",{className:"service-icon",children:h.jsx(Zi,{size:18})}),h.jsxs("span",{className:"service-row-copy",children:[h.jsx("span",{className:"service-name",children:H(M)}),h.jsx("span",{className:"service-description",children:M.url})]}),h.jsx(Si,{size:16,className:"service-selected"})]}),N?.targetPeerId===M.targetPeerId&&N.url===M.url?h.jsxs("div",{className:"service-form",children:[h.jsxs("p",{className:"service-help",children:["撤销此设备经“",H(M),"”所有地址连接目标的权限?如当前无法直连,目标服务将断开。"]}),h.jsxs("div",{className:"service-actions service-actions-pair",children:[h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:f,onClick:()=>L(void 0),children:"取消"}),h.jsx("button",{type:"button",className:"service-button service-danger",disabled:f,onClick:()=>{q(async()=>{await bI(s.targetPeerId,M);const $=i.filter(X=>X.targetPeerId!==M.targetPeerId);await Ms(e,$),a($),L(void 0)})},children:"确认撤销"})]})]}):h.jsxs("div",{className:"service-actions service-actions-pair",children:[h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:f,onClick:()=>{q(async()=>{const $=await gm(s,M);F(Nm({v:1,routeOnly:!0,serviceId:s.targetPeerId,name:e.label,serviceUrl:e.serviceOrigin||e.url,entryUrl:M.url,entryServiceId:M.targetPeerId,routeCode:$.routeCode}))})},children:"分享备用连接"}),h.jsx("button",{type:"button",className:"service-button service-danger",disabled:f,onClick:()=>L(M),children:"撤销授权"})]})]},JSON.stringify([M.targetPeerId,M.url])))}),d?h.jsxs("p",{role:"status",className:"service-feedback",children:[h.jsx(lt,{size:16,className:"service-spinning"}),"正在读取服务…"]}):h.jsxs("div",{children:[h.jsx("p",{className:"service-help",children:"添加中转入口"}),W.filter(M=>!i.some($=>$.targetPeerId===M.targetPeerId&&$.url===M.url)).map(M=>h.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:f||i.length>=4,onClick:()=>{j(M)},children:[h.jsxs("span",{className:"service-row-copy",children:[h.jsx("span",{className:"service-name",children:M.label}),h.jsx("span",{className:"service-description",children:M.url})]}),h.jsx(Gn,{size:16})]},M.id)),c.length===0&&h.jsx("p",{className:"service-empty",children:"添加并登录另一台服务后,可以将它设为中转入口。"})]})]})]}),f&&!v&&h.jsxs("p",{role:"status",className:"service-feedback",children:[h.jsx(lt,{size:16,className:"service-spinning"}),"正在验证连接与授权…"]})]})}const AA={architecture:{choosePaths:"Choose folders or files",browsePaths:"Browse",addScopeReference:"Add to analysis scope",searchScopePaths:"Search files or folders",useCurrentFile:"Use current file",useCurrentDirectory:"Use current folder",browsePathsHint:"Expand folders to browse. Use the reference button on a row to add it to the analysis scope.",correctPathsFirst:"Correct the entered paths before adding more scope.",pathsHint:"Choose scope or paste file/line references. Paths are relative to this project.",featureScopeHint:"Locate this feature within the selected scope first",removePath:"Remove path",chooseThisDirectory:"Select this folder",filterDirectory:"Filter this folder",loadingPaths:"Loading folder…",pathsLoadFailed:"Could not read this folder. Check connection or access, then retry.",noPaths:"No matching files or folders here.",pathsTruncated:"This folder has too many entries to show at once. Open a subfolder or paste its path directly.",selectedPaths:"Selected paths",usePaths:"Use selected scope",expandDetail:"Read module details",collapseDetail:"Collapse module details",backToMap:"Back to map",backToModule:"Back to module",previousModule:"Previous module",parentModule:"Back to parent",viewPrepared:"View this analysis",closeDetail:"Close module details",connections:"Connections",outgoing:"To",incoming:"From",browseMode:"Browse mode",outlineMode:"Module details",graphMode:"Relationship diagram",analysisNotes:"Analysis notes",limitations:"Scope and limitations",analyzedPaths:"Analyzed sources",fitGraph:"Fit entire diagram",fullscreen:"Open fullscreen diagram",closeFullscreen:"Close fullscreen diagram",panHint:"Drag to pan, pinch to zoom; select a module for details",newAnalysis:"New analysis",updateAnalysis:"Update current analysis",closePreparation:"Close analysis settings",analysisRange:"Analysis scope",projectRange:"Entire project",moduleRange:"Directory / module",featureRange:"Feature flow",modulePaths:"Module paths (one per line)",modulePlaceholder:"Choose folders/files or paste existing references, one per line",featureTarget:"Feature to understand",featurePlaceholder:"For example: file upload from selecting a file to storage",invalidPaths:"Choose up to 20 project folders/files or paste their references; outside paths and .. are not allowed.",requiredFeature:"Describe a specific feature and check that optional starting paths are project-relative.",independentHint:"Scoped analyses are saved separately. Repeating the same scope updates its map; the entire project uses the project overview.",updateOnly:"Only this analysis will be updated. Other maps are preserved.",analysisOptions:"Dependencies and other options",dependencyDepth:"Dependency tracing",boundaryDepth:"Scope boundary (faster)",followDepth:"Follow relevant calls and dependencies",startPaths:"Feature scope (optional)",focus:"Analysis request and constraints (optional)",focusPlaceholder:"For example: explain permission checks and retries; skip styling.",savedAnalyses:"Saved analyses",libraryFailed:"Could not list analyses. The current map is still available. Refresh to retry.",awaitingFile:"This analysis has not been saved yet. Send the prepared prompt to your Agent; the result will appear after the file is saved.",analyzeModule:"Analyze this module in detail",scopeUnavailable:"This scoped map is missing analysis metadata. Create a new analysis to specify its boundaries.",tab:"Map",title:"Code architecture",generate:"Generate",update:"Update",refresh:"Refresh architecture",prepare:"Prepare architecture analysis",promptHint:"Use the Agent in this project's terminal to analyze the code. The prompt goes into the current input or context draft for you to review and send. This view refreshes when the architecture is saved. Open an Agent first; analysis uses its time and allowance.",insertPrompt:"Insert prompt",copyPrompt:"Copy prompt",previewPrompt:"Review analysis prompt",inserting:"Adding to the current input…",insertFailed:"Could not add the prompt. Check the current session, or copy it below.",inserted:"Review the current input or context draft, then send it to your Agent.",copied:"Prompt copied.",failed:"Copy failed. Copy manually from the prompt below.",loading:"Reading project architecture…",invalid:"The architecture file is invalid. Analyze the project again to repair it.",loadFailed:"Could not read project architecture. Check connection and access, then retry.",previous:"The last successfully loaded architecture remains below.",retry:"Retry",empty:"Understand this project's architecture",emptyHint:"Start with the project, selected paths or one feature. A full project map is not required.",savedAt:"Saved",perspective:"Perspective",breadcrumb:"Architecture hierarchy",modules:"Modules",explore:"Explore submodules",sourceFiles:"Related source",diagram:"Architecture diagram",diagramHint:"Select a module for details",zoomOut:"Zoom out diagram",zoomIn:"Zoom in diagram",resetZoom:"Reset diagram zoom",download:"Download architecture SVG",downloadFailed:"Download failed. Please retry.",diagramFailed:"The diagram could not render. You can still explore the modules below.",rendering:"Drawing architecture…"},computer:{returnToDesktop:"Return to desktop",tools:"Control settings",closeTools:"Close control settings",keyboard:"Keyboard",keyboardInput:"Type directly on the computer",keyboardPlaceholder:"Tap to type directly on the computer",hideKeyboard:"Hide keyboard",keyboardNavigation:"Keyboard navigation",desktopZoom:"Desktop zoom",zoomIn:"Zoom in desktop",zoomOut:"Zoom out desktop",resetZoom:"Fit desktop to screen",pinchHint:"Pinch to zoom",keyEscape:"Send Esc",keyLeft:"Move left",keyDown:"Move down",keyUp:"Move up",keyRight:"Move right",keySelectAll:"Select all",clipboardTool:"Clipboard",zoom:"Zoom in",expand:"Full screen",switchTouchMode:"Switch touch mode",touchMode:"Touch mode",trackpadMode:"Trackpad",directTouchMode:"Direct touch",trackpadHint:"Slide to move, tap to click, hold to drag. Use two fingers to scroll or tap for right-click.",directTouchHint:"Tap a position on the screen to click. Drag your finger to interact with the desktop.",trustCertificateHere:"Trust this computer’s certificate",rememberLogin:"Remember login",autoConnect:"Connect automatically next time",forgetLogin:"Forget login",savedPassword:"Saved — leave empty to connect",loginExpired:"Saved login expired. Enter your password again.",loginSaveFailed:"Could not save or retrieve login details. Please retry.",title:"Computer control",host:"Computer address",hostPlaceholder:"192.168.1.20 or computer.local",username:"Username (optional)",password:"Password",passwordHint:"Enter the target computer’s VNC password. Include a username if the server requires account sign-in. Remember login encrypts credentials on the service after a successful connection.",connect:"Connect",disconnect:"Disconnect",cancel:"Cancel",connecting:"Connecting…",connected:"Connected",disconnected:"Disconnected. You can reconnect.",viewOnly:"View only",control:"Allow control",fit:"Fit to panel",actualSize:"Actual size",fullscreen:"Expand desktop",exitFullscreen:"Collapse desktop",setup:"How to connect a computer",step1:"On your Mac, open System Settings → General → Sharing → Screen Sharing.",step2:"Allow your user in Screen Sharing settings. For a VNC password, enable “VNC viewers may control screen with password”.",step3:"Enter a private computer address reachable from this service. To control the computer running this service, choose “This computer”.",networkHint:"Uses VNC port 5900. Browser-to-Termdock traffic is encrypted; use a trusted LAN or VPN for the VNC connection from the service to the target computer.",service:"Current service: {name}",remoteTitle:"Remote computer desktop",startHint:"Connect to view the desktop and control the computer with mouse, touch, and keyboard.",credentials:"Enter login credentials",authenticate:"Sign in",authFailed:"Sign-in failed. Check the username, password, and remote desktop permissions.",sharingOff:"VNC connection refused. Start desktop sharing and check port 5900.",unreachable:"Cannot reach the computer. Check the address, network, and firewall.",timeout:"Connection timed out. Make sure the target computer is awake and reachable from this service.",invalidHost:"Enter a private IP or hostname without a protocol or port.",privateOnly:"Only private or local addresses are supported. For remote access, switch to the Termdock service on the target computer.",permission:"Computer control requires full access to the current service.",failed:"Connection failed. Please reconnect.",clipboard:"Send clipboard",clipboardPlaceholder:"Send text to the computer clipboard",clipboardHint:"Enter text and press {shortcut} to paste, or send it to the clipboard only. Character support depends on the target computer.",remoteClipboard:"Text copied on the computer",copyToDevice:"Copy to this device",clipboardCopied:"Copied to this device",clipboardAccessFailed:"System clipboard is unavailable. Enter text here to send, or select the received text and copy it manually.",clipboardSent:"Sent to computer clipboard",shortcuts:"Shortcuts",switchApps:"Switch apps",spotlight:"Spotlight search",desktop:"Show desktop",loading:"Loading computer control…",platform:"Target system",thisComputer:"This computer",otherComputer:"Another computer",target:"Computer to connect",localService:"Computer running the current Termdock service · {name}",advanced:"Advanced settings",rdpLoginHint:"Use the credentials from Remote Desktop settings.",vncLoginHint:"Use your screen sharing VNC password.",checkSettings:"Check connection settings",localHint:"Local means the computer running the current Termdock service. Enable the selected remote desktop protocol on the target first.",linuxStep1:"Ubuntu / Linux needs a VNC server. To share the current desktop with x11vnc, use an X11 session; select “Ubuntu on Xorg” at the Ubuntu login screen.",linuxStep2:"Set a VNC password and listen on port 5900. RDP-only desktop sharing cannot connect here.",linuxCommandHint:"Run these commands in a desktop terminal on the target, then enter the VNC password you set. This example only accepts connections from the service computer. Commands are not run automatically:",linuxProtocolHint:"Ubuntu 24.04’s built-in Remote Desktop uses RDP; this panel uses VNC. Wayland needs a VNC server compatible with the desktop. TigerVNC virtual desktops are separate sessions, not the current screen.",windowsStep1:"Install and start a compatible VNC server on Windows. Windows RDP Remote Desktop cannot connect here.",windowsStep2:"Set a VNC password, enable keyboard and mouse control, and allow this service to reach port 5900 through the firewall.",systemSearch:"System search",protocol:"Connection protocol",port:"RDP port",rdpUsername:"RDP username",domain:"Domain (optional)",rdpPasswordHint:"Use the RDP username and password configured in Remote Desktop settings. Ubuntu remote login credentials may differ from your system account. Remember login encrypts credentials on the service after a successful connection.",rdpBackendUnavailable:"RDP support is unavailable on this service. Complete the server-side RDP setup first.",rdpBackendRecovery:"Start the RDP backend (guacd) on the computer running this Termdock service, then refresh this page to check again. Connection settings are kept; you can also switch to VNC in advanced settings.",rdpFailed:"RDP connection failed. Check Remote Desktop, the port, and credentials. For a self-signed certificate, verify the computer’s identity before enabling certificate trust.",rdpLinuxStep1:"On Ubuntu, open Settings → System → Remote Desktop. Enable Desktop Sharing or Remote Login and configure RDP credentials.",rdpStep1:"Enable RDP on the target computer. On Windows, use Settings → System → Remote Desktop. Use VNC for built-in Mac Screen Sharing.",rdpStep2:"Enter the username, password, and port from Remote Desktop settings. The default RDP port is 3389; Ubuntu Desktop Sharing may use 3390. Verify the target before trusting a self-signed certificate.",rdpNetworkHint:"Display and input use the encrypted browser-to-Termdock channel. The current service connects to the target over RDP. Desktop Sharing and Remote Login may use different sessions; showing the current screen depends on the target service’s settings.",trustCertificate:"Trust this computer’s RDP certificate (skip verification)",settingsLoading:"Loading connection settings…",settingsSaving:"Saving settings…",settingsSaved:"Connection settings saved on this service.",settingsSaveFailed:"Settings could not be saved. Your edits are still on this page.",settingsLoadFailed:"Connection settings could not be loaded. Please retry.",retry:"Retry",retryConnect:"Retry connection",rdpCertificate:"The target computer’s RDP certificate could not be verified. After confirming the computer’s identity, trust its certificate below and retry.",clipboardFailed:"Failed to send clipboard. Try again."},app:{name:"Termdock"},android:{device:"Device",selectDevice:"Select device",noDevices:"No device found",closeTab:"Close device tab",refresh:"Refresh devices",connect:"Connect",disconnect:"Stop mirroring",addDevice:"Connect over network",addressPlaceholder:"ip:port, e.g. 192.168.1.20:5555",adbUnavailable:"adb (Android platform-tools) not found; mirroring is unavailable. macOS: brew install android-platform-tools; Ubuntu: sudo apt install adb; or set TERMDOCK_ADB_BIN in ~/.termdock/.env.",scrcpyUnavailable:"scrcpy / scrcpy-server not found; mirroring is unavailable. macOS: brew install scrcpy; Ubuntu: sudo apt install scrcpy; or set TERMDOCK_SCRCPY_BIN in ~/.termdock/.env.",connecting:"Connecting to device…",reconnecting:"Connection lost, reconnecting…",retrySchedule:"Retry {attempt} starts in {seconds} seconds",lastError:"Last error (retained while reconnecting)",retry:"Retry",idleHint:"Pick a device to start mirroring",noDevicesHint:"Connect a phone over USB with debugging enabled, or add a network device",back:"Back",home:"Home",recents:"Recents",notifications:"Notifications",rotate:"Rotate",volumeUp:"Volume up",volumeDown:"Volume down",power:"Power",zoomIn:"Zoom in",zoomOut:"Zoom out",zoomPanHint:"Two-finger drag to move the view",inputText:"Type text",inputPlaceholder:"Text to send to the phone",send:"Send",splitOpen:"Open in split view",splitClose:"Exit split view",splitDockedHint:"Mirroring is shown in the split area.",splitDrag:"Drag to reposition",insertFixPrompt:"Insert fix prompt",screenshot:"Screenshot and insert",recordingStart:"Start recording",recordingStop:"Stop recording",recording:"Recording…",recordingLimit:"Reached the 5-minute limit, recording stopped",recordingStopped:"Mirroring stopped, recording ended",captureInserted:"Screenshot inserted",recordingInserted:"Recording inserted",recordingConfirm:"Recording finished. What next?",recordingInsert:"Insert directly",recordingSave:"Save to a folder",recordingSaveHint:"Recorded on the server. Insert a file reference, or save to a server folder.",recordingDiscard:"Discard recording",captureInserting:"Inserting…",recordingSaving:"Saving recording…",captureFailed:"Insert failed",captureUnavailable:"Cannot insert into the terminal right now",more:"More",fullscreen:"Fullscreen",fillSidebar:"Fill sidebar",exitFullscreen:"Exit fullscreen",fullscreenHint:"Mirroring is shown in fullscreen.",quality:"Quality",qualityAutoHint:"Adapts bitrate to connection and decoding performance without reconnecting. Resolution stays stable; controls and server recording are unaffected.",qualityAutoUnavailable:"Automatic bitrate adjustment paused; video stays connected.",qualityAutoVersionError:"Server scrcpy version is not supported (details).",qualityAutoBuildError:"Server scrcpy build has not been verified (details).",qualityAutoExtensionError:"Bitrate extension could not be read, verified or transferred (details).",qualityAutoTimeoutError:"Bitrate confirmation timed out; encoder support is unknown (details).",qualityAutoEncoderError:"Device encoder rejected this adjustment (details).",qualityAutoChannelError:"Bitrate control channel failed (details).",qualityAutoUnknownError:"Server did not provide a reason; update that server and retry (details).",qualityLow:"Smooth",qualityMedium:"Standard",qualityHigh:"HD",qualityCustom:"Custom",qualityResolution:"Resolution",qualityBitRate:"Bitrate",qualityFrameRate:"Frame rate",qualityAuto:"Auto",qualityApply:"Apply",presetNamePlaceholder:"Preset name",presetSave:"Save preset",presetDelete:"Delete preset",stateUnauthorized:"unauthorized",stateOffline:"offline",stateUnknown:"unknown state",unauthorizedHint:"Confirm the USB debugging prompt on the phone.",offlineHint:"Device is offline; reconnect the cable or network device."},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:e})=>`Please wait ${e}s`,submit:"Sign in",invalidPassword:"The password is incorrect, or the service identity could not be verified. Check and try again.",identityMismatch:"The service identity has changed. Check the address with its owner before trying again.",unavailable:"Password sign-in is temporarily unavailable. Check the connection and try again.",authorizationRequired:"This device needs authorization. Ask the service owner for a new invitation.",currentTarget:({address:e})=>`Signing in to ${e}`,manageServices:"Manage services / use another address",failed:"Could not sign in. Check the connection and try again.",rateLimited:"Too many attempts. Please wait and try again.",continueAfterReconnect:"You can continue signing in when the network returns.",savedConnectionRetained:"Saved service retained. Access will be checked after reconnecting.",invalidAddress:"Enter a valid HTTPS service address, for example computer.example:9834 or https://computer.example:9834.",invalidInvitation:"This invitation is incomplete or invalid. Copy the full invitation link and try again."},sidebar:{sessionCreating:"Starting…",sessionCreateDirectoryUnavailable:"The working directory is unavailable. Choose another folder and try again.",sessionCreatePermissionDenied:"You do not have permission to start here. Choose another folder.",sessionCreateConnectionFailed:"Could not connect. Check the connection and try again.",sessionCreateFailed:"Could not start the session. Please try again.",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",attentionButton:"Attention button",attentionButtonHint:"Show the yellow floating bell for unread or pending sessions",updateAvailable:({version:e})=>`Termdock ${e} 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:e})=>`Restart Termdock and switch to ${e}? 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",serverAttention:"The service had a problem",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:e})=>`Close ${e}`,newShell:"Shell",newTmux:"Tmux",newTmuxDisabled:"tmux not available on server",confirmNewShell:"Create Shell?",confirmNewTmux:"Create Tmux?",newSession:"New terminal",newSessionWithAgent:({agent:e})=>`New ${e}`,moreLaunchOptions:"More launch options",recoverableSessions:"Recoverable sessions",confirmCloseRecoverableSession:({name:e})=>`End ${e}? This stops all processes in the session.`,endRecoverableSession:"End session",closeRecoverableSessionFailed:"Could not end the session. Please retry.",refreshRecoverableSessions:"Refresh recoverable sessions",restoreRecoverableSession:({name:e})=>`Restore ${e}`,restoringRecoverableSession:"Restoring…",restore:"Restore",newSessionAdvanced:"Quick-launch agent",newSessionComposerTitle:"Start a session",newSessionHint:"Choose how and where it starts",launchSessionWith:({name:e})=>`Start ${e}`,setNewSessionDefault:({name:e})=>`Set ${e} as default`,currentNewSessionDefault:({name:e})=>`${e} is the current default`,currentDefaultAgent:({name:e})=>`Current default: ${e}`,defaultAgent:"Default",makeDefault:"Make default",sessionMode:"Run mode",tmuxKeepsRunning:"Keeps running after disconnect",resumeHistory:"Recent conversations",resumeHistoryCount:({n:e})=>`${e} saved`,resumeHistoryLoading:"Loading recent Agent conversations…",resumeHistoryAction:({title:e})=>`Resume ${e}`,resumeHistoryRemove:({title:e})=>`Remove ${e} 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.",customStartupCommand:"Custom command",changeStartupCommand:"Change startup command",saveStartupCommand:"Save command",startupCommandSaved:"Saved",saveStartupCommandFailed:"Could not save. Check browser storage permissions.",addStartupCommand:"Add custom command…",deleteStartupCommand:"Delete command",startupCommand:"Startup command",resetStartupCommand:"Reset",startupCommandPlaceholder:"e.g. vim, htop or npm run dev",agentStartupCommandHint:"Edit the full command; leave blank for the Agent default. Saved in this browser.",terminalStartupCommandHint:"Run a program in the selected directory, e.g. vim README.md. Saved in this browser.",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",hideGitIgnoredFiles:"Hide Git-ignored files",showGitIgnoredFiles:"Show Git-ignored files",gitIgnoreSaveFailed:"Could not save Git ignore visibility. Please retry.",gitIgnoreConfigureHint:"Long-press or right-click to configure exceptions",gitIgnoreExceptionsTitle:"Git ignore filter exceptions",gitIgnoreExceptionsHint:"Select files or folders to keep visible while filtering is enabled. Use the arrow beside a folder to browse inside it. Selected folders include all descendants; parent folders of selected files stay visible. Save to apply.",gitIgnoreExceptionsPaths:"Select files or folders",gitIgnoreExceptionsInvalid:"Select up to 200 files or folders.",gitIgnoreExceptionsLoadFailed:"Could not load this folder. Please retry.",gitIgnoreExceptionsEmptyDirectory:"This folder is empty",gitIgnoreExceptionsOpenDirectory:({name:e})=>`Open folder ${e}`,gitIgnoreExceptionsSelected:({count:e})=>`${e} selected`,gitIgnoreExceptionsClear:"Clear selection",gitIgnoreExceptionsRemove:({path:e})=>`Remove ${e}`,gitIgnoreExceptionsTruncated:"This folder has too many entries; only some are shown.",gitIgnoreExceptionsSaveFailed:"Could not save. Check that all paths are inside the current folder (up to 200), then retry.",insertCurrentFolder:"Insert current folder reference",insertCurrentFolderShort:"Insert",pinnedFolders:"Pinned",unpinFolder:({name:e})=>`Unpin ${e}`,fileWatchUnavailable:({message:e})=>`File watcher unavailable: ${e}. 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:e})=>`Last updated: ${e}`,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:e})=>`${e} hunk explanation${e===1?"":"s"} loaded`,changeAuditLoadedAt:({time:e})=>`Generated ${e}`,changeAuditRegenerate:"Regenerate",changeAuditRefreshStale:"Fill stale",changeAuditRefreshStaleTitle:"Insert a prompt to refresh stale hunk explanations",clearChangeAudit:"Clear change explanations",clearChangeAuditTitle:"Clear hunk explanations for the current repository",changeAuditClearFailed:({message:e})=>`Failed to clear hunk explanations: ${e}`,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:e})=>`${e} 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:e})=>`Failed to clear branch explanation: ${e}`,branchAuditCommitCount:({count:e})=>`${e} commit${e===1?"":"s"}`,branchAuditFileCount:({count:e})=>`${e} file${e===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:e})=>`${e} hunk explanation${e===1?"":"s"} saved`,branchAuditGeneratedAt:({time:e})=>`Generated ${e}`,insertPreset:({label:e})=>`Insert: ${e}`,tabChanges:"Changes",tabGit:"Git",tabFiles:"Files",tabAndroid:"Device",tabComputer:"Mac",showAndroidTab:"Show device tab",showArchitectureTab:"Show architecture tab",showComputerTab:"Show computer tab",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",referenceInsertFailed:"Could not insert. Check the target terminal connection and retry.",contextDraftInsertFailed:"Input not accepted — draft kept. Close the active form or return to the terminal and retry.",contextDraftPending:"Waiting…",contextDraftCharacterCount:({count:e})=>`${e} chars`,selectFilePrompt:"Select a file to preview its contents",backToFileList:"Back to file list",backToPreviousPreview:"Back to source document",insertLineRef:({lineLabel:e})=>`Insert ${e}`,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",downloadCanceled:"Download canceled",downloadSaved:"File saved",downloadStarted:"Browser download started",uploadPending:"Uploading…",uploadInserting:"File uploaded · waiting for input acceptance…",uploadDone:({count:e})=>`${e} files uploaded`,uploadReferenceDone:"File uploaded · reference added",uploadReferenceRejected:"File uploaded; reference not added. Close the active form or return to the original terminal and retry.",uploadLimit:"Choose up to 50 files. None were uploaded; select a smaller batch.",uploadCanceled:"Upload stopped. Check the target directory before uploading again.",uploadFileCount:({count:e})=>`${e} selected files`,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:e})=>`${e} file${e===1?"":"s"} uploaded`,uploadFailed:"Upload failed",binaryPreviewHint:"Binary files cannot be previewed. Use the download button above to save it.",selectedLineHint:({lineLabel:e})=>`Selected ${e} · 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 2× and drag forward to speed up · arrows seek/volume · space pauses",videoLoadFailed:"Failed to load video preview",videoUnsupported:"Your browser does not support this video format",videoPlay:"Play",videoPause:"Pause",videoLongPressSpeed:({rate:e})=>`Playing at ${e}×`,videoVolume:({percent:e})=>`Volume ${e}%`,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:e})=>`Dimensions: ${e}`,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:e,positioned:t})=>`Features: ${e} · positioned ${t}`,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:e})=>`Show all (${e})`,model3dParts:"Parts",model3dCloseParts:"Close parts",model3dSearchParts:"Find a part",model3dClearPartSearch:"Clear part search",model3dHiddenParts:({count:e})=>`${e} hidden`,model3dShowNamedPart:({name:e})=>`Show ${e}`,model3dHideNamedPart:({name:e})=>`Hide ${e}`,model3dIsolateNamedPart:({name:e})=>`Only show ${e}`,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:e})=>`Part ${e}`,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:e,y:t})=>`Selected ${e}%, ${t}%`,edaPickedBoardPosition:({x:e,y:t,object:n})=>`Board ${e}, ${t} mm · ${n}`,edaInspecting:"Reading board coordinates and nearby object…",edaNoNearbyObject:"No nearby object",edaInsertAnnotation:"Insert electronics annotation",csvUnnamedColumn:({index:e})=>`Column ${e}`,csvSelectedCell:({row:e,column:t})=>`Row ${e} · ${t}`,csvPickHint:({rows:e,columns:t})=>`${e} records · ${t} 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",markdownParseFailed:"Markdown preview parsing failed or exceeded its limits. Showing the source text.",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:e})=>`from ${e}`,selectedLineFooter:({lineLabel:e})=>`Selected ${e}`,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:e})=>`${e} change${e===1?"":"s"}`,repoStagedCount:({count:e})=>`${e} 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:"Scan 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:e})=>`${e} staged`,stagedCountShort:({count:e})=>`${e} staged`,commitSectionTitle:"Commit",commitReadyHint:({count:e})=>`${e} file${e===1?"":"s"} ready`,commitMessagePlaceholder:"Commit message",commitChanges:"Commit",commitNeedsStaged:"Stage changes before committing",commitAhead:"↑ Unpushed",commitBehind:"↓ Incoming",commitSynced:"Synced",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:e})=>`${e}`,pushBranchSearchPlaceholder:"Search branch",pushNoBranches:"No branches",pushUpstreamBadge:"upstream",pushCurrentBranchBadge:"current",pushNoUpstream:"No upstream configured",pushUpToDate:"Up to date with remote",pushAheadCount:({count:e})=>`${e} commit${e===1?"":"s"} to push`,pushBehindCount:({count:e})=>`${e} commit${e===1?"":"s"} to pull`,pushDivergedCount:({ahead:e,behind:t})=>`${e} ahead / ${t} behind`,pullChanges:"Pull",pushChanges:"Push",gitActionRunning:"Running…",gitActionFailed:({message:e})=>`Git action failed: ${e}`,confirmRestoreTitle:"Discard changes?",confirmRestoreDescription:({path:e})=>`This will discard unstaged changes in ${e}. 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:e})=>`Back to footnote ${e}`,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:e})=>`Insert reference: ${e}`,copyReference:({reference:e})=>`Copy reference: ${e}`,byteCount:({count:e})=>`${e} bytes`,previewTruncated:"Preview truncated to 1 MB",branchCandidatesLoading:"Loading branch candidates…",includeUncommitted:"Include local uncommitted changes",includeUncommittedCurrentBranchOnly:"Available only when the compared branch is checked out",includeUncommittedHint:"Include working tree and untracked diffs when viewing or explaining changes",missingBaseReposSkipped:({repositories:e})=>`Repositories without a base branch will be skipped: ${e}`,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:e})=>`Delete “${e}”? This action cannot be undone.`,deleteFileFailed:({message:e})=>`Failed to delete file: ${e}`,noWorkingDir:"No working directory detected.",emptyDir:"Empty directory.",noMatchingFiles:"No matching files.",searching:"Searching files…",searchingWithCount:({count:e})=>`Searching… ${e} found`,searchResults:({count:e})=>`${e} results`,searchScope:"Search scope",searchTruncatedHint:({count:e})=>`Fallback search scanned a large directory and stopped after ${e} matches. Install ripgrep or refine the query for complete results.`,searchStillRunning:"Search is still running. More results will appear automatically.",showingSearchResults:({shown:e,total:t})=>`Showing ${e} of ${t}`,loadMoreSearchResults:({shown:e,total:t})=>`Show more (${e}/${t})`,contentMatchesCount:({count:e})=>`${e} file${e===1?"":"s"} with matches`,moreMatches:({count:e})=>`+${e} more match${e===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",insertLineDiff:"Insert the selected diff lines",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?",hunkActionReverted:"Reverted",hunkActionStaged:"Staged",hunkActionApplying:"Applying…",hunkActionUnavailable:"Cannot build a patch for this hunk",hunkActionFailed:({message:e})=>`Failed: ${e}. If the changes moved on, refresh and retry.`,auditExplanation:"Change meaning",auditStale:"Explanation stale",auditClear:"Clear explanation",auditGeneratedAt:({time:e})=>`Generated ${e}`,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",expandAbove:({count:e})=>`Expand ${e} lines above`,expandBelow:({count:e})=>`Expand ${e} lines below`,contextLines:({count:e})=>`${e} lines`,contextAll:"All"},settings:{title:"Settings",font:"Font",render:"Render",workspaceLimit:"Keep service pages",workspaceUnlimited:"Unlimited",workspaceLimitHint:"Applies on this device, including the entry page. Lower limits save memory. Older background pages reconnect when revisited; terminal tasks keep running.",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.",desktopUpdateDownloadingShort:"Downloading…",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.",serverHealthTitle:"Service health",serverHealthHint:"What happened to the Termdock service recently.",serverHealthSupervised:"Automatic recovery is on: the service will attempt to restart if it crashes or stops responding.",serverHealthUnsupervised:"Built-in automatic recovery is off. A crash may require a manual restart.",serverHealthEnable:"Enable and restart",serverHealthEnableHint:"Enabling restarts the service and briefly disconnects clients. Plain terminals may close; tmux sessions can reconnect. Repeated startup failures stop automatic retries.",serverHealthEnabling:"Enabling…",serverHealthEnablePending:"Waiting for reconnection to confirm automatic recovery…",serverHealthEnableError:"Could not confirm automatic recovery. Reconnect to check its status. If the service is unreachable, check the startup logs on its host.",serverHealthEnableUnavailable:"This launch method cannot enable recovery here. Configure supervision on the service host; desktop and externally managed services remain managed by their launcher.",serverHealthClean:"No problems recorded.",serverHealthHistory:"Previous problem",serverHealthRunningNow:"The service is running now with automatic recovery enabled.",serverHealthLastIncident:"Last problem",serverHealthRestarted:({count:e})=>`Restarted automatically ${e}${e===1?" time":" times"}`,serverHealthGaveUp:({count:e})=>`This supervisor stopped retrying after ${e} consecutive failures.`,serverHealthSupervisorLost:"Automatic recovery is unavailable. The service is still running.",serverHealthOomNote:"Memory was near the limit before it died; the OOM killer may have taken it.",serverHealthUptime:({duration:e})=>`ran for ${e}`,serverHealthDismiss:"Got it",serverHealthDismissed:"Acknowledged",serverHealthUnknownEvent:"Something went wrong",serverHealthEventStartupFailure:"Failed to start",serverHealthEventCrash:"Crashed",serverHealthEventCrashNative:"Crashed in native code",serverHealthEventKilled:"Killed outright",serverHealthEventWedge:"Stopped responding and had to be killed",serverHealthEventPortConflict:"Could not start: the port is already in use",serverHealthEventGaveUp:"Repeated failures; retries stopped at that time",serverHealthEventExitZero:"Exited with code 0 without being asked to",serverHealthEventTerminated:"Terminated by another process",serverHealthEventSupervisorLost:"Lost contact with the supervisor",serverHealthEventUncaughtException:"Hit an uncaught exception",serverHealthEventUnhandledRejection:"Had an unhandled promise rejection",serverHealthEventExitNonzero:"Exited with an error code",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:e})=>`${e} session${e===1?"":"s"}`,windows:({n:e})=>`${e} window${e===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:"Connection addresses and phone setup instructions",resetAutoName:"Reset auto",mobileSetupIntro:"Connect your phone to the same network as this service. If HTTPS is enabled, install and trust its CA certificate first, then open an address below.",mobileSetupDownload:"1. Scan to download the CA certificate",mobileSetupIos:"iPhone / iPad: scan with the Camera and open in Safari. Install the downloaded profile in Settings → General → VPN & Device Management, then enable full trust in Settings → General → About → Certificate Trust Settings.",mobileSetupAndroid:"Android: download the certificate and install it as a CA certificate in system security settings. Menu names vary by device.",mobileSetupConnect:"2. Open Termdock",mobileSetupConnectHint:"After trusting the certificate, scan an IP address QR code below or copy the local address to your phone browser. If the hostname does not resolve, use an IP address.",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",desktopOpenDataDirectory:"Open data directory"},toolbarPresets:{preview:"Preview",presets:"Presets",label:"Label",new:"New",reset:"Reset",presetLabelPlaceholder:"Preset label",deletePreset:({name:e})=>`Delete preset ${e}`,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:e})=>`Row ${e}`,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:e})=>`Remove row ${e}`,removeAction:({name:e})=>`Remove ${e}`,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",fontSize:"Font size",fontSizeHint:"Only for this session",fontSizeReset:"Follow global",resumeAgent:"Resume agent session",resumeAgentHint:"Resume the last conversation by its native session id",resumeAgentAvailable:"Agent conversation available to resume",resumeAgentRecoveredTitle:({agent:e})=>`${e} 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:e})=>`${e} 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:e})=>`${e} Agent session(s) awaiting recovery`,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:e,failed:t})=>`Restored ${e}; ${t} still need attention.`,tmuxRecoveryFailed:"Recovery failed. Check the terminals and try again.",tmuxRecoveryDismissFailed:"Could not dismiss the recovery notice.",tmuxRecoveryProgress:({total:e,queued:t,paused:n,resourceWait:r,running:o,succeeded:s,failed:i})=>`Recovery: ${s}/${e} complete · ${t} queued · ${n} paused (${r} waiting for resources) · ${o} running · ${i} failed`,tmuxRecoveryPausedForResources:"Resources are below budget. New launches are paused and will resume automatically when capacity returns.",tmuxRecoveryPause:"Pause",tmuxRecoveryResume:"Resume",tmuxRecoveryInProgress:"Recovery in progress",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",closeFailed:({name:e})=>`Could not close ${e}. The session is still open. Try again.`,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:e})=>`${e} session${e===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"},serviceAttention:{title:"Attention across services",summary:"{services} services · {count} sessions",currentService:"Current service",waiting:"Waiting for you",offline:"Offline · Last known status",login:"Sign-in required · Last known status",empty:"No sessions need attention",viewService:"Open service",scope:"Includes opened services. Select a session to go directly to it.",changed:"The pending sessions have changed. Please choose again.",unavailable:"Unable to open this service. Retry from the service list."},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:e})=>`${e} left`,updated:({time:e})=>`Updated ${e}`,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"}}},CA={architecture:{choosePaths:"选择目录或文件",browsePaths:"浏览目录",addScopeReference:"引用到分析范围",searchScopePaths:"搜索文件或目录",useCurrentFile:"引用当前文件",useCurrentDirectory:"引用当前目录",browsePathsHint:"展开目录浏览,点击右侧引用按钮加入分析范围。",correctPathsFirst:"请先修正已填写的路径,再添加范围。",pathsHint:"可选择范围或粘贴文件/行引用,路径相对当前项目。",featureScopeHint:"优先在所选范围内定位功能",removePath:"移除路径",chooseThisDirectory:"选择此目录",filterDirectory:"筛选当前目录",loadingPaths:"正在读取目录…",pathsLoadFailed:"无法读取目录,请检查连接或访问权限后重试。",noPaths:"当前目录没有匹配的文件或子目录。",pathsTruncated:"当前目录条目较多,仅显示部分结果;可进入子目录,或直接粘贴目标路径。",selectedPaths:"已选路径",usePaths:"使用所选范围",expandDetail:"查看详情",collapseDetail:"收起说明",backToMap:"返回架构",backToModule:"返回模块",previousModule:"上一模块",parentModule:"返回上一级",viewPrepared:"查看这份分析",closeDetail:"关闭模块详情",connections:"连接关系",outgoing:"连向",incoming:"来自",browseMode:"浏览方式",outlineMode:"模块说明",graphMode:"关系图",analysisNotes:"分析说明",limitations:"范围与限制",analyzedPaths:"已分析源码",fitGraph:"查看全图",fullscreen:"全屏看图",closeFullscreen:"关闭全屏图",panHint:"拖动浏览,双指缩放;点击模块查看说明",newAnalysis:"新建分析",updateAnalysis:"更新当前分析",closePreparation:"关闭分析设置",analysisRange:"分析范围",projectRange:"整个项目",moduleRange:"目录 / 模块",featureRange:"功能链路",modulePaths:"模块路径(每行一个)",modulePlaceholder:"选择目录或文件,或粘贴已有引用,每行一个",featureTarget:"想了解的功能",featurePlaceholder:"例如:文件上传从选择文件到写入存储的完整流程",invalidPaths:"请选择项目内的目录或文件,或粘贴其引用,最多 20 个;项目外路径和 .. 无法使用。",requiredFeature:"请描述一个具体功能,并检查可选起始路径是否为项目内相对路径。",independentHint:"局部分析单独保存,可随时切换。同一范围再次生成会更新对应的图;整个项目使用项目总览。",updateOnly:"只更新当前这份分析,其他架构图会保留。",analysisOptions:"依赖深度与其他选项",dependencyDepth:"依赖追踪",boundaryDepth:"范围边界(更快)",followDepth:"追踪相关调用与依赖",startPaths:"功能范围(可选)",focus:"分析诉求与限制(可选)",focusPlaceholder:"例如:重点解释权限检查和失败重试,忽略界面样式。",savedAnalyses:"已保存分析",libraryFailed:"无法读取分析列表,当前图仍可浏览。请点击刷新重试。",awaitingFile:"这份分析尚未保存。将准备好的指令发送给 Agent;文件保存后这里会自动显示结果。",analyzeModule:"细化分析这个模块",scopeUnavailable:"这份局部架构缺少范围信息,请新建分析以明确分析边界。",tab:"架构",title:"代码架构",generate:"生成",update:"更新",refresh:"刷新架构",prepare:"准备架构分析",promptHint:"使用当前项目的 Agent 分析代码。提示词会放入当前输入区或上下文草稿,检查后发送;架构保存后,这里会自动刷新。请先在终端打开 Agent,分析会消耗其时间和额度。",insertPrompt:"放入输入区",copyPrompt:"复制提示词",previewPrompt:"查看分析提示词",inserting:"正在添加到当前输入区…",insertFailed:"未能添加提示词,请检查当前会话,或从下方复制。",inserted:"请检查当前输入区或上下文草稿,并发送给 Agent。",copied:"提示词已复制。",failed:"复制失败,请从下方提示词中手动复制。",loading:"正在读取项目架构…",invalid:"架构文件格式有误。可以重新分析项目来修复。",loadFailed:"无法读取项目架构,请检查连接与访问权限后重试。",previous:"下面保留上次成功读取的架构。",retry:"重试",empty:"了解这个项目的代码架构",emptyHint:"可以从整个项目、指定目录或某个功能开始分析,无需先生成全项目架构。",savedAt:"保存于",perspective:"视角",breadcrumb:"架构层级",modules:"模块",explore:"展开子模块",sourceFiles:"相关源码",diagram:"架构关系图",diagramHint:"点击模块查看详情",zoomOut:"缩小架构图",zoomIn:"放大架构图",resetZoom:"重置架构图缩放",download:"下载架构图 SVG",downloadFailed:"下载失败,请重试。",diagramFailed:"图表暂时无法渲染,仍可通过下方模块查看架构。",rendering:"正在绘制架构图…"},computer:{returnToDesktop:"返回桌面",tools:"控制设置",closeTools:"关闭控制设置",keyboard:"键盘",keyboardInput:"直接输入到电脑",keyboardPlaceholder:"点这里打字,文字直接发送到电脑",hideKeyboard:"收起键盘",keyboardNavigation:"键盘导航",desktopZoom:"桌面缩放",zoomIn:"放大桌面",zoomOut:"缩小桌面",resetZoom:"恢复适应屏幕",pinchHint:"双指捏合缩放",keyEscape:"发送 Esc",keyLeft:"向左",keyDown:"向下",keyUp:"向上",keyRight:"向右",keySelectAll:"全选",clipboardTool:"剪贴板",zoom:"放大",expand:"全屏",switchTouchMode:"切换触摸方式",touchMode:"触控模式",trackpadMode:"触控板",directTouchMode:"直接触摸",trackpadHint:"单指滑动移动鼠标,轻点点击,长按拖动;双指滚动,双指轻点右键。",directTouchHint:"轻点屏幕上的位置即可点击,拖动手指操作桌面。",trustCertificateHere:"信任此电脑的证书",rememberLogin:"记住登录",autoConnect:"下次打开自动连接",forgetLogin:"清除登录",savedPassword:"已保存,留空直接连接",loginExpired:"登录信息已失效,请重新输入密码。",loginSaveFailed:"登录信息保存或读取失败,请重试。",title:"电脑控制",host:"电脑地址",hostPlaceholder:"192.168.1.20 或 computer.local",username:"用户名(可选)",password:"密码",passwordHint:"填写目标电脑的 VNC 密码;服务器要求账户登录时,同时填写用户名。勾选记住登录后,成功连接时在服务端加密保存。",connect:"连接",disconnect:"断开",cancel:"取消",connecting:"正在连接…",connected:"已连接",disconnected:"连接已断开,可以重新连接。",viewOnly:"仅查看",control:"允许控制",fit:"适应面板",actualSize:"原始尺寸",fullscreen:"展开桌面",exitFullscreen:"收起桌面",setup:"如何连接电脑",step1:"在 Mac 上打开「系统设置 → 通用 → 共享 → 屏幕共享」。",step2:"在屏幕共享设置中允许你的用户访问;使用 VNC 密码时,开启「VNC 查看器可以使用密码控制屏幕」。",step3:"填写当前服务能访问的电脑内网地址;控制服务所在电脑时,选择「当前电脑」。",networkHint:"使用 VNC 端口 5900。浏览器到 Termdock 全程加密;服务到目标电脑的 VNC 段请使用可信内网或 VPN。",service:"当前服务:{name}",remoteTitle:"远程电脑桌面",startHint:"连接后可在这里查看桌面,用鼠标、触摸和键盘操作电脑。",credentials:"请填写登录信息",authenticate:"登录",authFailed:"登录失败,请检查用户名、密码和目标电脑的远程桌面权限。",sharingOff:"电脑未接受 VNC 连接,请先启动桌面共享服务,并检查端口 5900。",unreachable:"无法连接电脑,请检查地址、网络以及防火墙。",timeout:"连接超时,请确认目标电脑已唤醒且能从当前服务访问。",invalidHost:"请填写电脑的内网 IP 或主机名,无需协议或端口。",privateOnly:"仅支持内网或本机地址;远程访问可切换到目标电脑上的 Termdock 服务。",permission:"电脑控制需要当前服务的全权授权。",failed:"电脑连接失败,请重新连接。",clipboard:"发送剪贴板",clipboardPlaceholder:"发送文字到电脑剪贴板",clipboardHint:"输入文字后点 {shortcut} 即可粘贴;也可以只发送到剪贴板。字符支持取决于目标电脑。",remoteClipboard:"电脑复制的文字",copyToDevice:"复制到本机",clipboardCopied:"已复制到本机",clipboardAccessFailed:"无法访问系统剪贴板。可在此输入文字发送,或选中电脑复制的文字手动复制。",clipboardSent:"已发送到电脑剪贴板",shortcuts:"快捷键",switchApps:"切换应用",spotlight:"Spotlight 搜索",desktop:"显示桌面",loading:"正在加载电脑控制…",platform:"目标系统",thisComputer:"当前电脑",otherComputer:"其他电脑",target:"连接哪台电脑",localService:"运行当前 Termdock 服务的电脑 · {name}",advanced:"高级设置",rdpLoginHint:"使用远程桌面设置中的账号和密码。",vncLoginHint:"使用屏幕共享的 VNC 密码。",checkSettings:"检查连接设置",localHint:"本机指运行当前 Termdock 服务的电脑;目标电脑需先启用所选协议的远程桌面服务。",linuxStep1:"Ubuntu / Linux 需要运行 VNC 服务。共享当前桌面时,x11vnc 需要 X11 会话;Ubuntu 登录界面可选择「Ubuntu on Xorg」。",linuxStep2:"设置 VNC 密码,并让服务监听 5900 端口;只有 RDP 的桌面共享无法在此连接。",linuxCommandHint:"在目标电脑的桌面终端执行以下命令,然后填写设置的 VNC 密码。此示例仅允许连接服务所在电脑,不会自动执行:",linuxProtocolHint:"Ubuntu 24.04 的内置远程桌面使用 RDP,此处使用 VNC。Wayland 需要兼容该桌面的 VNC 服务;TigerVNC 虚拟桌面是独立会话,不等同于当前屏幕。",windowsStep1:"在 Windows 上安装并启动兼容 VNC 的桌面共享服务器;Windows 的 RDP 远程桌面无法在此连接。",windowsStep2:"设置 VNC 密码,启用键盘和鼠标控制,并允许当前服务通过防火墙访问 5900 端口。",systemSearch:"系统搜索",protocol:"连接协议",port:"RDP 端口",rdpUsername:"RDP 用户名",domain:"域(可选)",rdpPasswordHint:"填写远程桌面设置中的 RDP 用户名和密码;Ubuntu 的远程登录凭据可能与系统账户不同。勾选记住登录后,成功连接时在服务端加密保存。",rdpBackendUnavailable:"当前服务的 RDP 支持不可用,请先完成服务端 RDP 配置。",rdpBackendRecovery:"请在运行 Termdock 服务的电脑上启动 RDP 后台(guacd),然后刷新此页面重新检查。连接设置会保留;也可在高级设置中切换为 VNC。",rdpFailed:"远程桌面连接失败。请检查目标地址、端口和电脑上的远程桌面设置。",rdpLinuxStep1:"在 Ubuntu 打开「设置 → 系统 → 远程桌面」,启用「桌面共享」或「远程登录」,并设置 RDP 登录凭据。",rdpStep1:"在目标电脑启用 RDP 远程桌面。Windows 可在「设置 → 系统 → 远程桌面」中开启;Mac 内置屏幕共享请使用 VNC。",rdpStep2:"填写远程桌面设置中的用户名、密码和实际端口。RDP 默认端口为 3389;Ubuntu 的桌面共享也可能使用 3390。目标使用自签名证书时,确认电脑身份后可勾选信任证书。",rdpNetworkHint:"浏览器到 Termdock 的画面和输入复用加密通道;RDP 由当前服务连接目标电脑。桌面共享与远程登录可能连接不同会话,是否显示当前屏幕取决于目标服务的设置。",trustCertificate:"信任此电脑的 RDP 证书(跳过校验)",settingsLoading:"正在读取连接设置…",settingsSaving:"正在保存设置…",settingsSaved:"连接设置已保存到当前服务。",settingsSaveFailed:"设置未能保存,当前修改仍在此页面。",settingsLoadFailed:"连接设置读取失败,请重试。",retry:"重试",retryConnect:"重试连接",rdpCertificate:"目标电脑的 RDP 证书未通过校验。确认是你的电脑后,可勾选信任证书并重试。",clipboardFailed:"剪贴板发送失败,请重试。"},app:{name:"Termdock"},android:{device:"设备",selectDevice:"选择设备",noDevices:"未发现设备",closeTab:"关闭设备 Tab",refresh:"刷新设备",connect:"连接",disconnect:"停止投屏",addDevice:"网络连接",addressPlaceholder:"ip:port,例如 192.168.1.20:5555",adbUnavailable:"本机未找到 adb(Android platform-tools),无法投屏。macOS: brew install android-platform-tools;Ubuntu: sudo apt install adb;或在 ~/.termdock/.env 设置 TERMDOCK_ADB_BIN。",scrcpyUnavailable:"本机未找到 scrcpy / scrcpy-server,无法投屏。macOS: brew install scrcpy;Ubuntu: sudo apt install scrcpy;或在 ~/.termdock/.env 设置 TERMDOCK_SCRCPY_BIN。",connecting:"正在连接设备…",reconnecting:"连接断开,正在自动重连…",retrySchedule:"第 {attempt} 次重试将在 {seconds} 秒后开始",lastError:"最近一次错误(重连期间保留)",retry:"重试",idleHint:"选择设备开始投屏",noDevicesHint:"用 USB 连接手机并开启 USB 调试,或在此添加网络设备",back:"返回",home:"主页",recents:"多任务",notifications:"通知栏",rotate:"旋转屏幕",volumeUp:"音量 +",volumeDown:"音量 -",power:"电源",zoomIn:"放大",zoomOut:"缩小",zoomPanHint:"双指拖动可移动画面",inputText:"输入文字",inputPlaceholder:"输入要发送到手机的文字",send:"发送",splitOpen:"在分屏中打开",splitClose:"退出分屏",splitDockedHint:"投屏已在分屏区域显示。",splitDrag:"按住拖动调整位置",insertFixPrompt:"插入修复提示词",screenshot:"截图并插入",recordingStart:"开始录屏",recordingStop:"停止录屏",recording:"正在录屏…",recordingLimit:"已达 5 分钟上限,录屏已停止",recordingStopped:"投屏已中断,录屏已停止",captureInserted:"截图已插入",recordingInserted:"录屏已插入",recordingConfirm:"录屏已结束,如何处理?",recordingInsert:"直接插入",recordingSave:"保存到指定目录",recordingSaveHint:"录像已保存在服务端。可插入终端引用,或另存到服务端目录。",recordingDiscard:"丢弃录屏",captureInserting:"正在插入…",recordingSaving:"正在保存录屏…",captureFailed:"插入失败",captureUnavailable:"当前无法插入到终端",more:"更多",fullscreen:"全屏",fillSidebar:"铺满侧栏",exitFullscreen:"退出全屏",fullscreenHint:"投屏正在全屏显示。",quality:"画质",qualityAutoHint:"根据连接与解码表现动态调码率,不断流、不重连。分辨率保持稳定,操作和服务端录屏不受影响。",qualityAutoUnavailable:"自动调码率已暂停,画面保持连接。",qualityAutoVersionError:"服务端 scrcpy 版本尚未适配(点击查看详情)。",qualityAutoBuildError:"服务端 scrcpy 文件尚未验证兼容(点击查看详情)。",qualityAutoExtensionError:"调码率扩展文件读取、校验或推送失败(点击查看详情)。",qualityAutoTimeoutError:"调码率确认超时,不能据此判断编码器不支持(点击查看详情)。",qualityAutoEncoderError:"设备编码器拒绝了这次调节(点击查看详情)。",qualityAutoChannelError:"调码率控制通道异常(点击查看详情)。",qualityAutoUnknownError:"服务端未提供具体原因,请更新该服务端后重试(点击查看详情)。",qualityLow:"流畅",qualityMedium:"标准",qualityHigh:"高清",qualityCustom:"自定义",qualityResolution:"分辨率",qualityBitRate:"码率",qualityFrameRate:"帧率",qualityAuto:"自动",qualityApply:"应用",presetNamePlaceholder:"预设名称",presetSave:"保存预设",presetDelete:"删除预设",stateUnauthorized:"未授权",stateOffline:"离线",stateUnknown:"状态未知",unauthorizedHint:"请在手机上确认 USB 调试授权。",offlineHint:"设备离线,请重新插拔或重连。"},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:e})=>`请稍候 ${e}s`,submit:"登录",invalidPassword:"密码不正确,或服务身份无法验证。请检查后重试。",identityMismatch:"服务身份已改变。请与服务所有者核对地址后再试。",unavailable:"暂时无法登录此服务,请检查连接后重试。",authorizationRequired:"此设备需要授权。请向服务所有者索取新的邀请。",currentTarget:({address:e})=>`正在登录 ${e}`,manageServices:"管理服务 / 使用其他地址",failed:"暂时无法登录,请检查连接后重试。",rateLimited:"尝试次数较多,请稍后再试。",continueAfterReconnect:"网络恢复后可继续登录。",savedConnectionRetained:"已保留服务记录,恢复连接后会重新检查访问权限。",invalidAddress:"请输入有效的 HTTPS 服务地址,例如 computer.example:9834 或 https://computer.example:9834。",invalidInvitation:"邀请链接不完整或无效,请重新复制完整链接后重试。"},sidebar:{sessionCreating:"正在启动…",sessionCreateDirectoryUnavailable:"工作目录已失效,请重新选择目录后重试。",sessionCreatePermissionDenied:"没有权限在此目录启动,请选择其他目录。",sessionCreateConnectionFailed:"连接失败,请检查连接后重试。",sessionCreateFailed:"无法启动会话,请重试。",sessions:"会话",noSessions:"暂无打开的会话。",noMatchingSessions:"没有匹配的会话。",toggleSearch:"切换搜索",settings:"设置",moreActions:"更多操作",subscriptionQuota:"订阅额度",pinSidebar:"常驻边栏",unpinSidebar:"取消常驻",runningSessionButton:"运行中会话按钮",runningSessionButtonHint:"轻点循环,横向滑动选择,长按拖动",attentionButton:"待处理提醒按钮",attentionButtonHint:"显示未读、等待处理的黄色悬浮铃铛",updateAvailable:({version:e})=>`Termdock ${e} 可用`,updateInstalling:"正在后台安装,不会中断当前服务。",updateReady:"更新已安装,确认后将重启服务。",updateRestart:"重启并完成更新",updateRestartConfirm:({version:e})=>`确认重启 Termdock 并切换到 ${e}?当前网页会短暂重连,会话不会被关闭。`,updateRestarting:"正在重启,网页将自动重连…",updateFailed:"自动安装失败,提醒会保留。",updateRetry:"重新尝试",serverAttention:"服务出过问题",filterSessions:"过滤会话",clearSearch:"清除搜索",groupByFolder:"按文件夹分组",groupByFolderTitle:"按工作目录把会话归组折叠;与拖拽排序互斥。",ungrouped:"其他",needsAttention:"待处理",waitingForYou:"等你操作",completedUnread:"完成待查看",closeSession:({name:e})=>`关闭 ${e}`,newShell:"Shell",newTmux:"Tmux",newTmuxDisabled:"服务端未安装 tmux",confirmNewShell:"创建 Shell?",confirmNewTmux:"创建 Tmux?",newSession:"新建 Terminal",newSessionWithAgent:({agent:e})=>`新建 ${e}`,moreLaunchOptions:"更多启动选项",recoverableSessions:"可恢复会话",confirmCloseRecoverableSession:({name:e})=>`结束 ${e}?这会停止该会话中的所有进程。`,endRecoverableSession:"结束会话",closeRecoverableSessionFailed:"结束会话失败,请重试。",refreshRecoverableSessions:"刷新可恢复会话",restoreRecoverableSession:({name:e})=>`恢复 ${e}`,restoringRecoverableSession:"恢复中…",restore:"恢复",newSessionAdvanced:"快速启动 Agent",newSessionComposerTitle:"开始新会话",newSessionHint:"选好运行方式和目录后再启动",launchSessionWith:({name:e})=>`启动 ${e}`,setNewSessionDefault:({name:e})=>`将 ${e} 设为默认`,currentNewSessionDefault:({name:e})=>`${e} 是当前默认`,currentDefaultAgent:({name:e})=>`当前默认:${e}`,defaultAgent:"默认",makeDefault:"设为默认",sessionMode:"运行方式",tmuxKeepsRunning:"断开后继续运行",resumeHistory:"最近会话",resumeHistoryCount:({n:e})=>`已保存 ${e} 条`,resumeHistoryLoading:"正在载入最近的 Agent 会话…",resumeHistoryAction:({title:e})=>`恢复 ${e}`,resumeHistoryRemove:({title:e})=>`从最近会话中移除 ${e}`,resumeHistoryLoadFailed:"无法载入最近的 Agent 会话。",resumeHistoryFailed:"无法准备恢复该 Agent 会话。",resumeHistoryRemoveFailed:"无法从历史中移除该会话。",customStartupCommand:"自定义命令",changeStartupCommand:"更改启动命令",saveStartupCommand:"保存命令",startupCommandSaved:"已保存",saveStartupCommandFailed:"保存失败,请检查浏览器存储权限",addStartupCommand:"新增自定义命令…",deleteStartupCommand:"删除命令",startupCommand:"启动命令",resetStartupCommand:"恢复默认",startupCommandPlaceholder:"例如 vim、htop 或 npm run dev",agentStartupCommandHint:"可修改完整命令;留空使用 Agent 默认命令。保存到当前浏览器。",terminalStartupCommandHint:"在所选目录启动程序,例如 vim README.md。保存到当前浏览器。",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:"不显示隐藏文件",hideGitIgnoredFiles:"隐藏 Git 忽略文件",showGitIgnoredFiles:"显示 Git 忽略文件",gitIgnoreSaveFailed:"保存 Git 忽略文件显示设置失败,请重试",gitIgnoreConfigureHint:"长按或右键配置例外",gitIgnoreExceptionsTitle:"Git 忽略过滤例外",gitIgnoreExceptionsHint:"勾选过滤开启时仍需显示的文件或目录。点击目录右侧箭头可进入选择;选中目录会包含所有子项,文件的父目录会自动保留。保存后生效。",gitIgnoreExceptionsPaths:"选择文件或目录",gitIgnoreExceptionsInvalid:"最多选择 200 个文件或目录。",gitIgnoreExceptionsLoadFailed:"无法加载目录,请重试。",gitIgnoreExceptionsEmptyDirectory:"此目录为空",gitIgnoreExceptionsOpenDirectory:({name:e})=>`进入目录 ${e}`,gitIgnoreExceptionsSelected:({count:e})=>`已选 ${e} 项`,gitIgnoreExceptionsClear:"清空选择",gitIgnoreExceptionsRemove:({path:e})=>`移除 ${e}`,gitIgnoreExceptionsTruncated:"此目录项目过多,仅显示部分内容。",gitIgnoreExceptionsSaveFailed:"保存失败,请检查路径是否位于当前目录内(最多 200 个),然后重试。",insertCurrentFolder:"引用当前目录",insertCurrentFolderShort:"引用",pinnedFolders:"固定",unpinFolder:({name:e})=>`取消固定 ${e}`,fileWatchUnavailable:({message:e})=>`文件监听不可用:${e}。可点击手动刷新。`,browsingOutsideProject:"正在浏览当前项目外目录",browsingOutsideProjectHint:"Git 和改动仍使用当前项目;这里引用的文件会按外部路径插入。",toggleSearch:"切换搜索",refreshGit:"刷新 Git 状态",gitLastUpdated:({time:e})=>`上次更新:${e}`,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:e})=>`已加载 ${e} 条 hunk 解释`,changeAuditLoadedAt:({time:e})=>`最近生成 ${e}`,changeAuditRegenerate:"重新生成",changeAuditRefreshStale:"补充失效",changeAuditRefreshStaleTitle:"为已失效的 hunk 解释插入补充生成提示词",clearChangeAudit:"清理改动解释",clearChangeAuditTitle:"清理当前仓库的 hunk 解释",changeAuditClearFailed:({message:e})=>`清理 hunk 解释失败:${e}`,changeAuditScopeAll:"全部仓库",changeAuditScopeLabel:"解释范围",branchAuditTitle:"分支解释",branchAuditShort:"解释分支改动",branchAuditBaseLabel:"基线分支",branchAuditBasePlaceholder:"基线分支,例如 master",branchAuditBaseSearchPlaceholder:"搜索基线分支",branchAuditBaseEmpty:"没有可选分支,可直接输入分支名",branchAuditGenerate:"生成解释",branchAuditRegenerate:"重新生成",branchAuditGenerateTitle:"生成当前分支相对于基线分支的解释提示词",branchAuditViewDiff:"查看对比",branchAuditViewDiffTitle:"查看目标分支相对于基线分支的改动",branchAuditDiffLoading:"正在加载分支对比…",branchAuditDiffEmpty:"当前分支相对于基线分支暂无改动。",branchAuditMissingBase:({repo:e})=>`${e} 未设置基线分支`,branchAuditRefreshDiff:"刷新对比",branchAuditRefreshStale:"补充失效",branchAuditRefreshStaleTitle:"为已失效的分支解释插入补充生成提示词",branchAuditClearTitle:"清理当前分支解释",branchAuditClearFailed:({message:e})=>`清理分支解释失败:${e}`,branchAuditCommitCount:({count:e})=>`${e} 个提交`,branchAuditFileCount:({count:e})=>`${e} 个文件`,branchAuditTruncated:"diff 已截断",branchAuditCurrent:"已保存解释",branchAuditStale:"解释已失效",branchAuditEmpty:"暂无分支解释。生成后会持久化保存,可随时回来查看。",branchAuditView:"查看解释",branchAuditSaved:({count:e})=>`已保存 ${e} 条 hunk 解释`,branchAuditGeneratedAt:({time:e})=>`生成于 ${e}`,insertPreset:({label:e})=>`插入:${e}`,tabChanges:"改动",tabGit:"Git",tabFiles:"文件",tabAndroid:"设备",tabComputer:"电脑",showAndroidTab:"显示设备 Tab",showArchitectureTab:"显示架构 Tab",showComputerTab:"显示电脑 Tab",inserted:"已插入",copied:"已复制",toggleContextDraft:"切换上下文草稿",contextDraftTitle:"上下文草稿",contextDraftHint:"启用后,引用会追加到这里;可以继续浏览、补写描述,最后一次插入。",contextDraftPlaceholder:"在这里组织长提示词,继续点击侧栏中的引用来追加上下文…",contextDraftCollapse:"收起上下文草稿",contextDraftExpand:"展开上下文草稿",contextDraftDisable:"停用上下文草稿",contextDraftClear:"清空草稿",contextDraftInsert:"插入",contextDraftInsertAndSend:"插入并发送",contextDraftInserted:"已插入",contextDraftSent:"已发送",contextDraftSend:"发送草稿",contextDraftAppended:"已追加引用",contextDraftResize:"拖动调整高度,双击恢复默认",contextDraftAutoCollapseAfterSend:"插入/发送后收起",referenceInsertFailed:"未能插入,请检查目标终端连接后重试。",contextDraftInsertFailed:"输入未被接受,草稿已保留。关闭当前表单或返回终端后重试。",contextDraftPending:"等待接收…",contextDraftCharacterCount:({count:e})=>`${e} 字`,selectFilePrompt:"选择文件以预览内容",backToFileList:"返回文件列表",backToPreviousPreview:"返回来源文档",insertLineRef:({lineLabel:e})=>`引用${e}`,insertFileRef:"引用",copyFileRef:"复制文件引用",findInFile:"在文件内查找",findInFilePlaceholder:"在当前文件中查找…",previousSearchMatch:"上一个匹配项",nextSearchMatch:"下一个匹配项",closeFileSearch:"关闭文件搜索",downloadFile:"下载文件",downloadFailed:"下载失败",downloadCanceled:"下载已取消",downloadSaved:"文件已保存",downloadStarted:"浏览器已开始下载",uploadPending:"正在上传…",uploadInserting:"文件已上传,等待输入接收…",uploadDone:({count:e})=>`已上传 ${e} 个文件`,uploadReferenceDone:"文件已上传,引用已添加",uploadReferenceRejected:"文件已上传,引用尚未添加。关闭当前表单或返回原终端后重试。",uploadLimit:"每次最多上传 50 个文件。本次未上传,请重新选择较小批次。",uploadCanceled:"已停止上传。再次上传前请检查目标目录。",uploadFileCount:({count:e})=>`已选择 ${e} 个文件`,uploadFile:"上传文件",uploadFiles:"上传文件",insertLocalFile:"插入本地文件",insertLocalImage:"插入本地图片",layoutMode:"显示模式",layoutModeAuto:"自动",layoutModeNarrow:"窄版",layoutModeWide:"宽版",dropToUpload:"拖放文件以上传",uploading:"上传中…",uploadSuccess:({count:e})=>`已上传 ${e} 个文件`,uploadFailed:"上传失败",binaryPreviewHint:"二进制文件无法预览,请使用上方下载按钮保存到本地",selectedLineHint:({lineLabel:e})=>`已选 ${e} · 点下方「引用」按钮插入`,multiLineHint:"多行引用:先点起始行,再点结束行",loadingImage:"正在加载图片…",imagePreviewHint:"双指捏合或 ⌘/Ctrl + 滚动缩放 · 双击还原",imageLoadFailed:"图片预览加载失败",loadingVideo:"正在加载视频…",videoPreviewHint:"点击播放 · 长按 2× 并前拖提速 · 方向键调进度/音量 · 空格暂停",videoLoadFailed:"视频预览加载失败",videoUnsupported:"当前浏览器不支持该视频格式",videoPlay:"播放",videoPause:"暂停",videoLongPressSpeed:({rate:e})=>`正在 ${e}× 播放`,videoVolume:({percent:e})=>`音量 ${e}%`,videoRotate:"顺时针旋转 90°",videoFullscreenEnter:"全屏播放",videoFullscreenExit:"退出全屏",model3dLoading:"正在加载 3D 模型…",model3dExplode:"爆炸展开",model3dExplodeAxis:"展开方向(查看器坐标)",model3dExplodeAmount:"展开程度",model3dHome:"回正并看全",model3dFit:"看全可见零件",model3dFront:"正视图",model3dTop:"俯视图",model3dRight:"右视图",model3dAssemble:"恢复装配",model3dExplodedNotice:"爆炸展示 · 尺寸与引用仍为原始装配坐标",model3dLoadFailed:"3D 模型预览加载失败",model3dTimeout:"3D 模型传输超时,请检查连接后重试。",model3dDimensions:({dims:e})=>`尺寸: ${e}`,model3dHintMouse:"拖拽旋转 / 双指平移 / 捏合或滚轮缩放",model3dHintTouch:"单指旋转 / 双指缩放平移",model3dFullscreenEnter:"全屏查看",model3dFullscreenExit:"退出全屏",model3dBgToLight:"切换为白底",model3dBgToDark:"切换为黑底",model3dRefresh:"重新加载模型",model3dClipToggle:"切面查看",model3dClipPosition:"切面位置",model3dClipFlip:"反转切面方向",model3dFeatureToggle:"特征标注",model3dFeatureStatus:({total:e,positioned:t})=>`特征: ${e} 个 · 已定位 ${t}`,model3dFeatureInsert:"引用",model3dGlossaryToggle:"建模名词说明",model3dPickToggle:"选择零件 / 引用",model3dPickHint:"点选零件后可临时隐藏,或引用所选位置",model3dHidePart:"隐藏零件",model3dShowAllParts:({count:e})=>`显示全部(${e})`,model3dParts:"零件",model3dCloseParts:"关闭零件列表",model3dSearchParts:"查找零件",model3dClearPartSearch:"清空零件搜索",model3dHiddenParts:({count:e})=>`已隐藏 ${e}`,model3dShowNamedPart:({name:e})=>`显示 ${e}`,model3dHideNamedPart:({name:e})=>`隐藏 ${e}`,model3dIsolateNamedPart:({name:e})=>`只看 ${e}`,model3dIsolatePart:"只看此件",model3dShowPart:"显示零件",model3dNoParts:"没有匹配的零件",model3dUndoVisibility:"撤销",model3dClearSelection:"取消选择",model3dAllPartsVisible:"全部可见",model3dInspectHint:"单指旋转 · 双指缩放平移 · 双击局部放大,双击空白看全",model3dUnnamedPart:({index:e})=>`零件 ${e}`,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:e,y:t})=>`已选位置 ${e}%, ${t}%`,edaPickedBoardPosition:({x:e,y:t,object:n})=>`板坐标 ${e}, ${t} mm · ${n}`,edaInspecting:"正在读取板坐标和附近对象…",edaNoNearbyObject:"附近无对象",edaInsertAnnotation:"引用电子标注",csvUnnamedColumn:({index:e})=>`第 ${e} 列`,csvSelectedCell:({row:e,column:t})=>`已选第 ${e} 行 · ${t}`,csvPickHint:({rows:e,columns:t})=>`${e} 条记录 · ${t} 列,点击单元格引用`,csvInsertAnnotation:"引用表格标注",csvTablePreview:"表格预览:点击单元格后可引用完整记录",kicadLocalStateNotice:"这是本机界面状态文件,不参与原理图、PCB 或生产审查。",kicadShowRawJson:"查看原始 JSON",kicadProjectPickHint:"点击一项配置后可插入引用",kicadInsertSetting:"引用配置",markdownPreview:"预览",markdownSource:"源码",markdownParseFailed:"Markdown 预览解析失败或超过限制,已显示原文。",markdownPreviewHint:"点按行/段落引用,再点一行扩选;拖左侧竖条可连续框选",htmlPreview:"预览",htmlSource:"源码",htmlPreviewHint:"HTML 沙箱 iframe 预览,脚本受限",htmlFullscreenEnter:"全屏预览",htmlFullscreenExit:"退出全屏预览",markdownOutline:"Markdown 目录",markdownOutlineShort:"目录",closeMarkdownOutline:"关闭目录",changedFromPath:({path:e})=>`来自 ${e}`,selectedLineFooter:({lineLabel:e})=>`已选 ${e}`,clearSelection:"清除",allChanges:"全部改动",backToChangeList:"返回目录",allRepositories:"全部仓库",allRepositoriesShort:"全部",repositories:"仓库",gitRepositorySectionTitle:"操作仓库",gitRepositoryLabel:"仓库",gitRepositoryPlaceholder:"选择仓库",gitRepositorySearchPlaceholder:"搜索仓库",gitRepositoryEmpty:"没有可操作的仓库",selectRepositoryForGitActions:"请选择一个仓库后再执行 Git 操作",selectRepositoryForDiff:"选择一个仓库或文件查看 diff",repoNotLoaded:"点击加载",repoChangedCount:({count:e})=>`${e} 个改动`,repoStagedCount:({count:e})=>`${e} 已暂存`,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:e})=>`已暂存 ${e}`,stagedCountShort:({count:e})=>`已暂存 ${e}`,commitSectionTitle:"提交",commitReadyHint:({count:e})=>`${e} 个文件已准备提交`,commitMessagePlaceholder:"提交信息",commitChanges:"提交",commitNeedsStaged:"请先暂存要提交的改动",commitAhead:"↑ 待推送",commitBehind:"↓ 待拉取",commitSynced:"已同步",recentCommitsTitle:"近期提交",recentCommitsSearchPlaceholder:"搜索提交 hash 或信息",recentCommitsLoadMore:"加载更多提交",recentCommitsEmpty:"暂无提交历史",pushSectionTitle:"同步远端",pushRemoteLabel:"Remote",pushRemotePlaceholder:"origin",pushRemoteSearchPlaceholder:"搜索 Remote",pushNoRemotes:"没有 Remote",pushBranchLabel:"目标分支",pushBranchPlaceholder:({branch:e})=>`${e}`,pushBranchSearchPlaceholder:"搜索分支",pushNoBranches:"没有分支",pushUpstreamBadge:"upstream",pushCurrentBranchBadge:"当前",pushNoUpstream:"当前分支未设置 upstream",pushUpToDate:"与远端同步",pushAheadCount:({count:e})=>`领先远端 ${e} 个提交`,pushBehindCount:({count:e})=>`落后远端 ${e} 个提交`,pushDivergedCount:({ahead:e,behind:t})=>`领先 ${e} / 落后 ${t} 个提交`,pullChanges:"拉取",pushChanges:"推送",gitActionRunning:"执行中…",gitActionFailed:({message:e})=>`Git 操作失败:${e}`,confirmRestoreTitle:"确认丢弃改动",confirmRestoreDescription:({path:e})=>`将丢弃 ${e} 的未暂存改动,此操作不可从 Termdock 恢复。`,confirmRestorePhrase:"丢弃改动",confirmRestorePlaceholder:"输入“丢弃改动”确认",confirmStashAllTitle:"确认贮藏全部改动",confirmStashAllDescription:"会把当前工作区改动(包含未跟踪文件)移入贮藏。",confirmAction:"确认",renderingHtml:"正在渲染 HTML…",footnotes:"脚注",backToFootnote:({index:e})=>`返回脚注 ${e}`,openMermaidDiagram:"打开 Mermaid 图表",mermaidDiagram:"Mermaid 图表",renderingDiagram:"正在渲染图表…",markdownImage:"Markdown 图片",image:"图片",previousImage:"上一张图片",nextImage:"下一张图片",closeImagePreview:"关闭图片预览",emptyFile:"空文件。",insertReference:({reference:e})=>`插入引用:${e}`,copyReference:({reference:e})=>`复制引用:${e}`,byteCount:({count:e})=>`${e} 字节`,previewTruncated:"预览已截断至 1 MB",branchCandidatesLoading:"正在加载分支候选…",includeUncommitted:"包含本地未提交改动",includeUncommittedCurrentBranchOnly:"仅当对比分支是当前检出分支时可开启",includeUncommittedHint:"查看对比或生成解释时纳入工作区和未跟踪文件的 diff",missingBaseReposSkipped:({repositories:e})=>`未设置基线的仓库会跳过:${e}`,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:e})=>`确认删除“${e}”?此操作无法撤销。`,deleteFileFailed:({message:e})=>`删除文件失败:${e}`,noWorkingDir:"未检测到工作目录。",emptyDir:"空目录。",noMatchingFiles:"没有匹配的文件。",searching:"正在搜索文件…",searchingWithCount:({count:e})=>`搜索中…已找到 ${e} 项`,searchResults:({count:e})=>`${e} 个结果`,searchScope:"搜索范围",searchTruncatedHint:({count:e})=>`降级搜索已扫描大量目录并在找到 ${e} 项后停止。安装 ripgrep 或输入更精确关键词可获得完整结果。`,searchStillRunning:"搜索仍在进行,更多结果会自动出现。",showingSearchResults:({shown:e,total:t})=>`正在展示 ${e}/${t}`,loadMoreSearchResults:({shown:e,total:t})=>`查看更多(${e}/${t})`,contentMatchesCount:({count:e})=>`${e} 个文件命中`,moreMatches:({count:e})=>`还有 ${e} 处匹配`,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",insertLineDiff:"引用选中的这几行 diff",insertHunkShort:"引用",insertFileShort:"引用",insertAllShort:"全部",stageHunk:"暂存",stageHunkTitle:"只把这个 hunk 加入暂存区 (git apply --cached)",revertHunk:"撤销",revertHunkTitle:"撤销这个 hunk 的工作区改动(不可恢复)",revertHunkConfirm:"确认撤销?",hunkActionReverted:"已撤销",hunkActionStaged:"已暂存",hunkActionApplying:"应用中…",hunkActionUnavailable:"无法为这个 hunk 构造补丁",hunkActionFailed:({message:e})=>`操作失败:${e}。如改动已变化,请刷新后重试。`,auditExplanation:"更改意义",auditStale:"解释已失效",auditClear:"清除解释",auditGeneratedAt:({time:e})=>`生成于 ${e}`,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:"上下文",expandAbove:({count:e})=>`向上展开 ${e} 行`,expandBelow:({count:e})=>`向下展开 ${e} 行`,contextLines:({count:e})=>`${e} 行`,contextAll:"全部"},settings:{title:"设置",font:"字体",render:"渲染",workspaceLimit:"保留服务页面",workspaceUnlimited:"不限制",workspaceLimitHint:"在本机生效,包含入口页面。数量越少越省内存;超限释放最久未用的后台页面,切回时重新连接,终端任务继续运行。",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:"桌面版已是最新版本。",desktopUpdateDownloadingShort:"下载中…",desktopUpdateDownloading:"发现新版本,正在后台下载…",desktopUpdateReady:"桌面版更新已下载,可以重启安装。",desktopUpdateInstalling:"正在重启并安装桌面版更新…",desktopUpdateCheck:"检查桌面版",desktopUpdateCheckAgain:"再次检查",desktopUpdateRestart:"重启并安装",desktopUpdateRestartConfirm:"重启 Termdock 并安装已下载的桌面版更新?终端服务和 tmux 会话不会被停止。",serverHealthTitle:"服务健康",serverHealthHint:"Termdock 服务最近出过什么事。",serverHealthSupervised:"自动恢复已开启:服务崩溃或无响应时会尝试自动重启。",serverHealthUnsupervised:"内置自动恢复未开启,服务异常退出后可能需要手动重启。",serverHealthEnable:"开启并重启",serverHealthEnableHint:"开启后会重启服务并短暂断连。普通终端可能中断,tmux 会话可在重连后恢复。连续多次启动失败时会停止重试。",serverHealthEnabling:"正在开启…",serverHealthEnablePending:"等待服务重连并确认自动恢复状态…",serverHealthEnableError:"未能确认自动恢复已开启。请重连后查看状态;若服务无法连接,请在服务所在设备检查启动日志。",serverHealthEnableUnavailable:"当前启动方式不支持在此开启。请在服务所在设备配置守护启动;桌面版或外部托管服务由原启动程序管理。",serverHealthClean:"没有异常记录。",serverHealthHistory:"历史异常",serverHealthRunningNow:"当前服务正在运行,自动恢复已开启。",serverHealthLastIncident:"最近一次异常",serverHealthRestarted:({count:e})=>`已自动重启 ${e} 次`,serverHealthGaveUp:({count:e})=>`连续失败 ${e} 次后,该守护进程已停止重试。`,serverHealthSupervisorLost:"自动恢复已失效,服务仍在运行。",serverHealthOomNote:"退出前内存接近上限,可能是被 OOM killer 杀掉的。",serverHealthUptime:({duration:e})=>`运行了 ${e}`,serverHealthDismiss:"知道了",serverHealthDismissed:"已确认",serverHealthUnknownEvent:"服务出过问题",serverHealthEventStartupFailure:"启动失败",serverHealthEventCrash:"崩溃退出",serverHealthEventCrashNative:"原生代码崩溃",serverHealthEventKilled:"被强制杀掉",serverHealthEventWedge:"卡死无响应,只能杀掉",serverHealthEventPortConflict:"起不来:端口已被占用",serverHealthEventGaveUp:"当时连续失败,停止重试",serverHealthEventExitZero:"未经要求地以 0 退出",serverHealthEventTerminated:"被其他进程终止",serverHealthEventSupervisorLost:"与监督者失联",serverHealthEventUncaughtException:"触发了未捕获异常",serverHealthEventUnhandledRejection:"有未处理的 Promise 拒绝",serverHealthEventExitNonzero:"以错误码退出",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:e})=>`${e} 个会话`,windows:({n:e})=>`${e} 个窗口`,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:"连接地址与手机访问引导",resetAutoName:"恢复自动",mobileSetupIntro:"手机与此服务需处于同一网络。启用 HTTPS 时,先安装并信任本地 CA 证书,再打开下方访问地址。",mobileSetupDownload:"1. 扫码下载 CA 证书",mobileSetupIos:"iPhone / iPad:用相机扫码后在 Safari 打开。在「设置 → 通用 → VPN 与设备管理」安装已下载的描述文件,再到「设置 → 通用 → 关于本机 → 证书信任设置」开启完全信任。",mobileSetupAndroid:"Android:下载证书后,在系统安全设置中将其安装为 CA 证书。不同品牌的菜单名称可能有所不同。",mobileSetupConnect:"2. 打开 Termdock",mobileSetupConnectHint:"信任证书后,扫描下方 IP 地址二维码,或将本地地址复制到手机浏览器。若域名无法解析,请使用 IP 地址。",onboardingUrl:"手机引导",httpsActive:"HTTPS 已启用",httpsInactive:"HTTPS 未启用",caMissing:"未配置 CA 下载",closeSettings:"关闭设置",desktopTitle:"Termdock 桌面端",desktopStatusLoading:"正在读取 macOS 原生状态…",desktopSwitchService:"切换服务",desktopOpenDataDirectory:"打开数据目录"},toolbarPresets:{preview:"预览",presets:"预设",label:"标签",new:"新建",reset:"重置",presetLabelPlaceholder:"预设名称",deletePreset:({name:e})=>`删除预设 ${e}`,matchPrograms:"匹配程序",typeEnterHint:"输入后回车",programsPlaceholder:"vim, nvim, /^claude(-code)?$/i …",programsHelp:"纯字符串按大小写不敏感子串匹配。用 /…/flags 包裹则为正则(针对小写程序名测试)。",altSlot:"Alt 修饰键槽",altSlotHint:"在预览中保留一个 Alt 键槽位。",desktopVisibility:"桌面端显示",desktopVisibilityHint:"桌面端只显示该预设的自定义按钮,不显示基础快捷键。",rowLayout:"行布局",rowLayoutHint:"每行按钮数。",addRow:"行",rowN:({n:e})=>`第 ${e} 行`,del:"删",buttons:"按钮",buttonsHint:"点击编辑,使用 ↑↓ 排序。",addButton:"添加按钮",noCustomButtons:"暂无自定义按钮。添加一个来覆盖默认工具栏。",moveUp:"上移",moveDown:"下移",removeRow:({n:e})=>`移除第 ${e} 行`,removeAction:({name:e})=>`移除 ${e}`,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:"复制当前工作目录",fontSize:"字体大小",fontSizeHint:"仅对这个会话生效",fontSizeReset:"跟随全局",resumeAgent:"恢复 Agent 会话",resumeAgentHint:"用原生 session id 恢复上次对话",resumeAgentAvailable:"有可恢复的 Agent 对话",resumeAgentRecoveredTitle:({agent:e})=>`可继续上次的 ${e} 对话`,resumeAgentRecoveredHint:"Terminal 曾异常中断,已重新创建;可以从上次对话继续。",resumeAgentNow:"恢复",resumeAgentLater:"暂不恢复",resumeAgentSubmitting:"正在提交原生恢复命令…",resumeAgentWaiting:"正在等待 Agent 确认已载入原会话…",resumeAgentSuccess:({agent:e})=>`${e} 会话已恢复`,resumeAgentFailed:"Agent 会话恢复失败,可以重试。",resumeAgentConflict:"该 Agent 会话已在另一个 Terminal 中打开。",resumeAgentBusy:"当前 Agent 回合尚未结束,暂时不能恢复。",resumeAgentTimeout:"Agent 未确认已载入原会话,请查看 Terminal 输出或重试。",tmuxRecoveryTitle:({count:e})=>`${e} 个 Agent 会话待恢复`,tmuxRecoveryHint:"Termdock 保留了原生会话 ID。恢复操作会在原标签页中继续之前的对话。",tmuxRecoveryRestoreAll:"恢复全部",tmuxRecoveryRestoring:"正在恢复…",tmuxRecoveryDismiss:"暂不处理",tmuxRecoveryPartial:({restored:e,failed:t})=>`已恢复 ${e} 个,${t} 个需要重试。`,tmuxRecoveryFailed:"恢复失败,请检查终端状态后重试。",tmuxRecoveryDismissFailed:"暂时无法关闭该恢复提示。",tmuxRecoveryProgress:({total:e,queued:t,paused:n,resourceWait:r,running:o,succeeded:s,failed:i})=>`恢复进度:总计 ${e} · 排队 ${t} · 暂停 ${n}(资源等待 ${r}) · 执行中 ${o} · 完成 ${s} · 失败 ${i}`,tmuxRecoveryPausedForResources:"资源不足,已暂停启动;资源恢复后会自动继续。",tmuxRecoveryPause:"暂停",tmuxRecoveryResume:"继续",tmuxRecoveryInProgress:"恢复进行中",copied:"已复制",close:"关闭会话",closeHint:"从列表移除该标签",longPressTip:"提示:按住标签不动约半秒打开操作菜单,按住并拖动可排序。",sessionsTitle:"会话",explorerTitle:"资源管理器",split:"分屏",splitTitle:"添加到分屏工作区",closeFailed:({name:e})=>`未能关闭「${e}」。会话仍保留,请重试。`,splitNew:"新建会话并加入",splitNewHint:"沿用当前目录和默认会话类型;可连续加入多个会话",splitExisting:"选择已有会话或工作区",splitExistingHint:"会话可组成多个独立工作区;选择另一工作区会将两组合并",splitCurrent:"当前",splitClose:"退出分屏",splitLayout:"分屏布局",splitHorizontal:"左右",splitVertical:"上下",splitGrid:"网格",splitWorkspace:"分屏组",splitWorkspaces:"分屏工作区",splitRename:"重命名分屏组",splitRemovePane:"移出分屏",splitExistingGroups:"已有分屏组",splitAvailableSessions:"可加入的会话",splitOccupied:"已成组",splitUnavailableGrouped:"分组模式下只能分屏同一目录的会话",splitEndedGrouped:"已退出分屏:分组模式不支持跨目录组合",splitNoOtherSessions:"没有可组合的其他会话",sessionCount:({count:e})=>`${e} 个会话`,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:"当前"},serviceAttention:{title:"所有服务的待处理",summary:"{services} 个服务 · {count} 个会话",currentService:"当前服务",waiting:"等待你处理",offline:"连接已断开 · 显示上次状态",login:"需要重新登录 · 显示上次状态",empty:"暂时没有待处理会话",viewService:"进入服务查看",scope:"汇总已打开的服务,点会话直接进入",changed:"待处理状态已更新,请重新选择。",unavailable:"暂时无法打开该服务,请从服务列表重试。"},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:e})=>`剩余 ${e}`,updated:({time:e})=>`${e} 更新`,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:"联系技术支持"}}},RA=["en","zh"],Hr="en",cl=new WeakMap;let kA=0;function TA(e,t,n){const r=cl.get(e);if(!r?.pending||r.pending.id!==t)return;const o=performance.now();if(!document.hidden&&o-r.lastPoll<2500){const s=o-r.pending.sentAt;r.samples.push(s<8e3?s:null),r.samples=r.samples.slice(-20),s<8e3&&(r.lastReply=o,r.handlerMs=typeof n=="number"&&Number.isFinite(n)&&n>=0&&n<=s?n:void 0)}r.pending=void 0}function PA(e){const t={connected:!1,rtt:null,average:null,jitter:null,timeouts:0,samples:0,waiting:!1};if(!e||e.readyState!==WebSocket.OPEN)return t;const n=performance.now();let r=cl.get(e);if(r||(r={lastPoll:n,lastSent:-1/0,lastReply:-1/0,samples:[]},cl.set(e,r)),(document.hidden||n-r.lastPoll>=2500)&&(r.pending=void 0,r.lastSent=-1/0,r.lastReply=-1/0),r.lastPoll=n,!document.hidden&&(r.pending&&n-r.pending.sentAt>=8e3&&(r.samples.push(null),r.samples=r.samples.slice(-20),r.pending=void 0),!r.pending&&n-r.lastSent>=5e3)){const l=`quality-${++kA}`;r.pending={id:l,sentAt:n},r.lastSent=n;try{e.send(JSON.stringify({type:"ping",qualityProbeId:l}))}catch{return r.pending=void 0,t}}const o=r.samples.filter(l=>l!==null),s=r.samples[r.samples.length-1],i=n-r.lastReply<15e3,a=o.slice(1).map((l,d)=>Math.abs(l-o[d])),c=[...o].sort((l,d)=>l-d);return{diagnostics:e.getConnectionDiagnostics?.(),minimum:c[0],maximum:c[c.length-1],p95:c[Math.ceil(c.length*.95)-1],history:[...r.samples],handlerMs:i&&s!=null?r.handlerMs:void 0,lastReplyAgeMs:Number.isFinite(r.lastReply)?n-r.lastReply:void 0,connected:!0,rtt:i&&s!=null?Math.round(s):null,average:o.length?Math.round(o.reduce((l,d)=>l+d,0)/o.length):null,jitter:a.length?Math.round(a.reduce((l,d)=>l+d,0)/a.length):null,timeouts:r.samples.length-o.length,samples:r.samples.length,waiting:!!r.pending&&n-r.pending.sentAt>=1500}}function NA(e){const t=e.serviceLabel?.trim();if(!t||/^https?:\/\//i.test(t)||t===e.serviceOrigin)return"远端服务";try{const n=new URL(e.serviceOrigin??"");if(t===n.host||t===n.hostname)return"远端服务"}catch{}return t}function W2(e,t){const n=s=>{const i=s.name.trim();return!i||/^(?:tmux:|remote:|wt-)/i.test(i)||i===s.sessionId?s.agent?.displayName?.trim()||"成员":i},r=n(e),o=t.filter(s=>n(s)===r);return o.length>1?`${r} ${o.findIndex(s=>s.sessionId===e.sessionId)+1}`:r}function G2(e){return e.serviceConnected===!1||["offline","disconnected","service-unreachable","closed","exited"].includes(e.status??"")?"disconnected":e.serviceConnected===!0?"connected":"unknown"}function yo(e){if(!e.startsWith("remote:"))return null;const t=e.slice(7).split(":");if(t.length!==2)return null;try{const n=decodeURIComponent(t[0]),r=decodeURIComponent(t[1]);return!r||new URL(n).origin!==n||!/^https?:/.test(n)?null:{origin:n,id:r}}catch{return null}}class LA{constructor(t){this.source=t,this.peers={state:t.peerProtocol==="unsupported"?"unsupported":t.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(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}snapshot(){if(!this.local)return null;const t=new Map;for(const n of this.local.groups)for(const r of n.remoteSessions??[]){const o=yo(r.sessionId);o&&o.origin!==this.source.origin&&o.origin!==this.source.peerOrigin&&t.set(r.sessionId,{...r,status:"offline",serviceConnected:!1})}for(const n of this.remote)t.set(n.sessionId,n);for(const n of this.local.sessions){const r=yo(n.sessionId);t.set(n.sessionId,r&&r.origin!==this.source.origin&&r.origin!==this.source.peerOrigin?{...n,status:"offline",serviceConnected:!1}:n)}for(const n of this.remote){const r=this.peers.services?.find(o=>o.origin===n.serviceOrigin||o.origin===yo(n.sessionId)?.origin);t.set(n.sessionId,r?.connected===!1?{...n,status:"offline",serviceConnected:!1}:n)}return{groups:this.local.groups.map(n=>({...n,remoteSessions:n.remoteSessions?.map(r=>t.get(r.sessionId)??r)})),sessions:[...t.values()],peers:this.peers,capabilities:this.local.capabilities}}emit(){if(this.disposed||!this.localHealthy)return;const t=this.snapshot();if(t)for(const n of this.listeners)n(t)}load(){if(this.disposed)return Promise.reject(new Error("协作连接已切换,请重新加载"));if(this.localInFlight)return this.localInFlight;this.refreshPeers();const t=this.generation,n=Promise.resolve().then(()=>this.source.readLocal()).then(r=>{if(this.disposed)throw new Error("协作连接已切换,请重新加载");if(t!==this.generation)return this.load();if(!Array.isArray(r.groups)||!Array.isArray(r.sessions))throw new Error("协作会话响应无效,请更新服务后重试");return this.local=r,this.localHealthy=!0,this.emit(),this.snapshot()}).catch(r=>{throw t===this.generation&&(this.localHealthy=!1,this.remote=this.remote.map(o=>({...o,status:"offline",serviceConnected:!1}))),r}).finally(()=>{this.localInFlight===n&&(this.localInFlight=null)});return this.localInFlight=n,n}invalidate(){this.generation++,this.localInFlight=null,this.localHealthy=!1}refreshPeers(t=!1){if(this.disposed||!this.source.readPeers||this.peerInFlight||!t&&Date.now()-this.lastPeerAttempt<2e3)return;this.lastPeerAttempt=Date.now(),this.peers.checkedAt||(this.peers={state:"loading",checkedAt:null}),this.emit();const n=this.source.readPeers;this.peerInFlight=Promise.race([Promise.resolve().then(()=>n()),new Promise((r,o)=>{this.peerTimer=setTimeout(()=>o(new Error("服务端协作目录加载超时,请检查服务连接")),2e4)})]).then(r=>{if(this.disposed)return;const o=r.origin===this.source.origin||!!this.source.peerOrigin&&r.origin===this.source.peerOrigin;if(!Array.isArray(r.sessions)||this.source.peerProtocol==="v2"&&(r.protocolVersion!==2||!o)||r.origin&&!o||r.protocolVersion!==void 0&&r.protocolVersion!==2)throw new Error("协作目录响应与当前服务不匹配,请升级服务后重试");this.remote=r.sessions.filter(i=>{const a=yo(i.sessionId);return a&&a.origin!==this.source.origin&&a.origin!==this.source.peerOrigin});const s=r.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,removedServices:r.removedServices}}).catch(r=>{this.disposed||(this.remote=this.remote.map(o=>({...o,status:"offline",serviceConnected:!1})),this.peers={state:"error",checkedAt:Date.now(),error:r instanceof Error?r.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 BA(e,t){const n=navigator.serviceWorker?.controller;if(!n)return null;const r=new MessageChannel;return new Promise(o=>{const s=a=>{clearTimeout(i),r.port1.close(),o(a)},i=setTimeout(()=>s(null),5e3);r.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)}},r.port1.onmessageerror=()=>s(null);try{n.postMessage({type:"termdock:prepare-download",blob:e,filename:t},[r.port2])}catch{s(null)}})}const DA=4*1024*1024,_A=256*1024,OA=1440*6e4;let Tr=0,Ff;function vd(){return typeof indexedDB>"u"?Promise.resolve(null):Ff??=new Promise(e=>{const t=indexedDB.open(`termdock-terminal-snapshots:${yr}`,1);t.onupgradeneeded=()=>t.result.createObjectStore("snapshots",{keyPath:"id"}),t.onerror=()=>e(null),t.onblocked=()=>e(null),t.onsuccess=()=>{t.result.onversionchange=()=>{t.result.close(),Ff=void 0},e(t.result)}})}function ll(e){return!!e&&e.version===1&&typeof e.epoch=="string"&&e.epoch.length>0&&Number.isSafeInteger(e.cols)&&e.cols>0&&Number.isSafeInteger(e.rows)&&e.rows>0&&Number.isSafeInteger(e.seq)&&e.seq>0&&typeof e.data=="string"&&e.data.length*2<=_A&&e.savedAt<=Date.now()&&Date.now()-e.savedAt<OA}async function V2(e){const t=Tr;try{const n=await vd();return!n||t!==Tr?null:await new Promise(r=>{const o=n.transaction("snapshots").objectStore("snapshots").get(e);o.onerror=()=>r(null),o.onsuccess=()=>r(t===Tr&&ll(o.result)?o.result:null)})}catch{return null}}async function Y2(e){const t=Tr;if(ll(e))try{const n=await vd();if(!n||t!==Tr)return;await new Promise(r=>{const o=n.transaction("snapshots","readwrite"),s=o.objectStore("snapshots");s.put(e);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>DA||!ll(l))&&s.delete(l.id)},o.oncomplete=()=>r(),o.onerror=o.onabort=()=>r()})}catch{}}async function Bm(){Tr+=1;try{(await vd())?.transaction("snapshots","readwrite").objectStore("snapshots").clear()}catch{}}typeof window<"u"&&window.addEventListener("auth:unauthorized",()=>{Bm()});const Vt=new Map,yn=new Map,FA=32*1024*1024,MA=8*1024*1024,jA=48;let bo=0,dl=0;function Sd(){dl+=1,Vt.clear(),bo=0;for(const e of yn.values())e.controller.abort();yn.clear()}typeof window<"u"&&window.addEventListener("auth:unauthorized",Sd);function UA(e,t){const n=Vt.get(e);if(n&&(bo-=n.blob.size,Vt.delete(e)),!(t.blob.size>MA))for(Vt.set(e,t),bo+=t.blob.size;Vt.size>jA||bo>FA;){const r=Vt.keys().next().value;bo-=Vt.get(r).blob.size,Vt.delete(r)}}async function Dm(e,t={}){const n=new URL(e,typeof location<"u"?location.origin:"http://localhost");if(!/^\/api\/terminal\/fs\/(read|blob)$/.test(n.pathname))return fetch(e,{signal:t.signal});if(t.signal?.aborted)throw t.signal.reason??new DOMException("Aborted","AbortError");n.searchParams.delete("requestSlotId"),n.searchParams.delete("action"),n.searchParams.sort();const r=n.href;let o=yn.get(r);if(!o){const i=new AbortController,a=dl,c=Vt.get(r),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")),t.timeoutMs??15e3),f={controller:i,readers:0,promise:Promise.resolve(null)};f.promise=(async()=>{const p=await fetch(r,{headers:l,signal:i.signal,cache:"no-cache"});let g;return p.status===304&&c?g=c:g={blob:await p.blob(),headers:new Headers(p.headers),status:p.status},dl===a&&!i.signal.aborted&&g.status===200&&g.headers.has("ETag")&&UA(r,g),p.status===401&&Sd(),g})().finally(()=>{clearTimeout(u),yn.get(r)===f&&yn.delete(r)}),o=f,yn.set(r,o)}const s=o;return s.readers+=1,new Promise((i,a)=>{let c=!1;const l=()=>c?!1:(c=!0,t.signal?.removeEventListener("abort",d),s.readers-=1,s.readers===0&&yn.get(r)===s&&(yn.delete(r),s.controller.abort()),!0),d=()=>{l()&&a(t.signal?.reason??new DOMException("Aborted","AbortError"))};if(t.signal?.addEventListener("abort",d,{once:!0}),t.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 Ed="auth:unauthorized";let wr=null;class Ce extends Error{constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="TerminalApiError"}status;code}class Vn extends Error{code="TERMINAL_INPUT_REJECTED";constructor(t){super(t),this.name="TerminalInputError"}}async function HA(){const e=await fetch("/api/terminal/update");if(!e.ok)throw new Ce("Failed to load update state",e.status);return e.json()}async function $A(){const e=await re(),t=await fetch("/api/terminal/update/check",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Ce("Failed to check for updates",t.status);return t.json()}async function qA(e){if(e&&!e())throw new Ce("Update confirmation expired");const t=await re();if(e&&!e())throw new Ce("Update confirmation expired");const n=await fetch("/api/terminal/update/restart",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to restart Termdock"}));throw new Ce(r.error||"Failed to restart Termdock",n.status)}return n.json()}async function KA(){const e=await re(),t=await fetch("/api/terminal/server-health/enable-supervision",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Ce("Failed to enable automatic recovery",t.status)}async function zA(){const e=await fetch("/api/terminal/server-health");if(!e.ok)throw new Ce("Failed to load server health",e.status);return e.json()}async function WA(){const e=await re(),t=await fetch("/api/terminal/server-health/dismiss",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Ce("Failed to dismiss server health",t.status);return t.json()}async function GA(){const e=await fetch("/api/terminal/quota");if(!e.ok)throw new Ce("Failed to fetch quota",e.status);return e.json()}async function VA(){const e=await re(),t=await fetch("/api/terminal/quota/refresh",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Ce("Failed to refresh quota",t.status);return t.json()}const Qn=8e3,_m=6e4,YA=32e3,Om=125e3,rn=1e4,XA=65e3,Pr=45e3,ZA=18e4,Fm=8e3,Mm=8e3,jm=15e3,JA=1e4,$r=5e3;let QA=0;const js=[];let ja=!1;function Gt(e,t={}){if(typeof window>"u")return;const n=JSON.stringify({level:e==="error"||e==="timeout_or_abort"||e==="response_body_timeout"||e==="response_body_parse_error"?"warn":"info",message:`DIFF_API ${e}`,data:{seq:++QA,ts:Date.now(),...t}});js.push(n),eC()}async function eC(){if(!ja){ja=!0;try{for(;js.length>0;){const e=js[0];try{await fetch("/api/client-log",{method:"POST",headers:{"Content-Type":"application/json"},body:e,keepalive:!0}),js.shift()}catch{break}}}finally{ja=!1}}}function xd(e,t,n){const r=new AbortController;let o=setTimeout(()=>{r.abort(new DOMException(n,"TimeoutError"))},t);const s=()=>r.abort(e?.reason);return e&&(e.aborted?s():e.addEventListener("abort",s,{once:!0})),{signal:r.signal,cleanup:()=>{o&&(clearTimeout(o),o=null),e?.removeEventListener("abort",s)}}}async function je(e,t,n,r){const{signal:o,cleanup:s}=xd(t?.signal??void 0,n,r);try{return await fetch(e,{...t,signal:o})}catch(i){throw i instanceof DOMException&&i.name==="TimeoutError"?new Error(r):i}finally{s()}}async function Um(e,t,n){let r=null;const o=new Promise((s,i)=>{r=setTimeout(()=>i(new Error(n)),t)});try{return await Promise.race([e.text(),o])}finally{r&&clearTimeout(r)}}async function qr(e,t,n){const r=await Um(e,t,n);return JSON.parse(r)}if(typeof window<"u"&&!window.__termdockFetchPatched){window.__termdockFetchPatched=!0;const e=window.fetch.bind(window);window.fetch=async(...t)=>{const n=await e(...t);if(n.status===401){wr=null,ts();try{window.dispatchEvent(new CustomEvent(Ed))}catch{}}return n}}async function re(){if(wr)return wr;const e=await je("/api/csrf-token",void 0,Fm,"CSRF token request timed out");if(!e.ok)throw new Error("Failed to get CSRF token");const t=await qr(e,$r,"CSRF token response timed out");if(!t.csrfToken)throw new Error("Invalid CSRF token response");return wr=t.csrfToken,wr}function Id(){ts(),wr=null}const tC=2e4,Mf=8e3,Hm=1500,$m=Hm,Me=new Map,Ad=new Map;function nC(e){return PA(Me.get(e)?.ws)}const rC=24,oC=40,sC=40,iC=1024*1024,aC=1024*1024,cC=2*1024*1024,lC=36,qm=50,dC=1e3,uC=20,Km=new TextEncoder;function zm(e){return e.items.length-e.head}function jf(e){e.head===e.items.length?(e.items.length=0,e.head=0):e.head>=64&&e.head*2>=e.items.length&&(e.items.splice(0,e.head),e.head=0)}function fC(e){const t=JSON.stringify({id:"0".repeat(lC),type:"ws-data",data:e});return Km.encode(t).byteLength<=cC}function hC(e){return typeof e=="object"&&e!==null&&e.code==="PACKET_QUEUE_BACKPRESSURE"}function Ua(e,t){const n=t instanceof Vn?t:new Vn(t.message),r=e.pendingInputs;r.items.length=0,r.head=0,r.bytes=0,e.inputFlushTimer&&(clearTimeout(e.inputFlushTimer),e.inputFlushTimer=null);try{e.onError?.(n,!0)}finally{e.disconnect()}return n}function pC(e){const t=zm(e.pendingInputs);return e.retryState.retryCount>=2||t>=sC?"congested":e.retryState.retryCount>=1||t>=8?"degraded":"good"}function Uf(e){const t=e.pendingInputs;if(!(zm(t)===0||e.ws.readyState!==WebSocket.OPEN))for(;t.head<t.items.length;){const n=t.items[t.head];if(!n){t.head++,jf(t);continue}if(n.requiresCopyModeExit&&e.copyModeInput!==!0)return e.copyModeInput===void 0?void 0:Ua(e,new Vn("The reconnected server cannot safely resume this input; please type it again"));try{e.ws.send(n.message)}catch(r){if(!hC(r))return Ua(e,r instanceof Error?r:new Error(String(r)));if(e.inputRetryAttempts++,e.inputRetryAttempts>=uC)return Ua(e,new Vn("Terminal input was not accepted after repeated encrypted-channel backpressure"));const o=e.inputRetryDelayMs;e.inputRetryDelayMs=Math.min(dC,o*2),!e.inputFlushTimer&&!e.retryState.isClosed&&(e.inputFlushTimer=setTimeout(()=>{e.inputFlushTimer=null,Ii(e)},o));return}t.bytes-=n.bytes,t.items[t.head]=void 0,t.head++,jf(t),e.inputRetryDelayMs=qm,e.inputRetryAttempts=0}}function Ii(e){if(e.ws.readyState!==WebSocket.OPEN||e.inputFlushTimer)return;const t=pC(e);if(t==="good")return Uf(e);const n=t==="congested"?oC:rC;e.inputFlushTimer=setTimeout(()=>{e.inputFlushTimer=null,Uf(e)},n)}const Lo=new Map;function gC(e,t,n,r,o,s){const i=Lo.get(e);!i||i.connection!==s||(Lo.delete(e),t?i.resolve({success:!0,layout:n,selection:o}):i.reject(new Error(r||"Tmux action failed")))}const gr=new Map;function mC(e,t,n,r){const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/terminal/${e}/ws`,i=new URLSearchParams({flow:"2",transport:"tmux-client",active:Ad.get(e)===!1?"0":"1"});t>0&&i.set("since",String(t)),n&&i.set("epoch",n);const a=r??gr.get(e);return a&&(i.set("cols",String(a.cols)),i.set("rows",String(a.rows))),`${s}?${i}`}const ul=new Map,fl=new Map;function wC(e,t,n){ul.set(e,t),fl.set(e,n)}function yC(e){const t=Me.get(e);return t?.streamEpoch&&t.appliedSeq===t.lastSeq&&t.lastSeq>0?{seq:t.lastSeq,epoch:t.streamEpoch}:null}async function bC(e){const t=await re(),n=await fetch("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({cols:e.cols||80,rows:e.rows||24,mode:e.mode||"shell",tmuxSessionName:e.tmuxSessionName,cwd:e.cwd,termType:e.termType})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to create terminal"}));throw new Error(r.error||"Failed to create terminal session")}return n.json()}function vC(e,t,n,r={}){const{maxRetries:o=10,initialRetryDelay:s=1e3,maxRetryDelay:i=2e4,connectionTimeout:a=15e3}=r,c={maxRetries:o,initialDelayMs:s,maxDelayMs:i,connectionTimeoutMs:a,retryCount:0,retryTimeout:null,connectionTimeoutId:null,isClosed:!1,isSuspended:!1};let l=null,d=ul.get(e)??0,u=fl.get(e);fl.delete(e),ul.delete(e);const f={items:[],head:0,bytes:0};let p=!1,g=null;const m=new WeakSet,b=()=>{c.retryTimeout&&(clearTimeout(c.retryTimeout),c.retryTimeout=null),c.connectionTimeoutId&&(clearTimeout(c.connectionTimeoutId),c.connectionTimeoutId=null),g&&(clearTimeout(g),g=null)},y=S=>{S.wakeProbe&&(clearTimeout(S.wakeProbe.timer),S.wakeProbe=void 0),S.heartbeatTimer&&(clearInterval(S.heartbeatTimer),S.heartbeatTimer=null),S.pongTimer&&(clearTimeout(S.pongTimer),S.pongTimer=null),S.inputFlushTimer&&(clearTimeout(S.inputFlushTimer),S.inputFlushTimer=null)},x=S=>{y(S),S.heartbeatTimer=setInterval(()=>{if(S.ws.readyState===WebSocket.OPEN){try{S.ws.send(JSON.stringify({type:"ping"}))}catch{}S.pongTimer&&clearTimeout(S.pongTimer),S.pongTimer=setTimeout(()=>{if(Date.now()-S.lastInboundAt>=Mf){p=!0,y(S);try{S.ws.close()}catch{}R(new Error("WebSocket heartbeat timeout"),!1)}},Mf)}},tC)},w=()=>{if(c.isClosed=!0,b(),f.items.length=0,f.head=0,f.bytes=0,l){y(l),Me.delete(e);try{l.ws.close()}catch{}l=null}},I=()=>{if(c.isClosed)return;if(l){m.add(l.ws),y(l);try{l.ws.close()}catch{}}const S=mC(e,d,u,r.getDimensions?.()),A=pm(S);p=!1,c.connectionTimeoutId=setTimeout(()=>{A.readyState!==WebSocket.OPEN&&(p=!0,A.close(),R(new Error("WebSocket connection timeout"),!1))},a);const T={ws:A,onEvent:t,onError:n,disconnect:w,reconnectNow:v=>{if(!c.isClosed&&(c.isSuspended=!1,!g)){if(b(),l){m.add(l.ws),y(l);try{l.ws.close()}catch{}}v?.silent||t({type:"reconnecting",attempt:Math.min(c.retryCount+1,o),maxAttempts:o}),c.retryCount=Math.min(c.retryCount+1,o),p=!0,g=setTimeout(()=>{g=null,p=!1,I()},0)}},suspendReconnect:()=>{c.isClosed||(c.isSuspended=!0,c.retryTimeout&&(clearTimeout(c.retryTimeout),c.retryTimeout=null))},retryState:c,lastSeq:d,pendingInputs:f,inputRetryDelayMs:qm,inputRetryAttempts:0,inputFlushTimer:null,heartbeatTimer:null,pongTimer:null,lastInboundAt:Date.now(),inboundSequence:0};A.onopen=()=>{c.isClosed||m.has(A)||p||(b(),c.retryCount=0,T.lastInboundAt=Date.now(),T.inboundSequence+=1,x(T),Ii(T))},A.onmessage=v=>{if(!(c.isClosed||m.has(A)||p)){T.lastInboundAt=Date.now(),T.inboundSequence+=1;try{const E=JSON.parse(v.data);if(T.wakeProbe&&Me.get(e)===T){const B=T.wakeProbe;T.wakeProbe=void 0,clearTimeout(B.timer);for(const k of B.listeners)k()}if(E.type==="pong"){TA(A,E.qualityProbeId,E.handlerMs),T.pongTimer&&(clearTimeout(T.pongTimer),T.pongTimer=null);return}if(E.type==="tmux-result"&&E.reqId){gC(E.reqId,E.success!==!1,E.layout,E.error,E.selection,A);return}if(E.type==="tmux-layout"&&E.layout){t({type:"tmux-layout",layout:E.layout});return}if(E.type==="tmux-screen-sync"&&Array.isArray(E.chunks)){t({type:"tmux-screen-sync",chunks:E.chunks.filter(B=>typeof B=="string"),cols:typeof E.cols=="number"?E.cols:void 0,rows:typeof E.rows=="number"?E.rows:void 0,generation:typeof E.generation=="number"?E.generation:void 0});return}if(E.type==="active-program"){t({type:"active-program",activeProgram:E.activeProgram,activeProgramRaw:E.activeProgramRaw,activeProgramSource:E.activeProgramSource});return}if(E.type==="cwd"){t({type:"cwd",cwd:E.cwd});return}if(E.type==="agent-status"){t({type:"agent-status",agentStatus:E.agentStatus??null,agentIndicator:E.agentIndicator??null,agentStatusDetail:E.agentStatusDetail??null,agent:E.agent??null,agentMessage:E.agentMessage??null,agentNativeSessionId:E.agentNativeSessionId??null,agentResumeRecovered:E.agentResumeRecovered===!0,agentRich:E.agentRich===!0,agentActivity:typeof E.agentActivity=="number"?E.agentActivity:0,agentCwd:E.agentCwd??null,reviewed:typeof E.reviewed=="boolean"?E.reviewed:null});return}if(E.type==="git-status"){t({type:"git-status",gitStatus:E.gitStatus??null});return}if(E.type==="quota-status"&&Array.isArray(E.providers)){window.dispatchEvent(new CustomEvent("termdock:quota-update",{detail:E.providers}));return}if(E.type==="focus-mode"){t({type:"focus-mode",focusTrackingRequested:E.focusTrackingRequested===!0});return}if(E.type==="resize-ack"){t({type:"resize-ack",seq:typeof E.seq=="number"?E.seq:void 0,cols:typeof E.cols=="number"?E.cols:void 0,rows:typeof E.rows=="number"?E.rows:void 0,ok:E.ok!==!1,error:typeof E.error=="string"?E.error:void 0,screenSyncPending:E.screenSyncPending===!0,screenSyncGeneration:typeof E.screenSyncGeneration=="number"?E.screenSyncGeneration:void 0});return}if(E.type==="pty-size"){t({type:"pty-size",cols:typeof E.cols=="number"?E.cols:void 0,rows:typeof E.rows=="number"?E.rows:void 0,source:typeof E.source=="string"?E.source:void 0});return}if(E.type==="shell-title"){t({type:"shell-title",title:typeof E.title=="string"?E.title:""});return}if(E.type==="prompt-state"){t({type:"prompt-state",state:E.state==="running"?"running":"idle",exitCode:typeof E.exitCode=="number"?E.exitCode:void 0});return}const C=E;if(C.type==="connected"){if(T.appliedSeq=void 0,u=C.streamEpoch,T.streamEpoch=u,T.outputProtocol=C.outputProtocol,T.copyModeInput=C.copyModeInput===!0,Ii(T))return;typeof C.replayLastSeq=="number"&&C.replayLastSeq>=0&&(d=C.replayLastSeq,T.lastSeq=d),t(C),Gm(e,Ad.get(e)??!0);return}if(C.type==="exit"){w(),t(C);return}if(C.type==="data"){if(T.appliedSeq=void 0,typeof C.seq=="number"&&C.seq<=d)return;typeof C.flowSeq=="number"&&(T.flowSeq=C.flowSeq)}t(C),C.type==="data"&&typeof C.seq=="number"&&Number.isFinite(C.seq)&&C.seq>d&&(d=C.seq,T.lastSeq=d)}catch(E){n?.(E,!1)}}},A.onerror=()=>{c.isClosed||m.has(A)||p||(b(),y(T),p||(p=!0,R(new Error("WebSocket connection error"),!1)))},A.onclose=v=>{if(!(c.isClosed||m.has(A)||p)){if(v.code===Xc&&v.reason===Zc){T.reconnectNow({silent:!0});return}if(b(),y(T),p=!0,v.code===4001){console.warn("[Terminal] WS 4001: Session not found on server",{code:v.code,reason:v.reason,stack:new Error().stack}),R(new Error("Session not found on server"),!0);return}if(v.code===4003||v.code===4401){try{window.dispatchEvent(new CustomEvent(Ed))}catch{}R(new Error("Authentication required"),!0);return}R(new Error("WebSocket connection closed"),!1)}},l=T,Me.set(e,l)},R=(S,A)=>{if(!c.isClosed)if(A)n?.(S,!0),w();else{c.retryCount=Math.min(c.retryCount+1,Math.max(1,o));const T=Math.min(s*Math.pow(2,c.retryCount-1),i);if(t({type:"reconnecting",attempt:c.retryCount,maxAttempts:o}),c.isSuspended)return;c.retryTimeout=setTimeout(()=>{c.isClosed||I()},T)}};return I(),w}function Wm(e,t,n=!1){const r=JSON.stringify({type:"input",data:t,...n?{exitCopyMode:!0}:{}}),o=Km.encode(r).byteLength;if(o>iC||!fC(r))throw new Vn("Terminal input exceeds the encrypted socket frame limit");const s=e.pendingInputs;if(s.bytes+o>aC)throw new Vn("Terminal input queue is full; retry after the connection recovers");if(s.items.push({message:r,bytes:o,...n?{requiresCopyModeExit:!0}:{}}),s.bytes+=o,e.ws.readyState===WebSocket.OPEN){const i=Ii(e);if(i)throw i}}function SC(e,t){const n=Me.get(e);return!n||n.ws.readyState!==WebSocket.OPEN||n.copyModeInput!==!0?!1:(Wm(n,t,!0),!0)}async function EC(e,t){const n=Me.get(e);if(n&&(n.ws.readyState===WebSocket.OPEN||n.ws.readyState===WebSocket.CONNECTING)){Wm(n,t);return}const r=await re(),o=await fetch(`/api/terminal/${e}/input`,{method:"POST",headers:{"Content-Type":"text/plain","X-XSRF-TOKEN":r},body:t});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to send input"}));throw new Ce(s.error||"Failed to send terminal input",o.status,s.code)}}function xC(e,t,n={}){const r=Me.get(e);if(!r)return!1;if(r.retryState.isSuspended=!1,r.ws.readyState!==WebSocket.OPEN)return r.reconnectNow(),!0;const o=n.visible?$m:Hm,s=Date.now()+o,i=r.wakeProbe,a=i?.listeners??new Set;if(t&&a.add(t),i&&i.deadline<=s)return!0;i&&clearTimeout(i.timer);const c=setTimeout(()=>{Me.get(e)!==r||r.retryState.isClosed||(r.wakeProbe=void 0,r.reconnectNow())},o);if(r.wakeProbe={timer:c,listeners:a,deadline:s},i)return!0;try{r.ws.send(JSON.stringify({type:"ping"}))}catch{clearTimeout(c),r.wakeProbe=void 0,r.reconnectNow()}return!0}function IC(e){const t=Me.get(e);return t?(t.reconnectNow(),!0):!1}function AC(){for(const e of Me.values())e.suspendReconnect()}function CC(e,t,n){const r=Me.get(e);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"focus",focused:t,reason:n}))}catch{}}function Gm(e,t){Ad.set(e,t);const n=Me.get(e);!n||n.ws.readyState!==WebSocket.OPEN||n.outputProtocol!==2||n.ws.send(JSON.stringify({type:"output-subscription",active:t,since:n.lastSeq,epoch:n.streamEpoch}))}function RC(e){const t=Me.get(e);!t||t.ws.readyState!==WebSocket.OPEN||t.outputProtocol!==2||(t.appliedSeq=t.lastSeq,!(!t.flowSeq||t.flowSeq===t.acknowledgedFlowSeq)&&(t.acknowledgedFlowSeq=t.flowSeq,t.ws.send(JSON.stringify({type:"output-ack",flowSeq:t.flowSeq,since:t.appliedSeq,epoch:t.streamEpoch}))))}function kC(e,t,n){const r=Me.get(e);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"viewing",viewing:t,reason:n}))}catch{}}function hl(e){const t=Me.get(e);if(!(!t||t.ws.readyState!==WebSocket.OPEN))try{t.ws.send(JSON.stringify({type:"agent-review-ack"}))}catch{}}function TC(e,t,n){const r=Me.get(e);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"flow-control",paused:t,reason:n}))}catch{}}async function PC(e,t,n,r){Number.isFinite(t)&&Number.isFinite(n)&&t>=1&&n>=1&&(gr.delete(e),gr.set(e,{cols:Math.floor(t),rows:Math.floor(n)}),gr.size>256&&gr.delete(gr.keys().next().value));const o=Me.get(e);if(o&&o.ws.readyState===WebSocket.OPEN)try{o.ws.send(JSON.stringify({type:"resize",cols:t,rows:n,seq:r}));return}catch{}const s=await re(),i=await fetch(`/api/terminal/${e}/resize`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":s},body:JSON.stringify({cols:t,rows:n,seq:r})});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 NC(e,t){const n=Me.get(e);if(n&&n.ws.readyState===WebSocket.OPEN)return t.action==="scroll"?(n.ws.send(JSON.stringify({type:"tmux",...t})),{success:!0}):new Promise((s,i)=>{const a=Math.random().toString(36).substring(7);Lo.set(a,{resolve:s,reject:i,connection:n.ws}),n.ws.send(JSON.stringify({type:"tmux",reqId:a,...t})),setTimeout(()=>{Lo.has(a)&&(Lo.delete(a),i(new Error("Tmux action timed out")))},3e4)});const r=await re(),o=await fetch(`/api/terminal/${e}/tmux`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(t)});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to execute tmux action"}));throw new Ce(s.error||"Failed to execute tmux action",o.status,s.code)}return o.json()}async function LC(e){const t=await re(),n=await fetch(`/api/terminal/${e}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok&&n.status!==404){const o=await n.json().catch(()=>({error:"Failed to close terminal"}));throw new Error(o.error||"Failed to close terminal")}Me.get(e)?.disconnect()}async function BC(e,t){const n=Me.get(e);if(n){n.retryState.isClosed=!0;try{n.ws.close()}catch{}Me.delete(e)}const r=await re(),o=await fetch(`/api/terminal/${e}/restart`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify({...t.cwd?{cwd:t.cwd}:{},cols:t.cols??80,rows:t.rows??24,mode:t.mode,tmuxSessionName:t.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 DC(e){const t=await je(`/api/terminal/${e}/health`,{method:"GET"},Mm,"Terminal health check timed out");if(!t.ok){if(t.status===404)return{healthy:!1,sessionId:e};const n=await qr(t,$r,"Terminal health error response timed out").catch(()=>({error:"Failed to check terminal health"}));throw new Error(n.error||"Failed to check terminal health")}return qr(t,$r,"Terminal health response timed out")}async function _C(e){const t=await re(),n=await je("/api/terminal/force-kill",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)},JA,"Terminal force-kill request timed out");if(!n.ok){const r=await qr(n,$r,"Terminal force-kill error response timed out").catch(()=>({error:"Failed to force kill terminal"}));throw new Error(r.error||"Failed to force kill terminal")}}async function OC(){const e=await fetch("/api/terminal/tmux/sessions",{method:"GET"});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to list tmux sessions"}));throw new Error(n.error||"Failed to list tmux sessions")}const t=await e.json();return Array.isArray(t.sessions)?t.sessions:[]}async function FC(){const e=await fetch("/api/terminal/tmux/status",{method:"GET"});if(!e.ok){const t=await e.json().catch(()=>({error:"Failed to get tmux status"}));throw new Error(t.error||"Failed to get tmux status")}return e.json()}async function MC(e){const t=e.trim();if(!t)throw new Error("tmux session name is required");const n=await re(),r=await fetch(`/api/terminal/tmux/sessions/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":n}});if(!r.ok){const s=await r.json().catch(()=>({error:"Failed to kill tmux session"}));throw new Error(s.error||"Failed to kill tmux session")}const o=await r.json();return{cleanedSessions:Array.isArray(o.cleanedSessions)?o.cleanedSessions:[],alreadyGone:!!o.alreadyGone}}async function jC(e){const t=await re(),n=`ui-restore:${e??"current"}:${Date.now()}:${Math.random().toString(36).slice(2)}`,r=await fetch("/api/terminal/tmux/recovery/restore-all",{method:"POST",headers:{"X-XSRF-TOKEN":t,"Content-Type":"application/json"},body:JSON.stringify({idempotencyKey:n})}),o=await r.json().catch(()=>({}));if(!r.ok)throw new Ce(o.error||"Failed to restore tmux Agent sessions",r.status);return o}async function UC(e,t){const n=await re(),r=await fetch(`/api/terminal/tmux/recovery/operations/${encodeURIComponent(e)}/${t?"pause":"resume"}`,{method:"POST",headers:{"X-XSRF-TOKEN":n}});if(!r.ok)throw new Ce("Failed to update recovery operation",r.status)}async function HC(){const e=await re(),t=await fetch("/api/terminal/tmux/recovery",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Ce("Failed to dismiss tmux recovery",t.status)}const xs=new Map;function $C(e){return JSON.stringify({preferredFrontendSessionId:e.preferredFrontendSessionId??null,mode:e.mode??null,tmuxSessionName:e.tmuxSessionName??null,cwd:e.cwd??null,termType:e.termType??null,createIfEmpty:e.createIfEmpty===!0,requireExisting:e.requireExisting===!0})}async function Vm(){const e=await fetch("/api/terminal/session-inventory",{method:"GET"});if(!e.ok){const t=await e.json().catch(()=>({error:"Failed to load session inventory"}));throw new Error(t.error||"Failed to load session inventory")}return e.json()}async function Ym(e){const t=$C(e),n=xs.get(t);if(n)return n;const r=await re(),o=je("/api/terminal/session-inventory/open",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(e)},jm,"Terminal session open request timed out").then(async s=>{if(!s.ok){const i=await qr(s,$r,"Terminal session open error response timed out").catch(()=>({error:"Failed to open session"}));throw new Ce(i.error||"Failed to open session",s.status,typeof i.code=="string"?i.code:void 0)}return qr(s,$r,"Terminal session open response timed out")}).finally(()=>{xs.get(t)===o&&xs.delete(t)});return xs.set(t,o),o}async function Us(e,t){const n=await re(),r=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify(t)});if(!r.ok){const o=await r.json().catch(()=>({error:"Failed to update session"}));throw new Error(o.error||"Failed to update session")}return r.json()}async function Xm(e){const t=await re(),n=await fetch("/api/terminal/session-inventory/reorder",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({sessionIds:e})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to reorder sessions"}));throw new Error(r.error||"Failed to reorder sessions")}return n.json()}async function Zm(e){const t=await re(),n=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to remove session"}));throw new Error(r.error||"Failed to remove session")}}async function Jm(){const e=await re(),t=await fetch("/api/terminal/session-inventory/sessions",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to clear sessions"}));throw new Error(n.error||"Failed to clear sessions")}}async function qC(){const e=await fetch("/api/terminal/toolbar-presets",{method:"GET"});if(!e.ok){const t=await e.json().catch(()=>({error:"Failed to load toolbar presets"}));throw new Error(t.error||"Failed to load toolbar presets")}return e.json()}async function KC(e){const t=await re(),n=await fetch("/api/terminal/toolbar-presets",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to save toolbar presets"})),o=new Error(r.error||"Failed to save toolbar presets");throw o.current=r.current,o.code=r.code,o}return n.json()}let oo=null,vo=null;const Qm=1500;function bn(){return vo&&Date.now()-vo.readAt<Qm?Promise.resolve(vo.value):oo||(oo=(async()=>{const e=await fetch("/api/terminal/settings",{method:"GET"});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to load settings"}));throw new Error(n.error||"Failed to load settings")}const t=await e.json();return vo={value:t,readAt:Date.now()},t})().finally(()=>{oo=null}),oo)}async function yt(e){const t=await re(),n=await fetch("/api/terminal/settings",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to update settings"}));throw new Error(o.error||"Failed to update settings")}const r=await n.json();return vo={value:r,readAt:Date.now()},r}async function zC(e=!1){const t=await fetch(`/api/terminal/auto-title/catalog${e?"?refresh=1":""}`);if(!t.ok)throw new Error("Failed to discover title models");const n=await t.json();return Array.isArray(n?.namers)?n.namers:[]}let so=null,So=null;function WC(){return So&&Date.now()-So.readAt<Qm?Promise.resolve(So.value):so||(so=(async()=>{const e=await fetch("/api/terminal/context-draft",{method:"GET"});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to load context draft"}));throw new Error(n.error||"Failed to load context draft")}const t=await e.json();return So={value:t,readAt:Date.now()},t})().finally(()=>{so=null}),so)}async function GC(e,t){const n=await re(),r=await fetch("/api/terminal/context-draft",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify({text:e,origin:t})});if(!r.ok){const s=await r.json().catch(()=>({error:"Failed to update context draft"}));throw new Error(s.error||"Failed to update context draft")}const o=await r.json();return So={value:o,readAt:Date.now()},o}async function ew(e){let t;try{t=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:e})})}catch(r){const o=Yi(r);return{ok:!1,reason:bf(o.code),error:o.message}}if(t.ok)return Id(),{ok:!0};const n=await t.json().catch(()=>null);return t.status===429?{ok:!1,reason:"rateLimited",rateLimited:!0,retryAfterMs:typeof n?.retryAfterMs=="number"?n.retryAfterMs:void 0,error:n?.error||"Too many failed attempts. Please wait and try again."}:{ok:!1,reason:bf(n?.code)||(t.status===401?"invalidPassword":"unavailable"),error:n?.error||"Login failed"}}async function VC(){Sd(),Bm();const e=await re();await fetch("/api/auth/logout",{method:"POST",headers:{"X-XSRF-TOKEN":e}}),Id()}async function YC(){const e=await fetch("/api/terminal/agent-launchers");if(!e.ok)throw new Error("Failed to detect agent launchers");const t=await e.json();return Array.isArray(t?.agents)?t.agents:[]}async function XC(){const e=await fetch("/api/terminal/agent-hooks");if(!e.ok)throw new Error("Failed to get agent hooks");const t=await e.json();return Array.isArray(t?.agents)?t.agents:[]}async function ZC(e){const t=await re(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(e)}/install`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to install agent hooks");return{summary:r.summary??"Installed",devMode:r.devMode===!0}}async function JC(e){const t=await re(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(e)}/uninstall`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to uninstall agent hooks");return r.summary??"Removed"}class Cd extends Error{constructor(t,n,r){super(t),this.code=n,this.migration=r,this.name="AgentPluginManifestError"}code;migration}async function QC(){const e=await fetch("/api/terminal/agent-plugins");if(!e.ok)throw new Error("Failed to get agent plugins");return await e.json()}async function eR(e){const t=await re(),n=await fetch("/api/terminal/agent-plugins",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Cd(r.error||"Failed to create agent plugin",r.code,r.migration);return r}async function tR(e){const t=await re(),n=await fetch("/api/terminal/agent-plugins/install",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({source:e})}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Cd(r.error||"Failed to install agent plugin",r.code,r.migration);return r}async function nR(e){const t=await re(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}/check-update`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to check plugin updates");return r}async function rR(e){const t=await re(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}/update`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to update plugin");return r}async function oR(e){const t=await re(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}/doctor`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to diagnose plugin");return r}async function sR(e){const t=await re(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||"Failed to delete agent plugin")}}async function iR(e){const t=await re(),n=await fetch(`/api/terminal/${encodeURIComponent(e)}/agent-resume`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Ce(r.error||"Failed to resume agent session",n.status,typeof r.code=="string"?r.code:void 0);return{command:r.command??""}}async function aR(){const e=await fetch("/api/terminal/agent-resume-history",{method:"GET"});if(!e.ok)throw new Error("Failed to load Agent resume history");const t=await e.json().catch(()=>({entries:[]}));return Array.isArray(t.entries)?t.entries:[]}async function cR(e){const t=await re(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(e)}/prepare`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Ce(r.error||"Failed to prepare Agent session resume",n.status,typeof r.code=="string"?r.code:void 0);return r}async function lR(e){const t=await re(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok&&n.status!==404)throw new Error("Failed to remove Agent resume history")}async function dR(e){const t=await re(),n=await fetch("/api/terminal/program-rules",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to update program rules"}));throw new Error(r.error||"Failed to update program rules")}return n.json()}async function uR(){const e=await re(),t=await fetch("/api/terminal/program-rules",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Error("Failed to reset program rules");return t.json()}async function fR(){const e=await fetch("/api/terminal/program-detection");if(!e.ok)throw new Error("Failed to get program detection config");return e.json()}async function hR(e){const t=await re(),n=await fetch("/api/terminal/program-detection",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok)throw new Error("Failed to save program detection config");return n.json()}async function pR(){const e=await re(),t=await fetch("/api/terminal/program-detection",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Error("Failed to reset program detection config");return t.json()}const gR={".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 Qi(e){const t=e.lastIndexOf(".");return t<0?null:gR[e.slice(t).toLowerCase()]??null}function mR(e){return Qi(e)!==null}function tw(e){const t=Qi(e);return t==="image/heic"||t==="image/heif"}const wR={".mp4":"video/mp4",".m4v":"video/x-m4v",".webm":"video/webm",".mov":"video/quicktime",".ogv":"video/ogg",".mpeg":"video/mpeg",".mpg":"video/mpeg"};function nw(e){const t=e.lastIndexOf(".");return t<0?null:wR[e.slice(t).toLowerCase()]??null}function yR(e){return nw(e)!==null}function bR(e){return`/api/terminal/fs/video?path=${encodeURIComponent(e)}&action=view_file`}const rw=[".stl",".glb",".gltf"];function Rd(e){const t=e.lastIndexOf(".");if(t<0)return null;const n=e.slice(t).toLowerCase();return rw.includes(n)?n:null}function vR(e){return Rd(e)!==null}function kd(e){const t=e.toLowerCase();return t.endsWith(".kicad_sch")?".kicad_sch":t.endsWith(".kicad_pcb")?".kicad_pcb":null}function SR(e){return kd(e)!==null}function ER(e){return kd(e)===".kicad_pcb"?"pcb-front":"schematic"}const ow=[".html",".htm"];function xR(e){const t=e.lastIndexOf(".");if(t<0)return!1;const n=e.slice(t).toLowerCase();return ow.includes(n)}function IR(e){return`/api/terminal/fs/preview/${e.split(/[\\/]+/).filter(Boolean).map(n=>encodeURIComponent(n)).join("/")}`}const AR={".stl":"model/stl",".glb":"model/gltf-binary",".gltf":"model/gltf+json"};async function CR(e,t,n,r="list_directory",o,s="name",i){const a=new URLSearchParams({path:e});n&&a.set("showHidden","true"),s!=="name"&&a.set("sort",s),i&&a.set("gitIgnoreRoot",i),a.set("action",r),o&&a.set("requestSlotId",o);const c=await je(`/api/terminal/fs/list?${a}`,{signal:t},Qn,"Directory listing took too long. The folder may be on slow storage or blocked by another process.");if(!c.ok){const l=await c.json().catch(()=>({error:"Failed to list directory"}));throw new Error(l.error||"Failed to list directory")}return c.json()}async function RR(e,t,n,r,o,s="name",i,a={}){const c=new URLSearchParams({path:e,query:t,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:r});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 p=g=>{if(!g.trim())return;const m=JSON.parse(g);if(m.type==="meta")n({path:m.path,query:m.query,engine:m.engine,mode:m.mode,limited:m.limited});else if(m.type==="batch")n({entries:m.entries??[]});else if(m.type==="content-batch")n({contentEntries:m.contentEntries??[]});else{if(m.type==="error")throw new Error(m.message||"Search failed");m.type==="done"&&n({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 b=f.indexOf(`
3
- `);for(;b>=0;)p(f.slice(0,b)),f=f.slice(b+1),b=f.indexOf(`
4
- `)}f+=u.decode(),p(f)}async function kR(e,t,n){const r=new URLSearchParams;for(const d of e)r.append("root",d);const o=await fetch(`/api/terminal/fs/watch?${r}`,{signal:n});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){t(u.events);const f=u.events.find(p=>p.type==="rescan-required"&&p.reason!=="event-storm"&&p.reason!=="reconnected"&&p.reason!=="directory-rescan"&&p.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(`
5
- `);for(;f>=0;)l(a.slice(0,f)),a=a.slice(f+1),f=a.indexOf(`
6
- `)}if(a+=i.decode(),l(a),c)throw new Error(c)}function TR(e){if(!e)return;const t=new URLSearchParams({requestSlotId:e,action:"cancel_io_slot"});fetch(`/api/terminal/fs/cancel-slot?${t}`,{method:"GET",keepalive:!0}).catch(()=>{})}async function PR(e,t,n="view_file",r){const o=new URLSearchParams({path:e,action:n});r&&o.set("requestSlotId",r);const s=await Dm(`/api/terminal/fs/read?${o}`,{signal:t,timeoutMs:Qn});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 NR(e,t,n="HEAD",r,o="ref"){const s=new URLSearchParams({path:e,cwd:t,ref:n,action:"git_blob"});o!=="ref"&&s.set("source",o);const i=await je(`/api/terminal/fs/git-blob?${s}`,{signal:r},Qn,"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 LR(e,t,n="view_file",r){const o=new URLSearchParams({path:e,action:n});r&&o.set("requestSlotId",r);const s=await Dm(`/api/terminal/fs/blob?${o}`,{signal:t,timeoutMs:tw(e)?YA:Qn});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:e,size:a?Number(a):null,modified:s.headers.get("Last-Modified"),mimeType:s.headers.get("Content-Type")||i.type||Qi(e)||"application/octet-stream"}}function Td(e,t){try{const n=decodeURIComponent(e.headers.get("X-Termdock-Source-Path")||"");return n.startsWith("/")&&!/[\r\n\0]/.test(n)?n:t}catch{return t}}async function BR(e,t,n,r="view_file",o){const s=new URLSearchParams({path:e,view:t,action:r});o&&s.set("requestSlotId",o);const i="KiCad preview rendering or transfer timed out.",a=xd(n,Om,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:Td(c,e),view:t,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&&!n?.aborted?new Error(i):c}finally{a.cleanup()}}async function DR(e,t,n,r,o){const s=new URLSearchParams({path:e,view:t,x:String(n),y:String(r)}),i=await je(`/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 _R(e,t,n="view_file",r){const o=new URLSearchParams({path:e,action:n});r&&o.set("requestSlotId",r);const i=xd(t,_m,"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=Rd(e)??"";return{blob:c,path:Td(a,e),size:l?Number(l):null,modified:a.headers.get("Last-Modified"),ext:d,mimeType:a.headers.get("Content-Type")||c.type||AR[d]||"application/octet-stream"}}finally{i.cleanup()}}function Hf(){return typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}async function OR(e,t){if(t?.aborted)return"canceled";const n=at()?.targetPeerId,r=`/api/terminal/fs/download?path=${encodeURIComponent(e)}`;try{const o=t?await fetch(r,{signal:t}):await fetch(r);if(t?.aborted)return"canceled";if(!o.ok){const c=await o.json().catch(()=>({error:"Failed to download file"}));if(t?.aborted)return"canceled";throw new Error(c.error||"Failed to download file")}const s=iw(o.headers?.get?.("Content-Disposition")||"")??e.split("/").pop()?.split("\\").pop()??"download",i=mt()?.saveDownloadStream;if(i&&o.body){const c=o.headers?.get?.("Content-Length"),l=c!=null&&/^\d+$/.test(c)?Number(c):void 0;if(t?.aborted||at()?.targetPeerId!==n)return"canceled";const d=await i(o.body,s,{signal:t,expectedBytes:Number.isSafeInteger(l)?l:void 0});return t?.aborted||at()?.targetPeerId!==n?"canceled":d}const a=await o.blob();return t?.aborted||at()?.targetPeerId!==n?"canceled":await sw(a,s,t)}catch(o){if(t?.aborted)return"canceled";throw o}}async function sw(e,t,n){if(n?.aborted)return"canceled";const r=mt()?.saveDownloadBlob;if(r)return r(e,t,n);const o=window.showSaveFilePicker;if(typeof o=="function"){let a;try{a=await o({suggestedName:t})}catch(c){if(n?.aborted||c instanceof DOMException&&c.name==="AbortError")return"canceled"}if(n?.aborted)return"canceled";if(a){let c;try{c=await a.createWritable()}catch(d){if(n?.aborted)return"canceled";throw d}const l=()=>{c.abort?.().catch(()=>{})};n?.addEventListener("abort",l,{once:!0});try{return n?.aborted?(l(),"canceled"):(await c.write(e),n?.aborted?"canceled":(await c.close(),"saved"))}catch(d){if(n?.aborted)return"canceled";throw l(),d}finally{n?.removeEventListener("abort",l)}}}if(Hf()){const a=new File([e],t,{type:e.type||"application/octet-stream"});if(typeof navigator<"u"&&"share"in navigator&&(!navigator.canShare||navigator.canShare({files:[a]})))try{return await navigator.share({files:[a]}),"started"}catch(l){if(n?.aborted||l instanceof DOMException&&l.name==="AbortError")return"canceled"}}if(Hf()){if(n?.aborted)return"canceled";const a=await BA(e,t);if(n?.aborted)return"canceled";if(a)return window.location.assign(a),"started"}if(n?.aborted)return"canceled";const s=URL.createObjectURL(e),i=document.createElement("a");return i.href=s,i.download=t,i.rel="noopener",i.style.display="none",document.body.appendChild(i),i.click(),setTimeout(()=>{URL.revokeObjectURL(s),i.remove()},4e3),"started"}async function FR(e,t){if(t&&!t())throw new Error("File deletion context changed");const n=await re();if(t&&!t())throw new Error("File deletion context changed");const r=new URLSearchParams({path:e,confirm:"true"}),o=await je(`/api/terminal/fs/file?${r}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":n}},Qn,"File deletion took too long.");if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to delete file"}));throw new Error(s.error||"Failed to delete file")}}class pl extends Error{constructor(t,n,r){super(t),this.result=n,this.code=r,this.name="UploadFilesError"}result;code}const gl=50;async function MR(e,t,n,r,o){if(t.length>gl)throw new pl(`Choose up to ${gl} files per upload. None were uploaded.`,{files:[],results:t.map((g,m)=>({index:m,name:g.name,status:"rejected",code:"UPLOAD_LIMIT"}))},"UPLOAD_LIMIT");const s=at(),i=()=>{if(n?.aborted)throw n.reason??new DOMException("Upload cancelled","AbortError");if(at()!==s||o?.()===!1)throw new Error("Upload target changed")};i();const a=new FormData;for(const g of t)a.append("files",g);const c=`/api/terminal/fs/upload?dir=${encodeURIComponent(e)}&fileCount=${t.length}`,l=await re();i(),r?.(0);const d={"X-XSRF-TOKEN":l};let u=a;if(r){const g=new Response(a);d["Content-Type"]=g.headers.get("Content-Type"),u=await g.blob()}i();const f=await je(c,{method:"POST",headers:d,body:u,signal:n,onUploadProgress:u instanceof Blob&&r?g=>r(Math.min(99,Math.floor(g/Math.max(1,u.size)*100))):void 0},12e4,"Upload timed out");if(!f.ok){const g=await f.json().catch(()=>({error:"Upload failed"}));throw new pl(g.error||"Upload failed",g,g.code)}const p=await f.json();return i(),r?.(100),p}async function jR(e){const t=await je("/api/terminal/fs/local-open-availability",{signal:e},Qn,"Local file browser availability check timed out");return t.ok?t.json():{available:!1}}async function UR(e){const t=await re(),n=await je("/api/terminal/fs/open-in-file-browser",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({path:e})},Qn,"Opening file browser timed out");if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to open file browser"}));throw new Error(r.error||"Failed to open file browser")}}function iw(e){if(!e)return null;const t=/(?:^|;)\s*filename\*=\s*(?:UTF-8'')?([^;]+)/i.exec(e);if(t){const r=t[1].trim().replace(/^"|"$/g,"");try{return decodeURIComponent(r)}catch{return r}}const n=/(?:^|;)\s*filename=\s*(?:"([^"]*)"|([^;]+))/i.exec(e);return n?(n[1]??n[2]).trim():null}function HR(e,t){t?.algorithm&&t.algorithm!=="default"&&e.set("algorithm",t.algorithm),t?.whitespace&&t.whitespace!=="default"&&e.set("whitespace",t.whitespace),t?.context==="all"?e.set("context","all"):typeof t?.context=="number"&&e.set("context",String(t.context))}async function $R(e,t,n,r,o=e?"view_diff":"view_all_changes",s,i,a,c){const l=at()?.targetPeerId;for(let d=0;;d++){r?.throwIfAborted();const u=At();try{return await qR(e,t,n,r,o,s,i,a,c)}catch(f){const p=f instanceof Error?f.message:String(f),g=u?.closed||/^(Secure connection closed|Secure response ended unexpectedly)$/.test(p);if(d>=1||r?.aborted||!g||!l||at()?.targetPeerId!==l)throw f;Gt("connection_retry",{traceId:s,interactionId:i,requestSlotId:a,filePath:e,cwd:n,action:o,message:p})}}}async function qR(e,t,n,r,o=e?"view_diff":"view_all_changes",s,i,a,c){const l=new URLSearchParams;e&&l.set("path",e),n&&l.set("cwd",n),l.set("action",o),HR(l,c),s&&l.set("traceId",s),i&&l.set("interactionId",i);const d=!!e&&o==="view_diff",u=typeof performance<"u"?performance.now():Date.now();Gt("request_start",{traceId:s,interactionId:i,requestSlotId:a,filePath:e,cwd:n,action:o,cached:!!t,algorithm:c?.algorithm??"default",whitespace:c?.whitespace??"default",context:c?.context===void 0?"default":String(c.context),timeoutMs:d?Pr:rn});const f=await je(`/api/terminal/fs/diff?${l}`,{signal:r},d?Pr:rn,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 Gt("timeout_or_abort",{traceId:s,interactionId:i,requestSlotId:a,filePath:e,cwd:n,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),message:m instanceof Error?m.message:String(m),signalAborted:!!r?.aborted,signalReason:r?.aborted?String(r.reason??""):void 0}),m});if(Gt("response_headers",{traceId:s,interactionId:i,requestSlotId:a,filePath:e,cwd:n,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 Gt("error",{traceId:s,interactionId:i,requestSlotId:a,filePath:e,cwd:n,action:o,status:f.status,message:m.error||"Failed to get diff"}),new Error(m.error||"Failed to get diff")}Gt("response_body_start",{traceId:s,interactionId:i,requestSlotId:a,filePath:e,cwd:n,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),contentLength:f.headers.get("Content-Length")});let p;try{p=await Um(f,d?Pr:rn,d?"Git diff response body is still loading for this file.":"Git diff response body took too long.")}catch(m){throw Gt("response_body_timeout",{traceId:s,interactionId:i,requestSlotId:a,filePath:e,cwd:n,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),message:m instanceof Error?m.message:String(m),signalAborted:!!r?.aborted,signalReason:r?.aborted?String(r.reason??""):void 0}),m}let g;try{g=JSON.parse(p)}catch(m){throw Gt("response_body_parse_error",{traceId:s,interactionId:i,requestSlotId:a,filePath:e,cwd:n,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),bytes:p.length,snippet:p.slice(0,160),message:m instanceof Error?m.message:String(m)}),m}return Gt("response_body",{traceId:s,interactionId:i,requestSlotId:a,filePath:e,cwd:n,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 KR(e,t,n="load_git_details",r){const o=new URLSearchParams;e&&o.set("cwd",e),o.set("action",n),r&&o.set("requestSlotId",r);const s=o.toString(),i=await je(`/api/terminal/fs/git-context${s?`?${s}`:""}`,{signal:t},rn,"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 zR(e={},t){const n=new URLSearchParams;e.workspaceRoot&&n.set("workspaceRoot",e.workspaceRoot),e.repoRoot&&n.set("repoRoot",e.repoRoot);const r=n.toString(),o=await je(`/api/terminal/fs/change-audit${r?`?${r}`:""}`,{signal:t},rn,"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 WR(e,t){const n=new URLSearchParams;e.cwd&&n.set("cwd",e.cwd),e.repoRoot&&n.set("repoRoot",e.repoRoot),n.set("base",e.base),e.head&&n.set("head",e.head),e.includeUncommitted===!1&&n.set("includeUncommitted","0"),e.filePath&&n.set("filePath",e.filePath),e.comparisonBase&&n.set("comparisonBase",e.comparisonBase),n.set("action","load_branch_diff"),e.requestSlotId&&n.set("requestSlotId",e.requestSlotId);const r=await je(`/api/terminal/fs/branch-diff?${n}`,{signal:t},e.filePath&&e.comparisonBase?Pr:ZA,"Branch diff took too long. The repository may be busy, on slow storage, or locked by another Git process.");if(!r.ok){const o=await r.json().catch(()=>({error:"Failed to get branch diff"}));throw new Error(o.error||"Failed to get branch diff")}return r.json()}async function GR(e,t){const n=new URLSearchParams;e.cwd&&n.set("cwd",e.cwd),e.repoRoot&&n.set("repoRoot",e.repoRoot),n.set("commit",e.commit),n.set("action","load_commit_diff"),e.requestSlotId&&n.set("requestSlotId",e.requestSlotId);const r=await je(`/api/terminal/fs/commit-diff?${n}`,{signal:t},Pr,"Commit diff took too long. The repository may be busy, on slow storage, or locked by another Git process.");if(!r.ok){const o=await r.json().catch(()=>({error:"Failed to get commit diff"}));throw new Error(o.error||"Failed to get commit diff")}return r.json()}async function VR(e,t){const n=new URLSearchParams;e.cwd&&n.set("cwd",e.cwd),e.repoRoot&&n.set("repoRoot",e.repoRoot),n.set("limit",String(e.limit)),typeof e.skip=="number"&&n.set("skip",String(e.skip)),e.query&&n.set("query",e.query),n.set("action","load_recent_commits"),e.requestSlotId&&n.set("requestSlotId",e.requestSlotId);const r=await je(`/api/terminal/fs/git-recent-commits?${n}`,{signal:t},XA,"Recent commits took too long. The repository may be busy, on slow storage, or locked by another Git process.");if(!r.ok){const o=await r.json().catch(()=>({error:"Failed to get recent commits"}));throw new Error(o.error||"Failed to get recent commits")}return r.json()}async function YR(e={},t){const n=new URLSearchParams;e.workspaceRoot&&n.set("workspaceRoot",e.workspaceRoot),e.repoRoot&&n.set("repoRoot",e.repoRoot),e.baseRef&&n.set("baseRef",e.baseRef),e.branchName&&n.set("branchName",e.branchName);const r=n.toString(),o=await je(`/api/terminal/fs/branch-audit${r?`?${r}`:""}`,{signal:t},rn,"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 XR(e={}){const t=await re(),n=await je("/api/terminal/fs/change-audit",{method:"DELETE",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)},rn,"Change audit explanations took too long to clear.");if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to clear change audit explanations"}));throw new Error(r.error||"Failed to clear change audit explanations")}return n.json()}async function ZR(e={}){const t=await re(),n=await je("/api/terminal/fs/branch-audit",{method:"DELETE",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)},rn,"Branch explanations took too long to clear.");if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to clear branch explanations"}));throw new Error(r.error||"Failed to clear branch explanations")}return n.json()}async function JR(e,t,n){const r=new URLSearchParams;e&&r.set("cwd",e),r.set("action","load_untracked_files"),n&&r.set("requestSlotId",n);const o=r.toString();return(await je(`/api/terminal/fs/untracked-files${o?`?${o}`:""}`,{signal:t},Pr,"Untracked file scan took too long. The repository may be busy, on slow storage, or locked by another Git process.")).json()}async function QR(e,t,n={}){const r=new URLSearchParams;e&&r.set("cwd",e),n.includeNested&&r.set("includeNested","true"),n.refresh&&r.set("refresh","true"),n.cacheOnly&&r.set("cacheOnly","true"),n.discoverOnly&&r.set("discoverOnly","true"),r.set("action",n.action??(n.refresh?"manual_git_refresh":"open_sidebar_git_refresh")),n.requestSlotId&&r.set("requestSlotId",n.requestSlotId);const o=r.toString(),s=`/api/terminal/fs/git-bundle${o?`?${o}`:""}`,i=n.requestTimeoutMs===null?await fetch(s,{signal:t}):await je(s,{signal:t},n.requestTimeoutMs??rn,"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 ek(e){const t=await re(),n=await fetch("/api/terminal/fs/git-action",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok){const r=await n.json().catch(()=>({error:"Git action failed"})),o=r.confirmationPhrase?`${r.error||"Git action failed"} (${r.confirmationPhrase})`:r.error||"Git action failed";throw new Error(o)}return n.json()}async function tk(e){const t=new URLSearchParams;e.cwd&&t.set("cwd",e.cwd),e.action&&t.set("action",e.action),e.jobId&&t.set("jobId",e.jobId);const n=await fetch(`/api/terminal/fs/git-action/status?${t}`);if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to get Git action status"}));throw new Error(r.error||"Failed to get Git action status")}return n.json()}async function nk(e){const t=await re(),n=await fetch("/api/terminal/fs/apply-hunk",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to apply diff hunk"}));throw new Error(r.error||"Failed to apply diff hunk")}return n.json()}async function ve(e,t){const n=t?.method?.toUpperCase()??"GET",r=new Headers(t?.headers);n!=="GET"&&n!=="HEAD"&&r.set("X-XSRF-TOKEN",await re()),t?.body&&r.set("Content-Type","application/json");const o=async()=>{const s=await fetch(`/api/terminal/operations${e}`,{...t,headers:r});if(!s.ok){const i=await s.json().catch(()=>({error:"操作失败"}));throw new Ce(i.error||"操作失败",s.status)}return s.status===204?void 0:await s.json()};return n==="GET"||n==="HEAD"?aI(o,t?.signal):o()}function rk(e,t){return ve(`/collaboration-tasks${e?`?group=${encodeURIComponent(e)}`:""}`,t?{signal:t}:void 0)}function ok(e){return ve(`/collaboration-tasks/${encodeURIComponent(e)}`)}function sk(e){return ve("/collaboration-tasks",{method:"POST",body:JSON.stringify({input:e})})}function ik(e,t){return ve(`/collaboration-tasks/${encodeURIComponent(e)}`,{method:"POST",body:JSON.stringify({input:t})})}function ak(){return ve("/automations")}function ck(e){return ve("/automations",{method:"POST",body:JSON.stringify(e)})}function lk(e){return ve(`/automations/${encodeURIComponent(e)}/run`,{method:"POST"})}function dk(e,t){return ve(`/automations/${encodeURIComponent(e)}/enabled`,{method:"POST",body:JSON.stringify({enabled:t})})}function uk(e){return ve(`/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}let vn=null,$f="";const ml=new Set;typeof window<"u"&&Di(()=>vn?.refreshPeers(!0));function Pd(){return ve("/collaboration-groups",{signal:AbortSignal.timeout(1e4)})}function Dt(){const e=at(),t=e?.serviceOrigin??window.location?.origin??"",n=`${e?.targetPeerId??""}:${t}`;return(!vn||n!==$f)&&(vn?.dispose(),$f=n,vn=new LA({origin:t,readLocal:Pd,readPeers:async()=>{const r=await ve("/collaboration-directory",{signal:AbortSignal.timeout(1e4)});let o;const s=await Promise.race([Ve().catch(()=>[]),new Promise(l=>{o=setTimeout(()=>l([]),1e3)})]).finally(()=>clearTimeout(o)),i=l=>{const d=s.find(f=>l.serviceId&&f.targetPeerId===l.serviceId)??s.find(f=>!l.serviceId&&(f.serviceOrigin||f.url)===l.origin),u=NA({serviceLabel:d?.label||l.label,serviceOrigin:l.origin});return{...l,label:u,...d?{accessUrl:d.url}:{}}},a=r.services?.map(i),c=new Map(a?.map(l=>[l.origin,l.label]));return{...r,origin:t,services:a,removedServices:r.removedServices?.map(i),sessions:r.sessions.map(l=>({...l,serviceLabel:c.get(l.serviceOrigin??"")??l.serviceLabel}))}},peerProtocol:"v2"}),vn.subscribe(r=>{for(const o of ml)o(r)})),vn}function ts(){vn?.dispose(),vn=null}function fk(e){return ml.add(e),()=>{ml.delete(e)}}function hk(){window.dispatchEvent(new Event("termdock:collaboration-enroll")),Dt().refreshPeers(!0)}async function pk(e){await ve(`/collaboration-connections/${encodeURIComponent(e)}`,{method:"DELETE"}),ts(),await Nd()}async function gk(e){await ve(`/collaboration-connections/${encodeURIComponent(e)}/restore`,{method:"POST"}),ts(),await Nd()}function mk(e,t){return ve(`/collaboration-groups/${encodeURIComponent(e)}/rules`,{method:"POST",body:JSON.stringify(t)})}function Nd(){return Dt().load()}async function wk(e,t){const n=await ve(`/collaboration-groups/${encodeURIComponent(e.id)}/${t?"archive":"unarchive"}`,{method:"POST",body:JSON.stringify({expectedUpdatedAt:e.updatedAt,idempotencyKey:crypto.randomUUID()})});return Dt().invalidate(),n.group}async function yk(e){const t=await Pd(),n=e.id?t.groups.find(c=>c.id===e.id):void 0;if(e.id&&!n)throw new Ce("协作组已删除,请刷新列表",404);if(n&&e.expectedUpdatedAt!==void 0&&e.expectedUpdatedAt!==n.updatedAt)throw new Ce("协作组已被修改,请重新打开成员管理后再保存",409);const r=[...new Set(e.sessionIds)];if(!e.name.trim())throw new Ce("请填写协作组名称",400);const o=new Set([...t.sessions.map(c=>c.sessionId),...n?.sessionIds??[]]);if(r.filter(c=>!o.has(c)).some(c=>!yo(c)))throw new Ce("所选会话已变化,请刷新后重新选择;尚未保存任何修改",409);const i={...e,sessionIds:r,...n?{expectedUpdatedAt:e.expectedUpdatedAt??n.updatedAt}:{}},a=await ve("/collaboration-groups",{method:"POST",body:JSON.stringify(i)});return Dt().invalidate(),a}async function bk(e){if((await Pd()).capabilities?.groupMove!==1)throw new Ce("当前服务需要升级后才能在协作组之间移动成员;原成员关系未修改",409);await ve("/collaboration-groups/move-member",{method:"POST",body:JSON.stringify(e)}),Dt().invalidate()}function vk(e,t){return ve(`/collaboration-groups/${encodeURIComponent(e)}/spawn`,{method:"POST",body:JSON.stringify(t)}).then(n=>(Dt().invalidate(),n))}function Sk(e,t,n){return ve(`/collaboration-groups/${encodeURIComponent(e)}/role`,{method:"POST",body:JSON.stringify({sessionId:t,role:n})}).then(r=>(Dt().invalidate(),r))}function Ek(e,t){const n=t===void 0?"":`?expectedUpdatedAt=${encodeURIComponent(t)}`;return ve(`/collaboration-groups/${encodeURIComponent(e)}${n}`,{method:"DELETE"}).then(()=>{Dt().invalidate()})}function xk(e){return ve(`/collaboration-groups/${encodeURIComponent(e)}/messages`)}function Ik(e,t){return ve(`/collaboration-groups/${encodeURIComponent(e)}/messages`,{method:"POST",body:JSON.stringify(t)})}function Ak(e,t=50,n){return ve(`/session-search?q=${encodeURIComponent(e)}&limit=${t}`,{signal:n})}function Ck(e){return ve("/session-search/prepare",{method:"POST",body:JSON.stringify({nativeKey:e})})}let Yt=null;function Rk(){const e=at()?.targetPeerId??location.origin;if(Yt?.scope===e&&(Yt.pending||Date.now()-Yt.at<5e3))return Yt.result;const t={scope:e,at:Date.now(),pending:!0,result:ve("/execution-archives")};return Yt=t,t.result.then(()=>{t.pending=!1,t.at=Date.now()},()=>{Yt===t&&(Yt=null)}),t.result}async function kk(e){const t=await ve(`/execution-archives/${encodeURIComponent(e)}/archive`,{method:"POST"});return Yt=null,Dt().invalidate(),t}async function Tk(e){const t=await ve(`/execution-archives/${encodeURIComponent(e)}/restore`,{method:"POST"});return Yt=null,Dt().invalidate(),t}async function Pk(e,t){const n=await ve(`/collaboration-groups/${encodeURIComponent(e)}/team`,{method:"POST",body:JSON.stringify(t)});return Dt().invalidate(),n}const Nk=Object.freeze(Object.defineProperty({__proto__:null,AUTH_UNAUTHORIZED_EVENT:Ed,AgentPluginManifestError:Cd,EDA_PREVIEW_REQUEST_TIMEOUT_MS:Om,HTML_EXTENSIONS:ow,MAX_UPLOAD_FILES:gl,MODEL_3D_EXTS:rw,MODEL_PREVIEW_REQUEST_TIMEOUT_MS:_m,TERMINAL_CSRF_REQUEST_TIMEOUT_MS:Fm,TERMINAL_HEALTH_REQUEST_TIMEOUT_MS:Mm,TERMINAL_SESSION_OPEN_REQUEST_TIMEOUT_MS:jm,TerminalApiError:Ce,TerminalInputError:Vn,UploadFilesError:pl,VISIBLE_WAKEUP_PROBE_TIMEOUT_MS:$m,acknowledgeTerminalOutput:RC,applyDiffHunk:nk,archiveExecutionSession:kk,buildHtmlPreviewUrl:IR,buildVideoPreviewUrl:bR,cancelIoSlot:TR,checkAgentPluginUpdate:nR,checkTermdockUpdate:$A,checkTerminalHealth:DC,clearBranchAuditRecords:ZR,clearChangeAuditRecords:XR,clearSessionInventoryEntries:Jm,closeTerminal:LC,confirmTermdockUpdateRestart:qA,connectTerminalStream:vC,createAgentPlugin:eR,createCollaborationTask:sk,createTerminalSession:bC,deleteAgentPlugin:sR,deleteFile:FR,dismissServerHealthIncident:WA,dismissTmuxRecovery:HC,doctorAgentPlugin:oR,downloadFile:OR,enableServerSupervision:KA,ensureCollaborationTeam:Pk,fetchQuota:GA,forceKillTerminal:_C,getAgentHooks:XC,getAgentLaunchers:YC,getAgentPlugins:QC,getAppliedTerminalCursor:yC,getBranchAuditRecords:YR,getBranchDiff:WR,getChangeAuditRecords:zR,getCollaborationTask:ok,getCommitDiff:GR,getContextDraft:WC,getCsrfToken:re,getDefaultEdaPreviewView:ER,getEdaExtForPath:kd,getFileDiff:$R,getGitActionStatus:tk,getGitBlobContent:NR,getGitBundle:QR,getGitContext:KR,getImageMimeTypeForPath:Qi,getLocalFileBrowserAvailability:jR,getModel3dExtForPath:Rd,getProgramDetection:fR,getRecentCommits:VR,getServerHealth:zA,getSessionInventory:Vm,getSettings:bn,getTermdockUpdateState:HA,getTerminalConnectionQuality:nC,getTitleNamerCatalog:zC,getTmuxStatus:FC,getToolbarPresetsDoc:qC,getUntrackedFiles:JR,getVideoMimeTypeForPath:nw,inspectEdaPoint:DR,installAgentHooks:ZC,installAgentPluginSource:tR,isHeicImagePath:tw,isPreviewableEdaPath:SR,isPreviewableHtmlPath:xR,isPreviewableImagePath:mR,isPreviewableModel3dPath:vR,isPreviewableVideoPath:yR,killTmuxSession:MC,listAgentAutomations:ak,listAgentResumeHistory:aR,listCollaborationGroups:Nd,listCollaborationMessages:xk,listCollaborationTasks:rk,listDirectory:CR,listExecutionArchives:Rk,listTmuxSessions:OC,loginWithPassword:ew,logout:VC,moveCollaborationMember:bk,openInFileBrowser:UR,openSessionInventoryEntry:Ym,parseFilenameFromContentDisposition:iw,prepareAgentResumeHistory:cR,prepareSearchSession:Ck,probeTerminalConnection:xC,readEdaPreviewBlob:BR,readFileContent:PR,readImagePreviewBlob:LR,readModel3dBlob:_R,readPreviewSourcePath:Td,reconnectTerminalConnectionNow:IC,refreshQuota:VA,removeAgentAutomation:uk,removeAgentResumeHistory:lR,removeCollaborationConnection:pk,removeCollaborationGroup:Ek,removeSessionInventoryEntry:Zm,reorderSessionInventoryEntries:Xm,replaceProgramDetection:hR,replaceProgramRules:dR,replaceToolbarPresetsDoc:KC,resetCollaborationDirectory:ts,resetCsrfTokenCache:Id,resetProgramDetection:pR,resetProgramRules:uR,resizeTerminal:PC,restartTerminalSession:BC,restoreAllTmuxAgentSessions:jC,restoreCollaborationConnection:gk,restoreExecutionSession:Tk,resumeAgentSession:iR,retryCollaborationPeers:hk,runAgentAutomation:lk,runGitAction:ek,saveAgentAutomation:ck,saveCollaborationGroup:yk,saveDownloadBlob:sw,searchFilesStream:RR,searchTerminalSessions:Ak,sendAgentReviewAck:hl,sendCollaborationMessage:Ik,sendTerminalFlowControlState:TC,sendTerminalFocusState:CC,sendTerminalInput:EC,sendTerminalViewingState:kC,sendTmuxAction:NC,setAgentAutomationEnabled:dk,setCollaborationGroupArchived:wk,setCollaborationGroupRules:mk,setCollaborationMemberRole:Sk,setTerminalOutputSubscription:Gm,setTerminalSnapshotCursor:wC,setTmuxRecoveryOperationPaused:UC,spawnCollaborationAgent:vk,subscribeCollaborationGroups:fk,suspendTerminalConnectionReconnects:AC,trySendInputExitingCopyMode:SC,uninstallAgentHooks:JC,updateAgentPlugin:rR,updateCollaborationTask:ik,updateContextDraft:GC,updateSessionInventoryEntry:Us,updateSettings:yt,uploadFiles:MR,watchFileSystem:kR},Symbol.toStringTag,{value:"Module"})),wl="termdock:locale",Hs={en:AA,zh:CA};function Lk(e){return typeof e=="string"&&RA.includes(e)}function Bk(){if(typeof window>"u")return Hr;try{const t=window.localStorage.getItem(wl);if(Lk(t))return t}catch{}return(window.navigator?.language?.toLowerCase()??"").startsWith("zh")?"zh":Hr}const aw=P.createContext(null);function yl(e,t){const n=t.split(".");let r=e;for(const o of n)if(r&&typeof r=="object"&&o in r)r=r[o];else return;return r}function bl(e,t){return typeof e=="function"?e(t??{}):typeof e!="string"?String(e):t?e.replace(/\{(\w+)\}/g,(n,r)=>Object.prototype.hasOwnProperty.call(t,r)?String(t[r]):n):e}function Dk({children:e}){const[t,n]=P.useState(()=>Bk()),r=vt.useRef(!1);P.useEffect(()=>{typeof window>"u"||bn().then(c=>{if(c?.locale==="zh"||c?.locale==="en"){if(c.locale===t||c.locale==="en"&&t!=="en")return;n(c.locale);try{window.localStorage.setItem(wl,c.locale)}catch{}}}).catch(()=>{})},[]),P.useEffect(()=>{if(!(typeof window>"u")){try{window.localStorage.setItem(wl,t)}catch{}r.current&&(r.current=!1,yt({locale:t}).catch(()=>{})),document.documentElement.lang=t==="zh"?"zh-CN":"en"}},[t]);const o=P.useCallback(c=>{r.current=!0,n(c)},[]),s=Hs[t]??Hs[Hr],i=P.useCallback((c,l)=>{const d=yl(s,c);if(d===void 0){const u=yl(Hs[Hr],c);return u===void 0?c:bl(u,l)}return bl(d,l)},[s]),a=P.useMemo(()=>({locale:t,setLocale:o,t:i}),[t,o,i]);return h.jsx(aw.Provider,{value:a,children:e})}function Gr(){const e=P.useContext(aw);return e||{locale:Hr,setLocale:()=>{},t:(t,n)=>{const r=yl(Hs[Hr],t);return r===void 0?t:bl(r,n)}}}function _k({current:e,renderRoutes:t,renderRelayServices:n,onOpen:r,onAdd:o,onInvite:s,hideHeader:i,onNavigation:a,onBusyChange:c,initiallyAdding:l=!1,initialServicePage:d,certificateTrust:u}){const{t:f}=Gr(),p=z=>{try{z.includes("#termdock-invite=")?Un(z):Ne(z)}catch{throw new Error(f(z.includes("#termdock-invite=")?"login.invalidInvitation":"login.invalidAddress"))}},g=z=>{try{return p(z),!0}catch(J){return v(J.message),!1}},[m,b]=P.useState([]),[y,x]=P.useState(!0),[w,I]=P.useState(d||(l?{kind:"add"}:{kind:"list"})),[R,S]=P.useState(!1),A=P.useCallback(z=>{S(z),c?.(z)},[c]),[T,v]=P.useState(""),[E,C]=P.useState(),[B,k]=P.useState({}),N=P.useRef(0),L=P.useRef(),D=P.useRef(!0),F=P.useRef(!1),O=z=>D.current&&N.current===z,_=z=>{(!z||L.current===z)&&(L.current=void 0)},H=()=>{const z=L.current;z&&u?.discard(z).catch(()=>{}).finally(()=>_(z))},q=()=>{N.current++,H(),C(void 0)},j=P.useRef(q);j.current=q;const K=P.useCallback(()=>{j.current(),I(z=>z.kind==="routes"||z.kind==="relay-services"?{kind:"edit",service:z.service}:{kind:"list"}),v("")},[]),G=w.kind==="add"?"添加服务":w.kind==="edit"?"服务设置":w.kind==="routes"?"备用连接":w.kind==="relay-services"?"可中转的服务":void 0;P.useEffect(()=>{a?.({title:G,...G?{back:K}:{}})},[G,K,a]),P.useEffect(()=>{let z=!1,J=0;const se=async()=>{const Re=++J;try{const me=await Ve();!z&&J===Re&&(b(me),v(""))}catch{!z&&J===Re&&v("暂时无法读取服务列表,请重试。")}finally{!z&&J===Re&&x(!1)}};se();const Se=Di(()=>{se()});return()=>{z=!0,Se()}},[]),P.useEffect(()=>(D.current=!0,()=>{D.current=!1,N.current++,H()}),[]),P.useEffect(()=>{q()},[e?.id,e?.url,e?.targetPeerId]),P.useEffect(()=>{const z=N.current;u&&u.listPins().then(J=>{O(z)&&k(J)}).catch(()=>{})},[u]);const W=async(z,J,se=z)=>{q();const Se=N.current,Re={certificateReviewRequired:!0};try{const me=await J();return O(Se)?me:Re}catch(me){if(!O(Se))return Re;if(!u||!["PREVIEW_DISCOVERY_FAILED","PREVIEW_CERTIFICATE_REJECTED"].includes(me?.code||""))throw me;try{const Ee=await u.inspect(z);if(Ee.origin!==z||!/^[a-f0-9]{64}$/i.test(Ee.fingerprint)||!Ee.receipt)throw new Error("Invalid certificate inspection result");O(Se)?(L.current=Ee.receipt,C({origin:z,fingerprint:Ee.fingerprint,trustedFingerprint:Ee.trustedFingerprint,receipt:Ee.receipt,retry:J,retryInput:se,changed:!!Ee.trustedFingerprint&&Ee.trustedFingerprint.toLowerCase()!==Ee.fingerprint.toLowerCase(),confirmed:!1,generation:Se})):u.discard(Ee.receipt).catch(()=>{})}catch{O(Se)&&v("无法读取此地址的 HTTPS 证书。请检查地址和网络后重试。")}return{certificateReviewRequired:!0}}},Y=async()=>{const z=E;!z||!z.confirmed||!u||await M(async()=>{try{if(!O(z.generation)||(await u.trust(z.origin,z.fingerprint,z.receipt),_(z.receipt),!O(z.generation)))return;const J=await u.listPins();if(!O(z.generation)||(k(J),C(void 0),!O(z.generation)))return;const se=await z.retry();if(!O(z.generation))return;se?.passwordRequired?I({kind:"add",input:z.retryInput,passwordRequired:!0}):I({kind:"list"})}catch(J){if(_(z.receipt),J?.code==="PREVIEW_CERTIFICATE_CHANGED"&&O(z.generation)){C(void 0);try{const se=await u.inspect(z.origin);if(se.origin!==z.origin||!/^[a-f0-9]{64}$/i.test(se.fingerprint)||!se.receipt)throw new Error("Invalid certificate inspection result");O(z.generation)?(L.current=se.receipt,C({...z,fingerprint:se.fingerprint,trustedFingerprint:se.trustedFingerprint,receipt:se.receipt,changed:!0,confirmed:!1})):u.discard(se.receipt).catch(()=>{}),O(z.generation)&&v("证书在确认期间发生变化。请重新核对新指纹后再决定是否信任。")}catch{O(z.generation)&&v("证书在确认期间发生变化,且无法重新读取。请稍后重试。")}return}if(O(z.generation))throw C(void 0),J}})},M=async z=>{if(F.current||!D.current)return;F.current=!0,A(!0),v("");let J=N.current;try{const se=z();J=N.current,await se}catch(se){O(J)&&v(se instanceof Error?se.message:"暂时无法完成,请重试。")}finally{F.current=!1,D.current&&A(!1)}},$=w.kind==="edit"||w.kind==="routes"||w.kind==="relay-services"?m.find(z=>Jt(z,w.service))||w.service:void 0,X=e?m.find(z=>Jt(z,e))||e:void 0,Q=m.filter(z=>!e||!Jt(z,e)),oe=X?[X,...Q]:Q,de=h.jsxs(h.Fragment,{children:[y?h.jsxs("p",{className:"service-feedback",role:"status",children:[h.jsx(lt,{size:16,className:"service-spinning"}),"正在读取服务…"]}):h.jsxs("div",{className:"service-list",children:[oe.map(z=>{const J=!!e&&Jt(z,e);return h.jsxs("div",{className:"service-row",children:[h.jsxs("button",{type:"button",className:"service-row-open",disabled:R||J,onClick:()=>{M(async()=>{(await W(z.serviceOrigin||z.url,()=>r(z)))?.passwordRequired&&I({kind:"add",input:z.serviceOrigin||z.url,passwordRequired:!0})})},"aria-label":J?`当前服务 ${z.label}`:`打开 ${z.label}`,children:[h.jsx("span",{className:"service-icon",children:h.jsx(Zi,{size:20})}),h.jsxs("span",{className:"service-row-copy",children:[h.jsx("span",{className:"service-name",children:z.label}),h.jsx("span",{className:"service-description",children:J?"当前服务":new URL(z.serviceOrigin||z.url).host})]}),J?h.jsx(Si,{size:17,className:"service-selected"}):h.jsx(Gn,{size:16,className:"service-muted"})]}),h.jsx("button",{type:"button",className:"service-icon-button","aria-label":`管理 ${z.label}`,disabled:R,onClick:()=>{q(),I({kind:"edit",service:z}),v("")},children:h.jsx(Sm,{size:19})})]},z.id)}),oe.length===0&&h.jsx("p",{className:"service-empty",children:"还没有添加服务。连接你的电脑,或粘贴收到的邀请链接。"})]}),h.jsxs("div",{className:`service-actions${s?" service-actions-pair":""}`,children:[h.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:R,onClick:()=>{q(),I({kind:"add"}),v("")},children:[h.jsx(Em,{size:16}),"添加服务"]}),s&&h.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:R,onClick:s,children:[h.jsx(xm,{size:16}),"邀请设备"]})]})]});return h.jsxs("div",{className:"service-manager",children:[!i&&h.jsxs("div",{className:"service-heading",children:[G&&h.jsx("button",{type:"button",className:"service-icon-button","aria-label":"返回服务",disabled:R,onClick:K,children:h.jsx(wm,{size:20})}),h.jsx("h2",{children:G||"服务"})]}),w.kind==="relay-services"?n?.($,A):w.kind==="routes"?t?.($,A):w.kind==="list"?de:w.kind==="add"?h.jsx(Ok,{onValidate:g,onSave:z=>M(async()=>{q();const J=Ne(z);b(await on({id:J,url:J,label:new URL(J).host})),K()}),onTargetChange:q,initialInput:w.input,passwordRequired:w.passwordRequired,busy:R,onSubmit:async(z,J)=>{let se;return await M(async()=>{const Se=z.includes("#termdock-invite=")?Un(z).serviceOrigin||Un(z).url:Ne(z);se=await W(Se,()=>o(z,J),z),!se?.passwordRequired&&!se?.certificateReviewRequired&&K()}),se}}):h.jsx(Fk,{onRelayServices:n&&w.service.targetPeerId?()=>I({kind:"relay-services",service:w.service}):void 0,onRoutes:t&&w.service.targetPeerId?()=>I({kind:"routes",service:w.service}):void 0,service:$,busy:R,canRemove:!e||!Jt(w.service,e),onSave:z=>{M(async()=>{b(await on({...$,label:z})),K()})},onRemove:()=>{M(async()=>{b(await by(w.service.id)),K()})}}),E&&h.jsxs("section",{className:"service-certificate-review","aria-label":"HTTPS 证书确认",children:[h.jsx("h3",{children:"检查 HTTPS 证书"}),h.jsx("p",{children:E.origin}),E.changed&&h.jsx("p",{role:"alert",children:"当前证书与已保存的信任指纹不同。请通过独立可信渠道重新核对,再决定是否更新信任。"}),h.jsx("p",{children:"请通过独立可信渠道向服务管理员核对以下 SHA-256 指纹。仅查看指纹不会信任证书。"}),h.jsx("code",{children:E.fingerprint.match(/.{1,2}/g)?.join(":").toUpperCase()}),E.trustedFingerprint&&h.jsxs("p",{children:["已保存的指纹:",h.jsx("code",{children:E.trustedFingerprint.match(/.{1,2}/g)?.join(":").toUpperCase()})]}),h.jsxs("label",{children:[h.jsx("input",{type:"checkbox",checked:E.confirmed,disabled:R,onChange:z=>C(J=>J&&{...J,confirmed:z.target.checked})}),"我已通过独立可信渠道核对该指纹,并明确同意仅对此精确 HTTPS 地址信任。"]}),h.jsxs("div",{className:"service-actions service-actions-pair",children:[h.jsx("button",{type:"button",className:"service-button service-secondary",onClick:q,children:"取消"}),h.jsx("button",{type:"button",className:"service-button service-primary",disabled:R||!E.confirmed,onClick:()=>{Y()},children:"信任此指纹并重试一次"})]})]}),u&&Object.keys(B).length>0&&h.jsxs("details",{className:"service-certificate-pins",children:[h.jsxs("summary",{children:["已信任的 HTTPS 证书(",Object.keys(B).length,")"]}),Object.entries(B).map(([z,J])=>h.jsxs("div",{children:[h.jsxs("p",{children:[z,h.jsx("br",{}),h.jsx("code",{children:J.match(/.{1,2}/g)?.join(":").toUpperCase()})]}),h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:R,onClick:()=>{M(async()=>{const se=N.current;if(await u.revoke(z),!O(se))return;const Se=await u.listPins();O(se)&&k(Se)})},children:"撤销信任"})]},z))]}),T&&h.jsx("p",{className:"service-error",role:"alert",children:T})]})}function Ok({onValidate:e,busy:t,onSubmit:n,onSave:r,onTargetChange:o,initialInput:s="",passwordRequired:i=!1}){const a=P.useRef(null),c=()=>e(l.trim())?!0:(a.current?.focus(),!1),[l,d]=P.useState(s),[u,f]=P.useState(""),[p,g]=P.useState(i);return h.jsxs("form",{className:"service-form",onSubmit:async m=>{if(m.preventDefault(),t||!c())return;(await n(l.trim(),p?u:void 0))?.passwordRequired&&g(!0),f("")},children:[h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"服务地址或邀请链接"}),h.jsx("input",{ref:a,value:l,onChange:m=>{o(),d(m.target.value),g(!1),f("")},disabled:t,required:!0,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:电脑地址:9834 或 https://…"})]}),p?h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"服务密码"}),h.jsx("input",{type:"password",value:u,onChange:m=>f(m.target.value),disabled:t,required:!0,autoFocus:!0,autoComplete:"current-password",placeholder:"输入这台服务的密码"})]}):h.jsx("p",{className:"service-help",children:"连接自己的服务,输入地址即可;收到邀请时,粘贴完整链接。"}),h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:t||!l.trim()||l.includes("#termdock-invite="),onClick:()=>{c()&&r(l.trim())},children:"仅保存,不连接"}),h.jsx("button",{type:"submit",className:"service-button service-primary",disabled:t||!l.trim()||p&&!u,children:t?h.jsxs(h.Fragment,{children:[h.jsx(lt,{size:16,className:"service-spinning"}),"正在连接…"]}):p?"登录并连接":"继续"})]})}function Fk({service:e,busy:t,canRemove:n,onSave:r,onRemove:o,onRoutes:s,onRelayServices:i}){const[a,c]=P.useState(e.label),[l,d]=P.useState(!1);return h.jsxs("form",{className:"service-form",onSubmit:u=>{u.preventDefault(),r(a.trim())},children:[h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"服务名称"}),h.jsx("input",{value:a,onChange:u=>c(u.target.value),disabled:t,required:!0,maxLength:120,placeholder:"例如:办公室电脑"})]}),h.jsx("p",{className:"service-address",children:e.serviceOrigin||e.url}),h.jsx("button",{type:"submit",className:"service-button service-primary",disabled:t||!a.trim(),children:"保存名称"}),i&&h.jsxs("button",{type:"button",className:"service-row-open",disabled:t,onClick:i,children:[h.jsxs("span",{className:"service-row-copy",children:[h.jsx("span",{className:"service-name",children:"可中转的服务"}),h.jsx("span",{className:"service-description",children:"通过这台服务连接其他电脑"})]}),h.jsx(Gn,{size:16})]}),s&&h.jsxs("button",{type:"button",className:"service-row-open",disabled:t,onClick:s,children:[h.jsxs("span",{className:"service-row-copy",children:[h.jsx("span",{className:"service-name",children:"备用连接"}),h.jsx("span",{className:"service-description",children:"添加其他网络地址或授权入口"})]}),h.jsx(Gn,{size:16})]}),n&&h.jsx("div",{className:"service-remove",children:l?h.jsxs(h.Fragment,{children:[h.jsxs("p",{className:"service-help",children:["从列表移除“",e.label,"”?不会停止服务或删除终端。"]}),h.jsxs("div",{className:"service-actions service-actions-pair",children:[h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:t,onClick:()=>d(!1),children:"取消"}),h.jsx("button",{type:"button",className:"service-button service-danger",disabled:t,onClick:o,children:"确认移除"})]})]}):h.jsx("button",{type:"button",className:"service-button service-danger",disabled:t,onClick:()=>d(!0),children:"移除服务"})})]})}var cr={},Ha,qf;function Mk(){return qf||(qf=1,Ha=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Ha}var $a={},mn={},Kf;function er(){if(Kf)return mn;Kf=1;let e;const t=[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 mn.getSymbolSize=function(r){if(!r)throw new Error('"version" cannot be null or undefined');if(r<1||r>40)throw new Error('"version" should be in range from 1 to 40');return r*4+17},mn.getSymbolTotalCodewords=function(r){return t[r]},mn.getBCHDigit=function(n){let r=0;for(;n!==0;)r++,n>>>=1;return r},mn.setToSJISFunction=function(r){if(typeof r!="function")throw new Error('"toSJISFunc" is not a valid function.');e=r},mn.isKanjiModeEnabled=function(){return typeof e<"u"},mn.toSJIS=function(r){return e(r)},mn}var qa={},zf;function Ld(){return zf||(zf=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+n)}}e.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},e.from=function(r,o){if(e.isValid(r))return r;try{return t(r)}catch{return o}}})(qa)),qa}var Ka,Wf;function jk(){if(Wf)return Ka;Wf=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const n=Math.floor(t/8);return(this.buffer[n]>>>7-t%8&1)===1},put:function(t,n){for(let r=0;r<n;r++)this.putBit((t>>>n-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const n=Math.floor(this.length/8);this.buffer.length<=n&&this.buffer.push(0),t&&(this.buffer[n]|=128>>>this.length%8),this.length++}},Ka=e,Ka}var za,Gf;function Uk(){if(Gf)return za;Gf=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,n,r,o){const s=t*this.size+n;this.data[s]=r,o&&(this.reservedBit[s]=!0)},e.prototype.get=function(t,n){return this.data[t*this.size+n]},e.prototype.xor=function(t,n,r){this.data[t*this.size+n]^=r},e.prototype.isReserved=function(t,n){return this.reservedBit[t*this.size+n]},za=e,za}var Wa={},Vf;function Hk(){return Vf||(Vf=1,(function(e){const t=er().getSymbolSize;e.getRowColCoords=function(r){if(r===1)return[];const o=Math.floor(r/7)+2,s=t(r),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()},e.getPositions=function(r){const o=[],s=e.getRowColCoords(r),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}})(Wa)),Wa}var Ga={},Yf;function $k(){if(Yf)return Ga;Yf=1;const e=er().getSymbolSize,t=7;return Ga.getPositions=function(r){const o=e(r);return[[0,0],[o-t,0],[0,o-t]]},Ga}var Va={},Xf;function qk(){return Xf||(Xf=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},e.from=function(o){return e.isValid(o)?parseInt(o,10):void 0},e.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 p=o.get(u,f);p===l?a++:(a>=5&&(i+=t.N1+(a-5)),l=p,a=1),p=o.get(f,u),p===d?c++:(c>=5&&(i+=t.N1+(c-5)),d=p,c=1)}a>=5&&(i+=t.N1+(a-5)),c>=5&&(i+=t.N1+(c-5))}return i},e.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*t.N2},e.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*t.N3},e.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)*t.N4};function n(r,o,s){switch(r){case e.Patterns.PATTERN000:return(o+s)%2===0;case e.Patterns.PATTERN001:return o%2===0;case e.Patterns.PATTERN010:return s%3===0;case e.Patterns.PATTERN011:return(o+s)%3===0;case e.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case e.Patterns.PATTERN101:return o*s%2+o*s%3===0;case e.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case e.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}e.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,n(o,c,a))},e.getBestMask=function(o,s){const i=Object.keys(e.Patterns).length;let a=0,c=1/0;for(let l=0;l<i;l++){s(l),e.applyMask(l,o);const d=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(l,o),d<c&&(c=d,a=l)}return a}})(Va)),Va}var Is={},Zf;function cw(){if(Zf)return Is;Zf=1;const e=Ld(),t=[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],n=[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 Is.getBlocksCount=function(o,s){switch(s){case e.L:return t[(o-1)*4+0];case e.M:return t[(o-1)*4+1];case e.Q:return t[(o-1)*4+2];case e.H:return t[(o-1)*4+3];default:return}},Is.getTotalCodewordsCount=function(o,s){switch(s){case e.L:return n[(o-1)*4+0];case e.M:return n[(o-1)*4+1];case e.Q:return n[(o-1)*4+2];case e.H:return n[(o-1)*4+3];default:return}},Is}var Ya={},io={},Jf;function Kk(){if(Jf)return io;Jf=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let r=1;for(let o=0;o<255;o++)e[o]=r,t[r]=o,r<<=1,r&256&&(r^=285);for(let o=255;o<512;o++)e[o]=e[o-255]})(),io.log=function(r){if(r<1)throw new Error("log("+r+")");return t[r]},io.exp=function(r){return e[r]},io.mul=function(r,o){return r===0||o===0?0:e[t[r]+t[o]]},io}var Qf;function zk(){return Qf||(Qf=1,(function(e){const t=Kk();e.mul=function(r,o){const s=new Uint8Array(r.length+o.length-1);for(let i=0;i<r.length;i++)for(let a=0;a<o.length;a++)s[i+a]^=t.mul(r[i],o[a]);return s},e.mod=function(r,o){let s=new Uint8Array(r);for(;s.length-o.length>=0;){const i=s[0];for(let c=0;c<o.length;c++)s[c]^=t.mul(o[c],i);let a=0;for(;a<s.length&&s[a]===0;)a++;s=s.slice(a)}return s},e.generateECPolynomial=function(r){let o=new Uint8Array([1]);for(let s=0;s<r;s++)o=e.mul(o,new Uint8Array([1,t.exp(s)]));return o}})(Ya)),Ya}var Xa,eh;function Wk(){if(eh)return Xa;eh=1;const e=zk();function t(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(r){this.degree=r,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(r){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(r.length+this.degree);o.set(r);const s=e.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},Xa=t,Xa}var Za={},Ja={},Qa={},th;function lw(){return th||(th=1,Qa.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Qa}var jt={},nh;function dw(){if(nh)return jt;nh=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let n="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";n=n.replace(/u/g,"\\u");const r="(?:(?![A-Z0-9 $%*+\\-./:]|"+n+`)(?:.|[\r
7
- ]))+`;jt.KANJI=new RegExp(n,"g"),jt.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),jt.BYTE=new RegExp(r,"g"),jt.NUMERIC=new RegExp(e,"g"),jt.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+n+"$"),s=new RegExp("^"+e+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return jt.testKanji=function(c){return o.test(c)},jt.testNumeric=function(c){return s.test(c)},jt.testAlphanumeric=function(c){return i.test(c)},jt}var rh;function tr(){return rh||(rh=1,(function(e){const t=lw(),n=dw();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(s,i){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!t.isValid(i))throw new Error("Invalid version: "+i);return i>=1&&i<10?s.ccBits[0]:i<27?s.ccBits[1]:s.ccBits[2]},e.getBestModeForData=function(s){return n.testNumeric(s)?e.NUMERIC:n.testAlphanumeric(s)?e.ALPHANUMERIC:n.testKanji(s)?e.KANJI:e.BYTE},e.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},e.isValid=function(s){return s&&s.bit&&s.ccBits};function r(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+o)}}e.from=function(s,i){if(e.isValid(s))return s;try{return r(s)}catch{return i}}})(Ja)),Ja}var oh;function Gk(){return oh||(oh=1,(function(e){const t=er(),n=cw(),r=Ld(),o=tr(),s=lw(),i=7973,a=t.getBCHDigit(i);function c(f,p,g){for(let m=1;m<=40;m++)if(p<=e.getCapacity(m,g,f))return m}function l(f,p){return o.getCharCountIndicator(f,p)+4}function d(f,p){let g=0;return f.forEach(function(m){const b=l(m.mode,p);g+=b+m.getBitsLength()}),g}function u(f,p){for(let g=1;g<=40;g++)if(d(f,g)<=e.getCapacity(g,p,o.MIXED))return g}e.from=function(p,g){return s.isValid(p)?parseInt(p,10):g},e.getCapacity=function(p,g,m){if(!s.isValid(p))throw new Error("Invalid QR Code version");typeof m>"u"&&(m=o.BYTE);const b=t.getSymbolTotalCodewords(p),y=n.getTotalCodewordsCount(p,g),x=(b-y)*8;if(m===o.MIXED)return x;const w=x-l(m,p);switch(m){case o.NUMERIC:return Math.floor(w/10*3);case o.ALPHANUMERIC:return Math.floor(w/11*2);case o.KANJI:return Math.floor(w/13);case o.BYTE:default:return Math.floor(w/8)}},e.getBestVersionForData=function(p,g){let m;const b=r.from(g,r.M);if(Array.isArray(p)){if(p.length>1)return u(p,b);if(p.length===0)return 1;m=p[0]}else m=p;return c(m.mode,m.getLength(),b)},e.getEncodedBits=function(p){if(!s.isValid(p)||p<7)throw new Error("Invalid QR Code version");let g=p<<12;for(;t.getBCHDigit(g)-a>=0;)g^=i<<t.getBCHDigit(g)-a;return p<<12|g}})(Za)),Za}var ec={},sh;function Vk(){if(sh)return ec;sh=1;const e=er(),t=1335,n=21522,r=e.getBCHDigit(t);return ec.getEncodedBits=function(s,i){const a=s.bit<<3|i;let c=a<<10;for(;e.getBCHDigit(c)-r>=0;)c^=t<<e.getBCHDigit(c)-r;return(a<<10|c)^n},ec}var tc={},nc,ih;function Yk(){if(ih)return nc;ih=1;const e=tr();function t(n){this.mode=e.NUMERIC,this.data=n.toString()}return t.getBitsLength=function(r){return 10*Math.floor(r/3)+(r%3?r%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){let o,s,i;for(o=0;o+3<=this.data.length;o+=3)s=this.data.substr(o,3),i=parseInt(s,10),r.put(i,10);const a=this.data.length-o;a>0&&(s=this.data.substr(o),i=parseInt(s,10),r.put(i,a*3+1))},nc=t,nc}var rc,ah;function Xk(){if(ah)return rc;ah=1;const e=tr(),t=["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 n(r){this.mode=e.ALPHANUMERIC,this.data=r}return n.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(o){let s;for(s=0;s+2<=this.data.length;s+=2){let i=t.indexOf(this.data[s])*45;i+=t.indexOf(this.data[s+1]),o.put(i,11)}this.data.length%2&&o.put(t.indexOf(this.data[s]),6)},rc=n,rc}var oc,ch;function Zk(){if(ch)return oc;ch=1;const e=tr();function t(n){this.mode=e.BYTE,typeof n=="string"?this.data=new TextEncoder().encode(n):this.data=new Uint8Array(n)}return t.getBitsLength=function(r){return r*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){for(let r=0,o=this.data.length;r<o;r++)n.put(this.data[r],8)},oc=t,oc}var sc,lh;function Jk(){if(lh)return sc;lh=1;const e=tr(),t=er();function n(r){this.mode=e.KANJI,this.data=r}return n.getBitsLength=function(o){return o*13},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(r){let o;for(o=0;o<this.data.length;o++){let s=t.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]+`
8
- Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),r.put(s,13)}},sc=n,sc}var ic={exports:{}},dh;function Qk(){return dh||(dh=1,(function(e){var t={single_source_shortest_paths:function(n,r,o){var s={},i={};i[r]=0;var a=t.PriorityQueue.make();a.push(r,0);for(var c,l,d,u,f,p,g,m,b;!a.empty();){c=a.pop(),l=c.value,u=c.cost,f=n[l]||{};for(d in f)f.hasOwnProperty(d)&&(p=f[d],g=u+p,m=i[d],b=typeof i[d]>"u",(b||m>g)&&(i[d]=g,a.push(d,g),s[d]=l))}if(typeof o<"u"&&typeof i[o]>"u"){var y=["Could not find a path from ",r," to ",o,"."].join("");throw new Error(y)}return s},extract_shortest_path_from_predecessor_list:function(n,r){for(var o=[],s=r;s;)o.push(s),n[s],s=n[s];return o.reverse(),o},find_path:function(n,r,o){var s=t.single_source_shortest_paths(n,r,o);return t.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(n){var r=t.PriorityQueue,o={},s;n=n||{};for(s in r)r.hasOwnProperty(s)&&(o[s]=r[s]);return o.queue=[],o.sorter=n.sorter||r.default_sorter,o},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var o={value:n,cost:r};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(ic)),ic.exports}var uh;function eT(){return uh||(uh=1,(function(e){const t=tr(),n=Yk(),r=Xk(),o=Zk(),s=Jk(),i=dw(),a=er(),c=Qk();function l(y){return unescape(encodeURIComponent(y)).length}function d(y,x,w){const I=[];let R;for(;(R=y.exec(w))!==null;)I.push({data:R[0],index:R.index,mode:x,length:R[0].length});return I}function u(y){const x=d(i.NUMERIC,t.NUMERIC,y),w=d(i.ALPHANUMERIC,t.ALPHANUMERIC,y);let I,R;return a.isKanjiModeEnabled()?(I=d(i.BYTE,t.BYTE,y),R=d(i.KANJI,t.KANJI,y)):(I=d(i.BYTE_KANJI,t.BYTE,y),R=[]),x.concat(w,I,R).sort(function(A,T){return A.index-T.index}).map(function(A){return{data:A.data,mode:A.mode,length:A.length}})}function f(y,x){switch(x){case t.NUMERIC:return n.getBitsLength(y);case t.ALPHANUMERIC:return r.getBitsLength(y);case t.KANJI:return s.getBitsLength(y);case t.BYTE:return o.getBitsLength(y)}}function p(y){return y.reduce(function(x,w){const I=x.length-1>=0?x[x.length-1]:null;return I&&I.mode===w.mode?(x[x.length-1].data+=w.data,x):(x.push(w),x)},[])}function g(y){const x=[];for(let w=0;w<y.length;w++){const I=y[w];switch(I.mode){case t.NUMERIC:x.push([I,{data:I.data,mode:t.ALPHANUMERIC,length:I.length},{data:I.data,mode:t.BYTE,length:I.length}]);break;case t.ALPHANUMERIC:x.push([I,{data:I.data,mode:t.BYTE,length:I.length}]);break;case t.KANJI:x.push([I,{data:I.data,mode:t.BYTE,length:l(I.data)}]);break;case t.BYTE:x.push([{data:I.data,mode:t.BYTE,length:l(I.data)}])}}return x}function m(y,x){const w={},I={start:{}};let R=["start"];for(let S=0;S<y.length;S++){const A=y[S],T=[];for(let v=0;v<A.length;v++){const E=A[v],C=""+S+v;T.push(C),w[C]={node:E,lastCount:0},I[C]={};for(let B=0;B<R.length;B++){const k=R[B];w[k]&&w[k].node.mode===E.mode?(I[k][C]=f(w[k].lastCount+E.length,E.mode)-f(w[k].lastCount,E.mode),w[k].lastCount+=E.length):(w[k]&&(w[k].lastCount=E.length),I[k][C]=f(E.length,E.mode)+4+t.getCharCountIndicator(E.mode,x))}}R=T}for(let S=0;S<R.length;S++)I[R[S]].end=0;return{map:I,table:w}}function b(y,x){let w;const I=t.getBestModeForData(y);if(w=t.from(x,I),w!==t.BYTE&&w.bit<I.bit)throw new Error('"'+y+'" cannot be encoded with mode '+t.toString(w)+`.
9
- Suggested mode is: `+t.toString(I));switch(w===t.KANJI&&!a.isKanjiModeEnabled()&&(w=t.BYTE),w){case t.NUMERIC:return new n(y);case t.ALPHANUMERIC:return new r(y);case t.KANJI:return new s(y);case t.BYTE:return new o(y)}}e.fromArray=function(x){return x.reduce(function(w,I){return typeof I=="string"?w.push(b(I,null)):I.data&&w.push(b(I.data,I.mode)),w},[])},e.fromString=function(x,w){const I=u(x,a.isKanjiModeEnabled()),R=g(I),S=m(R,w),A=c.find_path(S.map,"start","end"),T=[];for(let v=1;v<A.length-1;v++)T.push(S.table[A[v]].node);return e.fromArray(p(T))},e.rawSplit=function(x){return e.fromArray(u(x,a.isKanjiModeEnabled()))}})(tc)),tc}var fh;function tT(){if(fh)return $a;fh=1;const e=er(),t=Ld(),n=jk(),r=Uk(),o=Hk(),s=$k(),i=qk(),a=cw(),c=Wk(),l=Gk(),d=Vk(),u=tr(),f=eT();function p(S,A){const T=S.size,v=s.getPositions(A);for(let E=0;E<v.length;E++){const C=v[E][0],B=v[E][1];for(let k=-1;k<=7;k++)if(!(C+k<=-1||T<=C+k))for(let N=-1;N<=7;N++)B+N<=-1||T<=B+N||(k>=0&&k<=6&&(N===0||N===6)||N>=0&&N<=6&&(k===0||k===6)||k>=2&&k<=4&&N>=2&&N<=4?S.set(C+k,B+N,!0,!0):S.set(C+k,B+N,!1,!0))}}function g(S){const A=S.size;for(let T=8;T<A-8;T++){const v=T%2===0;S.set(T,6,v,!0),S.set(6,T,v,!0)}}function m(S,A){const T=o.getPositions(A);for(let v=0;v<T.length;v++){const E=T[v][0],C=T[v][1];for(let B=-2;B<=2;B++)for(let k=-2;k<=2;k++)B===-2||B===2||k===-2||k===2||B===0&&k===0?S.set(E+B,C+k,!0,!0):S.set(E+B,C+k,!1,!0)}}function b(S,A){const T=S.size,v=l.getEncodedBits(A);let E,C,B;for(let k=0;k<18;k++)E=Math.floor(k/3),C=k%3+T-8-3,B=(v>>k&1)===1,S.set(E,C,B,!0),S.set(C,E,B,!0)}function y(S,A,T){const v=S.size,E=d.getEncodedBits(A,T);let C,B;for(C=0;C<15;C++)B=(E>>C&1)===1,C<6?S.set(C,8,B,!0):C<8?S.set(C+1,8,B,!0):S.set(v-15+C,8,B,!0),C<8?S.set(8,v-C-1,B,!0):C<9?S.set(8,15-C-1+1,B,!0):S.set(8,15-C-1,B,!0);S.set(v-8,8,1,!0)}function x(S,A){const T=S.size;let v=-1,E=T-1,C=7,B=0;for(let k=T-1;k>0;k-=2)for(k===6&&k--;;){for(let N=0;N<2;N++)if(!S.isReserved(E,k-N)){let L=!1;B<A.length&&(L=(A[B]>>>C&1)===1),S.set(E,k-N,L),C--,C===-1&&(B++,C=7)}if(E+=v,E<0||T<=E){E-=v,v=-v;break}}}function w(S,A,T){const v=new n;T.forEach(function(N){v.put(N.mode.bit,4),v.put(N.getLength(),u.getCharCountIndicator(N.mode,S)),N.write(v)});const E=e.getSymbolTotalCodewords(S),C=a.getTotalCodewordsCount(S,A),B=(E-C)*8;for(v.getLengthInBits()+4<=B&&v.put(0,4);v.getLengthInBits()%8!==0;)v.putBit(0);const k=(B-v.getLengthInBits())/8;for(let N=0;N<k;N++)v.put(N%2?17:236,8);return I(v,S,A)}function I(S,A,T){const v=e.getSymbolTotalCodewords(A),E=a.getTotalCodewordsCount(A,T),C=v-E,B=a.getBlocksCount(A,T),k=v%B,N=B-k,L=Math.floor(v/B),D=Math.floor(C/B),F=D+1,O=L-D,_=new c(O);let H=0;const q=new Array(B),j=new Array(B);let K=0;const G=new Uint8Array(S.buffer);for(let X=0;X<B;X++){const Q=X<N?D:F;q[X]=G.slice(H,H+Q),j[X]=_.encode(q[X]),H+=Q,K=Math.max(K,Q)}const W=new Uint8Array(v);let Y=0,M,$;for(M=0;M<K;M++)for($=0;$<B;$++)M<q[$].length&&(W[Y++]=q[$][M]);for(M=0;M<O;M++)for($=0;$<B;$++)W[Y++]=j[$][M];return W}function R(S,A,T,v){let E;if(Array.isArray(S))E=f.fromArray(S);else if(typeof S=="string"){let L=A;if(!L){const D=f.rawSplit(S);L=l.getBestVersionForData(D,T)}E=f.fromString(S,L||40)}else throw new Error("Invalid data");const C=l.getBestVersionForData(E,T);if(!C)throw new Error("The amount of data is too big to be stored in a QR Code");if(!A)A=C;else if(A<C)throw new Error(`
10
- The chosen QR Code version cannot contain this amount of data.
11
- Minimum version required to store current data is: `+C+`.
12
- `);const B=w(A,T,E),k=e.getSymbolSize(A),N=new r(k);return p(N,A),g(N),m(N,A),y(N,T,0),A>=7&&b(N,A),x(N,B),isNaN(v)&&(v=i.getBestMask(N,y.bind(null,N,T))),i.applyMask(v,N),y(N,T,v),{modules:N,version:A,errorCorrectionLevel:T,maskPattern:v,segments:E}}return $a.create=function(A,T){if(typeof A>"u"||A==="")throw new Error("No input text");let v=t.M,E,C;return typeof T<"u"&&(v=t.from(T.errorCorrectionLevel,t.M),E=l.from(T.version),C=i.from(T.maskPattern),T.toSJISFunc&&e.setToSJISFunction(T.toSJISFunc)),R(A,E,v,C)},$a}var ac={},cc={},hh;function uw(){return hh||(hh=1,(function(e){function t(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let r=n.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+n);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(s){return[s,s]}))),r.length===6&&r.push("F","F");const o=parseInt(r.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+r.slice(0,6).join("")}}e.getOptions=function(r){r||(r={}),r.color||(r.color={});const o=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,s=r.width&&r.width>=21?r.width:void 0,i=r.scale||4;return{width:s,scale:s?4:i,margin:o,color:{dark:t(r.color.dark||"#000000ff"),light:t(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},e.getScale=function(r,o){return o.width&&o.width>=r+o.margin*2?o.width/(r+o.margin*2):o.scale},e.getImageWidth=function(r,o){const s=e.getScale(r,o);return Math.floor((r+o.margin*2)*s)},e.qrToImageData=function(r,o,s){const i=o.modules.size,a=o.modules.data,c=e.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 p=0;p<l;p++){let g=(f*l+p)*4,m=s.color.light;if(f>=d&&p>=d&&f<l-d&&p<l-d){const b=Math.floor((f-d)/c),y=Math.floor((p-d)/c);m=u[a[b*i+y]?1:0]}r[g++]=m.r,r[g++]=m.g,r[g++]=m.b,r[g]=m.a}}})(cc)),cc}var ph;function nT(){return ph||(ph=1,(function(e){const t=uw();function n(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 r(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(s,i,a){let c=a,l=i;typeof c>"u"&&(!i||!i.getContext)&&(c=i,i=void 0),i||(l=r()),c=t.getOptions(c);const d=t.getImageWidth(s.modules.size,c),u=l.getContext("2d"),f=u.createImageData(d,d);return t.qrToImageData(f.data,s,c),n(u,l,d),u.putImageData(f,0,0),l},e.renderToDataURL=function(s,i,a){let c=a;typeof c>"u"&&(!i||!i.getContext)&&(c=i,i=void 0),c||(c={});const l=e.render(s,i,c),d=c.type||"image/png",u=c.rendererOpts||{};return l.toDataURL(d,u.quality)}})(ac)),ac}var lc={},gh;function rT(){if(gh)return lc;gh=1;const e=uw();function t(o,s){const i=o.a/255,a=s+'="'+o.hex+'"';return i<1?a+" "+s+'-opacity="'+i.toFixed(2).slice(1)+'"':a}function n(o,s,i){let a=o+s;return typeof i<"u"&&(a+=" "+i),a}function r(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),p=Math.floor(u/s);!f&&!l&&(l=!0),o[u]?(d++,u>0&&f>0&&o[u-1]||(a+=l?n("M",f+i,.5+p+i):n("m",c,0),c=0,l=!1),f+1<s&&o[u+1]||(a+=n("h",d),d=0)):c++}return a}return lc.render=function(s,i,a){const c=e.getOptions(i),l=s.modules.size,d=s.modules.data,u=l+c.margin*2,f=c.color.light.a?"<path "+t(c.color.light,"fill")+' d="M0 0h'+u+"v"+u+'H0z"/>':"",p="<path "+t(c.color.dark,"stroke")+' d="'+r(d,l,c.margin)+'"/>',g='viewBox="0 0 '+u+" "+u+'"',b='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+g+' shape-rendering="crispEdges">'+f+p+`</svg>
13
- `;return typeof a=="function"&&a(null,b),b},lc}var mh;function oT(){if(mh)return cr;mh=1;const e=Mk(),t=tT(),n=nT(),r=rT();function o(s,i,a,c,l){const d=[].slice.call(arguments,1),u=d.length,f=typeof d[u-1]=="function";if(!f&&!e())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(p,g){try{const m=t.create(a,c);p(s(m,i,c))}catch(m){g(m)}})}try{const p=t.create(a,c);l(null,s(p,i,c))}catch(p){l(p)}}return cr.create=t.create,cr.toCanvas=o.bind(null,n.render),cr.toDataURL=o.bind(null,n.renderToDataURL),cr.toString=o.bind(null,function(s,i,a){return r.render(s,a)}),cr}var sT=oT();const ao="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",Xe="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",lr=`${Xe} bg-primary text-primary-foreground hover:opacity-90`;function iT(e){return e.serviceName||new URL(e.url).hostname}function As(e){return e.includes("service:*")?"完整权限":e.includes("session.input")?"可操作":e.includes("session.view")?"只读":e.includes("route.use")?"仅中转":"自定义权限"}function aT({profile:e,subjectId:t}){return h.jsxs("details",{className:"mt-2 text-xs text-muted-foreground",children:[h.jsx("summary",{className:"cursor-pointer leading-relaxed",children:[e?.model||e?.hostname||e?.system,e?.route,`ID ${t.slice(-8)}`].filter(Boolean).join(" · ")}),h.jsxs("dl",{className:"mt-2 space-y-2 rounded-lg bg-surface-2 p-3",children:[[["设备型号",e?.model],["主机名称",e?.hostname],["操作系统",e?.system],["客户端",e?.client],["打开方式",e?.mode],["处理器",e?.cpu],["架构",e?.arch],["最近连接路径",e?.route],["首次记录",e?.firstSeenAt?new Date(e.firstSeenAt).toLocaleString():void 0],["最近连接",e?.lastSeenAt?new Date(e.lastSeenAt).toLocaleString():void 0],["设备标识",t]].filter(([,n])=>n).map(([n,r])=>h.jsxs("div",{children:[h.jsx("dt",{children:n}),h.jsx("dd",{className:"mt-0.5 select-text break-all text-foreground",children:r})]},n)),h.jsx("p",{className:"leading-relaxed",children:e?"系统、硬件与路径由设备报告;连接时间由服务记录。":"此设备尚未报告详情,更新客户端并重新连接后可补齐。"})]})]})}function cT(){const e=getComputedStyle(document.documentElement),t=e.getPropertyValue("--background").trim(),n=e.getPropertyValue("--foreground").trim(),r=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(!t||!n)throw new Error("Theme unavailable");return r(t)<r(n)?{dark:t,light:n}:{dark:n,light:t}}function lT({onConnect:e,onClose:t,onConnectWithPassword:n,onAddService:r,onOpenService:o,currentIdentity:s,currentServiceName:i,currentServiceId:a,currentServiceOrigin:c,hasBackup:l=!1,inviteAddresses:d=[],paired:u=!1,initialInvite:f,initialServicePage:p,sessions:g=[],grants:m=[],invitations:b=[],onCreateInvite:y,onRevokeInvitation:x,onRevoke:w,onRename:I,loading:R=!1,loadError:S,onRetry:A}){const[T,v]=P.useState(!1),[E,C]=P.useState(""),[B,k]=P.useState({}),[N,L]=P.useState(""),[D,F]=P.useState(""),[O,_]=P.useState(!1),[H,q]=P.useState(!1),[j,K]=P.useState(!u),[G,W]=P.useState(!0),[Y,M]=P.useState(""),[$,X]=P.useState(""),[Q,oe]=P.useState("read"),[de,z]=P.useState("all"),[J,se]=P.useState([]),[Se,Re]=P.useState(!1),[me,Ee]=P.useState(""),[V,ee]=P.useState(""),[ne,ue]=P.useState(),[we,pe]=P.useState(""),[ie,be]=P.useState(),[fe,xe]=P.useState(),[ke,De]=P.useState("services"),[Ie,et]=P.useState(),[$e,dt]=P.useState(""),[_e,Ot]=P.useState(!1),[Kd,Vr]=P.useState(),[qt,ns]=P.useState(!1),[nr,zd]=P.useState([]);let oa;try{oa=new URL(Y==="custom"?Ne($):Y||c||location.origin).hostname}catch{}const Jw=!!oa&&["localhost","127.0.0.1","[::1]"].includes(oa),sa=m.filter(U=>U.revokedAt===void 0&&(!U.expiresAt||U.expiresAt>Date.now())),ia=m.filter(U=>!sa.includes(U)),Yr=[...new Set(sa.map(U=>U.subjectId))].map(U=>{const Z=sa.filter(Ke=>Ke.subjectId===U);return{subjectId:U,grants:Z,name:U===s?"此设备":Z.find(Ke=>Ke.label)?.label||"未命名设备"}}).sort((U,Z)=>+(Z.subjectId===s)-+(U.subjectId===s)),rr=!Ie&&!_e&&u&&!j&&!H&&!f,Qw=()=>{et(void 0),Ot(!1),K(!1),q(!1),ue(void 0),Re(!1),L(""),F(""),Vr(void 0),be(void 0),xe(void 0),M(""),X("")},Wd=()=>{q(!0),K(!1),Re(!1),L(""),F("")},ey=U=>U.subjectId===s?"此设备":U.label||"未命名设备",aa=()=>{qt?ns(!1):t()},Gd=P.useRef(null);Pm(Gd,!0,()=>{O||aa()}),P.useEffect(()=>{let U=!1;if(pe(""),ne)try{sT.toDataURL(ne.url,{width:220,margin:3,errorCorrectionLevel:"M",color:cT()}).then(Z=>{U||pe(Z)}).catch(()=>{})}catch{}return()=>{U=!0}},[ne]);async function ca(U){_(!0),L(""),F("");try{await e(U);const{url:Z,targetPeerId:Ke,serviceName:Cn,serviceOrigin:or}=U;await on({id:Ke,url:Z,targetPeerId:Ke,label:Cn||new URL(Z).host,serviceOrigin:or,entryServiceId:U.entryServiceId}),K(!1),F("已连接。")}catch(Z){U.routeOnly&&Z instanceof gt?v(!0):L("暂时无法连接,请检查网络,或确认邀请是否仍然有效。")}finally{_(!1)}}async function ty(U){if(U.preventDefault(),!y)return;L(""),F("");const Z=J.filter(Kt=>g.some(la=>la.sessionId===Kt));if(Q!=="full"&&de==="selected"&&!Z.length){L("请选择至少一个 Session。");return}const Ke=Z.map(Kt=>g.find(la=>la.sessionId===Kt)?.sourceSessionId||Kt),Cn=V?new Date(V).getTime():void 0;if(Cn!==void 0&&(!Number.isFinite(Cn)||Cn<=Date.now())){L("授权到期时间必须晚于现在。");return}let or;if(Y==="custom")try{or=Ne($)}catch{L("请输入有效的接入地址,例如 https://192.168.1.23:9834。");return}else Y&&(or=Y);_(!0);try{const Kt=await y({...l?{includeBackup:G}:{},...or?{entryAddress:or}:{},scope:Q==="full"||de==="all"?{kind:"service"}:{kind:"sessions",sessionIds:Ke},actions:Q==="full"?["service:*"]:Q==="write"?["session.view","session.input","session.resize"]:["session.view"],...me.trim()?{label:me.trim()}:{},...Cn===void 0?{}:{expiresAt:Cn}});ue(Kt)}catch(Kt){L(Kt instanceof Error&&Kt.message.startsWith("无法分享备用连接:")?"无法分享备用连接:需要入口管理员授权。你也可以关闭“包含备用连接”,生成直连邀请。":"暂时无法生成邀请,请确认当前设备有授权管理权限。")}finally{_(!1)}}async function ny(){if(ne)try{await navigator.clipboard.writeText(ne.url),F("邀请链接已复制。")}catch{L("浏览器未允许复制,请长按下方链接复制。")}}const Vd=U=>U.kind==="service"?"全部终端":U.sessionIds.map(Z=>g.find(Ke=>Ke.sessionId===Z||Ke.sourceSessionId===Z)?.name||Z).join("、"),Yd=U=>x?ie===U?h.jsxs("div",{className:"mt-2 rounded-lg border border-border bg-background p-3 text-left",children:[h.jsx("p",{className:"text-xs leading-relaxed",children:"撤销后,原邀请链接和二维码将立即失效。"}),h.jsxs("div",{className:"mt-2 flex justify-end gap-2",children:[h.jsx("button",{type:"button",className:`${Xe} text-xs text-muted-foreground`,disabled:O,onClick:()=>be(void 0),children:"取消"}),h.jsx("button",{type:"button",className:`${Xe} text-xs text-destructive`,disabled:O,onClick:async()=>{_(!0),L(""),F("");try{await x(U),ne?.id===U&&ue(void 0),be(void 0),F("邀请已撤销,原链接和二维码已失效。")}catch{L("暂时无法撤销。如果邀请已被接受,请在设备列表撤销访问权限。")}finally{_(!1)}},children:"确认撤销邀请"})]})]}):h.jsx("button",{type:"button",className:`${Xe} text-xs text-destructive`,disabled:O,onClick:()=>{be(U),F("")},children:"撤销邀请"}):null,ry=B.title||(Ie?"设备名称":_e?ke==="devices"?"授权详情":"连接详情":qt?"选择终端":H?"邀请设备":j&&u?"添加服务":u?"服务与设备":"连接 Termdock"),oy=!!B.back||!!Ie||_e||qt||u&&(j||H),sy=()=>{if(B.back){B.back();return}qt?ns(!1):Qw()},Xd=U=>U.every(Z=>Z.routeTargetServiceId)?`${new Set(U.map(Z=>Z.routeTargetServiceId)).size} 台服务`:U.some(Z=>Z.scope.kind==="service")?"全部终端":`${new Set(U.flatMap(Z=>Z.scope.kind==="sessions"?Z.scope.sessionIds:[])).size} 个终端`;return Pi.createPortal(h.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&&!O&&aa()},children:h.jsxs("div",{ref:Gd,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",children:[h.jsxs("header",{className:"shrink-0 border-b border-border px-5 pt-3",children:[h.jsxs("div",{className:"flex min-h-12 items-center gap-2 pb-2",children:[oy&&h.jsx("button",{type:"button",className:`${Xe} -ml-3 inline-flex w-11 items-center justify-center text-muted-foreground`,disabled:O,onClick:sy,"aria-label":qt?"取消选择终端":ke==="devices"?"返回设备":"返回服务",children:h.jsx(wm,{size:20})}),h.jsx("h2",{id:"federation-title",className:"min-w-0 flex-1 text-base font-semibold",children:ry}),h.jsx("button",{type:"button",className:`${Xe} -mr-3 inline-flex w-11 items-center justify-center text-muted-foreground`,disabled:O,onClick:aa,"aria-label":"关闭",children:h.jsx(Im,{size:20})})]}),rr&&!B.title&&h.jsx("div",{className:"flex gap-6",role:"tablist","aria-label":"管理内容",children:[["services","服务"],["devices","设备"]].map(([U,Z])=>h.jsxs("button",{type:"button",role:"tab","aria-selected":ke===U,"aria-controls":`federation-${U}`,id:`federation-tab-${U}`,className:`min-h-11 border-b-2 px-1 text-sm transition ${ke===U?"border-primary font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"}`,onClick:()=>{De(U),Re(!1),Vr(void 0),L(""),F("")},children:[Z,U==="devices"&&Yr.length>0&&h.jsx("span",{className:"ml-1.5 text-xs text-muted-foreground",children:Yr.length})]},U))})]}),h.jsxs("div",{className:"min-h-0 overflow-y-auto overscroll-contain px-5 py-4 pb-[max(20px,env(safe-area-inset-bottom))]",children:[(rr&&ke==="services"||j&&!H&&!f)&&h.jsx(_k,{initialServicePage:p,renderRelayServices:(U,Z)=>h.jsx(IA,{service:U,onBusyChange:Z,onConnect:e,onConnectWithPassword:n}),renderRoutes:(U,Z)=>h.jsx(Lm,{service:U,onBusyChange:Z}),hideHeader:!0,initiallyAdding:j,current:a?{id:a,targetPeerId:a,url:c||location.origin,label:i||"当前服务"}:void 0,onNavigation:k,onBusyChange:_,onInvite:y?Wd:void 0,onOpen:async U=>{if(o)return o(U);U.targetPeerId?await ca({...U,targetPeerId:U.targetPeerId,serviceName:U.label}):r&&await r(U.url)},onAdd:async(U,Z)=>{if(r)return r(U,Z);await ca(Un(U))}}),rr&&ke==="devices"&&h.jsxs("section",{role:"tabpanel",id:"federation-devices","aria-labelledby":"federation-tab-devices",children:[h.jsx("p",{className:"mb-2 text-xs leading-relaxed text-muted-foreground",children:"可访问此服务的设备"}),R?h.jsxs("p",{role:"status",className:"flex items-center gap-2 py-5 text-sm text-muted-foreground",children:[h.jsx(lt,{size:16,className:"animate-spin"}),"正在读取设备…"]}):h.jsxs("div",{className:"divide-y divide-border",children:[Yr.map(U=>h.jsxs("div",{className:"py-3",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.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(Z=>Z.label)?.label||(U.subjectId===s?navigator.userAgent:""))?h.jsx(xm,{size:19}):h.jsx(WI,{size:19})}),h.jsxs("div",{className:"min-w-0 flex-1",children:[h.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[h.jsx("p",{className:"truncate text-sm font-medium",children:U.name}),I&&(w||U.subjectId===s)&&h.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:()=>{et(U.subjectId),dt(U.grants.find(Z=>Z.label)?.label||"")},children:h.jsx(VI,{size:14})})]}),U.subjectId===s&&U.grants.find(Z=>Z.label)?.label&&h.jsx("p",{className:"truncate text-xs text-muted-foreground",children:U.grants.find(Z=>Z.label)?.label}),h.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[As(U.grants.flatMap(Z=>Z.actions))," · ",Xd(U.grants)]})]}),w&&U.subjectId!==s&&Kd!==U.subjectId&&h.jsx("button",{type:"button",className:`${Xe} -mr-2 text-xs text-muted-foreground hover:text-destructive`,disabled:O,"aria-label":`撤销 ${U.name} 的访问权限`,onClick:()=>Vr(U.subjectId),children:"撤销"})]}),h.jsx(aT,{profile:U.grants.find(Z=>Z.deviceProfile)?.deviceProfile,subjectId:U.subjectId}),Kd===U.subjectId&&h.jsxs("div",{className:"mt-3 rounded-lg border border-border bg-background p-3",children:[h.jsx("p",{className:"text-xs leading-relaxed",children:"撤销后,这台设备将断开连接,需重新邀请才能访问。"}),h.jsxs("div",{className:"mt-2 flex justify-end gap-2",children:[h.jsx("button",{type:"button",className:`${Xe} text-xs text-muted-foreground`,disabled:O,onClick:()=>Vr(void 0),children:"取消"}),h.jsx("button",{type:"button",className:`${Xe} text-xs text-destructive`,disabled:O,onClick:async()=>{_(!0),L("");try{for(const Z of U.grants)await w?.(Z.id);Vr(void 0),F("设备访问权限已撤销。")}catch{L("暂时无法撤销,请重试。")}finally{_(!1)}},children:"确认撤销"})]})]})]},U.subjectId)),Yr.length===0&&!S&&h.jsxs("p",{className:"py-5 text-sm text-muted-foreground",children:["暂无设备授权。",y?"可通过邀请添加设备。":""]})]}),y&&h.jsxs("button",{type:"button",className:`${Xe} mt-4 inline-flex w-full items-center justify-center gap-2 border border-border text-sm`,disabled:O,onClick:Wd,children:[h.jsx(Em,{size:16}),"邀请设备"]}),b.length>0&&h.jsxs("section",{className:"mt-5 border-t border-border pt-4","aria-label":"待接受的邀请",children:[h.jsx("h3",{className:"text-sm font-medium",children:"待接受的邀请"}),h.jsx("div",{className:"divide-y divide-border",children:b.map(U=>h.jsxs("div",{className:"py-3",children:[h.jsx("p",{className:"text-sm",children:U.label||"设备邀请"}),h.jsxs("p",{className:"mt-1 break-words text-xs text-muted-foreground",children:[As(U.actions)," · ",Vd(U.scope)]}),h.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[new Date(U.invitationExpiresAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," 前有效"]}),Yd(U.id)]},U.id))})]}),ia.length>0&&h.jsxs("details",{className:"mt-4 text-xs text-muted-foreground",children:[h.jsxs("summary",{className:"cursor-pointer py-2",children:["已失效的授权(",ia.length,")"]}),h.jsx("div",{className:"mt-1 space-y-2 border-l border-border pl-3",children:ia.map(U=>h.jsxs("p",{className:"flex gap-3",children:[h.jsx("span",{className:"min-w-0 flex-1 truncate",children:ey(U)}),h.jsx("span",{className:"shrink-0",children:U.revokedAt!==void 0?"已撤销":"已到期"})]},U.id))})]})]}),Ie&&h.jsxs("form",{className:"space-y-4",onSubmit:async U=>{U.preventDefault(),_(!0),L("");try{await I?.(Ie,$e.trim()),et(void 0)}catch{L("暂时无法保存设备名称,请重试。")}finally{_(!1)}},children:[h.jsxs("label",{className:"block space-y-2 text-sm",children:[h.jsx("span",{children:"设备名称"}),h.jsx("input",{autoFocus:!0,className:ao,maxLength:80,required:!0,value:$e,onChange:U=>dt(U.target.value),placeholder:"例如:我的 iPhone、办公室电脑"})]}),h.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"为设备起一个容易辨认的名字,会同步显示在此服务的设备列表中。"}),h.jsx("button",{type:"submit",className:`${lr} w-full`,disabled:O||!$e.trim(),children:O?"正在保存…":"保存名称"})]}),_e&&h.jsx("section",{className:"space-y-5",children:ke==="devices"?Yr.map(U=>h.jsxs("div",{className:"space-y-3",children:[h.jsx("h3",{className:"text-sm font-medium",children:U.name}),h.jsxs("dl",{className:"space-y-3 rounded-xl bg-surface-2 p-3 text-xs",children:[h.jsxs("div",{children:[h.jsx("dt",{className:"text-muted-foreground",children:"访问权限"}),h.jsxs("dd",{className:"mt-1",children:[As(U.grants.flatMap(Z=>Z.actions))," · ",Xd(U.grants)]})]}),U.grants.map(Z=>h.jsxs("div",{children:[h.jsx("dt",{className:"text-muted-foreground",children:Z.routeTargetServiceId?"允许经此入口访问":As(Z.actions)}),h.jsxs("dd",{className:"mt-1 leading-relaxed",children:[Z.routeTargetServiceId?Z.routeTargetName||"指定服务":Vd(Z.scope),!Z.routeTargetServiceId&&h.jsx("span",{className:"mt-1 block text-muted-foreground",children:Z.expiresAt?new Date(Z.expiresAt).toLocaleString():"保留至撤销"})]}),w&&(Z.routeTargetServiceId||U.subjectId!==s)&&(fe===Z.id?h.jsxs("div",{className:"mt-2",children:[h.jsx("p",{className:"leading-relaxed",children:"确认撤销此项授权?此设备的其他授权将保留。"}),h.jsxs("div",{className:"mt-1 flex justify-end gap-2",children:[h.jsx("button",{type:"button",className:`${Xe} text-xs text-muted-foreground`,disabled:O,onClick:()=>xe(void 0),children:"取消"}),h.jsx("button",{type:"button",className:`${Xe} text-xs text-destructive`,disabled:O,onClick:async()=>{_(!0),L("");try{await w(Z.id),xe(void 0),F("此项授权已撤销。")}catch{L("暂时无法撤销,请重试。")}finally{_(!1)}},children:"确认撤销此项授权"})]})]}):h.jsx("button",{type:"button",className:`${Xe} mt-1 -ml-3 text-xs text-destructive`,disabled:O,onClick:()=>xe(Z.id),children:Z.routeTargetServiceId?"撤销此中转权限":"撤销此项授权"}))]},Z.id)),h.jsxs("div",{children:[h.jsx("dt",{className:"text-muted-foreground",children:"设备标识"}),h.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed text-muted-foreground select-text",children:U.subjectId})]})]})]},U.subjectId)):h.jsxs("dl",{className:"space-y-4 text-xs",children:[h.jsxs("div",{children:[h.jsx("dt",{className:"text-muted-foreground",children:"当前服务"}),h.jsx("dd",{className:"mt-1 text-sm",children:i||"当前服务"})]}),h.jsxs("div",{children:[h.jsx("dt",{className:"text-muted-foreground",children:"服务标识"}),h.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed select-text",children:a})]}),h.jsxs("div",{children:[h.jsx("dt",{className:"text-muted-foreground",children:"本设备标识"}),h.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed select-text",children:s})]})]})}),f&&!H&&h.jsxs("section",{className:"space-y-5 py-1",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("span",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-surface-2 text-muted-foreground",children:h.jsx(Zi,{size:22})}),h.jsxs("div",{className:"min-w-0",children:[h.jsx("p",{className:"text-xs text-muted-foreground",children:"你受邀连接"}),h.jsx("p",{className:"mt-1 break-words text-base font-medium",children:iT(f)})]})]}),f.routeOnly&&h.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"此邀请提供备用连接,目标服务仍会验证你的访问权限。"}),T?h.jsxs("form",{className:"space-y-3",onSubmit:async U=>{U.preventDefault(),_(!0),L("");try{await n?.(f,E)}catch(Z){L(Z instanceof Error?Z.message:"暂时无法登录,请重试。")}finally{C(""),_(!1)}},children:[h.jsxs("label",{className:"block space-y-2 text-sm",children:[h.jsx("span",{children:"目标服务密码"}),h.jsx("input",{className:ao,type:"password",required:!0,autoFocus:!0,autoComplete:"current-password",value:E,onChange:U=>C(U.target.value)})]}),h.jsx("button",{className:`${lr} w-full`,disabled:O||!E,children:O?"正在登录…":"登录并连接"})]}):h.jsx("button",{type:"button",className:`${lr} w-full text-sm`,disabled:O,onClick:()=>{ca(f)},children:O?"正在连接…":"接受邀请"})]}),H&&!qt&&h.jsx("section",{children:ne?h.jsxs("div",{className:"space-y-4 text-center",children:[h.jsx("p",{className:"text-sm font-medium",children:"用另一台设备扫描二维码"}),we?h.jsx("img",{src:we,width:220,height:220,className:"mx-auto max-w-full rounded-xl",alt:"设备邀请二维码"}):h.jsx("div",{className:"mx-auto flex h-48 w-48 items-center justify-center",children:h.jsx(lt,{size:22,className:"animate-spin text-muted-foreground"})}),h.jsxs("p",{className:"text-xs leading-relaxed text-muted-foreground",children:["仅限一台设备使用 · ",new Date(ne.expiresAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," 前有效"]}),h.jsxs("button",{type:"button",className:`${lr} inline-flex w-full items-center justify-center gap-2 text-sm`,onClick:()=>{ny()},children:[h.jsx(vm,{size:16}),"复制邀请链接"]}),h.jsxs("details",{className:"text-left text-xs text-muted-foreground",children:[h.jsx("summary",{className:"cursor-pointer py-2",children:"查看链接"}),h.jsx("p",{className:"mt-2 select-all break-all",children:ne.url})]}),ne.id&&Yd(ne.id)]}):h.jsxs("form",{className:"space-y-5",onSubmit:ty,children:[h.jsxs("fieldset",{children:[h.jsx("legend",{className:"mb-2 text-sm font-medium",children:"访问权限"}),h.jsx("div",{className:"space-y-2",children:[["read","仅查看","查看终端画面,不可输入命令"],["write","可操作","查看终端画面,并输入命令"],["full","完整访问","包括文件、设置和权限管理"]].map(([U,Z,Ke])=>h.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 ${Q===U?"border-primary bg-primary/10":"border-border hover:bg-surface-2"}`,children:[h.jsx("input",{type:"radio",name:"federation-permission",value:U,checked:Q===U,onChange:()=>oe(U),className:"sr-only"}),h.jsx("span",{"aria-hidden":"true",className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border ${Q===U?"border-primary bg-primary text-primary-foreground":"border-border bg-background"}`,children:Q===U&&h.jsx(Si,{size:13,strokeWidth:3})}),h.jsxs("span",{className:"min-w-0",children:[h.jsx("span",{className:"block text-sm font-medium text-foreground",children:Z}),h.jsx("span",{className:"mt-0.5 block text-xs leading-relaxed text-muted-foreground",children:Ke})]})]},U))})]}),Q!=="full"&&h.jsxs("fieldset",{children:[h.jsx("legend",{className:"mb-2 text-sm font-medium",children:"可访问的终端"}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{type:"button","aria-pressed":de==="all",className:`${Xe} flex-1 appearance-none border text-sm ${de==="all"?"border-primary bg-primary/10 text-foreground":"border-border text-muted-foreground"}`,onClick:()=>z("all"),children:"全部终端"}),h.jsxs("button",{type:"button","aria-pressed":de==="selected",className:`${Xe} inline-flex flex-1 appearance-none items-center justify-center gap-1 border text-sm ${de==="selected"?"border-primary bg-primary/10 text-foreground":"border-border text-muted-foreground"}`,onClick:()=>{zd(J),ns(!0)},children:[de==="selected"?`已选 ${J.length} 个`:"选择终端",h.jsx(Gn,{size:14})]})]}),de==="all"&&h.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"包括之后新建的终端。"})]}),Q==="write"&&h.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"终端命令可读写该系统用户有权访问的文件。"}),Q==="full"&&h.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"拥有此服务的全部当前及未来权限。仅授予你完全信任的设备。"}),l&&h.jsxs("label",{className:"flex items-start gap-3 text-sm",children:[h.jsx("input",{type:"checkbox",className:"mt-0.5 h-4 w-4 accent-primary",checked:G,onChange:U=>W(U.target.checked)}),h.jsxs("span",{children:["让新设备也能使用备用连接",h.jsx("span",{className:"mt-1 block text-xs leading-relaxed text-muted-foreground",children:"需要入口管理员授权;关闭后生成直接连接邀请。"})]})]}),h.jsxs("details",{className:"rounded-xl border border-border px-3 py-2 text-left",children:[h.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-foreground",children:["接入地址",h.jsx("span",{className:"ml-2 text-xs font-normal text-muted-foreground",children:Y==="custom"?$||"请输入地址":new URL(Y||c||location.origin).host})]}),h.jsxs("fieldset",{className:"mt-2 space-y-2",children:[h.jsx("legend",{className:"sr-only",children:"受邀设备打开的地址"}),h.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:Jw?"当前地址仅供这台电脑使用。邀请其他设备时,请选择它能访问的服务域名或 IP 地址。":"受邀设备将打开这个地址。请确认它能访问所选的服务域名或 IP 地址。"}),h.jsx("div",{className:"space-y-2",children:[["","当前地址",new URL(c||location.origin).host],...d.map(U=>[U.url,U.label,new URL(U.url).host]),["custom","自定义地址",""]].map(([U,Z,Ke])=>h.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 ${Y===U?"border-primary bg-primary/10":"border-border hover:bg-surface-2"}`,children:[h.jsx("input",{type:"radio",name:"federation-entry-address",value:U,checked:Y===U,onChange:()=>M(U),className:"sr-only"}),h.jsx("span",{"aria-hidden":"true",className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border ${Y===U?"border-primary bg-primary text-primary-foreground":"border-border bg-background"}`,children:Y===U&&h.jsx(Si,{size:13,strokeWidth:3})}),h.jsxs("span",{className:"min-w-0",children:[h.jsx("span",{className:"block text-sm font-medium text-foreground",children:Z}),Ke&&h.jsx("span",{className:"block break-all text-xs leading-relaxed text-muted-foreground",children:Ke})]})]},U||"current"))}),Y==="custom"&&h.jsx("input",{type:"text",className:ao,inputMode:"url",placeholder:"例如:https://192.168.1.23:9834",value:$,onChange:U=>X(U.target.value)})]})]}),h.jsxs("div",{children:[h.jsxs("button",{className:`${lr} inline-flex w-full items-center justify-center gap-2 text-sm`,type:"submit",disabled:O||R,children:[O&&h.jsx(lt,{size:16,className:"animate-spin"}),O?"正在生成…":"生成邀请"]}),h.jsxs("p",{className:"mt-2 text-center text-xs leading-relaxed text-muted-foreground",children:["链接 10 分钟内有效 · 访问权限",V?"按设定时间到期":"保留至撤销"]})]})]})}),qt&&h.jsxs("section",{children:[h.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"仅允许访问勾选的终端。"}),h.jsxs("div",{className:"space-y-1",children:[g.map(U=>h.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:[h.jsx("input",{type:"checkbox",className:"h-4 w-4 accent-primary",checked:nr.includes(U.sessionId),onChange:Z=>zd(Z.target.checked?[...nr,U.sessionId]:nr.filter(Ke=>Ke!==U.sessionId))}),h.jsx("span",{className:"min-w-0 break-words",children:U.name})]},U.sessionId)),!g.length&&h.jsx("p",{className:"py-4 text-sm text-muted-foreground",children:"当前没有可共享的终端。"})]})]}),S&&h.jsxs("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:[S,A&&h.jsx("button",{type:"button",className:`${Xe} ml-1 text-sm underline`,onClick:A,children:"重试"})]}),!B.title&&!j&&!Ie&&!_e&&!qt&&!ne&&h.jsxs("div",{className:"mt-4 border-t border-border pt-2",children:[h.jsxs("button",{type:"button",className:`${Xe} -ml-3 inline-flex items-center gap-1 bg-transparent text-xs text-muted-foreground`,"aria-expanded":rr?void 0:Se,onClick:()=>rr?Ot(!0):Re(U=>!U),children:[H?"有效期与备注":j?"手动连接":ke==="devices"?"授权详情":"连接详情",rr?h.jsx(Gn,{size:14}):h.jsx(bm,{size:13,className:Se?"rotate-180":""})]}),Se&&h.jsxs("section",{className:"space-y-3 pb-1 pt-2",children:[H&&h.jsxs(h.Fragment,{children:[h.jsxs("label",{className:"block space-y-1 text-sm",children:[h.jsx("span",{children:"设备备注(可选)"}),h.jsx("input",{className:ao,value:me,onChange:U=>Ee(U.target.value),placeholder:"例如:工作电脑"})]}),h.jsxs("label",{className:"block space-y-1 text-sm",children:[h.jsx("span",{children:"授权到期时间"}),h.jsx("input",{type:"datetime-local",className:ao,value:V,onChange:U=>ee(U.target.value)})]})]}),!H&&s&&h.jsxs("p",{className:"break-all text-xs leading-relaxed text-muted-foreground",children:["本设备身份:",s]})]})]}),N&&h.jsx("p",{role:"alert",className:"mt-3 text-sm text-destructive",children:N}),D&&h.jsx("p",{role:"status",className:"mt-3 text-sm text-muted-foreground",children:D})]}),qt&&h.jsx("footer",{className:"shrink-0 border-t border-border px-5 pt-3 pb-[max(16px,env(safe-area-inset-bottom))]",children:h.jsxs("button",{type:"button",className:`${lr} w-full text-sm`,disabled:!nr.length,onClick:()=>{se(nr),z("selected"),ns(!1)},children:["使用所选终端(",nr.length,")"]})})]})}),document.body)}const dT={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"},uT={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 fT(e){return e==="light"?uT:dT}const vl="termdock:open-services";function fw(){window.dispatchEvent(new Event(vl))}function hT({client:e,initialSessionId:t}){const[n,r]=P.useState([]),[o,s]=P.useState(),i=P.useRef();P.useEffect(()=>{if(!t||i.current===t)return;const f=n.find(p=>p.sessionId===t||p.sourceSessionId===t);f&&(i.current=t,s(f))},[n,t]);const[a,c]=P.useState("正在读取已授权 Session"),[l,d]=P.useState(()=>document.documentElement.dataset.theme==="light"?"light":"dark");P.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=P.useRef(null);return P.useEffect(()=>{let f=!0;const p=async()=>{try{const m=await e.request({type:"session-list"});if(f){const b=m.items;r(b),s(y=>{if(!y)return c(b.length?"选择一个已授权 Session":"暂无已授权的在线 Session"),y;const x=b.find(w=>w.sessionId===y.sessionId);if(!x){c("Session 已移除或授权失效");return}return x.canWrite===y.canWrite&&x.canResize===y.canResize?y:x})}}catch{f&&c("目标不可达或授权已失效")}};p();const g=setInterval(()=>{p()},15e3);return()=>{f=!1,clearInterval(g)}},[e]),P.useEffect(()=>{if(!o||!u.current)return;let f=!1,p=0,g;const m=new ay({theme:fT(l),cursorBlink:o.canWrite,disableStdin:!o.canWrite,convertEol:!1}),b=new cy;m.loadAddon(b),m.open(u.current),o.canResize&&b.fit(),c("正在建立加密终端连接");const y=e.openSocket(`/api/terminal/${encodeURIComponent(o.sessionId)}/ws?flow=2`),x=()=>{f||!o.canResize||(b.fit(),y.readyState===1&&y.send(JSON.stringify({type:"resize",cols:m.cols,rows:m.rows})))};y.onopen=()=>c(o.canWrite?"读写":"只读"),y.onmessage=S=>{try{const A=JSON.parse(S.data);if(f)return;if(A.type==="connected"){g=typeof A.streamEpoch=="string"?A.streamEpoch:void 0,p=Number.isSafeInteger(A.replayLastSeq)?A.replayLastSeq:0,!o.canResize&&Number.isSafeInteger(A.cols)&&Number.isSafeInteger(A.rows)&&A.cols>0&&A.rows>0&&m.resize(A.cols,A.rows);const T=Array.isArray(A.replayChunks)?A.replayChunks.filter(v=>typeof v=="string").join(""):"";m.write((A.replayOutOfWindow?"\x1Bc":"")+T,x)}else A.type==="data"&&typeof A.data=="string"?m.write(A.data,()=>{f||(Number.isSafeInteger(A.seq)&&(p=Math.max(p,A.seq)),y.readyState===1&&Number.isSafeInteger(A.flowSeq)&&y.send(JSON.stringify({type:"output-ack",flowSeq:A.flowSeq,since:p,epoch:g})))}):A.type==="pty-size"&&!o.canResize&&Number.isSafeInteger(A.cols)&&Number.isSafeInteger(A.rows)&&A.cols>0&&A.rows>0?m.resize(A.cols,A.rows):A.type==="error"&&c("目标拒绝终端操作,请检查有效授权")}catch{c("终端数据无效"),y.close()}},y.onclose=()=>c("连接已断开;画面已过期,重新选择 Session 可重连"),y.onerror=()=>c("目标不可达或授权不足");const w=m.onData(S=>{o.canWrite&&y.readyState===1&&y.send(JSON.stringify({type:"input",data:S}))}),I=setInterval(()=>{y.readyState===1&&y.send(JSON.stringify({type:"ping"}))},2e4),R=new ResizeObserver(x);return R.observe(u.current),()=>{f=!0,clearInterval(I),R.disconnect(),w.dispose(),y.onclose=null,y.onerror=null,y.close(),m.dispose()}},[e,o,l]),h.jsxs("div",{className:"flex h-dvh flex-col bg-background text-foreground",children:[h.jsxs("div",{className:"flex items-center gap-3 border-b border-border p-3 text-sm",children:[h.jsxs("span",{className:"min-w-0 flex-1",children:["已授权 Session · ",a]}),h.jsx("button",{type:"button",onClick:fw,className:"min-h-11 shrink-0 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2",children:"服务与设备"})]}),h.jsx("div",{className:"flex flex-wrap gap-2 p-2",children:n.map(f=>h.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?"读写":"只读"]},`${e.targetPeerId}:${f.sessionId}`))}),h.jsx("div",{ref:u,className:"min-h-0 flex-1 overflow-auto p-2"})]})}const pT=String.raw`
14
- ████████ ███████ ██████ ███ ███ ██████ ██████ ██████ ██ ██
15
- ██ ██ ██ ██ ████ ████ ██ ██ ██ ██ ██ ██ ██
16
- ██ █████ ██████ ██ ████ ██ ██ ██ ██ ██ ██ █████
17
- ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
18
- ██ ███████ ██ ██ ██ ██ ██████ ██████ ██████ ██ ██
19
- `;function hw({onLoginSuccess:e,focusEnabled:t=!0,serviceOrigin:n,onManageServices:r}){const{t:o}=Gr(),[s,i]=P.useState(""),[a,c]=P.useState(!1),[l,d]=P.useState(null),[u,f]=P.useState(0),p=P.useRef(null);P.useEffect(()=>{t&&!a&&u===0&&p.current?.focus()},[t,a,u]),P.useEffect(()=>{if(u<=0)return;const x=setInterval(()=>{f(w=>w>1?w-1:0)},1e3);return()=>clearInterval(x)},[u]);const g=u>0,m=t&&!a&&!g&&s.length>0,b=async x=>{if(x.preventDefault(),!!m){c(!0),d(null);try{const w=await ew(s);if(w.ok){i(""),e();return}d(w.rateLimited||w.reason==="rateLimited"?"login.rateLimited":w.reason==="connectionFailed"?"login.failed":w.reason==="identityMismatch"?"login.identityMismatch":w.reason==="unavailable"?"login.unavailable":w.reason==="authorizationRequired"?"login.authorizationRequired":"login.invalidPassword"),w.rateLimited&&typeof w.retryAfterMs=="number"&&f(Math.max(1,Math.ceil(w.retryAfterMs/1e3)))}catch{d("login.failed")}finally{c(!1)}}},y=g?o("login.placeholderBlocked",{s:u}):o("login.placeholder");return h.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:[h.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:pT}),h.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground font-mono",children:[h.jsx("span",{className:"text-primary",children:"$"}),h.jsx("span",{children:o("login.prompt")}),h.jsx("span",{className:"terminal-cursor","aria-hidden":!0,children:"▍"})]}),h.jsxs("form",{onSubmit:b,className:"w-full max-w-xs",children:[h.jsxs("div",{className:`flex items-center gap-1 rounded-full border bg-surface-2 p-1 pl-4 transition ${l?"border-destructive/60":"border-border"}`,children:[h.jsx("input",{ref:p,type:"password",autoComplete:"current-password",value:s,placeholder:y,"aria-label":o("login.placeholder"),onChange:x=>{i(x.target.value),l&&d(null)},disabled:!t||a||g,className:"flex-1 bg-transparent text-foreground placeholder:text-muted-foreground/70 focus:outline-none disabled:opacity-60",style:{minWidth:0,fontSize:"16px"}}),h.jsx("button",{type:"submit",disabled:!m,"aria-label":o("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:a?h.jsx(lt,{size:16,className:"animate-spin"}):h.jsx(DI,{size:16})})]}),l&&!g?h.jsx("div",{role:"alert",className:"mt-3 text-center text-xs text-destructive",children:o(l)}):null]}),n&&h.jsxs("div",{className:"w-full max-w-xs text-center text-xs leading-5 text-muted-foreground",children:[h.jsx("p",{className:"break-all",title:n,children:o("login.currentTarget",{address:new URL(n).host})}),r&&h.jsx("button",{type:"button",disabled:!t||a,className:"mt-1 min-h-11 rounded-lg px-3 text-xs underline underline-offset-4 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:opacity-50",onClick:r,children:o("login.manageServices")})]}),h.jsx("style",{children:`
20
- @keyframes terminal-blink {
21
- 0%, 49% { opacity: 1; }
22
- 50%, 100% { opacity: 0; }
23
- }
24
- .terminal-cursor {
25
- display: inline-block;
26
- animation: terminal-blink 1.05s steps(1, end) infinite;
27
- color: var(--primary);
28
- }
29
- `})]})}const gT={activeKey:"root",items:[]},mT=()=>()=>{},wT=()=>gT,Sl="termdock:open-saved-service";function yT(e,t){try{const n=new URL(e.serviceOrigin||e.url);return e.label!==n.host&&e.label!==n.origin?e.label:!t.some(o=>{const s=new URL(o.serviceOrigin||o.url);return s.hostname===n.hostname&&s.port!==n.port})&&n.port==="9834"?n.hostname:n.host}catch{return e.label}}function X2(e,t,n){P.useEffect(()=>{window.termdockDesktop?.reportServiceActivity?.({runningCount:e,reviewCount:t})},[e,t]),P.useEffect(()=>{hr({runningCount:e,reviewCount:t,attentionSessions:n})},[e,t,n])}function bT({onReselect:e}){return window.termdockDesktop?null:h.jsx(vT,{onReselect:e})}function vT({onReselect:e}){const[t,n]=P.useState([]),[r,o]=P.useState([]),[s,i]=P.useState(te()?.targetPeerId),[a,c]=P.useState(""),[l,d]=P.useState(!1),[u,f]=P.useState(!1),p=P.useRef(0),g=P.useRef(!1);P.useEffect(()=>{let S=!1;const A=()=>{const T=p.current;bn().then(v=>{!S&&!g.current&&T===p.current&&d(v.serviceSwitcherExpanded===!0)}).catch(()=>{})};return A(),window.addEventListener(Et,A),()=>{S=!0,window.removeEventListener(Et,A)}},[]);const m=async()=>{if(g.current)return;const S=l;p.current+=1,g.current=!0,f(!0),d(!S),c("");try{const A=await yt({serviceSwitcherExpanded:!S});d(A.serviceSwitcherExpanded===!0)}catch{d(S),c("展开状态保存失败,请重试")}finally{g.current=!1,f(!1)}},b=P.useRef(null),y=$t(),x=P.useSyncExternalStore(y?.subscribe||mT,y?.snapshot||wT);P.useEffect(()=>{let S=!1,A=0;const T=()=>{const C=++A;i(te()?.targetPeerId),Ve().then(B=>{if(!(S||C!==A)){try{const k="termdock-secure-service-order",N=JSON.parse(localStorage.getItem(k)||"[]"),L=Array.isArray(N)?N.filter(_=>typeof _=="string"):[],D=_=>_.targetPeerId||_.id,F=[...L.filter(_=>B.some(H=>D(H)===_)),...B.map(D).filter(_=>!L.includes(_))];B.sort((_,H)=>F.indexOf(D(_))-F.indexOf(D(H)));const O=JSON.stringify(F);O!==localStorage.getItem(k)&&localStorage.setItem(k,O)}catch{}n(B)}}).catch(()=>{})};T();const v=Di(T),E=window.termdockDesktop?.onServiceActivity?.(o);return window.addEventListener(Et,T),()=>{S=!0,v(),E?.(),window.removeEventListener(Et,T)}},[]),P.useEffect(()=>{const S=b.current,A=S?.querySelector('[aria-current="page"]');if(!S||!A)return;const T=A.offsetLeft,v=T+A.offsetWidth;T<S.scrollLeft?S.scrollLeft=T:v>S.scrollLeft+S.clientWidth&&(S.scrollLeft=v-S.clientWidth)},[s,t,l]);const w=async S=>{if(c(""),S.targetPeerId&&S.targetPeerId===s){e?.();return}try{const A=window.termdockDesktop;if(A?.openServiceConnection){const T=await A.openServiceConnection(S);if(!T.ok)throw new Error(T.error||"暂时无法打开服务")}else bi(S)||window.dispatchEvent(new CustomEvent(Sl,{detail:S}))}catch(A){c(A instanceof Error?A.message:"暂时无法切换服务")}},I=S=>{const A=x.items.find(v=>v.service?.targetPeerId===S.targetPeerId),T=r.find(v=>v.targetPeerId&&v.targetPeerId===S.targetPeerId||v.origin===(S.serviceOrigin||S.url));return{phase:A?.phase,running:A?.runningCount??T?.runningCount??0,review:A?.reviewCount??T?.reviewCount??0}},R=S=>{const A=I(S);return A.review?h.jsxs("span",{className:"inline-flex shrink-0 items-center gap-0.5 text-[color:var(--warning)]",title:"等待处理",children:[h.jsx(ym,{size:11}),A.review]}):A.phase==="connecting"||A.phase==="reconnecting"?h.jsx(lt,{size:12,className:"shrink-0 animate-spin","aria-label":"正在连接"}):A.phase==="offline"||A.phase==="login"?h.jsx("span",{className:"shrink-0 text-[color:var(--warning)]",title:A.phase==="login"?"需要登录":"连接已断开",children:"!"}):A.running?h.jsx("span",{className:"shrink-0 text-[color:var(--success)]",title:"运行中",children:A.running}):null};return t.length<=1?null:h.jsxs("div",{className:"min-w-0 shrink-0 bg-[var(--chrome-bg)] px-3 pb-1 md:order-first md:bg-transparent md:pb-0 md:pt-1","data-sidebar-gesture-ignore":!0,children:[h.jsx("button",{type:"button",onClick:()=>{m()},disabled:u,"aria-expanded":l,"aria-label":l?"收起服务切换":"展开服务切换",title:l?"收起服务切换":"展开服务切换",className:"flex h-6 w-full items-center justify-center rounded-lg text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary disabled:opacity-60",children:l?h.jsx(bm,{size:16}):h.jsx($I,{size:16})}),l&&h.jsxs("div",{className:"flex w-full items-center gap-1 md:gap-0 md:rounded-xl md:bg-surface md:p-1",children:[h.jsx("nav",{ref:b,"aria-label":"切换服务",className:"relative flex min-w-0 flex-1 gap-0.5 overflow-x-auto overscroll-x-contain md:gap-1 md:rounded-lg [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:t.map(S=>h.jsx("button",{type:"button",onClick:()=>{w(S)},"aria-current":S.targetPeerId===s?"page":void 0,"aria-label":S.label,title:S.label,className:`inline-flex min-h-11 min-w-0 flex-[1_0_auto] items-center justify-center rounded-lg text-[11px] leading-4 transition-colors motion-reduce:transition-none md:min-h-8 ${t.length>3?"md:flex-[0_0_30%]":"md:flex-[1_1_0%]"} focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary ${S.targetPeerId===s?"font-medium text-foreground md:bg-surface-elevated":"text-muted-foreground hover:bg-surface hover:text-foreground md:hover:bg-surface-2"}`,children:h.jsxs("span",{className:`inline-flex min-w-0 items-center justify-center gap-1 rounded-lg px-2 py-1.5 ${S.targetPeerId===s?"bg-surface-elevated md:bg-transparent":""}`,children:[h.jsx("span",{className:"max-w-[11rem] truncate md:hidden",children:yT(S,t)}),h.jsx("span",{className:"hidden truncate md:inline",children:S.label}),R(S)]})},S.id))}),h.jsx("button",{type:"button",onClick:fw,"aria-label":"管理服务",title:"管理服务",className:"inline-flex h-11 w-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-surface hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary md:hidden",children:h.jsx(Sm,{size:18})})]}),a&&h.jsx("p",{role:"alert",className:"mt-1 text-[11px] text-[color:var(--warning)]",children:a})]})}function Cs(e,t,n=new Set){for(const r of e.keys()){if(e.size<=t)break;n.has(r)||e.delete(r)}return e}function _t(e,t){if(typeof window>"u")return null;try{const n=window.localStorage.getItem(e);if(n===null||n==="")return null;const r=JSON.parse(n);return t(r)?r:null}catch{return null}}function pt(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function dr(e){if(!(typeof window>"u"))try{window.localStorage.removeItem(e)}catch{}}const Bo=new Map,Nr=new Map,$s=new Map;function Z2(e,t,n){if(typeof window>"u")return;const r=Date.now(),o=$s.get(e)??0,s=r-o;if(s>=n){$s.set(e,r),pt(e,t);return}if(Nr.set(e,t),Bo.has(e))return;const i=n-s,a=setTimeout(()=>{Bo.delete(e);const c=Nr.get(e);Nr.delete(e),$s.set(e,Date.now()),c!==void 0&&pt(e,c)},i);Bo.set(e,a)}function ST(e){const t=Bo.get(e);t&&(clearTimeout(t),Bo.delete(e));const n=Nr.get(e);n!==void 0&&(Nr.delete(e),$s.set(e,Date.now()),pt(e,n))}function J2(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}if(typeof window<"u"){const e=()=>{for(const t of Nr.keys())ST(t)};window.addEventListener("pagehide",e),window.addEventListener("termdock:before-update",e),document.addEventListener("visibilitychange",()=>{document.hidden&&e()})}const ET=600,qo=320,xT=280,IT=5;function Q2(e,t,n=0){const r=Math.max(qo,t-Math.max(0,n)-IT*(n>0?2:1)-xT);return Math.min(r,Math.max(qo,e))}const pw="termdock:right-sidebar:tabs-by-session:v2",gw="termdock:right-sidebar:explorer-roots-by-session:v2",Bd="termdock:right-sidebar:pinned-explorer-roots:v1",mw="termdock:right-sidebar:selected-files-by-session:v2",ww="termdock:right-sidebar:show-hidden-files:v1",El="termdock:right-sidebar:file-sort-modes:v1",xl="termdock:right-sidebar:nested-git-scan-roots:v1",yw="termdock:right-sidebar:active-git-repo:v2",AT="termdock:right-sidebar:active-git-repo:v1",wh="termdock-sidebar-group-by-folder",bw="termdock-sidebar-collapsed-folder-groups",vw="termdock-left-sidebar-pinned",Sw="termdock-left-sidebar-width",Ew="termdock-right-sidebar-pinned",Dd="termdock:right-sidebar:pinned-by-session:v1",xw="termdock-right-sidebar-width",_d="termdock:right-sidebar:widths-by-session:v1",Iw="termdock:right-sidebar:split-state-initialized:v1",Aw="termdock-right-sidebar-layout-preference";function CT(){if(typeof window>"u")return!0;try{const e=window.localStorage.getItem(vw);return e===null?!0:e==="1"}catch{return!0}}function yh(e){if(!(typeof window>"u"))try{window.localStorage.setItem(vw,e?"1":"0")}catch{}}function RT(){if(typeof window>"u")return 300;try{const e=window.localStorage.getItem(Sw);if(!e)return 300;const t=parseInt(e,10);return Number.isFinite(t)&&t>=200&&t<=500?t:300}catch{return 300}}function kT(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Sw,String(e))}catch{}}function qs(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Ew)==="1"}catch{return!1}}function TT(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Ew,e?"1":"0")}catch{}}function Ai(){return _t(Dd,e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="boolean"))??{}}function co(e,t){if(!e){TT(t);return}pt(Dd,{...Ai(),[e]:t})}function Ks(){if(typeof window>"u")return 760;try{const e=window.localStorage.getItem(xw);if(!e)return 760;const t=parseInt(e,10);return Number.isFinite(t)&&t>=qo?t:760}catch{return 760}}function PT(e){if(!(typeof window>"u"))try{window.localStorage.setItem(xw,String(e))}catch{}}function NT(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="number"&&Number.isFinite(t)&&t>=qo)}function Ci(){return _t(_d,NT)??{}}function Rs(e,t){if(!e){PT(t);return}pt(_d,{...Ci(),[e]:t})}function LT(){if(typeof window>"u")return"auto";try{const e=window.localStorage.getItem(Aw);return e==="narrow"||e==="wide"?e:"auto"}catch{return"auto"}}function BT(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Aw,e)}catch{}}function eN(e,t,n){return!t||n==="auto"?e<ET:n==="narrow"}function DT(){return!0}function bh(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(wh,"1"):window.localStorage.setItem(wh,"0")}catch{}}function _T(){if(typeof window>"u")return new Set;try{const e=window.localStorage.getItem(bw);if(!e)return new Set;const t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function OT(e){if(!(typeof window>"u"))try{window.localStorage.setItem(bw,JSON.stringify([...e]))}catch{}}function FT(e){return e==="git"||e==="files"||e==="diff"||e==="android"||e==="computer"||e==="architecture"}function MT(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(FT)}function Il(){return _t(pw,MT)??{}}function ur(e,t){e&&pt(pw,{...Il(),[e]:t})}function jT(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string")}function vh(){return _t(gw,jT)??{}}function ks(e){pt(gw,e)}function UT(e){return e!==null&&typeof e=="object"&&typeof e.path=="string"&&(e.kind==="file"||e.kind==="directory")}function HT(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>Array.isArray(t)&&t.every(n=>typeof n=="string"||UT(n)))}function Cw(e){const t=new Set,n=[];for(const r of e){const o=typeof r=="string"?{path:r,kind:"directory"}:r;!o.path||t.has(o.path)||(t.add(o.path),n.push(o))}return n}function $T(){const e=_t(Bd,HT)??{},t={};for(const[n,r]of Object.entries(e))t[n]=Cw(r);return t}function Sh(e){pt(Bd,e)}function qT(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string")}function Al(){return _t(mw,qT)??{}}function lo(e,t){if(!e)return;const n={...Al()};t?n[e]=t:delete n[e],pt(mw,n)}function Lr(e,t){return t?e?`${e}\0${t}`:t:null}function Ri(e,t,n){return n?`split-workspace\0${n}`:Lr(e,t)}function tN(e,t,n){const r=Ci(),o=Ri(e,t,n);if(o&&r[o]!==void 0)return r[o];if(n){const s=Lr(e,t);if(s&&r[s]!==void 0)return r[s]}return Ks()}function nN(e,t,n){const r=Ai(),o=Ri(e,t,n);if(o&&r[o]!==void 0)return r[o];if(n){const s=Lr(e,t);if(s&&r[s]!==void 0)return r[s]}return qs()}function Rw(){const e=_t(Iw,t=>Array.isArray(t)&&t.every(n=>typeof n=="string"));return new Set(e??[])}function KT(e){const t=Rw();t.has(e)||(t.add(e),pt(Iw,[...t]))}function zT(e){return typeof e=="boolean"}function WT(){return _t(ww,zT)??!1}function GT(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>t==="modified")}function VT(){return _t(El,GT)??{}}function YT(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>t===!0)}function XT(){return _t(xl,YT)??{}}function ZT(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.entries(e).every(([t,n])=>t.length>0&&typeof n=="string"&&n.length>0)}function JT(){return _t(yw,ZT)??{}}function Eh(e){pt(yw,e)}let uo=null,fo=null;const dc=new Map;let ho=null;const Ts=new Map;let po=null;const uc=new Set;let go=null;const fc=globalThis.crypto?.randomUUID?.()??`pins-${Math.random().toString(36).slice(2)}`;function QT(e){const t=e.replace(/\/+$/,"")||"/";return t==="/"?"/":t.slice(0,t.lastIndexOf("/"))||"/"}function kn(e,t){const n=e.replace(/\/+$/,"")||"/";return t===n||t.startsWith(`${n}/`)}function xh(e,t="name"){return[...e].sort((n,r)=>{if(n.type==="directory"&&r.type!=="directory")return-1;if(n.type!=="directory"&&r.type==="directory")return 1;if(t==="modified"){const o=Date.parse(r.modified??"")-Date.parse(n.modified??"");if(Number.isFinite(o)&&o!==0)return o}return n.name.localeCompare(r.name)})}function eP(e){return e.entry?{name:e.entry.name,path:e.entry.path,type:e.entry.type,isSymlink:e.entry.isSymlink,modified:e.entry.modified,expanded:!1,loaded:!1,children:e.entry.type==="directory"?[]:void 0}:null}const qe=Ji(e=>({leftOpen:!1,rightOpen:!1,leftPinned:CT(),leftSidebarWidth:RT(),rightPinned:qs(),rightSidebarWidth:Ks(),rightSidebarLayoutPreference:LT(),initialRightSidebarStateBySession:new Map,rightTab:"files",rightSearchOpen:!1,pendingTerminalPath:null,rootPath:null,contextKey:null,rightSidebarWidthContextKey:null,explorerRoot:null,explorerRootCache:vh(),pinnedExplorerRootsCache:$T(),pinnedExplorerRootsHydrated:!1,expandedPaths:new Set,selectedFilePath:null,directoryCache:new Map,fileSortModes:VT(),fileSortModesHydrated:!1,hideGitIgnoredRoots:{},gitIgnoreExceptions:{},hideGitIgnoredRootsHydrated:!1,nestedGitScanRoots:XT(),nestedGitScanRootsHydrated:!1,activeGitRepos:JT(),activeGitReposHydrated:!1,showHiddenFiles:WT(),groupByFolder:DT(),collapsedGroups:_T(),changedFiles:new Map,fileChangeVersions:new Map,fileWatchEpoch:0,gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null,gitBundleError:null,gitBundleLastLoadedAt:null,gitBundleCacheInfo:null,projectStateCache:new Map,rootDataCache:new Map,openLeft:()=>e({leftOpen:!0}),closeLeft:()=>e({leftOpen:!1}),toggleLeft:()=>e(t=>({leftOpen:!t.leftOpen,rightOpen:t.leftOpen?t.rightOpen:!1})),toggleLeftPinned:()=>e(t=>{const n=!t.leftPinned;return yh(n),{leftPinned:n,leftOpen:!0}}),setLeftPinned:t=>e(()=>(yh(t),{leftPinned:t})),setLeftSidebarWidth:t=>e(n=>{const r=Math.min(Math.max(t,200),500);return n.leftSidebarWidth===r?n:(kT(r),{leftSidebarWidth:r})}),toggleRightPinned:()=>e(t=>{const n=!t.rightPinned;return co(t.rightSidebarWidthContextKey,n),{rightPinned:n,rightOpen:!0}}),setRightPinned:t=>e(n=>(co(n.rightSidebarWidthContextKey,t),{rightPinned:t})),setRightSidebarWidth:t=>e(n=>{const r=Math.max(t,qo);return n.rightSidebarWidth===r?n:(Rs(n.rightSidebarWidthContextKey,r),{rightSidebarWidth:r})}),setRightSidebarLayoutPreference:t=>e(n=>n.rightSidebarLayoutPreference===t?n:(BT(t),{rightSidebarLayoutPreference:t})),openTerminalPath:t=>e(n=>(ur(n.contextKey,"files"),{pendingTerminalPath:{...t},rightTab:"files",rightOpen:!0})),openRight:()=>e({rightOpen:!0}),closeRight:()=>e({rightOpen:!1,rightSearchOpen:!1}),toggleRight:()=>e(t=>({rightOpen:!t.rightOpen,rightSearchOpen:t.rightOpen?!1:t.rightSearchOpen,leftOpen:t.rightOpen?t.leftOpen:!1})),closeAll:()=>e({leftOpen:!1,rightOpen:!1,rightSearchOpen:!1}),setRightTab:t=>e(n=>(ur(n.contextKey,t),{rightTab:t})),openRightSearch:()=>e({rightSearchOpen:!0}),closeRightSearch:()=>e({rightSearchOpen:!1}),setRightSearchOpen:t=>e({rightSearchOpen:t}),initializeRightSidebarForSession:(t,n,r)=>e(o=>{const s=Lr(t,n);s&&(co(s,r.rightPinned),Rs(s,r.rightSidebarWidth),ur(s,r.rightTab));const i=new Map(o.initialRightSidebarStateBySession);return i.set(t,{...r}),{initialRightSidebarStateBySession:i}}),setRootPath:(t,n=null,r=null)=>e(o=>{const s=Lr(n,t),i=Ri(n,t,r),a=r?i:s,c=n&&!r?o.initialRightSidebarStateBySession.get(n):void 0;if(!c&&o.contextKey===a&&o.rightSidebarWidthContextKey===i)return t===o.rootPath?o:{rootPath:t};const l=new Map(o.initialRightSidebarStateBySession);c&&s&&n&&(co(s,c.rightPinned),Rs(s,c.rightSidebarWidth),ur(s,c.rightTab),l.delete(n));const d=new Map(o.rootDataCache);o.rootPath&&d.set(o.rootPath,{directoryCache:o.directoryCache,changedFiles:o.changedFiles,gitBundleError:o.gitBundleError,gitBundleLastLoadedAt:o.gitBundleLastLoadedAt,gitBundleCacheInfo:o.gitBundleCacheInfo}),Cs(d,12,new Set(t?[t]:[]));const u=t?d.get(t):void 0,f=t===o.rootPath,p=new Map(o.projectStateCache);o.contextKey&&p.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 g=r?Rw().has(r):!1;let m={...vh(),...o.explorerRootCache};const b=!!r&&!g,y=b&&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}:p.get(s):void 0;if(b&&r){const E=y?.rightTab??(s?Il()[s]:void 0)??"files",C=y?.explorerRoot??(s?o.explorerRootCache[s]:void 0)??t,B=y?.selectedFilePath??(s?Al()[s]:void 0)??null,k={rightTab:E,explorerRoot:C,expandedPaths:new Set(y?.expandedPaths??[]),selectedFilePath:B,directoryCache:new Map(y?.directoryCache??[]),changedFiles:new Map(y?.changedFiles??[]),gitBundleError:y?.gitBundleError??null,gitBundleLastLoadedAt:y?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:y?.gitBundleCacheInfo??null};a&&(p.set(a,k),ur(a,E),lo(a,B),C&&(m={...m,[a]:C},ks(m))),KT(r)}Cs(p,12,new Set(a?[a]:[]));const x=a?p.get(a):void 0,w=a?Il()[a]:void 0,I=Ci();let R=i?I[i]:void 0;r&&i&&R===void 0&&(R=(s?I[s]:void 0)??Ks(),Rs(i,R));const S=a?m[a]:void 0,A=Ai();let T=i?A[i]:void 0;r&&i&&T===void 0&&(T=(s?A[s]:void 0)??qs(),co(i,T));const v=a?Al()[a]:void 0;return{rootPath:t,pendingTerminalPath:null,contextKey:a,rightSidebarWidthContextKey:i,initialRightSidebarStateBySession:l,rightSidebarWidth:c?.rightSidebarWidth??R??Ks(),rightPinned:c?.rightPinned??T??qs(),rightOpen:c?.rightOpen??(o.rightSidebarWidthContextKey===i?o.rightOpen:!1),rightTab:c?.rightTab??x?.rightTab??w??"files",explorerRoot:x?.explorerRoot??S??t,expandedPaths:x?new Set(x.expandedPaths):new Set,selectedFilePath:x?.selectedFilePath??v??null,explorerRootCache:m,directoryCache:u?.directoryCache??new Map,changedFiles:u?.changedFiles??new Map,gitBundleLoading:f?o.gitBundleLoading:!1,gitBundleSlow:f?o.gitBundleSlow:!1,gitBundleLoadingOwner:f?o.gitBundleLoadingOwner:null,gitBundleError:u?.gitBundleError??null,gitBundleLastLoadedAt:u?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:u?.gitBundleCacheInfo??null,rootDataCache:d,projectStateCache:p}}),inheritRightSidebarStateFromSplitWorkspace:(t,n)=>e(r=>{if(!t||n.length===0)return r;const o=Ci(),s=Ri(null,null,t);if(!s)return r;const i=o[s]??(r.rightSidebarWidthContextKey===s?r.rightSidebarWidth:void 0),a=Ai(),c=a[s]??(r.rightSidebarWidthContextKey===s?r.rightPinned:void 0),l=r.contextKey===s?{rightTab:r.rightTab,explorerRoot:r.explorerRoot,expandedPaths:new Set(r.expandedPaths),selectedFilePath:r.selectedFilePath,directoryCache:new Map(r.directoryCache),changedFiles:new Map(r.changedFiles),gitBundleError:r.gitBundleError,gitBundleLastLoadedAt:r.gitBundleLastLoadedAt,gitBundleCacheInfo:r.gitBundleCacheInfo}:r.projectStateCache.get(s);if(i===void 0&&c===void 0&&!l)return r;const d={...o},u=new Map(r.projectStateCache),f={...r.explorerRootCache},p=new Map(r.initialRightSidebarStateBySession);for(const g of n){p.delete(g.sessionId);const m=Lr(g.sessionId,g.rootPath);m&&(i!==void 0&&(d[m]=i),c!==void 0&&(a[m]=c),l&&(u.set(m,{...l,expandedPaths:new Set(l.expandedPaths),directoryCache:new Map(l.directoryCache),changedFiles:new Map(l.changedFiles)}),ur(m,l.rightTab),lo(m,l.selectedFilePath),l.explorerRoot?f[m]=l.explorerRoot:delete f[m]))}return i!==void 0&&pt(_d,d),l&&ks(f),c!==void 0&&pt(Dd,a),Cs(u,12,new Set(r.contextKey?[r.contextKey]:[])),{projectStateCache:u,explorerRootCache:f,initialRightSidebarStateBySession:p}}),setExplorerRoot:t=>e(n=>{if(n.explorerRoot===t)return n;const r={...n.explorerRootCache};return n.contextKey&&t&&(r[n.contextKey]=t,ks(r)),{explorerRoot:t,explorerRootCache:r}}),resetExplorerToProject:()=>e(t=>{if(t.explorerRoot===t.rootPath)return t;const n={...t.explorerRootCache};return t.contextKey&&t.rootPath&&(n[t.contextKey]=t.rootPath,ks(n)),{explorerRoot:t.rootPath,explorerRootCache:n}}),pinExplorerRoot:(t,n="directory")=>e(r=>{if(!r.rootPath||!t)return r;const o=r.rootPath,s=r.pinnedExplorerRootsCache[r.rootPath]??[];if(s.some(a=>a.path===t))return r;const i={...r.pinnedExplorerRootsCache,[r.rootPath]:[{path:t,kind:n},...s].slice(0,12)};return Sh(i),(async()=>{try{await qe.getState().hydratePinnedExplorerRoots();const a=await yt({pinnedExplorerRoot:{rootPath:o,path:t,kind:n,pinned:!0},pinnedExplorerRootsOrigin:fc});qe.getState().syncPinnedExplorerRoots(a.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:i}}),unpinExplorerRoot:t=>e(n=>{if(!n.rootPath||!t)return n;const r=n.rootPath,o=n.pinnedExplorerRootsCache[n.rootPath]??[],s=o.find(c=>c.path===t);if(!o.some(c=>c.path===t))return n;const i=o.filter(c=>c.path!==t),a={...n.pinnedExplorerRootsCache};return i.length>0?a[n.rootPath]=i:delete a[n.rootPath],Sh(a),(async()=>{try{await qe.getState().hydratePinnedExplorerRoots();const c=await yt({pinnedExplorerRoot:{rootPath:r,path:t,kind:s?.kind??"directory",pinned:!1},pinnedExplorerRootsOrigin:fc});qe.getState().syncPinnedExplorerRoots(c.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:a}}),hydratePinnedExplorerRoots:async()=>{if(!qe.getState().pinnedExplorerRootsHydrated)return go||(go=(async()=>{const t=qe.getState().pinnedExplorerRootsCache;let r=(await bn()).pinnedExplorerRoots??{};Object.keys(r).length===0&&Object.keys(t).length>0&&(r=(await yt({pinnedExplorerRoots:t,pinnedExplorerRootsOrigin:fc})).pinnedExplorerRoots??t),qe.getState().syncPinnedExplorerRoots(r)})().finally(()=>{go=null}),go)},syncPinnedExplorerRoots:t=>e(()=>{const n={};for(const[r,o]of Object.entries(t)){const s=Cw(o);s.length>0&&(n[r]=s.slice(0,12))}return dr(Bd),{pinnedExplorerRootsCache:n,pinnedExplorerRootsHydrated:!0}}),toggleExpanded:t=>e(n=>{const r=new Set(n.expandedPaths);return r.has(t)?r.delete(t):r.add(t),{expandedPaths:r}}),selectFile:t=>e(n=>(lo(n.contextKey,t),{selectedFilePath:t})),toggleShowHiddenFiles:()=>e(t=>{const n=!t.showHiddenFiles;pt(ww,n);const r=new Map(t.projectStateCache);for(const[o,s]of r)r.set(o,{...s,directoryCache:new Map});return{showHiddenFiles:n,directoryCache:new Map,projectStateCache:r}}),toggleGroupByFolder:()=>e(t=>{const n=!t.groupByFolder;return bh(n),{groupByFolder:n}}),setGroupByFolder:t=>e(n=>n.groupByFolder===t?n:(bh(t),{groupByFolder:t})),toggleGroupCollapsed:t=>e(n=>{const r=new Set(n.collapsedGroups);return r.has(t)?r.delete(t):r.add(t),OT(r),{collapsedGroups:r}}),setDirectoryCache:(t,n)=>e(r=>{const o=new Map(r.directoryCache);return o.delete(t),o.set(t,n),Cs(o,128,new Set([...r.expandedPaths,t,r.explorerRoot??r.rootPath??""])),{directoryCache:o}}),reconcileDirectoryCache:(t,n)=>e(r=>{const o=r.directoryCache.get(t);if(!o)return r;const s=new Map(o.map(d=>[d.path,d])),i=new Set(n.map(d=>d.path)),a=new Map(r.directoryCache),c=n.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(t,xh(c,r.fileSortModes[t]??"name"));for(const d of o)if(!i.has(d.path))for(const u of a.keys())kn(d.path,u)&&a.delete(u);let l=r.selectedFilePath;return l&&o.find(u=>!i.has(u.path)&&kn(u.path,l))&&(l=null,lo(r.rootPath,null)),{directoryCache:a,selectedFilePath:l}}),hydrateHideGitIgnoredRoots:async()=>{if(!qe.getState().hideGitIgnoredRootsHydrated)return uo||(uo=(async()=>{const t=await bn();e({hideGitIgnoredRoots:t.hideGitIgnoredRoots??{},gitIgnoreExceptions:t.gitIgnoreExceptions??{},hideGitIgnoredRootsHydrated:!0})})().finally(()=>{uo=null}),uo)},setHideGitIgnoredRoot:async(t,n)=>{const r=await yt({hideGitIgnoredRoot:{rootPath:t,enabled:n}});e(o=>{const s=new Map(o.projectStateCache);for(const[i,a]of s)s.set(i,{...a,directoryCache:new Map});return{hideGitIgnoredRoots:r.hideGitIgnoredRoots??{},gitIgnoreExceptions:r.gitIgnoreExceptions??{},hideGitIgnoredRootsHydrated:!0,directoryCache:new Map,projectStateCache:s}})},setGitIgnoreExceptions:async(t,n)=>{const r=await yt({gitIgnoreExceptions:{rootPath:t,paths:n}});e(o=>{const s=new Map(o.projectStateCache);for(const[i,a]of s)s.set(i,{...a,directoryCache:new Map});return{gitIgnoreExceptions:r.gitIgnoreExceptions??{},directoryCache:new Map,projectStateCache:s}})},hydrateFileSortModes:async()=>{if(!qe.getState().fileSortModesHydrated)return fo||(fo=(async()=>{const t=qe.getState().fileSortModes;let r=(await bn()).fileSortModes??{};Object.keys(r).length===0&&Object.keys(t).length>0&&(r=(await yt({fileSortModes:t})).fileSortModes??t),dr(El),e({fileSortModes:r,fileSortModesHydrated:!0,directoryCache:new Map})})().finally(()=>{fo=null}),fo)},setDirectorySortMode:async(t,n)=>{try{await qe.getState().hydrateFileSortModes()}catch{}const r=qe.getState().fileSortModes[t]??"name",o=(dc.get(t)??0)+1;dc.set(t,o),e(s=>{const i={...s.fileSortModes};n==="modified"?i[t]=n:delete i[t];const a=new Map(s.directoryCache);return a.delete(t),{fileSortModes:i,fileSortModesHydrated:!0,directoryCache:a}});try{await yt({fileSortMode:{path:t,mode:n}}),dr(El)}catch{if(dc.get(t)!==o)return;e(s=>{const i={...s.fileSortModes};r==="modified"?i[t]=r:delete i[t];const a=new Map(s.directoryCache);return a.delete(t),{fileSortModes:i,directoryCache:a}})}},hydrateNestedGitScanRoots:async()=>{if(!qe.getState().nestedGitScanRootsHydrated)return ho||(ho=(async()=>{const n=(await bn()).nestedGitScanRoots??{};dr(xl),e({nestedGitScanRoots:n,nestedGitScanRootsHydrated:!0})})().finally(()=>{ho=null}),ho)},setNestedGitScanRoot:async(t,n)=>{try{await qe.getState().hydrateNestedGitScanRoots()}catch{}const r=!!qe.getState().nestedGitScanRoots[t],o=(Ts.get(t)??0)+1;Ts.set(t,o),e(s=>{const i={...s.nestedGitScanRoots};return n?i[t]=!0:delete i[t],{nestedGitScanRoots:i,nestedGitScanRootsHydrated:!0}});try{const s=await yt({nestedGitScanRoot:{rootPath:t,enabled:n}});if(Ts.get(t)!==o)return;e({nestedGitScanRoots:s.nestedGitScanRoots??{}}),dr(xl)}catch{if(Ts.get(t)!==o)return;e(s=>{const i={...s.nestedGitScanRoots};return r?i[t]=!0:delete i[t],{nestedGitScanRoots:i}})}},hydrateActiveGitRepos:async()=>{if(!qe.getState().activeGitReposHydrated)return po||(po=(async()=>{const n=(await bn()).activeGitRepos??{},r={...n};for(const s of uc){const i=qe.getState().activeGitRepos[s];i?r[s]=i:delete r[s]}const o=Object.entries(r).filter(([s])=>n[s]===void 0);for(const[s]of o)uc.add(s);o.length>0&&await Promise.all(o.map(([s,i])=>yt({activeGitRepo:{contextKey:s,repoRoot:i}}).catch(()=>{}))),Eh(r),dr(AT),e({activeGitRepos:r,activeGitReposHydrated:!0})})().finally(()=>{po=null}),po)},setActiveGitRepo:t=>{const{contextKey:n,activeGitRepos:r}=qe.getState();if(!n||(r[n]??null)===t)return;uc.add(n);const o={...r};t?o[n]=t:delete o[n],e({activeGitRepos:o}),Eh(o),yt({activeGitRepo:{contextKey:n,repoRoot:t??null}}).catch(()=>{})},invalidateDirectoryCache:(t,n=!1)=>e(r=>{const o=new Map(r.directoryCache);for(const s of o.keys())(s===t||n&&kn(t,s))&&o.delete(s);return{directoryCache:o}}),applyFileWatchEvents:t=>e(n=>{if(t.length===0)return n;const r=new Map(n.directoryCache),o=new Map(n.fileChangeVersions);let s=n.selectedFilePath,i=!1,a=!1,c=!1;const l=d=>{o.set(d,(o.get(d)??0)+1),a=!0};for(const d of t){if(d.type==="rescan-required"){c=!0,s&&kn(d.path,s)&&l(s);continue}const u=QT(d.path),f=r.get(u);if(d.type==="deleted"){if(l(d.path),s&&kn(d.path,s)&&(s=null,lo(n.rootPath,null)),f){const y=f.filter(x=>x.path!==d.path);y.length!==f.length&&(r.set(u,y),i=!0)}for(const y of r.keys())kn(d.path,y)&&(r.delete(y),i=!0);continue}l(d.path);const p=eP(d);if(!p||!f)continue;const g=f.find(y=>y.path===p.path),m=n.explorerRoot??n.rootPath;if(!g&&m&&n.hideGitIgnoredRoots[m]&&kn(m,u))continue;const b=xh(g?f.map(y=>y.path===p.path?{...y,...p,children:y.children}:y):[...f,p],n.fileSortModes[u]??"name");r.set(u,b),i=!0}return!i&&!a&&!c?n:{directoryCache:i?r:n.directoryCache,selectedFilePath:s,fileChangeVersions:a?o:n.fileChangeVersions,fileWatchEpoch:c?n.fileWatchEpoch+1:n.fileWatchEpoch}}),bumpFileWatchEpoch:()=>e(t=>({fileWatchEpoch:t.fileWatchEpoch+1})),setChangedFiles:t=>e({changedFiles:t}),beginGitBundleLoading:t=>e({gitBundleLoading:!0,gitBundleSlow:!1,gitBundleLoadingOwner:t}),setGitBundleSlowFor:(t,n)=>e(r=>r.gitBundleLoadingOwner===t?{gitBundleSlow:n}:r),finishGitBundleLoading:t=>e(n=>n.gitBundleLoadingOwner===t?{gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}:n),resetGitBundleLoading:()=>e({gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}),setGitBundleError:t=>e({gitBundleError:t}),markGitBundleLoaded:(t=null)=>e({gitBundleLastLoadedAt:Date.now(),gitBundleCacheInfo:t})})),zs=new Map;let hc=0,mo;function Ws(){const e=++hc;requestAnimationFrame(()=>{if(e!==hc)return;const t=document.getElementById("termdock-startup");if(!t)return;const n=[...zs].find(([r])=>r.isConnected&&!r.closest('[aria-hidden="true"], [hidden]')&&getComputedStyle(r).visibility!=="hidden");if(n){t.hidden=!1;const r=t.querySelector("[data-startup-status]"),o=n[1];r&&r.textContent!==o.status&&(r.textContent=o.status);const s=t.querySelector("[data-startup-detail]");s&&(s.hidden=!o.detail,s.textContent=o.detail??"");const i=t.querySelector("[data-startup-action]");i&&(i.hidden=!o.actionLabel||!o.onAction,i.textContent=o.actionLabel??"",i.onclick=o.onAction??null);return}requestAnimationFrame(()=>{if(e!==hc)return;t.hidden=!0;const r=t.querySelector("[data-startup-action]");r&&(r.onclick=null)})})}function tP(){return P.useLayoutEffect(()=>{Ws()},[]),null}function Od({status:e="Loading Termdock",detail:t,actionLabel:n,onAction:r}){const o=P.useRef(null);return P.useLayoutEffect(()=>{const s=o.current;if(zs.set(s,{status:e,detail:t,actionLabel:n,onAction:r}),!mo){mo=new MutationObserver(Ws);const i=document.getElementById("root");i&&mo.observe(i,{attributes:!0,subtree:!0,attributeFilter:["style","aria-hidden","hidden"]})}return Ws(),()=>{zs.delete(s),zs.size||(mo?.disconnect(),mo=void 0),Ws()}},[e,t,n,r]),h.jsx("span",{ref:o,"data-startup-pending":"",style:{position:"absolute",width:0,height:0,pointerEvents:"none"}})}function nP({failure:e,target:t,onSettings:n,onRecovered:r,settingsOpen:o=!1}){const[s,i]=P.useState("notice"),[a,c]=P.useState([]),[l,d]=P.useState(""),[u,f]=P.useState(!1),p=P.useRef(null),g=P.useRef(s);g.current=s,P.useLayoutEffect(()=>{p.current?.toggleAttribute("inert",o)},[o]),P.useEffect(()=>()=>{g.current="cancelled"},[]),Pm(p,!o,()=>{u||i(s==="notice"?"cancelled":"notice")}),P.useEffect(()=>{let A=!1;return Ve().then(T=>{A||c(T)}).catch(()=>{}),()=>{A=!0}},[]);const m=t?.serviceName||a.find(A=>A.targetPeerId===e.context.targetServiceId)?.label||"目标服务",y=a.find(A=>A.targetPeerId===e.context.entryServiceId)?.label||"已保存的入口",x=e.code==="RELAY_AUTHORIZATION_REQUIRED",w=e.code==="TARGET_AUTHORIZATION_REQUIRED",I=x?`通过“${y}”连接“${m}”需要中转授权`:w?`“${m}”需要重新登录`:e.code==="TARGET_IDENTITY_MISMATCH"?`“${m}”的服务身份不一致`:e.code==="RELAY_SELF_TARGET"?`“${m}”的中转配置指向自身`:`当前权限无法访问“${m}”`,R=async()=>{if(g.current!=="route"&&g.current!=="login")throw new Error("RECOVERY_CANCELLED");await r()},S=async()=>{if(g.current==="login"){d("");try{await R()}catch{d("授权尚未核验通过,请检查连接设置或联系对应服务管理员。")}}};return h.jsx("div",{ref:p,style:o?{visibility:"hidden"}:void 0,"aria-hidden":o?!0:void 0,className:`fixed inset-0 z-modal-panel flex items-center justify-center overflow-auto bg-[var(--chrome-bg)] ${s==="login"?"":"px-6 py-[max(24px,env(safe-area-inset-top))]"}`,children:s==="login"?h.jsxs("div",{className:"h-full w-full",children:[h.jsx(hw,{serviceOrigin:t?.serviceOrigin||t?.url,focusEnabled:!o,onLoginSuccess:()=>{S()},onManageServices:n}),h.jsx("button",{className:"absolute bottom-[max(24px,env(safe-area-inset-bottom))] left-1/2 min-h-11 -translate-x-1/2 px-4 text-sm text-muted-foreground",onClick:()=>i("notice"),children:"取消"}),l&&h.jsx("p",{role:"alert",className:"absolute bottom-20 left-0 right-0 px-6 text-center text-sm text-destructive",children:l})]}):h.jsxs("section",{className:"w-full max-w-sm","aria-label":"恢复服务访问",children:[h.jsx("h1",{className:"text-base font-medium",role:"alert",children:I}),h.jsx("p",{className:"mt-3 text-sm leading-6 text-muted-foreground",children:s==="cancelled"?"连接已暂停。保存的服务、终端和草稿保持不变。":x?"当前没有有效中转授权,已暂停无效重试。不会自动重新授权。":w?"目标服务没有返回有效访问授权。登录目标服务后会重新核对。":"连接已暂停。请核对保存的身份或联系管理员确认具体权限;不会替换身份或扩大授权。"}),s==="route"&&t&&e.context.entryServiceId&&e.context.entryUrl?h.jsx("div",{className:"mt-5",children:h.jsx(Lm,{service:{...t,id:t.targetPeerId,label:m},onBusyChange:f,recoverEntry:{targetPeerId:e.context.entryServiceId,url:e.context.entryUrl},onRecovered:R,onCancelRecovery:()=>i("notice")})}):h.jsxs("div",{className:"mt-5 flex flex-col gap-2",children:[s!=="cancelled"&&x&&e.context.entryServiceId&&e.context.entryUrl&&h.jsx("button",{className:"service-button service-primary",onClick:()=>i("route"),children:"重新授权"}),s!=="cancelled"&&w&&h.jsx("button",{className:"service-button service-primary",onClick:()=>i("login"),children:"登录目标服务"}),h.jsx("button",{className:"service-button service-secondary",onClick:n,children:"查看连接设置"}),s==="cancelled"&&h.jsx("button",{className:"service-button service-secondary",onClick:()=>i("notice"),children:"返回恢复选项"}),s!=="cancelled"&&h.jsx("button",{className:"service-button service-secondary",onClick:()=>i("cancelled"),children:"取消"})]})]})})}const pc=(()=>{if(location.hash.startsWith("#termdock-invite="))try{return Un(location.href)}catch{return}finally{history.replaceState(null,"",location.pathname+location.search)}})(),Cl="termdock-secure-open-session";let gc;function rP(){try{const e=JSON.parse(sessionStorage.getItem(Cl)??"null");return e?.serviceId===te()?.targetPeerId?e.sessionId:void 0}catch{return}}function oP({children:e}){const{t}=Gr(),n=P.useRef(),r=P.useRef(0);P.useEffect(()=>{const V=()=>{r.current++};return window.addEventListener("pagehide",V),()=>{V(),window.removeEventListener("pagehide",V)}},[]);const[o,s]=P.useState(),[i,a]=P.useState(pc),[c,l]=P.useState(!1),[d,u]=P.useState(!!pc),[f,p]=P.useState(!pc),[g,m]=P.useState(!1),[b,y]=P.useState(),x=P.useRef(),[w,I]=P.useState("正在连接服务…"),[R,S]=P.useState([]),[A,T]=P.useState([]),[v,E]=P.useState([]),[C,B]=P.useState(!1),[k,N]=P.useState(!1),[L,D]=P.useState(""),[F,O]=P.useState(!1),[_,H]=P.useState(""),[q,j]=P.useState(te()?.serviceName??location.hostname),K=te(),G=K?.serviceOrigin||K?.url||o?.serviceOrigin||o?.url||location.origin,W=!K||K.targetPeerId===o?.targetPeerId&&(K.serviceOrigin||K.url)===(o?.serviceOrigin||o?.url),Y=K?.serviceName||(W?o?.label:void 0)||q,[M,$]=P.useState(rP),[X,Q]=P.useState(!1);P.useEffect(()=>{if(!f||g)return;const V=window.setTimeout(()=>Q(!0),8e3);return()=>window.clearTimeout(V)},[f,g]),P.useEffect(()=>{(!c&&!f||c&&(!C||M))&&hr({rendered:!0})},[c,f,C,M]),P.useEffect(()=>{Ct().then(V=>D(V.peerId)).catch(()=>m(!0))},[]),P.useEffect(()=>{let V=!1,ee=0;const ne=ue=>{const{origin:we,sessionId:pe}=ue.detail,ie=++ee;(async()=>{const be=(await Ve()).filter(De=>!!De.targetPeerId);let fe=be.find(De=>Jn(De).some(Ie=>new URL(Ie).origin===new URL(we).origin));if(!fe){const De=await(await St()).fetch("/api/terminal/operations/collaboration-directory",{signal:AbortSignal.timeout(5e3)});if(!De.ok)throw new Error("暂时无法读取协作服务目录,请重试。");const et=(await De.json()).services?.find($e=>$e.origin===we&&$e.serviceId);fe=be.find($e=>$e.targetPeerId===et?.serviceId)}if(V||ie!==ee)return;if(!fe){u(!0);return}const xe=window.termdockDesktop;if(xe?.collaborationFocus){const De=`remote:${encodeURIComponent(we)}:${encodeURIComponent(pe)}`;if(await xe.collaborationFocus(De,fe.targetPeerId))return;if(xe.openServiceConnection){const Ie=await xe.openServiceConnection(fe);if(V||ie!==ee||Ie?.ok&&await xe.collaborationFocus(De,fe.targetPeerId))return;throw new Error("目标服务窗口尚未就绪,请重试切换会话。")}}if($t()?.focusSession(fe.targetPeerId,pe))return;const ke={...fe,serviceName:fe.label};sessionStorage.setItem(Cl,JSON.stringify({serviceId:ke.targetPeerId,sessionId:pe})),await Pt(ke),!V&&ie===ee&&($(pe),l(!0))})().catch(be=>{V||ie!==ee||(H(be instanceof Error?be.message:"暂时无法打开远程会话"),u(!0))})};return window.addEventListener("termdock:open-remote-session",ne),()=>{V=!0,window.removeEventListener("termdock:open-remote-session",ne)}},[]);const oe=async(V=5e3)=>{const ee=r.current,ne=te(),ue=Ie=>Ie?JSON.stringify([Ie.targetPeerId,Ie.serviceOrigin||Ie.url]):"",we=ue(ne),pe=await St(),ie=await zr(pe,{timeoutMs:V});if(ee!==r.current||we!==ue(te())||pe!==At())throw new Error("SERVICE_SELECTION_CHANGED");const be=window.termdockDesktop?.acknowledgeServiceInvitation,fe=n.current;if(be&&fe){const Ie=await fe,et=()=>ee===r.current&&fe===n.current&&pe===At()&&!pe.closed&&ne===te()&&ne?.targetPeerId===pe.targetPeerId&&Ie?.targetPeerId===pe.targetPeerId;if(Ie?.invitation&&et())try{const $e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Ie.invitation)),dt=Array.from(new Uint8Array($e),_e=>_e.toString(16).padStart(2,"0")).join("");et()&&await be({targetPeerId:pe.targetPeerId,fingerprint:dt},et)&&et()&&(n.current=Promise.resolve({...Ie,invitation:void 0}),a(void 0))}catch{}}const xe=gI(),ke=sI()?.targetPeerId;Promise.all([SA(),Ve()]).then(([Ie,et])=>{const $e=et.find(_e=>_e.targetPeerId===ke),dt=xe==="relay"?`经 ${$e?.label||ke?.slice(-12)||"入口服务"} 中转`:"直连";return pe.request({type:"device-name",name:km(),onlyIfMissing:!0,profile:{...Ie,route:dt}})}).catch(()=>{}),B(ie.fullService),N(ie.canManage),l(!0),p(!1),m(!1),Po("ready");const De=te();hr({phase:"ready",...De?{service:{...De,id:De.targetPeerId,label:De.serviceName||location.host}}:{}}),_s()&&pI()};P.useEffect(()=>{let V=!1,ee=!1,ne=0,ue=!1,we;const pe=async()=>{if(V||ee||ue||ne&&(document.hidden||!_s()))return;if(!navigator.onLine){Po("offline"),p(!0),m(!0),I("网络已断开,恢复后会自动连接"),hr({phase:"offline"});return}ee=!0,clearTimeout(we);const Ie=performance.now(),et=At();try{if(Ni&&!te())throw new Error("工作区的服务记录已移除,请重新添加服务。");const $e=()=>{const Ot=te();return Ot?JSON.stringify([Ot.targetPeerId,Ot.url,Ot.serviceOrigin]):void 0},dt=$e();n.current??=window.termdockDesktop?.getServiceConnection?.();const _e=await n.current;if(V)return;if(_e&&dt===$e()&&(!te()||te()?.targetPeerId===_e.targetPeerId))try{const Ot=Ne(_e.serviceOrigin||_e.url);s({url:Ot,serviceOrigin:Ot,label:_e.label,targetPeerId:_e.targetPeerId})}catch{}if(_e?.invitation){a(Un(_e.invitation)),u(!0),p(!1);return}if(!te()){if(i){p(!1);return}if(gc??=(async()=>{if(_e?.targetPeerId){await Pt({..._e,targetPeerId:_e.targetPeerId,serviceName:_e.label});return}await cI()})(),await gc,!te()){V||(l(!1),p(!1),m(!1));return}}V||await oe(et?.canSwitchTransport?2500:5e3),ne=0,performance.measure("termdock:connection-ready",{start:Ie,end:performance.now()})}catch($e){if(V)return;const dt=yi($e,{targetServiceId:te()?.targetPeerId});if(dt?.context.targetServiceId&&dt.context.targetServiceId!==te()?.targetPeerId)return;dt?(ue=!0,clearTimeout(we),ol(dt),y(dt),p(!1),u(!1),m(!1),hr({phase:"login",rendered:!0})):(et&&At()===et&&wd(),m(!0),p(!0),gc=void 0,I("连接暂未恢复,正在重试…"),Po(navigator.onLine?"reconnecting":"offline"),hr({phase:"reconnecting"}),ne++,we=setTimeout(()=>{pe()},Math.min(5e3,300*2**Math.min(ne-1,5))),console.debug("[connection] retry",{elapsedMs:Math.round(performance.now()-Ie),attempt:ne,reason:$e instanceof Error?$e.message:"unknown"}))}finally{ee=!1}};x.current=()=>{ue=!1,ne=0};const ie=()=>{document.visibilityState==="visible"&&_s()&&pe()},be=ie,fe=()=>{ne=0,ie()},xe=()=>{qe.getState().openLeft(),ie()};window.addEventListener($o,ie),window.addEventListener(el,xe),$t()?.attach(Vi(),window),pe(),document.addEventListener("visibilitychange",be),window.addEventListener("focus",ie),window.addEventListener("online",fe),window.addEventListener("offline",ie),window.addEventListener("pageshow",ie);const ke=navigator.connection;ke?.addEventListener("change",fe),window.addEventListener("auth:unauthorized",ie),window.addEventListener(Et,ie);const De=setInterval(ie,3e4);return()=>{V=!0,clearTimeout(we),clearInterval(De),x.current=void 0,window.removeEventListener($o,ie),window.removeEventListener(el,xe),document.removeEventListener("visibilitychange",be),window.removeEventListener("focus",ie),window.removeEventListener("online",fe),window.removeEventListener("offline",ie),window.removeEventListener("pageshow",ie),ke?.removeEventListener("change",fe),window.removeEventListener("auth:unauthorized",ie),window.removeEventListener(Et,ie)}},[]);const de=async()=>{const V=At();if(V){O(!0),H("");try{const ee=await V.request({type:"session-list"});E(ee.items)}catch{H("暂时无法读取终端列表,请重试。")}try{if(k){const ee=await V.request({type:"grants-list"});T(ee.invitations??[]);const ne=ee.subjectLabels??{},ue=await V.request({type:"route-access"}),we=await Ve(),pe=(Array.isArray(ue.grants)?ue.grants:[]).map(ie=>({id:`route:${ie.id}`,subjectId:ie.subjectId,scope:{kind:"service"},actions:["route.use"],routeTargetServiceId:ie.targetServiceId,routeTargetName:we.find(be=>be.targetPeerId===ie.targetServiceId)?.label||"指定服务",...ie.active?{}:{revokedAt:ie.revokedAt??0}}));S([...ee.grants,...pe].map(ie=>({...ie,label:ne[ie.subjectId],deviceProfile:ee.deviceProfiles?.[ie.subjectId]})))}else{T([]);const ee=await V.request({type:"permissions"});S(ee.grants??[])}}catch{H("暂时无法读取设备权限,请重试。")}finally{O(!1)}}};P.useEffect(()=>{const V=()=>{u(!0),c&&de()};return window.addEventListener(vl,V),()=>window.removeEventListener(vl,V)},[c,k]);const[z,J]=P.useState([]);P.useEffect(()=>{if(!d||!k||z.length)return;let V=!1;return(async()=>{const ue=await(await(await St()).fetch("/api/terminal/settings")).json();if(V)return;const we=ue.localAccess??{},pe=[],ie=(be,fe)=>{try{const xe=new URL(be);if(xe.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(xe.hostname))return;const ke=xe.origin;if(ke===location.origin||pe.some(De=>De.url===ke))return;pe.push({url:ke,label:fe})}catch{}};if(we.status==="active"&&typeof we.url=="string"&&ie(we.url,"服务域名"),Array.isArray(we.interfaces))for(const be of we.interfaces){const fe=be;typeof fe.url=="string"&&ie(fe.url,typeof fe.label=="string"&&fe.label||typeof fe.name=="string"&&fe.name||"IP 地址")}J(pe)})().catch(()=>{}),()=>{V=!0}},[d,k,z.length]);const se=async V=>{if(!V.pairingCode&&!V.routeCode&&te()?.targetPeerId!==V.targetPeerId&&$t()){const ee={...V,id:V.targetPeerId,label:V.serviceName||new URL(V.serviceOrigin||V.url).host};if(await on(ee),bi(ee)){u(!1);return}}await Pt(V),$(void 0),sessionStorage.removeItem(Cl),j(V.serviceName??new URL(V.url).hostname),await oe(),y(void 0),x.current?.(),n.current&&(n.current=n.current.then(ee=>ee?{...ee,invitation:void 0}:null)),a(void 0),u(!1),m(!1)},Se=async V=>{const ee=window.termdockDesktop;if(ee?.openServiceConnection){const ne=await ee.openServiceConnection(V);if(!ne.ok)throw new Error(ne.error||"暂时无法打开这台服务。");u(!1);return}if(bi(V)){u(!1);return}if(V.targetPeerId)try{await se({...V,targetPeerId:V.targetPeerId,serviceName:V.label});return}catch(ne){if(!(ne instanceof gt))throw ne}return Ef(V.serviceOrigin||V.url)};P.useEffect(()=>{const V=ee=>{Se(ee.detail).catch(ne=>{u(!0),H(ne instanceof Error?ne.message:"暂时无法打开服务")})};return window.addEventListener(Sl,V),()=>window.removeEventListener(Sl,V)});const Re=async(V,ee)=>{if(V.includes("#termdock-invite=")){const ue=Un(V);if(window.termdockDesktop?.openServiceConnection){const we=await window.termdockDesktop.openServiceConnection({id:ue.targetPeerId,url:ue.url,label:ue.serviceName||new URL(ue.serviceOrigin||ue.url).host,targetPeerId:ue.targetPeerId,serviceOrigin:ue.serviceOrigin,entryServiceId:ue.entryServiceId},V);if(!we.ok)throw new Error(we.error||"暂时无法打开邀请。");u(!1);return}if(ee!==void 0&&ue.routeOnly){await If(ue,ee),await oe(),u(!1);return}try{await se(ue)}catch(we){if(ue.routeOnly&&we instanceof gt)return{passwordRequired:!0};throw we}return}const ne=Ne(V);return window.termdockDesktop?.openServiceConnection?Se({id:ne,url:ne,label:new URL(ne).host}):Ef(ne,ee)},me=async V=>{const ee=await St(),{includeBackup:ne=!0,entryAddress:ue,...we}=V,pe=te(),ie=pe?Bt(pe):[];let be;if(ne&&ie.length){for(const ke of ie)try{const De=await gm({...pe,targetPeerId:ee.targetPeerId},ke);be={...ke,routeCode:De.routeCode};break}catch{}if(!be)throw new Error("无法分享备用连接:需要入口管理员授权。也可以关闭此选项,生成直接连接邀请。")}let fe=pe?.serviceOrigin||location.origin;if(ue)try{fe=new URL(ue).origin}catch{throw new Error("邀请接入地址无效。")}const xe=await ee.request({type:"invite-create",...we});if(typeof xe.code!="string"||typeof xe.expiresAt!="number")throw new Error("暂时无法生成邀请。");return await de(),{id:typeof xe.invitationId=="string"?xe.invitationId:void 0,url:Nm({v:1,serviceId:ee.targetPeerId,code:xe.code,entryUrl:be?.url||fe,serviceUrl:fe,name:q,entryServiceId:be?.targetPeerId,routeCode:be?.routeCode}),expiresAt:xe.expiresAt}},Ee=async(V=te()?.targetPeerId)=>{if(V!==te()?.targetPeerId)throw new Error("SERVICE_SELECTION_CHANGED");oI();try{await oe(),x.current?.(),y(void 0)}catch(ee){const ne=yi(ee,{targetServiceId:te()?.targetPeerId});throw ne&&(ol(ne),y(ne)),ee}};return h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"h-full min-h-0",style:b?{visibility:"hidden"}:void 0,ref:V=>V?.toggleAttribute("inert",!!b),"aria-hidden":b?!0:void 0,children:c?C&&!M?e:h.jsx(hT,{client:At(),initialSessionId:M}):b?null:f&&!g&&!d?h.jsx(Od,{status:X?"连接时间较长,仍在等待服务…":w,detail:X?Y:void 0,actionLabel:X?"管理服务":void 0,onAction:()=>u(!0)}):f?h.jsx("div",{className:"flex h-full min-h-0 flex-col items-center justify-center bg-[var(--chrome-bg)] px-6 text-foreground",children:h.jsxs("div",{className:"flex w-full max-w-xs flex-col items-center text-center",children:[h.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:h.jsx(QI,{size:24,strokeWidth:1.5})}),h.jsx("h1",{className:"max-w-full truncate text-base font-medium tracking-tight",title:Y,children:Y}),h.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:[!g&&h.jsx(lt,{size:13,className:"shrink-0 animate-spin motion-reduce:animate-none","aria-hidden":"true"}),h.jsx("span",{children:w})]}),g&&h.jsx("p",{className:"mt-2 text-xs leading-5 text-muted-foreground",children:t(te()?"login.savedConnectionRetained":"login.continueAfterReconnect")}),h.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:()=>u(!0),children:"管理服务"})]})}):h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"fixed left-0 right-0 top-[var(--safe-top-inset)] z-chrome sm:right-auto sm:w-72",children:h.jsx(bT,{})}),h.jsx(hw,{serviceOrigin:G,onManageServices:()=>u(!0),focusEnabled:!d,onLoginSuccess:()=>{oe().catch(()=>m(!0))}})]})}),b&&h.jsx(nP,{failure:b,target:te(),settingsOpen:d,onRecovered:()=>Ee(b.context.targetServiceId),onSettings:()=>u(!0)},JSON.stringify([b.code,b.context])),d&&h.jsx(lT,{onConnect:se,onClose:()=>u(!1),onAddService:Re,onOpenService:Se,onConnectWithPassword:async(V,ee)=>{await If(V,ee),b?await Ee():await oe(),u(!1)},paired:c||!!te(),initialInvite:i,initialServicePage:b&&te()?{kind:b.code==="RELAY_AUTHORIZATION_REQUIRED"?"routes":"edit",service:{...te(),id:te().targetPeerId,label:Y}}:void 0,currentServiceName:Y,currentServiceId:At()?.targetPeerId||te()?.targetPeerId,currentServiceOrigin:G,currentIdentity:L,grants:R,sessions:v,loading:F,loadError:_,onRetry:()=>{de()},onRename:async(V,ee)=>{await(await St()).request({type:"device-name",subjectId:V,name:ee}),await de()},hasBackup:!!te()&&Bt(te()).length>0,inviteAddresses:z,onCreateInvite:k?me:void 0,invitations:k?A:[],onRevokeInvitation:k?async V=>{try{if((await(await St()).request({type:"invite-revoke",invitationId:V})).revoked!==!0)throw new Error("INVITATION_NOT_PENDING")}finally{await de()}}:void 0,onRevoke:k?async V=>{await(await St()).request(V.startsWith("route:")?{type:"route-revoke",grantId:V.slice(6)}:{type:"revoke",grantId:V}),await de()}:void 0})]})}function sP(e,t,n){const r=e?.name||"Error",o=e?.message||"Unexpected error";return["Termdock error report",`Time: ${n.capturedAt}`,`URL: ${n.url}`,`User agent: ${n.userAgent}`,"",`${r}: ${o}`,e?.stack?`
30
- Stack:
31
- ${e.stack}`:"",t?`
32
- React component stack:
33
- ${t.trim()}`:""].filter(Boolean).join(`
34
- `)}async function iP(e){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch{}const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();try{return document.execCommand("copy")}catch{return!1}finally{t.remove()}}function aP({error:e,componentStack:t}){const{t:n}=Gr(),[r,o]=vt.useState("idle"),s=async()=>{const i=sP(e,t,{url:window.location.href,userAgent:navigator.userAgent,capturedAt:new Date().toISOString()});o(await iP(i)?"copied":"failed")};return h.jsx("div",{className:"flex h-full items-center justify-center p-4",children:h.jsxs("div",{className:"flex flex-col items-center gap-3 text-center max-w-md",children:[h.jsx("div",{className:"w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center",children:h.jsx("svg",{className:"w-6 h-6 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:h.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"})})}),h.jsxs("div",{className:"space-y-1",children:[h.jsx("h3",{className:"font-medium text-foreground",children:n("errorBoundary.title")}),h.jsx("p",{className:"text-sm text-muted-foreground",children:e?.message||n("errorBoundary.unexpected")})]}),h.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-center gap-2",children:[h.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:n(r==="copied"?"errorBoundary.copied":r==="failed"?"errorBoundary.copyFailed":"errorBoundary.copyDetails")}),h.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:n("errorBoundary.retry")})]})]})})}class cP extends vt.Component{state={hasError:!1,error:null,componentStack:""};static getDerivedStateFromError(t){return{hasError:!0,error:t,componentStack:""}}componentDidCatch(t,n){console.error("Terminal error caught by boundary:",t,n),this.setState({componentStack:n.componentStack??""})}render(){return this.state.hasError?this.props.fallback?this.props.fallback:h.jsx(aP,{error:this.state.error,componentStack:this.state.componentStack}):this.props.children}}function Ae(){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 lP="debug",dP="termdock:debug";function Ih(e){return e?new Set(e.split(",").map(t=>t.trim().toLowerCase()).filter(Boolean)):new Set}function uP(){if(typeof window>"u")return new Set;const e=Ih(new URLSearchParams(window.location.search).get(lP));let t=new Set;try{t=Ih(window.localStorage.getItem(dP))}catch{t=new Set}const n=new Set([...e,...t]);return n.has("1")||n.has("true")||n.has("*")||n.has("all")?new Set(["*"]):n}function fP(e){const t=uP();return t.has("*")||t.has(e)}function hP(e){const t=fP(e);return(...n)=>{t&&console.log(`[debug:${e}]`,...n)}}function Fd(){return typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}function kw(){if(typeof window>"u")return!1;const e=Ae(),t=e.navigator.maxTouchPoints>0||"ontouchstart"in e;return Fd()||t&&Math.min(e.innerWidth,e.innerHeight)<768}const Ah=80,pP=60,gP="termdock:viewport-keyboard-change",mP="termdock:viewport-layout-change",tn=240,Ch=640,Rh=360,wP=1500;function yP({measuredHeight:e,documentVisible:t,editableFocused:n}){return t&&n&&e>0}function mc(){if(typeof document>"u")return!1;const e=document.activeElement;return e instanceof HTMLElement&&e.matches('input:not([type="hidden"]), textarea, select, [contenteditable]:not([contenteditable="false"])')}const ki=e=>{const t=typeof e=="number"?e:Number.parseFloat(typeof e=="string"?e:"0");return Number.isFinite(t)&&t>0?Math.round(t):0},Tw=(e,t)=>{const n=e.map(ki).filter(r=>r>0);return n.find(r=>r>=tn)??n[0]??t},Do=()=>typeof window>"u"?Ch:Tw([Ae().innerHeight,document.documentElement?.clientHeight,document.body?.clientHeight,Ae().visualViewport?.height,window.screen?.availHeight,window.screen?.height],Ch),Pw=()=>typeof window>"u"?Rh:Tw([Ae().innerWidth,document.documentElement?.clientWidth,document.body?.clientWidth,Ae().visualViewport?.width,window.screen?.availWidth,window.screen?.width],Rh),wn=e=>{const t=Number.parseFloat(e||"0");return Number.isFinite(t)?Math.max(0,Math.round(t)):0},Nw=Fd,Lw=()=>typeof window>"u"?!1:Ae().navigator.standalone===!0||Ae().matchMedia?.("(display-mode: standalone)").matches===!0,Bw=()=>{if(typeof window>"u"||!Nw()||!Lw())return{top:0,right:0,bottom:0,left:0};const e=Do()>=Pw(),t=window.screen?.width||window.innerWidth,n=window.screen?.height||window.innerHeight,r=Math.min(t,n),o=Math.max(t,n);return r>=700?{top:Ae().document.documentElement.dataset.termdockPwaStatusBar==="default"?0:20,right:0,bottom:20,left:0}:e?o<780?{top:20,right:0,bottom:0,left:0}:{top:o>=852?59:o>=844?47:44,right:0,bottom:34,left:0}:{top:0,right:0,bottom:0,left:0}};function bP(e="--app-vh"){if(typeof window>"u"||typeof document>"u")return;document.documentElement.dataset.termdockTouchViewport=String(kw()||Ae().innerWidth<=768),document.documentElement.dataset.termdockIpadPwa=String(document.documentElement.dataset.termdockPwaStatusBar==="default"&&Lw());const t=ki(Ae().visualViewport?.height),n=Math.max(0,Math.round(Ae().visualViewport?.offsetTop??0)),r=Do(),s=t>=tn?Math.min(r,t+n):r,i=Math.max(r,s),a=document.documentElement.style;a.setProperty(e,`${Math.max(s,tn)}px`),a.setProperty("--app-base-vh",`${Math.max(i,tn)}px`),a.setProperty("--app-visible-vh",`${Math.max(s,tn)}px`),a.setProperty("--app-vv-offset-top",`${n}px`),a.setProperty("--kb-translate-y","0px"),a.setProperty("--kb-margin-top","0px"),a.setProperty("--kb-height","0px");const c=Bw();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 rN(e={}){const{cssVarName:t="--app-vh"}=e,n=vt.useMemo(()=>hP("viewport"),[]),r=vt.useCallback(()=>{if(typeof window>"u")return 0;const d=Ae().visualViewport,u=Do();if(!d)return u;const f=ki(d.height);if(f<tn&&u>=tn)return u;const p=d.offsetTop,m=f<u-1&&p>0&&p<=96?f+p:f,b=Math.max(0,Math.min(u,m));return b>0?Math.round(b):u},[]),[o,s]=vt.useState(r),i=vt.useRef(0),a=vt.useRef(0),c=vt.useRef(0),l=vt.useRef(!1);return vt.useEffect(()=>{if(typeof window>"u")return;let d=null,u=0,f=null,p="",g=null;const m=()=>{if(g?.isConnected)return g;try{return g=document.createElement("div"),g.setAttribute("aria-hidden","true"),g.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(g),g}catch{}return null},b=()=>{let D={top:0,right:0,bottom:0,left:0};try{const H=m();if(H){const q=getComputedStyle(H);D={top:wn(q.paddingTop),right:wn(q.paddingRight),bottom:wn(q.paddingBottom),left:wn(q.paddingLeft)}}}catch{}const F=Ae();if(F!==window){const H=F.getComputedStyle(F.document.documentElement);D={top:Math.max(D.top,wn(H.getPropertyValue("--safe-top-inset"))),right:Math.max(D.right,wn(H.getPropertyValue("--safe-right-inset"))),bottom:Math.max(D.bottom,wn(H.getPropertyValue("--safe-bottom-inset"))),left:Math.max(D.left,wn(H.getPropertyValue("--safe-left-inset")))}}const O=Bw(),_={top:Math.max(D.top,O.top),right:Math.max(D.right,O.right),bottom:Math.max(D.bottom,O.bottom),left:Math.max(D.left,O.left)};return document.documentElement.style.setProperty("--safe-top-inset",`${_.top}px`),document.documentElement.style.setProperty("--safe-right-inset",`${_.right}px`),document.documentElement.style.setProperty("--safe-bottom-inset",`${_.bottom}px`),document.documentElement.style.setProperty("--safe-left-inset",`${_.left}px`),_},y=(D,F,O,_)=>{const H=Math.max(F,O);if(i.current===0){i.current=H,a.current=D,document.documentElement.style.setProperty("--app-base-vh",`${H}px`);return}const q=Math.abs(D-a.current),j=_<=Ah;(q>pP||j)&&(i.current=H,a.current=D,document.documentElement.style.setProperty("--app-base-vh",`${H}px`))},x=(D="event")=>{d=null,document.documentElement.dataset.termdockTouchViewport=String(kw()||Ae().innerWidth<=768);const F=r(),O=Math.round(Ae().visualViewport?.offsetTop??0),_=ki(Ae().visualViewport?.height),H=_>=tn?_:F,q=Do(),j=Pw(),K=Math.max(0,H+O),G=b(),W=G.bottom,Y=Math.max(0,i.current-K-W);y(j,q,K,Y),s(ee=>ee===F?ee:F);const M=Number.parseInt(document.documentElement.style.getPropertyValue(t)||"0",10);document.documentElement.style.setProperty(t,`${F}px`),document.documentElement.style.setProperty("--app-vv-offset-top",`${O}px`);const $=i.current,X=Math.min(F,H),Q=Math.max(0,Math.min($,K)),oe=Math.max(0,Math.round($-X-W)),de=mc(),z=yP({measuredHeight:oe,documentVisible:document.visibilityState==="visible",editableFocused:de}),J=z?oe:0,se=J>=Ah,Se=-J,Re=J;document.documentElement.style.setProperty("--kb-translate-y",`${Se}px`),document.documentElement.style.setProperty("--kb-margin-top",`${Re}px`),document.documentElement.style.setProperty("--kb-height",`${J}px`),document.documentElement.style.setProperty("--app-visible-vh",`${Q}px`);const me=Math.abs(J-c.current)>1,Ee=se!==l.current;(me||Ee)&&(c.current=J,l.current=se,document.dispatchEvent(new CustomEvent(gP,{detail:{baseHeight:$,visibleHeight:Q,visualViewportHeight:H,offsetTop:O,keyboardHeight:J,isOpen:se,source:D}}))),(M!==F||O>0||me||Ee)&&n("sync",{cssVarName:t,innerHeight:q,baseHeight:$,rawViewportHeight:H,offsetTop:O,visibleHeight:Q,rawHeight:F,appliedHeight:F,keyboardViewportHeight:X,measuredKeyboardHeight:oe,editableFocused:de,applyKeyboardInset:z,keyboardHeight:J,isKeyboardOpen:se,safeAreaInsets:G,source:D}),document.dispatchEvent(new CustomEvent(mP,{detail:{height:F,baseHeight:$,visibleHeight:Q,offsetTop:O,source:D}}))},w=()=>{d===null&&(d=window.requestAnimationFrame(()=>{d=null;const D=Ae(),F=D.visualViewport,O=[D.innerWidth,D.innerHeight,F?.width,F?.height,F?.offsetTop,F?.offsetLeft,document.visibilityState,mc()].join(":"),_=f;f=null,(_||O!==p)&&(p=O,x(_||"viewport.settle")),performance.now()<u&&w()}))},I=(D="event")=>{(D.includes("visibilitychange")||D.includes("pageshow"))&&n("schedule",{source:D}),f=D,Nw()&&document.visibilityState==="visible"&&(u=performance.now()+wP),w()};I("mount");const R=()=>I("resize"),S=()=>I("orientationchange"),A=()=>I("visualViewport.resize"),T=()=>I("visualViewport.scroll"),v=()=>I("focusin"),E=()=>I("focusout"),C=D=>{u=0;const F=document.activeElement;F instanceof HTMLElement&&mc()&&F.blur(),c.current=0,l.current=!1;const O=Math.max(i.current,Do(),tn),_=document.documentElement.style;_.setProperty(t,`${O}px`),_.setProperty("--app-visible-vh",`${O}px`),_.setProperty("--app-vv-offset-top","0px"),_.setProperty("--kb-translate-y","0px"),_.setProperty("--kb-margin-top","0px"),_.setProperty("--kb-height","0px"),s(H=>H===O?H:O),n("keyboard session reset",{source:D,baseHeight:O})};window.addEventListener("resize",R),window.addEventListener("orientationchange",S),Ae().visualViewport?.addEventListener("resize",A),Ae().visualViewport?.addEventListener("scroll",T),document.addEventListener("focusin",v),document.addEventListener("focusout",E);const B=D=>{n("resume",{source:D,innerHeight:Math.round(window.innerHeight),visualViewport:Ae().visualViewport?{width:Math.round(Ae().visualViewport.width),height:Math.round(Ae().visualViewport.height),offsetTop:Math.round(Ae().visualViewport.offsetTop)}:null,hidden:document.hidden}),I(D)},k=()=>{document.hidden?C("visibilitychange:hidden"):B("visibilitychange")},N=()=>B("pageshow"),L=()=>C("pagehide");return document.addEventListener("visibilitychange",k),window.addEventListener("pageshow",N),window.addEventListener("pagehide",L),()=>{window.removeEventListener("resize",R),window.removeEventListener("orientationchange",S),Ae().visualViewport?.removeEventListener("resize",A),Ae().visualViewport?.removeEventListener("scroll",T),document.removeEventListener("focusin",v),document.removeEventListener("focusout",E),document.removeEventListener("visibilitychange",k),window.removeEventListener("pageshow",N),window.removeEventListener("pagehide",L),d!==null&&window.cancelAnimationFrame(d),g?.remove()}},[t,n,r]),o}const vP=1e3,SP=2e4,EP=9e4,xP=5e3,ce={ws:null,listeners:new Set,reconnectAttempt:0,reconnectTimer:null,idleCloseTimer:null,closing:!1};let Ps=0,Br=null;function IP(){return typeof window>"u"?null:`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/control/ws`}function Dw(){ce.idleCloseTimer&&(clearTimeout(ce.idleCloseTimer),ce.idleCloseTimer=null)}function AP(){Dw(),!(ce.ws&&ce.ws.readyState===WebSocket.OPEN)&&(ce.idleCloseTimer=setTimeout(()=>{ce.idleCloseTimer=null,ce.listeners.size===0&&CP()},xP))}function CP(){if(ce.ws){try{ce.ws.close()}catch{}ce.ws=null}Br&&(clearInterval(Br),Br=null)}function kh(){if(ce.reconnectTimer)return;const e=Math.min(vP*Math.pow(2,ce.reconnectAttempt),SP);ce.reconnectAttempt+=1,ce.reconnectTimer=setTimeout(()=>{ce.reconnectTimer=null,_w()},e)}function _w(){const e=IP();if(!e||ce.ws&&ce.ws.readyState===WebSocket.OPEN)return;let t;try{t=pm(e)}catch{kh();return}ce.ws=t,t.onopen=()=>{ce.reconnectAttempt=0,Ps=Date.now(),Br||(Br=setInterval(()=>{if(!(!ce.ws||ce.ws.readyState!==WebSocket.OPEN)&&Ps>0&&Date.now()-Ps>EP)try{ce.ws.close()}catch{}},3e4),Br.unref?.())},t.onmessage=n=>{Ps=Date.now();let r=null;try{r=JSON.parse(n.data)}catch{return}if(!r)return;if(r.type==="session-notice"){if(typeof r.id!="string"||typeof r.sessionId!="string"||typeof r.sessionName!="string"||typeof r.message!="string"||!r.message.trim()||r.message.length>4e3||r.title!==void 0&&(typeof r.title!="string"||r.title.length>120)||typeof r.createdAt!="number")return;const i=r;for(const a of ce.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type==="update-state"){const i=r.state;if(!i||typeof i.status!="string"||typeof i.currentVersion!="string")return;const a={type:"update-state",state:i};for(const c of ce.listeners)try{c(a)}catch(l){console.error("[clientStateSync] listener threw:",l)}return}if(r.type==="server-health"){const i=r.state;if(!i||typeof i.attention!="boolean"||typeof i.supervised!="boolean")return;const a={type:"server-health",state:i};for(const c of ce.listeners)try{c(a)}catch(l){console.error("[clientStateSync] listener threw:",l)}return}if(r.type==="context-draft"){if(typeof r.text!="string")return;const i={type:"context-draft",text:r.text,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const a of ce.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type==="pinned-explorer-roots"){if(!r.pinnedExplorerRoots||typeof r.pinnedExplorerRoots!="object"||Array.isArray(r.pinnedExplorerRoots))return;const i={type:"pinned-explorer-roots",pinnedExplorerRoots:r.pinnedExplorerRoots,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const a of ce.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type==="config-updated"){if(r.key!=="toolbar-presets"&&r.key!=="agent-rules"&&r.key!=="program-detection")return;const i={type:"config-updated",key:r.key,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0};for(const a of ce.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type!=="client-state"||!r.state)return;const o=r.state,s={type:"client-state",clientState:{sessions:Array.isArray(o.sessions)?o.sessions:[],updatedAt:typeof o.updatedAt=="number"?o.updatedAt:Date.now()},inventory:r.inventory,seq:typeof r.seq=="number"?r.seq:void 0};for(const i of ce.listeners)try{i(s)}catch(a){console.error("[clientStateSync] listener threw:",a)}},t.onclose=()=>{ce.ws===t&&(ce.ws=null),ce.listeners.size>0&&kh()},t.onerror=()=>{}}function Ow(e){return ce.listeners.add(e),Dw(),ce.ws||_w(),()=>{ce.listeners.delete(e),ce.listeners.size===0&&AP()}}const wc=Ji(e=>({unread:{},viewing:null,receive:(t,n)=>e(r=>{const o=r.unread[t]??[];return r.viewing===t||o.includes(n)?r:{unread:{...r.unread,[t]:[...o,n]}}}),view:t=>e(n=>{if(!t||!n.unread[t])return n.viewing===t?n:{viewing:t};const r={...n.unread};return delete r[t],{viewing:t,unread:r}})})),Fw=new Set(["bash","zsh","fish","sh","dash","ksh","tcsh","csh","nu"]);function Eo(e){if(!e)return null;if(e==="/")return"/";const t=e.replace(/\/+$/,"").split("/");return t[t.length-1]||e}function RP(e,t,n,r=Fw,o=null,s=null){if(e.customName)return{primary:e.name,secondary:Eo(n)};if(o){const a=Eo(n),c=o===n||o===a;if(s!=="idle"&&!r.has(o)&&!c)return{primary:o,secondary:a}}if(t&&!r.has(t))return{primary:t,secondary:Eo(n)};const i=Eo(n);return i?{primary:i,secondary:null}:{primary:e.name,secondary:null}}function kP(e,t,n,r=Fw,o=null,s=null){return RP(e,t,n,r,o,s).primary}function TP(e,t,n){const r=e.findIndex(o=>n(o)===t);return r<0?null:e[r+1]?n(e[r+1]):r>0?n(e[r-1]):null}const Mw="termdock-session-fonts-v1",Th=8,PP=32;function jw(e){return Number.isFinite(e)?Math.max(Th,Math.min(PP,Math.round(e))):Th}function Md(){if(typeof window>"u")return{};try{const e=window.localStorage.getItem(Mw);if(!e)return{};const t=JSON.parse(e);if(typeof t!="object"||t===null)return{};const n={};for(const[r,o]of Object.entries(t))typeof o=="number"&&Number.isFinite(o)&&(n[r]=jw(o));return n}catch{return{}}}function Uw(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Mw,JSON.stringify(e))}catch{}}function oN(e){return Md()[e]??null}function sN(e,t){if(typeof window>"u")return;const n=Md(),r=t===null?null:jw(t);r===null?delete n[e]:n[e]=r,Uw(n),window.dispatchEvent(new CustomEvent("termfontchange",{detail:{sessionId:e,fontSize:r}}))}function NP(e){if(typeof window>"u")return;const t=Md();e in t&&(delete t[e],Uw(t))}const yc="termdock-sessions",Rl="termdock-active-session",jd="termdock-sessions-cache";function kl(){try{const e=localStorage.getItem(Rl);return e&&e.trim().length>0?e:null}catch{return null}}function fr(e){try{e?localStorage.setItem(Rl,e):localStorage.removeItem(Rl)}catch{}}function Hw(){if(typeof window>"u")return null;try{const e=localStorage.getItem(jd);if(!e)return null;const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&typeof n.sessionId=="string"&&typeof n.name=="string"):null}catch{return null}}function Tn(e){if(!(typeof window>"u"))try{localStorage.setItem(jd,JSON.stringify(e))}catch{}}function Ph(){if(!(typeof window>"u"))try{localStorage.removeItem(jd)}catch{}}const LP=["backendSessionId","mode","tmuxSessionName","lastActivity","connected","live","restorable","activeProgram","cwd","shellTitle","agent"];function $w(e){return e.map(t=>({...t,mode:t.mode==="tmux"?"tmux":"shell",tmuxSessionName:t.tmuxSessionName??null,customName:t.customName===!0}))}function Nh(e){return $w(e.map(t=>({sessionId:t.sessionId,name:t.name,customName:t.customName===!0,backendSessionId:t.backendSessionId,mode:t.mode,tmuxSessionName:t.tmuxSessionName,createdAt:t.createdAt,lastActivity:t.lastActivity}))).map((t,n)=>({...t,activeProgram:e[n]?.activeProgram??null,cwd:e[n]?.cwd??null,shellTitle:e[n]?.shellTitle??null,agent:e[n]?.agent}))}function Lh(e){return e.map(t=>`${t.sessionId}:${t.name}:${t.customName}:${t.backendSessionId}:${t.mode}:${t.tmuxSessionName}:${t.lastActivity}:${t.activeProgram??""}:${t.cwd??""}:${t.shellTitle??""}:${JSON.stringify(t.agent)??""}`).join("|")}function Tl(e,t){return e.length===0?null:t&&e.some(n=>n.sessionId===t)?t:e[0]?.sessionId??null}function BP(){const e=Hw()??[];return{sessions:e,activeSessionId:Tl(e,kl())}}function iN(){const e=P.useRef(Hw()).current,t=P.useRef(kl()).current,[n,r]=P.useState(e??[]),[o,s]=P.useState(null),[i,a]=P.useState(e&&e.length>0?Tl(e,t):t),[c,l]=P.useState(e===null),d=P.useRef(!1),u=P.useRef(i),f=P.useRef(n),p=P.useRef(null),g=P.useRef(0),m=P.useRef(0),b=P.useRef(new Map),y=P.useRef(0),x=P.useRef(e===null),w=P.useRef(0),I=P.useRef(new Set),R=P.useRef(0);P.useEffect(()=>{x.current=c},[c]),P.useEffect(()=>{u.current=i},[i]);const S=P.useCallback(j=>{const K=Tl(j,u.current??kl());return a(G=>G===K?G:K),fr(K),u.current=K,K},[]),A=P.useCallback((j,K)=>{const G=j.filter(W=>!I.current.has(W.sessionId));f.current=G,++g.current,r(W=>Lh(W)===Lh(G)?W:G),Tn(G),K?.reconcileActive&&S(G)},[S]),T=P.useCallback((j,K,G)=>{const W=b.current.get(j.sessionId);if(W&&(K<W.updatedAt||K===W.updatedAt&&G!==void 0&&W.revision>G))return{...j,...W.facts};const Y=Object.fromEntries(LP.filter(X=>X in j).map(X=>[X,j[X]])),$={...W?.facts.backendSessionId===j.backendSessionId?W?.facts:{connected:!1,live:!1,restorable:!1},...Y};return b.current.set(j.sessionId,{updatedAt:K,revision:++m.current,facts:$}),{...j,...$}},[]),v=P.useCallback((j,K)=>{if(!K?.mergedLocally&&p.current&&j.updatedAt<p.current.updatedAt)return;const G=I.current.size===0?j:{...j,clientSessions:j.clientSessions.filter(Y=>!I.current.has(Y.sessionId))},W=K?.mergedLocally?G:{...G,clientSessions:G.clientSessions.map(Y=>T(Y,j.updatedAt,K?.backendBaseRevision))};p.current=W,s(W),A(Nh(W.clientSessions),{...K})},[A,T]),E=P.useCallback(j=>{A(j(f.current))},[A]),C=P.useCallback(()=>typeof window>"u"?[]:localStorage.getItem(yc)?(localStorage.removeItem(yc),Ph(),fr(null),f.current=[],u.current=null,r([]),a(null),console.info("[session-persist] discarded legacy local session cache"),[]):[],[]),B=P.useCallback(async()=>{if(typeof window>"u")return[];const j=R.current,K=m.current;try{const G=await Vm(),W=Nh(G.clientSessions);return j!==R.current?(console.info("[session-inventory] ignored restore snapshot superseded by a local mutation"),W.filter(Y=>!I.current.has(Y.sessionId))):(v(G,{reconcileActive:!0,backendBaseRevision:K}),W.length>0?W:C())}catch(G){console.error("Failed to restore sessions from server:",G);try{return C()}catch(W){console.error("Failed to discard legacy local sessions:",W)}}finally{l(!1)}return[]},[v,C]),k=P.useCallback(async(j,K)=>{const G=++R.current,W=y.current,Y=g.current,M=m.current,$=await Ym(j),X=b.current.get($.session.sessionId),Q=X!==void 0&&(X.updatedAt>$.inventory.updatedAt||X.updatedAt===$.inventory.updatedAt&&X.revision>M);if(G===R.current&&Y===g.current)v($.inventory,{backendBaseRevision:M});else{const se=p.current,Se=new Map(se?.clientSessions.map(me=>[me.sessionId,me])),Re=f.current.map(me=>({frontendSessionId:me.sessionId,connected:!1,live:!1,restorable:!1,...Se.get(me.sessionId),...me}));if(!I.current.has($.session.sessionId)){const me=T($.session,$.inventory.updatedAt,M),Ee=Re.findIndex(V=>V.sessionId===me.sessionId);if(Ee<0)Re.push(me);else{const V=Re[Ee];Re[Ee]={...me,name:V.name,customName:V.customName,createdAt:V.createdAt}}}v({...se??$.inventory,clientSessions:Re},{mergedLocally:!0})}const oe=p.current?.clientSessions.find(se=>se.sessionId===$.session.sessionId)??$.session,de=I.current.has($.session.sessionId)||oe.backendSessionId===null;G===R.current&&W===y.current&&!de&&(K?.shouldActivate?.()??!0)&&(u.current=$.session.sessionId,a($.session.sessionId),fr($.session.sessionId));const J=oe.backendSessionId===$.terminalSession.sessionId&&!Q;return{...$,inventory:p.current??$.inventory,session:oe,terminalSession:{...J?$.terminalSession:{cols:j.cols??80,rows:j.rows??24},sessionId:oe.backendSessionId??$.terminalSession.sessionId,mode:oe.mode,tmuxSessionName:oe.tmuxSessionName,activeProgram:oe.activeProgram!==void 0?oe.activeProgram:J?$.terminalSession.activeProgram:null,cwd:oe.cwd!==void 0?oe.cwd:J?$.terminalSession.cwd:null},discarded:de}},[v,T]),N=P.useCallback(async(j,K)=>{++R.current,I.current.add(j),NP(j),E(G=>{const W=G.filter($=>$.sessionId!==j),Y=K!=null&&W.some($=>$.sessionId===K),M=u.current===j?Y?K:TP(G,j,$=>$.sessionId):u.current;return a(M),u.current=M,fr(M),Tn(W),W});try{await Zm(j)}catch(G){console.error("Failed to remove session from inventory:",G)}},[E]),L=P.useCallback(j=>{const K=Date.now();E(G=>{const W=G.map(Y=>Y.sessionId===j?{...Y,lastActivity:K}:Y);return Tn(W),W})},[E]),D=P.useCallback(j=>{++y.current,u.current=j,a(j),fr(j)},[]),F=P.useCallback(async(j,K)=>{const G=K.trim();if(!G)return;const W=++R.current,Y=m.current;E(M=>{const $=M.map(X=>X.sessionId===j?{...X,name:G,customName:!0}:X);return Tn($),$});try{const M=await Us(j,{name:G,customName:!0});W===R.current&&v(M,{backendBaseRevision:Y})}catch(M){console.error("Failed to rename session in inventory:",M)}},[v,E]),O=P.useCallback(async j=>{const K=++R.current,G=m.current;E(W=>{const Y=W.map(M=>M.sessionId===j?{...M,customName:!1}:M);return Tn(Y),Y});try{const W=await Us(j,{customName:!1});K===R.current&&v(W,{backendBaseRevision:G})}catch(W){console.error("Failed to reset session name in inventory:",W)}},[v,E]),_=P.useCallback(async j=>{const K=++R.current,G=m.current;E(W=>{const Y=new Map(W.map(oe=>[oe.sessionId,oe])),M=j.map(oe=>Y.get(oe)).filter(oe=>oe!==void 0),$=new Set(j),X=W.filter(oe=>!$.has(oe.sessionId)),Q=[...M,...X];return Tn(Q),Q});try{const W=await Xm(j);K===R.current&&v(W,{backendBaseRevision:G})}catch(W){console.error("Failed to reorder sessions in inventory:",W)}},[v,E]),H=P.useCallback(async()=>{++R.current;for(const j of f.current)I.current.add(j.sessionId);A([]),p.current=null,s(null),a(null),u.current=null,fr(null),Ph(),typeof window<"u"&&localStorage.removeItem(yc);try{await Jm()}catch(j){console.error("Failed to clear session inventory:",j)}},[A]),q=P.useCallback(async(j,K)=>{const G=++R.current,W=m.current;E(Y=>{const M=Y.map($=>$.sessionId===j?{...$,backendSessionId:K}:$);return Tn(M),M});try{const Y=await Us(j,{backendSessionId:K});G===R.current&&v(Y,{backendBaseRevision:W})}catch(Y){console.error("Failed to update session backend in inventory:",Y)}},[v,E]);return P.useEffect(()=>{d.current||(d.current=!0,B())},[B]),P.useEffect(()=>Ow(K=>{if(K.type!=="client-state"||x.current)return;const G=typeof K.seq=="number"?K.seq:null;if(G!==null){if(G<w.current){console.warn("[session-inventory] ignored stale control snapshot",{seq:G,latestSeq:w.current});return}w.current=G}if(K.inventory){v(K.inventory,{reconcileActive:!0});return}const W=$w(K.clientState.sessions||[]).map(Y=>T(Y,K.clientState.updatedAt));p.current&&K.clientState.updatedAt<p.current.updatedAt||A(W,{reconcileActive:!0})}),[v,A,T]),{sessions:n,inventory:o,activeSessionId:i,isLoading:c,openSession:k,removeSession:N,updateSessionActivity:L,setActiveSession:D,updateSessionBackendId:q,renameSession:F,resetSessionCustomName:O,reorderSessions:_,clearAllSessions:H,restoreSessions:B}}const DP=256*1024,_P=256*1024,OP=128;function Bh(e,t=DP){if(!e)return[];if(e.length<=t)return[e];const n=[];let r=0;for(;r<e.length;){let o=Math.min(r+t,e.length);if(o<e.length){const s=e.lastIndexOf(`
35
- `,o);s>r&&(o=s+1)}n.push(e.slice(r,o)),r=o}return n}function FP(e,t=_P,n=OP){const r=new Map;let o=0,s=0;for(const i of[...e.keys()]){const a=e.get(i);if(!a||a.length===0){e.delete(i);continue}const c=[];for(;a.length>0;){const l=a[0];if(s>0&&(s>=n||o+l.length>t))break;a.shift(),c.push(l),o+=l.length,s+=1}if(c.length>0&&r.set(i,c),e.delete(i),a.length>0&&e.set(i,a),s>=n||o>=t)break}return r}async function qw(e,t=!1,n="termdock-encrypted-background"){const r=await new Promise((o,s)=>{const i=indexedDB.open(n,1);i.onupgradeneeded=()=>i.result.createObjectStore("state"),i.onsuccess=()=>o(i.result),i.onerror=()=>s(i.error)});try{return await new Promise((o,s)=>{const i=r.transaction("state",t?"readwrite":"readonly"),a=e(i.objectStore("state"));i.oncomplete=()=>o(a.result),i.onabort=i.onerror=()=>s(i.error)})}finally{r.close()}}const MP=e=>qw(t=>t.put(e,e.targetPeerId),!0),jP=e=>qw(t=>t.delete(e),!0),Kw="termdock-pwa-notifications-enabled",zw="termdock-pwa-ai-notifications-enabled",Ww="termdock-pwa-exit-notifications-enabled",Gw="termdock-pwa-notification-alert-style",UP="termdock-notification-claim:",Pl=5e3,HP=1500,Nl="termdock-push-last-sync",Dh=360*60*1e3,$P=10080*60*1e3,_o=new Map;function Ud(){return mt()?!0:typeof window<"u"&&typeof Notification<"u"&&"serviceWorker"in navigator&&window.isSecureContext}function qP(){if(typeof navigator>"u")return!1;const e=navigator.userAgent;return/iPad|iPhone|iPod/.test(e)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}function KP(){return typeof window>"u"?!1:!!(window.matchMedia("(display-mode: standalone)").matches||"standalone"in navigator&&navigator.standalone===!0)}function zP(){return mt()?!0:!(!Ud()||qP()&&!KP())}function aN(){return mt()?"granted":typeof Notification>"u"?"unsupported":Notification.permission}function Hd(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Kw)==="true"}catch{return!1}}function cN(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Kw,String(e))}catch{}}function Ti(){if(typeof window>"u")return!0;try{const e=window.localStorage.getItem(zw);return e===null?!0:e==="true"}catch{return!0}}function lN(e){if(!(typeof window>"u"))try{window.localStorage.setItem(zw,String(e))}catch{}}function Ll(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Ww)==="true"}catch{return!1}}function dN(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Ww,String(e))}catch{}}function Ko(){if(typeof window>"u")return"normal";try{const e=window.localStorage.getItem(Gw);if(e==="quiet"||e==="persistent")return e}catch{}return"normal"}function uN(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Gw,e)}catch{}}async function fN(){return mt()?"granted":Ud()?Notification.permission==="default"?Notification.requestPermission():Notification.permission:"unsupported"}function WP(){return typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus()}function GP(e){for(const[t,n]of _o)e-n>Pl&&_o.delete(t)}function VP(e){return e.dedupKey?.trim()?e.dedupKey.trim():e.tag?.trim()?e.tag.trim():[e.data?.sessionId,e.title,e.body].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim()).join("|")}function YP(e){const t=VP(e);if(!t)return!0;const n=Date.now();GP(n);const r=_o.get(t)??0;if(n-r<Pl)return!1;try{if(typeof window<"u"&&window.localStorage){const o=`${UP}${t}`,s=Number(window.localStorage.getItem(o)??"0");if(Number.isFinite(s)&&n-s<Pl)return _o.set(t,s),!1;Number.isFinite(s)&&s>0&&window.localStorage.removeItem(o),window.localStorage.setItem(o,String(n))}}catch{}return _o.set(t,n),!0}async function ea(){if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;try{const e=await navigator.serviceWorker.getRegistration()??null;return e?.active?e:await Promise.race([navigator.serviceWorker.ready,new Promise(n=>{window.setTimeout(()=>n(null),HP)})])??e}catch{return null}}function XP(e){const t="=".repeat((4-e.length%4)%4),n=(e+t).replace(/-/g,"+").replace(/_/g,"/"),r=window.atob(n),o=new Uint8Array(new ArrayBuffer(r.length));for(let s=0;s<r.length;s+=1)o[s]=r.charCodeAt(s);return o}async function $d(e,t){const n=await fetch("/api/csrf-token");if(!n.ok)throw new Error("Unable to get notification security token");const{csrfToken:r}=await n.json();return fetch(`/api/notifications/${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(t)})}async function ZP(e=!1,t=!1){if(mt())return!0;if(!Hd()||!zP()||Notification.permission!=="granted")return!1;const n=await ea();if(!n?.pushManager)return!1;try{const r=await fetch("/api/notifications/status");if(!r.ok)return!1;const o=await r.json();let s=await n.pushManager.getSubscription();const i=!!(s?.expirationTime&&s.expirationTime-Date.now()<$P);if(!s)try{s=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:XP(o.publicKey)})}catch(d){return console.warn(`[PWA notifications] Push subscription missing; re-subscribe failed${t?" (user gesture)":""}:`,d),!1}const a=Number(window.localStorage.getItem(Nl)??"0"),c=!o.subscription||o.subscription.endpoint!==s.endpoint||Date.now()-(o.subscription.updatedAt??0)>=Dh;if(e||c||Date.now()-a>=Dh||i){if(!(await $d("subscribe",{subscription:s.toJSON(),aiEnabled:Ti(),exitEnabled:Ll(),alertStyle:Ko(),locale:navigator.language})).ok)return!1;window.localStorage.setItem(Nl,String(Date.now()))}const l=te();return l&&await MP({targetPeerId:l.targetPeerId,addresses:Jn(l),routes:Bt(l),publicKey:o.publicKey,preferences:{aiEnabled:Ti(),exitEnabled:Ll(),alertStyle:Ko(),locale:navigator.language}}),!0}catch(r){return console.warn("[PWA notifications] Push subscription sync failed:",r),!1}}async function hN(){if(mt())return;const t=await(await ea())?.pushManager?.getSubscription();try{await $d("unsubscribe",{endpoint:t?.endpoint})}finally{const n=te();n&&await jP(n.targetPeerId),await t?.unsubscribe();try{window.localStorage.removeItem(Nl)}catch{}}}async function pN(){if(mt()||!Hd())return;(await $d("preferences",{aiEnabled:Ti(),exitEnabled:Ll(),alertStyle:Ko(),locale:navigator.language})).status===404&&await ZP(!0)}async function gN(){if(!mt())try{const e=navigator;typeof e.clearAppBadge=="function"&&await e.clearAppBadge()}catch{}}async function mN(e){if(!mt())try{const t=await ea();if(!t||typeof t.getNotifications!="function")return;const n=`agent:${e}`,r=await t.getNotifications({tag:n});for(const s of r)s.close();const o=navigator;if(typeof o.setAppBadge=="function"){const s=await t.getNotifications();await o.setAppBadge(s.length)}}catch{}}async function bc(e){if(!Hd()||!Ud())return!1;if(e.requireHidden!==!1&&WP())return!0;const t=mt();if(t){const s=e.alertStyle??Ko(),i=await t.showNotification({title:e.title,body:e.body,tag:e.tag,sessionId:e.data?.sessionId,silent:s==="quiet",persistent:s==="persistent"});return t.notificationDeliveryConfirmation===!0&&i}if(Notification.permission!=="granted")return!1;const n=await ea();if(e.deferToPush&&await n?.pushManager?.getSubscription())return!0;if(e.requireHidden!==!1){if(await n?.pushManager?.getSubscription())return!0}if(!YP(e))return!0;const r=e.alertStyle??Ko(),o={body:e.body,tag:e.tag,icon:"/pwa-192x192.png",badge:"/maskable-icon-512x512.png",requireInteraction:r==="persistent",renotify:r==="persistent"?!!e.tag:!1,silent:r==="quiet",vibrate:r==="quiet"?[]:[80,40,80],data:{url:e.data?.url??"/",sessionId:e.data?.sessionId}};try{if(n&&typeof n.showNotification=="function")return await n.showNotification(e.title,o),!0;const s=new Notification(e.title,o);return s.onclick=()=>{window.focus(),e.data?.url&&window.location.href!==e.data.url&&window.location.assign(e.data.url),s.close()},!0}catch(s){if(s instanceof DOMException&&s.name==="NotSupportedError"&&o.renotify)try{const i={...o,renotify:!1};return n&&typeof n.showNotification=="function"?await n.showNotification(e.title,i):new Notification(e.title,i),!0}catch(i){return console.warn("[PWA notifications] Failed to show notification (renotify fallback):",i),!1}return console.warn("[PWA notifications] Failed to show notification:",s),!1}}function JP(){try{return localStorage.getItem("termdock:locale")||"en"}catch{return"en"}}function QP(e,t){return e==="zh"?{waitingTitle:`${t} 需要你的处理`,waitingBody:`${t} 需要你的处理。`,doneTitle:`${t} 已完成`,doneBody:`${t} 已完成,点按查看结果。`,exitedTitle:`${t} 已退出`,exitedBody:`${t} 已退出,点按查看结果。`}:{waitingTitle:`${t} needs your input`,waitingBody:`${t} is waiting for your input.`,doneTitle:`${t} finished`,doneBody:"Tap to see the result.",exitedTitle:`${t} exited`,exitedBody:"Tap to see the result."}}const _h=1e6;function Ut(e){return{sessionId:e,directory:"",terminalSessionId:null,mode:"shell",tmuxSessionName:null,activeProgram:null,activeProgramRaw:null,activeProgramSource:null,cwd:null,inCopyMode:!1,isConnecting:!1,agentStatus:null,agentIndicator:null,agentStatusDetail:null,agent:null,agentMessage:null,agentNativeSessionId:null,agentResumeRecovered:!1,agentRich:!1,agentActivity:0,agentCwd:null,agentNeedsReview:!1,shellTitle:null,promptState:null,shellExitCode:null,tuiProgress:null,gitStatus:null,bufferChunks:[],bufferLength:0,lastOutputAt:null,updatedAt:Date.now()}}const ta="termdock-shell-titles-v1";function na(){if(typeof window>"u")return{};try{const e=localStorage.getItem(ta);if(!e)return{};const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{}}catch{return{}}}function e2(e){return na()[e]??null}function t2(e,t){if(!(typeof window>"u"))try{const n=na();t?n[e]=t:delete n[e],localStorage.setItem(ta,JSON.stringify(n))}catch{}}function n2(e){if(!(typeof window>"u"))try{const t=na();delete t[e],localStorage.setItem(ta,JSON.stringify(t))}catch{}}const ra="termdock-agent-cache-v1";function qd(){if(typeof window>"u")return{};try{const e=localStorage.getItem(ra);if(!e)return{};const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{}}catch{return{}}}function Oh(e,t){if(!(typeof window>"u"))try{const n=qd();t?n[e]=t:delete n[e],localStorage.setItem(ra,JSON.stringify(n))}catch{}}function r2(e){if(!(typeof window>"u"))try{const t=qd();delete t[e],localStorage.setItem(ra,JSON.stringify(t))}catch{}}function o2(){if(!(typeof window>"u"))try{localStorage.removeItem(ra)}catch{}}function s2(e){return qd()[e]??null}function i2(){if(!(typeof window>"u"))try{localStorage.removeItem(ta)}catch{}}const vc=Ji((e,t)=>{const n={pendingChunksBySession:new Map,activitySessionIds:new Set,batchFlushRafRef:null},r=(i,a)=>{const c=new Map;return e(l=>{const d=new Map(l.sessions);let u=l.nextChunkId;const f=Date.now();for(const[p,g]of i){const m=d.get(p)??Ut(p);let b=m.bufferChunks.length>0?[...m.bufferChunks]:[],y=m.bufferLength;for(const x of g){const w=u++;b.push({id:w,data:x}),c.set(p,w),y+=x.length}for(;y>_h&&b.length>1;){const x=b.shift();if(!x)break;y-=x.data.length}d.set(p,{...m,bufferChunks:b,bufferLength:y,lastOutputAt:a.has(p)?f:m.lastOutputAt,updatedAt:f})}return{sessions:d,nextChunkId:u}}),c},o=()=>{if(n.batchFlushRafRef===null){if(typeof window>"u"){s();return}n.batchFlushRafRef=window.requestAnimationFrame(()=>{n.batchFlushRafRef=null,s()})}},s=()=>{if(n.pendingChunksBySession.size===0)return;const i=FP(n.pendingChunksBySession),a=new Set([...i.keys()].filter(c=>n.activitySessionIds.has(c)));for(const c of i.keys())n.pendingChunksBySession.has(c)||n.activitySessionIds.delete(c);r(i,a),n.pendingChunksBySession.size>0&&o()};return{sessions:new Map,nextChunkId:1,activeSessionId:null,getTerminalSession:i=>t().sessions.get(i),setActiveSessionId:i=>{if(e({activeSessionId:i}),i){const a=t().sessions.get(i);if(a?.agentNeedsReview){const c=new Map(t().sessions);c.set(i,{...a,agentNeedsReview:!1,updatedAt:Date.now()}),e({sessions:c}),a.terminalSessionId&&hl(a.terminalSessionId)}}},setTerminalSession:(i,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(i),f=!d||d.terminalSessionId!==a.sessionId?Ut(i):d??Ut(i),p=a.history??d?.history??[];return l.set(i,{...f,terminalSessionId:a.sessionId,mode:a.mode??f.mode,tmuxSessionName:a.tmuxSessionName??f.tmuxSessionName,activeProgram:a.activeProgram??d?.activeProgram??f.activeProgram,activeProgramRaw:a.activeProgramRaw??d?.activeProgramRaw??f.activeProgramRaw,activeProgramSource:a.activeProgramSource??d?.activeProgramSource??f.activeProgramSource,cwd:a.cwd??d?.cwd??f.cwd,agent:d?.agent??s2(i)??f.agent,agentResumeRecovered:d?.agentResumeRecovered??f.agentResumeRecovered,shellTitle:d?.shellTitle??na()[i]??f.shellTitle,sessionId:i,isConnecting:!1,history:p,updatedAt:Date.now()}),{sessions:l}})},setSessionHistory:(i,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(i)??Ut(i);return l.set(i,{...d,history:a,updatedAt:Date.now()}),{sessions:l}})},setSessionActiveProgram:(i,a,c=null,l=null)=>{e(d=>{const u=new Map(d.sessions),f=u.get(i)??Ut(i);return u.set(i,{...f,activeProgram:a,activeProgramRaw:l,activeProgramSource:c,updatedAt:Date.now()}),{sessions:u}})},setSessionCwd:(i,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(i)??Ut(i);return l.set(i,{...d,cwd:a,updatedAt:Date.now()}),{sessions:l}})},setSessionShellTitle:(i,a)=>{e(c=>{const l=c.sessions.get(i)??Ut(i);if(l.shellTitle===a)return c;const d=new Map(c.sessions);return d.set(i,{...l,shellTitle:a,updatedAt:Date.now()}),{sessions:d}}),t2(i,a)},setSessionPromptState:(i,a,c)=>{e(l=>{const d=l.sessions.get(i);if(!d||d.promptState===a)return l;const u=new Map(l.sessions);return u.set(i,{...d,promptState:a,shellExitCode:c??d.shellExitCode,updatedAt:Date.now()}),{sessions:u}})},setSessionTuiProgress:(i,a)=>{e(c=>{const l=c.sessions.get(i);if(!l)return c;const d=a?.state==="remove"?null:a;if(l.tuiProgress?.state===d?.state&&l.tuiProgress?.progress===d?.progress)return c;const u=new Map(c.sessions);return u.set(i,{...l,tuiProgress:d,updatedAt:Date.now()}),{sessions:u}})},setSessionGitStatus:(i,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(i);return!d||JSON.stringify(d.gitStatus)===JSON.stringify(a)?c:(l.set(i,{...d,gitStatus:a,updatedAt:Date.now()}),{sessions:l})})},setSessionCopyMode:(i,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(i);return!d||d.inCopyMode===a?c:(l.set(i,{...d,inCopyMode:a,updatedAt:Date.now()}),{sessions:l})})},setSessionAgentIdentity:(i,a)=>{Oh(i,a),e(c=>{const l=c.sessions.get(i)??Ut(i);if(JSON.stringify(l.agent)===JSON.stringify(a))return c;const d=new Map(c.sessions);return d.set(i,{...l,agent:a,updatedAt:Date.now()}),{sessions:d}})},setSessionAgentStatus:(i,a)=>{const c=t(),l=c.sessions.get(i);if(!l)return;const d=a.agentStatus??null,u=d&&d!=="idle"?a.agentIndicator??l.agentIndicator??null:null,f=d&&d!=="idle"?a.agentStatusDetail??null:null,p=a.agent!==void 0?a.agent:l.agent,g=a.agentMessage!==void 0?a.agentMessage:d?l.agentMessage:null,m=a.agentNativeSessionId!==void 0?a.agentNativeSessionId:l.agentNativeSessionId,b=a.agentResumeRecovered!==void 0?a.agentResumeRecovered:l.agentResumeRecovered,y=a.agentRich??l.agentRich,x=a.agentActivity??l.agentActivity,w=a.agentCwd!==void 0?a.agentCwd:l.agentCwd,I=c.activeSessionId!==i,R=l.agentStatus==="working"||l.agentStatus==="waiting"||l.agentStatus==="done",S=a.reviewed===!1||a.reviewed===null&&d===null&&R&&I;if(l.agentStatus===d&&l.agentIndicator===u&&l.agentStatusDetail===f&&l.agent===p&&l.agentMessage===g&&l.agentNativeSessionId===m&&l.agentResumeRecovered===b&&l.agentRich===y&&l.agentActivity===x&&l.agentCwd===w&&l.agentNeedsReview===S)return;const A=new Map(c.sessions);if(A.set(i,{...l,agentStatus:d,agentIndicator:u,agentStatusDetail:f,agent:p,agentMessage:g,agentNativeSessionId:m,agentResumeRecovered:b,agentRich:y,agentActivity:x,agentCwd:w,agentNeedsReview:S,updatedAt:Date.now()}),e({sessions:A}),p&&Oh(i,p),!Ti())return;const T=p?.displayName??l.agent?.displayName??"Agent",v=JP(),E=QP(v,T);if(d==="waiting"&&l.agentStatus!=="waiting"&&I){bc({title:E.waitingTitle,body:g??E.waitingBody,tag:`agent:${i}`,dedupKey:`agent:${i}:waiting:${x}`,data:{url:"/",sessionId:i},deferToPush:!0});return}if(d==="done"&&l.agentStatus!=="done"&&I){bc({title:E.doneTitle,body:E.doneBody,tag:`agent:${i}`,dedupKey:`agent:${i}:done:${x}`,data:{url:"/",sessionId:i},deferToPush:!0});return}d===null&&(l.agentStatus==="working"||l.agentStatus==="waiting")&&I&&bc({title:E.exitedTitle,body:E.exitedBody,tag:`agent:${i}`,dedupKey:`agent:${i}:exited:${x}`,data:{url:"/",sessionId:i},deferToPush:!0})},setAgentResumeRecovered:(i,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(i)??Ut(i);return d.agentResumeRecovered===a?c:(l.set(i,{...d,agentResumeRecovered:a,updatedAt:Date.now()}),{sessions:l})})},clearAgentNeedsReview:i=>{const a=t().sessions.get(i);a?.agentNeedsReview&&(e(c=>{const l=new Map(c.sessions),d=l.get(i);return!d||!d.agentNeedsReview?c:(l.set(i,{...d,agentNeedsReview:!1,updatedAt:Date.now()}),{sessions:l})}),a.terminalSessionId&&hl(a.terminalSessionId))},setConnecting:(i,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(i)??Ut(i);return l.set(i,{...d,isConnecting:a,updatedAt:Date.now()}),{sessions:l}})},appendToBuffer:(i,a,c)=>{if(!a)return;let l=n.pendingChunksBySession.get(i);l||(l=[],n.pendingChunksBySession.set(i,l)),l.push(...Bh(a)),c?.markActivity!==!1&&n.activitySessionIds.add(i),o()},hasPendingBufferWrites:i=>(n.pendingChunksBySession.get(i)?.length??0)>0,flushPendingBufferWrites:i=>{const a=n.pendingChunksBySession.get(i);if(!a?.length)return t().sessions.get(i)?.bufferChunks.at(-1)?.id??null;n.pendingChunksBySession.delete(i);const c=n.activitySessionIds.delete(i);return n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),r(new Map([[i,a]]),c?new Set([i]):new Set).get(i)??null},replaceBuffer:(i,a)=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null);let c=null;return e(l=>{const d=new Map(l.sessions),u=d.get(i);if(!u)return l;if(!a||a.length===0)return d.set(i,{...u,bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:d};let f=l.nextChunkId;const p=[];let g=0;for(const m of a)if(m)for(const b of Bh(m)){const y=f++;p.push({id:y,data:b}),c=y,g+=b.length}for(;g>_h&&p.length>1;){const m=p.shift();if(!m)break;g-=m.data.length}return d.set(i,{...u,bufferChunks:p,bufferLength:g,updatedAt:Date.now()}),{sessions:d,nextChunkId:f}}),c},clearTerminalSession:i=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),e(a=>{const c=new Map(a.sessions),l=c.get(i);return l&&c.set(i,{...l,terminalSessionId:null,isConnecting:!1,agentStatus:null,agentIndicator:null,agentStatusDetail:null,agent:null,agentMessage:null,agentNeedsReview:!1,updatedAt:Date.now()}),{sessions:c}})},clearBuffer:i=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),e(a=>{const c=new Map(a.sessions),l=c.get(i);return l?(c.set(i,{...l,bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:c}):a})},removeTerminalSession:i=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),e(a=>{const c=new Map(a.sessions);return c.delete(i),{sessions:c}}),n2(i),r2(i)},clearAllTerminalSessions:()=>{n.pendingChunksBySession.clear(),n.activitySessionIds.clear(),n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),e({sessions:new Map,nextChunkId:1}),i2(),o2()}}}),Bl="termdock:session-notice";function a2(){return P.useEffect(()=>{const e=()=>wc.getState().view(!document.hidden&&_s()?vc.getState().activeSessionId:null);e();const t=vc.subscribe((n,r)=>{n.activeSessionId!==r.activeSessionId&&e()});return document.addEventListener("visibilitychange",e),window.addEventListener($o,e),()=>{t(),document.removeEventListener("visibilitychange",e),window.removeEventListener($o,e),wc.getState().view(null)}},[]),P.useEffect(()=>Ow(e=>{if(e.type!=="session-notice")return;wc.getState().receive(e.sessionId,e.id);const t=te()?.targetPeerId,n=$t(),r=window.parent,o=BP().sessions.find(u=>u.sessionId===e.sessionId),s=vc.getState().sessions.get(e.sessionId),i=s?.shellTitle??e2(e.sessionId),a=i===s?.cwd||i===Eo(s?.cwd??null)?null:i,c=kP(o??{name:e.sessionName},s?.activeProgram??null,null,void 0,a,s?.promptState??null),l={...e,sessionName:c,key:`${t??"local"}:${e.id}`,open:()=>t&&n?n.focusSession(t,e.sessionId):(window.dispatchEvent(new CustomEvent("termdock:focus-session",{detail:e.sessionId})),!0)},d=r.document.createEvent("CustomEvent");d.initCustomEvent(Bl,!1,!1,l),r.dispatchEvent(d)}),[]),null}function c2(){const{locale:e}=Gr(),t=e==="zh",[n,r]=P.useState([]);P.useEffect(()=>{const i=a=>{const c=a.detail;r(l=>l.some(d=>d.key===c.key)?l:[...l,c])};return window.addEventListener(Bl,i),()=>window.removeEventListener(Bl,i)},[]);const o=P.useCallback(i=>{r(a=>a.filter(c=>c.key!==i))},[]),s=n[0];return s?Pi.createPortal(h.jsx(l2,{notice:s,remaining:n.length-1,chinese:t,onDismiss:o},s.key),document.body):null}function l2({notice:e,remaining:t,chinese:n,onDismiss:r}){const[o,s]=P.useState(!1);return h.jsxs("section",{"aria-label":n?"关键进展提醒":"Progress reminder",className:"fixed left-3 right-3 top-[calc(var(--safe-top-inset,0px)+0.75rem)] z-toast overflow-hidden rounded-xl bg-surface text-foreground shadow-lg ring-1 ring-inset ring-border/15 animate-fade-in md:left-auto md:right-4 md:w-[360px]",children:[h.jsxs("button",{type:"button","aria-label":n?"查看 Session":"Open session",className:"group flex w-full items-start gap-2.5 p-3.5 pr-11 text-left transition-colors hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",onClick:()=>{e.open()?r(e.key):s(!0)},children:[h.jsx(ym,{size:16,className:"mt-0.5 shrink-0 text-primary","aria-hidden":"true"}),h.jsxs("span",{className:"min-w-0 flex-1",role:"status","aria-live":"polite","aria-atomic":"true",children:[h.jsxs("span",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium",title:e.sessionName,children:e.sessionName}),h.jsx(OI,{size:13,className:"shrink-0 text-muted-foreground/60 transition-colors group-hover:text-primary","aria-hidden":"true"})]}),e.title&&h.jsx("span",{className:"mt-1 block truncate text-[11px] text-muted-foreground",children:e.title}),h.jsx("span",{className:"mt-1.5 line-clamp-3 whitespace-pre-wrap break-words text-[13px] leading-relaxed text-foreground/85",title:e.message,children:e.message}),t>0&&h.jsx("span",{className:"mt-2 block text-[10px] text-muted-foreground",children:n?`还有 ${t} 条`:`${t} more`}),o&&h.jsx("span",{role:"alert",className:"mt-2 block text-xs text-warning",children:n?"暂时无法打开该服务,请重试。":"Unable to open the service. Please retry."})]})]}),h.jsx("button",{type:"button","aria-label":n?"关闭提醒":"Dismiss reminder",className:"absolute right-0 top-0 flex h-11 w-11 items-center justify-center rounded-tr-xl text-muted-foreground/60 transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",onClick:()=>r(e.key),children:h.jsx(Im,{size:14})})]})}const Fh=5*6e4;let Dl,Vw=!1,Yw=!1,Mh=!1;const _l=new Set;function jh(){Vw=!0,_l.forEach(e=>e())}function d2(){return P.useSyncExternalStore(e=>(_l.add(e),()=>{_l.delete(e)}),()=>Vw,()=>!1)}function u2(){window.dispatchEvent(new Event("termdock:before-update")),Yw=!0,Dl?.waiting?Dl.waiting.postMessage({type:"SKIP_WAITING"}):window.location.reload()}function f2(e,t){let n=e;return()=>{if(!n){n=!0;return}t()}}function h2(){if(Mh||typeof window>"u"||!("serviceWorker"in navigator))return;Mh=!0,navigator.serviceWorker.addEventListener("controllerchange",f2(!!navigator.serviceWorker.controller,()=>{Yw?window.location.reload():jh()}));const e=()=>{navigator.serviceWorker.register("/sw.js",{scope:"/",updateViaCache:"none"}).then(t=>{Dl=t;const n=()=>{t.waiting&&jh()},r=()=>{const i=t.installing;i?.addEventListener("statechange",()=>{i.state==="installed"&&navigator.serviceWorker.controller&&n()})};t.addEventListener("updatefound",r),r(),n();let o=0;const s=()=>{document.visibilityState!=="visible"||Date.now()-o<Fh||(o=Date.now(),t.update().then(n).catch(()=>{}))};s(),window.setInterval(s,Fh),document.addEventListener("visibilitychange",s)}).catch(()=>{})};document.readyState==="complete"?e():window.addEventListener("load",e,{once:!0})}function p2(){const e=d2(),[t,n]=P.useState(!1),{locale:r}=Gr();if(!e||t)return null;const o=r==="zh";return h.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:[h.jsx("span",{children:o?"新版本已就绪":"An update is ready"}),h.jsx("button",{type:"button",className:"whitespace-nowrap text-primary",onClick:u2,children:o?"重新加载":"Reload"}),h.jsx("button",{type:"button",className:"whitespace-nowrap text-muted-foreground",onClick:()=>n(!0),children:o?"稍后":"Later"})]})}let xo=[],Sc=!1;function g2(e,t,n={}){typeof window>"u"||(xo.push(JSON.stringify({level:e,message:t,data:{ts:Date.now(),...n}})),m2())}async function m2(){if(!Sc){Sc=!0;try{for(;xo.length>0;){const e=xo[0];try{await fetch("/api/client-log",{method:"POST",headers:{"Content-Type":"application/json"},body:e,keepalive:!0}),xo.shift()}catch{xo=[];break}}}finally{Sc=!1}}}function w2(){const e=P.useRef(null),t=navigator.standalone===!0||window.matchMedia?.("(display-mode: standalone)").matches===!0,n=window.parent===window&&Fd()&&t;return P.useEffect(()=>{if(!n)return;const r=()=>{const o=e.current;if(!o)return;const s=o.getBoundingClientRect(),i=getComputedStyle(o);g2("info","PWA_STATUS_BAR_SURFACE",{revision:"ipad-default-status-bar",statusBarStyle:document.querySelector('meta[name="apple-mobile-web-app-status-bar-style"]')?.getAttribute("content"),entry:document.querySelector('script[type="module"][src]')?.getAttribute("src"),parent:o.parentElement?.tagName,rect:{x:s.x,y:s.y,width:s.width,height:s.height},background:i.backgroundColor,clip:i.backgroundClip,zIndex:i.zIndex,safeTop:getComputedStyle(document.documentElement).getPropertyValue("--safe-top-inset"),viewport:{width:window.innerWidth,height:window.innerHeight,offsetTop:window.visualViewport?.offsetTop},screen:{width:window.screen.width,height:window.screen.height}})};return window.addEventListener("termdock:initial-viewport-presented",r,{once:!0}),()=>window.removeEventListener("termdock:initial-viewport-presented",r)},[n]),n?Pi.createPortal(h.jsx("div",{ref:e,"data-pwa-status-bar-surface":!0,"aria-hidden":"true",className:"pwa-status-bar-surface pointer-events-none fixed inset-x-0 top-0 z-popover app-chrome-bg"}),document.body):null}function Xw(e){const t=document.querySelector('meta[name="theme-color"]');t&&t.setAttribute("content",e==="light"?"#FFFCF0":"#1C1B1A")}const Zw=P.createContext(void 0);function wN({children:e}){const t=P.useContext(Zw),n=t===void 0?typeof document>"u"?null:document.body:t;return n?Pi.createPortal(e,n):null}const y2={activeKey:"root",items:[]},b2=()=>()=>{},v2=()=>y2;function S2({host:e,item:t,visible:n,active:r}){const o=P.useRef(null);return P.useEffect(()=>{o.current?.toggleAttribute("inert",!r)},[r]),P.useLayoutEffect(()=>{const s=o.current;return()=>{try{const i=s?.contentWindow,a=i?.document.createEvent("Event");a&&(a.initEvent("termdock:before-update",!1,!1),i?.dispatchEvent(a))}catch{}e.attach(t.key,null)}},[e,t.key]),h.jsx("iframe",{ref:o,title:t.service?.label||"服务工作区","data-workspace-key":t.key,src:`/workspace.html?${am}=${encodeURIComponent(t.key)}`,className:"fixed inset-0 w-full border-0 bg-[var(--chrome-bg)]",style:{height:"var(--app-base-vh, 100%)",visibility:n?"visible":"hidden",pointerEvents:r?"auto":"none"},"aria-hidden":!r,tabIndex:r?0:-1,allow:"clipboard-read; clipboard-write; fullscreen"})}function E2({children:e}){const t=window.parent===window?$t():void 0,n=P.useSyncExternalStore(t?.subscribe||b2,t?.snapshot||v2),[r,o]=P.useState(null),[s,i]=P.useState(()=>n.activeKey==="root"?"root":null),[a,c]=P.useState(),[l,d]=P.useState(!1),[u,f]=P.useState(),p=n.items.find(w=>w.key===n.activeKey),g=p?.rendered||a===n.activeKey?n.activeKey:s,m=g!==n.activeKey,b=m&&s===null;P.useLayoutEffect(()=>{if(!m||b){f(void 0);return}const w=()=>{const I=Array.from(document.querySelectorAll("iframe[data-workspace-key]")).find(C=>C.dataset.workspaceKey===s),T=(s==="root"?r:I?.contentDocument)?.querySelector('nav[aria-label="切换服务"]')?.closest("[data-sidebar-gesture-ignore]")?.getBoundingClientRect();if(!T||T.width===0||T.right<=0){f(void 0);return}const v=I?.getBoundingClientRect(),E=T.top+(v?.top??0)>=160;f({left:T.left+(v?.left??0)+12,top:(E?T.top-8:T.bottom+8)+(v?.top??0),width:Math.max(0,T.width-24),transform:E?"translateY(-100%)":"none"})};return w(),window.addEventListener("resize",w),()=>window.removeEventListener("resize",w)},[m,b,s,r]),P.useLayoutEffect(()=>{t?.present(g),m||i(g),r?.toggleAttribute("inert",g!=="root"||m)},[t,r,g,m]),P.useEffect(()=>{if(d(!1),!m)return;const w=setTimeout(()=>d(!0),8e3);return()=>clearTimeout(w)},[n.activeKey,m]),P.useEffect(()=>{c(void 0)},[n.activeKey]);const y=n.items.find(w=>w.key===s),x=p?.phase==="offline"?"网络已断开,等待恢复…":p?.phase==="reconnecting"?"连接暂未恢复,正在重试…":l?"连接时间较长,仍在等待服务…":b?"正在恢复服务…":"正在切换服务…";return P.useEffect(()=>{if(!t)return;const w=()=>{try{const I=JSON.parse(localStorage.getItem("termdock-color-theme")||"null");(I==="dark"||I==="light")&&(document.documentElement.dataset.theme=I,Xw(I))}catch{}};return window.addEventListener("storage",w),()=>window.removeEventListener("storage",w)},[t]),P.useEffect(()=>{if(!t||!("serviceWorker"in navigator))return;const w=S=>{if(S.source!==navigator.serviceWorker.controller)return;const A=S.data;A?.type==="termdock:focus-session"&&typeof A.targetPeerId=="string"&&typeof A.sessionId=="string"&&t.focusSession(A.targetPeerId,A.sessionId)&&(S.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),S.stopImmediatePropagation())},I=async()=>{if("caches"in window)try{const S=await caches.open("termdock-notification-target-v1"),A=await S.match("/__termdock-notification-target");if(!A)return;const T=await A.json();typeof T.targetPeerId=="string"&&typeof T.sessionId=="string"&&Date.now()-T.clickedAt<3e4&&t.focusSession(T.targetPeerId,T.sessionId)&&await S.delete("/__termdock-notification-target")}catch{}},R=()=>{document.hidden||I()};return navigator.serviceWorker.addEventListener("message",w),document.addEventListener("visibilitychange",R),I(),()=>{navigator.serviceWorker.removeEventListener("message",w),document.removeEventListener("visibilitychange",R)}},[t]),t?h.jsxs("div",{className:"relative h-full w-full overflow-hidden bg-[var(--chrome-bg)]",children:[h.jsx("div",{ref:o,className:"isolate h-full w-full","aria-hidden":g!=="root"||m,style:{visibility:g==="root"?"visible":"hidden"},children:h.jsx(Zw.Provider,{value:r,children:e})}),n.items.filter(w=>w.key!=="root").map(w=>h.jsx(S2,{host:t,item:w,visible:g===w.key,active:!m&&g===w.key},w.key)),b&&h.jsx(Od,{className:"z-modal-panel",status:x,detail:l||p?.phase==="offline"||p?.phase==="reconnecting"?p?.service?.label:void 0,actionLabel:l||p?.phase==="offline"||p?.phase==="reconnecting"?"查看连接页面":void 0,onAction:()=>c(n.activeKey)}),m&&!b&&h.jsx("div",{className:"fixed inset-0 z-modal-panel flex items-end justify-center px-3 pb-[calc(env(safe-area-inset-bottom)+96px)]",role:"dialog","aria-modal":"true","aria-label":"切换服务",onKeyDown:w=>{if(w.key==="Escape"&&y?.service&&(w.preventDefault(),t.activate(y.service)),w.key==="Tab"){const I=Array.from(w.currentTarget.querySelectorAll("button")),R=I[0],S=I[I.length-1];w.shiftKey&&document.activeElement===R?(w.preventDefault(),S?.focus()):!w.shiftKey&&document.activeElement===S&&(w.preventDefault(),R?.focus())}},children:h.jsxs("div",{style:u?{position:"absolute",...u}:void 0,className:"flex w-full max-w-sm flex-wrap items-center gap-x-2 gap-y-1 rounded-xl border border-border bg-surface-elevated px-3 py-1.5 text-foreground shadow-lg",children:[h.jsxs("div",{role:"status","aria-live":"polite",className:"flex min-w-0 flex-1 items-center gap-2",children:[h.jsx(lt,{size:16,className:"shrink-0 animate-spin text-primary motion-reduce:animate-none","aria-hidden":"true"}),h.jsxs("div",{className:"min-w-0",children:[h.jsx("div",{className:"truncate text-sm font-medium",children:p?.service?.label||"服务工作区"}),h.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:x})]})]}),h.jsxs("div",{className:"flex items-center justify-end gap-1",children:[l&&h.jsx("button",{type:"button",className:"min-h-11 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2",onClick:()=>c(n.activeKey),children:"查看连接页面"}),y?.service&&h.jsx("button",{type:"button",autoFocus:!0,"aria-label":"取消切换",className:"min-h-11 shrink-0 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>t.activate(y.service),children:"取消"})]})]})})]}):e}const x2=P.lazy(()=>An(()=>import("./App-BiDKeTpx.js").then(e=>e.d),__vite__mapDeps([4,2,1,5,6,3,7,8]))),I2=P.lazy(()=>An(()=>import("./DagPlayground-Cshoqo5l.js"),__vite__mapDeps([9,10,2,1,11,7,3])).then(e=>({default:e.DagPlayground}))),A2=P.lazy(()=>An(()=>import("./DiffLab-DFut8ZHi.js"),__vite__mapDeps([12,2,1,13,8,14,3])).then(e=>({default:e.DiffLab}))),C2=P.lazy(()=>An(()=>import("./DiffReviewLab-Y9JlI5DQ.js"),__vite__mapDeps([15,2,1,16,5,6,11,13,8,14,3])).then(e=>({default:e.DiffReviewLab})));bP();mI();SI();window.parent===window&&h2();const Io=te();Io&&An(()=>import("./App-BiDKeTpx.js").then(e=>e.d),__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")&&nI(Io?{...Io,id:Io.targetPeerId,label:Io.serviceName||location.host}:void 0);try{const e=JSON.parse(window.localStorage.getItem("termdock-color-theme")||"null");(e==="dark"||e==="light")&&(document.documentElement.dataset.theme=e,Xw(e))}catch{}II.createRoot(document.getElementById("root")).render(h.jsxs(vt.StrictMode,{children:[h.jsx(w2,{}),h.jsx(tP,{}),h.jsxs(Dk,{children:[window.parent===window&&h.jsxs(h.Fragment,{children:[h.jsx(p2,{}),h.jsx(c2,{})]}),h.jsx(cP,{children:h.jsx(P.Suspense,{fallback:h.jsx(Od,{}),children:(()=>{const e=new URLSearchParams(window.location.search);return e.get("dag-playground")==="1"?h.jsx(I2,{}):e.get("diff-review-lab")==="1"?h.jsx(C2,{}):e.get("diff-lab")==="1"?h.jsx(A2,{}):h.jsx(E2,{children:h.jsxs(oP,{children:[h.jsx(a2,{}),h.jsx(x2,{})]})})})()})})]})]}));export{Q2 as $,Cd as A,ym as B,Si as C,Fw as D,Om as E,kk as F,F2 as G,sT as H,IR as I,bR as J,id as K,lt as L,Z1 as M,TR as N,W1 as O,IT as P,nR as Q,oE as R,rI as S,QI as T,pl as U,mP as V,$o as W,Im as X,$A as Y,DC as Z,An as _,wm as a,zA as a$,Mn as a0,ZR as a1,XR as a2,gN as a3,g2 as a4,LC as a5,W2 as a6,Ei as a7,G2 as a8,NA as a9,St as aA,xA as aB,XC as aC,YC as aD,QC as aE,yC as aF,YR as aG,WR as aH,s2 as aI,e2 as aJ,zR as aK,ok as aL,GR as aM,WC as aN,re as aO,Eo as aP,ER as aQ,$R as aR,tk as aS,NR as aT,QR as aU,KR as aV,jR as aW,fR as aX,aN as aY,VR as aZ,Ri as a_,qA as aa,vC as ab,j2 as ac,Ji as ad,eR as ae,sk as af,hP as ag,Qe as ah,bC as ai,xa as aj,At as ak,sR as al,FR as am,mN as an,WA as ao,HC as ap,oR as aq,OR as ar,KA as as,Pk as at,mA as au,Dm as av,GA as aw,ST as ax,hA as ay,_C as az,DI as b,nN as b$,RP as b0,kP as b1,oN as b2,bn as b3,Ti as b4,Ll as b5,Ko as b6,Hd as b7,mt as b8,HA as b9,h as bA,M2 as bB,MC as bC,ak as bD,aR as bE,Nd as bF,xk as bG,rk as bH,CR as bI,Rk as bJ,OC as bK,VC as bL,bk as bM,UR as bN,fw as bO,Ym as bP,TP as bQ,cR as bR,Ck as bS,xC as bT,$n as bU,_t as bV,BP as bW,BR as bX,PR as bY,LR as bZ,_R as b_,nC as ba,fT as bb,zC as bc,FC as bd,qC as be,JR as bf,nw as bg,$t as bh,mc as bi,dg as bj,Pg as bk,DR as bl,ZC as bm,tR as bn,lm as bo,tw as bp,EA as bq,K2 as br,SR as bs,xR as bt,mR as bu,vR as bv,yR as bw,zP as bx,Ud as by,_s as bz,OI as c,AC as c$,tN as c0,V2 as c1,IC as c2,VA as c3,$2 as c4,yo as c5,uk as c6,lR as c7,pk as c8,Ek as c9,at as cA,Ik as cB,TC as cC,CC as cD,EC as cE,kC as cF,NC as cG,dk as cH,wk as cI,mk as cJ,Sk as cK,sN as cL,lN as cM,dN as cN,uN as cO,cN as cP,Gm as cQ,wC as cR,UC as cS,Ia as cT,J2 as cU,bc as cV,vk as cW,Ow as cX,fk as cY,q2 as cZ,P2 as c_,hR as ca,dR as cb,KC as cc,hr as cd,fN as ce,pR as cf,uR as cg,PC as ch,eN as ci,BC as cj,jC as ck,gk as cl,Tk as cm,iR as cn,hk as co,_2 as cp,pA as cq,lk as cr,ek as cs,ck as ct,yk as cu,sw as cv,te as cw,RR as cx,Ak as cy,pm as cz,bm as d,O2 as d0,pN as d1,ZP as d2,Xw as d3,SC as d4,D2 as d5,JC as d6,hN as d7,rR as d8,ik as d9,GC as da,Us as db,yt as dc,MR as dd,Cm as de,U2 as df,Gr as dg,Pm as dh,z2 as di,X2 as dj,wc as dk,iN as dl,qe as dm,vc as dn,rN as dp,kw as dq,Ae as dr,kR as ds,Vi as dt,pt as du,Z2 as dv,Y2 as dw,Gn as e,$I as f,vm as g,Sm as h,cP as i,H2 as j,_m as k,WI as l,VI as m,Em as n,Et as o,Zi as p,bT as q,xm as r,Od as s,Ce as t,wN as u,RC as v,bi as w,sd as x,cn as y,nk as z};