termdock 1.4.248 → 1.4.249

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 (322) hide show
  1. package/dist/client/assets/{App-DA7cQLR7.js → App-ySHLLxfl.js} +35 -35
  2. package/dist/client/assets/App-ySHLLxfl.js.br +0 -0
  3. package/dist/client/assets/App-ySHLLxfl.js.gz +0 -0
  4. package/dist/client/assets/{ChangeWalkthroughPanel-vDiLbIdv.js → ChangeWalkthroughPanel-DrsLVbFw.js} +2 -2
  5. package/dist/client/assets/ChangeWalkthroughPanel-DrsLVbFw.js.br +0 -0
  6. package/dist/client/assets/ChangeWalkthroughPanel-DrsLVbFw.js.gz +0 -0
  7. package/dist/client/assets/{DagPlayground-BvY_KblL.js → DagPlayground-CBUX-s8X.js} +1 -1
  8. package/dist/client/assets/DagPlayground-CBUX-s8X.js.br +0 -0
  9. package/dist/client/assets/DagPlayground-CBUX-s8X.js.gz +0 -0
  10. package/dist/client/assets/{DiffLab-Dra7cEKx.js → DiffLab-DD8m9b0G.js} +1 -1
  11. package/dist/client/assets/DiffLab-DD8m9b0G.js.br +0 -0
  12. package/dist/client/assets/DiffLab-DD8m9b0G.js.gz +0 -0
  13. package/dist/client/assets/{DiffReview-v9_1IS2n.js → DiffReview-BEFjWY01.js} +1 -1
  14. package/dist/client/assets/DiffReview-BEFjWY01.js.br +0 -0
  15. package/dist/client/assets/DiffReview-BEFjWY01.js.gz +0 -0
  16. package/dist/client/assets/{DiffReviewLab-BF8Dada6.js → DiffReviewLab-BS1rFkx9.js} +1 -1
  17. package/dist/client/assets/DiffReviewLab-BS1rFkx9.js.br +0 -0
  18. package/dist/client/assets/DiffReviewLab-BS1rFkx9.js.gz +0 -0
  19. package/dist/client/assets/{DiffViewer-C2s4BXp0.js → DiffViewer-zb8C5YLR.js} +1 -1
  20. package/dist/client/assets/DiffViewer-zb8C5YLR.js.br +0 -0
  21. package/dist/client/assets/DiffViewer-zb8C5YLR.js.gz +0 -0
  22. package/dist/client/assets/{ModelPreview-D9pzW_YD.js → ModelPreview-BdY9A7GQ.js} +1 -1
  23. package/dist/client/assets/ModelPreview-BdY9A7GQ.js.br +0 -0
  24. package/dist/client/assets/ModelPreview-BdY9A7GQ.js.gz +0 -0
  25. package/dist/client/assets/RightSidebar-lV2Ca2-c.js +1678 -0
  26. package/dist/client/assets/RightSidebar-lV2Ca2-c.js.br +0 -0
  27. package/dist/client/assets/RightSidebar-lV2Ca2-c.js.gz +0 -0
  28. package/dist/client/assets/{abnfDiagram-VCTEODGH-DVOxqZDY.js → abnfDiagram-VCTEODGH-ChpMiLwB.js} +1 -1
  29. package/dist/client/assets/abnfDiagram-VCTEODGH-ChpMiLwB.js.br +0 -0
  30. package/dist/client/assets/abnfDiagram-VCTEODGH-ChpMiLwB.js.gz +0 -0
  31. package/dist/client/assets/{app-JK4pM9zv.js → app-DhyrRqRS.js} +11 -11
  32. package/dist/client/assets/app-DhyrRqRS.js.br +0 -0
  33. package/dist/client/assets/app-DhyrRqRS.js.gz +0 -0
  34. package/dist/client/assets/{arc-DY_WK1Ln.js → arc-CcPLW1-W.js} +1 -1
  35. package/dist/client/assets/arc-CcPLW1-W.js.br +0 -0
  36. package/dist/client/assets/arc-CcPLW1-W.js.gz +0 -0
  37. package/dist/client/assets/{architectureDiagram-5GKGNRK7-oyhVtQ5E.js → architectureDiagram-5GKGNRK7-CjWa2b5g.js} +1 -1
  38. package/dist/client/assets/architectureDiagram-5GKGNRK7-CjWa2b5g.js.br +0 -0
  39. package/dist/client/assets/{architectureDiagram-5GKGNRK7-oyhVtQ5E.js.gz → architectureDiagram-5GKGNRK7-CjWa2b5g.js.gz} +0 -0
  40. package/dist/client/assets/{blockDiagram-I7D4REHJ-DTMir8MU.js → blockDiagram-I7D4REHJ-D1AMj3Ey.js} +1 -1
  41. package/dist/client/assets/blockDiagram-I7D4REHJ-D1AMj3Ey.js.br +0 -0
  42. package/dist/client/assets/blockDiagram-I7D4REHJ-D1AMj3Ey.js.gz +0 -0
  43. package/dist/client/assets/{c4Diagram-7LVT6UL2-DpDHYMUW.js → c4Diagram-7LVT6UL2-Bo4f-Dyo.js} +1 -1
  44. package/dist/client/assets/c4Diagram-7LVT6UL2-Bo4f-Dyo.js.br +0 -0
  45. package/dist/client/assets/c4Diagram-7LVT6UL2-Bo4f-Dyo.js.gz +0 -0
  46. package/dist/client/assets/channel-B5npd3sc.js +1 -0
  47. package/dist/client/assets/{chunk-2Q5K7J3B-CZw9qV1g.js → chunk-2Q5K7J3B-EA_Ksody.js} +1 -1
  48. package/dist/client/assets/{chunk-5VM5RSS4-7oLZ2vUy.js → chunk-5VM5RSS4-D49nnzNg.js} +1 -1
  49. package/dist/client/assets/{chunk-F27PBJKO-8wDqj2MV.js → chunk-F27PBJKO-BiHLxDgP.js} +1 -1
  50. package/dist/client/assets/chunk-F27PBJKO-BiHLxDgP.js.br +0 -0
  51. package/dist/client/assets/chunk-F27PBJKO-BiHLxDgP.js.gz +0 -0
  52. package/dist/client/assets/{chunk-IMKFNOWR-BnRNosQc.js → chunk-IMKFNOWR-B_x-RlD-.js} +1 -1
  53. package/dist/client/assets/chunk-IMKFNOWR-B_x-RlD-.js.br +0 -0
  54. package/dist/client/assets/chunk-IMKFNOWR-B_x-RlD-.js.gz +0 -0
  55. package/dist/client/assets/{chunk-JWPE2WC7-DnbB0Lhi.js → chunk-JWPE2WC7-BO2gECxo.js} +1 -1
  56. package/dist/client/assets/{chunk-POPQ4Y6H-TXREax5x.js → chunk-POPQ4Y6H-CTJ8R53n.js} +1 -1
  57. package/dist/client/assets/{chunk-SVP7TREG-qPD0Q74z.js → chunk-SVP7TREG-jDMFhXej.js} +1 -1
  58. package/dist/client/assets/chunk-SVP7TREG-jDMFhXej.js.br +0 -0
  59. package/dist/client/assets/chunk-SVP7TREG-jDMFhXej.js.gz +0 -0
  60. package/dist/client/assets/{chunk-TICWLB2K-yzLwt_MH.js → chunk-TICWLB2K-DuOVjlA7.js} +1 -1
  61. package/dist/client/assets/chunk-TICWLB2K-DuOVjlA7.js.br +0 -0
  62. package/dist/client/assets/chunk-TICWLB2K-DuOVjlA7.js.gz +0 -0
  63. package/dist/client/assets/{chunk-XXDRQBXY-Dksq2NzZ.js → chunk-XXDRQBXY-Dg68j1ru.js} +1 -1
  64. package/dist/client/assets/classDiagram-ZZMXUADV-BxAMJQEG.js +1 -0
  65. package/dist/client/assets/classDiagram-v2-VYDZK3BY-BxAMJQEG.js +1 -0
  66. package/dist/client/assets/{cose-bilkent-JH36ORCC-BZyAGO6R.js → cose-bilkent-JH36ORCC-eC0PV-vF.js} +1 -1
  67. package/dist/client/assets/cose-bilkent-JH36ORCC-eC0PV-vF.js.br +0 -0
  68. package/dist/client/assets/cose-bilkent-JH36ORCC-eC0PV-vF.js.gz +0 -0
  69. package/dist/client/assets/{cynefin-OW5HDTMX-CyrkJWSU.js → cynefin-OW5HDTMX-CbwuuKCK.js} +1 -1
  70. package/dist/client/assets/cynefin-OW5HDTMX-CbwuuKCK.js.br +0 -0
  71. package/dist/client/assets/cynefin-OW5HDTMX-CbwuuKCK.js.gz +0 -0
  72. package/dist/client/assets/{cynefinDiagram-5FMLGOSQ-BrqS8ZGX.js → cynefinDiagram-5FMLGOSQ-DiL62xjJ.js} +1 -1
  73. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-DiL62xjJ.js.br +0 -0
  74. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-DiL62xjJ.js.gz +0 -0
  75. package/dist/client/assets/{dagre-GXQ25YYZ-ysmdkSNr.js → dagre-GXQ25YYZ-BoCcQeIF.js} +1 -1
  76. package/dist/client/assets/dagre-GXQ25YYZ-BoCcQeIF.js.br +0 -0
  77. package/dist/client/assets/dagre-GXQ25YYZ-BoCcQeIF.js.gz +0 -0
  78. package/dist/client/assets/{diagram-S7CK7UJ4-CWSuzX1d.js → diagram-S7CK7UJ4-BHxSkDxD.js} +1 -1
  79. package/dist/client/assets/diagram-S7CK7UJ4-BHxSkDxD.js.br +0 -0
  80. package/dist/client/assets/diagram-S7CK7UJ4-BHxSkDxD.js.gz +0 -0
  81. package/dist/client/assets/{diagram-UQ7AKVKN-BMxc5NDd.js → diagram-UQ7AKVKN-D2t82qXI.js} +1 -1
  82. package/dist/client/assets/diagram-UQ7AKVKN-D2t82qXI.js.br +0 -0
  83. package/dist/client/assets/diagram-UQ7AKVKN-D2t82qXI.js.gz +0 -0
  84. package/dist/client/assets/{diagram-VSXAHHWV-Cz5KpnGX.js → diagram-VSXAHHWV-DYQmQwL5.js} +1 -1
  85. package/dist/client/assets/diagram-VSXAHHWV-DYQmQwL5.js.br +0 -0
  86. package/dist/client/assets/diagram-VSXAHHWV-DYQmQwL5.js.gz +0 -0
  87. package/dist/client/assets/{diagram-VX7I27RA-CNk1h20b.js → diagram-VX7I27RA-6SfVR4Z9.js} +1 -1
  88. package/dist/client/assets/diagram-VX7I27RA-6SfVR4Z9.js.br +0 -0
  89. package/dist/client/assets/diagram-VX7I27RA-6SfVR4Z9.js.gz +0 -0
  90. package/dist/client/assets/{diagram-Z3DM3KII-C4lcgl6z.js → diagram-Z3DM3KII-CQiCDGAx.js} +1 -1
  91. package/dist/client/assets/diagram-Z3DM3KII-CQiCDGAx.js.br +0 -0
  92. package/dist/client/assets/diagram-Z3DM3KII-CQiCDGAx.js.gz +0 -0
  93. package/dist/client/assets/{ebnfDiagram-PWID7BFC-Cwo356mF.js → ebnfDiagram-PWID7BFC-C7YMHrC7.js} +1 -1
  94. package/dist/client/assets/ebnfDiagram-PWID7BFC-C7YMHrC7.js.br +0 -0
  95. package/dist/client/assets/ebnfDiagram-PWID7BFC-C7YMHrC7.js.gz +0 -0
  96. package/dist/client/assets/{erDiagram-RLTQ6QDP-B4DEocxu.js → erDiagram-RLTQ6QDP-C1-5SbSU.js} +1 -1
  97. package/dist/client/assets/erDiagram-RLTQ6QDP-C1-5SbSU.js.br +0 -0
  98. package/dist/client/assets/erDiagram-RLTQ6QDP-C1-5SbSU.js.gz +0 -0
  99. package/dist/client/assets/{flowDiagram-HODETNUW-CWP3R7jz.js → flowDiagram-HODETNUW-xNfUeMOl.js} +1 -1
  100. package/dist/client/assets/flowDiagram-HODETNUW-xNfUeMOl.js.br +0 -0
  101. package/dist/client/assets/flowDiagram-HODETNUW-xNfUeMOl.js.gz +0 -0
  102. package/dist/client/assets/{ganttDiagram-EL5Y4UJY-DBdMWa6L.js → ganttDiagram-EL5Y4UJY-CHiEXULk.js} +1 -1
  103. package/dist/client/assets/ganttDiagram-EL5Y4UJY-CHiEXULk.js.br +0 -0
  104. package/dist/client/assets/ganttDiagram-EL5Y4UJY-CHiEXULk.js.gz +0 -0
  105. package/dist/client/assets/{gestureArbiter-FNHriuhM.js → gestureArbiter-Q4qvTxJM.js} +1 -1
  106. package/dist/client/assets/gestureArbiter-Q4qvTxJM.js.br +0 -0
  107. package/dist/client/assets/gestureArbiter-Q4qvTxJM.js.gz +0 -0
  108. package/dist/client/assets/{gitGraphDiagram-WWUBYQGX-B6qG6eRT.js → gitGraphDiagram-WWUBYQGX-DGHj-HHA.js} +1 -1
  109. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-DGHj-HHA.js.br +0 -0
  110. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-DGHj-HHA.js.gz +0 -0
  111. package/dist/client/assets/{index-fjWWhVQp.css → index-CwuSutCd.css} +1 -1
  112. package/dist/client/assets/index-CwuSutCd.css.br +0 -0
  113. package/dist/client/assets/{index-fjWWhVQp.css.gz → index-CwuSutCd.css.gz} +0 -0
  114. package/dist/client/assets/{infoDiagram-27XIBGKW-DStk0sCn.js → infoDiagram-27XIBGKW-CkKjaZnz.js} +1 -1
  115. package/dist/client/assets/{ishikawaDiagram-5VMMS53U-Cz8OXUK9.js → ishikawaDiagram-5VMMS53U-BxwoaCAJ.js} +1 -1
  116. package/dist/client/assets/ishikawaDiagram-5VMMS53U-BxwoaCAJ.js.br +0 -0
  117. package/dist/client/assets/ishikawaDiagram-5VMMS53U-BxwoaCAJ.js.gz +0 -0
  118. package/dist/client/assets/{journeyDiagram-3NMN7TZE-CD4v2_eb.js → journeyDiagram-3NMN7TZE-Co0Qn6y1.js} +1 -1
  119. package/dist/client/assets/journeyDiagram-3NMN7TZE-Co0Qn6y1.js.br +0 -0
  120. package/dist/client/assets/journeyDiagram-3NMN7TZE-Co0Qn6y1.js.gz +0 -0
  121. package/dist/client/assets/{kanban-definition-UXKFOSKX-DwLWqTSY.js → kanban-definition-UXKFOSKX-BSOfc04T.js} +1 -1
  122. package/dist/client/assets/kanban-definition-UXKFOSKX-BSOfc04T.js.br +0 -0
  123. package/dist/client/assets/kanban-definition-UXKFOSKX-BSOfc04T.js.gz +0 -0
  124. package/dist/client/assets/{layout-C1EhlDX0.js → layout-BmHMb94h.js} +1 -1
  125. package/dist/client/assets/layout-BmHMb94h.js.br +0 -0
  126. package/dist/client/assets/layout-BmHMb94h.js.gz +0 -0
  127. package/dist/client/assets/{linear-DQLRPRnN.js → linear-y-Abd9JO.js} +1 -1
  128. package/dist/client/assets/linear-y-Abd9JO.js.br +0 -0
  129. package/dist/client/assets/linear-y-Abd9JO.js.gz +0 -0
  130. package/dist/client/assets/{mermaid.core-BzEGo4OD.js → mermaid.core-B4rzVonW.js} +5 -5
  131. package/dist/client/assets/mermaid.core-B4rzVonW.js.br +0 -0
  132. package/dist/client/assets/mermaid.core-B4rzVonW.js.gz +0 -0
  133. package/dist/client/assets/{mindmap-definition-YA3MSWOX-Dct8OiDY.js → mindmap-definition-YA3MSWOX-DY3bdl53.js} +1 -1
  134. package/dist/client/assets/mindmap-definition-YA3MSWOX-DY3bdl53.js.br +0 -0
  135. package/dist/client/assets/mindmap-definition-YA3MSWOX-DY3bdl53.js.gz +0 -0
  136. package/dist/client/assets/{passwordBootstrap-C7Gy7ATG.js → passwordBootstrap-kiljsfOw.js} +1 -1
  137. package/dist/client/assets/passwordBootstrap-kiljsfOw.js.br +0 -0
  138. package/dist/client/assets/passwordBootstrap-kiljsfOw.js.gz +0 -0
  139. package/dist/client/assets/{pegDiagram-XKGWAZYB-fIABDYj-.js → pegDiagram-XKGWAZYB-XdVcJb90.js} +1 -1
  140. package/dist/client/assets/pegDiagram-XKGWAZYB-XdVcJb90.js.br +0 -0
  141. package/dist/client/assets/pegDiagram-XKGWAZYB-XdVcJb90.js.gz +0 -0
  142. package/dist/client/assets/{pieDiagram-E7YTZNPT-D2EuLDIj.js → pieDiagram-E7YTZNPT-CgAHRPHX.js} +1 -1
  143. package/dist/client/assets/pieDiagram-E7YTZNPT-CgAHRPHX.js.br +0 -0
  144. package/dist/client/assets/pieDiagram-E7YTZNPT-CgAHRPHX.js.gz +0 -0
  145. package/dist/client/assets/{quadrantDiagram-AXDQQJYC-BjF42rwO.js → quadrantDiagram-AXDQQJYC-C-nwguRe.js} +1 -1
  146. package/dist/client/assets/quadrantDiagram-AXDQQJYC-C-nwguRe.js.br +0 -0
  147. package/dist/client/assets/quadrantDiagram-AXDQQJYC-C-nwguRe.js.gz +0 -0
  148. package/dist/client/assets/{railroadDiagram-O6MQD6OU-DjfSTDvw.js → railroadDiagram-O6MQD6OU-TcJFsMp6.js} +1 -1
  149. package/dist/client/assets/railroadDiagram-O6MQD6OU-TcJFsMp6.js.br +0 -0
  150. package/dist/client/assets/railroadDiagram-O6MQD6OU-TcJFsMp6.js.gz +0 -0
  151. package/dist/client/assets/{referenceLongPress-Cz9no5pI.js → referenceLongPress-DcD1aZqh.js} +1 -1
  152. package/dist/client/assets/referenceLongPress-DcD1aZqh.js.br +0 -0
  153. package/dist/client/assets/referenceLongPress-DcD1aZqh.js.gz +0 -0
  154. package/dist/client/assets/{requirementDiagram-BXWQKSXE-BewZ62Ou.js → requirementDiagram-BXWQKSXE-CDAoFFyT.js} +1 -1
  155. package/dist/client/assets/requirementDiagram-BXWQKSXE-CDAoFFyT.js.br +0 -0
  156. package/dist/client/assets/requirementDiagram-BXWQKSXE-CDAoFFyT.js.gz +0 -0
  157. package/dist/client/assets/{sankeyDiagram-P5KCCOFB-BhlchAkm.js → sankeyDiagram-P5KCCOFB-rscTAtOd.js} +1 -1
  158. package/dist/client/assets/sankeyDiagram-P5KCCOFB-rscTAtOd.js.br +0 -0
  159. package/dist/client/assets/sankeyDiagram-P5KCCOFB-rscTAtOd.js.gz +0 -0
  160. package/dist/client/assets/{sequenceDiagram-WJ2MYXX4-CFzratAc.js → sequenceDiagram-WJ2MYXX4-w_pdEULi.js} +1 -1
  161. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-w_pdEULi.js.br +0 -0
  162. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-w_pdEULi.js.gz +0 -0
  163. package/dist/client/assets/{sizeCapture-INFHLROL-DeLB3S5x.js → sizeCapture-INFHLROL-tqubtbTJ.js} +1 -1
  164. package/dist/client/assets/sizeCapture-INFHLROL-tqubtbTJ.js.br +0 -0
  165. package/dist/client/assets/sizeCapture-INFHLROL-tqubtbTJ.js.gz +0 -0
  166. package/dist/client/assets/{sparkles-BHsBDSo5.js → sparkles-BQVhXL1X.js} +1 -1
  167. package/dist/client/assets/{stateDiagram-D77RDMKH-smIkttxr.js → stateDiagram-D77RDMKH-DFm71XIp.js} +1 -1
  168. package/dist/client/assets/stateDiagram-D77RDMKH-DFm71XIp.js.br +0 -0
  169. package/dist/client/assets/stateDiagram-D77RDMKH-DFm71XIp.js.gz +0 -0
  170. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-aTUiN9r3.js +1 -0
  171. package/dist/client/assets/{swimlanes-42K2YHIH-CVwGuPcK.js → swimlanes-42K2YHIH-Bg6TJPYj.js} +1 -1
  172. package/dist/client/assets/swimlanes-42K2YHIH-Bg6TJPYj.js.br +0 -0
  173. package/dist/client/assets/swimlanes-42K2YHIH-Bg6TJPYj.js.gz +0 -0
  174. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-Bwf9yeLM.js +8 -0
  175. package/dist/client/assets/{timeline-definition-24CTP7MA-Dsn_Rxbd.js → timeline-definition-24CTP7MA-CwrKihuj.js} +1 -1
  176. package/dist/client/assets/timeline-definition-24CTP7MA-CwrKihuj.js.br +0 -0
  177. package/dist/client/assets/timeline-definition-24CTP7MA-CwrKihuj.js.gz +0 -0
  178. package/dist/client/assets/{triangle-alert-DexJX8jR.js → triangle-alert-DZyRaNWe.js} +1 -1
  179. package/dist/client/assets/{vennDiagram-4TSXK5OY-Dtdth9UN.js → vennDiagram-4TSXK5OY-WqUYcege.js} +1 -1
  180. package/dist/client/assets/vennDiagram-4TSXK5OY-WqUYcege.js.br +0 -0
  181. package/dist/client/assets/vennDiagram-4TSXK5OY-WqUYcege.js.gz +0 -0
  182. package/dist/client/assets/{wardleyDiagram-VM6X3IG4-82oGoyOd.js → wardleyDiagram-VM6X3IG4-B7Xfv-yN.js} +1 -1
  183. package/dist/client/assets/wardleyDiagram-VM6X3IG4-B7Xfv-yN.js.br +0 -0
  184. package/dist/client/assets/wardleyDiagram-VM6X3IG4-B7Xfv-yN.js.gz +0 -0
  185. package/dist/client/assets/{xychartDiagram-S5SC5T6Z-Ygu0NbUo.js → xychartDiagram-S5SC5T6Z-BJupQX5U.js} +1 -1
  186. package/dist/client/assets/{xychartDiagram-S5SC5T6Z-Ygu0NbUo.js.br → xychartDiagram-S5SC5T6Z-BJupQX5U.js.br} +0 -0
  187. package/dist/client/assets/xychartDiagram-S5SC5T6Z-BJupQX5U.js.gz +0 -0
  188. package/dist/client/index.html +2 -2
  189. package/dist/client/index.html.br +0 -0
  190. package/dist/client/index.html.gz +0 -0
  191. package/dist/client/sw.js +1 -1
  192. package/dist/client/sw.js.br +0 -0
  193. package/dist/client/sw.js.gz +0 -0
  194. package/dist/server/android/adb.js +154 -0
  195. package/dist/server/android/scrcpy.js +379 -0
  196. package/dist/server/entry.js +9 -1
  197. package/dist/server/federation/runtime.js +29 -4
  198. package/dist/server/routes/android.js +205 -0
  199. package/dist/server/routes/terminal.js +13 -1
  200. package/dist/server/utils/apiAccess.js +3 -1
  201. package/dist/server/utils/settings.js +47 -0
  202. package/package.json +1 -1
  203. package/runtime-manifest.json +3 -3
  204. package/dist/client/assets/App-DA7cQLR7.js.br +0 -0
  205. package/dist/client/assets/App-DA7cQLR7.js.gz +0 -0
  206. package/dist/client/assets/ChangeWalkthroughPanel-vDiLbIdv.js.br +0 -0
  207. package/dist/client/assets/ChangeWalkthroughPanel-vDiLbIdv.js.gz +0 -0
  208. package/dist/client/assets/DagPlayground-BvY_KblL.js.br +0 -0
  209. package/dist/client/assets/DagPlayground-BvY_KblL.js.gz +0 -0
  210. package/dist/client/assets/DiffLab-Dra7cEKx.js.br +0 -0
  211. package/dist/client/assets/DiffLab-Dra7cEKx.js.gz +0 -0
  212. package/dist/client/assets/DiffReview-v9_1IS2n.js.br +0 -0
  213. package/dist/client/assets/DiffReview-v9_1IS2n.js.gz +0 -0
  214. package/dist/client/assets/DiffReviewLab-BF8Dada6.js.br +0 -0
  215. package/dist/client/assets/DiffReviewLab-BF8Dada6.js.gz +0 -0
  216. package/dist/client/assets/DiffViewer-C2s4BXp0.js.br +0 -0
  217. package/dist/client/assets/DiffViewer-C2s4BXp0.js.gz +0 -0
  218. package/dist/client/assets/ModelPreview-D9pzW_YD.js.br +0 -0
  219. package/dist/client/assets/ModelPreview-D9pzW_YD.js.gz +0 -0
  220. package/dist/client/assets/RightSidebar-DL8z6vvJ.js +0 -1678
  221. package/dist/client/assets/RightSidebar-DL8z6vvJ.js.br +0 -0
  222. package/dist/client/assets/RightSidebar-DL8z6vvJ.js.gz +0 -0
  223. package/dist/client/assets/abnfDiagram-VCTEODGH-DVOxqZDY.js.br +0 -0
  224. package/dist/client/assets/abnfDiagram-VCTEODGH-DVOxqZDY.js.gz +0 -0
  225. package/dist/client/assets/app-JK4pM9zv.js.br +0 -0
  226. package/dist/client/assets/app-JK4pM9zv.js.gz +0 -0
  227. package/dist/client/assets/arc-DY_WK1Ln.js.br +0 -0
  228. package/dist/client/assets/arc-DY_WK1Ln.js.gz +0 -0
  229. package/dist/client/assets/architectureDiagram-5GKGNRK7-oyhVtQ5E.js.br +0 -0
  230. package/dist/client/assets/blockDiagram-I7D4REHJ-DTMir8MU.js.br +0 -0
  231. package/dist/client/assets/blockDiagram-I7D4REHJ-DTMir8MU.js.gz +0 -0
  232. package/dist/client/assets/c4Diagram-7LVT6UL2-DpDHYMUW.js.br +0 -0
  233. package/dist/client/assets/c4Diagram-7LVT6UL2-DpDHYMUW.js.gz +0 -0
  234. package/dist/client/assets/channel-cexw6K2f.js +0 -1
  235. package/dist/client/assets/chunk-F27PBJKO-8wDqj2MV.js.br +0 -0
  236. package/dist/client/assets/chunk-F27PBJKO-8wDqj2MV.js.gz +0 -0
  237. package/dist/client/assets/chunk-IMKFNOWR-BnRNosQc.js.br +0 -0
  238. package/dist/client/assets/chunk-IMKFNOWR-BnRNosQc.js.gz +0 -0
  239. package/dist/client/assets/chunk-SVP7TREG-qPD0Q74z.js.br +0 -0
  240. package/dist/client/assets/chunk-SVP7TREG-qPD0Q74z.js.gz +0 -0
  241. package/dist/client/assets/chunk-TICWLB2K-yzLwt_MH.js.br +0 -0
  242. package/dist/client/assets/chunk-TICWLB2K-yzLwt_MH.js.gz +0 -0
  243. package/dist/client/assets/classDiagram-ZZMXUADV-CpjKakYG.js +0 -1
  244. package/dist/client/assets/classDiagram-v2-VYDZK3BY-CpjKakYG.js +0 -1
  245. package/dist/client/assets/cose-bilkent-JH36ORCC-BZyAGO6R.js.br +0 -0
  246. package/dist/client/assets/cose-bilkent-JH36ORCC-BZyAGO6R.js.gz +0 -0
  247. package/dist/client/assets/cynefin-OW5HDTMX-CyrkJWSU.js.br +0 -0
  248. package/dist/client/assets/cynefin-OW5HDTMX-CyrkJWSU.js.gz +0 -0
  249. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-BrqS8ZGX.js.br +0 -0
  250. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-BrqS8ZGX.js.gz +0 -0
  251. package/dist/client/assets/dagre-GXQ25YYZ-ysmdkSNr.js.br +0 -0
  252. package/dist/client/assets/dagre-GXQ25YYZ-ysmdkSNr.js.gz +0 -0
  253. package/dist/client/assets/diagram-S7CK7UJ4-CWSuzX1d.js.br +0 -0
  254. package/dist/client/assets/diagram-S7CK7UJ4-CWSuzX1d.js.gz +0 -0
  255. package/dist/client/assets/diagram-UQ7AKVKN-BMxc5NDd.js.br +0 -0
  256. package/dist/client/assets/diagram-UQ7AKVKN-BMxc5NDd.js.gz +0 -0
  257. package/dist/client/assets/diagram-VSXAHHWV-Cz5KpnGX.js.br +0 -0
  258. package/dist/client/assets/diagram-VSXAHHWV-Cz5KpnGX.js.gz +0 -0
  259. package/dist/client/assets/diagram-VX7I27RA-CNk1h20b.js.br +0 -0
  260. package/dist/client/assets/diagram-VX7I27RA-CNk1h20b.js.gz +0 -0
  261. package/dist/client/assets/diagram-Z3DM3KII-C4lcgl6z.js.br +0 -0
  262. package/dist/client/assets/diagram-Z3DM3KII-C4lcgl6z.js.gz +0 -0
  263. package/dist/client/assets/ebnfDiagram-PWID7BFC-Cwo356mF.js.br +0 -0
  264. package/dist/client/assets/ebnfDiagram-PWID7BFC-Cwo356mF.js.gz +0 -0
  265. package/dist/client/assets/erDiagram-RLTQ6QDP-B4DEocxu.js.br +0 -0
  266. package/dist/client/assets/erDiagram-RLTQ6QDP-B4DEocxu.js.gz +0 -0
  267. package/dist/client/assets/flowDiagram-HODETNUW-CWP3R7jz.js.br +0 -0
  268. package/dist/client/assets/flowDiagram-HODETNUW-CWP3R7jz.js.gz +0 -0
  269. package/dist/client/assets/ganttDiagram-EL5Y4UJY-DBdMWa6L.js.br +0 -0
  270. package/dist/client/assets/ganttDiagram-EL5Y4UJY-DBdMWa6L.js.gz +0 -0
  271. package/dist/client/assets/gestureArbiter-FNHriuhM.js.br +0 -0
  272. package/dist/client/assets/gestureArbiter-FNHriuhM.js.gz +0 -0
  273. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-B6qG6eRT.js.br +0 -0
  274. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-B6qG6eRT.js.gz +0 -0
  275. package/dist/client/assets/index-fjWWhVQp.css.br +0 -0
  276. package/dist/client/assets/ishikawaDiagram-5VMMS53U-Cz8OXUK9.js.br +0 -0
  277. package/dist/client/assets/ishikawaDiagram-5VMMS53U-Cz8OXUK9.js.gz +0 -0
  278. package/dist/client/assets/journeyDiagram-3NMN7TZE-CD4v2_eb.js.br +0 -0
  279. package/dist/client/assets/journeyDiagram-3NMN7TZE-CD4v2_eb.js.gz +0 -0
  280. package/dist/client/assets/kanban-definition-UXKFOSKX-DwLWqTSY.js.br +0 -0
  281. package/dist/client/assets/kanban-definition-UXKFOSKX-DwLWqTSY.js.gz +0 -0
  282. package/dist/client/assets/layout-C1EhlDX0.js.br +0 -0
  283. package/dist/client/assets/layout-C1EhlDX0.js.gz +0 -0
  284. package/dist/client/assets/linear-DQLRPRnN.js.br +0 -0
  285. package/dist/client/assets/linear-DQLRPRnN.js.gz +0 -0
  286. package/dist/client/assets/mermaid.core-BzEGo4OD.js.br +0 -0
  287. package/dist/client/assets/mermaid.core-BzEGo4OD.js.gz +0 -0
  288. package/dist/client/assets/mindmap-definition-YA3MSWOX-Dct8OiDY.js.br +0 -0
  289. package/dist/client/assets/mindmap-definition-YA3MSWOX-Dct8OiDY.js.gz +0 -0
  290. package/dist/client/assets/passwordBootstrap-C7Gy7ATG.js.br +0 -0
  291. package/dist/client/assets/passwordBootstrap-C7Gy7ATG.js.gz +0 -0
  292. package/dist/client/assets/pegDiagram-XKGWAZYB-fIABDYj-.js.br +0 -0
  293. package/dist/client/assets/pegDiagram-XKGWAZYB-fIABDYj-.js.gz +0 -0
  294. package/dist/client/assets/pieDiagram-E7YTZNPT-D2EuLDIj.js.br +0 -0
  295. package/dist/client/assets/pieDiagram-E7YTZNPT-D2EuLDIj.js.gz +0 -0
  296. package/dist/client/assets/quadrantDiagram-AXDQQJYC-BjF42rwO.js.br +0 -0
  297. package/dist/client/assets/quadrantDiagram-AXDQQJYC-BjF42rwO.js.gz +0 -0
  298. package/dist/client/assets/railroadDiagram-O6MQD6OU-DjfSTDvw.js.br +0 -0
  299. package/dist/client/assets/railroadDiagram-O6MQD6OU-DjfSTDvw.js.gz +0 -0
  300. package/dist/client/assets/referenceLongPress-Cz9no5pI.js.br +0 -0
  301. package/dist/client/assets/referenceLongPress-Cz9no5pI.js.gz +0 -0
  302. package/dist/client/assets/requirementDiagram-BXWQKSXE-BewZ62Ou.js.br +0 -0
  303. package/dist/client/assets/requirementDiagram-BXWQKSXE-BewZ62Ou.js.gz +0 -0
  304. package/dist/client/assets/sankeyDiagram-P5KCCOFB-BhlchAkm.js.br +0 -0
  305. package/dist/client/assets/sankeyDiagram-P5KCCOFB-BhlchAkm.js.gz +0 -0
  306. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-CFzratAc.js.br +0 -0
  307. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-CFzratAc.js.gz +0 -0
  308. package/dist/client/assets/sizeCapture-INFHLROL-DeLB3S5x.js.br +0 -0
  309. package/dist/client/assets/sizeCapture-INFHLROL-DeLB3S5x.js.gz +0 -0
  310. package/dist/client/assets/stateDiagram-D77RDMKH-smIkttxr.js.br +0 -0
  311. package/dist/client/assets/stateDiagram-D77RDMKH-smIkttxr.js.gz +0 -0
  312. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-BFDLILuN.js +0 -1
  313. package/dist/client/assets/swimlanes-42K2YHIH-CVwGuPcK.js.br +0 -0
  314. package/dist/client/assets/swimlanes-42K2YHIH-CVwGuPcK.js.gz +0 -0
  315. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-B0Dzvkwg.js +0 -8
  316. package/dist/client/assets/timeline-definition-24CTP7MA-Dsn_Rxbd.js.br +0 -0
  317. package/dist/client/assets/timeline-definition-24CTP7MA-Dsn_Rxbd.js.gz +0 -0
  318. package/dist/client/assets/vennDiagram-4TSXK5OY-Dtdth9UN.js.br +0 -0
  319. package/dist/client/assets/vennDiagram-4TSXK5OY-Dtdth9UN.js.gz +0 -0
  320. package/dist/client/assets/wardleyDiagram-VM6X3IG4-82oGoyOd.js.br +0 -0
  321. package/dist/client/assets/wardleyDiagram-VM6X3IG4-82oGoyOd.js.gz +0 -0
  322. package/dist/client/assets/xychartDiagram-S5SC5T6Z-Ygu0NbUo.js.gz +0 -0
@@ -1,16 +1,16 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/passwordBootstrap-C7Gy7ATG.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/App-DA7cQLR7.js","assets/gestureArbiter-FNHriuhM.js","assets/gestureArbiter-C2J0D0kV.css","assets/triangle-alert-DexJX8jR.js","assets/referenceLongPress-Cz9no5pI.js","assets/DagPlayground-BvY_KblL.js","assets/ChangeWalkthroughPanel-vDiLbIdv.js","assets/sparkles-BHsBDSo5.js","assets/DiffLab-Dra7cEKx.js","assets/DiffViewer-C2s4BXp0.js","assets/DiffViewer-T3uj2-aP.css","assets/DiffReviewLab-BF8Dada6.js","assets/DiffReview-v9_1IS2n.js"])))=>i.map(i=>d[i]);
2
- import{r as _c,a as Rm,g as Cf}from"./react-XDCjal2T.js";import{b as O,R as We,r as Oc}from"./dnd-BCFAPC0L.js";import{L as Tm,l as Pm}from"./terminal-C7X98Amf.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))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 Nm="modulepreload",Lm=function(t){return"/"+t},Wl={},Jt=function(e,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=Lm(l),l in Wl)return;Wl[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":Nm,d||(f.as="script"),f.crossOrigin="",f.href=l,a&&f.setAttribute("nonce",a),document.head.appendChild(f),d)return new Promise((h,g)=>{f.addEventListener("load",h),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${l}`)))})}))}function s(i){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=i,window.dispatchEvent(a),!a.defaultPrevented)throw i}return o.then(i=>{for(const a of i||[])a.status==="rejected"&&s(a.reason);return e().catch(s)})};var Ei={exports:{}},kr={};var Gl;function Bm(){if(Gl)return kr;Gl=1;var t=_c(),e=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function i(a,c,l){var d,u={},f=null,h=null;l!==void 0&&(f=""+l),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(h=c.ref);for(d in c)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:e,type:a,key:f,ref:h,props:u,_owner:o.current}}return kr.Fragment=n,kr.jsx=i,kr.jsxs=i,kr}var Vl;function _m(){return Vl||(Vl=1,Ei.exports=Bm()),Ei.exports}var p=_m();const gn="termdock-secure-target-v1",Dc="termdock-secure-entry-v1",Om=new Set([gn,Dc,"termdock-color-theme","termdock:locale","termdock.federation.connections.v1"]),Io=typeof Storage>"u"?void 0:Storage.prototype.getItem,Ai=typeof Storage>"u"?void 0:Storage.prototype.setItem,Xl="termdock-secure-legacy-owner",Hs=typeof window<"u"&&window.parent!==window&&location.pathname==="/workspace.html";function Dm(){if(typeof window>"u")return null;try{if(Hs){const e=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===e):void 0;return r&&typeof r.url=="string"&&typeof r.targetPeerId=="string"?{...r,serviceName:r.label||r.serviceName}:null}const t=JSON.parse(sessionStorage.getItem(gn)??localStorage.getItem(gn)??"null");return t&&typeof t.url=="string"&&typeof t.targetPeerId=="string"?t:null}catch{return null}}let qs=Dm();const Wn=qs?.targetPeerId??"unpaired";function Fc(){return qs}function Rf(t){if(qs=t,Hs)return;const e=JSON.stringify(t);sessionStorage.setItem(gn,e),localStorage.setItem(gn,e)}function Fm(){qs=null,!Hs&&(localStorage.removeItem(gn),sessionStorage.removeItem(gn),localStorage.removeItem(Dc))}function Xr(t,e=Wn){return Om.has(t)||t.startsWith("termdock-secure-")?t:`termdock-service:${e}:${t}`}function Mm(t){if(!(!Io||!Ai))try{if(Io.call(localStorage,Xl))return;Ai.call(localStorage,Xl,t);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:")||Xr(o,t)===o)continue;const s=Xr(o,t),i=Io.call(n,o);i!==null&&Io.call(n,s)===null&&Ai.call(n,s,i)}}}catch{}}let Yl=!1;function jm(){if(Yl||typeof Storage>"u")return;Yl=!0;const t=Storage.prototype.getItem,e=Storage.prototype.setItem,n=Storage.prototype.removeItem;Storage.prototype.getItem=function(r){return t.call(this,Xr(String(r)))},Storage.prototype.setItem=function(r,o){e.call(this,Xr(String(r)),o)},Storage.prototype.removeItem=function(r){n.call(this,Xr(String(r)))}}jm();const Ks="termdock.federation.connections.v1",Na="termdock:services-changed",Mc="termdock-secure-removed-services",ls=t=>[t.id,t.targetPeerId,t.serviceOrigin||t.url].filter(e=>!!e);function jc(){try{const t=JSON.parse(localStorage.getItem(Mc)||"[]");return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}catch{return[]}}function _e(t){const e=t.trim();if(!e)throw new Error("请输入服务地址。");const n=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(e)?e:`https://${e}`);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 zs(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.url=="string")try{const n=_e(e.url),r=typeof e.targetPeerId=="string"&&e.targetPeerId?e.targetPeerId:void 0,o=(typeof e.label=="string"?e.label:typeof e.serviceName=="string"?e.serviceName:"").trim().slice(0,120)||new URL(n).host;return{id:typeof e.id=="string"&&e.id?e.id:r||n,url:n,label:o,...r?{targetPeerId:r}:{},...typeof e.serviceOrigin=="string"?{serviceOrigin:_e(e.serviceOrigin)}:{},...typeof e.entryServiceId=="string"&&e.entryServiceId?{entryServiceId:e.entryServiceId}:{},...Array.isArray(e.routes)?{routes:e.routes.slice(0,4).flatMap(s=>{try{return s&&typeof s.targetPeerId=="string"&&s.targetPeerId?[{url:_e(s.url),targetPeerId:s.targetPeerId}]:[]}catch{return[]}})}:{}}}catch{return}}function At(t,e){return t.targetPeerId&&e.targetPeerId?t.targetPeerId===e.targetPeerId:(t.serviceOrigin||t.url)===(e.serviceOrigin||e.url)}function Tf(t){const e=[];for(const n of t){const r=e.findIndex(o=>At(o,n));r<0?e.push(n):e[r]={...e[r],...n,id:e[r].id}}return e}function mo(){return typeof window>"u"?void 0:window.termdockDesktop}function mn(){try{const t=JSON.parse(localStorage.getItem(Ks)||"[]");return Array.isArray(t)?Tf(t.map(zs).filter(e=>!!e)):[]}catch{return[]}}function Pf(t){localStorage.setItem(Ks,JSON.stringify(t.map(e=>({...e,serviceName:e.label})))),window.dispatchEvent(new Event(Na))}let Ir;async function Ke(){const t=mo();if(!t?.serviceConnections||!t.saveServiceConnection)return mn();if(Ir)return Ir;Ir=(async()=>{let e=await t.serviceConnections();const n=mn();for(const r of n)e.some(o=>At(o,r))||(e=await(t.importServiceConnection||t.saveServiceConnection)(r));return n.length&&localStorage.removeItem(Ks),e})();try{return await Ir}finally{Ir=void 0}}async function Tt(t){const e=zs(t);if(!e)throw new Error("服务地址无效。");const n=mo();if(n?.saveServiceConnection)return n.saveServiceConnection(e);const r=mn(),o=r.find(a=>a.id===e.id||At(a,e)),s=new Set([...ls(e),...o?ls(o):[]]);localStorage.setItem(Mc,JSON.stringify(jc().filter(a=>!s.has(a))));const i=Tf([...r.filter(a=>a!==o),{...o,...e,id:o?.id||e.id}]);return Pf(i),i}async function Um(t){const e=zs(t);if(!e)throw new Error("服务地址无效。");const n=mo();if(n?.importServiceConnection)return n.importServiceConnection(e);if(n?.serviceConnections){const r=await n.serviceConnections();return r.some(o=>At(o,e))?Tt(e):r}return ls(e).some(r=>jc().includes(r))?mn():Tt(e)}async function $m(t){const e=mo();if(e?.removeServiceConnection)return e.removeServiceConnection(t);const n=mn(),r=n.find(s=>s.id===t);r&&localStorage.setItem(Mc,JSON.stringify([...new Set([...jc(),...ls(r)])].slice(-768)));const o=n.filter(s=>s.id!==t);return Pf(o),o}function Ws(t){const e=r=>{(r.key===Ks||r.key===null)&&t()};window.addEventListener(Na,t),window.addEventListener("storage",e);const n=mo()?.onServiceConnections?.(t);return()=>{window.removeEventListener(Na,t),window.removeEventListener("storage",e),n?.()}}class Hm extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}let qm=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},at=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};class Nf extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class Lf extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}}class Km extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class zm extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class Gs extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}const Bf=Symbol.for("@libp2p/peer-id");function Wm(t){return typeof t?.handleEvent=="function"}function Gm(t){return t===!0||t===!1}function Vm(t){return Gm(t)?t:t?.capture??!1}function La(t){const e={capture:Vm(t),once:!!t?.once};return t?.passive!=null&&(e.passive=t?.passive),t?.signal!=null&&(e.signal=t?.signal),e}function Zl(t,e){return La(t).capture===La(e).capture}class Xm extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const n=this.#e.get(e);return n==null?0:n.length}addEventListener(e,n,r){const o=La(r);if(o?.signal?.aborted===!0)return;const s=l=>{o.once&&this.removeEventListener(e,n,o),Wm(n)?n.handleEvent(l):n(l)};let i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(l=>l.callback!==n?!1:Zl(l.options,o)))return;super.addEventListener(e,s,o);const c=()=>{this.removeEventListener(e,n,o)};o.signal?.addEventListener("abort",c),i.push({callback:n,wrapper:s,options:o,onAbort:c})}removeEventListener(e,n,r){const o=this.#e.get(e);if(o==null){super.removeEventListener(e,n??null,r);return}this.#e.set(e,o.filter(s=>s.callback===n&&Zl(s.options,r)?(super.removeEventListener(e,s.wrapper,r),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,n={}){return this.dispatchEvent(new CustomEvent(e,n))}}const Ym=Symbol.for("@libp2p/service-capabilities");function Zm(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let n=0;n<t.byteLength;n++)if(t[n]!==e[n])return!1;return!0}function Vs(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function Jm(t){return new TextEncoder().encode(t)}function Qm(t){return new TextDecoder().decode(t)}function ew(t,e){if(t.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<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(n[i]!==255)throw new TypeError(s+" is ambiguous");n[i]=o}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var m=0,b=0,w=0,R=g.length;w!==R&&g[w]===0;)w++,m++;for(var y=(R-w)*d+1>>>0,k=new Uint8Array(y);w!==R;){for(var N=g[w],x=0,T=y-1;(N!==0||x<b)&&T!==-1;T--,x++)N+=256*k[T]>>>0,k[T]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");b=x,w++}for(var S=y-b;S!==y&&k[S]===0;)S++;for(var v=c.repeat(m);S<y;++S)v+=t.charAt(k[S]);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,w=0;g[m]===c;)b++,m++;for(var R=(g.length-m)*l+1>>>0,y=new Uint8Array(R);g[m];){var k=n[g.charCodeAt(m)];if(k===255)return;for(var N=0,x=R-1;(k!==0||N<w)&&x!==-1;x--,N++)k+=a*y[x]>>>0,y[x]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");w=N,m++}if(g[m]!==" "){for(var T=R-w;T!==R&&y[T]===0;)T++;for(var S=new Uint8Array(b+(R-T)),v=b;T!==R;)S[v++]=y[T++];return S}}}function h(g){var m=f(g);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:h}}var tw=ew,nw=tw;class rw{name;prefix;baseEncode;constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class ow{name;prefix;baseDecode;prefixCodePoint;constructor(e,n,r){this.name=e,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(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return _f(this,e)}}class sw{decoders;constructor(e){this.decoders=e}or(e){return _f(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r!=null)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function _f(t,e){return new sw({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class iw{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,n,r,o){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=o,this.encoder=new rw(e,n,r),this.decoder=new ow(e,n,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function Xs({name:t,prefix:e,encode:n,decode:r}){return new iw(t,e,n,r)}function wo({name:t,prefix:e,alphabet:n}){const{encode:r,decode:o}=nw(n,t);return Xs({prefix:e,name:t,encode:r,decode:s=>Vs(o(s))})}function aw(t,e,n,r){let o=t.length;for(;t[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=e[t[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 cw(t,e,n){const r=e[e.length-1]==="=",o=(1<<n)-1;let s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>n;)i-=n,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<n-i]),r)for(;(s.length*n&7)!==0;)s+="=";return s}function lw(t){const e={};for(let n=0;n<t.length;++n)e[t[n]]=n;return e}function Te({name:t,prefix:e,bitsPerChar:n,alphabet:r}){const o=lw(r);return Xs({prefix:e,name:t,encode(s){return cw(s,r,n)},decode(s){return aw(s,o,n,t)}})}const Fe=wo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),dw=wo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),uw=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Fe,base58flickr:dw},Symbol.toStringTag,{value:"Module"})),Yr=Te({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),fw=Te({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hw=Te({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pw=Te({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),gw=Te({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),mw=Te({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ww=Te({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),yw=Te({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),bw=Te({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),vw=Object.freeze(Object.defineProperty({__proto__:null,base32:Yr,base32hex:gw,base32hexpad:ww,base32hexpadupper:yw,base32hexupper:mw,base32pad:hw,base32padupper:pw,base32upper:fw,base32z:bw},Symbol.toStringTag,{value:"Module"})),Yo=wo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Sw=wo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),xw=Object.freeze(Object.defineProperty({__proto__:null,base36:Yo,base36upper:Sw},Symbol.toStringTag,{value:"Module"}));var Ew=Of,Jl=128,Aw=-128,kw=Math.pow(2,31);function Of(t,e,n){e=e||[],n=n||0;for(var r=n;t>=kw;)e[n++]=t&255|Jl,t/=128;for(;t&Aw;)e[n++]=t&255|Jl,t>>>=7;return e[n]=t|0,Of.bytes=n-r+1,e}var Iw=Ba,Cw=128,Ql=127;function Ba(t,r){var n=0,r=r||0,o=0,s=r,i,a=t.length;do{if(s>=a)throw Ba.bytes=0,new RangeError("Could not decode varint");i=t[s++],n+=o<28?(i&Ql)<<o:(i&Ql)*Math.pow(2,o),o+=7}while(i>=Cw);return Ba.bytes=s-r,n}var Rw=Math.pow(2,7),Tw=Math.pow(2,14),Pw=Math.pow(2,21),Nw=Math.pow(2,28),Lw=Math.pow(2,35),Bw=Math.pow(2,42),_w=Math.pow(2,49),Ow=Math.pow(2,56),Dw=Math.pow(2,63),Fw=function(t){return t<Rw?1:t<Tw?2:t<Pw?3:t<Nw?4:t<Lw?5:t<Bw?6:t<_w?7:t<Ow?8:t<Dw?9:10},Mw={encode:Ew,decode:Iw,encodingLength:Fw},ds=Mw;function _a(t,e=0){return[ds.decode(t,e),ds.decode.bytes]}function us(t,e,n=0){return ds.encode(t,e,n),e}function fs(t){return ds.encodingLength(t)}function yo(t,e){const n=e.byteLength,r=fs(t),o=r+fs(n),s=new Uint8Array(o+n);return us(t,s,0),us(n,s,r),s.set(e,o),new Uc(t,n,e,s)}function Df(t){const e=Vs(t),[n,r]=_a(e),[o,s]=_a(e.subarray(r)),i=e.subarray(r+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Uc(n,o,i,e)}function jw(t,e){if(t===e)return!0;{const n=e;return t.code===n.code&&t.size===n.size&&n.bytes instanceof Uint8Array&&Zm(t.bytes,n.bytes)}}class Uc{code;size;digest;bytes;constructor(e,n,r,o){this.code=e,this.size=n,this.digest=r,this.bytes=o}}function ed(t,e){const{bytes:n,version:r}=t;return r===0?$w(n,Oa(t),e??Fe.encoder):Hw(n,Oa(t),e??Yr.encoder)}const td=new WeakMap;function Oa(t){const e=td.get(t);if(e==null){const n=new Map;return td.set(t,n),n}return e}class ue{code;version;multihash;bytes;"/";constructor(e,n,r,o){this.code=n,this.version=e,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:e,multihash:n}=this;if(e!==Cr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==qw)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ue.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:e,digest:n}=this.multihash,r=yo(e,n);return ue.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(e){return ue.equals(this,e)}static equals(e,n){const r=n;return r!=null&&e.code===r.code&&e.version===r.version&&jw(e.multihash,r.multihash)}toString(e){return ed(this,e)}toJSON(){return{"/":ed(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;const n=e;if(n instanceof ue)return n;if(n["/"]!=null&&n["/"]===n.bytes||n.asCID===n){const{version:r,code:o,multihash:s,bytes:i}=n;return new ue(r,o,s,i??nd(r,o,s.bytes))}else if(n[Kw]===!0){const{version:r,multihash:o,code:s}=n,i=Df(o);return ue.create(r,s,i)}else return null}static create(e,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(e){case 0:{if(n!==Cr)throw new Error(`Version 0 CID must use dag-pb (code: ${Cr}) block encoding`);return new ue(e,n,r,r.bytes)}case 1:{const o=nd(e,n,r.bytes);return new ue(e,n,r,o)}default:throw new Error("Invalid version")}}static createV0(e){return ue.create(0,Cr,e)}static createV1(e,n){return ue.create(1,e,n)}static decode(e){const[n,r]=ue.decodeFirst(e);if(r.length!==0)throw new Error("Incorrect length");return n}static decodeFirst(e){const n=ue.inspectBytes(e),r=n.size-n.multihashSize,o=Vs(e.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 Uc(n.multihashCode,n.digestSize,s,o);return[n.version===0?ue.createV0(i):ue.createV1(n.codec,i),e.subarray(n.size)]}static inspectBytes(e){let n=0;const r=()=>{const[u,f]=_a(e.subarray(n));return n+=f,u};let o=r(),s=Cr;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(e,n){const[r,o]=Uw(e,n),s=ue.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Oa(s).set(r,e),s}}function Uw(t,e){switch(t[0]){case"Q":{const n=e??Fe;return[Fe.prefix,n.decode(`${Fe.prefix}${t}`)]}case Fe.prefix:{const n=e??Fe;return[Fe.prefix,n.decode(t)]}case Yr.prefix:{const n=e??Yr;return[Yr.prefix,n.decode(t)]}case Yo.prefix:{const n=e??Yo;return[Yo.prefix,n.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function $w(t,e,n){const{prefix:r}=n;if(r!==Fe.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);const o=e.get(r);if(o==null){const s=n.encode(t).slice(1);return e.set(r,s),s}else return o}function Hw(t,e,n){const{prefix:r}=n,o=e.get(r);if(o==null){const s=n.encode(t);return e.set(r,s),s}else return o}const Cr=112,qw=18;function nd(t,e,n){const r=fs(t),o=r+fs(e),s=new Uint8Array(o+n.byteLength);return us(t,s,0),us(e,s,r),s.set(n,o),s}const Kw=Symbol.for("@ipld/js-cid/CID"),Ff=0,zw="identity",Mf=Vs;function Ww(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return yo(Ff,Mf(t))}const bo={code:Ff,name:zw,encode:Mf,digest:Ww};function ct(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let n=0;n<t.byteLength;n++)if(t[n]!==e[n])return!1;return!0}function He(t=0){return new Uint8Array(t)}function Pt(t=0){return new Uint8Array(t)}function Da(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));const n=Pt(e);let r=0;for(const o of t)n.set(o,r),r+=o.length;return n}const jf=Symbol.for("@achingbrain/uint8arraylist");function rd(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let n=0;for(const r of t){const o=n+r.byteLength;if(e<o)return{buf:r,index:e-n};n=o}throw new RangeError("index is out of bounds")}function Co(t){return!!t?.[jf]}class se{bufs;length;[jf]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let n=0;for(const r of e)if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.push(r);else if(Co(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(...e){this.prependAll(e)}prependAll(e){let n=0;for(const r of e.reverse())if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.unshift(r);else if(Co(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(e){const n=rd(this.bufs,e);return n.buf[n.index]}set(e,n){const r=rd(this.bufs,e);r.buf[r.index]=n}write(e,n=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(n+r,e[r]);else if(Co(e))for(let r=0;r<e.length;r++)this.set(n+r,e.get(r));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,n){const{bufs:r,length:o}=this._subList(e,n);return Da(r,o)}subarray(e,n){const{bufs:r,length:o}=this._subList(e,n);return r.length===1?r[0]:Da(r,o)}sublist(e,n){const{bufs:r,length:o}=this._subList(e,n),s=new se;return s.length=o,s.bufs=r,s}_subList(e,n){if(e=e??0,n=n??this.length,e<0&&(e=this.length+e),n<0&&(n=this.length+n),e<0||n>this.length)throw new RangeError("index is out of bounds");if(e===n)return{bufs:[],length:0};if(e===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,e>=c)continue;const l=e>=a&&e<c,d=n>a&&n<=c;if(l&&d){if(e===a&&n===c){r.push(i);break}const u=e-a;r.push(i.subarray(u,u+(n-e)));break}if(l){if(e===0){r.push(i);continue}r.push(i.subarray(e-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-e}}indexOf(e,n=0){if(!Co(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(n=Number(n??0),isNaN(n)&&(n=0),n<0&&(n=this.length+n),n<0&&(n=0),e.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 h=this.get(u+f);if(r[f]!==h){d=Math.max(1,f-a[h]);break}}if(d===0)return u}return-1}getInt8(e){const n=this.subarray(e,e+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt8(0)}setInt8(e,n){const r=Pt(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,n),this.write(r,e)}getInt16(e,n){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,n)}setInt16(e,n,r){const o=He(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,n,r),this.write(o,e)}getInt32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,n)}setInt32(e,n,r){const o=He(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,n,r),this.write(o,e)}getBigInt64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,n)}setBigInt64(e,n,r){const o=He(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,n,r),this.write(o,e)}getUint8(e){const n=this.subarray(e,e+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint8(0)}setUint8(e,n){const r=Pt(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,n),this.write(r,e)}getUint16(e,n){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,n)}setUint16(e,n,r){const o=He(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,n,r),this.write(o,e)}getUint32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,n)}setUint32(e,n,r){const o=He(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,n,r),this.write(o,e)}getBigUint64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,n)}setBigUint64(e,n,r){const o=He(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,n,r),this.write(o,e)}getFloat32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,n)}setFloat32(e,n,r){const o=He(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,n,r),this.write(o,e)}getFloat64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,n)}setFloat64(e,n,r){const o=He(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,n,r),this.write(o,e)}equals(e){if(e==null||!(e instanceof se)||e.bufs.length!==this.bufs.length)return!1;for(let n=0;n<this.bufs.length;n++)if(!ct(this.bufs[n],e.bufs[n]))return!1;return!0}static fromUint8Arrays(e,n){const r=new se;return r.bufs=e,n==null&&(n=e.reduce((o,s)=>o+s.byteLength,0)),r.length=n,r}}const Gw=wo({prefix:"9",name:"base10",alphabet:"0123456789"}),Vw=Object.freeze(Object.defineProperty({__proto__:null,base10:Gw},Symbol.toStringTag,{value:"Module"})),Xw=Te({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Yw=Te({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Zw=Object.freeze(Object.defineProperty({__proto__:null,base16:Xw,base16upper:Yw},Symbol.toStringTag,{value:"Module"})),Jw=Te({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Qw=Object.freeze(Object.defineProperty({__proto__:null,base2:Jw},Symbol.toStringTag,{value:"Module"})),Uf=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),ey=Uf.reduce((t,e,n)=>(t[n]=e,t),[]),ty=Uf.reduce((t,e,n)=>{const r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return t[r]=n,t},[]);function ny(t){return t.reduce((e,n)=>(e+=ey[n],e),"")}function ry(t){const e=[];for(const n of t){const r=n.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${n}`);const o=ty[r];if(o==null)throw new Error(`Non-base256emoji character: ${n}`);e.push(o)}return new Uint8Array(e)}const oy=Xs({prefix:"🚀",name:"base256emoji",encode:ny,decode:ry}),sy=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:oy},Symbol.toStringTag,{value:"Module"})),iy=Te({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ay=Te({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cy=Te({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ly=Te({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),dy=Object.freeze(Object.defineProperty({__proto__:null,base64:iy,base64pad:ay,base64url:cy,base64urlpad:ly},Symbol.toStringTag,{value:"Module"})),uy=Te({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),fy=Object.freeze(Object.defineProperty({__proto__:null,base8:uy},Symbol.toStringTag,{value:"Module"})),hy=Xs({prefix:"\0",name:"identity",encode:t=>Qm(t),decode:t=>Jm(t)}),py=Object.freeze(Object.defineProperty({__proto__:null,identity:hy},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const gy=20;function my({name:t,code:e,encode:n,minDigestLength:r,maxDigestLength:o}){return new wy(t,e,n,r,o)}class wy{name;code;encode;minDigestLength;maxDigestLength;constructor(e,n,r,o,s){this.name=e,this.code=n,this.encode=r,this.minDigestLength=o??gy,this.maxDigestLength=s}digest(e,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(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?od(r,this.code,n?.truncate):r.then(o=>od(o,this.code,n?.truncate))}else throw Error("Unknown type, must be binary type")}}function od(t,e,n){if(n!=null&&n!==t.byteLength){if(n>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,n)}return yo(e,t)}function yy(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}const $c=my({name:"sha2-256",code:18,encode:yy("SHA-256")}),sd={...py,...Qw,...fy,...Vw,...Zw,...vw,...xw,...uw,...dy,...sy};function $f(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const id=$f("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ki=$f("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=Pt(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),Hf={utf8:id,"utf-8":id,hex:sd.base16,latin1:ki,ascii:ki,binary:ki,...sd};function be(t,e="utf8"){const n=Hf[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.decoder.decode(`${n.prefix}${t}`)}function te(t,e="utf8"){const n=Hf[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.encoder.encode(t).substring(1)}const by=parseInt("11111",2),Fa=parseInt("10000000",2),vy=parseInt("01111111",2),ad={0:Rr,1:Rr,2:Sy,3:Ay,4:ky,5:Ey,6:xy,16:Rr,22:Rr,48:Rr};function wr(t,e={offset:0}){const n=t[e.offset]&by;if(e.offset++,ad[n]!=null)return ad[n](t,e);throw new Error("No decoder for tag "+n)}function vo(t,e){let n=0;if((t[e.offset]&Fa)===Fa){const r=t[e.offset]&vy;let o="0x";e.offset++;for(let s=0;s<r;s++,e.offset++)o+=t[e.offset].toString(16).padStart(2,"0");n=parseInt(o,16)}else n=t[e.offset],e.offset++;return n}function Rr(t,e){vo(t,e);const n=[];for(;!(e.offset>=t.byteLength);){const r=wr(t,e);if(r===null)break;n.push(r)}return n}function Sy(t,e){const n=vo(t,e),r=e.offset,o=e.offset+n,s=[];for(let i=r;i<o;i++)i===r&&t[i]===0||s.push(t[i]);return e.offset+=n,Uint8Array.from(s)}function xy(t,e){const n=vo(t,e),r=e.offset+n,o=t[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<r;){const l=t[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let d=0;for(let u=0;u<c.length;u++)d+=c[u]<<u*7;a+=`.${d}`,c=[]}}return a}function Ey(t,e){return e.offset++,null}function Ay(t,e){const n=vo(t,e),r=t[e.offset];e.offset++;const o=t.subarray(e.offset,e.offset+n-1);if(e.offset+=n,r!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function ky(t,e){const n=vo(t,e),r=t.subarray(e.offset,e.offset+n);return e.offset+=n,r}function Iy(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);const n=new se;for(let r=0;r<e.length;r+=2)n.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return n}function Ys(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);const e=Iy(t.byteLength);return new se(Uint8Array.from([e.byteLength|Fa]),e)}function ze(t){const e=new se,n=128;return(t.subarray()[0]&n)===n&&e.append(Uint8Array.from([0])),e.append(t),new se(Uint8Array.from([2]),Ys(e),e)}function Hc(t){const e=Uint8Array.from([0]),n=new se(e,t);return new se(Uint8Array.from([3]),Ys(n),n)}function Cy(t){return new se(Uint8Array.from([4]),Ys(t),t)}function Rt(t,e=48){const n=new se;for(const r of t)n.append(r);return new se(Uint8Array.from([e]),Ys(n),n)}async function Ry(t,e,n){const r=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["sign"]);n?.signal?.throwIfAborted();const o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Ty(t,e,n,r){const o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();const s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,n.subarray());return r?.signal?.throwIfAborted(),s}const Py=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Ny=Uint8Array.from([6,5,43,129,4,0,34]),Ly=Uint8Array.from([6,5,43,129,4,0,35]),qf={ext:!0,kty:"EC",crv:"P-256"},Kf={ext:!0,kty:"EC",crv:"P-384"},zf={ext:!0,kty:"EC",crv:"P-521"},Gn=32,Vn=48,Xn=66;function By(t){const e=wr(t);return _y(e)}function _y(t){const e=t[1],n=te(e,"base64url"),r=t[2][1][0],o=1;let s,i;if(e.byteLength===Gn)return s=te(r.subarray(o,o+Gn),"base64url"),i=te(r.subarray(o+Gn),"base64url"),new Ii({...qf,key_ops:["sign"],d:n,x:s,y:i});if(e.byteLength===Vn)return s=te(r.subarray(o,o+Vn),"base64url"),i=te(r.subarray(o+Vn),"base64url"),new Ii({...Kf,key_ops:["sign"],d:n,x:s,y:i});if(e.byteLength===Xn)return s=te(r.subarray(o,o+Xn),"base64url"),i=te(r.subarray(o+Xn),"base64url"),new Ii({...zf,key_ops:["sign"],d:n,x:s,y:i});throw new at(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function Wf(t){const e=wr(t);return Oy(e)}function Oy(t){const e=t[1][1][0],n=1;let r,o;if(e.byteLength===Gn*2+1)return r=te(e.subarray(n,n+Gn),"base64url"),o=te(e.subarray(n+Gn),"base64url"),new Zo({...qf,key_ops:["verify"],x:r,y:o});if(e.byteLength===Vn*2+1)return r=te(e.subarray(n,n+Vn),"base64url"),o=te(e.subarray(n+Vn),"base64url"),new Zo({...Kf,key_ops:["verify"],x:r,y:o});if(e.byteLength===Xn*2+1)return r=te(e.subarray(n,n+Xn),"base64url"),o=te(e.subarray(n+Xn),"base64url"),new Zo({...zf,key_ops:["verify"],x:r,y:o});throw new at(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Dy(t){return Rt([ze(Uint8Array.from([1])),Cy(be(t.d??"","base64url")),Rt([Gf(t.crv)],160),Rt([Hc(new se(Uint8Array.from([4]),be(t.x??"","base64url"),be(t.y??"","base64url")))],161)]).subarray()}function Fy(t){return Rt([ze(Uint8Array.from([1])),Rt([Gf(t.crv)],160),Rt([Hc(new se(Uint8Array.from([4]),be(t.x??"","base64url"),be(t.y??"","base64url")))],161)]).subarray()}function Gf(t){if(t==="P-256")return Py;if(t==="P-384")return Ny;if(t==="P-521")return Ly;throw new at(`Invalid curve ${t}`)}class Zo{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Fy(this.jwk)),this._raw}toMultihash(){return bo.digest(ni(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return Fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ct(this.raw,e.raw)}async verify(e,n,r){return Ty(this.jwk,n,e,r)}}class Ii{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Zo({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=Dy(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ct(this.raw,e.raw)}async sign(e,n){return Ry(this.jwk,e,n)}}const Bn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function So(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ma(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function xn(t,...e){if(!So(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Vf(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Ma(t.outputLen),Ma(t.blockLen)}function hs(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function My(t,e){xn(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function cr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Ci(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function lt(t,e){return t<<32-e|t>>>e}const Xf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",jy=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function un(t){if(xn(t),Xf)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=jy[t[n]];return e}const yt={_0:48,_9:57,A:65,F:70,a:97,f:102};function cd(t){if(t>=yt._0&&t<=yt._9)return t-yt._0;if(t>=yt.A&&t<=yt.F)return t-(yt.A-10);if(t>=yt.a&&t<=yt.f)return t-(yt.a-10)}function ps(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Xf)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){const i=cd(t.charCodeAt(s)),a=cd(t.charCodeAt(s+1));if(i===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a}return r}function Uy(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function qc(t){return typeof t=="string"&&(t=Uy(t)),xn(t),t}function ft(...t){let e=0;for(let r=0;r<t.length;r++){const o=t[r];xn(o),e+=o.length}const n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){const s=t[r];n.set(s,o),o+=s.length}return n}class Yf{}function Zf(t){const e=r=>t().update(qc(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Kc(t=32){if(Bn&&typeof Bn.getRandomValues=="function")return Bn.getRandomValues(new Uint8Array(t));if(Bn&&typeof Bn.randomBytes=="function")return Uint8Array.from(Bn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function $y(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,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;t.setUint32(e+c,i,r),t.setUint32(e+l,a,r)}function Hy(t,e,n){return t&e^~t&n}function qy(t,e,n){return t&e^t&n^e&n}let Jf=class extends Yf{constructor(e,n,r,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Ci(this.buffer)}update(e){hs(this),e=qc(e),xn(e);const{view:n,buffer:r,blockLen:o}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(o-this.pos,s-i);if(a===o){const c=Ci(e);for(;o<=s-i;i+=o)this.process(c,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){hs(this),My(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:o,isLE:s}=this;let{pos:i}=this;n[i++]=128,cr(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(r,0),i=0);for(let u=i;u<o;u++)n[u]=0;$y(r,o-8,BigInt(this.length*8),s),this.process(r,0);const a=Ci(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};const Ot=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Pe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Ro=BigInt(2**32-1),ld=BigInt(32);function Ky(t,e=!1){return e?{h:Number(t&Ro),l:Number(t>>ld&Ro)}:{h:Number(t>>ld&Ro)|0,l:Number(t&Ro)|0}}function zy(t,e=!1){const n=t.length;let r=new Uint32Array(n),o=new Uint32Array(n);for(let s=0;s<n;s++){const{h:i,l:a}=Ky(t[s],e);[r[s],o[s]]=[i,a]}return[r,o]}const dd=(t,e,n)=>t>>>n,ud=(t,e,n)=>t<<32-n|e>>>n,_n=(t,e,n)=>t>>>n|e<<32-n,On=(t,e,n)=>t<<32-n|e>>>n,To=(t,e,n)=>t<<64-n|e>>>n-32,Po=(t,e,n)=>t>>>n-32|e<<64-n;function bt(t,e,n,r){const o=(e>>>0)+(r>>>0);return{h:t+n+(o/2**32|0)|0,l:o|0}}const Wy=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Gy=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Vy=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Xy=(t,e,n,r,o)=>e+n+r+o+(t/2**32|0)|0,Yy=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Zy=(t,e,n,r,o,s)=>e+n+r+o+s+(t/2**32|0)|0,Jy=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Dt=new Uint32Array(64);class Qy extends Jf{constructor(e=32){super(64,e,8,!1),this.A=Ot[0]|0,this.B=Ot[1]|0,this.C=Ot[2]|0,this.D=Ot[3]|0,this.E=Ot[4]|0,this.F=Ot[5]|0,this.G=Ot[6]|0,this.H=Ot[7]|0}get(){const{A:e,B:n,C:r,D:o,E:s,F:i,G:a,H:c}=this;return[e,n,r,o,s,i,a,c]}set(e,n,r,o,s,i,a,c){this.A=e|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(e,n){for(let u=0;u<16;u++,n+=4)Dt[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const f=Dt[u-15],h=Dt[u-2],g=lt(f,7)^lt(f,18)^f>>>3,m=lt(h,17)^lt(h,19)^h>>>10;Dt[u]=m+Dt[u-7]+g+Dt[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=lt(a,6)^lt(a,11)^lt(a,25),h=d+f+Hy(a,c,l)+Jy[u]+Dt[u]|0,m=(lt(r,2)^lt(r,13)^lt(r,22))+qy(r,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=r,r=h+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(){cr(Dt)}destroy(){this.set(0,0,0,0,0,0,0,0),cr(this.buffer)}}const Qf=zy(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),eb=Qf[0],tb=Qf[1],Ft=new Uint32Array(80),Mt=new Uint32Array(80);class nb extends Jf{constructor(e=64){super(128,e,16,!1),this.Ah=Pe[0]|0,this.Al=Pe[1]|0,this.Bh=Pe[2]|0,this.Bl=Pe[3]|0,this.Ch=Pe[4]|0,this.Cl=Pe[5]|0,this.Dh=Pe[6]|0,this.Dl=Pe[7]|0,this.Eh=Pe[8]|0,this.El=Pe[9]|0,this.Fh=Pe[10]|0,this.Fl=Pe[11]|0,this.Gh=Pe[12]|0,this.Gl=Pe[13]|0,this.Hh=Pe[14]|0,this.Hl=Pe[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:f,Gh:h,Gl:g,Hh:m,Hl:b}=this;return[e,n,r,o,s,i,a,c,l,d,u,f,h,g,m,b]}set(e,n,r,o,s,i,a,c,l,d,u,f,h,g,m,b){this.Ah=e|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=h|0,this.Gl=g|0,this.Hh=m|0,this.Hl=b|0}process(e,n){for(let y=0;y<16;y++,n+=4)Ft[y]=e.getUint32(n),Mt[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){const k=Ft[y-15]|0,N=Mt[y-15]|0,x=_n(k,N,1)^_n(k,N,8)^dd(k,N,7),T=On(k,N,1)^On(k,N,8)^ud(k,N,7),S=Ft[y-2]|0,v=Mt[y-2]|0,A=_n(S,v,19)^To(S,v,61)^dd(S,v,6),_=On(S,v,19)^Po(S,v,61)^ud(S,v,6),B=Vy(T,_,Mt[y-7],Mt[y-16]),I=Xy(B,x,A,Ft[y-7],Ft[y-16]);Ft[y]=I|0,Mt[y]=B|0}let{Ah:r,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:f,Fh:h,Fl:g,Gh:m,Gl:b,Hh:w,Hl:R}=this;for(let y=0;y<80;y++){const k=_n(u,f,14)^_n(u,f,18)^To(u,f,41),N=On(u,f,14)^On(u,f,18)^Po(u,f,41),x=u&h^~u&m,T=f&g^~f&b,S=Yy(R,N,T,tb[y],Mt[y]),v=Zy(S,w,k,x,eb[y],Ft[y]),A=S|0,_=_n(r,o,28)^To(r,o,34)^To(r,o,39),B=On(r,o,28)^Po(r,o,34)^Po(r,o,39),I=r&s^r&a^s&a,E=o&i^o&c^i&c;w=m|0,R=b|0,m=h|0,b=g|0,h=u|0,g=f|0,{h:u,l:f}=bt(l|0,d|0,v|0,A|0),l=a|0,d=c|0,a=s|0,c=i|0,s=r|0,i=o|0;const P=Wy(A,B,E);r=Gy(P,v,_,I),o=P|0}({h:r,l:o}=bt(this.Ah|0,this.Al|0,r|0,o|0)),{h:s,l:i}=bt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=bt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=bt(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:f}=bt(this.Eh|0,this.El|0,u|0,f|0),{h,l:g}=bt(this.Fh|0,this.Fl|0,h|0,g|0),{h:m,l:b}=bt(this.Gh|0,this.Gl|0,m|0,b|0),{h:w,l:R}=bt(this.Hh|0,this.Hl|0,w|0,R|0),this.set(r,o,s,i,a,c,l,d,u,f,h,g,m,b,w,R)}roundClean(){cr(Ft,Mt)}destroy(){cr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const eh=Zf(()=>new Qy),rb=Zf(()=>new nb);const zc=BigInt(0),ja=BigInt(1);function wn(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function it(t,e,n=""){const r=So(t),o=t?.length,s=e!==void 0;if(!r||s&&o!==e){const i=n&&`"${n}" `,a=s?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function No(t){const e=t.toString(16);return e.length&1?"0"+e:e}function th(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?zc:BigInt("0x"+t)}function Zs(t){return th(un(t))}function so(t){return xn(t),th(un(Uint8Array.from(t).reverse()))}function Wc(t,e){return ps(t.toString(16).padStart(e*2,"0"))}function nh(t,e){return Wc(t,e).reverse()}function pe(t,e,n){let r;if(typeof e=="string")try{r=ps(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(So(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const o=r.length;if(typeof n=="number"&&o!==n)throw new Error(t+" of length "+n+" expected, got "+o);return r}function fd(t){return Uint8Array.from(t)}const Ri=t=>typeof t=="bigint"&&zc<=t;function ob(t,e,n){return Ri(t)&&Ri(e)&&Ri(n)&&e<=t&&t<n}function Ua(t,e,n,r){if(!ob(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function rh(t){let e;for(e=0;t>zc;t>>=ja,e+=1);return e}const xo=t=>(ja<<BigInt(t))-ja;function sb(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=h=>new Uint8Array(h),o=h=>Uint8Array.of(h);let s=r(t),i=r(t),a=0;const c=()=>{s.fill(1),i.fill(0),a=0},l=(...h)=>n(i,s,...h),d=(h=r(0))=>{i=l(o(0),h),s=l(),h.length!==0&&(i=l(o(1),h),s=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const g=[];for(;h<e;){s=l();const m=s.slice();g.push(m),h+=s.length}return ft(...g)};return(h,g)=>{c(),d(h);let m;for(;!(m=g(u()));)d();return c(),m}}function Eo(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(o,s,i){const a=t[o];if(i&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([o,s])=>r(o,s,!1)),Object.entries(n).forEach(([o,s])=>r(o,s,!0))}function gs(t){const e=new WeakMap;return(n,...r)=>{const o=e.get(n);if(o!==void 0)return o;const s=t(n,...r);return e.set(n,s),s}}const qe=BigInt(0),Re=BigInt(1),on=BigInt(2),oh=BigInt(3),sh=BigInt(4),ih=BigInt(5),ib=BigInt(7),ah=BigInt(8),ab=BigInt(9),ch=BigInt(16);function ve(t,e){const n=t%e;return n>=qe?n:e+n}function he(t,e,n){let r=t;for(;e-- >qe;)r*=r,r%=n;return r}function hd(t,e){if(t===qe)throw new Error("invert: expected non-zero number");if(e<=qe)throw new Error("invert: expected positive modulus, got "+e);let n=ve(t,e),r=e,o=qe,s=Re;for(;n!==qe;){const a=r/n,c=r%n,l=o-s*a;r=n,n=c,o=s,s=l}if(r!==Re)throw new Error("invert: does not exist");return ve(o,e)}function Gc(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function lh(t,e){const n=(t.ORDER+Re)/sh,r=t.pow(e,n);return Gc(t,r,e),r}function cb(t,e){const n=(t.ORDER-ih)/ah,r=t.mul(e,on),o=t.pow(r,n),s=t.mul(e,o),i=t.mul(t.mul(s,on),o),a=t.mul(s,t.sub(i,t.ONE));return Gc(t,a,e),a}function lb(t){const e=En(t),n=dh(t),r=n(e,e.neg(e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+ib)/ch;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),h=a.eql(a.sqr(d),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,d,h),d=a.cmov(f,u,g);const m=a.eql(a.sqr(d),c),b=a.cmov(l,d,m);return Gc(a,b,c),b}}function dh(t){if(t<oh)throw new Error("sqrt is not defined for small field");let e=t-Re,n=0;for(;e%on===qe;)e/=on,n++;let r=on;const o=En(t);for(;pd(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return lh;let s=o.pow(r,e);const i=(e+Re)/on;return function(c,l){if(c.is0(l))return l;if(pd(c,l)!==1)throw new Error("Cannot find square root");let d=n,u=c.mul(c.ONE,s),f=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let g=1,m=c.sqr(f);for(;!c.eql(m,c.ONE);)if(g++,m=c.sqr(m),g===d)throw new Error("Cannot find square root");const b=Re<<BigInt(d-g-1),w=c.pow(u,b);d=g,u=c.sqr(w),f=c.mul(f,u),h=c.mul(h,w)}return h}}function db(t){return t%sh===oh?lh:t%ah===ih?cb:t%ch===ab?lb(t):dh(t)}const ub=(t,e)=>(ve(t,e)&Re)===Re,fb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hb(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=fb.reduce((r,o)=>(r[o]="function",r),e);return Eo(t,n),t}function pb(t,e,n){if(n<qe)throw new Error("invalid exponent, negatives unsupported");if(n===qe)return t.ONE;if(n===Re)return e;let r=t.ONE,o=e;for(;n>qe;)n&Re&&(r=t.mul(r,o)),o=t.sqr(o),n>>=Re;return r}function uh(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),o=e.reduce((i,a,c)=>t.is0(a)?i:(r[c]=i,t.mul(i,a)),t.ONE),s=t.inv(o);return e.reduceRight((i,a,c)=>t.is0(a)?i:(r[c]=t.mul(i,r[c]),t.mul(i,a)),s),r}function pd(t,e){const n=(t.ORDER-Re)/on,r=t.pow(e,n),o=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),i=t.eql(r,t.neg(t.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function fh(t,e){e!==void 0&&Ma(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function En(t,e,n=!1,r={}){if(t<=qe)throw new Error("invalid field: expected ORDER > 0, got "+t);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const f=e;f.BITS&&(o=f.BITS),f.sqrt&&(s=f.sqrt),typeof f.isLE=="boolean"&&(n=f.isLE),typeof f.modFromBytes=="boolean"&&(i=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(o=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:l}=fh(t,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:l,MASK:xo(c),ZERO:qe,ONE:Re,allowedLengths:a,create:f=>ve(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return qe<=f&&f<t},is0:f=>f===qe,isValidNot0:f=>!u.is0(f)&&u.isValid(f),isOdd:f=>(f&Re)===Re,neg:f=>ve(-f,t),eql:(f,h)=>f===h,sqr:f=>ve(f*f,t),add:(f,h)=>ve(f+h,t),sub:(f,h)=>ve(f-h,t),mul:(f,h)=>ve(f*h,t),pow:(f,h)=>pb(u,f,h),div:(f,h)=>ve(f*hd(h,t),t),sqrN:f=>f*f,addN:(f,h)=>f+h,subN:(f,h)=>f-h,mulN:(f,h)=>f*h,inv:f=>hd(f,t),sqrt:s||(f=>(d||(d=db(t)),d(u,f))),toBytes:f=>n?nh(f,l):Wc(f,l),fromBytes:(f,h=!0)=>{if(a){if(!a.includes(f.length)||f.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);const m=new Uint8Array(l);m.set(f,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?so(f):Zs(f);if(i&&(g=ve(g,t)),!h&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:f=>uh(u,f),cmov:(f,h,g)=>g?h:f});return Object.freeze(u)}function hh(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function ph(t){const e=hh(t);return e+Math.ceil(e/2)}function gb(t,e,n=!1){const r=t.length,o=hh(e),s=ph(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const i=n?so(t):Zs(t),a=ve(i,e-Re)+Re;return n?nh(a,o):Wc(a,o)}const lr=BigInt(0),sn=BigInt(1);function ms(t,e){const n=e.negate();return t?n:e}function an(t,e){const n=uh(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function gh(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ti(t,e){gh(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,s=xo(t),i=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function gd(t,e,n){const{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n;let a=Number(t&o),c=t>>i;a>r&&(a-=s,c+=sn);const l=e*r,d=l+Math.abs(a)-1,u=a===0,f=a<0,h=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:f,isNegF:h,offsetF:l}}function mb(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function wb(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const Pi=new WeakMap,mh=new WeakMap;function Ni(t){return mh.get(t)||1}function md(t){if(t!==lr)throw new Error("invalid wNAF")}class wh{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>lr;)n&sn&&(r=r.add(o)),o=o.double(),n>>=sn;return r}precomputeWindow(e,n){const{windows:r,windowSize:o}=Ti(n,this.bits),s=[];let i=e,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(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE;const i=Ti(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:f,offsetF:h}=gd(r,a,i);r=c,d?s=s.add(ms(f,n[h])):o=o.add(ms(u,n[l]))}return md(r),{p:o,f:s}}wNAFUnsafe(e,n,r,o=this.ZERO){const s=Ti(e,this.bits);for(let i=0;i<s.windows&&r!==lr;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=gd(r,i,s);if(r=a,!l){const u=n[c];o=o.add(d?u.negate():u)}}return md(r),o}getPrecomputes(e,n,r){let o=Pi.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Pi.set(n,o))),o}cached(e,n,r){const o=Ni(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){const s=Ni(e);return s===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,o)}createCache(e,n){gh(n,this.bits),mh.set(e,n),Pi.delete(e)}hasCache(e){return Ni(e)!==1}}function yb(t,e,n,r){let o=e,s=t.ZERO,i=t.ZERO;for(;n>lr||r>lr;)n&sn&&(s=s.add(o)),r&sn&&(i=i.add(o)),o=o.double(),n>>=sn,r>>=sn;return{p1:s,p2:i}}function yh(t,e,n,r){mb(n,t),wb(r,e);const o=n.length,s=r.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,a=rh(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=xo(c),d=new Array(Number(l)+1).fill(i),u=Math.floor((e.BITS-1)/c)*c;let f=i;for(let h=u;h>=0;h-=c){d.fill(i);for(let m=0;m<s;m++){const b=r[m],w=Number(b>>BigInt(h)&l);d[w]=d[w].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),h!==0)for(let m=0;m<c;m++)f=f.double()}return f}function wd(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return hb(e),e}else return En(t,{isLE:n})}function bh(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>lr))throw new Error(`CURVE.${c} must be positive bigint`)}const o=wd(e.p,n.Fp,r),s=wd(e.n,n.Fn,r),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}const jt=BigInt(0),Se=BigInt(1),Li=BigInt(2),bb=BigInt(8);function vb(t,e,n,r){const o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function Sb(t,e={}){const n=bh("edwards",t,e,e.FpFnLE),{Fp:r,Fn:o}=n;let s=n.CURVE;const{h:i}=s;Eo(e,{},{uvRatio:"function"});const a=Li<<BigInt(o.BYTES*8)-Se,c=b=>r.create(b),l=e.uvRatio||((b,w)=>{try{return{isValid:!0,value:r.sqrt(r.div(b,w))}}catch{return{isValid:!1,value:jt}}});if(!vb(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(b,w,R=!1){const y=R?Se:jt;return Ua("coordinate "+b,w,y,a),w}function u(b){if(!(b instanceof g))throw new Error("ExtendedPoint expected")}const f=gs((b,w)=>{const{X:R,Y:y,Z:k}=b,N=b.is0();w==null&&(w=N?bb:r.inv(k));const x=c(R*w),T=c(y*w),S=r.mul(k,w);if(N)return{x:jt,y:Se};if(S!==Se)throw new Error("invZ was invalid");return{x,y:T}}),h=gs(b=>{const{a:w,d:R}=s;if(b.is0())throw new Error("bad point: ZERO");const{X:y,Y:k,Z:N,T:x}=b,T=c(y*y),S=c(k*k),v=c(N*N),A=c(v*v),_=c(T*w),B=c(v*c(_+S)),I=c(A+c(R*c(T*S)));if(B!==I)throw new Error("bad point: equation left != right (1)");const E=c(y*k),P=c(N*x);if(E!==P)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(w,R,y,k){this.X=d("x",w),this.Y=d("y",R),this.Z=d("z",y,!0),this.T=d("t",k),Object.freeze(this)}static CURVE(){return s}static fromAffine(w){if(w instanceof g)throw new Error("extended point not allowed");const{x:R,y}=w||{};return d("x",R),d("y",y),new g(R,y,Se,c(R*y))}static fromBytes(w,R=!1){const y=r.BYTES,{a:k,d:N}=s;w=fd(it(w,y,"point")),wn(R,"zip215");const x=fd(w),T=w[y-1];x[y-1]=T&-129;const S=so(x),v=R?a:r.ORDER;Ua("point.y",S,jt,v);const A=c(S*S),_=c(A-Se),B=c(N*A-k);let{isValid:I,value:E}=l(_,B);if(!I)throw new Error("bad point: invalid y coordinate");const P=(E&Se)===Se,C=(T&128)!==0;if(!R&&E===jt&&C)throw new Error("bad point: x=0 and x_0=1");return C!==P&&(E=c(-E)),g.fromAffine({x:E,y:S})}static fromHex(w,R=!1){return g.fromBytes(pe("point",w),R)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,R=!0){return m.createCache(this,w),R||this.multiply(Li),this}assertValidity(){h(this)}equals(w){u(w);const{X:R,Y:y,Z:k}=this,{X:N,Y:x,Z:T}=w,S=c(R*T),v=c(N*k),A=c(y*T),_=c(x*k);return S===v&&A===_}is0(){return this.equals(g.ZERO)}negate(){return new g(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:w}=s,{X:R,Y:y,Z:k}=this,N=c(R*R),x=c(y*y),T=c(Li*c(k*k)),S=c(w*N),v=R+y,A=c(c(v*v)-N-x),_=S+x,B=_-T,I=S-x,E=c(A*B),P=c(_*I),C=c(A*I),D=c(B*_);return new g(E,P,D,C)}add(w){u(w);const{a:R,d:y}=s,{X:k,Y:N,Z:x,T}=this,{X:S,Y:v,Z:A,T:_}=w,B=c(k*S),I=c(N*v),E=c(T*y*_),P=c(x*A),C=c((k+N)*(S+v)-B-I),D=P-E,M=P+E,F=c(I-R*B),L=c(C*D),$=c(M*F),H=c(C*F),U=c(D*M);return new g(L,$,U,H)}subtract(w){return this.add(w.negate())}multiply(w){if(!o.isValidNot0(w))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:R,f:y}=m.cached(this,w,k=>an(g,k));return an(g,[R,y])[0]}multiplyUnsafe(w,R=g.ZERO){if(!o.isValid(w))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return w===jt?g.ZERO:this.is0()||w===Se?this:m.unsafe(this,w,y=>an(g,y),R)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(w){return f(this,w)}clearCofactor(){return i===Se?this:this.multiplyUnsafe(i)}toBytes(){const{x:w,y:R}=this.toAffine(),y=r.toBytes(R);return y[y.length-1]|=w&Se?128:0,y}toHex(){return un(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(w){return an(g,w)}static msm(w,R){return yh(g,o,w,R)}_setWindowSize(w){this.precompute(w)}toRawBytes(){return this.toBytes()}}g.BASE=new g(s.Gx,s.Gy,Se,c(s.Gx*s.Gy)),g.ZERO=new g(jt,Se,Se,jt),g.Fp=r,g.Fn=o;const m=new wh(g,o.BITS);return g.BASE.precompute(8),g}function xb(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is required');Eo(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:o,Fp:s,Fn:i}=t,a=n.randomBytes||Kc,c=n.adjustScalarBytes||(v=>v),l=n.domain||((v,A,_)=>{if(wn(_,"phflag"),A.length||_)throw new Error("Contexts/pre-hash are not supported");return v});function d(v){return i.create(so(v))}function u(v){const A=y.secretKey;v=pe("private key",v,A);const _=pe("hashed private key",e(v),2*A),B=c(_.slice(0,A)),I=_.slice(A,2*A),E=d(B);return{head:B,prefix:I,scalar:E}}function f(v){const{head:A,prefix:_,scalar:B}=u(v),I=o.multiply(B),E=I.toBytes();return{head:A,prefix:_,scalar:B,point:I,pointBytes:E}}function h(v){return f(v).pointBytes}function g(v=Uint8Array.of(),...A){const _=ft(...A);return d(e(l(_,pe("context",v),!!r)))}function m(v,A,_={}){v=pe("message",v),r&&(v=r(v));const{prefix:B,scalar:I,pointBytes:E}=f(A),P=g(_.context,B,v),C=o.multiply(P).toBytes(),D=g(_.context,C,E,v),M=i.create(P+D*I);if(!i.isValid(M))throw new Error("sign failed: invalid s");const F=ft(C,i.toBytes(M));return it(F,y.signature,"result")}const b={zip215:!0};function w(v,A,_,B=b){const{context:I,zip215:E}=B,P=y.signature;v=pe("signature",v,P),A=pe("message",A),_=pe("publicKey",_,y.publicKey),E!==void 0&&wn(E,"zip215"),r&&(A=r(A));const C=P/2,D=v.subarray(0,C),M=so(v.subarray(C,P));let F,L,$;try{F=t.fromBytes(_,E),L=t.fromBytes(D,E),$=o.multiplyUnsafe(M)}catch{return!1}if(!E&&F.isSmallOrder())return!1;const H=g(I,L.toBytes(),F.toBytes(),A);return L.add(F.multiplyUnsafe(H)).subtract($).clearCofactor().is0()}const R=s.BYTES,y={secretKey:R,publicKey:R,signature:2*R,seed:R};function k(v=a(y.seed)){return it(v,y.seed,"seed")}function N(v){const A=S.randomSecretKey(v);return{secretKey:A,publicKey:h(A)}}function x(v){return So(v)&&v.length===i.BYTES}function T(v,A){try{return!!t.fromBytes(v,A)}catch{return!1}}const S={getExtendedPublicKey:f,randomSecretKey:k,isValidSecretKey:x,isValidPublicKey:T,toMontgomery(v){const{y:A}=t.fromBytes(v),_=y.publicKey,B=_===32;if(!B&&_!==57)throw new Error("only defined for 25519 and 448");const I=B?s.div(Se+A,Se-A):s.div(A-Se,A+Se);return s.toBytes(I)},toMontgomerySecret(v){const A=y.secretKey;it(v,A);const _=e(v.subarray(0,A));return c(_).subarray(0,A)},randomPrivateKey:k,precompute(v=8,A=t.BASE){return A.precompute(v,!1)}};return Object.freeze({keygen:N,getPublicKey:h,sign:m,verify:w,utils:S,Point:t,lengths:y})}function Eb(t){const e={a:t.a,d:t.d,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp,r=En(e.n,t.nBitLength,!0),o={Fp:n,Fn:r,uvRatio:t.uvRatio},s={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:o,hash:t.hash,eddsaOpts:s}}function Ab(t,e){const n=e.Point;return Object.assign({},e,{ExtendedPoint:n,CURVE:t,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function kb(t){const{CURVE:e,curveOpts:n,hash:r,eddsaOpts:o}=Eb(t),s=Sb(e,n),i=xb(s,r,o);return Ab(t,i)}const Ib=BigInt(1),yd=BigInt(2);BigInt(3);const Cb=BigInt(5),Rb=BigInt(8),Vc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),vh={p:Vc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Rb,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Tb(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=Vc,a=t*t%s*t%s,c=he(a,yd,s)*a%s,l=he(c,Ib,s)*t%s,d=he(l,Cb,s)*l%s,u=he(d,e,s)*d%s,f=he(u,n,s)*u%s,h=he(f,r,s)*f%s,g=he(h,o,s)*h%s,m=he(g,o,s)*h%s,b=he(m,e,s)*d%s;return{pow_p_5_8:he(b,yd,s)*t%s,b2:a}}function Pb(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const bd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Nb(t,e){const n=Vc,r=ve(e*e*e,n),o=ve(r*r*e,n),s=Tb(t*o).pow_p_5_8;let i=ve(t*r*s,n);const a=ve(e*i*i,n),c=i,l=ve(i*bd,n),d=a===t,u=a===ve(-t,n),f=a===ve(-t*bd,n);return d&&(i=c),(u||f)&&(i=l),ub(i,n)&&(i=ve(-i,n)),{isValid:d||u,value:i}}const Lb=En(vh.p,{isLE:!0}),Bb={...vh,Fp:Lb,hash:rb,adjustScalarBytes:Pb,uvRatio:Nb},ws=kb(Bb);class vd extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}}class Sd extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class _b extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}const Nt={get(t=globalThis){const e=t.crypto;if(e?.subtle==null)throw new _b("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}},ys=32,St=64,$a=32;let Yn;const Sh=(async()=>{try{return await Nt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Ob(){const t=ws.utils.randomPrivateKey(),e=ws.getPublicKey(t);return{privateKey:Hb(t,e),publicKey:e}}async function Db(t,e){let n;t.length===St?n=t.subarray(0,32):n=t;const r={crv:"Ed25519",kty:"OKP",x:te(t.subarray(32),"base64url"),d:te(n,"base64url"),ext:!0,key_ops:["sign"]},o=await Nt.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),s=await Nt.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function Fb(t,e){const n=t.subarray(0,$a);return ws.sign(e instanceof Uint8Array?e:e.subarray(),n)}async function Mb(t,e){return Yn==null&&(Yn=await Sh),Yn?Db(t,e):Fb(t,e)}async function jb(t,e,n){if(t.buffer instanceof ArrayBuffer){const r=await Nt.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await Nt.get().subtle.verify({name:"Ed25519"},r,e,n instanceof Uint8Array?n:n.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Ub(t,e,n){return ws.verify(e,n instanceof Uint8Array?n:n.subarray(),t)}async function $b(t,e,n){return Yn==null&&(Yn=await Sh),Yn?jb(t,e,n):Ub(t,e,n)}function Hb(t,e){const n=new Uint8Array(St);for(let r=0;r<$a;r++)n[r]=t[r],n[$a+r]=e[r];return n}function Js(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}class xh{type="Ed25519";raw;constructor(e){this.raw=io(e,ys)}toMultihash(){return bo.digest(ni(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return Fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ct(this.raw,e.raw)}verify(e,n,r){r?.signal?.throwIfAborted();const o=$b(this.raw,n,e);return Js(o)?o.then(s=>(r?.signal?.throwIfAborted(),s)):o}}class Ha{type="Ed25519";raw;publicKey;constructor(e,n){this.raw=io(e,St),this.publicKey=new xh(n)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ct(this.raw,e.raw)}sign(e,n){n?.signal?.throwIfAborted();const r=Mb(this.raw,e);return Js(r)?r.then(o=>(n?.signal?.throwIfAborted(),o)):(n?.signal?.throwIfAborted(),r)}}function qb(t){if(t.length>St){t=io(t,St+ys);const r=t.subarray(0,St),o=t.subarray(St,t.length);return new Ha(r,o)}t=io(t,St);const e=t.subarray(0,St),n=t.subarray(ys);return new Ha(e,n)}function Eh(t){return t=io(t,ys),new xh(t)}async function Kb(){const{privateKey:t,publicKey:e}=Ob();return new Ha(t,e)}function io(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new at(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}const zb=Math.pow(2,7),Wb=Math.pow(2,14),Gb=Math.pow(2,21),Xc=Math.pow(2,28),Yc=Math.pow(2,35),Zc=Math.pow(2,42),Jc=Math.pow(2,49),oe=128,Ne=127;function An(t){if(t<zb)return 1;if(t<Wb)return 2;if(t<Gb)return 3;if(t<Xc)return 4;if(t<Yc)return 5;if(t<Zc)return 6;if(t<Jc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ah(t,e,n=0){switch(An(t)){case 8:e[n++]=t&255|oe,t/=128;case 7:e[n++]=t&255|oe,t/=128;case 6:e[n++]=t&255|oe,t/=128;case 5:e[n++]=t&255|oe,t/=128;case 4:e[n++]=t&255|oe,t>>>=7;case 3:e[n++]=t&255|oe,t>>>=7;case 2:e[n++]=t&255|oe,t>>>=7;case 1:{e[n++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Vb(t,e,n=0){switch(An(t)){case 8:e.set(n++,t&255|oe),t/=128;case 7:e.set(n++,t&255|oe),t/=128;case 6:e.set(n++,t&255|oe),t/=128;case 5:e.set(n++,t&255|oe),t/=128;case 4:e.set(n++,t&255|oe),t>>>=7;case 3:e.set(n++,t&255|oe),t>>>=7;case 2:e.set(n++,t&255|oe),t>>>=7;case 1:{e.set(n++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function kh(t,e){let n=t[e],r=0;if(r+=n&Ne,n<oe||(n=t[e+1],r+=(n&Ne)<<7,n<oe)||(n=t[e+2],r+=(n&Ne)<<14,n<oe)||(n=t[e+3],r+=(n&Ne)<<21,n<oe)||(n=t[e+4],r+=(n&Ne)*Xc,n<oe)||(n=t[e+5],r+=(n&Ne)*Yc,n<oe)||(n=t[e+6],r+=(n&Ne)*Zc,n<oe)||(n=t[e+7],r+=(n&Ne)*Jc,n<oe))return r;throw new RangeError("Could not decode varint")}function Xb(t,e){let n=t.get(e),r=0;if(r+=n&Ne,n<oe||(n=t.get(e+1),r+=(n&Ne)<<7,n<oe)||(n=t.get(e+2),r+=(n&Ne)<<14,n<oe)||(n=t.get(e+3),r+=(n&Ne)<<21,n<oe)||(n=t.get(e+4),r+=(n&Ne)*Xc,n<oe)||(n=t.get(e+5),r+=(n&Ne)*Yc,n<oe)||(n=t.get(e+6),r+=(n&Ne)*Zc,n<oe)||(n=t.get(e+7),r+=(n&Ne)*Jc,n<oe))return r;throw new RangeError("Could not decode varint")}function Yb(t,e,n=0){return e==null&&(e=Pt(An(t))),e instanceof Uint8Array?Ah(t,e,n):Vb(t,e,n)}function Ih(t,e=0){return t instanceof Uint8Array?kh(t,e):Xb(t,e)}const Qc=new Float32Array([-0]),Vt=new Uint8Array(Qc.buffer);function Zb(t,e,n){Qc[0]=t,e[n]=Vt[0],e[n+1]=Vt[1],e[n+2]=Vt[2],e[n+3]=Vt[3]}function Jb(t,e){return Vt[0]=t[e],Vt[1]=t[e+1],Vt[2]=t[e+2],Vt[3]=t[e+3],Qc[0]}const el=new Float64Array([-0]),Le=new Uint8Array(el.buffer);function Qb(t,e,n){el[0]=t,e[n]=Le[0],e[n+1]=Le[1],e[n+2]=Le[2],e[n+3]=Le[3],e[n+4]=Le[4],e[n+5]=Le[5],e[n+6]=Le[6],e[n+7]=Le[7]}function e0(t,e){return Le[0]=t[e],Le[1]=t[e+1],Le[2]=t[e+2],Le[3]=t[e+3],Le[4]=t[e+4],Le[5]=t[e+5],Le[6]=t[e+6],Le[7]=t[e+7],el[0]}const t0=BigInt(Number.MAX_SAFE_INTEGER),n0=BigInt(Number.MIN_SAFE_INTEGER);class Be{lo;hi;constructor(e,n){this.lo=e|0,this.hi=n|0}toNumber(e=!1){if(!e&&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(e=!1){if(e)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(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,n=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?n===0?e<16384?e<128?1:2:e<2097152?3:4:n<16384?n<128?5:6:n<2097152?7:8:r<128?9:10}static fromBigInt(e){if(e===0n)return fn;if(e<t0&&e>n0)return this.fromNumber(Number(e));const n=e<0n;n&&(e=-e);let r=e>>32n,o=e-(r<<32n);return n&&(r=~r|0n,o=~o|0n,++o>xd&&(o=0n,++r>xd&&(r=0n))),new Be(Number(o),Number(r))}static fromNumber(e){if(e===0)return fn;const n=e<0;n&&(e=-e);let r=e>>>0,o=(e-r)/4294967296>>>0;return n&&(o=~o>>>0,r=~r>>>0,++r>4294967295&&(r=0,++o>4294967295&&(o=0))),new Be(r,o)}static from(e){return typeof e=="number"?Be.fromNumber(e):typeof e=="bigint"?Be.fromBigInt(e):typeof e=="string"?Be.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new Be(e.low>>>0,e.high>>>0):fn}}const fn=new Be(0,0);fn.toBigInt=function(){return 0n};fn.zzEncode=fn.zzDecode=function(){return this};fn.length=function(){return 1};const xd=4294967296n;function r0(t){let e=0,n=0;for(let r=0;r<t.length;++r)n=t.charCodeAt(r),n<128?e+=1:n<2048?e+=2:(n&64512)===55296&&(t.charCodeAt(r+1)&64512)===56320?(++r,e+=4):e+=3;return e}function o0(t,e,n){if(n-e<1)return"";let o;const s=[];let i=0,a;for(;e<n;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Ch(t,e,n){const r=n;let o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[n++]=o:o<2048?(e[n++]=o>>6|192,e[n++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[n++]=o>>18|240,e[n++]=o>>12&63|128,e[n++]=o>>6&63|128,e[n++]=o&63|128):(e[n++]=o>>12|224,e[n++]=o>>6&63|128,e[n++]=o&63|128);return n-r}function rt(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function Lo(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}class s0{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,rt(this,10);return e}int32(){return this.uint32()|0}sint32(){const e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw rt(this,4);return Lo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw rt(this,4);return Lo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw rt(this,4);const e=Jb(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw rt(this,4);const e=e0(this.buf,this.pos);return this.pos+=8,e}bytes(){const e=this.uint32(),n=this.pos,r=this.pos+e;if(r>this.len)throw rt(this,e);return this.pos+=e,n===r?new Uint8Array(0):this.buf.subarray(n,r)}string(){const e=this.bytes();return o0(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw rt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw rt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new Be(0,0);let n=0;if(this.len-this.pos>4){for(;n<4;++n)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<n*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;n=0}else{for(;n<3;++n){if(this.pos>=this.len)throw rt(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<n*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<n*7)>>>0,e}if(this.len-this.pos>4){for(;n<5;++n)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<n*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;n<5;++n){if(this.pos>=this.len)throw rt(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<n*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw rt(this,8);const e=Lo(this.buf,this.pos+=4),n=Lo(this.buf,this.pos+=4);return new Be(e,n)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=kh(this.buf,this.pos);return this.pos+=An(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function i0(t){return new s0(t instanceof Uint8Array?t:t.subarray())}function Qs(t,e,n){const r=i0(t);return e.decode(r,void 0,n)}function a0(t){let r,o=8192;return function(i){if(i<1||i>4096)return Pt(i);o+i>8192&&(r=Pt(8192),o=0);const a=r.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}class Kr{fn;len;next;val;constructor(e,n,r){this.fn=e,this.len=n,this.next=void 0,this.val=r}}function Bi(){}class c0{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const l0=a0();function d0(t){return globalThis.Buffer!=null?Pt(t):l0(t)}class qa{len;head;tail;states;constructor(){this.len=0,this.head=new Kr(Bi,0,0),this.tail=this.head,this.states=null}_push(e,n,r){return this.tail=this.tail.next=new Kr(e,n,r),this.len+=n,this}uint32(e){return this.len+=(this.tail=this.tail.next=new f0((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Bo,10,Be.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const n=Be.fromBigInt(e);return this._push(Bo,n.length(),n)}uint64Number(e){return this._push(Ah,An(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const n=Be.fromBigInt(e).zzEncode();return this._push(Bo,n.length(),n)}sint64Number(e){const n=Be.fromNumber(e).zzEncode();return this._push(Bo,n.length(),n)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(_i,1,e?1:0)}fixed32(e){return this._push(Tr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const n=Be.fromBigInt(e);return this._push(Tr,4,n.lo)._push(Tr,4,n.hi)}fixed64Number(e){const n=Be.fromNumber(e);return this._push(Tr,4,n.lo)._push(Tr,4,n.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Zb,4,e)}double(e){return this._push(Qb,8,e)}bytes(e){const n=e.length>>>0;return n===0?this._push(_i,1,0):this.uint32(n)._push(h0,n,e)}string(e){const n=r0(e);return n!==0?this.uint32(n)._push(Ch,n,e):this._push(_i,1,0)}fork(){return this.states=new c0(this),this.head=this.tail=new Kr(Bi,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 Kr(Bi,0,0),this.len=0),this}ldelim(){const e=this.head,n=this.tail,r=this.len;return this.reset().uint32(r),r!==0&&(this.tail.next=e.next,this.tail=n,this.len+=r),this}finish(){let e=this.head.next;const n=d0(this.len);let r=0;for(;e!=null;)e.fn(e.val,n,r),r+=e.len,e=e.next;return n}}function _i(t,e,n){e[n]=t&255}function u0(t,e,n){for(;t>127;)e[n++]=t&127|128,t>>>=7;e[n]=t}class f0 extends Kr{next;constructor(e,n){super(u0,e,n),this.next=void 0}}function Bo(t,e,n){for(;t.hi!==0;)e[n++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[n++]=t.lo&127|128,t.lo=t.lo>>>7;e[n++]=t.lo}function Tr(t,e,n){e[n]=t&255,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}function h0(t,e,n){e.set(t,n)}globalThis.Buffer!=null&&(qa.prototype.bytes=function(t){const e=t.length>>>0;return this.uint32(e),e>0&&this._push(p0,e,t),this},qa.prototype.string=function(t){const e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(g0,e,t),this});function p0(t,e,n){e.set(t,n)}function g0(t,e,n){t.length<40?Ch(t,e,n):e.utf8Write!=null?e.utf8Write(t,n):e.set(be(t),n)}function m0(){return new qa}function ei(t,e){const n=m0();return e.encode(t,n,{lengthDelimited:!1}),n.finish()}var bs;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(bs||(bs={}));function Rh(t,e,n,r){return{name:t,type:e,encode:n,decode:r}}function w0(t){function e(o){if(t[o.toString()]==null)throw new Error("Invalid enum value");return t[o]}const n=function(s,i){const a=e(s);i.int32(a)},r=function(s){const i=s.int32();return e(i)};return Rh("enum",bs.VARINT,n,r)}function ti(t,e){return Rh("message",bs.LENGTH_DELIMITED,t,e)}class Ed extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var fe;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(fe||(fe={}));var Ka;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(Ka||(Ka={}));(function(t){t.codec=()=>w0(Ka)})(fe||(fe={}));var yn;(function(t){let e;t.codec=()=>(e==null&&(e=ti((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),fe.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=fe.codec().decode(n);break}case 2:{s.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>ei(n,t.codec()),t.decode=(n,r)=>Qs(n,t.codec(),r)})(yn||(yn={}));var vs;(function(t){let e;t.codec=()=>(e==null&&(e=ti((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),fe.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=fe.codec().decode(n);break}case 2:{s.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>ei(n,t.codec()),t.decode=(n,r)=>Qs(n,t.codec(),r)})(vs||(vs={}));const Th=eh;class Ph{type="RSA";jwk;_raw;_multihash;constructor(e,n){this.jwk=e,this._multihash=n}get raw(){return this._raw==null&&(this._raw=Lh(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ue.createV1(114,this._multihash)}toString(){return Fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ct(this.raw,e.raw)}verify(e,n,r){return L0(this.jwk,n,e,r)}}class y0{type="RSA";jwk;_raw;publicKey;constructor(e,n){this.jwk=e,this.publicKey=n}get raw(){return this._raw==null&&(this._raw=E0(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ct(this.raw,e.raw)}sign(e,n){return N0(this.jwk,e,n)}}const b0=8192,Nh=18,v0=1062,S0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function x0(t){return{n:te(t[1],"base64url"),e:te(t[2],"base64url"),d:te(t[3],"base64url"),p:te(t[4],"base64url"),q:te(t[5],"base64url"),dp:te(t[6],"base64url"),dq:te(t[7],"base64url"),qi:te(t[8],"base64url"),kty:"RSA"}}function E0(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new at("JWK was missing components");return Rt([ze(Uint8Array.from([0])),ze(be(t.n,"base64url")),ze(be(t.e,"base64url")),ze(be(t.d,"base64url")),ze(be(t.p,"base64url")),ze(be(t.q,"base64url")),ze(be(t.dp,"base64url")),ze(be(t.dq,"base64url")),ze(be(t.qi,"base64url"))]).subarray()}function A0(t){const e=wr(t[1],{offset:0});return{kty:"RSA",n:te(e[0],"base64url"),e:te(e[1],"base64url")}}function Lh(t){if(t.n==null||t.e==null)throw new at("JWK was missing components");return Rt([S0,Hc(Rt([ze(be(t.n,"base64url")),ze(be(t.e,"base64url"))]))]).subarray()}function k0(t){const e=wr(t);return I0(e)}function I0(t){const e=x0(t);return T0(e)}function C0(t,e){if(t.byteLength>=v0)throw new Nf("Key size is too large");const n=wr(t,{offset:0});return R0(n,t,e)}function R0(t,e,n){const r=A0(t);if(n==null){const o=Th(yn.encode({Type:fe.RSA,Data:e}));n=yo(Nh,o)}return new Ph(r,n)}function T0(t){if(B0(t)>b0)throw new at("Key size is too large");const e=P0(t),n=Th(yn.encode({Type:fe.RSA,Data:Lh(e.publicKey)})),r=yo(Nh,n);return new y0(e.privateKey,new Ph(e.publicKey,r))}function P0(t){if(t==null)throw new at("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function N0(t,e,n){const r=await Nt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);n?.signal?.throwIfAborted();const o=await Nt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function L0(t,e,n,r){const o=await Nt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const s=await Nt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,n instanceof Uint8Array?n:n.subarray());return r?.signal?.throwIfAborted(),s}function B0(t){if(t.kty!=="RSA")throw new at("invalid key type");if(t.n==null)throw new at("invalid key modulus");return be(t.n,"base64url").length*8}class Bh extends Yf{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,Vf(e);const r=qc(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const o=this.blockLen,s=new Uint8Array(o);s.set(r.length>o?e.create().update(r).digest():r);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),cr(s)}update(e){return hs(this),this.iHash.update(e),this}digestInto(e){hs(this),xn(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const _h=(t,e,n)=>new Bh(t,e).update(n).digest();_h.create=(t,e)=>new Bh(t,e);const Ad=(t,e)=>(t+(t>=0?e:-e)/Oh)/e;function _0(t,e,n){const[[r,o],[s,i]]=e,a=Ad(i*t,n),c=Ad(-o*t,n);let l=t-a*r-c*s,d=-a*o-c*i;const u=l<kt,f=d<kt;u&&(l=-l),f&&(d=-d);const h=xo(Math.ceil(rh(n)/2))+Zn;if(l<kt||l>=h||d<kt||d>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:f,k2:d}}function za(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Oi(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return wn(n.lowS,"lowS"),wn(n.prehash,"prehash"),n.format!==void 0&&za(n.format),n}class O0 extends Error{constructor(e=""){super(e)}}const xt={Err:O0,_tlv:{encode:(t,e)=>{const{Err:n}=xt;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,o=No(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?No(o.length/2|128):"";return No(t)+s+o+e},decode(t,e){const{Err:n}=xt;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const o=e[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=e.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=e.subarray(r,r+i);if(a.length!==i)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+i)}}},_int:{encode(t){const{Err:e}=xt;if(t<kt)throw new e("integer: negative integers are not allowed");let n=No(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=xt;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Zs(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=xt,o=pe("signature",t),{v:s,l:i}=r.decode(48,o);if(i.length)throw new e("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 e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){const{_tlv:e,_int:n}=xt,r=e.encode(2,n.encode(t.r)),o=e.encode(2,n.encode(t.s)),s=r+o;return e.encode(48,s)}},kt=BigInt(0),Zn=BigInt(1),Oh=BigInt(2),_o=BigInt(3),D0=BigInt(4);function qn(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let o=pe("private key",e);try{r=t.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function F0(t,e={}){const n=bh("weierstrass",t,e),{Fp:r,Fn:o}=n;let s=n.CURVE;const{h:i,n:a}=s;Eo(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;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=Fh(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(B,I,E){const{x:P,y:C}=I.toAffine(),D=r.toBytes(P);if(wn(E,"isCompressed"),E){d();const M=!r.isOdd(C);return ft(Dh(M),D)}else return ft(Uint8Array.of(4),D,r.toBytes(C))}function f(B){it(B,void 0,"Point");const{publicKey:I,publicKeyUncompressed:E}=l,P=B.length,C=B[0],D=B.subarray(1);if(P===I&&(C===2||C===3)){const M=r.fromBytes(D);if(!r.isValid(M))throw new Error("bad point: is not on curve, wrong x");const F=m(M);let L;try{L=r.sqrt(F)}catch(U){const q=U instanceof Error?": "+U.message:"";throw new Error("bad point: is not on curve, sqrt error"+q)}d();const $=r.isOdd(L);return(C&1)===1!==$&&(L=r.neg(L)),{x:M,y:L}}else if(P===E&&C===4){const M=r.BYTES,F=r.fromBytes(D.subarray(0,M)),L=r.fromBytes(D.subarray(M,M*2));if(!b(F,L))throw new Error("bad point: is not on curve");return{x:F,y:L}}else throw new Error(`bad point: got length ${P}, expected compressed=${I} or uncompressed=${E}`)}const h=e.toBytes||u,g=e.fromBytes||f;function m(B){const I=r.sqr(B),E=r.mul(I,B);return r.add(r.add(E,r.mul(B,s.a)),s.b)}function b(B,I){const E=r.sqr(I),P=m(B);return r.eql(E,P)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const w=r.mul(r.pow(s.a,_o),D0),R=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(w,R)))throw new Error("bad curve params: a or b");function y(B,I,E=!1){if(!r.isValid(I)||E&&r.is0(I))throw new Error(`bad point coordinate ${B}`);return I}function k(B){if(!(B instanceof v))throw new Error("ProjectivePoint expected")}function N(B){if(!c||!c.basises)throw new Error("no endo");return _0(B,c.basises,o.ORDER)}const x=gs((B,I)=>{const{X:E,Y:P,Z:C}=B;if(r.eql(C,r.ONE))return{x:E,y:P};const D=B.is0();I==null&&(I=D?r.ONE:r.inv(C));const M=r.mul(E,I),F=r.mul(P,I),L=r.mul(C,I);if(D)return{x:r.ZERO,y:r.ZERO};if(!r.eql(L,r.ONE))throw new Error("invZ was invalid");return{x:M,y:F}}),T=gs(B=>{if(B.is0()){if(e.allowInfinityPoint&&!r.is0(B.Y))return;throw new Error("bad point: ZERO")}const{x:I,y:E}=B.toAffine();if(!r.isValid(I)||!r.isValid(E))throw new Error("bad point: x or y not field elements");if(!b(I,E))throw new Error("bad point: equation left != right");if(!B.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(B,I,E,P,C){return E=new v(r.mul(E.X,B),E.Y,E.Z),I=ms(P,I),E=ms(C,E),I.add(E)}class v{constructor(I,E,P){this.X=y("x",I),this.Y=y("y",E,!0),this.Z=y("z",P),Object.freeze(this)}static CURVE(){return s}static fromAffine(I){const{x:E,y:P}=I||{};if(!I||!r.isValid(E)||!r.isValid(P))throw new Error("invalid affine point");if(I instanceof v)throw new Error("projective point not allowed");return r.is0(E)&&r.is0(P)?v.ZERO:new v(E,P,r.ONE)}static fromBytes(I){const E=v.fromAffine(g(it(I,void 0,"point")));return E.assertValidity(),E}static fromHex(I){return v.fromBytes(pe("pointHex",I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,E=!0){return _.createCache(this,I),E||this.multiply(_o),this}assertValidity(){T(this)}hasEvenY(){const{y:I}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(I)}equals(I){k(I);const{X:E,Y:P,Z:C}=this,{X:D,Y:M,Z:F}=I,L=r.eql(r.mul(E,F),r.mul(D,C)),$=r.eql(r.mul(P,F),r.mul(M,C));return L&&$}negate(){return new v(this.X,r.neg(this.Y),this.Z)}double(){const{a:I,b:E}=s,P=r.mul(E,_o),{X:C,Y:D,Z:M}=this;let F=r.ZERO,L=r.ZERO,$=r.ZERO,H=r.mul(C,C),U=r.mul(D,D),q=r.mul(M,M),K=r.mul(C,D);return K=r.add(K,K),$=r.mul(C,M),$=r.add($,$),F=r.mul(I,$),L=r.mul(P,q),L=r.add(F,L),F=r.sub(U,L),L=r.add(U,L),L=r.mul(F,L),F=r.mul(K,F),$=r.mul(P,$),q=r.mul(I,q),K=r.sub(H,q),K=r.mul(I,K),K=r.add(K,$),$=r.add(H,H),H=r.add($,H),H=r.add(H,q),H=r.mul(H,K),L=r.add(L,H),q=r.mul(D,M),q=r.add(q,q),H=r.mul(q,K),F=r.sub(F,H),$=r.mul(q,U),$=r.add($,$),$=r.add($,$),new v(F,L,$)}add(I){k(I);const{X:E,Y:P,Z:C}=this,{X:D,Y:M,Z:F}=I;let L=r.ZERO,$=r.ZERO,H=r.ZERO;const U=s.a,q=r.mul(s.b,_o);let K=r.mul(E,D),X=r.mul(P,M),z=r.mul(C,F),W=r.add(E,P),G=r.add(D,M);W=r.mul(W,G),G=r.add(K,X),W=r.sub(W,G),G=r.add(E,C);let Y=r.add(D,F);return G=r.mul(G,Y),Y=r.add(K,z),G=r.sub(G,Y),Y=r.add(P,C),L=r.add(M,F),Y=r.mul(Y,L),L=r.add(X,z),Y=r.sub(Y,L),H=r.mul(U,G),L=r.mul(q,z),H=r.add(L,H),L=r.sub(X,H),H=r.add(X,H),$=r.mul(L,H),X=r.add(K,K),X=r.add(X,K),z=r.mul(U,z),G=r.mul(q,G),X=r.add(X,z),z=r.sub(K,z),z=r.mul(U,z),G=r.add(G,z),K=r.mul(X,G),$=r.add($,K),K=r.mul(Y,G),L=r.mul(W,L),L=r.sub(L,K),K=r.mul(W,X),H=r.mul(Y,H),H=r.add(H,K),new v(L,$,H)}subtract(I){return this.add(I.negate())}is0(){return this.equals(v.ZERO)}multiply(I){const{endo:E}=e;if(!o.isValidNot0(I))throw new Error("invalid scalar: out of range");let P,C;const D=M=>_.cached(this,M,F=>an(v,F));if(E){const{k1neg:M,k1:F,k2neg:L,k2:$}=N(I),{p:H,f:U}=D(F),{p:q,f:K}=D($);C=U.add(K),P=S(E.beta,H,q,M,L)}else{const{p:M,f:F}=D(I);P=M,C=F}return an(v,[P,C])[0]}multiplyUnsafe(I){const{endo:E}=e,P=this;if(!o.isValid(I))throw new Error("invalid scalar: out of range");if(I===kt||P.is0())return v.ZERO;if(I===Zn)return P;if(_.hasCache(this))return this.multiply(I);if(E){const{k1neg:C,k1:D,k2neg:M,k2:F}=N(I),{p1:L,p2:$}=yb(v,P,D,F);return S(E.beta,L,$,C,M)}else return _.unsafe(P,I)}multiplyAndAddUnsafe(I,E,P){const C=this.multiplyUnsafe(E).add(I.multiplyUnsafe(P));return C.is0()?void 0:C}toAffine(I){return x(this,I)}isTorsionFree(){const{isTorsionFree:I}=e;return i===Zn?!0:I?I(v,this):_.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:I}=e;return i===Zn?this:I?I(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(I=!0){return wn(I,"isCompressed"),this.assertValidity(),h(v,this,I)}toHex(I=!0){return un(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(I=!0){return this.toBytes(I)}_setWindowSize(I){this.precompute(I)}static normalizeZ(I){return an(v,I)}static msm(I,E){return yh(v,o,I,E)}static fromPrivateKey(I){return v.BASE.multiply(qn(o,I))}}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 A=o.BITS,_=new wh(v,e.endo?Math.ceil(A/2):A);return v.BASE.precompute(8),v}function Dh(t){return Uint8Array.of(t?2:3)}function Fh(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function M0(t,e={}){const{Fn:n}=t,r=e.randomBytes||Kc,o=Object.assign(Fh(t.Fp,n),{seed:ph(n.ORDER)});function s(h){try{return!!qn(n,h)}catch{return!1}}function i(h,g){const{publicKey:m,publicKeyUncompressed:b}=o;try{const w=h.length;return g===!0&&w!==m||g===!1&&w!==b?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=r(o.seed)){return gb(it(h,o.seed,"seed"),n.ORDER)}function c(h,g=!0){return t.BASE.multiply(qn(n,h)).toBytes(g)}function l(h){const g=a(h);return{secretKey:g,publicKey:c(g)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:g,publicKey:m,publicKeyUncompressed:b}=o;if(n.allowedLengths||g===m)return;const w=pe("key",h).length;return w===m||w===b}function u(h,g,m=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(g)===!1)throw new Error("second arg must be public key");const b=qn(n,h);return t.fromHex(g).multiply(b).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>qn(n,h),precompute(h=8,g=t.BASE){return g.precompute(h,!1)}},lengths:o})}function j0(t,e,n={}){Vf(e),Eo(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Kc,o=n.hmac||((E,...P)=>_h(e,E,ft(...P))),{Fp:s,Fn:i}=t,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h}=M0(t,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function b(E){const P=a>>Zn;return E>P}function w(E,P){if(!i.isValidNot0(P))throw new Error(`invalid signature ${E}: out of range 1..Point.Fn.ORDER`);return P}function R(E,P){za(P);const C=h.signature,D=P==="compact"?C:P==="recovered"?C+1:void 0;return it(E,D,`${P} signature`)}class y{constructor(P,C,D){this.r=w("r",P),this.s=w("s",C),D!=null&&(this.recovery=D),Object.freeze(this)}static fromBytes(P,C=m){R(P,C);let D;if(C==="der"){const{r:$,s:H}=xt.toSig(it(P));return new y($,H)}C==="recovered"&&(D=P[0],C="compact",P=P.subarray(1));const M=i.BYTES,F=P.subarray(0,M),L=P.subarray(M,M*2);return new y(i.fromBytes(F),i.fromBytes(L),D)}static fromHex(P,C){return this.fromBytes(ps(P),C)}addRecoveryBit(P){return new y(this.r,this.s,P)}recoverPublicKey(P){const C=s.ORDER,{r:D,s:M,recovery:F}=this;if(F==null||![0,1,2,3].includes(F))throw new Error("recovery id invalid");if(a*Oh<C&&F>1)throw new Error("recovery id is ambiguous for h>1 curve");const $=F===2||F===3?D+a:D;if(!s.isValid($))throw new Error("recovery id 2 or 3 invalid");const H=s.toBytes($),U=t.fromBytes(ft(Dh((F&1)===0),H)),q=i.inv($),K=N(pe("msgHash",P)),X=i.create(-K*q),z=i.create(M*q),W=t.BASE.multiplyUnsafe(X).add(U.multiplyUnsafe(z));if(W.is0())throw new Error("point at infinify");return W.assertValidity(),W}hasHighS(){return b(this.s)}toBytes(P=m){if(za(P),P==="der")return ps(xt.hexFromSig(this));const C=i.toBytes(this.r),D=i.toBytes(this.s);if(P==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return ft(Uint8Array.of(this.recovery),C,D)}return ft(C,D)}toHex(P){return un(this.toBytes(P))}assertValidity(){}static fromCompact(P){return y.fromBytes(pe("sig",P),"compact")}static fromDER(P){return y.fromBytes(pe("sig",P),"der")}normalizeS(){return this.hasHighS()?new y(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return un(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return un(this.toBytes("compact"))}}const k=n.bits2int||function(P){if(P.length>8192)throw new Error("input is too large");const C=Zs(P),D=P.length*8-c;return D>0?C>>BigInt(D):C},N=n.bits2int_modN||function(P){return i.create(k(P))},x=xo(c);function T(E){return Ua("num < 2^"+c,E,kt,x),i.toBytes(E)}function S(E,P){return it(E,void 0,"message"),P?it(e(E),void 0,"prehashed message"):E}function v(E,P,C){if(["recovered","canonical"].some(X=>X in C))throw new Error("sign() legacy options not supported");const{lowS:D,prehash:M,extraEntropy:F}=Oi(C,g);E=S(E,M);const L=N(E),$=qn(i,P),H=[T($),T(L)];if(F!=null&&F!==!1){const X=F===!0?r(h.secretKey):F;H.push(pe("extraEntropy",X))}const U=ft(...H),q=L;function K(X){const z=k(X);if(!i.isValidNot0(z))return;const W=i.inv(z),G=t.BASE.multiply(z).toAffine(),Y=i.create(G.x);if(Y===kt)return;const Q=i.create(W*i.create(q+Y*$));if(Q===kt)return;let ae=(G.x===Y?0:2)|Number(G.y&Zn),ce=Q;return D&&b(Q)&&(ce=i.neg(Q),ae^=1),new y(Y,ce,ae)}return{seed:U,k2sig:K}}function A(E,P,C={}){E=pe("message",E);const{seed:D,k2sig:M}=v(E,P,C);return sb(e.outputLen,i.BYTES,o)(D,M)}function _(E){let P;const C=typeof E=="string"||So(E),D=!C&&E!==null&&typeof E=="object"&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!C&&!D)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(D)P=new y(E.r,E.s);else if(C){try{P=y.fromBytes(pe("sig",E),"der")}catch(M){if(!(M instanceof xt.Err))throw M}if(!P)try{P=y.fromBytes(pe("sig",E),"compact")}catch{return!1}}return P||!1}function B(E,P,C,D={}){const{lowS:M,prehash:F,format:L}=Oi(D,g);if(C=pe("publicKey",C),P=S(pe("message",P),F),"strict"in D)throw new Error("options.strict was renamed to lowS");const $=L===void 0?_(E):y.fromBytes(pe("sig",E),L);if($===!1)return!1;try{const H=t.fromBytes(C);if(M&&$.hasHighS())return!1;const{r:U,s:q}=$,K=N(P),X=i.inv(q),z=i.create(K*X),W=i.create(U*X),G=t.BASE.multiplyUnsafe(z).add(H.multiplyUnsafe(W));return G.is0()?!1:i.create(G.x)===U}catch{return!1}}function I(E,P,C={}){const{prehash:D}=Oi(C,g);return P=S(P,D),y.fromBytes(E,"recovered").recoverPublicKey(P).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h,Point:t,sign:A,verify:B,recoverPublicKey:I,Signature:y,hash:e})}function U0(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp;let r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0;const o=En(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),s={Fp:n,Fn:o,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function $0(t){const{CURVE:e,curveOpts:n}=U0(t),r={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,hash:t.hash,ecdsaOpts:r}}function H0(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,fh(n.Fn.ORDER,n.Fn.BITS))})}function q0(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:o}=$0(t),s=F0(e,n),i=j0(s,r,o);return H0(t,i)}function K0(t,e){const n=r=>q0({...t,hash:r});return{...n(e),create:n}}const tl={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},z0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},kd=BigInt(2);function W0(t){const e=tl.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,u=he(d,n,e)*d%e,f=he(u,n,e)*d%e,h=he(f,kd,e)*l%e,g=he(h,o,e)*h%e,m=he(g,s,e)*g%e,b=he(m,a,e)*m%e,w=he(b,c,e)*b%e,R=he(w,a,e)*m%e,y=he(R,n,e)*d%e,k=he(y,i,e)*g%e,N=he(k,r,e)*l%e,x=he(N,kd,e);if(!Wa.eql(Wa.sqr(x),t))throw new Error("Cannot find square root");return x}const Wa=En(tl.p,{sqrt:W0}),Yt=K0({...tl,Fp:Wa,lowS:!0,endo:z0},eh);function G0(t,e,n){const r=$c.digest(e instanceof Uint8Array?e:e.subarray());if(Js(r))return r.then(({digest:o})=>(n?.signal?.throwIfAborted(),Yt.sign(o,t).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new vd(String(o))});try{return Yt.sign(r.digest,t).toDERRawBytes()}catch(o){throw new vd(String(o))}}function V0(t,e,n,r){const o=$c.digest(n instanceof Uint8Array?n:n.subarray());if(Js(o))return o.then(({digest:s})=>(r?.signal?.throwIfAborted(),Yt.verify(e,s,t))).catch(s=>{throw s.name==="AbortError"?s:new Sd(String(s))});try{return r?.signal?.throwIfAborted(),Yt.verify(e,o.digest,t)}catch(s){throw new Sd(String(s))}}class Mh{type="secp256k1";raw;_key;constructor(e){this._key=Q0(e),this.raw=Z0(this._key)}toMultihash(){return bo.digest(ni(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return Fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ct(this.raw,e.raw)}verify(e,n,r){return V0(this._key,n,e,r)}}class X0{type="secp256k1";raw;publicKey;constructor(e,n){this.raw=J0(e),this.publicKey=new Mh(n??ev(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ct(this.raw,e.raw)}sign(e,n){return G0(this.raw,e,n)}}function Y0(t){return new X0(t)}function jh(t){return new Mh(t)}function Z0(t){return Yt.ProjectivePoint.fromHex(t).toRawBytes(!0)}function J0(t){try{return Yt.getPublicKey(t,!0),t}catch(e){throw new Lf(String(e))}}function Q0(t){try{return Yt.ProjectivePoint.fromHex(t),t}catch(e){throw new Nf(String(e))}}function ev(t){try{return Yt.getPublicKey(t,!0)}catch(e){throw new Lf(String(e))}}async function tv(t,e){return Kb()}function Ga(t,e){const{Type:n,Data:r}=yn.decode(t),o=r??new Uint8Array;switch(n){case fe.RSA:return C0(o,e);case fe.Ed25519:return Eh(o);case fe.secp256k1:return jh(o);case fe.ECDSA:return Wf(o);default:throw new Gs}}function nv(t){const{Type:e,Data:n}=yn.decode(t.digest),r=n??new Uint8Array;switch(e){case fe.Ed25519:return Eh(r);case fe.secp256k1:return jh(r);case fe.ECDSA:return Wf(r);default:throw new Gs}}function ni(t){return yn.encode({Type:fe[t.type],Data:t.raw})}function rv(t){const e=vs.decode(t),n=e.Data??new Uint8Array;switch(e.Type){case fe.RSA:return k0(n);case fe.Ed25519:return qb(n);case fe.secp256k1:return Y0(n);case fe.ECDSA:return By(n);default:throw new Gs}}function ov(t){return vs.encode({Type:fe[t.type],Data:t.raw})}const Uh=Symbol.for("nodejs.util.inspect.custom"),sv=114;class nl{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Bf]=!0;toString(){return this.string==null&&(this.string=Fe.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ue.createV1(sv,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ct(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ct(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Uh](){return`PeerId(${this.toString()})`}}class $h extends nl{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class Hh extends nl{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class qh extends nl{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}const iv=2336;class Kh{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=bo.digest(be(this.url))}[Uh](){return`PeerId(${this.url})`}[Bf]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ue.createV1(iv,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=te(e)),e.toString()===this.toString())}}const av=114,Id=2336;function cv(t,e){let n;if(t.charAt(0)==="1"||t.charAt(0)==="Q")n=Df(Fe.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return lv(ue.parse(t));throw new at('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return zh(n)}function dr(t){if(t.type==="Ed25519")return new Hh({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new qh({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new $h({multihash:t.toCID().multihash,publicKey:t});throw new Gs}function zh(t){if(uv(t))return new $h({multihash:t});if(dv(t))try{const e=nv(t);if(e.type==="Ed25519")return new Hh({multihash:t,publicKey:e});if(e.type==="secp256k1")return new qh({multihash:t,publicKey:e})}catch{const n=te(t.digest);return new Kh(new URL(n))}throw new zm("Supplied PeerID Multihash is invalid")}function lv(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==av&&t.code!==Id)throw new Km("Supplied PeerID CID is invalid");if(t.code===Id){const e=te(t.multihash.digest);return new Kh(new URL(e))}return zh(t.multihash)}function dv(t){return t.code===bo.code}function uv(t){return t.code===$c.code}class Wh extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class fv extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class Pr extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class Cd extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}}class hv extends Event{data;constructor(e,n){super("message",n),this.data=e}}class rl extends Event{error;local;constructor(e,n,r){super("close",r),this.error=n,this.local=e}}class pv extends rl{constructor(e,n){super(!0,e,n)}}class gv extends rl{constructor(e,n){super(!1,e,n)}}const mv=t=>t/2**32|0,wv=t=>t>>>0;function yv(t,e,n,r){const o=mv(n),s=wv(n);t.setUint32(e,r?s:o,r),t.setUint32(e+4,r?o:s,r)}function Va(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const Xa=t=>t?`"${t}" `:"";function Lt(t,e=""){if(typeof t!="number")throw new TypeError(Xa(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(Xa(e)+"expected integer >= 0, got "+t);return t}function Bt(t,e,n=""){if(Va(t)&&(e===void 0||t.length===e))return t;e!==void 0&&Lt(e,"length");const r=Va(t),o=e!==void 0?` of length ${e}`:"",s=r?`length=${t.length}`:`type=${typeof t}`,i=Xa(n)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}function ol(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Lt(t.outputLen),Lt(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}const bv=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)},Rd=(t,e)=>{bv(t,e);const n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function Ss(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function Gh(t,e){Bt(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function nR(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function hn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Di(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function dt(t,e){return t<<32-e|t>>>e}function rR(t,e){return t<<e|t>>>32-e>>>0}const vv=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Sv(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function xv(t){for(let e=0;e<t.length;e++)t[e]=Sv(t[e]);return t}const oR=vv?t=>t:xv,Vh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ev=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function sl(t){if(Bt(t),Vh)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Ev[t[n]];return e}function Td(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function Xh(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Vh)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}const e=t.length,n=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){const i=Td(t.charCodeAt(s)),a=Td(t.charCodeAt(s+1));if(i===void 0||a===void 0){const c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a}return r}function Av(t){const e=globalThis;if(typeof e.scheduler?.yield=="function"){const n=e.scheduler.yield();return t&&n.catch(t),n}return new Promise(n=>e.setTimeout(n,0))}async function sR(t,e,n,r){if(Lt(t,"iters"),Lt(e,"tick"),typeof n!="function")throw new TypeError("callback must be a function");let o=Date.now();for(let s=0;s<t;s++){n(s);const i=Date.now()-o;i>=0&&i<e||(await Av(r),o=Date.now())}}function kv(t){if(typeof t!="string")throw new TypeError("string expected");const e=new TextEncoder().encode(t);try{return new Uint8Array(e)}finally{hn(e)}}function iR(t,e=""){return typeof t=="string"?kv(t):Bt(t,void 0,e)}function Iv(t,e,n="opts"){return Rd(t,"defaults"),e!==void 0&&Rd(e,n),Object.assign(Object.create(null),t,e)}function Cv(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=Iv({},e,"info");const n=(o,s)=>t(s).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function Rv(t=32){Lt(t,"bytesLength");const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}const Tv=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Pv(t,e,n){return t&e^~t&n}function Nv(t,e,n){return t&e^t&n^e&n}class Lv{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,n,r,o){this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Di(this.buffer)}update(e){Ss(this),Bt(e);const{view:n,buffer:r,blockLen:o}=this,s=e.length;let i=!1;for(let a=0;a<s;){const c=Math.min(o-this.pos,s-a);if(c===o){const l=Di(e);for(;o<=s-a;a+=o)this.process(l,a);i=!0;continue}r.set(a===0&&c===s?e:e.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+=e.length,i&&this.roundClean(),this}digestInto(e){Ss(this),Gh(e,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)),yv(r,o-8,this.length*8,s),this.process(r,0),this.roundClean();const a=e===n?r:Di(e),c=this.outputLen,l=c/4,d=this.get();if(c%4||l>d.length)throw new Error("invalid outputLen");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneIntoMeta(e){const{buffer:n,length:r,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=r,e.pos=i,i&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Bv=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),_v=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]),Ut=new Uint32Array(64);class Ov extends Lv{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,n){super(64,e,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:e,B:n,C:r,D:o,E:s,F:i,G:a,H:c}=this;return[e,n,r,o,s,i,a,c]}set(e,n,r,o,s,i,a,c){this.A=e|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(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,n){for(let u=0;u<16;u++,n+=4)Ut[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const f=Ut[u-15],h=Ut[u-2],g=dt(f,7)^dt(f,18)^f>>>3,m=dt(h,17)^dt(h,19)^h>>>10;Ut[u]=m+Ut[u-7]+g+Ut[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=dt(a,6)^dt(a,11)^dt(a,25),h=d+f+Pv(a,c,l)+_v[u]+Ut[u]|0,m=(dt(r,2)^dt(r,13)^dt(r,22))+Nv(r,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=r,r=h+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(){hn(Ut)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),hn(this.buffer)}}class Dv extends Ov{constructor(){super(32,Bv)}}const Fi=Cv(()=>new Dv,Tv(1));function Yh(t,e,n=()=>{}){if(!Array.isArray(t))throw new TypeError(`"${e}" expected array, got type=${typeof t}`);for(let r=0;r<t.length;r++)n(t[r],`${e}[${r}]`);return t}const Jn=(t,e,n)=>Bt(t,e,n),Zh=Lt;function Qn(t,e="object"){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`);return t}function Zr(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}const Fv=sl,Mv=t=>Xh(t),Jh=Va,Qh=t=>Rv(t),xs=BigInt(0),Pd=BigInt(1),jv=t=>t?`"${t}" `:"";function ri(t,e=""){if(typeof t!="boolean")throw new TypeError(jv(e)+"expected boolean, got type="+typeof t);return t}function Uv(t){if(typeof t=="bigint"){if(!pn(t))throw new RangeError("positive bigint expected, got "+t)}else Zh(t);return t}function Ya(t,e=""){if(typeof t!="number"){const n=e&&`"${e}" `;throw new TypeError(n+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){const n=e&&`"${e}" `;throw new RangeError(n+"expected safe integer, got "+t)}}function ep(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?xs:BigInt("0x"+t)}function tp(t){return ep(sl(t))}function Es(t){return ep(sl(ao(Bt(t)).reverse()))}function np(t,e){if(Lt(e),e===0)throw new Error("zero output length is invalid");t=Uv(t);const n=e*2,r=t.toString(16);if(r.length>n)throw new RangeError("number is too large");return Xh(r.padStart(n,"0"))}function rp(t,e){return np(t,e).reverse()}function ao(t){return Uint8Array.from(Jn(t))}function pn(t){return typeof t=="bigint"&&xs<=t}function op(t,e,n){return pn(t)&&pn(e)&&pn(n)&&e<=t&&t<n}function Jr(t,e,n,r){if(!op(e,n,r))throw new RangeError("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function $v(t){if(t<xs)throw new Error("expected non-negative bigint, got "+t);return t===xs?0:t.toString(2).length}const Hv=t=>(Ya(t,"n"),(Pd<<BigInt(t))-Pd);function As(t,e={},n={},r="object"){Qn(t,r),Qn(e,"fields"),Qn(n,"optFields");function o(i,a,c){const l=r==="object"?`param "${String(i)}"`:`"${r}.${String(i)}"`,d=t[i];if(!Object.hasOwn(t,i)&&(c?d!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&d===void 0)return;const u=typeof d;if(u!==a||d===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${u}`)}const s=(i,a)=>Object.entries(i).forEach(([c,l])=>o(c,l,a));s(e,!1),s(n,!0)}const Ee=BigInt(0),de=BigInt(1),cn=BigInt(2),sp=BigInt(3),il=BigInt(4),ip=BigInt(5),qv=BigInt(7),ap=BigInt(8),Kv=BigInt(9),zv=BigInt(15),cp=BigInt(16),Wv=BigInt("0x10000000000000000");function le(t,e){if(e<=Ee)throw new Error("mod: expected positive modulus, got "+e);const n=t%e;return n>=Ee?n:e+n}function Gv(t,e,n){if(n<=de)throw new Error("pow: expected modulus > 1, got "+n);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<Ee)throw new Error("invalid exponent, negatives unsupported");if(e===Ee)return de;if(e===de)return t;let r=t%n;if(r<Ee&&(r+=n),e<Wv){let a=de;for(;e>Ee;)e&de&&(a=a*r%n),r=r*r%n,e>>=de;return a}const o=[];for(;e>Ee;)o.push(Number(e&zv)),e>>=il;const s=new Array(16);s[0]=de,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 ot(t,e,n){if(n<=de)throw new Error("pow2: expected modulus > 1, got "+n);if(e<Ee)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >Ee;)r*=r,r%=n;return r}function Nd(t,e){if(t===Ee)throw new Error("invert: expected non-zero number");if(e<=de)throw new Error("invert: expected modulus > 1, got "+e);let n=le(t,e),r=e,o=Ee,s=de;for(;n!==Ee;){const a=r/n,c=r-n*a,l=o-s*a;r=n,n=c,o=s,s=l}if(r!==de)throw new Error("invert: does not exist");return le(o,e)}function al(t,e,n){const r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function cl(t,e){if((t&de)===Ee)throw new Error(e+": expected odd modulus, got "+t)}function lp(t,e){const n=t,r=(n.ORDER+de)/il,o=n.pow(e,r);return al(n,o,e),o}function Vv(t,e){const n=t,r=(n.ORDER-ip)/ap,o=n.mul(e,cn),s=n.pow(o,r),i=n.mul(e,s),a=n.mul(n.mul(i,cn),s),c=n.mul(i,n.sub(a,n.ONE));return al(n,c,e),c}function Xv(t){const e=ll(t),n=dp(t),r=n(e,e.neg(e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+qv)/cp;return((a,c)=>{const l=a;let d=l.pow(c,i),u=l.mul(d,r);const f=l.mul(d,o),h=l.mul(d,s),g=l.eql(l.sqr(u),c),m=l.eql(l.sqr(f),c);d=l.cmov(d,u,g),u=l.cmov(h,f,m);const b=l.eql(l.sqr(u),c),w=l.cmov(d,u,b);return al(l,w,c),w})}function dp(t){if(t<sp)throw new Error("sqrt is not defined for small field");cl(t,"tonelliShanks");let e=t-de,n=0;for(;e%cn===Ee;)e/=cn,n++;let r=cn;const o=ll(t);for(;ks(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return lp;let s=o.pow(r,e);const i=(e+de)/cn;return function(c,l){const d=c;if(d.is0(l))return l;if(ks(d,l)!==1)throw new Error("Cannot find square root");let u=n,f=d.mul(d.ONE,s),h=d.pow(l,e),g=d.pow(l,i);for(;!d.eql(h,d.ONE);){if(d.is0(h))throw new Error("Cannot find square root: probably non-prime P");let m=1,b=d.sqr(h);for(;!d.eql(b,d.ONE);)if(m++,b=d.sqr(b),m===u)throw new Error("Cannot find square root");const w=de<<BigInt(u-m-1),R=d.pow(f,w);u=m,f=d.sqr(R),h=d.mul(h,f),g=d.mul(g,R)}return g}}function Yv(t){return cl(t,"Fp.sqrt"),t%il===sp?lp:t%ap===ip?Vv:t%cp===Kv?Xv(t):dp(t)}const Zv=(t,e)=>(le(t,e)&de)===de,Jv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function co(t){if(Qn(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);Ya(t.BYTES,"BYTES"),Ya(t.BITS,"BITS");for(const e of Jv)Zr(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=de)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function up(t,e,n=!1){co(t),Yh(e,"nums"),ri(n,"passZero");const r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),s=e.reduce((a,c,l)=>r.is0(c)?a:(o[l]=a,r.mul(a,c)),r.ONE),i=r.inv(s);return e.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),i),o}function ks(t,e){co(t);const n=t;cl(n.ORDER,"FpLegendre");const r=(n.ORDER-de)/cn,o=n.pow(e,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 Qv(t,e){if(e!==void 0&&Zh(e),t<=Ee)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);const n=$v(t);if(e!==void 0&&e<n)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${n})`);const r=e!==void 0?e:n,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}const Ld=new WeakMap;class Bd{ORDER;BITS;BYTES;isLE;ZERO=Ee;ONE=de;_lengths;_mod;constructor(e,n={}){if(e<=de)throw new Error("invalid field: expected ORDER > 1, got "+e);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}=Qv(e,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return le(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Ee<=e&&e<this.ORDER}is0(e){return e===Ee}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&de)===de}neg(e){return le(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return le(e*e,this.ORDER)}add(e,n){return le(e+n,this.ORDER)}sub(e,n){return le(e-n,this.ORDER)}mul(e,n){return le(e*n,this.ORDER)}pow(e,n){return Gv(e,n,this.ORDER)}div(e,n){return le(e*Nd(n,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return Nd(e,this.ORDER)}sqrt(e){let n=Ld.get(this);return n||Ld.set(this,n=Yv(this.ORDER)),n(this,e)}toBytes(e){return this.isLE?rp(e,this.BYTES):np(e,this.BYTES)}fromBytes(e,n=!1){Jn(e);const{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);const l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?Es(e):tp(e);if(a&&(c=le(c,i)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return up(this,e,!0)}cmov(e,n,r){return ri(r,"condition"),r?n:e}}function ll(t,e={}){return Object.freeze(Bd.prototype),new Bd(t,e)}const dl=BigInt(0),lo=BigInt(1),eS=BigInt(4),Mi=16,_d=128,tS=5,Od=2**31;function ul(t){const e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);Zr(e.fromAffine,"Point.fromAffine"),Zr(e.fromBytes,"Point.fromBytes"),Zr(e.fromHex,"Point.fromHex"),Qn(e.BASE,"Point.BASE"),Qn(e.ZERO,"Point.ZERO"),co(e.Fp),co(e.Fn)}function nS(t,e){ul(t),fp(e,t);const n=up(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function rS(t,e,n=1){if(!Number.isSafeInteger(t)||t<n||t>e)throw new Error("invalid window size, expected ["+n+".."+e+"], got W="+t)}function oS(t,e){const n=t*(4*e+128);if(n>Od)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+Od/2**20+" MiB")}function sS(t,e){if(t!==void 0){Zr(t,"randomBytes");try{const n=t(e);if(!Jh(n)||n.length!==e)return}catch{return}return t}}function fp(t,e){Yh(t,"points"),t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function iS(t,e,n){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,o)=>{if(!(n===void 0?e.isValid(r):pn(r)&&r<n))throw new Error("invalid scalar at index "+o)})}const hp=new WeakMap;function ji(t){return hp.get(t)||1}function aS(t,e){const n=t.double(),r=[t];for(let o=1;o<e;o++)r.push(r[o-1].add(n));return r}function cS(t,e){const n=2**e,r=n/2,o=BigInt(n-1),s=[];for(;t>dl;){let i=0;t&lo&&(i=Number(t&o),i>=r&&(i-=n),t-=BigInt(i)),s.push(i),t>>=lo}return s}function lS(t,e,n){const r=2**e,o=r/2,s=BigInt(r-1),i=BigInt(e),a=[];for(let c=0;c<n;c++){let l=Number(t&s);t>>=i,l>o&&(l-=r,t+=lo),a.push(l)}if(t!==dl)throw new Error("invalid wnaf");return a}function dS(t,e,n){let r=0;for(const s of n)r=Math.max(r,s.length);let o=t;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=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}class uS{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,n){ul(e),this.randomBytes=sS(n,Mi),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,n,r){const o=Math.ceil(r/n)+1,s=2**(n-1),i=[];let a=e;for(let c=0;c<o;c++){let l=a;for(let d=0;d<s;d++)i.push(l),l=l.add(a);a=i[i.length-1].double()}return{W:n,bits:r,windows:o,comp:i}}wnafCachedCT(e,n){const{W:r,windows:o,comp:s}=e,i=2**(r-1),a=lS(n,r,o);let c=this.ZERO,l=this.BASE;for(let d=0;d<o;d++){const u=a[d],f=d*i,h=Math.abs(u)-1;let g=s[f];for(let b=1;b<i;b++)g=b===h?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(e,n,r,o){let s=this.wnafPrecomputes.get(n),i=s?.find(a=>a.W===e&&a.bits===r);return i||(i=this.buildWnafTable(n,e,r),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(n,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,n){if(this.assertPoint(e),!op(n,lo,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,n,r,o){const s=ji(e);return s===1?this.fixedWindowCT(e,n,r):this.wnafCachedCT(this.getWnafPrecomputes(s,e,r,o),n)}mulCT(e,n,r){return this.validateMulInput(e,n),this.runCT(e,n,this.bits,r)}mulCTBlinded(e,n,r){if(this.validateMulInput(e,n),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");const o=this.Point.Fn.BITS+_d,s=this.randomBytes(Mi);if(!Jh(s)||s.length!==Mi)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;const i=n+tp(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,r)}fixedWindowCT(e,n,r){const o=tS,s=1<<o,i=Hv(o),a=new Array(s);a[0]=this.ZERO;for(let d=1;d<s;d++)a[d]=a[d-1].add(e);const c=Math.ceil(r/o);let l=this.ZERO;for(let d=c-1;d>=0;d--){if(d!==c-1)for(let h=0;h<o;h++)l=l.double();const u=Number(n>>BigInt(d*o)&i);let f=a[0];for(let h=1;h<s;h++)f=h===u?a[h]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(e,n){return this.randomBytes===void 0?!1:n===lo?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,n,r,o){return this.shouldBlind(e,r)?this.mulCTBlinded(e,n,o):this.mulCT(e,n,o)}mulUnsafe(e,n,r){if(this.assertPoint(e),!pn(n))throw new Error("invalid scalar");const o=ji(e);if(o===1||n>=this.Point.Fn.ORDER)return fS(this.Point,[e],[n],!0);const s=this.getWnafPrecomputes(o,e,this.bits,r);return this.wnafCachedCT(s,n).p}setWindowSize(e,n){this.assertPoint(e),rS(n,this.bits);const r=Math.ceil((this.bits+_d)/n)+1;oS(r*2**(n-1),this.Point.Fp.BYTES),hp.set(e,n),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return ji(e)!==1}}function fS(t,e,n,r=!1){if(ul(t),fp(e,t),ri(r,"allowOversized"),iS(n,t.Fn,r?t.Fn.ORDER**eS:void 0),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const o=e.map(i=>aS(i,4)),s=n.map(i=>cS(i,4));return dS(t.ZERO,o,s)}function Dd(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return co(e),e}else return ll(t,{isLE:n})}function hS(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);As(n);for(const c of["p","n","h"]){const l=e[c];if(!(pn(l)&&l!==dl))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Dd(e.p,n.Fp,r),s=Dd(e.n,n.Fn,r),a=["Gx","Gy","a","d"];for(const c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function pS(t,e){return function(r){const o=t(r);return{secretKey:o,publicKey:e(o)}}}const Oo=BigInt(0),Do=BigInt(1),Fo=BigInt(2),gS=BigInt(4),Fd=BigInt(8);function mS(t,e,n,r){const o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function wS(t,e={}){As(e,{},{},"extraOpts");const n=e,r=hS("edwards",t,n,n.FpFnLE),{Fp:o,Fn:s}=r;let i=r.CURVE;const{h:a}=i;if(ks(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(ks(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");As(n,{},{uvRatio:"function",randomBytes:"function"});const c=n.randomBytes===void 0?Qh:n.randomBytes,l=Fo<<BigInt(o.BYTES*8)-Do;function d(R){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(R)}const u=n.uvRatio===void 0?(R,y)=>{try{return{isValid:!0,value:o.sqrt(o.div(R,y))}}catch{return{isValid:!1,value:Oo}}}:n.uvRatio;if(!mS(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");const f=o.eql(i.a,o.neg(o.ONE))?R=>o.neg(R):o.eql(i.a,o.ONE)?R=>R:R=>o.mul(i.a,R);function h(R,y,k=!1){const N=k?Do:Oo;return Jr("coordinate "+R,y,N,l),y}function g(R){if(!(R 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(y,k,N,x){this.X=h("x",y),this.Y=h("y",k),this.Z=h("z",N,!0),this.T=h("t",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(y){if(y instanceof m)throw new Error("extended point not allowed");const{x:k,y:N}=y||{};return h("x",k),h("y",N),new m(k,N,o.ONE,o.mul(k,N))}static fromBytes(y,k=!1){const N=o.BYTES,{a:x,d:T}=i;y=ao(Jn(y,N,"point")),ri(k,"zip215");const S=ao(y),v=y[N-1];S[N-1]=v&-129;const A=Es(S),_=k?l:o.ORDER;Jr("point.y",A,Oo,_);const B=o.sqr(A),I=o.sub(B,o.ONE),E=o.sub(o.mulN(T,B),x);let{isValid:P,value:C}=u(I,E);if(!P)throw new Error("bad point: invalid y coordinate");const D=d(C),M=(v&128)!==0;if(!k&&o.is0(C)&&M)throw new Error("bad point: x=0 and x_0=1");return M!==D&&(C=o.neg(C)),m.fromAffine({x:C,y:A})}static fromHex(y,k=!1){return m.fromBytes(Mv(y),k)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=6,k=!0){return w.setWindowSize(this,y),k||this.multiply(Fo),this}assertValidity(){const y=this,{a:k,d:N}=i;if(y.is0())throw new Error("bad point: ZERO");const{X:x,Y:T,Z:S,T:v}=y,A=o.sqr(x),_=o.sqr(T),B=o.sqr(S),I=o.sqr(B),E=o.mul(A,k),P=o.mul(o.add(E,_),B),C=o.add(I,o.mul(N,o.mul(A,_)));if(!o.eql(P,C))throw new Error("bad point: equation left != right (1)");const D=o.mul(x,T),M=o.mul(S,v);if(!o.eql(D,M))throw new Error("bad point: equation left != right (2)")}equals(y){g(y);const{X:k,Y:N,Z:x}=this,{X:T,Y:S,Z:v}=y,A=o.mul(k,v),_=o.mul(T,x),B=o.mul(N,v),I=o.mul(S,x);return o.eql(A,_)&&o.eql(B,I)}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:y,Y:k,Z:N}=this,x=o.sqr(y),T=o.sqr(k),S=o.mul(o.sqr(N),Fo),v=f(x),A=o.addN(y,k),_=o.sub(o.subN(o.sqr(A),x),T),B=o.addN(v,T),I=o.subN(B,S),E=o.subN(v,T),P=o.mul(_,I),C=o.mul(B,E),D=o.mul(_,E),M=o.mul(I,B);return new m(P,C,M,D)}add(y){g(y);const{d:k}=i,{X:N,Y:x,Z:T,T:S}=this,{X:v,Y:A,Z:_,T:B}=y,I=o.mul(N,v),E=o.mul(x,A),P=o.mul(o.mulN(S,k),B),C=o.mul(T,_),D=o.sub(o.subN(o.mulN(o.addN(N,x),o.addN(v,A)),I),E),M=o.subN(C,P),F=o.addN(C,P),L=o.sub(E,f(I)),$=o.mul(D,M),H=o.mul(F,L),U=o.mul(D,L),q=o.mul(M,F);return new m($,H,q,U)}subtract(y){return g(y),this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");const{p:k,f:N}=w.mulSecret(this,y,a,b);return b([k,N])[0]}multiplyUnsafe(y){if(!s.isValid(y))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return y===Oo?m.ZERO:this.is0()||y===Do?this:w.mulUnsafe(this,y,b)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.mulUnsafe(this,i.n).is0()}toAffine(y){const k=this;let N=y;if(N!=null&&typeof N!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof N);const{X:x,Y:T,Z:S}=k,v=k.is0();N==null&&(N=v?o.create(Fd):o.inv(S));const A=o.mul(x,N),_=o.mul(T,N),B=o.mul(S,N);if(v)return{x:o.ZERO,y:o.ONE};if(!o.eql(B,o.ONE))throw new Error("invZ was invalid");return{x:A,y:_}}clearCofactor(){return a===Do?this:a===Fo?this.double():a===gS?this.double().double():a===Fd?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){const{x:y,y:k}=this.toAffine(),N=o.toBytes(k);return N[N.length-1]|=d(y)?128:0,N}toHex(){return Fv(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const b=R=>nS(m,R),w=new uS(m,c);return w.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}const tn=BigInt(0),Ze=BigInt(1),Mo=BigInt(2);function Md(t,e){return t+e-(e>>Ze<<Ze)}function yS(t){const e=BigInt(6)*t;return(n,r,o)=>{const s=r+o,a=((e+o-r)*n+r)%t;return{x_2:a,x_3:s-a}}}function bS(t){return As(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...t})}function vS(t){const e=bS(t),{P:n,type:r,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=e.scalarMultBase,c=r==="x25519";if(!c&&r!=="x448")throw new Error("invalid type");const l=i===void 0?Qh:i,d=c?255:448,u=yS(n),f=c?32:56,h=BigInt(c?9:5),g=BigInt(c?121665:39081),m=c?Mo**BigInt(254):Mo**BigInt(447),b=c?BigInt(8)*(Mo**BigInt(251)-Ze):BigInt(4)*(Mo**BigInt(445)-Ze),w=m+b+Ze,R=C=>le(C,n),y=k(h);function k(C){return rp(R(C),f)}function N(C){const D=ao(Jn(C,f,"uCoordinate"));return c&&(D[31]&=127),R(Es(D))}function x(C){return Es(o(ao(Jn(C,f,"scalar"))))}const T=new Set(c?[tn,Ze,n-Ze,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[tn,Ze,n-Ze]);function S(C,D){const M=N(D);if(T.has(M))throw new Error("invalid private or public key received");const F=B(M,x(C));if(F===tn)throw new Error("invalid private or public key received");return k(F)}function v(C){if(a===void 0)return S(C,y);const D=x(C);Jr("scalar",D,m,w);const M=R(a(D));if(M===tn)throw new Error("invalid private or public key received");return k(M)}const A=v,_=S;function B(C,D){Jr("u",C,tn,n),Jr("scalar",D,m,w);const M=D,F=C;let L=Ze,$=tn,H=C,U=Ze;const q=M^M>>Ze;for(let z=BigInt(d-1);z>=tn;z--){const W=Md(n,q>>z);({x_2:L,x_3:H}=u(W,L,H)),{x_2:$,x_3:U}=u(W,$,U);const G=L+$,Y=R(G*G),Q=L-$,ae=R(Q*Q),ce=Y-ae,ie=H+U,$e=H-U,ke=R($e*G),Ve=R(ie*Q),en=ke+Ve,Oe=ke-Ve;H=R(en*en),U=R(F*R(Oe*Oe)),L=R(Y*ae),$=R(ce*(Y+R(g*ce)))}const K=Md(n,M);({x_2:L,x_3:H}=u(K,L,H)),{x_2:$,x_3:U}=u(K,$,U);const X=s($);return R(L*X)}const I={secretKey:f,publicKey:f,seed:f},E=C=>(C=C===void 0?l(f):C,Jn(C,I.seed,"seed"),C),P={randomSecretKey:E};return Object.freeze(I),Object.freeze(P),Object.freeze({keygen:pS(E,A),getSharedSecret:_,getPublicKey:A,scalarMult:S,scalarMultBase:v,utils:P,GuBytes:y.slice(),lengths:I})}const jd=BigInt(0),SS=BigInt(1),Ud=BigInt(2),xS=BigInt(3),ES=BigInt(5),AS=BigInt(8),oi=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),kS={p:oi,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:AS,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function pp(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=oi,a=t*t%s*t%s,c=ot(a,Ud,s)*a%s,l=ot(c,SS,s)*t%s,d=ot(l,ES,s)*l%s,u=ot(d,e,s)*d%s,f=ot(u,n,s)*u%s,h=ot(f,r,s)*f%s,g=ot(h,o,s)*h%s,m=ot(g,o,s)*h%s,b=ot(m,e,s)*d%s;return{pow_p_5_8:ot(b,Ud,s)*t%s,b2:a}}function IS(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const $d=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function CS(t,e){const n=oi,r=le(e*e*e,n),o=le(r*r*e,n),s=pp(t*o).pow_p_5_8;let i=le(t*r*s,n);const a=le(e*i*i,n),c=i,l=le(i*$d,n),d=a===t,u=a===le(-t,n),f=a===le(-t*$d,n);return d&&(i=c),(u||f)&&(i=l),Zv(i,n)&&(i=le(-i,n)),{isValid:d||u,value:i}}const Hd=wS(kS,{uvRatio:CS}),jo=(()=>{const t=oi,e=n=>{const{pow_p_5_8:r,b2:o}=pp(n);return le(ot(r,xS,t)*o,t)};return vS({P:t,type:"x25519",powPminus2:e,adjustScalarBytes:IS,scalarMultBase:n=>{const r=le(n,Hd.Fn.ORDER);if(r===jd)return jd;const o=Hd.BASE.multiply(r);return le((o.Z+o.Y)*e(le(o.Z-o.Y,t)),t)}})})();class qd{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,n){if(ol(e),Bt(n,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?e.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),hn(o)}update(e){return Ss(this),this.iHash.update(e),this}digestInto(e){Ss(this),Gh(e,this),this.finished=!0;const n=e.subarray(0,this.outputLen);this.iHash.digestInto(n),this.oHash.update(n),this.oHash.digestInto(n),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});const{oHash:n,iHash:r,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const gp=(()=>{const t=((e,n,r)=>new qd(e,n).update(r).digest());return t.create=(e,n)=>new qd(e,n),t})();function Kd(){const t={};return t.promise=new Promise((e,n)=>{t.resolve=e,t.reject=n}),t}class zd{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}}class Ui{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new zd(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const n=this.head;this.head=n.next=new zd(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){const n=this.tail.next;this.tail.next=null,this.tail=n,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}class RS extends Error{type;code;constructor(e,n){super(e??"The operation was aborted"),this.type="aborted",this.code=n??"ABORT_ERR"}}function TS(t={}){return PS(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}},t)}function PS(t,e){e=e??{};let n=e.onEnd,r=new Ui,o,s,i,a=Kd();const c=async()=>{try{return r.isEmpty()?i?{done:!0}:await new Promise((b,w)=>{s=R=>{s=null,r.push(R);try{b(t(r))}catch(y){w(y)}return o}}):t(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Kd()})}},l=b=>s!=null?s(b):(r.push(b),o),d=b=>(r=new Ui,s!=null?s({error:b}):(r.push({error:b}),o)),u=b=>{if(i)return o;if(e?.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})),h=()=>(r=new Ui,f(),{done:!0}),g=b=>(f(b),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:g,push:u,end:f,get readableLength(){return r.size},onEmpty:async b=>{const w=b?.signal;if(w?.throwIfAborted(),r.isEmpty())return;let R,y;w!=null&&(R=new Promise((k,N)=>{y=()=>{N(new RS)},w.addEventListener("abort",y)}));try{await Promise.race([a.promise,R])}finally{y!=null&&w!=null&&w?.removeEventListener("abort",y)}}},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 fl extends Error{name="TimeoutError";constructor(e,n){super(e,n),Error.captureStackTrace?.(this,fl)}}const Wd=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function NS(t,e){const{milliseconds:n,fallback:r,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e;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(Wd(i));return}if(i&&(c=()=>{f(Wd(i))},i.addEventListener("abort",c,{once:!0})),t.then(u,f),n===Number.POSITIVE_INFINITY)return;const h=new fl;a=s.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){f(g)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?u():o instanceof Error?f(o):(h.message=o??`Promise timed out after ${n} milliseconds`,f(h))},n)}).finally(()=>{d.clear(),c&&i&&i.removeEventListener("abort",c)});return d.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},d}const LS=t=>{const e=t.addEventListener||t.on||t.addListener,n=t.removeEventListener||t.off||t.removeListener;if(!e||!n)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:n.bind(t)}};function BS(t,e,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=[e].flat(),c=[],{addListener:l,removeListener:d}=LS(t),u=async(...h)=>{const g=n.multiArgs?h:h[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=(...h)=>{r(),i(n.rejectionMultiArgs?h:h[0])};r=()=>{for(const h of a)d(h,u);for(const h of n.rejectionEvents)a.includes(h)||d(h,f)};for(const h of a)l(h,u);for(const h of n.rejectionEvents)a.includes(h)||l(h,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=NS(o,{milliseconds:n.timeout});return s.cancel=()=>{r(),s.clear()},s}return o}function _S(t,e,n){typeof n=="function"&&(n={filter:n}),n={...n,count:1,resolveImmediately:!1};const r=BS(t,e,n),o=r.then(s=>s[0]);return o.cancel=r.cancel,o}class Is extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class OS extends Error{static name="StreamClosedError";name="StreamClosedError"}function DS(t){return t.reason}function mp(t,e,n){if(e==null||t==null)return t;const r=DS;if(e.aborted)return t.catch(()=>{}),Promise.reject(r(e));let o;return Promise.race([t,new Promise((s,i)=>{o=()=>{i(r(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}const FS=Math.pow(2,20)*4;class wp extends Xm{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??FS,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new se,this.writeBuffer=new se,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 OS)};this.addEventListener("close",r)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),mp(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;const e=TS(),n=s=>{e.push(s.data)};this.addEventListener("message",n);const r=s=>{e.end(s.error)};this.addEventListener("close",r);const o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",n),this.removeEventListener("close",r),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Pr(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(n){this.log("failed to send reset to remote - %e",n)}this.dispatchEvent(new pv(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Pr("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 Pr("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Pr(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Pr(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");const e=new fv;this.dispatchEvent(new gv(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new rl))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0;const 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){e=!1;break}const s=this.writeBuffer.sublist(0,o),i=new se(s);this.writeBuffer.consume(s.byteLength);const a=this.sendData(s);if(e=a.canSendMore,r+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",r,n,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}const e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new hv(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Cd(`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 Cd(`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 MS=4194304;class Gd extends Error{static name="UnwrappedError";name="UnwrappedError"}class yp extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class jS extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class US extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function $S(t){return typeof t?.closeRead=="function"}function HS(t){return typeof t?.close=="function"}function $i(t){return $S(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:HS(t)?t.status!=="open":!1}function qS(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function KS(t,e){const n=e?.maxBufferSize??MS,r=new se;let o,s=!1;if(!qS(t))throw new Wh("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()};t.addEventListener("message",i);const a=d=>{d.error!=null?o?.reject(d.error):o?.resolve()};t.addEventListener("close",a);const c=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",c);const l={readBuffer:r,async read(d){if(s===!0)throw new Gd("Stream was unwrapped");if($i(t)){if(d?.bytes==null)return null;if(r.byteLength<d.bytes)throw t.log.error("closed after reading %d/%d bytes",r.byteLength,d.bytes),new Is(`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 mp(o.promise,d?.signal),$i(t)){if(r.byteLength===0&&d?.bytes==null)return null;break}o=Promise.withResolvers()}const f=d?.bytes??r.byteLength;if(r.byteLength<f){if($i(t))throw t.log.error("closed while reading %d/%d bytes",r.byteLength,f),new Is(`Unexpected EOF - stream closed while reading ${r.byteLength}/${f} bytes`);return l.read(d)}const h=r.sublist(0,f);return r.consume(f),h},async write(d,u){if(s===!0)throw new Gd("Stream was unwrapped");t.send(d)||await _S(t,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",i),t.removeEventListener("close",a),t.removeEventListener("remoteCloseWrite",c),r.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",r.byteLength),t.push(r))),t}};return l}function Vd(t,e={}){const n=KS(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=An(e.maxDataLength));const r=e?.lengthDecoder??Ih,o=e?.lengthEncoder??Yb;return{async read(i){let a=-1;const c=new se;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 yp("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new US(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new jS(`Message length too long - ${a} > ${e.maxDataLength}`);const l=await n.read({...i,bytes:a});if(l==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new Is(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw t.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Is(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await n.write(new se(o(i.byteLength),i),a)},async writeV(i,a){const c=new se(...i.flatMap(l=>[o(l.byteLength),l]));await n.write(c,a)},unwrap(){return n.unwrap()}}}const zS=1024*1024*4,WS=1024*1024*4;class GS{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new se,this.maxBufferSize=e.maxBufferSize??zS,this.maxDataLength=e.maxDataLength??WS,this.lengthDecoder=e.lengthDecoder??Ih,this.encodingLength=e.encodingLength??An}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new Wh(`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 yp("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 VS={};const uo=65535,Xd=uo-16,Ao=!!VS?.DUMP_SESSION_KEYS,Yd=16;function Za(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const Cs=t=>t?`"${t}" `:"";function Ja(t,e=""){if(typeof t!="boolean")throw new TypeError(Cs(e)+"expected boolean, got type="+typeof t);return t}function er(t,e=""){if(typeof t!="number")throw new TypeError(Cs(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(Cs(e)+"expected integer >= 0, got "+t);return t}function xe(t,e,n=""){if(Za(t)&&(e===void 0||t.length===e))return t;e!==void 0&&er(e,"length");const r=Za(t),o=e!==void 0?` of length ${e}`:"",s=r?`length=${t.length}`:`type=${typeof t}`,i=Cs(n)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}const Zd=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`)};function Jd(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function XS(t,e){xe(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function It(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Xt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function YS(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const tr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ZS(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function JS(t){for(let e=0;e<t.length;e++)t[e]=ZS(t[e]);return t}const ln=tr?t=>t:JS;function QS(t,e){return!t.byteLength||!e.byteLength?!1:t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function ex(t,e){if(QS(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function tx(t,e){return Zd(t,"defaults"),Zd(e,"opts"),Object.assign(t,e)}function nx(t,e){if(t=xe(t),e=xe(e),t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}function rx(t,e,n){const r=e,o=(()=>[]),s=(a,c)=>r(c,...o(a)).update(a).digest(),i=r(new Uint8Array(t),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>r(a,...c),s}const ox=(t,e)=>{function n(r,...o){if(xe(r,void 0,"key"),t.nonceLength!==void 0){const u=o[0];xe(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}const s=t.tagLength,i=t.nonceLength!==void 0?1:0;if(!t.withAAD){for(let u=i;u<o.length;u++)if(Za(o[u]))throw new Error("AAD not supported")}t.withAAD&&o[i]!==void 0&&xe(o[i],void 0,"AAD");const a=e(r,...o),c=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");xe(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,xe(u,void 0,"data"),c(a.encrypt.length,f),a.encrypt(u,f)},decrypt(u,f){if(xe(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,t),n};function Qa(t,e,n=!0){if(e===void 0)return new Uint8Array(t);if(xe(e,t,"output"),n&&!Rs(e))throw new Error("invalid output, must be aligned");return e}function sx(t,e,n){er(t),er(e),Ja(n);const r=new Uint8Array(16),o=YS(r);return o.setBigUint64(0,BigInt(e),n),o.setBigUint64(8,BigInt(t),n),r}function Rs(t){return t.byteOffset%4===0}function Ts(t){return Uint8Array.from(xe(t))}const bp=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),ix=ln(It(bp("expand 16-byte k"))),ax=ln(It(bp("expand 32-byte k")));function ne(t,e){return t<<e|t>>>32-e}const Nr=64,cx=16,ec=2**32-1,Qd=Uint32Array.of();function lx(t,e,n,r,o,s,i,a){const c=o.length,l=new Uint8Array(Nr),d=It(l),u=tr&&Rs(o)&&Rs(s),f=u?It(o):Qd,h=u?It(s):Qd;if(!tr){for(let g=0;g<c;i++){if(t(e,n,r,d,i,a),ln(d),i>=ec)throw new Error("arx: counter overflow");const m=Math.min(Nr,c-g);for(let b=0,w;b<m;b++)w=g+b,s[w]=o[w]^l[b];g+=m}return}for(let g=0;g<c;i++){if(t(e,n,r,d,i,a),i>=ec)throw new Error("arx: counter overflow");const m=Math.min(Nr,c-g);if(u&&m===Nr){const b=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,R;w<cx;w++)R=b+w,h[R]=f[R]^d[w];g+=Nr;continue}for(let b=0,w;b<m;b++)w=g+b,s[w]=o[w]^l[b];g+=m}}function dx(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:s,rounds:i}=tx({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return er(o),er(i),Ja(s),Ja(n),(a,c,l,d,u=0)=>{xe(a,void 0,"key"),xe(c,void 0,"nonce"),xe(l,void 0,"data");const f=l.length,h=d!==void 0;if(d=Qa(f,d,!1),h&&ex(l,d),er(u),u<0||u>=ec)throw new Error("arx: counter overflow");const g=[];let m=a.length,b,w;if(m===32)g.push(b=Ts(a)),w=ax;else if(m===16&&n)b=new Uint8Array(32),b.set(a),b.set(a,16),w=ix,g.push(b);else throw xe(a,32,"arx key"),new Error("invalid key size");(!tr||!Rs(c))&&g.push(c=Ts(c));let R=It(b);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");const N=c.subarray(0,16);if(tr)r(w,R,It(N),R);else{const x=ln(Uint32Array.from(w));r(x,R,It(N),R),Xt(x),ln(R)}c=c.subarray(16)}else tr||ln(R);const y=16-o;if(y!==c.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){const N=new Uint8Array(12);N.set(c,s?0:12-c.length),c=N,g.push(c)}const k=ln(It(c));try{return lx(t,w,R,k,l,d,u,i),d}finally{Xt(...g)}}}function Ie(t,e){return t[e++]&255|(t[e++]&255)<<8}class ux{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=Ts(xe(e,32,"key"));const n=Ie(e,0),r=Ie(e,2),o=Ie(e,4),s=Ie(e,6),i=Ie(e,8),a=Ie(e,10),c=Ie(e,12),l=Ie(e,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]=Ie(e,16+2*d)}process(e,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],h=i[6],g=i[7],m=i[8],b=i[9],w=Ie(e,n+0),R=Ie(e,n+2),y=Ie(e,n+4),k=Ie(e,n+6),N=Ie(e,n+8),x=Ie(e,n+10),T=Ie(e,n+12),S=Ie(e,n+14);let v=s[0]+(w&8191),A=s[1]+((w>>>13|R<<3)&8191),_=s[2]+((R>>>10|y<<6)&8191),B=s[3]+((y>>>7|k<<9)&8191),I=s[4]+((k>>>4|N<<12)&8191),E=s[5]+(N>>>1&8191),P=s[6]+((N>>>14|x<<2)&8191),C=s[7]+((x>>>11|T<<5)&8191),D=s[8]+((T>>>8|S<<8)&8191),M=s[9]+(S>>>5|o),F=0,L=F+v*a+A*(5*b)+_*(5*m)+B*(5*g)+I*(5*h);F=L>>>13,L&=8191,L+=E*(5*f)+P*(5*u)+C*(5*d)+D*(5*l)+M*(5*c),F+=L>>>13,L&=8191;let $=F+v*c+A*a+_*(5*b)+B*(5*m)+I*(5*g);F=$>>>13,$&=8191,$+=E*(5*h)+P*(5*f)+C*(5*u)+D*(5*d)+M*(5*l),F+=$>>>13,$&=8191;let H=F+v*l+A*c+_*a+B*(5*b)+I*(5*m);F=H>>>13,H&=8191,H+=E*(5*g)+P*(5*h)+C*(5*f)+D*(5*u)+M*(5*d),F+=H>>>13,H&=8191;let U=F+v*d+A*l+_*c+B*a+I*(5*b);F=U>>>13,U&=8191,U+=E*(5*m)+P*(5*g)+C*(5*h)+D*(5*f)+M*(5*u),F+=U>>>13,U&=8191;let q=F+v*u+A*d+_*l+B*c+I*a;F=q>>>13,q&=8191,q+=E*(5*b)+P*(5*m)+C*(5*g)+D*(5*h)+M*(5*f),F+=q>>>13,q&=8191;let K=F+v*f+A*u+_*d+B*l+I*c;F=K>>>13,K&=8191,K+=E*a+P*(5*b)+C*(5*m)+D*(5*g)+M*(5*h),F+=K>>>13,K&=8191;let X=F+v*h+A*f+_*u+B*d+I*l;F=X>>>13,X&=8191,X+=E*c+P*a+C*(5*b)+D*(5*m)+M*(5*g),F+=X>>>13,X&=8191;let z=F+v*g+A*h+_*f+B*u+I*d;F=z>>>13,z&=8191,z+=E*l+P*c+C*a+D*(5*b)+M*(5*m),F+=z>>>13,z&=8191;let W=F+v*m+A*g+_*h+B*f+I*u;F=W>>>13,W&=8191,W+=E*d+P*l+C*c+D*a+M*(5*b),F+=W>>>13,W&=8191;let G=F+v*b+A*m+_*g+B*h+I*f;F=G>>>13,G&=8191,G+=E*u+P*d+C*l+D*c+M*a,F+=G>>>13,G&=8191,F=(F<<2)+F|0,F=F+L|0,L=F&8191,F=F>>>13,$+=F,s[0]=L,s[1]=$,s[2]=H,s[3]=U,s[4]=q,s[5]=K,s[6]=X,s[7]=z,s[8]=W,s[9]=G}finalize(){const{h:e,pad:n}=this,r=new Uint16Array(10);let o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[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++)e[a]=e[a]&s|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+n[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+n[a]|0)+(i>>>16)|0,e[a]=i&65535;Xt(r)}update(e){Jd(this),xe(e),e=Ts(e);const{buffer:n,blockLen:r}=this,o=e.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(e,s);continue}n.set(e.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,Xt(this.h,this.r,this.buffer,this.pad)}digestInto(e){Jd(this),XS(e,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++)e[s++]=r[i]>>>0,e[s++]=r[i]>>>8}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}}const fx=rx(32,t=>new ux(t));function hx(t,e,n,r,o,s=20){let i=t[0],a=t[1],c=t[2],l=t[3],d=e[0],u=e[1],f=e[2],h=e[3],g=e[4],m=e[5],b=e[6],w=e[7],R=o,y=n[0],k=n[1],N=n[2],x=i,T=a,S=c,v=l,A=d,_=u,B=f,I=h,E=g,P=m,C=b,D=w,M=R,F=y,L=k,$=N;for(let U=0;U<s;U+=2)x=x+A|0,M=ne(M^x,16),E=E+M|0,A=ne(A^E,12),x=x+A|0,M=ne(M^x,8),E=E+M|0,A=ne(A^E,7),T=T+_|0,F=ne(F^T,16),P=P+F|0,_=ne(_^P,12),T=T+_|0,F=ne(F^T,8),P=P+F|0,_=ne(_^P,7),S=S+B|0,L=ne(L^S,16),C=C+L|0,B=ne(B^C,12),S=S+B|0,L=ne(L^S,8),C=C+L|0,B=ne(B^C,7),v=v+I|0,$=ne($^v,16),D=D+$|0,I=ne(I^D,12),v=v+I|0,$=ne($^v,8),D=D+$|0,I=ne(I^D,7),x=x+_|0,$=ne($^x,16),C=C+$|0,_=ne(_^C,12),x=x+_|0,$=ne($^x,8),C=C+$|0,_=ne(_^C,7),T=T+B|0,M=ne(M^T,16),D=D+M|0,B=ne(B^D,12),T=T+B|0,M=ne(M^T,8),D=D+M|0,B=ne(B^D,7),S=S+I|0,F=ne(F^S,16),E=E+F|0,I=ne(I^E,12),S=S+I|0,F=ne(F^S,8),E=E+F|0,I=ne(I^E,7),v=v+A|0,L=ne(L^v,16),P=P+L|0,A=ne(A^P,12),v=v+A|0,L=ne(L^v,8),P=P+L|0,A=ne(A^P,7);let H=0;r[H++]=i+x|0,r[H++]=a+T|0,r[H++]=c+S|0,r[H++]=l+v|0,r[H++]=d+A|0,r[H++]=u+_|0,r[H++]=f+B|0,r[H++]=h+I|0,r[H++]=g+E|0,r[H++]=m+P|0,r[H++]=b+C|0,r[H++]=w+D|0,r[H++]=R+M|0,r[H++]=y+F|0,r[H++]=k+L|0,r[H++]=N+$|0}const px=dx(hx,{counterRight:!1,counterLength:4,allowShortKeys:!1}),gx=new Uint8Array(16),eu=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(gx.subarray(n))},mx=new Uint8Array(32);function tu(t,e,n,r,o){o!==void 0&&xe(o,void 0,"AAD");const s=t(e,n,mx),i=sx(r.length,o?o.length:0,!0),a=fx.create(s);o&&eu(a,o),eu(a,r),a.update(i);const c=a.digest();return Xt(s,i),c}const wx=t=>(e,n,r)=>({encrypt(s,i){const a=s.length;i=Qa(a+16,i,!1),i.set(s);const c=i.subarray(0,-16);t(e,n,c,c,1);const l=tu(t,e,n,c,r);return i.set(l,a),Xt(l),i},decrypt(s,i){i=Qa(s.length-16,i,!1);const a=s.subarray(0,-16),c=s.subarray(-16),l=tu(t,e,n,a,r);if(!nx(c,l))throw Xt(l),new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,n,i,i,1),Xt(l),i}}),nu=ox({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},wx(px));function yx(t,e,n){return ol(t),n===void 0&&(n=new Uint8Array(t.outputLen)),gp(t,n,e)}const Lr=Uint8Array.of(0),bx=Uint8Array.of();function vx(t,e,n,r=32,o){ol(t),Lt(r,"length"),Bt(e,void 0,"prk");const s=t.outputLen;if(e.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=bx:Bt(n,void 0,"info"),!i)return new Uint8Array;const a=new Uint8Array(i*s),{iHash:c,oHash:l}=gp.create(t,e),d=new Uint8Array(s),u=i>1?t.create():void 0;for(let h=0;h<i-1;h++){Lr[0]=h+1;const g=c._cloneInto(u);h&&g.update(d),g.update(n).update(Lr).digestInto(d),l._cloneInto(u).update(d).digestInto(d),a.set(d,s*h)}if(Lr[0]=i,i>1&&c.update(d),c.update(n).update(Lr).digestInto(d),l.update(d).digestInto(d),a.set(d,s*(i-1)),c.destroy(),l.destroy(),u?.destroy(),d!==a&&hn(d),hn(Lr),r===a.length)return a;const f=a.slice(0,r);return hn(a),f}const vp={hashSHA256(t){return Fi(t.subarray())},getHKDF(t,e){const n=yx(Fi,e,t),o=vx(Fi,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 t=jo.utils.randomSecretKey();return{publicKey:jo.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:jo.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return jo.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,n,r){return nu(r,e,n).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,n,r,o){return nu(r,e,n).decrypt(t.subarray(),o)}},Sx=vp;function xx(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,n)=>t.generateX25519SharedKey(e.privateKey,n).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}const Ps=t=>{const e=Pt(2);return e[0]=t>>8,e[1]=t,e};Ps.bytes=2;const Ns=t=>{if(t.length<2)throw RangeError("Could not decode int16BE");if(t instanceof Uint8Array){let e=0;return e+=t[0]<<8,e+=t[1],e}return t.getUint16(0)};Ns.bytes=2;function Ex(t){return{xxHandshakeSuccesses:t.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:t.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:t.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:t.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:t.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Sp(t,e){!e.enabled||!Ao||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${te(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${te(t.privateKey,"hex")}`)):e("Missing local static keys."))}function xp(t,e){!e.enabled||!Ao||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${te(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${te(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Ax(t,e){!e.enabled||!Ao||e(t?`REMOTE_STATIC_PUBLIC_KEY ${te(t.subarray(),"hex")}`:"Missing remote static public key.")}function Ep(t,e){!e.enabled||!Ao||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${te(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Ap(t,e,n){!n.enabled||!Ao||(n(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&te(t.k,"hex")}`),n(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&te(e.k,"hex")}`))}class Qr extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=Qr.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}const kx=0,Ix=4294967295,Cx="Cipherstate has reached maximum n, a new handshake must be performed";class Rx{n;bytes;view;constructor(e=kx){this.n=e,this.bytes=He(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>Ix)throw new Error(Cx)}}const nr=He(0);class Uo{k;n;crypto;constructor(e,n=void 0,r=0){this.crypto=e,this.k=n,this.n=new Rx(r)}hasKey(){return!!this.k}encryptWithAd(e,n){if(!this.hasKey())return n;this.n.assertValue();const r=this.crypto.encrypt(n,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,n,r){if(!this.hasKey())return n;this.n.assertValue();const o=this.crypto.decrypt(n,this.n.getBytes(),e,this.k,r);return this.n.increment(),o}}class Tx{cs;ck;h;crypto;constructor(e,n){this.crypto=e;const r=be(n,"utf-8");this.h=Nx(e,r),this.ck=this.h,this.cs=new Uo(e)}mixKey(e){const[n,r]=this.crypto.hkdf(this.ck,e);this.ck=n,this.cs=new Uo(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new se(this.h,e))}encryptAndHash(e){const n=this.cs.encryptWithAd(this.h,e);return this.mixHash(n),n}decryptAndHash(e){const n=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),n}split(){const[e,n]=this.crypto.hkdf(this.ck,nr);return[new Uo(this.crypto,e),new Uo(this.crypto,n)]}}class Px{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:n,protocolName:r,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=n,this.ss=new Tx(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 e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,n=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<n+32)throw new Error("message is not long enough");this.re=e.sublist(n,n+32),this.ss.mixHash(this.re)}readS(e,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(e.byteLength<n+r)throw new Error("message is not long enough");const o=e.sublist(n,n+r);return this.rs=this.ss.decryptAndHash(o),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class kp extends Px{writeMessageA(e){return new se(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const n=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new se(n,r,this.ss.encryptAndHash(e))}writeMessageC(e){const n=this.writeS();return this.writeSE(),new se(n,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(n){throw new Qr(`handshake stage 0 validation fail: ${n.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();const n=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+n))}catch(n){throw new Qr(`handshake stage 1 validation fail: ${n.message}`)}}readMessageC(e){try{const n=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(n))}catch(n){throw new Qr(`handshake stage 2 validation fail: ${n.message}`)}}}function Nx(t,e){if(e.length<=32){const n=He(32);return n.set(e),n}else return t.hash(e)}var Ls;(function(t){let e;t.codec=()=>(e==null&&(e=ti((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 Ed('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 Ed('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(n.string());break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>ei(n,t.codec()),t.decode=(n,r)=>Qs(n,t.codec(),r)})(Ls||(Ls={}));var Bs;(function(t){let e;t.codec=()=>(e==null&&(e=ti((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),Ls.codec().encode(n.extensions,r)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={identityKey:He(0),identitySig:He(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=Ls.codec().decode(n,n.uint32(),{limits:o.limits?.extensions});break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>ei(n,t.codec()),t.decode=(n,r)=>Qs(n,t.codec(),r)})(Bs||(Bs={}));async function Ip(t,e,n){const r=await t.sign(Rp(e));return Bs.encode({identityKey:ni(t.publicKey),identitySig:r,extensions:n})}async function Cp(t,e,n){try{const r=Bs.decode(t),o=Ga(r.identityKey);if(n?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${n}`);if(!e)throw new Error("Remote static does not exist");const s=Rp(e);if(!await o.verify(s,r.identitySig))throw new Error("Invalid payload signature");return r}catch(r){throw new Hm(r.message)}}function Rp(t){const e=be("noise-libp2p-static-key:");return t instanceof Uint8Array?Da([e,t],e.length+t.length):(t.prepend(e),t)}class Lx extends wp{stream;handshake;metrics;decoder;constructor(e,n,r){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=n,this.metrics=r,this.decoder=new GS({lengthDecoder:Ns,maxBufferSize:16*1024*1024,encodingLength:()=>2});const o=c=>{try{for(const l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);const s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);const i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);const a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){const n=new se;for(let r=0;r<e.byteLength;r+=Xd){let o=r+Xd;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(r,o)):s=this.handshake.encrypt(e.sublist(r,o)),this.metrics?.encryptedPackets.increment(),n.append(Ps(s.byteLength)),n.append(s)}return n}decrypt(e){const n=new se;for(let r=0;r<e.byteLength;r+=uo){let o=r+uo;if(o>e.byteLength&&(o=e.byteLength),o-Yd<r)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(r,o):s=e.sublist(r,o);const i=e.subarray(r,o-Yd);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(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}}function ru(t,e,n){return new Lx(t,e,n)}async function Bx(t,e){const{log:n,connection:r,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Ip(s,a.publicKey,l),u=new kp({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Sp(u.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(u.writeMessageA(nr),e),n.trace("Stage 0 - Initiator finished sending first message."),xp(u.e,n),n.trace("Stage 1 - Initiator waiting to receive first message from responder...");const f=u.readMessageB(await r.read(e));n.trace("Stage 1 - Initiator received the message."),Ep(u.re,n),Ax(u.rs,n),n.trace("Initiator going to check remote's signature...");const h=await Cp(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),e),n.trace("Stage 2 - Initiator sent message with signed payload.");const[g,m]=u.ss.split();return Ap(g,m,n),{payload:h,encrypt:b=>g.encryptWithAd(nr,b),decrypt:(b,w)=>m.decryptWithAd(nr,b,w)}}async function _x(t,e){const{log:n,connection:r,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Ip(s,a.publicKey,l),u=new kp({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Sp(u.s,n),n.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await r.read(e)),n.trace("Stage 0 - Responder received first message."),Ep(u.re,n),n.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await r.write(u.writeMessageB(d),e),n.trace("Stage 1 - Responder sent the second handshake message with signed payload."),xp(u.e,n),n.trace("Stage 2 - Responder waiting for third handshake message...");const f=u.readMessageC(await r.read(e));n.trace("Stage 2 - Responder received the message, finished handshake.");const h=await Cp(f,u.rs,c),[g,m]=u.ss.split();return Ap(g,m,n),{payload:h,encrypt:b=>m.encryptWithAd(nr,b),decrypt:(b,w)=>g.decryptWithAd(nr,b,w)}}class Ox{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,n={}){const{staticNoiseKey:r,extensions:o,crypto:s,prologueBytes:i}=n,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");const c=s??Sx;this.crypto=xx(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Ex(a):void 0,r?this.staticKey=c.generateX25519KeyPairFromSeed(r):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??He(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Ym]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,n){const r=e.log?.newScope("noise")??this.log,o=Vd(e,{lengthEncoder:Ps,lengthDecoder:Ns,maxDataLength:uo}),s=await this.performHandshakeInitiator(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=Ga(s.payload.identityKey);return{connection:ru(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:dr(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;const n=this.components.upgrader.getStreamMuxers();if(n!=null)for(const r of e){const o=n.get(r);if(o!=null)return o}if(e.length)throw new qm("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,n){const r=e.log?.newScope("noise")??this.log,o=Vd(e,{lengthEncoder:Ps,lengthDecoder:Ns,maxDataLength:uo}),s=await this.performHandshakeResponder(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=Ga(s.payload.identityKey);return{connection:ru(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:dr(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,n,r,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Bx({connection:e,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(e,n,r,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await _x({connection:e,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 Dx(t={}){return e=>new Ox(e,t)}const Fx="termdock-e2ee-v1",tc=3600*1e3,ou=512*1024*1024,nc=4*1024*1024,Jo=()=>{},si=Object.assign(Jo,{enabled:!1,error:Jo,trace:Jo,newScope:()=>si});Object.freeze(si);async function Tp(){const t=await tv();return{privateKey:t,peerId:dr(t.publicKey).toString()}}function Mx(t){return btoa(String.fromCharCode(...ov(t.privateKey)))}function su(t){if(t.length>512||!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Invalid identity encoding");const e=rv(Uint8Array.from(atob(t),n=>n.charCodeAt(0)));if(e.type!=="Ed25519")throw new Error("Only Ed25519 device identities are supported");return{privateKey:e,peerId:dr(e.publicKey).toString()}}class Pp{constructor(e=Jo){this.consumed=e}consumed;chunks=[];size=0;ended=!1;error;wake;push(e){if(this.ended)throw this.error??new Error("Byte stream closed");if(this.size+e.byteLength>nc)throw new Error("Secure stream buffer limit exceeded");this.chunks.push(e.slice()),this.size+=e.byteLength,this.wake?.()}end(e){this.ended=!0,this.error??=e,this.wake?.()}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const e=this.chunks.shift();if(e)this.size-=e.byteLength,yield e,this.consumed();else{if(this.ended)return;await new Promise(n=>{this.wake=n})}}}}class jx extends wp{constructor(e,n){super({log:si,direction:n?"outbound":"inbound",maxReadBufferLength:nc,maxWriteBufferLength:nc}),this.duplex=e,this.finished=e.sink(this.outgoing).catch(r=>{this.abort(ur(r))}),this.readTransport()}duplex;outgoing=new Pp(()=>this.onMuxerDrain());finished;async readTransport(){try{for await(const e of this.duplex.source)this.onData(e.slice());this.onTransportClosed()}catch(e){this.onTransportClosed(ur(e))}}sendData(e){return this.outgoing.push(e.subarray()),{sentBytes:e.byteLength,canSendMore:!1}}sendReset(e){this.outgoing.end(e),this.duplex.close?.(e)}sendPause(){}sendResume(){}async close(){this.outgoing.end(),this.duplex.close?.(),this.onTransportClosed(),await this.finished}}function ur(t){return t instanceof Error?t:new Error("Secure transport failed")}class Ux extends Error{code="E2EE_REHANDSHAKE_REQUIRED";constructor(){super("Encrypted connection lifetime reached; establish a new handshake without replaying pending input")}}function $x(t){const e=t?.maxAgeMs??tc,n=t?.maxBytesPerDirection??ou;if(!Number.isSafeInteger(e)||e<=0||e>tc||!Number.isSafeInteger(n)||n<=0||n>ou)throw new Error("Encrypted connection limits cannot exceed the production maximum");return{maxAgeMs:e,maxBytesPerDirection:n}}async function Hx(t){const{identity:e,duplex:n,initiator:r,targetPinnedPeerId:o,signal:s}=t,i=$x(t.limits);if(typeof Reflect.get(Promise,"withResolvers")!="function"||typeof globalThis.crypto?.getRandomValues!="function")throw new Error("End-to-end encryption requires Node.js 22+ or a modern browser with Promise.withResolvers and secure random support");if(r&&!o)throw new Error("A pinned target identity is required");const a=o?cv(o):void 0;if(a&&a.type!=="Ed25519")throw new Error("Only Ed25519 target identities are supported");if(e.peerId!==dr(e.privateKey.publicKey).toString())throw new Error("Local identity mismatch");if(s?.aborted)throw s.reason??new Error("Connection aborted");const c=new jx(n,r),l=new AbortController,d=setTimeout(()=>{const h=new Error("Encrypted handshake timed out");l.abort(h),c.abort(h)},15e3),u=()=>{l.abort(s?.reason),c.abort(ur(s?.reason))};s?.addEventListener("abort",u,{once:!0}),c.addEventListener("close",()=>s?.removeEventListener("abort",u),{once:!0});const f=Dx({crypto:vp,prologueBytes:new TextEncoder().encode(Fx)})({privateKey:e.privateKey,peerId:dr(e.privateKey.publicKey),logger:{forComponent:()=>si},upgrader:{getStreamMuxers:()=>new Map}});try{const h=await(r?f.secureOutbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}):f.secureInbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}));if(h.remotePeer.type!=="Ed25519")throw new Error("Unsupported remote identity");return{authenticatedPeerId:h.remotePeer.toString(),duplex:qx(h.connection,i)}}catch(h){throw c.abort(ur(h)),h}finally{clearTimeout(d),s?.removeEventListener("abort",u)}}function qx(t,e){const n=new Pp,r=performance.now(),o=Date.now();let s=0,i=0,a;const c=()=>(a??=new Ux,n.end(a),t.abort(a),a),l=setTimeout(c,e.maxAgeMs);typeof l=="object"&&l.unref?.();const d=(f,h)=>{if(a)throw a;if(Math.max(performance.now()-r,Date.now()-o)>=e.maxAgeMs||f+h>=e.maxBytesPerDirection)throw c()};t.addEventListener("message",f=>{try{d(i,f.data.byteLength),i+=f.data.byteLength,n.push(f.data.subarray())}catch(h){t.abort(ur(h))}}),t.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 h of f)d(s,h.byteLength),s+=h.byteLength,t.send(h)||await t.onDrain()}catch(h){throw t.abort(ur(h)),h}},close(f){f?t.abort(f):t.close()}}}const Np=1012,Lp="Encrypted transport renewed";class hl{constructor(e=64){this.limit=e}limit;items=[];wake;ended=!1;error;push(e){if(this.ended)throw new Error("Channel closed");if(this.items.length>=this.limit)throw this.end(new Error("Channel queue exceeded")),this.error;this.items.push(e),this.wake?.()}end(e){this.ended=!0,this.error??=e,this.wake?.()}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const e=this.items.shift();if(e!==void 0){yield e;continue}if(this.ended)return;await new Promise(n=>{this.wake=n}),this.wake=void 0}}}const Hi=2*1024*1024,Kx=new TextEncoder,zx=new TextDecoder("utf-8",{fatal:!0});class Wx{constructor(e){this.duplex=e;const n=this;this.done=e.sink((async function*(){for await(const r of n.outgoing)try{yield r}finally{n.outgoingBytes-=r.byteLength}})()),this.done.catch(r=>this.close(r instanceof Error?r:new Error("Transport failed")))}duplex;outgoing=new hl(256);outgoingBytes=0;get hasPendingWrites(){return this.outgoingBytes>0}done;send(e){const n=Kx.encode(JSON.stringify(e));if(n.length>Hi)throw new Error("Record too large");const r=new Uint8Array(n.length+4);if(new DataView(r.buffer).setUint32(0,n.length),r.set(n,4),this.outgoingBytes+r.byteLength>4*1024*1024)throw new Error("Record queue byte budget exceeded");this.outgoingBytes+=r.byteLength;try{this.outgoing.push(r)}catch(o){throw this.outgoingBytes-=r.byteLength,o}}close(e){this.outgoing.end(e),this.duplex.close?.(e)}async*read(){let e=new Uint8Array(0);for await(const n of this.duplex.source){if(e.length+n.length>Hi*2+8)throw new Error("Record buffer exceeded");const r=new Uint8Array(e.length+n.length);for(r.set(e),r.set(n,e.length),e=r;e.length>=4;){const o=new DataView(e.buffer,e.byteOffset,4).getUint32(0);if(o>Hi||o===0)throw new Error("Invalid record size");if(e.length<o+4)break;const s=JSON.parse(zx.decode(e.subarray(4,o+4)));if(!s||typeof s!="object"||typeof s.id!="string"||typeof s.type!="string")throw new Error("Invalid record");yield s,e=e.slice(o+4)}}if(e.length)throw new Error("Truncated record")}}function Bp(t){let e="";for(let n=0;n<t.length;n+=8192)e+=String.fromCharCode(...t.subarray(n,n+8192));return btoa(e)}function _p(t){const e=atob(t);return Uint8Array.from(e,n=>n.charCodeAt(0))}function Gx(t){const e=new hl(64);t.binaryType="arraybuffer";const n=r=>{e.end(r),t.close(1e3)};return t.addEventListener("message",r=>{try{if(!(r.data instanceof ArrayBuffer)||r.data.byteLength>1024*1024)throw new Error("Invalid encrypted frame");e.push(new Uint8Array(r.data))}catch{n(new Error("Encrypted transport rejected frame"))}}),t.addEventListener("close",()=>e.end()),t.addEventListener("error",()=>e.end(new Error("Encrypted transport disconnected"))),{source:e,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(;t.bufferedAmount>256*1024;){if(t.readyState!==1||Date.now()-i>15e3)throw new Error("Encrypted transport congested");await new Promise(a=>setTimeout(a,10))}if(t.readyState!==1)throw new Error("Encrypted transport closed");t.send(o.subarray(s,s+64*1024))}}catch(o){throw n(o instanceof Error?o:new Error("Encrypted transport failed")),o}}}}const Op=8,Dp=128,Vx=5*1024*1024,Xx=Dp+Op+8,Yx=256,$o=3e4,Br=64*1024;function zt(t){return t instanceof Error?t:new Error(String(t??"Secure connection closed"))}function iu(t){if(!t.startsWith("/")||t.startsWith("//")||t.includes("#"))throw new Error("A local API path is required");return t}class Fp extends EventTarget{constructor(e,n,r){super(),this.url=e,this.transmit=n,this.disconnect=r}url;transmit;disconnect;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;binaryType="arraybuffer";bufferedAmount=0;protocol="termdock-e2ee-v1";extensions="";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;send(e){if(this.readyState!==1)throw new Error("Secure socket is not open");if(typeof e!="string"||new TextEncoder().encode(e).length>1024*1024)throw new Error("Unsupported socket payload");this.transmit(e)}close(e=1e3,n=""){this.readyState!==3&&(this.disconnect(),this.finish(e,n))}accept(e){if(this.readyState!==3)if(e.type==="ws-ready"){this.readyState=1;const n=new Event("open");this.dispatchEvent(n),this.onopen?.(n)}else if(e.type==="ws-data"&&typeof e.data=="string"){const n=new MessageEvent("message",{data:e.data});this.dispatchEvent(n),this.onmessage?.(n)}else e.type==="ws-close"?this.finish(typeof e.code=="number"?e.code:1e3,typeof e.reason=="string"?e.reason:""):e.type==="error"&&this.fail(zt(e.error))}fail(e){if(this.readyState===3)return;const n=new Event("error");this.dispatchEvent(n),this.onerror?.(n),this.finish(1006,e.message)}finish(e,n){if(this.readyState===3)return;this.readyState=3;const r=new CloseEvent("close",{code:e,reason:n,wasClean:e===1e3});this.dispatchEvent(r),this.onclose?.(r)}}class Zx{constructor(e,n,r){this.channel=e,this.identity=n,this.targetPeerId=r,this.read().catch(o=>this.close(zt(o))),e.done.catch(o=>this.close(zt(o)))}channel;identity;targetPeerId;establishedAt=performance.now();establishedWallTime=Date.now();lastInputAt=-1/0;pending=new Map;waiting=[];stopped=!1;closeReason;get canSwitchTransport(){return!this.channel.hasPendingWrites&&performance.now()-this.lastInputAt>=2e3&&![...this.pending.values()].some(e=>e.kind!=="socket")&&!this.waiting.some(e=>e.kind!=="socket")}get renewalDue(){return!this.stopped&&Math.max(performance.now()-this.establishedAt,Date.now()-this.establishedWallTime)>=tc-5*6e4}get closed(){return this.stopped}hasCapacity(e){if(this.pending.size>=Xx)return!1;const n=[...this.pending.values()].filter(r=>r.kind===e).length;return e==="http"?n<Op:e==="socket"?n<Dp:!0}allocate(e){if(this.stopped)throw this.closeReason??new Error("Secure connection closed");const n=crypto.randomUUID(),r=new hl(4);return this.pending.set(n,{queue:r,kind:e}),{id:n,queue:r}}reserve(e,n){return n?.aborted?Promise.reject(n.reason):this.stopped?Promise.reject(this.closeReason??new Error("Secure connection closed")):this.hasCapacity(e)?Promise.resolve(this.allocate(e)):this.waiting.length>=Yx?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("连接等待超时,请重试。")),$o),c={kind:e,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 e=0;e<this.waiting.length;){const n=this.waiting[e];if(!this.hasCapacity(n.kind)){e++;continue}this.waiting.splice(e,1),n.cleanup(),n.resolve(this.allocate(n.kind))}}async read(){try{for await(const e of this.channel.read()){const n=this.pending.get(e.id);n&&(n.socket?(n.socket.accept(e),(e.type==="ws-close"||e.type==="error")&&this.release(e.id)):(n.queue.push(e),(e.type==="end"||e.type==="error")&&(n.cancelUpload?.(),this.release(e.id))))}}finally{this.close(new Error("Secure connection closed"))}}release(e){this.pending.get(e)?.queue.end(),this.pending.delete(e),this.dispatchWaiting()}async request(e,n){const{id:r,queue:o}=await this.reserve("request"),s=setTimeout(()=>this.close(new Error("Secure connection timed out")),Math.max(1e3,Math.min($o,n?.timeoutMs??$o)));try{if(this.stopped)throw this.closeReason;this.channel.send({...e,id:r});const i=(await o[Symbol.asyncIterator]().next()).value;if(!i)throw new Error("Secure request closed");if(i.type==="error")throw zt(i.error);return i}finally{clearTimeout(s),this.release(r)}}openSocket(e){iu(e);let n;const r=new AbortController,o=new Fp(e,s=>{if(n){try{JSON.parse(s)?.type==="input"&&(this.lastInputAt=performance.now())}catch{}this.channel.send({id:n,type:"ws-data",data:s})}},()=>{if(r.abort(),n)try{this.channel.send({id:n,type:"ws-close"})}finally{this.release(n)}});return this.reserve("socket",r.signal).then(s=>{if(n=s.id,o.readyState===3){this.release(n);return}const i=this.pending.get(n);if(!i)throw new Error("Secure connection closed");i.socket=o,this.channel.send({id:n,type:"ws-open",path:e})}).catch(s=>{n&&this.release(n),o.fail(zt(s))}),o}async fetch(e,n){const r=typeof location>"u"?"https://termdock.invalid":location.origin,o=e instanceof Request?e:null,s=new URL(o?.url??String(e),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=iu(s.pathname+s.search),l=s.pathname==="/api/terminal/fs/upload"?110*1024*1024:Vx;if(i.signal.aborted)throw i.signal.reason;const d={};i.headers.forEach((k,N)=>{["cookie","authorization","host","connection","content-length"].includes(N)||(d[N]=k)});const{id:u,queue:f}=await this.reserve("http",i.signal),h=f[Symbol.asyncIterator]();let g;const m=()=>{g?.cancel().catch(()=>{})},b=this.pending.get(u);if(!b)throw new Error("Secure connection closed");b.cancelUpload=m;const w=()=>{m();try{this.channel.send({id:u,type:"cancel"})}catch{}f.end(zt(i.signal.reason??"Request aborted")),this.release(u)};i.signal.addEventListener("abort",w,{once:!0});const R=()=>{i.signal.removeEventListener("abort",w),this.release(u)},y=async()=>{let k;try{const N=(await Promise.race([h.next(),new Promise((x,T)=>{k=setTimeout(()=>T(new Error("服务响应超时,请重试。")),$o)})])).value;if(!N)throw new Error("Secure response ended unexpectedly");if(N.type==="error")throw zt(N.error);return N}finally{clearTimeout(k)}};try{if(i.signal.aborted)throw i.signal.reason;if(this.channel.send({id:u,type:"http",method:a,path:c,headers:d}),i.body){const S=i.body.getReader();g=S;let v=0,A=0;try{for(;;){const{done:_,value:B}=await S.read();if(_)break;if(v+=B.byteLength,v>l)throw new Error("Request body exceeds upload limit");for(let I=0;I<B.byteLength;I+=Br){if(this.channel.send({id:u,type:"upload",data:Bp(B.subarray(I,I+Br))}),(await y()).type!=="upload-ack")throw new Error("Invalid upload acknowledgement");A+=Math.min(Br,B.byteLength-I),n?.onUploadProgress?.(A)}}}catch(_){throw await S.cancel(_).catch(()=>{}),_}finally{g=void 0,S.releaseLock()}}if(i.signal.aborted||this.stopped)throw new Error("Request aborted");this.channel.send({id:u,type:"upload-end"});const k=await y();if(k.type!=="head"||typeof k.status!="number")throw new Error("Invalid response header");const N=new Headers(k.headers);if(a==="HEAD"||[204,205,304].includes(k.status)){if((await y()).type!=="end")throw new Error("Unexpected response body");return R(),new Response(null,{status:k.status,headers:N})}let x=!1;const T=new ReadableStream({pull:async S=>{try{x&&(this.channel.send({id:u,type:"ack"}),x=!1);const v=await y();if(v.type==="end"){S.close(),R();return}if(v.type!=="chunk"||typeof v.data!="string")throw new Error("Invalid response chunk");const A=_p(v.data);if(A.length>Br)throw new Error("Response chunk exceeds budget");S.enqueue(A),x=!0}catch(v){S.error(v),w(),R()}},cancel:()=>{w(),R()}},{highWaterMark:Br,size:S=>S.byteLength});return new Response(T,{status:k.status,headers:N})}catch(k){throw w(),R(),k}}retire(){for(const e of this.pending.values())e.socket?.accept({id:"",type:"ws-close",code:Np,reason:Lp});this.close()}close(e=new Error("Secure connection closed")){if(!this.stopped){this.stopped=!0,this.closeReason=e;for(const n of this.waiting.splice(0))n.cleanup(),n.reject(e);for(const n of this.pending.values())n.queue.end(e),n.cancelUpload?.(),n.socket?.fail(e);this.pending.clear(),this.channel.close(e)}}}async function bn(t){const e=new URL(t.url);if(!["wss:","ws:"].includes(e.protocol))throw new Error("A WebSocket endpoint is required");if(e.protocol==="ws:"&&!["127.0.0.1","localhost","[::1]"].includes(e.hostname))throw new Error("Remote secure channels require WSS");const n=t.identity??await Tp(),r=(t.socketFactory??(c=>new WebSocket(c)))(e.href),o=Gx(r),s=new AbortController,i=setTimeout(()=>s.abort(new Error("Secure handshake timed out")),2e4),a=t.signal?AbortSignal.any([t.signal,s.signal]):s.signal;try{await new Promise((d,u)=>{if(a.aborted){u(a.reason);return}const f=()=>{a.removeEventListener("abort",m),r.removeEventListener("open",h),r.removeEventListener("error",g),r.removeEventListener("close",g)},h=()=>{f(),d()},g=()=>{f(),u(new Error("Secure transport unavailable"))},m=()=>{f(),u(a.reason)};a.addEventListener("abort",m,{once:!0}),r.addEventListener("open",h),r.addEventListener("error",g),r.addEventListener("close",g),r.readyState===1&&h()});const c=await Hx({identity:n,duplex:o,initiator:!0,targetPinnedPeerId:t.targetPeerId,signal:a}),l=new Zx(new Wx(c.duplex),n,c.authenticatedPeerId);if(t.pairingCode)try{await l.request({type:"pair",code:t.pairingCode})}catch(d){throw l.close(zt(d)),d}return l}catch(c){throw r.close(),c}finally{clearTimeout(i)}}const au=256*1024,Jx=1024*1024;class Qx extends EventTarget{constructor(e,n,r=o=>new WebSocket(o)){if(super(),this.url=e,!/^[a-zA-Z0-9_.:-]{1,160}$/.test(n))throw new Error("Invalid target identity");this.upstream=r(e),this.deadline=setTimeout(()=>this.fail("Relay connection timed out"),2e4),this.upstream.addEventListener("message",o=>{if(this.readyState!==3)try{if(typeof o.data!="string"||new TextEncoder().encode(o.data).length>au)throw new Error("Invalid relay envelope");const s=JSON.parse(o.data);if(s.type==="ready"&&!this.requested){this.requested=!0,this.transmit({type:"open",streamId:this.streamId,serviceId:n});return}if(s.streamId!==this.streamId)return;if(s.type==="opened"&&this.readyState===0){clearTimeout(this.deadline),this.readyState=1;const l=new Event("open");this.dispatchEvent(l),this.onopen?.(l);return}if(s.type==="close"){this.finish(1001,"Relay route closed"),this.upstream.close();return}if(s.type!=="data"||this.readyState!==1||s.encoding!=="base64"||typeof s.payload!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(s.payload))throw new Error("Invalid ciphertext relay frame");const i=_p(s.payload),a=this.binaryType==="blob"?new Blob([i]):i.buffer,c=new MessageEvent("message",{data:a});this.dispatchEvent(c),this.onmessage?.(c)}catch{this.fail("Relay protocol rejected frame")}}),this.upstream.addEventListener("close",o=>this.finish(o.code||1006,"Relay disconnected")),this.upstream.addEventListener("error",()=>this.fail("Relay transport unavailable"))}url;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;protocol="";extensions="";binaryType="arraybuffer";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;upstream;streamId=crypto.randomUUID();requested=!1;deadline;get bufferedAmount(){return this.upstream.bufferedAmount}transmit(e){const n=JSON.stringify(e);if(this.upstream.readyState!==1||this.upstream.bufferedAmount+n.length>Jx||n.length>au)throw new Error("Relay unavailable or congested");this.upstream.send(n)}send(e){if(this.readyState!==1)throw new Error("Relay socket is not open");let n;if(ArrayBuffer.isView(e))n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof ArrayBuffer)n=new Uint8Array(e);else throw new Error("Relay secure transport requires binary bytes");try{this.transmit({type:"data",streamId:this.streamId,encoding:"base64",payload:Bp(n)})}catch(r){throw this.fail("Relay transport congested"),r}}close(e=1e3,n=""){if(this.readyState!==3){try{this.requested&&this.transmit({type:"close",streamId:this.streamId})}catch{}this.finish(e,n),this.upstream.close()}}fail(e){if(this.readyState===3)return;const n=new Event("error");this.dispatchEvent(n),this.onerror?.(n),this.finish(1006,e),this.upstream.close()}finish(e,n){if(this.readyState===3)return;clearTimeout(this.deadline),this.readyState=3;const r=new CloseEvent("close",{code:e,reason:n,wasClean:e===1e3});this.dispatchEvent(r),this.onclose?.(r)}}function Mp(t){return e=>new Qx(e,t)}function eE(t){if(typeof t!="string"||!t.startsWith("/api/")||/[\\\x00-\x20\x7f#]/.test(t))return null;const e=t.split("?")[0];if(e.includes("//"))return null;try{const r=e.split("/").map((o,s)=>{if(s===0||o===""&&s===e.split("/").length-1)return o;const i=decodeURIComponent(o);if(!i||i==="."||i===".."||/[\\/\x00-\x1f\x7f]/.test(i)||/%[a-f0-9]{2}/i.test(i))throw new Error("Ambiguous API path");return i}).join("/");return r.endsWith("/")&&!r.startsWith("/api/terminal/fs/preview/")?null:r}catch{return null}}function tE(t){if(!("serviceWorker"in navigator))return()=>{};const e=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/")||e.size>=32||typeof i!="string"||c!==void 0&&(!(c instanceof ArrayBuffer)||c.byteLength>5*1024*1024)){o.postMessage({type:"error"}),o.close();return}if(d!==void 0&&(typeof d!="string"||!d.endsWith("/")||!/^\/api\/terminal\/fs\/preview\/[a-f0-9]{32}\//.test(d)||!["GET","HEAD"].includes(i)||!eE(u.pathname)?.startsWith(d))){o.postMessage({type:"error"}),o.close();return}const f=new AbortController;let h,g,m=!1,b=!1;const w=()=>{b||(b=!0,e.delete(w),f.abort(),h?.cancel().catch(()=>{}),o.close())};e.add(w),o.onmessage=R=>{if(R.data?.type==="cancel"){w();return}R.data?.type!=="pull"||m||b||(m=!0,(async()=>{if(!h){o.postMessage({type:"end"}),w();return}if(!g?.length){const k=await h.read();if(k.done){o.postMessage({type:"end"}),w();return}g=k.value}const y=g.slice(0,64*1024);g=g.subarray(y.length),o.postMessage({type:"chunk",data:y.buffer},[y.buffer])})().catch(()=>{o.postMessage({type:"error"}),w()}).finally(()=>{m=!1}))},o.onmessageerror=w,o.start(),(async()=>{const R=await t();if(b)return;if(l&&l!==R.targetPeerId)throw new Error("Preview target changed");const y=await R.fetch(u.pathname+u.search,{method:i,headers:a,body:["GET","HEAD"].includes(i)?void 0:c,signal:f.signal});if(b){await y.body?.cancel();return}h=y.body?.getReader();const k={};y.headers.forEach((N,x)=>{k[x]=N}),o.postMessage({type:"head",status:y.status,headers:k,bodyless:!h,targetPeerId:R.targetPeerId})})().catch(()=>{b||(o.postMessage({type:"error"}),w())})};return navigator.serviceWorker.addEventListener("message",n),()=>{navigator.serviceWorker.removeEventListener("message",n);for(const r of[...e])r()}}class et extends Error{constructor(){super("Device authorization expired or revoked")}}const Ho=new WeakMap;function yr(t,e={}){const n=Ho.get(t);if(!t.closed&&n&&(!n.settled||Date.now()-n.at<(e.maxAgeMs??1e3)))return n.pending;const r={at:Date.now(),settled:!1,pending:void 0},o=nE(t,e.timeoutMs??5e3).then(s=>(r.at=Date.now(),r.settled=!0,s),s=>{throw Ho.get(t)===r&&Ho.delete(t),s});return r.pending=o,Ho.set(t,r),o}async function nE(t,e){const n=await t.request({type:"permissions"},{timeoutMs:e});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 et;return{fullService:o,grants:r,canManage:o&&r.length>0||r.some(s=>s.actions.includes("authorization.manage"))}}const jp="termdock-secure-last-path:",rE=10*6e4;function Up(t){try{const e=JSON.parse(sessionStorage.getItem(jp+t)||"null");return e&&typeof e.key=="string"&&Date.now()-e.at<rE?e.key:void 0}catch{return}}function rc(t,e){try{sessionStorage.setItem(jp+t,JSON.stringify({key:e,at:Date.now()}))}catch{}}function $p(t,e,n=!1){return new Promise((r,o)=>{let s=0,i=0,a=!1,c,l;const d=new Set,u=()=>{clearTimeout(l);for(const h of d)h.abort();d.clear()},f=()=>{if(a)return;if(s>=t.length){i||(a=!0,u(),o(c||new Error("没有可用的连接路线。")));return}if(i>=(n?1:2))return;const h=t[s++],g=performance.now(),m=w=>{performance.getEntriesByName("termdock:connection-path").length>64&&performance.clearMeasures("termdock:connection-path"),performance.measure("termdock:connection-path",{start:g,end:performance.now(),detail:{path:h.key.startsWith("relay:")?"relay":"direct",ok:w}})},b=new AbortController;d.add(b),i++,h.run(b.signal).then(w=>{if(m(!0),d.delete(b),a){e(w);return}a=!0,u(),r({value:w,key:h.key})},w=>{if(m(!1),d.delete(b),i--,!a){if(c=w,w instanceof et){a=!0,u(),o(w);return}f()}}),clearTimeout(l),!n&&s<t.length&&(l=setTimeout(f,400))};f()})}const oE=3,sE=1/0,iE=10,Hp="termdock-secure-workspace-limit";function qp(t){return t===1/0||Number.isInteger(t)&&t>=3&&t<=iE}function aE(){try{const t=localStorage.getItem(Hp),e=t==="unlimited"?1/0:Number(t);if(qp(e))return e}catch{}return navigator.maxTouchPoints>0?oE:sE}function cE(t,e,n,r){if(t.length<=r)return t;const o=new Set(["root",e,...n?[n]:[]]),s=[...t].reverse().sort((i,a)=>a.touchedAt-i.touchedAt);for(const i of s){if(o.size>=r)break;o.add(i.key)}return t.filter(i=>o.has(i.key))}const Kp="termdock-workspace",fo="termdock:workspace-visibility",oc="termdock:workspace-activate";function ii(){return window.parent!==window&&location.pathname==="/workspace.html"&&new URLSearchParams(location.search).get(Kp)||"root"}let cu,lu;function ht(){try{if(window.parent===window)return window.__termdockWorkspaceHost;const t=window.parent.__termdockWorkspaceHost;return t&&t!==cu&&(cu=t,lu={...t,subscribe(e){const n=t.subscribe(e,ii()),r=o=>{o.persisted||n()};return window.addEventListener("pagehide",r),()=>{n(),window.removeEventListener("pagehide",r)}}}),t?lu:void 0}catch{return}}function Qo(){const t=ht();return!t||t.snapshot().activeKey===ii()}function _s(t,e=!0){return ht()?.activate(t,e)??!1}function Un(t){ht()?.report(ii(),t)}const sc="termdock-secure-workspace-session:",zp="termdock-secure-last-workspace";function lE(){for(const t of["sessionStorage","localStorage"])try{const e=window[t].getItem(zp);if(e)return e}catch{}return null}function dE(t){for(const e of["sessionStorage","localStorage"])try{window[e].setItem(zp,t)}catch{}}function aR(t){if(t)try{const e=JSON.parse(localStorage.getItem(sc+t)||"null");return localStorage.removeItem(sc+t),e&&typeof e.sessionId=="string"&&Date.now()-e.at<6e4?e.sessionId:void 0}catch{return}}function uE(t){if(window.parent!==window||window.termdockDesktop)return;if(window.__termdockWorkspaceHost)return window.__termdockWorkspaceHost;let e={activeKey:"root",items:[{key:"root",service:t,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]};try{const u=lE(),f=t&&u!==t.targetPeerId?mn().find(h=>h.targetPeerId===u):void 0;f?.targetPeerId&&(e={activeKey:f.targetPeerId,items:[...e.items,{key:f.targetPeerId,service:f,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]})}catch{}let n=aE(),r=e.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=cE(e.items,e.activeKey,r,n),f=new Set(u.map(h=>h.key));e={...e,items:u};for(const[h,g]of o)g&&!f.has(g)&&o.delete(h);for(const h of s.keys())f.has(h)||s.delete(h);for(const h of i)f.has(h)||i.delete(h)},l=(u,f)=>{try{const h=f.document.createEvent("CustomEvent");if(h.initCustomEvent(fo,!1,!1,{active:e.activeKey===u}),f.dispatchEvent(h),e.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(oc,!1,!1),f.dispatchEvent(m)}}else f.document.activeElement?.blur?.()}catch{}},d={snapshot:()=>e,subscribe:(u,f)=>(o.set(u,f),()=>{o.delete(u)}),present(u){r=u},retentionLimit:()=>n,setRetentionLimit(u){if(qp(u)){n=u;try{localStorage.setItem(Hp,u===1/0?"unlimited":String(u))}catch{}c(),a()}},activate(u,f=!0){const h=zs(u);if(!h?.targetPeerId)return!1;const g=e.items.find(w=>w.service?.targetPeerId===h.targetPeerId),m=g?.key||h.targetPeerId,b=g?{...g,service:h,touchedAt:Date.now()}:{key:m,service:h,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()};e={activeKey:m,items:g?e.items.map(w=>w===g?b:w):[...e.items,b]},c(),dE(h.targetPeerId),f&&i.add(m),a();for(const[w,R]of s)l(w,R);return!0},report(u,f){const h=e.items.find(m=>m.key===u);if(!h||f.service&&h.service?.targetPeerId&&f.service.targetPeerId!==h.service.targetPeerId)return;const g={...h,...f};JSON.stringify(g)!==JSON.stringify(h)&&(e={...e,items:e.items.map(m=>m===h?g:m)},a())},attach(u,f){f&&e.items.some(h=>h.key===u)?(s.set(u,f),l(u,f)):s.delete(u)},focusSession(u,f){const h=mn().find(m=>m.targetPeerId===u);if(!h)return!1;try{localStorage.setItem(sc+u,JSON.stringify({sessionId:f,at:Date.now()}))}catch{return!1}d.activate(h,!1);const g=s.get(e.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 qi;async function tt(){return qi||(qi=(async()=>{const t=await new Promise((e,n)=>{const r=indexedDB.open("termdock-device-identity",1);r.onupgradeneeded=()=>r.result.createObjectStore("keys"),r.onsuccess=()=>e(r.result),r.onerror=()=>n(r.error)});try{const e=await new Promise((o,s)=>{const i=t.transaction("keys").objectStore("keys").get("identity");i.onsuccess=()=>o(i.result),i.onerror=()=>s(i.error)});if(e)return su(e);const n=await Tp();let r=n;return await new Promise((o,s)=>{const i=t.transaction("keys","readwrite"),a=i.objectStore("keys"),c=a.get("identity");c.onsuccess=()=>{typeof c.result=="string"?r=su(c.result):a.put(Mx(n),"identity")},i.oncomplete=()=>o(),i.onerror=()=>s(i.error)}),r}finally{t.close()}})()),qi}const Je="termdock:secure-state";let J,$n,Me,fr="direct",es=!1,du=0,ts=!1,uu=-1/0;const hr=globalThis.fetch.bind(globalThis);function re(){return Fc()}function rn(){return J}function fE(){return Me}function Wp(){J?.close(),Me?.close(),J=void 0,Me=void 0}async function Gp(){const t=await hr("/api/auth/status",{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error("Failed to query auth status");return t.json()}async function hE(){if(re()){await st();return}if((await Gp()).enabled)return;const t=await hr("/api/auth/open/parameters",{cache:"no-store"});if(!t.ok)throw new Error("Open service unavailable");const{serviceIdentity:e}=await t.json();if(typeof e!="string"||!e)throw new Error("Invalid service identity");await Qe({url:location.origin,targetPeerId:e,serviceName:location.hostname})}async function pE(t,e){const{startPasswordBootstrap:n,finishPasswordBootstrap:r}=await Jt(async()=>{const{startPasswordBootstrap:l,finishPasswordBootstrap:d}=await import("./passwordBootstrap-C7Gy7ATG.js");return{startPasswordBootstrap:l,finishPasswordBootstrap:d}},__vite__mapDeps([0,1,2,3])),o=l=>t===location.origin?l:new URL(l,t).href,s=async(l,d)=>{const u=await hr(o(l),{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(15e3),...d?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}:{}});if(!u.ok)throw new Error(u.status===429?"尝试次数较多,请稍后再试。":u.status===401?"密码不正确,请重新输入。":"暂时无法登录这台服务,请稍后重试。");return u.json()},{saltHex:i}=await s("/api/auth/password/parameters"),a=await tt(),c=await n(e,i);try{const l=await s("/api/auth/password/start",{startLoginRequest:c.startLoginRequest,clientIdentity:a.peerId});let d;try{d=await r(c,l,{clientIdentity:a.peerId,origin:location.origin})}catch{throw new Error("密码不正确,或服务身份无法验证。请检查后重试。")}return await s("/api/auth/password/finish",{attemptId:d.attemptId,finishLoginRequest:d.finishLoginRequest}),{url:t,targetPeerId:d.serverIdentity,serviceName:new URL(t).host,serviceOrigin:t}}finally{c.passwordKey=""}}async function pl(t,e){const n=re();if(n&&(n.serviceOrigin||n.url)===t)return await ic(n,e),n;try{return await pE(t,e)}catch(r){if(!(r instanceof TypeError)&&!(r instanceof DOMException))throw r;const o=(await Ke()).find(i=>i.targetPeerId&&(i.serviceOrigin||i.url)===t);if(!o?.targetPeerId)throw new Error("暂时连不上这台服务,请检查地址和网络。");const s={...o,targetPeerId:o.targetPeerId,serviceName:o.label};return await ic(s,e),s}}async function ic(t,e){const n=await gl(t),{startPasswordBootstrap:r,finishPasswordBootstrap:o}=await Jt(async()=>{const{startPasswordBootstrap:i,finishPasswordBootstrap:a}=await import("./passwordBootstrap-C7Gy7ATG.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(e,String(i.saltHex));const a=await n.request({type:"password-start",startLoginRequest:s.startLoginRequest,origin:location.origin}),c=await o(s,a,{clientIdentity:(await tt()).peerId,origin:location.origin});if(c.serverIdentity!==t.targetPeerId)throw new Error("服务身份发生变化。");await n.request({type:"password-finish",attemptId:c.attemptId,finishLoginRequest:c.finishLoginRequest})}catch{throw new Error("暂时无法登录,请检查目标服务密码与入口授权后重试。")}finally{s&&(s.passwordKey=""),n.close()}}async function gE(t){try{const e=re(),n=e?.serviceOrigin||location.origin,r=await pl(n,t);return await Qe({...r,routes:e?.routes,serviceName:e?.serviceName||r.serviceName}),Response.json({ok:!0})}catch(e){return Response.json({error:e instanceof Error?e.message:"暂时无法登录,请重试。",code:"INVALID_PASSWORD"},{status:401})}}async function fu(t,e){const n=_e(t),r=(await Ke()).find(i=>(i.serviceOrigin||i.url)===n&&i.targetPeerId);if(e===void 0&&r?.targetPeerId)try{return await Qe({...r,targetPeerId:r.targetPeerId,serviceName:r.label}),{}}catch(i){if(!(i instanceof et))throw i}if(e!==void 0){const i=await pl(n,e);if(r?.targetPeerId&&r.targetPeerId!==i.targetPeerId)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await Qe({...i,routes:r?.routes,serviceName:r?.label||i.serviceName}),{}}const o=await hr(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 Qe({url:n,targetPeerId:s,serviceName:r?.label||new URL(n).host,serviceOrigin:n}),{}}function Zt(t){const e=[...t.routes||[]];if(t.entryServiceId&&t.entryServiceId!==t.targetPeerId&&e.unshift({url:t.url,targetPeerId:t.entryServiceId}),!e.length&&t.routes===void 0)try{const n=JSON.parse(localStorage.getItem(Dc)||"null");n&&n.targetPeerId!==t.targetPeerId&&new URL(n.url).host===new URL(t.url).host&&e.push(n)}catch{}return e.flatMap((n,r)=>{try{return n.targetPeerId&&n.targetPeerId!==t.targetPeerId&&e.findIndex(o=>o.targetPeerId===n.targetPeerId)===r?[{url:_e(n.url),targetPeerId:n.targetPeerId}]:[]}catch{return[]}}).slice(0,4)}function br(t){const e=Zt(t),n=[t.serviceOrigin||t.url,...(t.routes||[]).slice(0,4).filter(o=>o.targetPeerId===t.targetPeerId).map(o=>o.url)],r=new Set;for(const o of n)try{const s=_e(o);e.some(i=>i.url===s)||r.add(s)}catch{}return[...r]}function vn(t){const e=new URL("/api/federation/secure",_e(t));return e.protocol=e.protocol==="https:"?"wss:":"ws:",e.href}async function Qt(t,e){return bn({url:vn(t.url),targetPeerId:t.targetPeerId,identity:await tt(),signal:e?AbortSignal.any([e,AbortSignal.timeout(5e3)]):AbortSignal.timeout(5e3)})}async function gl(t,e){const n=await tt(),r=br(t).map(i=>({key:`direct:${i}`,run:a=>bn({url:vn(i),targetPeerId:t.targetPeerId,identity:n,signal:AbortSignal.any([a,AbortSignal.timeout(8e3),...e?[e]:[]])})}));for(const i of Zt(t))r.push({key:`relay:${i.targetPeerId}:${i.url}`,run:async a=>{e&&(a=AbortSignal.any([a,e]));const c=[J,Me].find(d=>d&&!d.closed&&d.targetPeerId===i.targetPeerId),l=c||await Qt(i,a);try{if(a.aborted)throw a.reason;const d=await l.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(a.aborted)throw a.reason;if(typeof d.routeToken!="string")throw new Error("入口未允许此设备连接该服务。");const u=new URL(vn(i.url));return u.pathname="/api/federation/relay",u.searchParams.set("routeToken",d.routeToken),await bn({url:u.href,targetPeerId:t.targetPeerId,identity:n,socketFactory:Mp(t.targetPeerId),signal:AbortSignal.any([a,AbortSignal.timeout(8e3)])})}finally{c||l.close()}}});const o=Up(t.targetPeerId);r.sort((i,a)=>+(a.key===o)-+(i.key===o));const s=await $p(r,i=>i.close());return rc(t.targetPeerId,s.key),s.value}async function mE(t,e){const n=await gl(t,e);try{const o=(await n.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node;if(o?.serviceId!==t.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");return{...o,serviceId:t.targetPeerId}}finally{n.close()}}async function wE(t,e){const n=await gl(t,e),r=()=>n.close();e.addEventListener("abort",r,{once:!0});try{if(e.aborted||(await yr(n,{timeoutMs:3e3}),e.aborted))throw e.reason;return n}catch(o){throw n.close(),o}finally{e.removeEventListener("abort",r)}}async function Qe(t,e={}){const n=J,r=Me,o=await tt(),s=_e(t.serviceOrigin||t.url),i=(await Ke()).find(w=>w.targetPeerId===t.targetPeerId),a={...t,routes:t.routes??i?.routes},c=Zt(a),l=br(a);let d,u,f=t.pairingCode,h="direct";const g=new Set,m=new Map,b=async(w,R)=>{if(n&&!n.closed&&n.targetPeerId===w.targetPeerId)return n;if(r&&!r.closed&&r.targetPeerId===w.targetPeerId)return r;const y=m.get(w.targetPeerId);if(y&&!y.closed)return y;const k=await Qt(w,R);return g.add(k),m.set(w.targetPeerId,k),k};try{if(t.routeCode&&t.entryServiceId){const S=c.find(_=>_.targetPeerId===t.entryServiceId);if(!S)throw new Error("邀请缺少入口信息。");if((await(await b(S)).request({type:"route-pair",code:t.routeCode})).serviceId!==t.targetPeerId)throw new Error("邀请的目标服务不一致。");t.routeOnly&&await Tt({id:t.targetPeerId,url:s,label:t.serviceName||new URL(s).host,targetPeerId:t.targetPeerId,serviceOrigin:s,routes:c})}const w=[],R=async(S,v)=>{const A=()=>S.close();v.addEventListener("abort",A,{once:!0});try{if(v.aborted||(await yr(S),v.aborted))throw v.reason}catch(_){throw S.close(),_}finally{v.removeEventListener("abort",A)}};for(const S of l)w.push({key:`direct:${S}`,run:async v=>{const A=await bn({url:vn(S),targetPeerId:t.targetPeerId,pairingCode:f,identity:o,signal:AbortSignal.any([v,AbortSignal.timeout(8e3)])});return f=void 0,await R(A,v),{client:A,path:"direct"}}});for(const S of c)w.push({key:`relay:${S.targetPeerId}:${S.url}`,run:async v=>{let A,_;try{if(A=await b(S,v),v.aborted)throw v.reason;const B=await A.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(v.aborted)throw v.reason;if(typeof B.routeToken!="string"||!B.routeToken)throw new Error("入口未允许此设备连接该服务。");const I=new URL(vn(S.url));return I.pathname="/api/federation/relay",I.searchParams.set("routeToken",B.routeToken),_=await bn({url:I.href,targetPeerId:t.targetPeerId,pairingCode:f,identity:o,socketFactory:Mp(t.targetPeerId),signal:AbortSignal.any([v,AbortSignal.timeout(8e3)])}),f=void 0,await R(_,v),{client:_,entry:A,path:"relay"}}catch(B){throw _?.close(),A&&A!==r&&A!==n&&A.close(),B}}});const y=Up(t.targetPeerId);w.sort((S,v)=>+(v.key===y)-+(S.key===y));const k=await $p(w,S=>{S.client.close(),S.entry&&S.entry!==n&&S.entry!==r&&S.entry.close()},!!f);if(d=k.value.client,u=k.value.entry,h=k.value.path,e.renewIfCurrent){if(J!==e.renewIfCurrent||n!==e.renewIfCurrent||n.closed||!n.canSwitchTransport||re()?.targetPeerId!==t.targetPeerId){d.close();for(const S of g)S!==Me&&S!==J&&S.close();return J??n}J=d,fr=h,Me=u,rc(t.targetPeerId,k.key),n.retire();for(const S of new Set([r,...g]))S&&S!==n&&S!==d&&S!==u&&S.close();return window.dispatchEvent(new Event(Je)),d}if(rc(t.targetPeerId,k.key),J!==n&&J&&!J.closed&&J.targetPeerId===t.targetPeerId){d.close();for(const S of g)S!==Me&&S.close();return J}h==="direct"&&new URL(s).host===location.host&&Mm(t.targetPeerId);const N=(await Ke()).find(S=>S.targetPeerId===t.targetPeerId||!S.targetPeerId&&(S.serviceOrigin||S.url)===s),x=N?.label||t.serviceName||new URL(s).host,T={url:s,targetPeerId:t.targetPeerId,serviceName:x,serviceOrigin:s,routes:a.routes??c};if(await(e.rememberOnly?Um:Tt)({id:N?.id||t.targetPeerId,...T,label:x}),Wn!=="unpaired"&&Wn!==t.targetPeerId&&ht()&&_s({id:N?.id||t.targetPeerId,...T,label:x})){d.close();for(const S of g)S!==n&&S!==r&&S.close();return n||d}Rf(T),J=d,fr=h,Me=u;for(const S of new Set([n,r,...g]))S&&S!==d&&S!==u&&S.close();return Wn!==t.targetPeerId?(location.reload(),new Promise(()=>{})):(window.dispatchEvent(new Event(Je)),d)}catch(w){d?.close();for(const R of g)R!==r&&R.close();throw w}}async function yE(){const t=J,e=re();if(!(ts||es||$n||!t?.renewalDue||!t.canSwitchTransport||!e||performance.now()-uu<3e4)){uu=performance.now(),ts=!0;try{await Qe(e,{renewIfCurrent:t})}catch(n){console.debug("[connection] renewal deferred",{reason:n instanceof Error?n.message:"unknown"})}finally{ts=!1}}}async function bE(){const t=J,e=re();if(Date.now()-du<6e4||ts||es||fr!=="relay"||!t||t.closed||!t.canSwitchTransport||!e?.serviceOrigin)return;es=!0,du=Date.now();let n;try{for(const o of br(e))try{n=await bn({url:vn(o),targetPeerId:e.targetPeerId,identity:await tt(),signal:AbortSignal.timeout(3e3)}),await yr(n);break}catch(s){if(n?.close(),n=void 0,s instanceof et)throw s}if(!n||J!==t||!t.canSwitchTransport)return;const r=Me;J=n,n=void 0,Me=void 0,fr="direct",t.close(),r?.close(),window.dispatchEvent(new Event(Je))}catch(r){r instanceof et&&J===t&&(Wp(),window.dispatchEvent(new Event("auth:unauthorized")))}finally{n?.close(),es=!1}}function vE(){return fr}async function SE(t){return t?(t.throwIfAborted(),new Promise((e,n)=>{const r=()=>n(t.reason);t.addEventListener("abort",r,{once:!0}),st().then(o=>{t.removeEventListener("abort",r),t.aborted?n(t.reason):e(o)},o=>{t.removeEventListener("abort",r),n(o)})})):st()}async function st(){if(J&&!J.closed){const e=J;return yE(),e}if(J=void 0,$n)return $n;const t=re();if(!t)throw new Error("DEVICE_PAIRING_REQUIRED");return $n=Qe(t,{rememberOnly:!0}).catch(e=>{if(J&&!J.closed&&J.targetPeerId===t.targetPeerId)return J;throw e}).finally(()=>{$n=void 0}),$n}function Vp(t){const e=new URL(t,location.href);if(J&&!J.closed)return J.openSocket(e.pathname+e.search);let n;const r=new Fp(t,o=>n?.send(o),()=>n?.close());return st().then(o=>{r.readyState!==3&&(n=o.openSocket(e.pathname+e.search),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 xE(){tE(st),window.fetch=async(t,e)=>{const n=new URL(t instanceof Request?t.url:String(t),location.href);if(!n.pathname.startsWith("/api/"))return hr(t,e);if(n.origin!==location.origin)throw new Error("Remote business API requires a paired encrypted service");if(n.pathname==="/api/meta")return hr(t,e);if(n.pathname==="/api/auth/status"){if(!re()){const s=await Gp();return Response.json({enabled:s.enabled,authenticated:!1})}try{const s=await yr(await st());return Response.json({enabled:s.grants.length>0,authenticated:!0})}catch(s){if(s instanceof et)return Response.json({enabled:!0,authenticated:!1});throw s}}if(n.pathname==="/api/auth/login"){const i=await new Request(t instanceof Request?t:n.href,e).json();return gE(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 J&&!J.closed&&await J.request({type:"logout"}),J?.close(),Me?.close(),J=void 0,Me=void 0,Fm(),location.reload(),Response.json({ok:!0});const r=e?.signal!==void 0?e.signal:t instanceof Request?t.signal:void 0,o=await SE(r);return t instanceof Request?o.fetch(t,e):o.fetch(n.pathname+n.search,e)}}async function EE(t){if(!t.targetPeerId)throw new Error("请先连接这台服务,再查看可中转的服务。");for(const e of br({...t,targetPeerId:t.targetPeerId})){let n;const r={url:e,targetPeerId:t.targetPeerId};try{n=await Qt(r)}catch{continue}try{const o=await n.request({type:"route-targets"},{timeoutMs:5e3});if(!Array.isArray(o.items))throw new Error("入口服务需要更新后才能查看中转列表。");return{route:r,canManage:o.canManage===!0,items:o.items}}catch(o){throw o instanceof Error&&/UNKNOWN|UNSUPPORTED/i.test(o.message)?new Error("入口服务需要更新后才能查看中转列表。"):o}finally{n.close()}}throw new Error("暂时连不上中转入口,请检查地址和网络后重试。")}async function AE(t,e){const n=await Qt(t);try{const r=await n.request({type:"route-targets"},{timeoutMs:5e3}),o=(Array.isArray(r.items)?r.items:[]).find(c=>c.serviceId===e);if(!o)throw new Error("该服务已不可见,请刷新列表或请入口管理员授权。");if(!o.available)throw new Error("入口暂时无法中转到这台服务,请稍后重试。");const s=(await Ke()).find(c=>c.targetPeerId===o.serviceId),i=[t,...(s?.routes||[]).filter(c=>c.targetPeerId!==t.targetPeerId)];if(i.length>4)throw new Error("这台服务已保存 4 个备用连接,请先移除一个后重试。");if(!o.authorized){if(!r.canManage)throw new Error("请先让入口管理员授权此设备。");await n.request({type:"route-grant",serviceId:o.serviceId,subjectId:(await tt()).peerId})}const a=s?.serviceOrigin||s?.url||o.url||t.url;return{url:a,serviceOrigin:a,targetPeerId:o.serviceId,serviceName:s?.label||o.label||(o.url?new URL(o.url).host:`中转服务 ${o.serviceId.slice(0,8)}`),routes:i}}finally{n.close()}}async function kE(t,e){const n=await Qt(t);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),o=(await tt()).peerId;return{canManage:r.canManage===!0,grants:(Array.isArray(r.grants)?r.grants:[]).filter(s=>s.subjectId===o&&s.targetServiceId===e)}}finally{n.close()}}async function IE(t,e,n){if(n!==void 0&&(await pl(_e(e.url),n)).targetPeerId!==e.targetPeerId)throw new Error("入口服务的身份已改变,请重新连接并确认。");const r=await Qt(e);try{await r.request({type:"route-grant",serviceId:t.targetPeerId,subjectId:(await tt()).peerId,url:_e(t.serviceOrigin||t.url)})}finally{r.close()}}async function CE(t,e){const n=await Qt(e);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),o=(await tt()).peerId,s=(Array.isArray(r.grants)?r.grants:[]).filter(i=>i.subjectId===o&&i.targetServiceId===t&&i.active);for(const i of s)await n.request({type:"route-revoke",grantId:i.id})}finally{n.close()}}async function Xp(t,e){const n=await Qt(e);try{const r=await n.request({type:"route-invite-create",serviceId:t.targetPeerId});if(typeof r.routeCode!="string"||typeof r.expiresAt!="number")throw new Error("暂时无法生成备用连接邀请。");return{routeCode:r.routeCode,expiresAt:r.expiresAt}}finally{n.close()}}async function ns(t,e){const n=(await Ke()).find(o=>o.id===t.id||t.targetPeerId&&o.targetPeerId===t.targetPeerId)||t;await Tt({...n,url:n.serviceOrigin||n.url,entryServiceId:void 0,routes:e});const r=re();r&&r.targetPeerId===t.targetPeerId&&Rf({...r,url:r.serviceOrigin||r.url,entryServiceId:void 0,routes:e})}async function RE(t,e){const n=t.targetPeerId;if(!n)throw new Error("请先连接这台服务,再添加备用地址。");let r;try{r=_e(e)}catch{throw new Error("请输入有效的 HTTPS 地址,例如 https://电脑地址:9834。")}const o=async()=>(await Ke()).find(a=>a.targetPeerId===n)||t,s=a=>{const c=a.routes??Zt({...a,targetPeerId:n});if(_e(a.serviceOrigin||a.url)===r||c.some(l=>_e(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 bn({url:vn(r),targetPeerId:n,identity:await tt(),signal:AbortSignal.timeout(5e3)}),await yr(i)}catch(l){throw l instanceof et?new Error("这台服务尚未授权当前设备,请先恢复设备授权。"):new Error("无法验证这个地址。请确认能访问该地址、HTTPS 证书受信任,且运行的是同一台 Termdock 服务。")}const a=await o(),c=s(a);if(await ns(a,c),re()?.targetPeerId===n&&Wn===n&&(!J||J.closed)){const l=J,d=Me;J=i,i=void 0,Me=void 0,fr="direct",l?.close(),d?.close(),window.dispatchEvent(new Event(Je))}return c}finally{i?.close()}}async function hu(t,e){await ic(t,e),await Qe({...t,pairingCode:void 0,routeCode:void 0})}function TE(){let t=!1,e=!1,n=!1,r;const o=new Map,s=new Set,i=new Map,a=async(f,h,g)=>{const m=JSON.stringify(g);if(o.get(h.serviceId)===m)return;const b=AbortSignal.timeout(1e4),w=await f.fetch("/api/csrf-token",{signal:b});if(!w.ok)throw new Error("CONNECTION_AUTHORIZATION_REQUIRED");const R=await w.json();if(typeof R.csrfToken!="string")throw new Error("INVALID_CSRF_TOKEN");const y=await f.fetch("/api/terminal/operations/collaboration-connections",{method:"POST",signal:b,headers:{"Content-Type":"application/json","X-XSRF-TOKEN":R.csrfToken},body:JSON.stringify({origin:h.origin,nodes:g})});if(!y.ok){const k=await y.json().catch(()=>({}));throw new Error(k.error||`HTTP_${y.status}`)}o.set(h.serviceId,m)},c=async()=>{if(t){n=!0;return}const f=re(),h=rn();if(!(e||!f||!h||h.closed)){t=!0,n=!1;try{let g;const m=await Promise.race([Ke(),new Promise((N,x)=>{g=setTimeout(()=>x(new Error("SERVICE_DIRECTORY_TIMEOUT")),8e3)})]).finally(()=>clearTimeout(g));m.some(N=>N.targetPeerId===f.targetPeerId)||m.push({...f,id:f.targetPeerId,label:f.serviceName||f.url});const b=[...new Map(m.filter(N=>!!N.targetPeerId).map(N=>[N.targetPeerId,N])).values()].slice(0,64);if(b.length<2)return;const w=[];for(const N of b)try{const x=`${N.targetPeerId}:${N.serviceOrigin||N.url}`;let T=i.get(x);if(!T){const S=N.targetPeerId===f.targetPeerId?(await h.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node:await mE({...N,targetPeerId:N.targetPeerId},AbortSignal.timeout(8e3));if(S?.serviceId!==N.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");const v=S.origin||N.serviceOrigin||N.url,A=new URL(v);if(A.protocol!=="https:"||A.origin!==v)throw new Error("INVALID_SERVICE_ORIGIN");T={serviceId:S.serviceId,origin:v,...S.caFingerprint256?{caFingerprint256:S.caFingerprint256}:{}},i.set(x,T)}w.push({service:N,node:T})}catch{}if(e||rn()!==h||re()?.targetPeerId!==f.targetPeerId)return;const R=w.find(N=>N.node.serviceId===f.targetPeerId);if(!R||w.length<2){l(3e4);return}const y=w.map(N=>N.node).sort((N,x)=>N.serviceId.localeCompare(x.serviceId));await a(h,R.node,y);let k=w.length<b.length;for(const N of w){if(N===R||o.get(N.node.serviceId)===JSON.stringify(y))continue;let x;try{x=await wE({...N.service,targetPeerId:N.node.serviceId},AbortSignal.timeout(8e3)),await a(x,N.node,y)}catch{let T=s.has(N.node.serviceId);if(!T&&x)try{(await x.request({type:"collaboration-scoped-peer",origin:N.node.origin,node:R.node},{timeoutMs:8e3})).type==="result"&&(s.add(N.node.serviceId),T=!0)}catch{}T||(k=!0)}finally{x?.close()}}window.dispatchEvent(new CustomEvent("termdock:collaboration-enrollment",{detail:{ok:!0}})),k&&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{t=!1,n&&l(100)}}};function l(f=100){e||(clearTimeout(r),r=setTimeout(()=>{c()},f))}const d=()=>{l()},u=Ws(d);window.addEventListener(Je,d),window.addEventListener("termdock:collaboration-enroll",d),window.addEventListener("online",d),window.addEventListener("pageshow",d),window.addEventListener("pagehide",f=>{f.persisted||(e=!0,clearTimeout(r),u(),window.removeEventListener("termdock:collaboration-enroll",d),window.removeEventListener(Je,d),window.removeEventListener("online",d),window.removeEventListener("pageshow",d))}),l()}var qo={},pu;function PE(){if(pu)return qo;pu=1;var t=Rm();return qo.createRoot=t.createRoot,qo.hydrateRoot=t.hydrateRoot,qo}var NE=PE();const LE=Cf(NE);const Yp=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim();const BE=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const _E=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,r)=>r?r.toUpperCase():n.toLowerCase());const gu=t=>{const e=_E(t);return e.charAt(0).toUpperCase()+e.slice(1)};var Ki={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 OE=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1},DE=O.createContext({}),FE=()=>O.useContext(DE),ME=O.forwardRef(({color:t,size:e,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:h=""}=FE()??{},g=r??u?Number(n??d)*24/Number(e??l):n??d;return O.createElement("svg",{ref:c,...Ki,width:e??l??Ki.width,height:e??l??Ki.height,stroke:t??f,strokeWidth:g,className:Yp("lucide",h,o),...!s&&!OE(a)&&{"aria-hidden":"true"},...a},[...i.map(([m,b])=>O.createElement(m,b)),...Array.isArray(s)?s:[s]])});const Ae=(t,e)=>{const n=O.forwardRef(({className:r,...o},s)=>O.createElement(ME,{ref:s,iconNode:e,className:Yp(`lucide-${BE(gu(t))}`,`lucide-${t}`,r),...o}));return n.displayName=gu(t),n};const jE=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Zp=Ae("arrow-left",jE);const UE=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],$E=Ae("arrow-right",UE);const HE=[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]],qE=Ae("arrow-up-right",HE);const KE=[["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"}]],Jp=Ae("bell-dot",KE);const zE=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Os=Ae("check",zE);const WE=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Qp=Ae("chevron-down",WE);const GE=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Sn=Ae("chevron-right",GE);const VE=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],XE=Ae("chevron-up",VE);const YE=[["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"}]],eg=Ae("copy",YE);const ZE=[["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"}]],tg=Ae("ellipsis",ZE);const JE=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],je=Ae("loader-circle",JE);const QE=[["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"}]],e1=Ae("monitor",QE);const t1=[["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"}]],n1=Ae("pencil",t1);const r1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],ng=Ae("plus",r1);const o1=[["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"}]],ai=Ae("server",o1);const s1=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],rg=Ae("smartphone",s1);const i1=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],a1=Ae("terminal",i1);const c1=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],og=Ae("x",c1),l1={},mu=t=>{let e;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(e):d;if(!Object.is(f,e)){const h=e;e=u??(typeof f!="object"||f===null)?f:Object.assign({},e,f),n.forEach(g=>g(e,h))}},o=()=>e,c={setState:r,getState:o,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(l1?"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=e=t(r,o,c);return c},d1=t=>t?mu(t):mu;var zi={exports:{}},Wi={},Gi={exports:{}},Vi={};var wu;function u1(){if(wu)return Vi;wu=1;var t=_c();function e(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var n=typeof Object.is=="function"?Object.is:e,r=t.useState,o=t.useEffect,s=t.useLayoutEffect,i=t.useDebugValue;function a(u,f){var h=f(),g=r({inst:{value:h,getSnapshot:f}}),m=g[0].inst,b=g[1];return s(function(){m.value=h,m.getSnapshot=f,c(m)&&b({inst:m})},[u,h,f]),o(function(){return c(m)&&b({inst:m}),u(function(){c(m)&&b({inst:m})})},[u]),i(h),h}function c(u){var f=u.getSnapshot;u=u.value;try{var h=f();return!n(u,h)}catch{return!0}}function l(u,f){return f()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?l:a;return Vi.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:d,Vi}var yu;function f1(){return yu||(yu=1,Gi.exports=u1()),Gi.exports}var bu;function h1(){if(bu)return Wi;bu=1;var t=_c(),e=f1();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=e.useSyncExternalStore,s=t.useRef,i=t.useEffect,a=t.useMemo,c=t.useDebugValue;return Wi.useSyncExternalStoreWithSelector=function(l,d,u,f,h){var g=s(null);if(g.current===null){var m={hasValue:!1,value:null};g.current=m}else m=g.current;g=a(function(){function w(x){if(!R){if(R=!0,y=x,x=f(x),h!==void 0&&m.hasValue){var T=m.value;if(h(T,x))return k=T}return k=x}if(T=k,r(y,x))return T;var S=f(x);return h!==void 0&&h(T,S)?(y=x,T):(y=x,k=S)}var R=!1,y,k,N=u===void 0?null:u;return[function(){return w(d())},N===null?void 0:function(){return w(N())}]},[d,u,f,h]);var b=o(l,g[0],g[1]);return i(function(){m.hasValue=!0,m.value=b},[b]),c(b),b},Wi}var vu;function p1(){return vu||(vu=1,zi.exports=h1()),zi.exports}var g1=p1();const m1=Cf(g1),sg={},{useDebugValue:w1}=We,{useSyncExternalStoreWithSelector:y1}=m1;let Su=!1;const b1=t=>t;function v1(t,e=b1,n){(sg?"production":void 0)!=="production"&&n&&!Su&&(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"),Su=!0);const r=y1(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,n);return w1(r),r}const xu=t=>{(sg?"production":void 0)!=="production"&&typeof t!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof t=="function"?d1(t):t,n=(r,o)=>v1(e,r,o);return Object.assign(n,e),n},ci=t=>t?xu(t):xu,ml=t=>`@collaboration:${t}`,ig=ci(t=>({activePaneId:null,setActivePane:e=>t({activePaneId:e}),docks:{},hosts:{},setDock:(e,n)=>t(r=>{const o={...r.docks};return n?o[e]=n:delete o[e],{docks:o,...!n&&r.activePaneId===ml(e)?{activePaneId:r.docks[e]?.sessionId??null}:{}}}),setHost:(e,n)=>t(r=>{const o={...r.hosts};return n?o[e]=n:delete o[e],{hosts:o}})})),dn=new Map;let eo;function ag(){const t=ig.getState().activePaneId;for(const[n,r]of dn)if(r.requiresFocus&&t===ml(n))return r.receive;const e=dn.get(eo??"");return e&&!e.requiresFocus?e.receive:void 0}function cR(t){const e=dn.get(t);e&&(e.requiresFocus?ig.getState().setActivePane(ml(t)):eo=t)}function S1(t){const e=ag();return!e||!t?!1:(e(t),!0)}function lR(t,e="default",n=!1){dn.set(e,{receive:t,requiresFocus:n}),n||(eo=e);const r=o=>{const{text:s,nonce:i}=o.detail??{};!s||ag()!==t||(t(s),o.stopImmediatePropagation(),i&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:i,ok:!0}})))};return window.addEventListener("termdock-insert-reference",r,!0),()=>{dn.get(e)?.receive===t&&(dn.delete(e),eo===e&&(eo=[...dn.keys()].at(-1))),window.removeEventListener("termdock-insert-reference",r,!0)}}const x1=/^[A-Za-z0-9_@%+=:,./-]$/;function E1(t){return Array.from(t,e=>(e.codePointAt(0)??0)>127||x1.test(e)?e:`\\${e}`).join("")}function A1(t,e){if(!e)return!1;try{const n=new URL(e.serviceOrigin||e.url);return n.origin===t&&/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})$/.test(n.hostname)&&!(e.routes??[]).some(r=>r.targetPeerId!==e.targetPeerId)}catch{return!1}}function k1(t){const e=s=>s.target instanceof Element?s.target.closest("[data-termdock-terminal-dropzone]"):null,n=()=>!A1(location.origin,Fc()),r=s=>{const i=e(s);!i||!n()||!s.dataTransfer?.types.includes("Files")||(s.preventDefault(),s.stopImmediatePropagation(),s.dataTransfer.dropEffect="copy",i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="remote")},o=s=>{const i=e(s),a=Array.from(s.dataTransfer?.files??[]);if(!i||!a.length||!n())return;s.preventDefault(),s.stopImmediatePropagation();const c=i.dataset.termdockTerminalDropzone??"";i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="uploading",Jt(async()=>{const{uploadFiles:l}=await Promise.resolve().then(()=>O2);return{uploadFiles:l}},void 0).then(({uploadFiles:l})=>l("/tmp",a)).then(l=>{if(l.files.length!==a.length||l.files.some(d=>!d.path))throw new Error("Upload did not return every file path");delete i.dataset.nativeFileDrag,delete i.dataset.nativeFileDropState,t({sessionKey:c,paths:l.files.map(d=>d.path)})}).catch(l=>{i.dataset.nativeFileDropState="error",i.dispatchEvent(new CustomEvent("termdock:file-drop-error",{bubbles:!0,detail:l instanceof Error?l.message:"File upload failed"})),window.setTimeout(()=>{i.dataset.nativeFileDropState==="error"&&(delete i.dataset.nativeFileDrag,delete i.dataset.nativeFileDropState)},3e3)})};return window.addEventListener("dragover",r,!0),window.addEventListener("drop",o,!0),()=>{window.removeEventListener("dragover",r,!0),window.removeEventListener("drop",o,!0)}}function nt(){return typeof window>"u"?null:window.termdockDesktop??null}const Xi=new Set;let Eu=!1;function dR(t){const e=nt();if(!e)return()=>{};if(Xi.add(t),!Eu){const n=r=>{if(!S1(r.paths.map(E1).join(" ")+" "))for(const o of Xi)o(r)};k1(n),e.onNativeFileDrop(n),Eu=!0}return()=>{Xi.delete(t)}}function cg(t=navigator.userAgent,e=navigator.maxTouchPoints){const n=/iPad/.test(t)||/Macintosh/.test(t)&&e>1?"iPad":/iPhone/.test(t)?"iPhone":/Android/.test(t)?"Android":/Windows/.test(t)?"Windows":/Macintosh|Mac OS X/.test(t)?"Mac":/Linux/.test(t)?"Linux":"设备",r=/Electron/.test(t)?"Termdock":/Edg\//.test(t)?"Edge":/Firefox|FxiOS/.test(t)?"Firefox":/Chrome|CriOS/.test(t)?"Chrome":/Safari/.test(t)?"Safari":"浏览器";return`${n} · ${r}`}let I1;function C1(){return I1??=(async()=>{const t=navigator.userAgent,[e,n]=cg().split(" · "),r=/(?:Edg|Firefox|FxiOS|Chrome|CriOS|Version)\/([\d.]+)/g,o=[...t.matchAll(r)],s=/(?:CPU (?:iPhone )?OS |Mac OS X |Android )([\d._]+)/.exec(t)?.[1]?.replaceAll("_","."),i={system:`${e}${s?` ${s}`:""}`,client:`${n}${o.length?` ${o.at(-1)[1]}`:""}`,mode:matchMedia("(display-mode: standalone)").matches||navigator.standalone?"已安装的网页应用":"网页"},a=nt();if(a){i.mode="桌面客户端";const l=/Electron\/([\d.]+)/.exec(t)?.[1];i.client=l?`Termdock(Electron ${l})`:"Termdock";try{Object.assign(i,await a.deviceInfo?.())}catch{}return i}const c=navigator.userAgentData;try{const l=await c?.getHighEntropyValues(["model","architecture","bitness","platformVersion"]);typeof l?.model=="string"&&l.model&&(i.model=l.model),typeof l?.architecture=="string"&&l.architecture&&(i.arch=`${l.architecture}${l.bitness?` ${l.bitness} 位`:""}`)}catch{}return i})()}function R1({service:t,onBusyChange:e,onConnect:n,onConnectWithPassword:r}){const[o,s]=O.useState(),[i,a]=O.useState(!0),[c,l]=O.useState(!1),[d,u]=O.useState(""),[f,h]=O.useState(0),[g,m]=O.useState(),[b,w]=O.useState("");O.useEffect(()=>{let k=!1,N=!1,x;a(!0),u(""),s(void 0);const T=async S=>{try{const v=await EE(t);if(k)return;N=!0,s(v),u("")}catch(v){!k&&(!N||S)&&u(v instanceof Error?v.message:"暂时无法读取中转列表,请重试。")}finally{k||(a(!1),x=setTimeout(()=>{T(!1)},2e3))}};return T(!0),()=>{k=!0,clearTimeout(x)}},[t.id,t.url,f]);const R=async k=>{if(!c){l(!0),e(!0),u("");try{await k()}catch(N){u(N instanceof Error?N.message:"暂时无法连接,请重试。")}finally{l(!1),e(!1)}}},y=async k=>{const N=await AE(o.route,k.serviceId);try{await n(N)}catch(x){if(!(x instanceof et))throw x;m(N)}};return p.jsxs("div",{className:"service-form",children:[g?p.jsxs("form",{className:"service-form",onSubmit:k=>{k.preventDefault(),R(async()=>{try{await r?.(g,b)}finally{w("")}})},children:[p.jsxs("p",{className:"service-help",children:["已通过“",t.label,"”连接到“",g.serviceName,"”。请登录目标服务,完成此设备的访问授权。"]}),r?p.jsxs(p.Fragment,{children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"目标服务密码"}),p.jsx("input",{type:"password",autoFocus:!0,required:!0,autoComplete:"current-password",value:b,disabled:c,onChange:k=>w(k.target.value)})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:c||!b,children:c?"正在登录…":"登录并连接"})]}):p.jsx("p",{className:"service-help",children:"请让目标服务管理员邀请此设备后再连接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>{m(void 0),w(""),u(""),h(k=>k+1)},children:"返回中转列表"})]}):p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["通过“",t.label,"”连接下方服务。",o?.canManage?"选择未授权的服务会授权此设备使用该中转。":"这里只显示已授权给此设备的中转。","目标服务会单独验证访问权限。"]}),i?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(je,{size:16,className:"service-spinning"}),"正在读取可中转的服务…"]}):o&&p.jsxs("div",{className:"service-list",children:[o.items.map(k=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:c||!k.available,onClick:()=>{R(()=>y(k))},children:[p.jsx("span",{className:"service-icon",children:p.jsx(ai,{size:19})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:k.label||(k.url?new URL(k.url).host:`中转服务 ${k.serviceId.slice(0,8)}`)}),p.jsx("span",{className:"service-description",children:k.available?k.authorized?"已获中转授权 · 连接":"授权此设备并连接":"中转暂不可用"})]}),p.jsx(Sn,{size:16})]},k.serviceId)),o.items.length===0&&p.jsx("p",{className:"service-empty",children:o.canManage?"暂无可中转的服务。可在本机 Mac 客户端连接目标服务,或在目标服务的“备用连接”中启用本入口。":"暂无已授权的中转服务,请让入口管理员分享备用连接邀请。"})]}),c&&p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(je,{size:16,className:"service-spinning"}),"正在授权并连接目标服务…"]}),!i&&p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>h(k=>k+1),children:"刷新列表"})]}),d&&p.jsx("p",{className:"service-error",role:"alert",children:d})]})}const ac="#termdock-invite=";function lg(t){const e=new URL(t.entryUrl);e.hash="",e.search="",e.pathname="/";const n=new TextEncoder().encode(JSON.stringify(t));return e.hash=ac.slice(1)+btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.href}function Ds(t){const e=new URL(t);if(!["https:","http:"].includes(e.protocol)||!e.hash.startsWith(ac))throw new Error("这不是有效的 Termdock 邀请链接");const n=e.hash.slice(ac.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!==e.origin||o.username||o.password||!["https:","http:"].includes(o.protocol))throw new Error("邀请地址与服务不一致");if(o.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(o.hostname))throw new Error("远程邀请需要 HTTPS");if(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 T1({service:t,onBusyChange:e}){const n={...t,targetPeerId:t.targetPeerId,serviceName:t.label},[r,o]=O.useState(()=>t.routes??Zt(n)),[s,i]=O.useState([]),[a,c]=O.useState(!0),[l,d]=O.useState(!1),[u,f]=O.useState(""),h=L=>{d(L),e(L)},[g,m]=O.useState(),[b,w]=O.useState(""),[R,y]=O.useState(""),[k,N]=O.useState(""),[x,T]=O.useState(!1),[S,v]=O.useState(),[A,_]=O.useState(),[B,I]=O.useState(!1);O.useEffect(()=>{let L=!1;return Ke().then($=>{L||i($.filter(H=>H.targetPeerId&&H.targetPeerId!==t.targetPeerId))}).catch(()=>{L||f("暂时无法读取可用服务。")}).finally(()=>{L||c(!1)}),()=>{L=!0}},[t.targetPeerId]);const E=L=>s.find($=>$.targetPeerId===L.targetPeerId)?.label||new URL(L.url).host,P=async L=>{h(!0),f(""),N("");try{await L()}catch($){const H=$ instanceof Error?$.message:"";f(/AUTHORIZATION|DENIED/.test(H)?"当前设备没有入口管理权限。请让管理员分享备用连接邀请,或使用入口密码授权。":"暂时无法完成。请确认入口能连接目标服务,且目标地址、证书和授权有效。")}finally{h(!1)}},C=async(L,$)=>{const H={url:L.serviceOrigin||L.url,targetPeerId:L.targetPeerId};await P(async()=>{const U=await kE(H,n.targetPeerId);if(!U.grants.some(K=>K.active)){if(!U.canManage&&$===void 0){m(L);return}await IE(n,H,$)}const q=[...r.filter(K=>K.targetPeerId!==H.targetPeerId),H];await ns(t,q),o(q),m(void 0),w("")})};if(A)return p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["把链接发给需要使用此备用连接的人。它只允许通过入口连接“",t.label,"”,对方仍需获得目标服务的访问权限。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用连接邀请"}),p.jsx("input",{readOnly:!0,value:A,onFocus:L=>L.target.select()})]}),p.jsxs("button",{type:"button",className:"service-button service-primary",onClick:()=>{navigator.clipboard.writeText(A).then(()=>I(!0)).catch(()=>f("无法自动复制,请长按链接复制。"))},children:[p.jsx(eg,{size:16}),B?"已复制":"复制邀请链接"]}),p.jsx("button",{type:"button",className:"service-button service-secondary",onClick:()=>{_(void 0),I(!1)},children:"返回备用连接"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});if(g)return p.jsxs("form",{className:"service-form",onSubmit:L=>{L.preventDefault(),C(g,b).finally(()=>w(""))},children:[p.jsxs("p",{className:"service-help",children:["需要“",g.label,"”的管理员授权。若这是你的服务,可以使用它的密码;否则请管理员分享备用连接邀请。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"入口服务密码"}),p.jsx("input",{type:"password",required:!0,value:b,onChange:L=>w(L.target.value),autoComplete:"current-password",disabled:l,autoFocus:!0})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||!b,children:l?"正在授权…":"授权并启用"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{m(void 0),w("")},children:"取消"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});const D=r.filter(L=>L.targetPeerId===n.targetPeerId),M=r.filter(L=>L.targetPeerId!==n.targetPeerId),F=async()=>{if(!l){h(!0),T(!0),f(""),N("");try{o(await RE({...t,routes:r},R)),y(""),N("备用地址已验证并保存。")}catch(L){f(L instanceof Error?L.message:"暂时无法添加地址,请重试。")}finally{h(!1),T(!1)}}};return p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"电脑换了网络?添加它在新网络下的地址,原地址连不上时会自动尝试。只接受同一台服务。"}),p.jsxs("form",{className:"service-form",onSubmit:L=>{L.preventDefault(),F()},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用地址"}),p.jsx("input",{value:R,onChange:L=>{y(L.target.value),f(""),N("")},required:!0,disabled:l||r.length>=4,inputMode:"url",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:192.168.10.20:9834"})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||r.length>=4||!R.trim(),children:x?p.jsxs(p.Fragment,{children:[p.jsx(je,{size:16,className:"service-spinning"}),"正在验证…"]}):"验证并添加"})]}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u}),k&&p.jsx("p",{role:"status",className:"service-help",children:k}),r.length>=4&&p.jsx("p",{className:"service-help",children:"已保存 4 个备用连接。移除不再使用的地址或入口后,可以继续添加。"}),p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"首选地址"}),p.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url})]}),D.length>0&&p.jsx("div",{className:"service-list",children:D.map(L=>p.jsxs("div",{className:"service-route-item",children:[p.jsxs("div",{className:"service-route-line",children:[p.jsx("span",{className:"service-address service-route-address",children:L.url}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`移除地址 ${L.url}`,disabled:l,onClick:()=>v(L),children:"移除"})]}),S?.targetPeerId===L.targetPeerId&&S.url===L.url&&p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"从备用连接中移除此地址?不会停止正在运行的终端。"}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>v(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{P(async()=>{const $=r.filter(H=>H.targetPeerId!==L.targetPeerId||H.url!==L.url);await ns(t,$),o($),v(void 0)})},children:"确认移除"})]})]})]},L.url))}),p.jsxs("details",{className:"service-relay-options",children:[p.jsxs("summary",{children:["通过其他服务中转",M.length?`(${M.length})`:""]}),p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"所有直连地址都不可用时,尝试下方已授权入口;直连恢复后自动切回。"}),M.length>0&&p.jsx("div",{className:"service-list",children:M.map(L=>p.jsxs("div",{className:"service-route-item",children:[p.jsxs("div",{className:"service-route-line",children:[p.jsx("span",{className:"service-icon",children:p.jsx(ai,{size:18})}),p.jsx("span",{className:"service-name",children:E(L)}),p.jsx(Os,{size:16,className:"service-selected"})]}),S?.targetPeerId===L.targetPeerId?p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["撤销此设备经“",E(L),"”连接目标的权限?如当前无法直连,目标服务将断开。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>v(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{P(async()=>{await CE(n.targetPeerId,L);const $=r.filter(H=>H.targetPeerId!==L.targetPeerId);await ns(t,$),o($),v(void 0)})},children:"确认撤销"})]})]}):p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{P(async()=>{const $=await Xp(n,L);_(lg({v:1,routeOnly:!0,serviceId:n.targetPeerId,name:t.label,serviceUrl:t.serviceOrigin||t.url,entryUrl:L.url,entryServiceId:L.targetPeerId,routeCode:$.routeCode}))})},children:"分享备用连接"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>v(L),children:"撤销授权"})]})]},L.targetPeerId))}),a?p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(je,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"添加中转入口"}),s.filter(L=>!r.some($=>$.targetPeerId===L.targetPeerId)).map(L=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:l||r.length>=4,onClick:()=>{C(L)},children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:L.label}),p.jsx("span",{className:"service-description",children:"验证并授权后启用"})]}),p.jsx(Sn,{size:16})]},L.id)),s.length===0&&p.jsx("p",{className:"service-empty",children:"添加并登录另一台服务后,可以将它设为中转入口。"})]})]})]}),l&&!x&&p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(je,{size:16,className:"service-spinning"}),"正在验证连接与授权…"]})]})}function P1({current:t,renderRoutes:e,renderRelayServices:n,onOpen:r,onAdd:o,onInvite:s,hideHeader:i,onNavigation:a,onBusyChange:c,initiallyAdding:l=!1}){const[d,u]=O.useState([]),[f,h]=O.useState(!0),[g,m]=O.useState(l?{kind:"add"}:{kind:"list"}),[b,w]=O.useState(!1),R=O.useCallback(I=>{w(I),c?.(I)},[c]),[y,k]=O.useState(""),N=O.useCallback(()=>{m(I=>I.kind==="routes"||I.kind==="relay-services"?{kind:"edit",service:I.service}:{kind:"list"}),k("")},[]),x=g.kind==="add"?"添加服务":g.kind==="edit"?"服务设置":g.kind==="routes"?"备用连接":g.kind==="relay-services"?"可中转的服务":void 0;O.useEffect(()=>{a?.({title:x,...x?{back:N}:{}})},[x,N,a]),O.useEffect(()=>{let I=!1,E=0;const P=async()=>{const D=++E;try{const M=await Ke();!I&&E===D&&(u(M),k(""))}catch{!I&&E===D&&k("暂时无法读取服务列表,请重试。")}finally{!I&&E===D&&h(!1)}};P();const C=Ws(()=>{P()});return()=>{I=!0,C()}},[]);const T=async I=>{if(!b){R(!0),k("");try{await I()}catch(E){k(E instanceof Error?E.message:"暂时无法完成,请重试。")}finally{R(!1)}}},S=g.kind==="edit"||g.kind==="routes"||g.kind==="relay-services"?d.find(I=>At(I,g.service))||g.service:void 0,v=t?d.find(I=>At(I,t))||t:void 0,A=d.filter(I=>!t||!At(I,t)),_=v?[v,...A]:A,B=p.jsxs(p.Fragment,{children:[f?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(je,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{className:"service-list",children:[_.map(I=>{const E=!!t&&At(I,t);return p.jsxs("div",{className:"service-row",children:[p.jsxs("button",{type:"button",className:"service-row-open",disabled:b||E,onClick:()=>{T(async()=>{(await r(I))?.passwordRequired&&m({kind:"add",input:I.serviceOrigin||I.url,passwordRequired:!0})})},"aria-label":E?`当前服务 ${I.label}`:`打开 ${I.label}`,children:[p.jsx("span",{className:"service-icon",children:p.jsx(ai,{size:20})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:I.label}),p.jsx("span",{className:"service-description",children:E?"当前服务":new URL(I.serviceOrigin||I.url).host})]}),E?p.jsx(Os,{size:17,className:"service-selected"}):p.jsx(Sn,{size:16,className:"service-muted"})]}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`管理 ${I.label}`,disabled:b,onClick:()=>{m({kind:"edit",service:I}),k("")},children:p.jsx(tg,{size:19})})]},I.id)}),_.length===0&&p.jsx("p",{className:"service-empty",children:"还没有添加服务。连接你的电脑,或粘贴收到的邀请链接。"})]}),p.jsxs("div",{className:`service-actions${s?" service-actions-pair":""}`,children:[p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:b,onClick:()=>{m({kind:"add"}),k("")},children:[p.jsx(ng,{size:16}),"添加服务"]}),s&&p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:b,onClick:s,children:[p.jsx(rg,{size:16}),"邀请设备"]})]})]});return p.jsxs("div",{className:"service-manager",children:[!i&&p.jsxs("div",{className:"service-heading",children:[x&&p.jsx("button",{type:"button",className:"service-icon-button","aria-label":"返回服务",disabled:b,onClick:N,children:p.jsx(Zp,{size:20})}),p.jsx("h2",{children:x||"服务"})]}),g.kind==="relay-services"?n?.(S,R):g.kind==="routes"?e?.(S,R):g.kind==="list"?B:g.kind==="add"?p.jsx(N1,{onSave:I=>T(async()=>{const E=_e(I);u(await Tt({id:E,url:E,label:new URL(E).host})),N()}),initialInput:g.input,passwordRequired:g.passwordRequired,busy:b,onSubmit:async(I,E)=>{let P;return await T(async()=>{P=await o(I,E),P?.passwordRequired||N()}),P}}):p.jsx(L1,{onRelayServices:n&&g.service.targetPeerId?()=>m({kind:"relay-services",service:g.service}):void 0,onRoutes:e&&g.service.targetPeerId?()=>m({kind:"routes",service:g.service}):void 0,service:S,busy:b,canRemove:!t||!At(g.service,t),onSave:I=>{T(async()=>{u(await Tt({...S,label:I})),N()})},onRemove:()=>{T(async()=>{u(await $m(g.service.id)),N()})}}),y&&p.jsx("p",{className:"service-error",role:"alert",children:y})]})}function N1({busy:t,onSubmit:e,onSave:n,initialInput:r="",passwordRequired:o=!1}){const[s,i]=O.useState(r),[a,c]=O.useState(""),[l,d]=O.useState(o);return p.jsxs("form",{className:"service-form",onSubmit:async u=>{u.preventDefault(),(await e(s.trim(),l?a:void 0))?.passwordRequired&&d(!0),c("")},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务地址或邀请链接"}),p.jsx("input",{value:s,onChange:u=>{i(u.target.value),d(!1),c("")},disabled:t,required:!0,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:电脑地址:9834 或 https://…"})]}),l?p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务密码"}),p.jsx("input",{type:"password",value:a,onChange:u=>c(u.target.value),disabled:t,required:!0,autoFocus:!0,autoComplete:"current-password",placeholder:"输入这台服务的密码"})]}):p.jsx("p",{className:"service-help",children:"连接自己的服务,输入地址即可;收到邀请时,粘贴完整链接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:t||!s.trim()||s.includes("#termdock-invite="),onClick:()=>{n(s.trim())},children:"仅保存,不连接"}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:t||!s.trim()||l&&!a,children:t?p.jsxs(p.Fragment,{children:[p.jsx(je,{size:16,className:"service-spinning"}),"正在连接…"]}):l?"登录并连接":"继续"})]})}function L1({service:t,busy:e,canRemove:n,onSave:r,onRemove:o,onRoutes:s,onRelayServices:i}){const[a,c]=O.useState(t.label),[l,d]=O.useState(!1);return p.jsxs("form",{className:"service-form",onSubmit:u=>{u.preventDefault(),r(a.trim())},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务名称"}),p.jsx("input",{value:a,onChange:u=>c(u.target.value),disabled:e,required:!0,maxLength:120,placeholder:"例如:办公室电脑"})]}),p.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:e||!a.trim(),children:"保存名称"}),i&&p.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:i,children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:"可中转的服务"}),p.jsx("span",{className:"service-description",children:"通过这台服务连接其他电脑"})]}),p.jsx(Sn,{size:16})]}),s&&p.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:s,children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:"备用连接"}),p.jsx("span",{className:"service-description",children:"添加其他网络地址或授权入口"})]}),p.jsx(Sn,{size:16})]}),n&&p.jsx("div",{className:"service-remove",children:l?p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["从列表移除“",t.label,"”?不会停止服务或删除终端。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:e,onClick:()=>d(!1),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:o,children:"确认移除"})]})]}):p.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:()=>d(!0),children:"移除服务"})})]})}var Dn={},Yi,Au;function B1(){return Au||(Au=1,Yi=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Yi}var Zi={},$t={},ku;function kn(){if(ku)return $t;ku=1;let t;const e=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return $t.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},$t.getSymbolTotalCodewords=function(r){return e[r]},$t.getBCHDigit=function(n){let r=0;for(;n!==0;)r++,n>>>=1;return r},$t.setToSJISFunction=function(r){if(typeof r!="function")throw new Error('"toSJISFunc" is not a valid function.');t=r},$t.isKanjiModeEnabled=function(){return typeof t<"u"},$t.toSJIS=function(r){return t(r)},$t}var Ji={},Iu;function wl(){return Iu||(Iu=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+n)}}t.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},t.from=function(r,o){if(t.isValid(r))return r;try{return e(r)}catch{return o}}})(Ji)),Ji}var Qi,Cu;function _1(){if(Cu)return Qi;Cu=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(e){const n=Math.floor(e/8);return(this.buffer[n]>>>7-e%8&1)===1},put:function(e,n){for(let r=0;r<n;r++)this.putBit((e>>>n-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const n=Math.floor(this.length/8);this.buffer.length<=n&&this.buffer.push(0),e&&(this.buffer[n]|=128>>>this.length%8),this.length++}},Qi=t,Qi}var ea,Ru;function O1(){if(Ru)return ea;Ru=1;function t(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return t.prototype.set=function(e,n,r,o){const s=e*this.size+n;this.data[s]=r,o&&(this.reservedBit[s]=!0)},t.prototype.get=function(e,n){return this.data[e*this.size+n]},t.prototype.xor=function(e,n,r){this.data[e*this.size+n]^=r},t.prototype.isReserved=function(e,n){return this.reservedBit[e*this.size+n]},ea=t,ea}var ta={},Tu;function D1(){return Tu||(Tu=1,(function(t){const e=kn().getSymbolSize;t.getRowColCoords=function(r){if(r===1)return[];const o=Math.floor(r/7)+2,s=e(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()},t.getPositions=function(r){const o=[],s=t.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}})(ta)),ta}var na={},Pu;function F1(){if(Pu)return na;Pu=1;const t=kn().getSymbolSize,e=7;return na.getPositions=function(r){const o=t(r);return[[0,0],[o-e,0],[0,o-e]]},na}var ra={},Nu;function M1(){return Nu||(Nu=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},t.from=function(o){return t.isValid(o)?parseInt(o,10):void 0},t.getPenaltyN1=function(o){const s=o.size;let i=0,a=0,c=0,l=null,d=null;for(let u=0;u<s;u++){a=c=0,l=d=null;for(let f=0;f<s;f++){let h=o.get(u,f);h===l?a++:(a>=5&&(i+=e.N1+(a-5)),l=h,a=1),h=o.get(f,u),h===d?c++:(c>=5&&(i+=e.N1+(c-5)),d=h,c=1)}a>=5&&(i+=e.N1+(a-5)),c>=5&&(i+=e.N1+(c-5))}return i},t.getPenaltyN2=function(o){const s=o.size;let i=0;for(let a=0;a<s-1;a++)for(let c=0;c<s-1;c++){const l=o.get(a,c)+o.get(a,c+1)+o.get(a+1,c)+o.get(a+1,c+1);(l===4||l===0)&&i++}return i*e.N2},t.getPenaltyN3=function(o){const s=o.size;let i=0,a=0,c=0;for(let l=0;l<s;l++){a=c=0;for(let d=0;d<s;d++)a=a<<1&2047|o.get(l,d),d>=10&&(a===1488||a===93)&&i++,c=c<<1&2047|o.get(d,l),d>=10&&(c===1488||c===93)&&i++}return i*e.N3},t.getPenaltyN4=function(o){let s=0;const i=o.data.length;for(let c=0;c<i;c++)s+=o.data[c];return Math.abs(Math.ceil(s*100/i/5)-10)*e.N4};function n(r,o,s){switch(r){case t.Patterns.PATTERN000:return(o+s)%2===0;case t.Patterns.PATTERN001:return o%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(o+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return o*s%2+o*s%3===0;case t.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case t.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}t.applyMask=function(o,s){const i=s.size;for(let a=0;a<i;a++)for(let c=0;c<i;c++)s.isReserved(c,a)||s.xor(c,a,n(o,c,a))},t.getBestMask=function(o,s){const i=Object.keys(t.Patterns).length;let a=0,c=1/0;for(let l=0;l<i;l++){s(l),t.applyMask(l,o);const d=t.getPenaltyN1(o)+t.getPenaltyN2(o)+t.getPenaltyN3(o)+t.getPenaltyN4(o);t.applyMask(l,o),d<c&&(c=d,a=l)}return a}})(ra)),ra}var Ko={},Lu;function dg(){if(Lu)return Ko;Lu=1;const t=wl(),e=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],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 Ko.getBlocksCount=function(o,s){switch(s){case t.L:return e[(o-1)*4+0];case t.M:return e[(o-1)*4+1];case t.Q:return e[(o-1)*4+2];case t.H:return e[(o-1)*4+3];default:return}},Ko.getTotalCodewordsCount=function(o,s){switch(s){case t.L:return n[(o-1)*4+0];case t.M:return n[(o-1)*4+1];case t.Q:return n[(o-1)*4+2];case t.H:return n[(o-1)*4+3];default:return}},Ko}var oa={},_r={},Bu;function j1(){if(Bu)return _r;Bu=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let r=1;for(let o=0;o<255;o++)t[o]=r,e[r]=o,r<<=1,r&256&&(r^=285);for(let o=255;o<512;o++)t[o]=t[o-255]})(),_r.log=function(r){if(r<1)throw new Error("log("+r+")");return e[r]},_r.exp=function(r){return t[r]},_r.mul=function(r,o){return r===0||o===0?0:t[e[r]+e[o]]},_r}var _u;function U1(){return _u||(_u=1,(function(t){const e=j1();t.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]^=e.mul(r[i],o[a]);return s},t.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]^=e.mul(o[c],i);let a=0;for(;a<s.length&&s[a]===0;)a++;s=s.slice(a)}return s},t.generateECPolynomial=function(r){let o=new Uint8Array([1]);for(let s=0;s<r;s++)o=t.mul(o,new Uint8Array([1,e.exp(s)]));return o}})(oa)),oa}var sa,Ou;function $1(){if(Ou)return sa;Ou=1;const t=U1();function e(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(r){this.degree=r,this.genPoly=t.generateECPolynomial(this.degree)},e.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=t.mod(o,this.genPoly),i=this.degree-s.length;if(i>0){const a=new Uint8Array(this.degree);return a.set(s,i),a}return s},sa=e,sa}var ia={},aa={},ca={},Du;function ug(){return Du||(Du=1,ca.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),ca}var ut={},Fu;function fg(){if(Fu)return ut;Fu=1;const t="[0-9]+",e="[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
3
- ]))+`;ut.KANJI=new RegExp(n,"g"),ut.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),ut.BYTE=new RegExp(r,"g"),ut.NUMERIC=new RegExp(t,"g"),ut.ALPHANUMERIC=new RegExp(e,"g");const o=new RegExp("^"+n+"$"),s=new RegExp("^"+t+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return ut.testKanji=function(c){return o.test(c)},ut.testNumeric=function(c){return s.test(c)},ut.testAlphanumeric=function(c){return i.test(c)},ut}var Mu;function In(){return Mu||(Mu=1,(function(t){const e=ug(),n=fg();t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(s,i){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!e.isValid(i))throw new Error("Invalid version: "+i);return i>=1&&i<10?s.ccBits[0]:i<27?s.ccBits[1]:s.ccBits[2]},t.getBestModeForData=function(s){return n.testNumeric(s)?t.NUMERIC:n.testAlphanumeric(s)?t.ALPHANUMERIC:n.testKanji(s)?t.KANJI:t.BYTE},t.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},t.isValid=function(s){return s&&s.bit&&s.ccBits};function r(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+o)}}t.from=function(s,i){if(t.isValid(s))return s;try{return r(s)}catch{return i}}})(aa)),aa}var ju;function H1(){return ju||(ju=1,(function(t){const e=kn(),n=dg(),r=wl(),o=In(),s=ug(),i=7973,a=e.getBCHDigit(i);function c(f,h,g){for(let m=1;m<=40;m++)if(h<=t.getCapacity(m,g,f))return m}function l(f,h){return o.getCharCountIndicator(f,h)+4}function d(f,h){let g=0;return f.forEach(function(m){const b=l(m.mode,h);g+=b+m.getBitsLength()}),g}function u(f,h){for(let g=1;g<=40;g++)if(d(f,g)<=t.getCapacity(g,h,o.MIXED))return g}t.from=function(h,g){return s.isValid(h)?parseInt(h,10):g},t.getCapacity=function(h,g,m){if(!s.isValid(h))throw new Error("Invalid QR Code version");typeof m>"u"&&(m=o.BYTE);const b=e.getSymbolTotalCodewords(h),w=n.getTotalCodewordsCount(h,g),R=(b-w)*8;if(m===o.MIXED)return R;const y=R-l(m,h);switch(m){case o.NUMERIC:return Math.floor(y/10*3);case o.ALPHANUMERIC:return Math.floor(y/11*2);case o.KANJI:return Math.floor(y/13);case o.BYTE:default:return Math.floor(y/8)}},t.getBestVersionForData=function(h,g){let m;const b=r.from(g,r.M);if(Array.isArray(h)){if(h.length>1)return u(h,b);if(h.length===0)return 1;m=h[0]}else m=h;return c(m.mode,m.getLength(),b)},t.getEncodedBits=function(h){if(!s.isValid(h)||h<7)throw new Error("Invalid QR Code version");let g=h<<12;for(;e.getBCHDigit(g)-a>=0;)g^=i<<e.getBCHDigit(g)-a;return h<<12|g}})(ia)),ia}var la={},Uu;function q1(){if(Uu)return la;Uu=1;const t=kn(),e=1335,n=21522,r=t.getBCHDigit(e);return la.getEncodedBits=function(s,i){const a=s.bit<<3|i;let c=a<<10;for(;t.getBCHDigit(c)-r>=0;)c^=e<<t.getBCHDigit(c)-r;return(a<<10|c)^n},la}var da={},ua,$u;function K1(){if($u)return ua;$u=1;const t=In();function e(n){this.mode=t.NUMERIC,this.data=n.toString()}return e.getBitsLength=function(r){return 10*Math.floor(r/3)+(r%3?r%3*3+1:0)},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(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))},ua=e,ua}var fa,Hu;function z1(){if(Hu)return fa;Hu=1;const t=In(),e=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function n(r){this.mode=t.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=e.indexOf(this.data[s])*45;i+=e.indexOf(this.data[s+1]),o.put(i,11)}this.data.length%2&&o.put(e.indexOf(this.data[s]),6)},fa=n,fa}var ha,qu;function W1(){if(qu)return ha;qu=1;const t=In();function e(n){this.mode=t.BYTE,typeof n=="string"?this.data=new TextEncoder().encode(n):this.data=new Uint8Array(n)}return e.getBitsLength=function(r){return r*8},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(n){for(let r=0,o=this.data.length;r<o;r++)n.put(this.data[r],8)},ha=e,ha}var pa,Ku;function G1(){if(Ku)return pa;Ku=1;const t=In(),e=kn();function n(r){this.mode=t.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=e.toSJIS(this.data[o]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
4
- Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),r.put(s,13)}},pa=n,pa}var ga={exports:{}},zu;function V1(){return zu||(zu=1,(function(t){var e={single_source_shortest_paths:function(n,r,o){var s={},i={};i[r]=0;var a=e.PriorityQueue.make();a.push(r,0);for(var c,l,d,u,f,h,g,m,b;!a.empty();){c=a.pop(),l=c.value,u=c.cost,f=n[l]||{};for(d in f)f.hasOwnProperty(d)&&(h=f[d],g=u+h,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 w=["Could not find a path from ",r," to ",o,"."].join("");throw new Error(w)}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=e.single_source_shortest_paths(n,r,o);return e.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(n){var r=e.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}}};t.exports=e})(ga)),ga.exports}var Wu;function X1(){return Wu||(Wu=1,(function(t){const e=In(),n=K1(),r=z1(),o=W1(),s=G1(),i=fg(),a=kn(),c=V1();function l(w){return unescape(encodeURIComponent(w)).length}function d(w,R,y){const k=[];let N;for(;(N=w.exec(y))!==null;)k.push({data:N[0],index:N.index,mode:R,length:N[0].length});return k}function u(w){const R=d(i.NUMERIC,e.NUMERIC,w),y=d(i.ALPHANUMERIC,e.ALPHANUMERIC,w);let k,N;return a.isKanjiModeEnabled()?(k=d(i.BYTE,e.BYTE,w),N=d(i.KANJI,e.KANJI,w)):(k=d(i.BYTE_KANJI,e.BYTE,w),N=[]),R.concat(y,k,N).sort(function(T,S){return T.index-S.index}).map(function(T){return{data:T.data,mode:T.mode,length:T.length}})}function f(w,R){switch(R){case e.NUMERIC:return n.getBitsLength(w);case e.ALPHANUMERIC:return r.getBitsLength(w);case e.KANJI:return s.getBitsLength(w);case e.BYTE:return o.getBitsLength(w)}}function h(w){return w.reduce(function(R,y){const k=R.length-1>=0?R[R.length-1]:null;return k&&k.mode===y.mode?(R[R.length-1].data+=y.data,R):(R.push(y),R)},[])}function g(w){const R=[];for(let y=0;y<w.length;y++){const k=w[y];switch(k.mode){case e.NUMERIC:R.push([k,{data:k.data,mode:e.ALPHANUMERIC,length:k.length},{data:k.data,mode:e.BYTE,length:k.length}]);break;case e.ALPHANUMERIC:R.push([k,{data:k.data,mode:e.BYTE,length:k.length}]);break;case e.KANJI:R.push([k,{data:k.data,mode:e.BYTE,length:l(k.data)}]);break;case e.BYTE:R.push([{data:k.data,mode:e.BYTE,length:l(k.data)}])}}return R}function m(w,R){const y={},k={start:{}};let N=["start"];for(let x=0;x<w.length;x++){const T=w[x],S=[];for(let v=0;v<T.length;v++){const A=T[v],_=""+x+v;S.push(_),y[_]={node:A,lastCount:0},k[_]={};for(let B=0;B<N.length;B++){const I=N[B];y[I]&&y[I].node.mode===A.mode?(k[I][_]=f(y[I].lastCount+A.length,A.mode)-f(y[I].lastCount,A.mode),y[I].lastCount+=A.length):(y[I]&&(y[I].lastCount=A.length),k[I][_]=f(A.length,A.mode)+4+e.getCharCountIndicator(A.mode,R))}}N=S}for(let x=0;x<N.length;x++)k[N[x]].end=0;return{map:k,table:y}}function b(w,R){let y;const k=e.getBestModeForData(w);if(y=e.from(R,k),y!==e.BYTE&&y.bit<k.bit)throw new Error('"'+w+'" cannot be encoded with mode '+e.toString(y)+`.
5
- Suggested mode is: `+e.toString(k));switch(y===e.KANJI&&!a.isKanjiModeEnabled()&&(y=e.BYTE),y){case e.NUMERIC:return new n(w);case e.ALPHANUMERIC:return new r(w);case e.KANJI:return new s(w);case e.BYTE:return new o(w)}}t.fromArray=function(R){return R.reduce(function(y,k){return typeof k=="string"?y.push(b(k,null)):k.data&&y.push(b(k.data,k.mode)),y},[])},t.fromString=function(R,y){const k=u(R,a.isKanjiModeEnabled()),N=g(k),x=m(N,y),T=c.find_path(x.map,"start","end"),S=[];for(let v=1;v<T.length-1;v++)S.push(x.table[T[v]].node);return t.fromArray(h(S))},t.rawSplit=function(R){return t.fromArray(u(R,a.isKanjiModeEnabled()))}})(da)),da}var Gu;function Y1(){if(Gu)return Zi;Gu=1;const t=kn(),e=wl(),n=_1(),r=O1(),o=D1(),s=F1(),i=M1(),a=dg(),c=$1(),l=H1(),d=q1(),u=In(),f=X1();function h(x,T){const S=x.size,v=s.getPositions(T);for(let A=0;A<v.length;A++){const _=v[A][0],B=v[A][1];for(let I=-1;I<=7;I++)if(!(_+I<=-1||S<=_+I))for(let E=-1;E<=7;E++)B+E<=-1||S<=B+E||(I>=0&&I<=6&&(E===0||E===6)||E>=0&&E<=6&&(I===0||I===6)||I>=2&&I<=4&&E>=2&&E<=4?x.set(_+I,B+E,!0,!0):x.set(_+I,B+E,!1,!0))}}function g(x){const T=x.size;for(let S=8;S<T-8;S++){const v=S%2===0;x.set(S,6,v,!0),x.set(6,S,v,!0)}}function m(x,T){const S=o.getPositions(T);for(let v=0;v<S.length;v++){const A=S[v][0],_=S[v][1];for(let B=-2;B<=2;B++)for(let I=-2;I<=2;I++)B===-2||B===2||I===-2||I===2||B===0&&I===0?x.set(A+B,_+I,!0,!0):x.set(A+B,_+I,!1,!0)}}function b(x,T){const S=x.size,v=l.getEncodedBits(T);let A,_,B;for(let I=0;I<18;I++)A=Math.floor(I/3),_=I%3+S-8-3,B=(v>>I&1)===1,x.set(A,_,B,!0),x.set(_,A,B,!0)}function w(x,T,S){const v=x.size,A=d.getEncodedBits(T,S);let _,B;for(_=0;_<15;_++)B=(A>>_&1)===1,_<6?x.set(_,8,B,!0):_<8?x.set(_+1,8,B,!0):x.set(v-15+_,8,B,!0),_<8?x.set(8,v-_-1,B,!0):_<9?x.set(8,15-_-1+1,B,!0):x.set(8,15-_-1,B,!0);x.set(v-8,8,1,!0)}function R(x,T){const S=x.size;let v=-1,A=S-1,_=7,B=0;for(let I=S-1;I>0;I-=2)for(I===6&&I--;;){for(let E=0;E<2;E++)if(!x.isReserved(A,I-E)){let P=!1;B<T.length&&(P=(T[B]>>>_&1)===1),x.set(A,I-E,P),_--,_===-1&&(B++,_=7)}if(A+=v,A<0||S<=A){A-=v,v=-v;break}}}function y(x,T,S){const v=new n;S.forEach(function(E){v.put(E.mode.bit,4),v.put(E.getLength(),u.getCharCountIndicator(E.mode,x)),E.write(v)});const A=t.getSymbolTotalCodewords(x),_=a.getTotalCodewordsCount(x,T),B=(A-_)*8;for(v.getLengthInBits()+4<=B&&v.put(0,4);v.getLengthInBits()%8!==0;)v.putBit(0);const I=(B-v.getLengthInBits())/8;for(let E=0;E<I;E++)v.put(E%2?17:236,8);return k(v,x,T)}function k(x,T,S){const v=t.getSymbolTotalCodewords(T),A=a.getTotalCodewordsCount(T,S),_=v-A,B=a.getBlocksCount(T,S),I=v%B,E=B-I,P=Math.floor(v/B),C=Math.floor(_/B),D=C+1,M=P-C,F=new c(M);let L=0;const $=new Array(B),H=new Array(B);let U=0;const q=new Uint8Array(x.buffer);for(let G=0;G<B;G++){const Y=G<E?C:D;$[G]=q.slice(L,L+Y),H[G]=F.encode($[G]),L+=Y,U=Math.max(U,Y)}const K=new Uint8Array(v);let X=0,z,W;for(z=0;z<U;z++)for(W=0;W<B;W++)z<$[W].length&&(K[X++]=$[W][z]);for(z=0;z<M;z++)for(W=0;W<B;W++)K[X++]=H[W][z];return K}function N(x,T,S,v){let A;if(Array.isArray(x))A=f.fromArray(x);else if(typeof x=="string"){let P=T;if(!P){const C=f.rawSplit(x);P=l.getBestVersionForData(C,S)}A=f.fromString(x,P||40)}else throw new Error("Invalid data");const _=l.getBestVersionForData(A,S);if(!_)throw new Error("The amount of data is too big to be stored in a QR Code");if(!T)T=_;else if(T<_)throw new Error(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/passwordBootstrap-kiljsfOw.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/App-ySHLLxfl.js","assets/gestureArbiter-Q4qvTxJM.js","assets/gestureArbiter-C2J0D0kV.css","assets/triangle-alert-DZyRaNWe.js","assets/referenceLongPress-DcD1aZqh.js","assets/DagPlayground-CBUX-s8X.js","assets/ChangeWalkthroughPanel-DrsLVbFw.js","assets/sparkles-BQVhXL1X.js","assets/DiffLab-DD8m9b0G.js","assets/DiffViewer-zb8C5YLR.js","assets/DiffViewer-T3uj2-aP.css","assets/DiffReviewLab-BS1rFkx9.js","assets/DiffReview-BEFjWY01.js"])))=>i.map(i=>d[i]);
2
+ import{r as _c,a as Rm,g as If}from"./react-XDCjal2T.js";import{b as O,R as We,r as Oc}from"./dnd-BCFAPC0L.js";import{L as Tm,l as Pm}from"./terminal-C7X98Amf.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))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 Nm="modulepreload",Lm=function(t){return"/"+t},Wl={},Jt=function(e,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=Lm(l),l in Wl)return;Wl[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":Nm,d||(f.as="script"),f.crossOrigin="",f.href=l,a&&f.setAttribute("nonce",a),document.head.appendChild(f),d)return new Promise((h,g)=>{f.addEventListener("load",h),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${l}`)))})}))}function s(i){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=i,window.dispatchEvent(a),!a.defaultPrevented)throw i}return o.then(i=>{for(const a of i||[])a.status==="rejected"&&s(a.reason);return e().catch(s)})};var Ei={exports:{}},kr={};var Vl;function Bm(){if(Vl)return kr;Vl=1;var t=_c(),e=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function i(a,c,l){var d,u={},f=null,h=null;l!==void 0&&(f=""+l),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(h=c.ref);for(d in c)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:e,type:a,key:f,ref:h,props:u,_owner:o.current}}return kr.Fragment=n,kr.jsx=i,kr.jsxs=i,kr}var Gl;function _m(){return Gl||(Gl=1,Ei.exports=Bm()),Ei.exports}var p=_m();const gn="termdock-secure-target-v1",Dc="termdock-secure-entry-v1",Om=new Set([gn,Dc,"termdock-color-theme","termdock:locale","termdock.federation.connections.v1"]),Co=typeof Storage>"u"?void 0:Storage.prototype.getItem,Ai=typeof Storage>"u"?void 0:Storage.prototype.setItem,Xl="termdock-secure-legacy-owner",Hs=typeof window<"u"&&window.parent!==window&&location.pathname==="/workspace.html";function Dm(){if(typeof window>"u")return null;try{if(Hs){const e=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===e):void 0;return r&&typeof r.url=="string"&&typeof r.targetPeerId=="string"?{...r,serviceName:r.label||r.serviceName}:null}const t=JSON.parse(sessionStorage.getItem(gn)??localStorage.getItem(gn)??"null");return t&&typeof t.url=="string"&&typeof t.targetPeerId=="string"?t:null}catch{return null}}let qs=Dm();const Wn=qs?.targetPeerId??"unpaired";function Fc(){return qs}function Rf(t){if(qs=t,Hs)return;const e=JSON.stringify(t);sessionStorage.setItem(gn,e),localStorage.setItem(gn,e)}function Fm(){qs=null,!Hs&&(localStorage.removeItem(gn),sessionStorage.removeItem(gn),localStorage.removeItem(Dc))}function Xr(t,e=Wn){return Om.has(t)||t.startsWith("termdock-secure-")?t:`termdock-service:${e}:${t}`}function Mm(t){if(!(!Co||!Ai))try{if(Co.call(localStorage,Xl))return;Ai.call(localStorage,Xl,t);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:")||Xr(o,t)===o)continue;const s=Xr(o,t),i=Co.call(n,o);i!==null&&Co.call(n,s)===null&&Ai.call(n,s,i)}}}catch{}}let Yl=!1;function jm(){if(Yl||typeof Storage>"u")return;Yl=!0;const t=Storage.prototype.getItem,e=Storage.prototype.setItem,n=Storage.prototype.removeItem;Storage.prototype.getItem=function(r){return t.call(this,Xr(String(r)))},Storage.prototype.setItem=function(r,o){e.call(this,Xr(String(r)),o)},Storage.prototype.removeItem=function(r){n.call(this,Xr(String(r)))}}jm();const Ks="termdock.federation.connections.v1",Na="termdock:services-changed",Mc="termdock-secure-removed-services",ls=t=>[t.id,t.targetPeerId,t.serviceOrigin||t.url].filter(e=>!!e);function jc(){try{const t=JSON.parse(localStorage.getItem(Mc)||"[]");return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}catch{return[]}}function _e(t){const e=t.trim();if(!e)throw new Error("请输入服务地址。");const n=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(e)?e:`https://${e}`);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 zs(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.url=="string")try{const n=_e(e.url),r=typeof e.targetPeerId=="string"&&e.targetPeerId?e.targetPeerId:void 0,o=(typeof e.label=="string"?e.label:typeof e.serviceName=="string"?e.serviceName:"").trim().slice(0,120)||new URL(n).host;return{id:typeof e.id=="string"&&e.id?e.id:r||n,url:n,label:o,...r?{targetPeerId:r}:{},...typeof e.serviceOrigin=="string"?{serviceOrigin:_e(e.serviceOrigin)}:{},...typeof e.entryServiceId=="string"&&e.entryServiceId?{entryServiceId:e.entryServiceId}:{},...Array.isArray(e.routes)?{routes:e.routes.slice(0,4).flatMap(s=>{try{return s&&typeof s.targetPeerId=="string"&&s.targetPeerId?[{url:_e(s.url),targetPeerId:s.targetPeerId}]:[]}catch{return[]}})}:{}}}catch{return}}function At(t,e){return t.targetPeerId&&e.targetPeerId?t.targetPeerId===e.targetPeerId:(t.serviceOrigin||t.url)===(e.serviceOrigin||e.url)}function Tf(t){const e=[];for(const n of t){const r=e.findIndex(o=>At(o,n));r<0?e.push(n):e[r]={...e[r],...n,id:e[r].id}}return e}function mo(){return typeof window>"u"?void 0:window.termdockDesktop}function mn(){try{const t=JSON.parse(localStorage.getItem(Ks)||"[]");return Array.isArray(t)?Tf(t.map(zs).filter(e=>!!e)):[]}catch{return[]}}function Pf(t){localStorage.setItem(Ks,JSON.stringify(t.map(e=>({...e,serviceName:e.label})))),window.dispatchEvent(new Event(Na))}let Cr;async function Ke(){const t=mo();if(!t?.serviceConnections||!t.saveServiceConnection)return mn();if(Cr)return Cr;Cr=(async()=>{let e=await t.serviceConnections();const n=mn();for(const r of n)e.some(o=>At(o,r))||(e=await(t.importServiceConnection||t.saveServiceConnection)(r));return n.length&&localStorage.removeItem(Ks),e})();try{return await Cr}finally{Cr=void 0}}async function Tt(t){const e=zs(t);if(!e)throw new Error("服务地址无效。");const n=mo();if(n?.saveServiceConnection)return n.saveServiceConnection(e);const r=mn(),o=r.find(a=>a.id===e.id||At(a,e)),s=new Set([...ls(e),...o?ls(o):[]]);localStorage.setItem(Mc,JSON.stringify(jc().filter(a=>!s.has(a))));const i=Tf([...r.filter(a=>a!==o),{...o,...e,id:o?.id||e.id}]);return Pf(i),i}async function Um(t){const e=zs(t);if(!e)throw new Error("服务地址无效。");const n=mo();if(n?.importServiceConnection)return n.importServiceConnection(e);if(n?.serviceConnections){const r=await n.serviceConnections();return r.some(o=>At(o,e))?Tt(e):r}return ls(e).some(r=>jc().includes(r))?mn():Tt(e)}async function $m(t){const e=mo();if(e?.removeServiceConnection)return e.removeServiceConnection(t);const n=mn(),r=n.find(s=>s.id===t);r&&localStorage.setItem(Mc,JSON.stringify([...new Set([...jc(),...ls(r)])].slice(-768)));const o=n.filter(s=>s.id!==t);return Pf(o),o}function Ws(t){const e=r=>{(r.key===Ks||r.key===null)&&t()};window.addEventListener(Na,t),window.addEventListener("storage",e);const n=mo()?.onServiceConnections?.(t);return()=>{window.removeEventListener(Na,t),window.removeEventListener("storage",e),n?.()}}class Hm extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}let qm=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},at=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};class Nf extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class Lf extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}}class Km extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class zm extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class Vs extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}const Bf=Symbol.for("@libp2p/peer-id");function Wm(t){return typeof t?.handleEvent=="function"}function Vm(t){return t===!0||t===!1}function Gm(t){return Vm(t)?t:t?.capture??!1}function La(t){const e={capture:Gm(t),once:!!t?.once};return t?.passive!=null&&(e.passive=t?.passive),t?.signal!=null&&(e.signal=t?.signal),e}function Zl(t,e){return La(t).capture===La(e).capture}class Xm extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const n=this.#e.get(e);return n==null?0:n.length}addEventListener(e,n,r){const o=La(r);if(o?.signal?.aborted===!0)return;const s=l=>{o.once&&this.removeEventListener(e,n,o),Wm(n)?n.handleEvent(l):n(l)};let i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(l=>l.callback!==n?!1:Zl(l.options,o)))return;super.addEventListener(e,s,o);const c=()=>{this.removeEventListener(e,n,o)};o.signal?.addEventListener("abort",c),i.push({callback:n,wrapper:s,options:o,onAbort:c})}removeEventListener(e,n,r){const o=this.#e.get(e);if(o==null){super.removeEventListener(e,n??null,r);return}this.#e.set(e,o.filter(s=>s.callback===n&&Zl(s.options,r)?(super.removeEventListener(e,s.wrapper,r),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,n={}){return this.dispatchEvent(new CustomEvent(e,n))}}const Ym=Symbol.for("@libp2p/service-capabilities");function Zm(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let n=0;n<t.byteLength;n++)if(t[n]!==e[n])return!1;return!0}function Gs(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function Jm(t){return new TextEncoder().encode(t)}function Qm(t){return new TextDecoder().decode(t)}function ew(t,e){if(t.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<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(n[i]!==255)throw new TypeError(s+" is ambiguous");n[i]=o}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var m=0,b=0,w=0,R=g.length;w!==R&&g[w]===0;)w++,m++;for(var y=(R-w)*d+1>>>0,k=new Uint8Array(y);w!==R;){for(var N=g[w],x=0,T=y-1;(N!==0||x<b)&&T!==-1;T--,x++)N+=256*k[T]>>>0,k[T]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");b=x,w++}for(var S=y-b;S!==y&&k[S]===0;)S++;for(var v=c.repeat(m);S<y;++S)v+=t.charAt(k[S]);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,w=0;g[m]===c;)b++,m++;for(var R=(g.length-m)*l+1>>>0,y=new Uint8Array(R);g[m];){var k=n[g.charCodeAt(m)];if(k===255)return;for(var N=0,x=R-1;(k!==0||N<w)&&x!==-1;x--,N++)k+=a*y[x]>>>0,y[x]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");w=N,m++}if(g[m]!==" "){for(var T=R-w;T!==R&&y[T]===0;)T++;for(var S=new Uint8Array(b+(R-T)),v=b;T!==R;)S[v++]=y[T++];return S}}}function h(g){var m=f(g);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:h}}var tw=ew,nw=tw;class rw{name;prefix;baseEncode;constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class ow{name;prefix;baseDecode;prefixCodePoint;constructor(e,n,r){this.name=e,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(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return _f(this,e)}}class sw{decoders;constructor(e){this.decoders=e}or(e){return _f(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r!=null)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function _f(t,e){return new sw({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class iw{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,n,r,o){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=o,this.encoder=new rw(e,n,r),this.decoder=new ow(e,n,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function Xs({name:t,prefix:e,encode:n,decode:r}){return new iw(t,e,n,r)}function wo({name:t,prefix:e,alphabet:n}){const{encode:r,decode:o}=nw(n,t);return Xs({prefix:e,name:t,encode:r,decode:s=>Gs(o(s))})}function aw(t,e,n,r){let o=t.length;for(;t[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=e[t[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 cw(t,e,n){const r=e[e.length-1]==="=",o=(1<<n)-1;let s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>n;)i-=n,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<n-i]),r)for(;(s.length*n&7)!==0;)s+="=";return s}function lw(t){const e={};for(let n=0;n<t.length;++n)e[t[n]]=n;return e}function Te({name:t,prefix:e,bitsPerChar:n,alphabet:r}){const o=lw(r);return Xs({prefix:e,name:t,encode(s){return cw(s,r,n)},decode(s){return aw(s,o,n,t)}})}const Fe=wo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),dw=wo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),uw=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Fe,base58flickr:dw},Symbol.toStringTag,{value:"Module"})),Yr=Te({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),fw=Te({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hw=Te({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pw=Te({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),gw=Te({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),mw=Te({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ww=Te({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),yw=Te({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),bw=Te({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),vw=Object.freeze(Object.defineProperty({__proto__:null,base32:Yr,base32hex:gw,base32hexpad:ww,base32hexpadupper:yw,base32hexupper:mw,base32pad:hw,base32padupper:pw,base32upper:fw,base32z:bw},Symbol.toStringTag,{value:"Module"})),Yo=wo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Sw=wo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),xw=Object.freeze(Object.defineProperty({__proto__:null,base36:Yo,base36upper:Sw},Symbol.toStringTag,{value:"Module"}));var Ew=Of,Jl=128,Aw=-128,kw=Math.pow(2,31);function Of(t,e,n){e=e||[],n=n||0;for(var r=n;t>=kw;)e[n++]=t&255|Jl,t/=128;for(;t&Aw;)e[n++]=t&255|Jl,t>>>=7;return e[n]=t|0,Of.bytes=n-r+1,e}var Cw=Ba,Iw=128,Ql=127;function Ba(t,r){var n=0,r=r||0,o=0,s=r,i,a=t.length;do{if(s>=a)throw Ba.bytes=0,new RangeError("Could not decode varint");i=t[s++],n+=o<28?(i&Ql)<<o:(i&Ql)*Math.pow(2,o),o+=7}while(i>=Iw);return Ba.bytes=s-r,n}var Rw=Math.pow(2,7),Tw=Math.pow(2,14),Pw=Math.pow(2,21),Nw=Math.pow(2,28),Lw=Math.pow(2,35),Bw=Math.pow(2,42),_w=Math.pow(2,49),Ow=Math.pow(2,56),Dw=Math.pow(2,63),Fw=function(t){return t<Rw?1:t<Tw?2:t<Pw?3:t<Nw?4:t<Lw?5:t<Bw?6:t<_w?7:t<Ow?8:t<Dw?9:10},Mw={encode:Ew,decode:Cw,encodingLength:Fw},ds=Mw;function _a(t,e=0){return[ds.decode(t,e),ds.decode.bytes]}function us(t,e,n=0){return ds.encode(t,e,n),e}function fs(t){return ds.encodingLength(t)}function yo(t,e){const n=e.byteLength,r=fs(t),o=r+fs(n),s=new Uint8Array(o+n);return us(t,s,0),us(n,s,r),s.set(e,o),new Uc(t,n,e,s)}function Df(t){const e=Gs(t),[n,r]=_a(e),[o,s]=_a(e.subarray(r)),i=e.subarray(r+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Uc(n,o,i,e)}function jw(t,e){if(t===e)return!0;{const n=e;return t.code===n.code&&t.size===n.size&&n.bytes instanceof Uint8Array&&Zm(t.bytes,n.bytes)}}class Uc{code;size;digest;bytes;constructor(e,n,r,o){this.code=e,this.size=n,this.digest=r,this.bytes=o}}function ed(t,e){const{bytes:n,version:r}=t;return r===0?$w(n,Oa(t),e??Fe.encoder):Hw(n,Oa(t),e??Yr.encoder)}const td=new WeakMap;function Oa(t){const e=td.get(t);if(e==null){const n=new Map;return td.set(t,n),n}return e}class ue{code;version;multihash;bytes;"/";constructor(e,n,r,o){this.code=n,this.version=e,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:e,multihash:n}=this;if(e!==Ir)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==qw)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ue.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:e,digest:n}=this.multihash,r=yo(e,n);return ue.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(e){return ue.equals(this,e)}static equals(e,n){const r=n;return r!=null&&e.code===r.code&&e.version===r.version&&jw(e.multihash,r.multihash)}toString(e){return ed(this,e)}toJSON(){return{"/":ed(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;const n=e;if(n instanceof ue)return n;if(n["/"]!=null&&n["/"]===n.bytes||n.asCID===n){const{version:r,code:o,multihash:s,bytes:i}=n;return new ue(r,o,s,i??nd(r,o,s.bytes))}else if(n[Kw]===!0){const{version:r,multihash:o,code:s}=n,i=Df(o);return ue.create(r,s,i)}else return null}static create(e,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(e){case 0:{if(n!==Ir)throw new Error(`Version 0 CID must use dag-pb (code: ${Ir}) block encoding`);return new ue(e,n,r,r.bytes)}case 1:{const o=nd(e,n,r.bytes);return new ue(e,n,r,o)}default:throw new Error("Invalid version")}}static createV0(e){return ue.create(0,Ir,e)}static createV1(e,n){return ue.create(1,e,n)}static decode(e){const[n,r]=ue.decodeFirst(e);if(r.length!==0)throw new Error("Incorrect length");return n}static decodeFirst(e){const n=ue.inspectBytes(e),r=n.size-n.multihashSize,o=Gs(e.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 Uc(n.multihashCode,n.digestSize,s,o);return[n.version===0?ue.createV0(i):ue.createV1(n.codec,i),e.subarray(n.size)]}static inspectBytes(e){let n=0;const r=()=>{const[u,f]=_a(e.subarray(n));return n+=f,u};let o=r(),s=Ir;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(e,n){const[r,o]=Uw(e,n),s=ue.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Oa(s).set(r,e),s}}function Uw(t,e){switch(t[0]){case"Q":{const n=e??Fe;return[Fe.prefix,n.decode(`${Fe.prefix}${t}`)]}case Fe.prefix:{const n=e??Fe;return[Fe.prefix,n.decode(t)]}case Yr.prefix:{const n=e??Yr;return[Yr.prefix,n.decode(t)]}case Yo.prefix:{const n=e??Yo;return[Yo.prefix,n.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function $w(t,e,n){const{prefix:r}=n;if(r!==Fe.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);const o=e.get(r);if(o==null){const s=n.encode(t).slice(1);return e.set(r,s),s}else return o}function Hw(t,e,n){const{prefix:r}=n,o=e.get(r);if(o==null){const s=n.encode(t);return e.set(r,s),s}else return o}const Ir=112,qw=18;function nd(t,e,n){const r=fs(t),o=r+fs(e),s=new Uint8Array(o+n.byteLength);return us(t,s,0),us(e,s,r),s.set(n,o),s}const Kw=Symbol.for("@ipld/js-cid/CID"),Ff=0,zw="identity",Mf=Gs;function Ww(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return yo(Ff,Mf(t))}const bo={code:Ff,name:zw,encode:Mf,digest:Ww};function ct(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let n=0;n<t.byteLength;n++)if(t[n]!==e[n])return!1;return!0}function He(t=0){return new Uint8Array(t)}function Pt(t=0){return new Uint8Array(t)}function Da(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));const n=Pt(e);let r=0;for(const o of t)n.set(o,r),r+=o.length;return n}const jf=Symbol.for("@achingbrain/uint8arraylist");function rd(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let n=0;for(const r of t){const o=n+r.byteLength;if(e<o)return{buf:r,index:e-n};n=o}throw new RangeError("index is out of bounds")}function Io(t){return!!t?.[jf]}class se{bufs;length;[jf]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let n=0;for(const r of e)if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.push(r);else if(Io(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(...e){this.prependAll(e)}prependAll(e){let n=0;for(const r of e.reverse())if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.unshift(r);else if(Io(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(e){const n=rd(this.bufs,e);return n.buf[n.index]}set(e,n){const r=rd(this.bufs,e);r.buf[r.index]=n}write(e,n=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(n+r,e[r]);else if(Io(e))for(let r=0;r<e.length;r++)this.set(n+r,e.get(r));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,n){const{bufs:r,length:o}=this._subList(e,n);return Da(r,o)}subarray(e,n){const{bufs:r,length:o}=this._subList(e,n);return r.length===1?r[0]:Da(r,o)}sublist(e,n){const{bufs:r,length:o}=this._subList(e,n),s=new se;return s.length=o,s.bufs=r,s}_subList(e,n){if(e=e??0,n=n??this.length,e<0&&(e=this.length+e),n<0&&(n=this.length+n),e<0||n>this.length)throw new RangeError("index is out of bounds");if(e===n)return{bufs:[],length:0};if(e===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,e>=c)continue;const l=e>=a&&e<c,d=n>a&&n<=c;if(l&&d){if(e===a&&n===c){r.push(i);break}const u=e-a;r.push(i.subarray(u,u+(n-e)));break}if(l){if(e===0){r.push(i);continue}r.push(i.subarray(e-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-e}}indexOf(e,n=0){if(!Io(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(n=Number(n??0),isNaN(n)&&(n=0),n<0&&(n=this.length+n),n<0&&(n=0),e.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 h=this.get(u+f);if(r[f]!==h){d=Math.max(1,f-a[h]);break}}if(d===0)return u}return-1}getInt8(e){const n=this.subarray(e,e+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt8(0)}setInt8(e,n){const r=Pt(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,n),this.write(r,e)}getInt16(e,n){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,n)}setInt16(e,n,r){const o=He(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,n,r),this.write(o,e)}getInt32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,n)}setInt32(e,n,r){const o=He(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,n,r),this.write(o,e)}getBigInt64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,n)}setBigInt64(e,n,r){const o=He(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,n,r),this.write(o,e)}getUint8(e){const n=this.subarray(e,e+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint8(0)}setUint8(e,n){const r=Pt(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,n),this.write(r,e)}getUint16(e,n){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,n)}setUint16(e,n,r){const o=He(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,n,r),this.write(o,e)}getUint32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,n)}setUint32(e,n,r){const o=He(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,n,r),this.write(o,e)}getBigUint64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,n)}setBigUint64(e,n,r){const o=He(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,n,r),this.write(o,e)}getFloat32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,n)}setFloat32(e,n,r){const o=He(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,n,r),this.write(o,e)}getFloat64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,n)}setFloat64(e,n,r){const o=He(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,n,r),this.write(o,e)}equals(e){if(e==null||!(e instanceof se)||e.bufs.length!==this.bufs.length)return!1;for(let n=0;n<this.bufs.length;n++)if(!ct(this.bufs[n],e.bufs[n]))return!1;return!0}static fromUint8Arrays(e,n){const r=new se;return r.bufs=e,n==null&&(n=e.reduce((o,s)=>o+s.byteLength,0)),r.length=n,r}}const Vw=wo({prefix:"9",name:"base10",alphabet:"0123456789"}),Gw=Object.freeze(Object.defineProperty({__proto__:null,base10:Vw},Symbol.toStringTag,{value:"Module"})),Xw=Te({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Yw=Te({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Zw=Object.freeze(Object.defineProperty({__proto__:null,base16:Xw,base16upper:Yw},Symbol.toStringTag,{value:"Module"})),Jw=Te({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Qw=Object.freeze(Object.defineProperty({__proto__:null,base2:Jw},Symbol.toStringTag,{value:"Module"})),Uf=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),ey=Uf.reduce((t,e,n)=>(t[n]=e,t),[]),ty=Uf.reduce((t,e,n)=>{const r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return t[r]=n,t},[]);function ny(t){return t.reduce((e,n)=>(e+=ey[n],e),"")}function ry(t){const e=[];for(const n of t){const r=n.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${n}`);const o=ty[r];if(o==null)throw new Error(`Non-base256emoji character: ${n}`);e.push(o)}return new Uint8Array(e)}const oy=Xs({prefix:"🚀",name:"base256emoji",encode:ny,decode:ry}),sy=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:oy},Symbol.toStringTag,{value:"Module"})),iy=Te({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ay=Te({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cy=Te({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ly=Te({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),dy=Object.freeze(Object.defineProperty({__proto__:null,base64:iy,base64pad:ay,base64url:cy,base64urlpad:ly},Symbol.toStringTag,{value:"Module"})),uy=Te({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),fy=Object.freeze(Object.defineProperty({__proto__:null,base8:uy},Symbol.toStringTag,{value:"Module"})),hy=Xs({prefix:"\0",name:"identity",encode:t=>Qm(t),decode:t=>Jm(t)}),py=Object.freeze(Object.defineProperty({__proto__:null,identity:hy},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const gy=20;function my({name:t,code:e,encode:n,minDigestLength:r,maxDigestLength:o}){return new wy(t,e,n,r,o)}class wy{name;code;encode;minDigestLength;maxDigestLength;constructor(e,n,r,o,s){this.name=e,this.code=n,this.encode=r,this.minDigestLength=o??gy,this.maxDigestLength=s}digest(e,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(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?od(r,this.code,n?.truncate):r.then(o=>od(o,this.code,n?.truncate))}else throw Error("Unknown type, must be binary type")}}function od(t,e,n){if(n!=null&&n!==t.byteLength){if(n>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,n)}return yo(e,t)}function yy(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}const $c=my({name:"sha2-256",code:18,encode:yy("SHA-256")}),sd={...py,...Qw,...fy,...Gw,...Zw,...vw,...xw,...uw,...dy,...sy};function $f(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const id=$f("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ki=$f("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=Pt(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),Hf={utf8:id,"utf-8":id,hex:sd.base16,latin1:ki,ascii:ki,binary:ki,...sd};function be(t,e="utf8"){const n=Hf[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.decoder.decode(`${n.prefix}${t}`)}function te(t,e="utf8"){const n=Hf[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.encoder.encode(t).substring(1)}const by=parseInt("11111",2),Fa=parseInt("10000000",2),vy=parseInt("01111111",2),ad={0:Rr,1:Rr,2:Sy,3:Ay,4:ky,5:Ey,6:xy,16:Rr,22:Rr,48:Rr};function wr(t,e={offset:0}){const n=t[e.offset]&by;if(e.offset++,ad[n]!=null)return ad[n](t,e);throw new Error("No decoder for tag "+n)}function vo(t,e){let n=0;if((t[e.offset]&Fa)===Fa){const r=t[e.offset]&vy;let o="0x";e.offset++;for(let s=0;s<r;s++,e.offset++)o+=t[e.offset].toString(16).padStart(2,"0");n=parseInt(o,16)}else n=t[e.offset],e.offset++;return n}function Rr(t,e){vo(t,e);const n=[];for(;!(e.offset>=t.byteLength);){const r=wr(t,e);if(r===null)break;n.push(r)}return n}function Sy(t,e){const n=vo(t,e),r=e.offset,o=e.offset+n,s=[];for(let i=r;i<o;i++)i===r&&t[i]===0||s.push(t[i]);return e.offset+=n,Uint8Array.from(s)}function xy(t,e){const n=vo(t,e),r=e.offset+n,o=t[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<r;){const l=t[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let d=0;for(let u=0;u<c.length;u++)d+=c[u]<<u*7;a+=`.${d}`,c=[]}}return a}function Ey(t,e){return e.offset++,null}function Ay(t,e){const n=vo(t,e),r=t[e.offset];e.offset++;const o=t.subarray(e.offset,e.offset+n-1);if(e.offset+=n,r!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function ky(t,e){const n=vo(t,e),r=t.subarray(e.offset,e.offset+n);return e.offset+=n,r}function Cy(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);const n=new se;for(let r=0;r<e.length;r+=2)n.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return n}function Ys(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);const e=Cy(t.byteLength);return new se(Uint8Array.from([e.byteLength|Fa]),e)}function ze(t){const e=new se,n=128;return(t.subarray()[0]&n)===n&&e.append(Uint8Array.from([0])),e.append(t),new se(Uint8Array.from([2]),Ys(e),e)}function Hc(t){const e=Uint8Array.from([0]),n=new se(e,t);return new se(Uint8Array.from([3]),Ys(n),n)}function Iy(t){return new se(Uint8Array.from([4]),Ys(t),t)}function Rt(t,e=48){const n=new se;for(const r of t)n.append(r);return new se(Uint8Array.from([e]),Ys(n),n)}async function Ry(t,e,n){const r=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["sign"]);n?.signal?.throwIfAborted();const o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Ty(t,e,n,r){const o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();const s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,n.subarray());return r?.signal?.throwIfAborted(),s}const Py=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Ny=Uint8Array.from([6,5,43,129,4,0,34]),Ly=Uint8Array.from([6,5,43,129,4,0,35]),qf={ext:!0,kty:"EC",crv:"P-256"},Kf={ext:!0,kty:"EC",crv:"P-384"},zf={ext:!0,kty:"EC",crv:"P-521"},Vn=32,Gn=48,Xn=66;function By(t){const e=wr(t);return _y(e)}function _y(t){const e=t[1],n=te(e,"base64url"),r=t[2][1][0],o=1;let s,i;if(e.byteLength===Vn)return s=te(r.subarray(o,o+Vn),"base64url"),i=te(r.subarray(o+Vn),"base64url"),new Ci({...qf,key_ops:["sign"],d:n,x:s,y:i});if(e.byteLength===Gn)return s=te(r.subarray(o,o+Gn),"base64url"),i=te(r.subarray(o+Gn),"base64url"),new Ci({...Kf,key_ops:["sign"],d:n,x:s,y:i});if(e.byteLength===Xn)return s=te(r.subarray(o,o+Xn),"base64url"),i=te(r.subarray(o+Xn),"base64url"),new Ci({...zf,key_ops:["sign"],d:n,x:s,y:i});throw new at(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function Wf(t){const e=wr(t);return Oy(e)}function Oy(t){const e=t[1][1][0],n=1;let r,o;if(e.byteLength===Vn*2+1)return r=te(e.subarray(n,n+Vn),"base64url"),o=te(e.subarray(n+Vn),"base64url"),new Zo({...qf,key_ops:["verify"],x:r,y:o});if(e.byteLength===Gn*2+1)return r=te(e.subarray(n,n+Gn),"base64url"),o=te(e.subarray(n+Gn),"base64url"),new Zo({...Kf,key_ops:["verify"],x:r,y:o});if(e.byteLength===Xn*2+1)return r=te(e.subarray(n,n+Xn),"base64url"),o=te(e.subarray(n+Xn),"base64url"),new Zo({...zf,key_ops:["verify"],x:r,y:o});throw new at(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Dy(t){return Rt([ze(Uint8Array.from([1])),Iy(be(t.d??"","base64url")),Rt([Vf(t.crv)],160),Rt([Hc(new se(Uint8Array.from([4]),be(t.x??"","base64url"),be(t.y??"","base64url")))],161)]).subarray()}function Fy(t){return Rt([ze(Uint8Array.from([1])),Rt([Vf(t.crv)],160),Rt([Hc(new se(Uint8Array.from([4]),be(t.x??"","base64url"),be(t.y??"","base64url")))],161)]).subarray()}function Vf(t){if(t==="P-256")return Py;if(t==="P-384")return Ny;if(t==="P-521")return Ly;throw new at(`Invalid curve ${t}`)}class Zo{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Fy(this.jwk)),this._raw}toMultihash(){return bo.digest(ni(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return Fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ct(this.raw,e.raw)}async verify(e,n,r){return Ty(this.jwk,n,e,r)}}class Ci{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Zo({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=Dy(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ct(this.raw,e.raw)}async sign(e,n){return Ry(this.jwk,e,n)}}const Bn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function So(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ma(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function xn(t,...e){if(!So(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Gf(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Ma(t.outputLen),Ma(t.blockLen)}function hs(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function My(t,e){xn(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function cr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Ii(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function lt(t,e){return t<<32-e|t>>>e}const Xf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",jy=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function un(t){if(xn(t),Xf)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=jy[t[n]];return e}const yt={_0:48,_9:57,A:65,F:70,a:97,f:102};function cd(t){if(t>=yt._0&&t<=yt._9)return t-yt._0;if(t>=yt.A&&t<=yt.F)return t-(yt.A-10);if(t>=yt.a&&t<=yt.f)return t-(yt.a-10)}function ps(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Xf)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){const i=cd(t.charCodeAt(s)),a=cd(t.charCodeAt(s+1));if(i===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a}return r}function Uy(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function qc(t){return typeof t=="string"&&(t=Uy(t)),xn(t),t}function ft(...t){let e=0;for(let r=0;r<t.length;r++){const o=t[r];xn(o),e+=o.length}const n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){const s=t[r];n.set(s,o),o+=s.length}return n}class Yf{}function Zf(t){const e=r=>t().update(qc(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Kc(t=32){if(Bn&&typeof Bn.getRandomValues=="function")return Bn.getRandomValues(new Uint8Array(t));if(Bn&&typeof Bn.randomBytes=="function")return Uint8Array.from(Bn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function $y(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,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;t.setUint32(e+c,i,r),t.setUint32(e+l,a,r)}function Hy(t,e,n){return t&e^~t&n}function qy(t,e,n){return t&e^t&n^e&n}let Jf=class extends Yf{constructor(e,n,r,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Ii(this.buffer)}update(e){hs(this),e=qc(e),xn(e);const{view:n,buffer:r,blockLen:o}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(o-this.pos,s-i);if(a===o){const c=Ii(e);for(;o<=s-i;i+=o)this.process(c,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){hs(this),My(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:o,isLE:s}=this;let{pos:i}=this;n[i++]=128,cr(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(r,0),i=0);for(let u=i;u<o;u++)n[u]=0;$y(r,o-8,BigInt(this.length*8),s),this.process(r,0);const a=Ii(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};const Ot=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Pe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Ro=BigInt(2**32-1),ld=BigInt(32);function Ky(t,e=!1){return e?{h:Number(t&Ro),l:Number(t>>ld&Ro)}:{h:Number(t>>ld&Ro)|0,l:Number(t&Ro)|0}}function zy(t,e=!1){const n=t.length;let r=new Uint32Array(n),o=new Uint32Array(n);for(let s=0;s<n;s++){const{h:i,l:a}=Ky(t[s],e);[r[s],o[s]]=[i,a]}return[r,o]}const dd=(t,e,n)=>t>>>n,ud=(t,e,n)=>t<<32-n|e>>>n,_n=(t,e,n)=>t>>>n|e<<32-n,On=(t,e,n)=>t<<32-n|e>>>n,To=(t,e,n)=>t<<64-n|e>>>n-32,Po=(t,e,n)=>t>>>n-32|e<<64-n;function bt(t,e,n,r){const o=(e>>>0)+(r>>>0);return{h:t+n+(o/2**32|0)|0,l:o|0}}const Wy=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Vy=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Gy=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Xy=(t,e,n,r,o)=>e+n+r+o+(t/2**32|0)|0,Yy=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Zy=(t,e,n,r,o,s)=>e+n+r+o+s+(t/2**32|0)|0,Jy=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Dt=new Uint32Array(64);class Qy extends Jf{constructor(e=32){super(64,e,8,!1),this.A=Ot[0]|0,this.B=Ot[1]|0,this.C=Ot[2]|0,this.D=Ot[3]|0,this.E=Ot[4]|0,this.F=Ot[5]|0,this.G=Ot[6]|0,this.H=Ot[7]|0}get(){const{A:e,B:n,C:r,D:o,E:s,F:i,G:a,H:c}=this;return[e,n,r,o,s,i,a,c]}set(e,n,r,o,s,i,a,c){this.A=e|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(e,n){for(let u=0;u<16;u++,n+=4)Dt[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const f=Dt[u-15],h=Dt[u-2],g=lt(f,7)^lt(f,18)^f>>>3,m=lt(h,17)^lt(h,19)^h>>>10;Dt[u]=m+Dt[u-7]+g+Dt[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=lt(a,6)^lt(a,11)^lt(a,25),h=d+f+Hy(a,c,l)+Jy[u]+Dt[u]|0,m=(lt(r,2)^lt(r,13)^lt(r,22))+qy(r,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=r,r=h+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(){cr(Dt)}destroy(){this.set(0,0,0,0,0,0,0,0),cr(this.buffer)}}const Qf=zy(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),eb=Qf[0],tb=Qf[1],Ft=new Uint32Array(80),Mt=new Uint32Array(80);class nb extends Jf{constructor(e=64){super(128,e,16,!1),this.Ah=Pe[0]|0,this.Al=Pe[1]|0,this.Bh=Pe[2]|0,this.Bl=Pe[3]|0,this.Ch=Pe[4]|0,this.Cl=Pe[5]|0,this.Dh=Pe[6]|0,this.Dl=Pe[7]|0,this.Eh=Pe[8]|0,this.El=Pe[9]|0,this.Fh=Pe[10]|0,this.Fl=Pe[11]|0,this.Gh=Pe[12]|0,this.Gl=Pe[13]|0,this.Hh=Pe[14]|0,this.Hl=Pe[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:f,Gh:h,Gl:g,Hh:m,Hl:b}=this;return[e,n,r,o,s,i,a,c,l,d,u,f,h,g,m,b]}set(e,n,r,o,s,i,a,c,l,d,u,f,h,g,m,b){this.Ah=e|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=h|0,this.Gl=g|0,this.Hh=m|0,this.Hl=b|0}process(e,n){for(let y=0;y<16;y++,n+=4)Ft[y]=e.getUint32(n),Mt[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){const k=Ft[y-15]|0,N=Mt[y-15]|0,x=_n(k,N,1)^_n(k,N,8)^dd(k,N,7),T=On(k,N,1)^On(k,N,8)^ud(k,N,7),S=Ft[y-2]|0,v=Mt[y-2]|0,A=_n(S,v,19)^To(S,v,61)^dd(S,v,6),_=On(S,v,19)^Po(S,v,61)^ud(S,v,6),B=Gy(T,_,Mt[y-7],Mt[y-16]),C=Xy(B,x,A,Ft[y-7],Ft[y-16]);Ft[y]=C|0,Mt[y]=B|0}let{Ah:r,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:f,Fh:h,Fl:g,Gh:m,Gl:b,Hh:w,Hl:R}=this;for(let y=0;y<80;y++){const k=_n(u,f,14)^_n(u,f,18)^To(u,f,41),N=On(u,f,14)^On(u,f,18)^Po(u,f,41),x=u&h^~u&m,T=f&g^~f&b,S=Yy(R,N,T,tb[y],Mt[y]),v=Zy(S,w,k,x,eb[y],Ft[y]),A=S|0,_=_n(r,o,28)^To(r,o,34)^To(r,o,39),B=On(r,o,28)^Po(r,o,34)^Po(r,o,39),C=r&s^r&a^s&a,E=o&i^o&c^i&c;w=m|0,R=b|0,m=h|0,b=g|0,h=u|0,g=f|0,{h:u,l:f}=bt(l|0,d|0,v|0,A|0),l=a|0,d=c|0,a=s|0,c=i|0,s=r|0,i=o|0;const P=Wy(A,B,E);r=Vy(P,v,_,C),o=P|0}({h:r,l:o}=bt(this.Ah|0,this.Al|0,r|0,o|0)),{h:s,l:i}=bt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=bt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=bt(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:f}=bt(this.Eh|0,this.El|0,u|0,f|0),{h,l:g}=bt(this.Fh|0,this.Fl|0,h|0,g|0),{h:m,l:b}=bt(this.Gh|0,this.Gl|0,m|0,b|0),{h:w,l:R}=bt(this.Hh|0,this.Hl|0,w|0,R|0),this.set(r,o,s,i,a,c,l,d,u,f,h,g,m,b,w,R)}roundClean(){cr(Ft,Mt)}destroy(){cr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const eh=Zf(()=>new Qy),rb=Zf(()=>new nb);const zc=BigInt(0),ja=BigInt(1);function wn(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function it(t,e,n=""){const r=So(t),o=t?.length,s=e!==void 0;if(!r||s&&o!==e){const i=n&&`"${n}" `,a=s?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function No(t){const e=t.toString(16);return e.length&1?"0"+e:e}function th(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?zc:BigInt("0x"+t)}function Zs(t){return th(un(t))}function so(t){return xn(t),th(un(Uint8Array.from(t).reverse()))}function Wc(t,e){return ps(t.toString(16).padStart(e*2,"0"))}function nh(t,e){return Wc(t,e).reverse()}function pe(t,e,n){let r;if(typeof e=="string")try{r=ps(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(So(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const o=r.length;if(typeof n=="number"&&o!==n)throw new Error(t+" of length "+n+" expected, got "+o);return r}function fd(t){return Uint8Array.from(t)}const Ri=t=>typeof t=="bigint"&&zc<=t;function ob(t,e,n){return Ri(t)&&Ri(e)&&Ri(n)&&e<=t&&t<n}function Ua(t,e,n,r){if(!ob(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function rh(t){let e;for(e=0;t>zc;t>>=ja,e+=1);return e}const xo=t=>(ja<<BigInt(t))-ja;function sb(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=h=>new Uint8Array(h),o=h=>Uint8Array.of(h);let s=r(t),i=r(t),a=0;const c=()=>{s.fill(1),i.fill(0),a=0},l=(...h)=>n(i,s,...h),d=(h=r(0))=>{i=l(o(0),h),s=l(),h.length!==0&&(i=l(o(1),h),s=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const g=[];for(;h<e;){s=l();const m=s.slice();g.push(m),h+=s.length}return ft(...g)};return(h,g)=>{c(),d(h);let m;for(;!(m=g(u()));)d();return c(),m}}function Eo(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(o,s,i){const a=t[o];if(i&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([o,s])=>r(o,s,!1)),Object.entries(n).forEach(([o,s])=>r(o,s,!0))}function gs(t){const e=new WeakMap;return(n,...r)=>{const o=e.get(n);if(o!==void 0)return o;const s=t(n,...r);return e.set(n,s),s}}const qe=BigInt(0),Re=BigInt(1),on=BigInt(2),oh=BigInt(3),sh=BigInt(4),ih=BigInt(5),ib=BigInt(7),ah=BigInt(8),ab=BigInt(9),ch=BigInt(16);function ve(t,e){const n=t%e;return n>=qe?n:e+n}function he(t,e,n){let r=t;for(;e-- >qe;)r*=r,r%=n;return r}function hd(t,e){if(t===qe)throw new Error("invert: expected non-zero number");if(e<=qe)throw new Error("invert: expected positive modulus, got "+e);let n=ve(t,e),r=e,o=qe,s=Re;for(;n!==qe;){const a=r/n,c=r%n,l=o-s*a;r=n,n=c,o=s,s=l}if(r!==Re)throw new Error("invert: does not exist");return ve(o,e)}function Vc(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function lh(t,e){const n=(t.ORDER+Re)/sh,r=t.pow(e,n);return Vc(t,r,e),r}function cb(t,e){const n=(t.ORDER-ih)/ah,r=t.mul(e,on),o=t.pow(r,n),s=t.mul(e,o),i=t.mul(t.mul(s,on),o),a=t.mul(s,t.sub(i,t.ONE));return Vc(t,a,e),a}function lb(t){const e=En(t),n=dh(t),r=n(e,e.neg(e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+ib)/ch;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),h=a.eql(a.sqr(d),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,d,h),d=a.cmov(f,u,g);const m=a.eql(a.sqr(d),c),b=a.cmov(l,d,m);return Vc(a,b,c),b}}function dh(t){if(t<oh)throw new Error("sqrt is not defined for small field");let e=t-Re,n=0;for(;e%on===qe;)e/=on,n++;let r=on;const o=En(t);for(;pd(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return lh;let s=o.pow(r,e);const i=(e+Re)/on;return function(c,l){if(c.is0(l))return l;if(pd(c,l)!==1)throw new Error("Cannot find square root");let d=n,u=c.mul(c.ONE,s),f=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let g=1,m=c.sqr(f);for(;!c.eql(m,c.ONE);)if(g++,m=c.sqr(m),g===d)throw new Error("Cannot find square root");const b=Re<<BigInt(d-g-1),w=c.pow(u,b);d=g,u=c.sqr(w),f=c.mul(f,u),h=c.mul(h,w)}return h}}function db(t){return t%sh===oh?lh:t%ah===ih?cb:t%ch===ab?lb(t):dh(t)}const ub=(t,e)=>(ve(t,e)&Re)===Re,fb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hb(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=fb.reduce((r,o)=>(r[o]="function",r),e);return Eo(t,n),t}function pb(t,e,n){if(n<qe)throw new Error("invalid exponent, negatives unsupported");if(n===qe)return t.ONE;if(n===Re)return e;let r=t.ONE,o=e;for(;n>qe;)n&Re&&(r=t.mul(r,o)),o=t.sqr(o),n>>=Re;return r}function uh(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),o=e.reduce((i,a,c)=>t.is0(a)?i:(r[c]=i,t.mul(i,a)),t.ONE),s=t.inv(o);return e.reduceRight((i,a,c)=>t.is0(a)?i:(r[c]=t.mul(i,r[c]),t.mul(i,a)),s),r}function pd(t,e){const n=(t.ORDER-Re)/on,r=t.pow(e,n),o=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),i=t.eql(r,t.neg(t.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function fh(t,e){e!==void 0&&Ma(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function En(t,e,n=!1,r={}){if(t<=qe)throw new Error("invalid field: expected ORDER > 0, got "+t);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const f=e;f.BITS&&(o=f.BITS),f.sqrt&&(s=f.sqrt),typeof f.isLE=="boolean"&&(n=f.isLE),typeof f.modFromBytes=="boolean"&&(i=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(o=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:l}=fh(t,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:l,MASK:xo(c),ZERO:qe,ONE:Re,allowedLengths:a,create:f=>ve(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return qe<=f&&f<t},is0:f=>f===qe,isValidNot0:f=>!u.is0(f)&&u.isValid(f),isOdd:f=>(f&Re)===Re,neg:f=>ve(-f,t),eql:(f,h)=>f===h,sqr:f=>ve(f*f,t),add:(f,h)=>ve(f+h,t),sub:(f,h)=>ve(f-h,t),mul:(f,h)=>ve(f*h,t),pow:(f,h)=>pb(u,f,h),div:(f,h)=>ve(f*hd(h,t),t),sqrN:f=>f*f,addN:(f,h)=>f+h,subN:(f,h)=>f-h,mulN:(f,h)=>f*h,inv:f=>hd(f,t),sqrt:s||(f=>(d||(d=db(t)),d(u,f))),toBytes:f=>n?nh(f,l):Wc(f,l),fromBytes:(f,h=!0)=>{if(a){if(!a.includes(f.length)||f.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);const m=new Uint8Array(l);m.set(f,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?so(f):Zs(f);if(i&&(g=ve(g,t)),!h&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:f=>uh(u,f),cmov:(f,h,g)=>g?h:f});return Object.freeze(u)}function hh(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function ph(t){const e=hh(t);return e+Math.ceil(e/2)}function gb(t,e,n=!1){const r=t.length,o=hh(e),s=ph(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const i=n?so(t):Zs(t),a=ve(i,e-Re)+Re;return n?nh(a,o):Wc(a,o)}const lr=BigInt(0),sn=BigInt(1);function ms(t,e){const n=e.negate();return t?n:e}function an(t,e){const n=uh(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function gh(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ti(t,e){gh(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,s=xo(t),i=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function gd(t,e,n){const{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n;let a=Number(t&o),c=t>>i;a>r&&(a-=s,c+=sn);const l=e*r,d=l+Math.abs(a)-1,u=a===0,f=a<0,h=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:f,isNegF:h,offsetF:l}}function mb(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function wb(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const Pi=new WeakMap,mh=new WeakMap;function Ni(t){return mh.get(t)||1}function md(t){if(t!==lr)throw new Error("invalid wNAF")}class wh{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>lr;)n&sn&&(r=r.add(o)),o=o.double(),n>>=sn;return r}precomputeWindow(e,n){const{windows:r,windowSize:o}=Ti(n,this.bits),s=[];let i=e,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(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE;const i=Ti(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:f,offsetF:h}=gd(r,a,i);r=c,d?s=s.add(ms(f,n[h])):o=o.add(ms(u,n[l]))}return md(r),{p:o,f:s}}wNAFUnsafe(e,n,r,o=this.ZERO){const s=Ti(e,this.bits);for(let i=0;i<s.windows&&r!==lr;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=gd(r,i,s);if(r=a,!l){const u=n[c];o=o.add(d?u.negate():u)}}return md(r),o}getPrecomputes(e,n,r){let o=Pi.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Pi.set(n,o))),o}cached(e,n,r){const o=Ni(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){const s=Ni(e);return s===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,o)}createCache(e,n){gh(n,this.bits),mh.set(e,n),Pi.delete(e)}hasCache(e){return Ni(e)!==1}}function yb(t,e,n,r){let o=e,s=t.ZERO,i=t.ZERO;for(;n>lr||r>lr;)n&sn&&(s=s.add(o)),r&sn&&(i=i.add(o)),o=o.double(),n>>=sn,r>>=sn;return{p1:s,p2:i}}function yh(t,e,n,r){mb(n,t),wb(r,e);const o=n.length,s=r.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,a=rh(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=xo(c),d=new Array(Number(l)+1).fill(i),u=Math.floor((e.BITS-1)/c)*c;let f=i;for(let h=u;h>=0;h-=c){d.fill(i);for(let m=0;m<s;m++){const b=r[m],w=Number(b>>BigInt(h)&l);d[w]=d[w].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),h!==0)for(let m=0;m<c;m++)f=f.double()}return f}function wd(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return hb(e),e}else return En(t,{isLE:n})}function bh(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>lr))throw new Error(`CURVE.${c} must be positive bigint`)}const o=wd(e.p,n.Fp,r),s=wd(e.n,n.Fn,r),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}const jt=BigInt(0),Se=BigInt(1),Li=BigInt(2),bb=BigInt(8);function vb(t,e,n,r){const o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function Sb(t,e={}){const n=bh("edwards",t,e,e.FpFnLE),{Fp:r,Fn:o}=n;let s=n.CURVE;const{h:i}=s;Eo(e,{},{uvRatio:"function"});const a=Li<<BigInt(o.BYTES*8)-Se,c=b=>r.create(b),l=e.uvRatio||((b,w)=>{try{return{isValid:!0,value:r.sqrt(r.div(b,w))}}catch{return{isValid:!1,value:jt}}});if(!vb(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(b,w,R=!1){const y=R?Se:jt;return Ua("coordinate "+b,w,y,a),w}function u(b){if(!(b instanceof g))throw new Error("ExtendedPoint expected")}const f=gs((b,w)=>{const{X:R,Y:y,Z:k}=b,N=b.is0();w==null&&(w=N?bb:r.inv(k));const x=c(R*w),T=c(y*w),S=r.mul(k,w);if(N)return{x:jt,y:Se};if(S!==Se)throw new Error("invZ was invalid");return{x,y:T}}),h=gs(b=>{const{a:w,d:R}=s;if(b.is0())throw new Error("bad point: ZERO");const{X:y,Y:k,Z:N,T:x}=b,T=c(y*y),S=c(k*k),v=c(N*N),A=c(v*v),_=c(T*w),B=c(v*c(_+S)),C=c(A+c(R*c(T*S)));if(B!==C)throw new Error("bad point: equation left != right (1)");const E=c(y*k),P=c(N*x);if(E!==P)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(w,R,y,k){this.X=d("x",w),this.Y=d("y",R),this.Z=d("z",y,!0),this.T=d("t",k),Object.freeze(this)}static CURVE(){return s}static fromAffine(w){if(w instanceof g)throw new Error("extended point not allowed");const{x:R,y}=w||{};return d("x",R),d("y",y),new g(R,y,Se,c(R*y))}static fromBytes(w,R=!1){const y=r.BYTES,{a:k,d:N}=s;w=fd(it(w,y,"point")),wn(R,"zip215");const x=fd(w),T=w[y-1];x[y-1]=T&-129;const S=so(x),v=R?a:r.ORDER;Ua("point.y",S,jt,v);const A=c(S*S),_=c(A-Se),B=c(N*A-k);let{isValid:C,value:E}=l(_,B);if(!C)throw new Error("bad point: invalid y coordinate");const P=(E&Se)===Se,I=(T&128)!==0;if(!R&&E===jt&&I)throw new Error("bad point: x=0 and x_0=1");return I!==P&&(E=c(-E)),g.fromAffine({x:E,y:S})}static fromHex(w,R=!1){return g.fromBytes(pe("point",w),R)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,R=!0){return m.createCache(this,w),R||this.multiply(Li),this}assertValidity(){h(this)}equals(w){u(w);const{X:R,Y:y,Z:k}=this,{X:N,Y:x,Z:T}=w,S=c(R*T),v=c(N*k),A=c(y*T),_=c(x*k);return S===v&&A===_}is0(){return this.equals(g.ZERO)}negate(){return new g(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:w}=s,{X:R,Y:y,Z:k}=this,N=c(R*R),x=c(y*y),T=c(Li*c(k*k)),S=c(w*N),v=R+y,A=c(c(v*v)-N-x),_=S+x,B=_-T,C=S-x,E=c(A*B),P=c(_*C),I=c(A*C),D=c(B*_);return new g(E,P,D,I)}add(w){u(w);const{a:R,d:y}=s,{X:k,Y:N,Z:x,T}=this,{X:S,Y:v,Z:A,T:_}=w,B=c(k*S),C=c(N*v),E=c(T*y*_),P=c(x*A),I=c((k+N)*(S+v)-B-C),D=P-E,M=P+E,F=c(C-R*B),L=c(I*D),$=c(M*F),H=c(I*F),U=c(D*M);return new g(L,$,U,H)}subtract(w){return this.add(w.negate())}multiply(w){if(!o.isValidNot0(w))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:R,f:y}=m.cached(this,w,k=>an(g,k));return an(g,[R,y])[0]}multiplyUnsafe(w,R=g.ZERO){if(!o.isValid(w))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return w===jt?g.ZERO:this.is0()||w===Se?this:m.unsafe(this,w,y=>an(g,y),R)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(w){return f(this,w)}clearCofactor(){return i===Se?this:this.multiplyUnsafe(i)}toBytes(){const{x:w,y:R}=this.toAffine(),y=r.toBytes(R);return y[y.length-1]|=w&Se?128:0,y}toHex(){return un(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(w){return an(g,w)}static msm(w,R){return yh(g,o,w,R)}_setWindowSize(w){this.precompute(w)}toRawBytes(){return this.toBytes()}}g.BASE=new g(s.Gx,s.Gy,Se,c(s.Gx*s.Gy)),g.ZERO=new g(jt,Se,Se,jt),g.Fp=r,g.Fn=o;const m=new wh(g,o.BITS);return g.BASE.precompute(8),g}function xb(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is required');Eo(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:o,Fp:s,Fn:i}=t,a=n.randomBytes||Kc,c=n.adjustScalarBytes||(v=>v),l=n.domain||((v,A,_)=>{if(wn(_,"phflag"),A.length||_)throw new Error("Contexts/pre-hash are not supported");return v});function d(v){return i.create(so(v))}function u(v){const A=y.secretKey;v=pe("private key",v,A);const _=pe("hashed private key",e(v),2*A),B=c(_.slice(0,A)),C=_.slice(A,2*A),E=d(B);return{head:B,prefix:C,scalar:E}}function f(v){const{head:A,prefix:_,scalar:B}=u(v),C=o.multiply(B),E=C.toBytes();return{head:A,prefix:_,scalar:B,point:C,pointBytes:E}}function h(v){return f(v).pointBytes}function g(v=Uint8Array.of(),...A){const _=ft(...A);return d(e(l(_,pe("context",v),!!r)))}function m(v,A,_={}){v=pe("message",v),r&&(v=r(v));const{prefix:B,scalar:C,pointBytes:E}=f(A),P=g(_.context,B,v),I=o.multiply(P).toBytes(),D=g(_.context,I,E,v),M=i.create(P+D*C);if(!i.isValid(M))throw new Error("sign failed: invalid s");const F=ft(I,i.toBytes(M));return it(F,y.signature,"result")}const b={zip215:!0};function w(v,A,_,B=b){const{context:C,zip215:E}=B,P=y.signature;v=pe("signature",v,P),A=pe("message",A),_=pe("publicKey",_,y.publicKey),E!==void 0&&wn(E,"zip215"),r&&(A=r(A));const I=P/2,D=v.subarray(0,I),M=so(v.subarray(I,P));let F,L,$;try{F=t.fromBytes(_,E),L=t.fromBytes(D,E),$=o.multiplyUnsafe(M)}catch{return!1}if(!E&&F.isSmallOrder())return!1;const H=g(C,L.toBytes(),F.toBytes(),A);return L.add(F.multiplyUnsafe(H)).subtract($).clearCofactor().is0()}const R=s.BYTES,y={secretKey:R,publicKey:R,signature:2*R,seed:R};function k(v=a(y.seed)){return it(v,y.seed,"seed")}function N(v){const A=S.randomSecretKey(v);return{secretKey:A,publicKey:h(A)}}function x(v){return So(v)&&v.length===i.BYTES}function T(v,A){try{return!!t.fromBytes(v,A)}catch{return!1}}const S={getExtendedPublicKey:f,randomSecretKey:k,isValidSecretKey:x,isValidPublicKey:T,toMontgomery(v){const{y:A}=t.fromBytes(v),_=y.publicKey,B=_===32;if(!B&&_!==57)throw new Error("only defined for 25519 and 448");const C=B?s.div(Se+A,Se-A):s.div(A-Se,A+Se);return s.toBytes(C)},toMontgomerySecret(v){const A=y.secretKey;it(v,A);const _=e(v.subarray(0,A));return c(_).subarray(0,A)},randomPrivateKey:k,precompute(v=8,A=t.BASE){return A.precompute(v,!1)}};return Object.freeze({keygen:N,getPublicKey:h,sign:m,verify:w,utils:S,Point:t,lengths:y})}function Eb(t){const e={a:t.a,d:t.d,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp,r=En(e.n,t.nBitLength,!0),o={Fp:n,Fn:r,uvRatio:t.uvRatio},s={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:o,hash:t.hash,eddsaOpts:s}}function Ab(t,e){const n=e.Point;return Object.assign({},e,{ExtendedPoint:n,CURVE:t,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function kb(t){const{CURVE:e,curveOpts:n,hash:r,eddsaOpts:o}=Eb(t),s=Sb(e,n),i=xb(s,r,o);return Ab(t,i)}const Cb=BigInt(1),yd=BigInt(2);BigInt(3);const Ib=BigInt(5),Rb=BigInt(8),Gc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),vh={p:Gc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Rb,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Tb(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=Gc,a=t*t%s*t%s,c=he(a,yd,s)*a%s,l=he(c,Cb,s)*t%s,d=he(l,Ib,s)*l%s,u=he(d,e,s)*d%s,f=he(u,n,s)*u%s,h=he(f,r,s)*f%s,g=he(h,o,s)*h%s,m=he(g,o,s)*h%s,b=he(m,e,s)*d%s;return{pow_p_5_8:he(b,yd,s)*t%s,b2:a}}function Pb(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const bd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Nb(t,e){const n=Gc,r=ve(e*e*e,n),o=ve(r*r*e,n),s=Tb(t*o).pow_p_5_8;let i=ve(t*r*s,n);const a=ve(e*i*i,n),c=i,l=ve(i*bd,n),d=a===t,u=a===ve(-t,n),f=a===ve(-t*bd,n);return d&&(i=c),(u||f)&&(i=l),ub(i,n)&&(i=ve(-i,n)),{isValid:d||u,value:i}}const Lb=En(vh.p,{isLE:!0}),Bb={...vh,Fp:Lb,hash:rb,adjustScalarBytes:Pb,uvRatio:Nb},ws=kb(Bb);class vd extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}}class Sd extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class _b extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}const Nt={get(t=globalThis){const e=t.crypto;if(e?.subtle==null)throw new _b("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}},ys=32,St=64,$a=32;let Yn;const Sh=(async()=>{try{return await Nt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Ob(){const t=ws.utils.randomPrivateKey(),e=ws.getPublicKey(t);return{privateKey:Hb(t,e),publicKey:e}}async function Db(t,e){let n;t.length===St?n=t.subarray(0,32):n=t;const r={crv:"Ed25519",kty:"OKP",x:te(t.subarray(32),"base64url"),d:te(n,"base64url"),ext:!0,key_ops:["sign"]},o=await Nt.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),s=await Nt.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function Fb(t,e){const n=t.subarray(0,$a);return ws.sign(e instanceof Uint8Array?e:e.subarray(),n)}async function Mb(t,e){return Yn==null&&(Yn=await Sh),Yn?Db(t,e):Fb(t,e)}async function jb(t,e,n){if(t.buffer instanceof ArrayBuffer){const r=await Nt.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await Nt.get().subtle.verify({name:"Ed25519"},r,e,n instanceof Uint8Array?n:n.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Ub(t,e,n){return ws.verify(e,n instanceof Uint8Array?n:n.subarray(),t)}async function $b(t,e,n){return Yn==null&&(Yn=await Sh),Yn?jb(t,e,n):Ub(t,e,n)}function Hb(t,e){const n=new Uint8Array(St);for(let r=0;r<$a;r++)n[r]=t[r],n[$a+r]=e[r];return n}function Js(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}class xh{type="Ed25519";raw;constructor(e){this.raw=io(e,ys)}toMultihash(){return bo.digest(ni(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return Fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ct(this.raw,e.raw)}verify(e,n,r){r?.signal?.throwIfAborted();const o=$b(this.raw,n,e);return Js(o)?o.then(s=>(r?.signal?.throwIfAborted(),s)):o}}class Ha{type="Ed25519";raw;publicKey;constructor(e,n){this.raw=io(e,St),this.publicKey=new xh(n)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ct(this.raw,e.raw)}sign(e,n){n?.signal?.throwIfAborted();const r=Mb(this.raw,e);return Js(r)?r.then(o=>(n?.signal?.throwIfAborted(),o)):(n?.signal?.throwIfAborted(),r)}}function qb(t){if(t.length>St){t=io(t,St+ys);const r=t.subarray(0,St),o=t.subarray(St,t.length);return new Ha(r,o)}t=io(t,St);const e=t.subarray(0,St),n=t.subarray(ys);return new Ha(e,n)}function Eh(t){return t=io(t,ys),new xh(t)}async function Kb(){const{privateKey:t,publicKey:e}=Ob();return new Ha(t,e)}function io(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new at(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}const zb=Math.pow(2,7),Wb=Math.pow(2,14),Vb=Math.pow(2,21),Xc=Math.pow(2,28),Yc=Math.pow(2,35),Zc=Math.pow(2,42),Jc=Math.pow(2,49),oe=128,Ne=127;function An(t){if(t<zb)return 1;if(t<Wb)return 2;if(t<Vb)return 3;if(t<Xc)return 4;if(t<Yc)return 5;if(t<Zc)return 6;if(t<Jc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ah(t,e,n=0){switch(An(t)){case 8:e[n++]=t&255|oe,t/=128;case 7:e[n++]=t&255|oe,t/=128;case 6:e[n++]=t&255|oe,t/=128;case 5:e[n++]=t&255|oe,t/=128;case 4:e[n++]=t&255|oe,t>>>=7;case 3:e[n++]=t&255|oe,t>>>=7;case 2:e[n++]=t&255|oe,t>>>=7;case 1:{e[n++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Gb(t,e,n=0){switch(An(t)){case 8:e.set(n++,t&255|oe),t/=128;case 7:e.set(n++,t&255|oe),t/=128;case 6:e.set(n++,t&255|oe),t/=128;case 5:e.set(n++,t&255|oe),t/=128;case 4:e.set(n++,t&255|oe),t>>>=7;case 3:e.set(n++,t&255|oe),t>>>=7;case 2:e.set(n++,t&255|oe),t>>>=7;case 1:{e.set(n++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function kh(t,e){let n=t[e],r=0;if(r+=n&Ne,n<oe||(n=t[e+1],r+=(n&Ne)<<7,n<oe)||(n=t[e+2],r+=(n&Ne)<<14,n<oe)||(n=t[e+3],r+=(n&Ne)<<21,n<oe)||(n=t[e+4],r+=(n&Ne)*Xc,n<oe)||(n=t[e+5],r+=(n&Ne)*Yc,n<oe)||(n=t[e+6],r+=(n&Ne)*Zc,n<oe)||(n=t[e+7],r+=(n&Ne)*Jc,n<oe))return r;throw new RangeError("Could not decode varint")}function Xb(t,e){let n=t.get(e),r=0;if(r+=n&Ne,n<oe||(n=t.get(e+1),r+=(n&Ne)<<7,n<oe)||(n=t.get(e+2),r+=(n&Ne)<<14,n<oe)||(n=t.get(e+3),r+=(n&Ne)<<21,n<oe)||(n=t.get(e+4),r+=(n&Ne)*Xc,n<oe)||(n=t.get(e+5),r+=(n&Ne)*Yc,n<oe)||(n=t.get(e+6),r+=(n&Ne)*Zc,n<oe)||(n=t.get(e+7),r+=(n&Ne)*Jc,n<oe))return r;throw new RangeError("Could not decode varint")}function Yb(t,e,n=0){return e==null&&(e=Pt(An(t))),e instanceof Uint8Array?Ah(t,e,n):Gb(t,e,n)}function Ch(t,e=0){return t instanceof Uint8Array?kh(t,e):Xb(t,e)}const Qc=new Float32Array([-0]),Gt=new Uint8Array(Qc.buffer);function Zb(t,e,n){Qc[0]=t,e[n]=Gt[0],e[n+1]=Gt[1],e[n+2]=Gt[2],e[n+3]=Gt[3]}function Jb(t,e){return Gt[0]=t[e],Gt[1]=t[e+1],Gt[2]=t[e+2],Gt[3]=t[e+3],Qc[0]}const el=new Float64Array([-0]),Le=new Uint8Array(el.buffer);function Qb(t,e,n){el[0]=t,e[n]=Le[0],e[n+1]=Le[1],e[n+2]=Le[2],e[n+3]=Le[3],e[n+4]=Le[4],e[n+5]=Le[5],e[n+6]=Le[6],e[n+7]=Le[7]}function e0(t,e){return Le[0]=t[e],Le[1]=t[e+1],Le[2]=t[e+2],Le[3]=t[e+3],Le[4]=t[e+4],Le[5]=t[e+5],Le[6]=t[e+6],Le[7]=t[e+7],el[0]}const t0=BigInt(Number.MAX_SAFE_INTEGER),n0=BigInt(Number.MIN_SAFE_INTEGER);class Be{lo;hi;constructor(e,n){this.lo=e|0,this.hi=n|0}toNumber(e=!1){if(!e&&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(e=!1){if(e)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(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,n=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?n===0?e<16384?e<128?1:2:e<2097152?3:4:n<16384?n<128?5:6:n<2097152?7:8:r<128?9:10}static fromBigInt(e){if(e===0n)return fn;if(e<t0&&e>n0)return this.fromNumber(Number(e));const n=e<0n;n&&(e=-e);let r=e>>32n,o=e-(r<<32n);return n&&(r=~r|0n,o=~o|0n,++o>xd&&(o=0n,++r>xd&&(r=0n))),new Be(Number(o),Number(r))}static fromNumber(e){if(e===0)return fn;const n=e<0;n&&(e=-e);let r=e>>>0,o=(e-r)/4294967296>>>0;return n&&(o=~o>>>0,r=~r>>>0,++r>4294967295&&(r=0,++o>4294967295&&(o=0))),new Be(r,o)}static from(e){return typeof e=="number"?Be.fromNumber(e):typeof e=="bigint"?Be.fromBigInt(e):typeof e=="string"?Be.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new Be(e.low>>>0,e.high>>>0):fn}}const fn=new Be(0,0);fn.toBigInt=function(){return 0n};fn.zzEncode=fn.zzDecode=function(){return this};fn.length=function(){return 1};const xd=4294967296n;function r0(t){let e=0,n=0;for(let r=0;r<t.length;++r)n=t.charCodeAt(r),n<128?e+=1:n<2048?e+=2:(n&64512)===55296&&(t.charCodeAt(r+1)&64512)===56320?(++r,e+=4):e+=3;return e}function o0(t,e,n){if(n-e<1)return"";let o;const s=[];let i=0,a;for(;e<n;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Ih(t,e,n){const r=n;let o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[n++]=o:o<2048?(e[n++]=o>>6|192,e[n++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[n++]=o>>18|240,e[n++]=o>>12&63|128,e[n++]=o>>6&63|128,e[n++]=o&63|128):(e[n++]=o>>12|224,e[n++]=o>>6&63|128,e[n++]=o&63|128);return n-r}function rt(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function Lo(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}class s0{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,rt(this,10);return e}int32(){return this.uint32()|0}sint32(){const e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw rt(this,4);return Lo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw rt(this,4);return Lo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw rt(this,4);const e=Jb(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw rt(this,4);const e=e0(this.buf,this.pos);return this.pos+=8,e}bytes(){const e=this.uint32(),n=this.pos,r=this.pos+e;if(r>this.len)throw rt(this,e);return this.pos+=e,n===r?new Uint8Array(0):this.buf.subarray(n,r)}string(){const e=this.bytes();return o0(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw rt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw rt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new Be(0,0);let n=0;if(this.len-this.pos>4){for(;n<4;++n)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<n*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;n=0}else{for(;n<3;++n){if(this.pos>=this.len)throw rt(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<n*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<n*7)>>>0,e}if(this.len-this.pos>4){for(;n<5;++n)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<n*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;n<5;++n){if(this.pos>=this.len)throw rt(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<n*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw rt(this,8);const e=Lo(this.buf,this.pos+=4),n=Lo(this.buf,this.pos+=4);return new Be(e,n)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=kh(this.buf,this.pos);return this.pos+=An(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function i0(t){return new s0(t instanceof Uint8Array?t:t.subarray())}function Qs(t,e,n){const r=i0(t);return e.decode(r,void 0,n)}function a0(t){let r,o=8192;return function(i){if(i<1||i>4096)return Pt(i);o+i>8192&&(r=Pt(8192),o=0);const a=r.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}class Kr{fn;len;next;val;constructor(e,n,r){this.fn=e,this.len=n,this.next=void 0,this.val=r}}function Bi(){}class c0{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const l0=a0();function d0(t){return globalThis.Buffer!=null?Pt(t):l0(t)}class qa{len;head;tail;states;constructor(){this.len=0,this.head=new Kr(Bi,0,0),this.tail=this.head,this.states=null}_push(e,n,r){return this.tail=this.tail.next=new Kr(e,n,r),this.len+=n,this}uint32(e){return this.len+=(this.tail=this.tail.next=new f0((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Bo,10,Be.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const n=Be.fromBigInt(e);return this._push(Bo,n.length(),n)}uint64Number(e){return this._push(Ah,An(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const n=Be.fromBigInt(e).zzEncode();return this._push(Bo,n.length(),n)}sint64Number(e){const n=Be.fromNumber(e).zzEncode();return this._push(Bo,n.length(),n)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(_i,1,e?1:0)}fixed32(e){return this._push(Tr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const n=Be.fromBigInt(e);return this._push(Tr,4,n.lo)._push(Tr,4,n.hi)}fixed64Number(e){const n=Be.fromNumber(e);return this._push(Tr,4,n.lo)._push(Tr,4,n.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Zb,4,e)}double(e){return this._push(Qb,8,e)}bytes(e){const n=e.length>>>0;return n===0?this._push(_i,1,0):this.uint32(n)._push(h0,n,e)}string(e){const n=r0(e);return n!==0?this.uint32(n)._push(Ih,n,e):this._push(_i,1,0)}fork(){return this.states=new c0(this),this.head=this.tail=new Kr(Bi,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 Kr(Bi,0,0),this.len=0),this}ldelim(){const e=this.head,n=this.tail,r=this.len;return this.reset().uint32(r),r!==0&&(this.tail.next=e.next,this.tail=n,this.len+=r),this}finish(){let e=this.head.next;const n=d0(this.len);let r=0;for(;e!=null;)e.fn(e.val,n,r),r+=e.len,e=e.next;return n}}function _i(t,e,n){e[n]=t&255}function u0(t,e,n){for(;t>127;)e[n++]=t&127|128,t>>>=7;e[n]=t}class f0 extends Kr{next;constructor(e,n){super(u0,e,n),this.next=void 0}}function Bo(t,e,n){for(;t.hi!==0;)e[n++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[n++]=t.lo&127|128,t.lo=t.lo>>>7;e[n++]=t.lo}function Tr(t,e,n){e[n]=t&255,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}function h0(t,e,n){e.set(t,n)}globalThis.Buffer!=null&&(qa.prototype.bytes=function(t){const e=t.length>>>0;return this.uint32(e),e>0&&this._push(p0,e,t),this},qa.prototype.string=function(t){const e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(g0,e,t),this});function p0(t,e,n){e.set(t,n)}function g0(t,e,n){t.length<40?Ih(t,e,n):e.utf8Write!=null?e.utf8Write(t,n):e.set(be(t),n)}function m0(){return new qa}function ei(t,e){const n=m0();return e.encode(t,n,{lengthDelimited:!1}),n.finish()}var bs;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(bs||(bs={}));function Rh(t,e,n,r){return{name:t,type:e,encode:n,decode:r}}function w0(t){function e(o){if(t[o.toString()]==null)throw new Error("Invalid enum value");return t[o]}const n=function(s,i){const a=e(s);i.int32(a)},r=function(s){const i=s.int32();return e(i)};return Rh("enum",bs.VARINT,n,r)}function ti(t,e){return Rh("message",bs.LENGTH_DELIMITED,t,e)}class Ed extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var fe;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(fe||(fe={}));var Ka;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(Ka||(Ka={}));(function(t){t.codec=()=>w0(Ka)})(fe||(fe={}));var yn;(function(t){let e;t.codec=()=>(e==null&&(e=ti((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),fe.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=fe.codec().decode(n);break}case 2:{s.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>ei(n,t.codec()),t.decode=(n,r)=>Qs(n,t.codec(),r)})(yn||(yn={}));var vs;(function(t){let e;t.codec=()=>(e==null&&(e=ti((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),fe.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=fe.codec().decode(n);break}case 2:{s.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>ei(n,t.codec()),t.decode=(n,r)=>Qs(n,t.codec(),r)})(vs||(vs={}));const Th=eh;class Ph{type="RSA";jwk;_raw;_multihash;constructor(e,n){this.jwk=e,this._multihash=n}get raw(){return this._raw==null&&(this._raw=Lh(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ue.createV1(114,this._multihash)}toString(){return Fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ct(this.raw,e.raw)}verify(e,n,r){return L0(this.jwk,n,e,r)}}class y0{type="RSA";jwk;_raw;publicKey;constructor(e,n){this.jwk=e,this.publicKey=n}get raw(){return this._raw==null&&(this._raw=E0(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ct(this.raw,e.raw)}sign(e,n){return N0(this.jwk,e,n)}}const b0=8192,Nh=18,v0=1062,S0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function x0(t){return{n:te(t[1],"base64url"),e:te(t[2],"base64url"),d:te(t[3],"base64url"),p:te(t[4],"base64url"),q:te(t[5],"base64url"),dp:te(t[6],"base64url"),dq:te(t[7],"base64url"),qi:te(t[8],"base64url"),kty:"RSA"}}function E0(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new at("JWK was missing components");return Rt([ze(Uint8Array.from([0])),ze(be(t.n,"base64url")),ze(be(t.e,"base64url")),ze(be(t.d,"base64url")),ze(be(t.p,"base64url")),ze(be(t.q,"base64url")),ze(be(t.dp,"base64url")),ze(be(t.dq,"base64url")),ze(be(t.qi,"base64url"))]).subarray()}function A0(t){const e=wr(t[1],{offset:0});return{kty:"RSA",n:te(e[0],"base64url"),e:te(e[1],"base64url")}}function Lh(t){if(t.n==null||t.e==null)throw new at("JWK was missing components");return Rt([S0,Hc(Rt([ze(be(t.n,"base64url")),ze(be(t.e,"base64url"))]))]).subarray()}function k0(t){const e=wr(t);return C0(e)}function C0(t){const e=x0(t);return T0(e)}function I0(t,e){if(t.byteLength>=v0)throw new Nf("Key size is too large");const n=wr(t,{offset:0});return R0(n,t,e)}function R0(t,e,n){const r=A0(t);if(n==null){const o=Th(yn.encode({Type:fe.RSA,Data:e}));n=yo(Nh,o)}return new Ph(r,n)}function T0(t){if(B0(t)>b0)throw new at("Key size is too large");const e=P0(t),n=Th(yn.encode({Type:fe.RSA,Data:Lh(e.publicKey)})),r=yo(Nh,n);return new y0(e.privateKey,new Ph(e.publicKey,r))}function P0(t){if(t==null)throw new at("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function N0(t,e,n){const r=await Nt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);n?.signal?.throwIfAborted();const o=await Nt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function L0(t,e,n,r){const o=await Nt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const s=await Nt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,n instanceof Uint8Array?n:n.subarray());return r?.signal?.throwIfAborted(),s}function B0(t){if(t.kty!=="RSA")throw new at("invalid key type");if(t.n==null)throw new at("invalid key modulus");return be(t.n,"base64url").length*8}class Bh extends Yf{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,Gf(e);const r=qc(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const o=this.blockLen,s=new Uint8Array(o);s.set(r.length>o?e.create().update(r).digest():r);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),cr(s)}update(e){return hs(this),this.iHash.update(e),this}digestInto(e){hs(this),xn(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const _h=(t,e,n)=>new Bh(t,e).update(n).digest();_h.create=(t,e)=>new Bh(t,e);const Ad=(t,e)=>(t+(t>=0?e:-e)/Oh)/e;function _0(t,e,n){const[[r,o],[s,i]]=e,a=Ad(i*t,n),c=Ad(-o*t,n);let l=t-a*r-c*s,d=-a*o-c*i;const u=l<kt,f=d<kt;u&&(l=-l),f&&(d=-d);const h=xo(Math.ceil(rh(n)/2))+Zn;if(l<kt||l>=h||d<kt||d>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:f,k2:d}}function za(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Oi(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return wn(n.lowS,"lowS"),wn(n.prehash,"prehash"),n.format!==void 0&&za(n.format),n}class O0 extends Error{constructor(e=""){super(e)}}const xt={Err:O0,_tlv:{encode:(t,e)=>{const{Err:n}=xt;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,o=No(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?No(o.length/2|128):"";return No(t)+s+o+e},decode(t,e){const{Err:n}=xt;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const o=e[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=e.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=e.subarray(r,r+i);if(a.length!==i)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+i)}}},_int:{encode(t){const{Err:e}=xt;if(t<kt)throw new e("integer: negative integers are not allowed");let n=No(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=xt;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Zs(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=xt,o=pe("signature",t),{v:s,l:i}=r.decode(48,o);if(i.length)throw new e("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 e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){const{_tlv:e,_int:n}=xt,r=e.encode(2,n.encode(t.r)),o=e.encode(2,n.encode(t.s)),s=r+o;return e.encode(48,s)}},kt=BigInt(0),Zn=BigInt(1),Oh=BigInt(2),_o=BigInt(3),D0=BigInt(4);function qn(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let o=pe("private key",e);try{r=t.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function F0(t,e={}){const n=bh("weierstrass",t,e),{Fp:r,Fn:o}=n;let s=n.CURVE;const{h:i,n:a}=s;Eo(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;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=Fh(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(B,C,E){const{x:P,y:I}=C.toAffine(),D=r.toBytes(P);if(wn(E,"isCompressed"),E){d();const M=!r.isOdd(I);return ft(Dh(M),D)}else return ft(Uint8Array.of(4),D,r.toBytes(I))}function f(B){it(B,void 0,"Point");const{publicKey:C,publicKeyUncompressed:E}=l,P=B.length,I=B[0],D=B.subarray(1);if(P===C&&(I===2||I===3)){const M=r.fromBytes(D);if(!r.isValid(M))throw new Error("bad point: is not on curve, wrong x");const F=m(M);let L;try{L=r.sqrt(F)}catch(U){const q=U instanceof Error?": "+U.message:"";throw new Error("bad point: is not on curve, sqrt error"+q)}d();const $=r.isOdd(L);return(I&1)===1!==$&&(L=r.neg(L)),{x:M,y:L}}else if(P===E&&I===4){const M=r.BYTES,F=r.fromBytes(D.subarray(0,M)),L=r.fromBytes(D.subarray(M,M*2));if(!b(F,L))throw new Error("bad point: is not on curve");return{x:F,y:L}}else throw new Error(`bad point: got length ${P}, expected compressed=${C} or uncompressed=${E}`)}const h=e.toBytes||u,g=e.fromBytes||f;function m(B){const C=r.sqr(B),E=r.mul(C,B);return r.add(r.add(E,r.mul(B,s.a)),s.b)}function b(B,C){const E=r.sqr(C),P=m(B);return r.eql(E,P)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const w=r.mul(r.pow(s.a,_o),D0),R=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(w,R)))throw new Error("bad curve params: a or b");function y(B,C,E=!1){if(!r.isValid(C)||E&&r.is0(C))throw new Error(`bad point coordinate ${B}`);return C}function k(B){if(!(B instanceof v))throw new Error("ProjectivePoint expected")}function N(B){if(!c||!c.basises)throw new Error("no endo");return _0(B,c.basises,o.ORDER)}const x=gs((B,C)=>{const{X:E,Y:P,Z:I}=B;if(r.eql(I,r.ONE))return{x:E,y:P};const D=B.is0();C==null&&(C=D?r.ONE:r.inv(I));const M=r.mul(E,C),F=r.mul(P,C),L=r.mul(I,C);if(D)return{x:r.ZERO,y:r.ZERO};if(!r.eql(L,r.ONE))throw new Error("invZ was invalid");return{x:M,y:F}}),T=gs(B=>{if(B.is0()){if(e.allowInfinityPoint&&!r.is0(B.Y))return;throw new Error("bad point: ZERO")}const{x:C,y:E}=B.toAffine();if(!r.isValid(C)||!r.isValid(E))throw new Error("bad point: x or y not field elements");if(!b(C,E))throw new Error("bad point: equation left != right");if(!B.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(B,C,E,P,I){return E=new v(r.mul(E.X,B),E.Y,E.Z),C=ms(P,C),E=ms(I,E),C.add(E)}class v{constructor(C,E,P){this.X=y("x",C),this.Y=y("y",E,!0),this.Z=y("z",P),Object.freeze(this)}static CURVE(){return s}static fromAffine(C){const{x:E,y:P}=C||{};if(!C||!r.isValid(E)||!r.isValid(P))throw new Error("invalid affine point");if(C instanceof v)throw new Error("projective point not allowed");return r.is0(E)&&r.is0(P)?v.ZERO:new v(E,P,r.ONE)}static fromBytes(C){const E=v.fromAffine(g(it(C,void 0,"point")));return E.assertValidity(),E}static fromHex(C){return v.fromBytes(pe("pointHex",C))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(C=8,E=!0){return _.createCache(this,C),E||this.multiply(_o),this}assertValidity(){T(this)}hasEvenY(){const{y:C}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(C)}equals(C){k(C);const{X:E,Y:P,Z:I}=this,{X:D,Y:M,Z:F}=C,L=r.eql(r.mul(E,F),r.mul(D,I)),$=r.eql(r.mul(P,F),r.mul(M,I));return L&&$}negate(){return new v(this.X,r.neg(this.Y),this.Z)}double(){const{a:C,b:E}=s,P=r.mul(E,_o),{X:I,Y:D,Z:M}=this;let F=r.ZERO,L=r.ZERO,$=r.ZERO,H=r.mul(I,I),U=r.mul(D,D),q=r.mul(M,M),K=r.mul(I,D);return K=r.add(K,K),$=r.mul(I,M),$=r.add($,$),F=r.mul(C,$),L=r.mul(P,q),L=r.add(F,L),F=r.sub(U,L),L=r.add(U,L),L=r.mul(F,L),F=r.mul(K,F),$=r.mul(P,$),q=r.mul(C,q),K=r.sub(H,q),K=r.mul(C,K),K=r.add(K,$),$=r.add(H,H),H=r.add($,H),H=r.add(H,q),H=r.mul(H,K),L=r.add(L,H),q=r.mul(D,M),q=r.add(q,q),H=r.mul(q,K),F=r.sub(F,H),$=r.mul(q,U),$=r.add($,$),$=r.add($,$),new v(F,L,$)}add(C){k(C);const{X:E,Y:P,Z:I}=this,{X:D,Y:M,Z:F}=C;let L=r.ZERO,$=r.ZERO,H=r.ZERO;const U=s.a,q=r.mul(s.b,_o);let K=r.mul(E,D),X=r.mul(P,M),z=r.mul(I,F),W=r.add(E,P),V=r.add(D,M);W=r.mul(W,V),V=r.add(K,X),W=r.sub(W,V),V=r.add(E,I);let Y=r.add(D,F);return V=r.mul(V,Y),Y=r.add(K,z),V=r.sub(V,Y),Y=r.add(P,I),L=r.add(M,F),Y=r.mul(Y,L),L=r.add(X,z),Y=r.sub(Y,L),H=r.mul(U,V),L=r.mul(q,z),H=r.add(L,H),L=r.sub(X,H),H=r.add(X,H),$=r.mul(L,H),X=r.add(K,K),X=r.add(X,K),z=r.mul(U,z),V=r.mul(q,V),X=r.add(X,z),z=r.sub(K,z),z=r.mul(U,z),V=r.add(V,z),K=r.mul(X,V),$=r.add($,K),K=r.mul(Y,V),L=r.mul(W,L),L=r.sub(L,K),K=r.mul(W,X),H=r.mul(Y,H),H=r.add(H,K),new v(L,$,H)}subtract(C){return this.add(C.negate())}is0(){return this.equals(v.ZERO)}multiply(C){const{endo:E}=e;if(!o.isValidNot0(C))throw new Error("invalid scalar: out of range");let P,I;const D=M=>_.cached(this,M,F=>an(v,F));if(E){const{k1neg:M,k1:F,k2neg:L,k2:$}=N(C),{p:H,f:U}=D(F),{p:q,f:K}=D($);I=U.add(K),P=S(E.beta,H,q,M,L)}else{const{p:M,f:F}=D(C);P=M,I=F}return an(v,[P,I])[0]}multiplyUnsafe(C){const{endo:E}=e,P=this;if(!o.isValid(C))throw new Error("invalid scalar: out of range");if(C===kt||P.is0())return v.ZERO;if(C===Zn)return P;if(_.hasCache(this))return this.multiply(C);if(E){const{k1neg:I,k1:D,k2neg:M,k2:F}=N(C),{p1:L,p2:$}=yb(v,P,D,F);return S(E.beta,L,$,I,M)}else return _.unsafe(P,C)}multiplyAndAddUnsafe(C,E,P){const I=this.multiplyUnsafe(E).add(C.multiplyUnsafe(P));return I.is0()?void 0:I}toAffine(C){return x(this,C)}isTorsionFree(){const{isTorsionFree:C}=e;return i===Zn?!0:C?C(v,this):_.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:C}=e;return i===Zn?this:C?C(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(C=!0){return wn(C,"isCompressed"),this.assertValidity(),h(v,this,C)}toHex(C=!0){return un(this.toBytes(C))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(C=!0){return this.toBytes(C)}_setWindowSize(C){this.precompute(C)}static normalizeZ(C){return an(v,C)}static msm(C,E){return yh(v,o,C,E)}static fromPrivateKey(C){return v.BASE.multiply(qn(o,C))}}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 A=o.BITS,_=new wh(v,e.endo?Math.ceil(A/2):A);return v.BASE.precompute(8),v}function Dh(t){return Uint8Array.of(t?2:3)}function Fh(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function M0(t,e={}){const{Fn:n}=t,r=e.randomBytes||Kc,o=Object.assign(Fh(t.Fp,n),{seed:ph(n.ORDER)});function s(h){try{return!!qn(n,h)}catch{return!1}}function i(h,g){const{publicKey:m,publicKeyUncompressed:b}=o;try{const w=h.length;return g===!0&&w!==m||g===!1&&w!==b?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=r(o.seed)){return gb(it(h,o.seed,"seed"),n.ORDER)}function c(h,g=!0){return t.BASE.multiply(qn(n,h)).toBytes(g)}function l(h){const g=a(h);return{secretKey:g,publicKey:c(g)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:g,publicKey:m,publicKeyUncompressed:b}=o;if(n.allowedLengths||g===m)return;const w=pe("key",h).length;return w===m||w===b}function u(h,g,m=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(g)===!1)throw new Error("second arg must be public key");const b=qn(n,h);return t.fromHex(g).multiply(b).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>qn(n,h),precompute(h=8,g=t.BASE){return g.precompute(h,!1)}},lengths:o})}function j0(t,e,n={}){Gf(e),Eo(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Kc,o=n.hmac||((E,...P)=>_h(e,E,ft(...P))),{Fp:s,Fn:i}=t,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h}=M0(t,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function b(E){const P=a>>Zn;return E>P}function w(E,P){if(!i.isValidNot0(P))throw new Error(`invalid signature ${E}: out of range 1..Point.Fn.ORDER`);return P}function R(E,P){za(P);const I=h.signature,D=P==="compact"?I:P==="recovered"?I+1:void 0;return it(E,D,`${P} signature`)}class y{constructor(P,I,D){this.r=w("r",P),this.s=w("s",I),D!=null&&(this.recovery=D),Object.freeze(this)}static fromBytes(P,I=m){R(P,I);let D;if(I==="der"){const{r:$,s:H}=xt.toSig(it(P));return new y($,H)}I==="recovered"&&(D=P[0],I="compact",P=P.subarray(1));const M=i.BYTES,F=P.subarray(0,M),L=P.subarray(M,M*2);return new y(i.fromBytes(F),i.fromBytes(L),D)}static fromHex(P,I){return this.fromBytes(ps(P),I)}addRecoveryBit(P){return new y(this.r,this.s,P)}recoverPublicKey(P){const I=s.ORDER,{r:D,s:M,recovery:F}=this;if(F==null||![0,1,2,3].includes(F))throw new Error("recovery id invalid");if(a*Oh<I&&F>1)throw new Error("recovery id is ambiguous for h>1 curve");const $=F===2||F===3?D+a:D;if(!s.isValid($))throw new Error("recovery id 2 or 3 invalid");const H=s.toBytes($),U=t.fromBytes(ft(Dh((F&1)===0),H)),q=i.inv($),K=N(pe("msgHash",P)),X=i.create(-K*q),z=i.create(M*q),W=t.BASE.multiplyUnsafe(X).add(U.multiplyUnsafe(z));if(W.is0())throw new Error("point at infinify");return W.assertValidity(),W}hasHighS(){return b(this.s)}toBytes(P=m){if(za(P),P==="der")return ps(xt.hexFromSig(this));const I=i.toBytes(this.r),D=i.toBytes(this.s);if(P==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return ft(Uint8Array.of(this.recovery),I,D)}return ft(I,D)}toHex(P){return un(this.toBytes(P))}assertValidity(){}static fromCompact(P){return y.fromBytes(pe("sig",P),"compact")}static fromDER(P){return y.fromBytes(pe("sig",P),"der")}normalizeS(){return this.hasHighS()?new y(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return un(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return un(this.toBytes("compact"))}}const k=n.bits2int||function(P){if(P.length>8192)throw new Error("input is too large");const I=Zs(P),D=P.length*8-c;return D>0?I>>BigInt(D):I},N=n.bits2int_modN||function(P){return i.create(k(P))},x=xo(c);function T(E){return Ua("num < 2^"+c,E,kt,x),i.toBytes(E)}function S(E,P){return it(E,void 0,"message"),P?it(e(E),void 0,"prehashed message"):E}function v(E,P,I){if(["recovered","canonical"].some(X=>X in I))throw new Error("sign() legacy options not supported");const{lowS:D,prehash:M,extraEntropy:F}=Oi(I,g);E=S(E,M);const L=N(E),$=qn(i,P),H=[T($),T(L)];if(F!=null&&F!==!1){const X=F===!0?r(h.secretKey):F;H.push(pe("extraEntropy",X))}const U=ft(...H),q=L;function K(X){const z=k(X);if(!i.isValidNot0(z))return;const W=i.inv(z),V=t.BASE.multiply(z).toAffine(),Y=i.create(V.x);if(Y===kt)return;const Q=i.create(W*i.create(q+Y*$));if(Q===kt)return;let ae=(V.x===Y?0:2)|Number(V.y&Zn),ce=Q;return D&&b(Q)&&(ce=i.neg(Q),ae^=1),new y(Y,ce,ae)}return{seed:U,k2sig:K}}function A(E,P,I={}){E=pe("message",E);const{seed:D,k2sig:M}=v(E,P,I);return sb(e.outputLen,i.BYTES,o)(D,M)}function _(E){let P;const I=typeof E=="string"||So(E),D=!I&&E!==null&&typeof E=="object"&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!I&&!D)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(D)P=new y(E.r,E.s);else if(I){try{P=y.fromBytes(pe("sig",E),"der")}catch(M){if(!(M instanceof xt.Err))throw M}if(!P)try{P=y.fromBytes(pe("sig",E),"compact")}catch{return!1}}return P||!1}function B(E,P,I,D={}){const{lowS:M,prehash:F,format:L}=Oi(D,g);if(I=pe("publicKey",I),P=S(pe("message",P),F),"strict"in D)throw new Error("options.strict was renamed to lowS");const $=L===void 0?_(E):y.fromBytes(pe("sig",E),L);if($===!1)return!1;try{const H=t.fromBytes(I);if(M&&$.hasHighS())return!1;const{r:U,s:q}=$,K=N(P),X=i.inv(q),z=i.create(K*X),W=i.create(U*X),V=t.BASE.multiplyUnsafe(z).add(H.multiplyUnsafe(W));return V.is0()?!1:i.create(V.x)===U}catch{return!1}}function C(E,P,I={}){const{prehash:D}=Oi(I,g);return P=S(P,D),y.fromBytes(E,"recovered").recoverPublicKey(P).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h,Point:t,sign:A,verify:B,recoverPublicKey:C,Signature:y,hash:e})}function U0(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp;let r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0;const o=En(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),s={Fp:n,Fn:o,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function $0(t){const{CURVE:e,curveOpts:n}=U0(t),r={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,hash:t.hash,ecdsaOpts:r}}function H0(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,fh(n.Fn.ORDER,n.Fn.BITS))})}function q0(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:o}=$0(t),s=F0(e,n),i=j0(s,r,o);return H0(t,i)}function K0(t,e){const n=r=>q0({...t,hash:r});return{...n(e),create:n}}const tl={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},z0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},kd=BigInt(2);function W0(t){const e=tl.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,u=he(d,n,e)*d%e,f=he(u,n,e)*d%e,h=he(f,kd,e)*l%e,g=he(h,o,e)*h%e,m=he(g,s,e)*g%e,b=he(m,a,e)*m%e,w=he(b,c,e)*b%e,R=he(w,a,e)*m%e,y=he(R,n,e)*d%e,k=he(y,i,e)*g%e,N=he(k,r,e)*l%e,x=he(N,kd,e);if(!Wa.eql(Wa.sqr(x),t))throw new Error("Cannot find square root");return x}const Wa=En(tl.p,{sqrt:W0}),Yt=K0({...tl,Fp:Wa,lowS:!0,endo:z0},eh);function V0(t,e,n){const r=$c.digest(e instanceof Uint8Array?e:e.subarray());if(Js(r))return r.then(({digest:o})=>(n?.signal?.throwIfAborted(),Yt.sign(o,t).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new vd(String(o))});try{return Yt.sign(r.digest,t).toDERRawBytes()}catch(o){throw new vd(String(o))}}function G0(t,e,n,r){const o=$c.digest(n instanceof Uint8Array?n:n.subarray());if(Js(o))return o.then(({digest:s})=>(r?.signal?.throwIfAborted(),Yt.verify(e,s,t))).catch(s=>{throw s.name==="AbortError"?s:new Sd(String(s))});try{return r?.signal?.throwIfAborted(),Yt.verify(e,o.digest,t)}catch(s){throw new Sd(String(s))}}class Mh{type="secp256k1";raw;_key;constructor(e){this._key=Q0(e),this.raw=Z0(this._key)}toMultihash(){return bo.digest(ni(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return Fe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ct(this.raw,e.raw)}verify(e,n,r){return G0(this._key,n,e,r)}}class X0{type="secp256k1";raw;publicKey;constructor(e,n){this.raw=J0(e),this.publicKey=new Mh(n??ev(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ct(this.raw,e.raw)}sign(e,n){return V0(this.raw,e,n)}}function Y0(t){return new X0(t)}function jh(t){return new Mh(t)}function Z0(t){return Yt.ProjectivePoint.fromHex(t).toRawBytes(!0)}function J0(t){try{return Yt.getPublicKey(t,!0),t}catch(e){throw new Lf(String(e))}}function Q0(t){try{return Yt.ProjectivePoint.fromHex(t),t}catch(e){throw new Nf(String(e))}}function ev(t){try{return Yt.getPublicKey(t,!0)}catch(e){throw new Lf(String(e))}}async function tv(t,e){return Kb()}function Va(t,e){const{Type:n,Data:r}=yn.decode(t),o=r??new Uint8Array;switch(n){case fe.RSA:return I0(o,e);case fe.Ed25519:return Eh(o);case fe.secp256k1:return jh(o);case fe.ECDSA:return Wf(o);default:throw new Vs}}function nv(t){const{Type:e,Data:n}=yn.decode(t.digest),r=n??new Uint8Array;switch(e){case fe.Ed25519:return Eh(r);case fe.secp256k1:return jh(r);case fe.ECDSA:return Wf(r);default:throw new Vs}}function ni(t){return yn.encode({Type:fe[t.type],Data:t.raw})}function rv(t){const e=vs.decode(t),n=e.Data??new Uint8Array;switch(e.Type){case fe.RSA:return k0(n);case fe.Ed25519:return qb(n);case fe.secp256k1:return Y0(n);case fe.ECDSA:return By(n);default:throw new Vs}}function ov(t){return vs.encode({Type:fe[t.type],Data:t.raw})}const Uh=Symbol.for("nodejs.util.inspect.custom"),sv=114;class nl{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Bf]=!0;toString(){return this.string==null&&(this.string=Fe.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ue.createV1(sv,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ct(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ct(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Uh](){return`PeerId(${this.toString()})`}}class $h extends nl{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class Hh extends nl{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class qh extends nl{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}const iv=2336;class Kh{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=bo.digest(be(this.url))}[Uh](){return`PeerId(${this.url})`}[Bf]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ue.createV1(iv,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=te(e)),e.toString()===this.toString())}}const av=114,Cd=2336;function cv(t,e){let n;if(t.charAt(0)==="1"||t.charAt(0)==="Q")n=Df(Fe.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return lv(ue.parse(t));throw new at('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return zh(n)}function dr(t){if(t.type==="Ed25519")return new Hh({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new qh({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new $h({multihash:t.toCID().multihash,publicKey:t});throw new Vs}function zh(t){if(uv(t))return new $h({multihash:t});if(dv(t))try{const e=nv(t);if(e.type==="Ed25519")return new Hh({multihash:t,publicKey:e});if(e.type==="secp256k1")return new qh({multihash:t,publicKey:e})}catch{const n=te(t.digest);return new Kh(new URL(n))}throw new zm("Supplied PeerID Multihash is invalid")}function lv(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==av&&t.code!==Cd)throw new Km("Supplied PeerID CID is invalid");if(t.code===Cd){const e=te(t.multihash.digest);return new Kh(new URL(e))}return zh(t.multihash)}function dv(t){return t.code===bo.code}function uv(t){return t.code===$c.code}class Wh extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class fv extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class Pr extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class Id extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}}class hv extends Event{data;constructor(e,n){super("message",n),this.data=e}}class rl extends Event{error;local;constructor(e,n,r){super("close",r),this.error=n,this.local=e}}class pv extends rl{constructor(e,n){super(!0,e,n)}}class gv extends rl{constructor(e,n){super(!1,e,n)}}const mv=t=>t/2**32|0,wv=t=>t>>>0;function yv(t,e,n,r){const o=mv(n),s=wv(n);t.setUint32(e,r?s:o,r),t.setUint32(e+4,r?o:s,r)}function Ga(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const Xa=t=>t?`"${t}" `:"";function Lt(t,e=""){if(typeof t!="number")throw new TypeError(Xa(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(Xa(e)+"expected integer >= 0, got "+t);return t}function Bt(t,e,n=""){if(Ga(t)&&(e===void 0||t.length===e))return t;e!==void 0&&Lt(e,"length");const r=Ga(t),o=e!==void 0?` of length ${e}`:"",s=r?`length=${t.length}`:`type=${typeof t}`,i=Xa(n)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}function ol(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Lt(t.outputLen),Lt(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}const bv=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)},Rd=(t,e)=>{bv(t,e);const n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function Ss(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function Vh(t,e){Bt(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function nR(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function hn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Di(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function dt(t,e){return t<<32-e|t>>>e}function rR(t,e){return t<<e|t>>>32-e>>>0}const vv=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Sv(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function xv(t){for(let e=0;e<t.length;e++)t[e]=Sv(t[e]);return t}const oR=vv?t=>t:xv,Gh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ev=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function sl(t){if(Bt(t),Gh)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Ev[t[n]];return e}function Td(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function Xh(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Gh)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}const e=t.length,n=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){const i=Td(t.charCodeAt(s)),a=Td(t.charCodeAt(s+1));if(i===void 0||a===void 0){const c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a}return r}function Av(t){const e=globalThis;if(typeof e.scheduler?.yield=="function"){const n=e.scheduler.yield();return t&&n.catch(t),n}return new Promise(n=>e.setTimeout(n,0))}async function sR(t,e,n,r){if(Lt(t,"iters"),Lt(e,"tick"),typeof n!="function")throw new TypeError("callback must be a function");let o=Date.now();for(let s=0;s<t;s++){n(s);const i=Date.now()-o;i>=0&&i<e||(await Av(r),o=Date.now())}}function kv(t){if(typeof t!="string")throw new TypeError("string expected");const e=new TextEncoder().encode(t);try{return new Uint8Array(e)}finally{hn(e)}}function iR(t,e=""){return typeof t=="string"?kv(t):Bt(t,void 0,e)}function Cv(t,e,n="opts"){return Rd(t,"defaults"),e!==void 0&&Rd(e,n),Object.assign(Object.create(null),t,e)}function Iv(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=Cv({},e,"info");const n=(o,s)=>t(s).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function Rv(t=32){Lt(t,"bytesLength");const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}const Tv=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Pv(t,e,n){return t&e^~t&n}function Nv(t,e,n){return t&e^t&n^e&n}class Lv{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,n,r,o){this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Di(this.buffer)}update(e){Ss(this),Bt(e);const{view:n,buffer:r,blockLen:o}=this,s=e.length;let i=!1;for(let a=0;a<s;){const c=Math.min(o-this.pos,s-a);if(c===o){const l=Di(e);for(;o<=s-a;a+=o)this.process(l,a);i=!0;continue}r.set(a===0&&c===s?e:e.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+=e.length,i&&this.roundClean(),this}digestInto(e){Ss(this),Vh(e,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)),yv(r,o-8,this.length*8,s),this.process(r,0),this.roundClean();const a=e===n?r:Di(e),c=this.outputLen,l=c/4,d=this.get();if(c%4||l>d.length)throw new Error("invalid outputLen");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneIntoMeta(e){const{buffer:n,length:r,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=r,e.pos=i,i&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Bv=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),_v=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]),Ut=new Uint32Array(64);class Ov extends Lv{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,n){super(64,e,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:e,B:n,C:r,D:o,E:s,F:i,G:a,H:c}=this;return[e,n,r,o,s,i,a,c]}set(e,n,r,o,s,i,a,c){this.A=e|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(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,n){for(let u=0;u<16;u++,n+=4)Ut[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const f=Ut[u-15],h=Ut[u-2],g=dt(f,7)^dt(f,18)^f>>>3,m=dt(h,17)^dt(h,19)^h>>>10;Ut[u]=m+Ut[u-7]+g+Ut[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=dt(a,6)^dt(a,11)^dt(a,25),h=d+f+Pv(a,c,l)+_v[u]+Ut[u]|0,m=(dt(r,2)^dt(r,13)^dt(r,22))+Nv(r,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=r,r=h+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(){hn(Ut)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),hn(this.buffer)}}class Dv extends Ov{constructor(){super(32,Bv)}}const Fi=Iv(()=>new Dv,Tv(1));function Yh(t,e,n=()=>{}){if(!Array.isArray(t))throw new TypeError(`"${e}" expected array, got type=${typeof t}`);for(let r=0;r<t.length;r++)n(t[r],`${e}[${r}]`);return t}const Jn=(t,e,n)=>Bt(t,e,n),Zh=Lt;function Qn(t,e="object"){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`);return t}function Zr(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}const Fv=sl,Mv=t=>Xh(t),Jh=Ga,Qh=t=>Rv(t),xs=BigInt(0),Pd=BigInt(1),jv=t=>t?`"${t}" `:"";function ri(t,e=""){if(typeof t!="boolean")throw new TypeError(jv(e)+"expected boolean, got type="+typeof t);return t}function Uv(t){if(typeof t=="bigint"){if(!pn(t))throw new RangeError("positive bigint expected, got "+t)}else Zh(t);return t}function Ya(t,e=""){if(typeof t!="number"){const n=e&&`"${e}" `;throw new TypeError(n+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){const n=e&&`"${e}" `;throw new RangeError(n+"expected safe integer, got "+t)}}function ep(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?xs:BigInt("0x"+t)}function tp(t){return ep(sl(t))}function Es(t){return ep(sl(ao(Bt(t)).reverse()))}function np(t,e){if(Lt(e),e===0)throw new Error("zero output length is invalid");t=Uv(t);const n=e*2,r=t.toString(16);if(r.length>n)throw new RangeError("number is too large");return Xh(r.padStart(n,"0"))}function rp(t,e){return np(t,e).reverse()}function ao(t){return Uint8Array.from(Jn(t))}function pn(t){return typeof t=="bigint"&&xs<=t}function op(t,e,n){return pn(t)&&pn(e)&&pn(n)&&e<=t&&t<n}function Jr(t,e,n,r){if(!op(e,n,r))throw new RangeError("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function $v(t){if(t<xs)throw new Error("expected non-negative bigint, got "+t);return t===xs?0:t.toString(2).length}const Hv=t=>(Ya(t,"n"),(Pd<<BigInt(t))-Pd);function As(t,e={},n={},r="object"){Qn(t,r),Qn(e,"fields"),Qn(n,"optFields");function o(i,a,c){const l=r==="object"?`param "${String(i)}"`:`"${r}.${String(i)}"`,d=t[i];if(!Object.hasOwn(t,i)&&(c?d!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&d===void 0)return;const u=typeof d;if(u!==a||d===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${u}`)}const s=(i,a)=>Object.entries(i).forEach(([c,l])=>o(c,l,a));s(e,!1),s(n,!0)}const Ee=BigInt(0),de=BigInt(1),cn=BigInt(2),sp=BigInt(3),il=BigInt(4),ip=BigInt(5),qv=BigInt(7),ap=BigInt(8),Kv=BigInt(9),zv=BigInt(15),cp=BigInt(16),Wv=BigInt("0x10000000000000000");function le(t,e){if(e<=Ee)throw new Error("mod: expected positive modulus, got "+e);const n=t%e;return n>=Ee?n:e+n}function Vv(t,e,n){if(n<=de)throw new Error("pow: expected modulus > 1, got "+n);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<Ee)throw new Error("invalid exponent, negatives unsupported");if(e===Ee)return de;if(e===de)return t;let r=t%n;if(r<Ee&&(r+=n),e<Wv){let a=de;for(;e>Ee;)e&de&&(a=a*r%n),r=r*r%n,e>>=de;return a}const o=[];for(;e>Ee;)o.push(Number(e&zv)),e>>=il;const s=new Array(16);s[0]=de,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 ot(t,e,n){if(n<=de)throw new Error("pow2: expected modulus > 1, got "+n);if(e<Ee)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >Ee;)r*=r,r%=n;return r}function Nd(t,e){if(t===Ee)throw new Error("invert: expected non-zero number");if(e<=de)throw new Error("invert: expected modulus > 1, got "+e);let n=le(t,e),r=e,o=Ee,s=de;for(;n!==Ee;){const a=r/n,c=r-n*a,l=o-s*a;r=n,n=c,o=s,s=l}if(r!==de)throw new Error("invert: does not exist");return le(o,e)}function al(t,e,n){const r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function cl(t,e){if((t&de)===Ee)throw new Error(e+": expected odd modulus, got "+t)}function lp(t,e){const n=t,r=(n.ORDER+de)/il,o=n.pow(e,r);return al(n,o,e),o}function Gv(t,e){const n=t,r=(n.ORDER-ip)/ap,o=n.mul(e,cn),s=n.pow(o,r),i=n.mul(e,s),a=n.mul(n.mul(i,cn),s),c=n.mul(i,n.sub(a,n.ONE));return al(n,c,e),c}function Xv(t){const e=ll(t),n=dp(t),r=n(e,e.neg(e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+qv)/cp;return((a,c)=>{const l=a;let d=l.pow(c,i),u=l.mul(d,r);const f=l.mul(d,o),h=l.mul(d,s),g=l.eql(l.sqr(u),c),m=l.eql(l.sqr(f),c);d=l.cmov(d,u,g),u=l.cmov(h,f,m);const b=l.eql(l.sqr(u),c),w=l.cmov(d,u,b);return al(l,w,c),w})}function dp(t){if(t<sp)throw new Error("sqrt is not defined for small field");cl(t,"tonelliShanks");let e=t-de,n=0;for(;e%cn===Ee;)e/=cn,n++;let r=cn;const o=ll(t);for(;ks(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return lp;let s=o.pow(r,e);const i=(e+de)/cn;return function(c,l){const d=c;if(d.is0(l))return l;if(ks(d,l)!==1)throw new Error("Cannot find square root");let u=n,f=d.mul(d.ONE,s),h=d.pow(l,e),g=d.pow(l,i);for(;!d.eql(h,d.ONE);){if(d.is0(h))throw new Error("Cannot find square root: probably non-prime P");let m=1,b=d.sqr(h);for(;!d.eql(b,d.ONE);)if(m++,b=d.sqr(b),m===u)throw new Error("Cannot find square root");const w=de<<BigInt(u-m-1),R=d.pow(f,w);u=m,f=d.sqr(R),h=d.mul(h,f),g=d.mul(g,R)}return g}}function Yv(t){return cl(t,"Fp.sqrt"),t%il===sp?lp:t%ap===ip?Gv:t%cp===Kv?Xv(t):dp(t)}const Zv=(t,e)=>(le(t,e)&de)===de,Jv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function co(t){if(Qn(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);Ya(t.BYTES,"BYTES"),Ya(t.BITS,"BITS");for(const e of Jv)Zr(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=de)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function up(t,e,n=!1){co(t),Yh(e,"nums"),ri(n,"passZero");const r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),s=e.reduce((a,c,l)=>r.is0(c)?a:(o[l]=a,r.mul(a,c)),r.ONE),i=r.inv(s);return e.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),i),o}function ks(t,e){co(t);const n=t;cl(n.ORDER,"FpLegendre");const r=(n.ORDER-de)/cn,o=n.pow(e,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 Qv(t,e){if(e!==void 0&&Zh(e),t<=Ee)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);const n=$v(t);if(e!==void 0&&e<n)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${n})`);const r=e!==void 0?e:n,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}const Ld=new WeakMap;class Bd{ORDER;BITS;BYTES;isLE;ZERO=Ee;ONE=de;_lengths;_mod;constructor(e,n={}){if(e<=de)throw new Error("invalid field: expected ORDER > 1, got "+e);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}=Qv(e,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return le(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Ee<=e&&e<this.ORDER}is0(e){return e===Ee}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&de)===de}neg(e){return le(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return le(e*e,this.ORDER)}add(e,n){return le(e+n,this.ORDER)}sub(e,n){return le(e-n,this.ORDER)}mul(e,n){return le(e*n,this.ORDER)}pow(e,n){return Vv(e,n,this.ORDER)}div(e,n){return le(e*Nd(n,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return Nd(e,this.ORDER)}sqrt(e){let n=Ld.get(this);return n||Ld.set(this,n=Yv(this.ORDER)),n(this,e)}toBytes(e){return this.isLE?rp(e,this.BYTES):np(e,this.BYTES)}fromBytes(e,n=!1){Jn(e);const{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);const l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?Es(e):tp(e);if(a&&(c=le(c,i)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return up(this,e,!0)}cmov(e,n,r){return ri(r,"condition"),r?n:e}}function ll(t,e={}){return Object.freeze(Bd.prototype),new Bd(t,e)}const dl=BigInt(0),lo=BigInt(1),eS=BigInt(4),Mi=16,_d=128,tS=5,Od=2**31;function ul(t){const e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);Zr(e.fromAffine,"Point.fromAffine"),Zr(e.fromBytes,"Point.fromBytes"),Zr(e.fromHex,"Point.fromHex"),Qn(e.BASE,"Point.BASE"),Qn(e.ZERO,"Point.ZERO"),co(e.Fp),co(e.Fn)}function nS(t,e){ul(t),fp(e,t);const n=up(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function rS(t,e,n=1){if(!Number.isSafeInteger(t)||t<n||t>e)throw new Error("invalid window size, expected ["+n+".."+e+"], got W="+t)}function oS(t,e){const n=t*(4*e+128);if(n>Od)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+Od/2**20+" MiB")}function sS(t,e){if(t!==void 0){Zr(t,"randomBytes");try{const n=t(e);if(!Jh(n)||n.length!==e)return}catch{return}return t}}function fp(t,e){Yh(t,"points"),t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function iS(t,e,n){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,o)=>{if(!(n===void 0?e.isValid(r):pn(r)&&r<n))throw new Error("invalid scalar at index "+o)})}const hp=new WeakMap;function ji(t){return hp.get(t)||1}function aS(t,e){const n=t.double(),r=[t];for(let o=1;o<e;o++)r.push(r[o-1].add(n));return r}function cS(t,e){const n=2**e,r=n/2,o=BigInt(n-1),s=[];for(;t>dl;){let i=0;t&lo&&(i=Number(t&o),i>=r&&(i-=n),t-=BigInt(i)),s.push(i),t>>=lo}return s}function lS(t,e,n){const r=2**e,o=r/2,s=BigInt(r-1),i=BigInt(e),a=[];for(let c=0;c<n;c++){let l=Number(t&s);t>>=i,l>o&&(l-=r,t+=lo),a.push(l)}if(t!==dl)throw new Error("invalid wnaf");return a}function dS(t,e,n){let r=0;for(const s of n)r=Math.max(r,s.length);let o=t;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=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}class uS{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,n){ul(e),this.randomBytes=sS(n,Mi),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,n,r){const o=Math.ceil(r/n)+1,s=2**(n-1),i=[];let a=e;for(let c=0;c<o;c++){let l=a;for(let d=0;d<s;d++)i.push(l),l=l.add(a);a=i[i.length-1].double()}return{W:n,bits:r,windows:o,comp:i}}wnafCachedCT(e,n){const{W:r,windows:o,comp:s}=e,i=2**(r-1),a=lS(n,r,o);let c=this.ZERO,l=this.BASE;for(let d=0;d<o;d++){const u=a[d],f=d*i,h=Math.abs(u)-1;let g=s[f];for(let b=1;b<i;b++)g=b===h?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(e,n,r,o){let s=this.wnafPrecomputes.get(n),i=s?.find(a=>a.W===e&&a.bits===r);return i||(i=this.buildWnafTable(n,e,r),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(n,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,n){if(this.assertPoint(e),!op(n,lo,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,n,r,o){const s=ji(e);return s===1?this.fixedWindowCT(e,n,r):this.wnafCachedCT(this.getWnafPrecomputes(s,e,r,o),n)}mulCT(e,n,r){return this.validateMulInput(e,n),this.runCT(e,n,this.bits,r)}mulCTBlinded(e,n,r){if(this.validateMulInput(e,n),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");const o=this.Point.Fn.BITS+_d,s=this.randomBytes(Mi);if(!Jh(s)||s.length!==Mi)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;const i=n+tp(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,r)}fixedWindowCT(e,n,r){const o=tS,s=1<<o,i=Hv(o),a=new Array(s);a[0]=this.ZERO;for(let d=1;d<s;d++)a[d]=a[d-1].add(e);const c=Math.ceil(r/o);let l=this.ZERO;for(let d=c-1;d>=0;d--){if(d!==c-1)for(let h=0;h<o;h++)l=l.double();const u=Number(n>>BigInt(d*o)&i);let f=a[0];for(let h=1;h<s;h++)f=h===u?a[h]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(e,n){return this.randomBytes===void 0?!1:n===lo?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,n,r,o){return this.shouldBlind(e,r)?this.mulCTBlinded(e,n,o):this.mulCT(e,n,o)}mulUnsafe(e,n,r){if(this.assertPoint(e),!pn(n))throw new Error("invalid scalar");const o=ji(e);if(o===1||n>=this.Point.Fn.ORDER)return fS(this.Point,[e],[n],!0);const s=this.getWnafPrecomputes(o,e,this.bits,r);return this.wnafCachedCT(s,n).p}setWindowSize(e,n){this.assertPoint(e),rS(n,this.bits);const r=Math.ceil((this.bits+_d)/n)+1;oS(r*2**(n-1),this.Point.Fp.BYTES),hp.set(e,n),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return ji(e)!==1}}function fS(t,e,n,r=!1){if(ul(t),fp(e,t),ri(r,"allowOversized"),iS(n,t.Fn,r?t.Fn.ORDER**eS:void 0),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const o=e.map(i=>aS(i,4)),s=n.map(i=>cS(i,4));return dS(t.ZERO,o,s)}function Dd(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return co(e),e}else return ll(t,{isLE:n})}function hS(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);As(n);for(const c of["p","n","h"]){const l=e[c];if(!(pn(l)&&l!==dl))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Dd(e.p,n.Fp,r),s=Dd(e.n,n.Fn,r),a=["Gx","Gy","a","d"];for(const c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function pS(t,e){return function(r){const o=t(r);return{secretKey:o,publicKey:e(o)}}}const Oo=BigInt(0),Do=BigInt(1),Fo=BigInt(2),gS=BigInt(4),Fd=BigInt(8);function mS(t,e,n,r){const o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function wS(t,e={}){As(e,{},{},"extraOpts");const n=e,r=hS("edwards",t,n,n.FpFnLE),{Fp:o,Fn:s}=r;let i=r.CURVE;const{h:a}=i;if(ks(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(ks(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");As(n,{},{uvRatio:"function",randomBytes:"function"});const c=n.randomBytes===void 0?Qh:n.randomBytes,l=Fo<<BigInt(o.BYTES*8)-Do;function d(R){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(R)}const u=n.uvRatio===void 0?(R,y)=>{try{return{isValid:!0,value:o.sqrt(o.div(R,y))}}catch{return{isValid:!1,value:Oo}}}:n.uvRatio;if(!mS(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");const f=o.eql(i.a,o.neg(o.ONE))?R=>o.neg(R):o.eql(i.a,o.ONE)?R=>R:R=>o.mul(i.a,R);function h(R,y,k=!1){const N=k?Do:Oo;return Jr("coordinate "+R,y,N,l),y}function g(R){if(!(R 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(y,k,N,x){this.X=h("x",y),this.Y=h("y",k),this.Z=h("z",N,!0),this.T=h("t",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(y){if(y instanceof m)throw new Error("extended point not allowed");const{x:k,y:N}=y||{};return h("x",k),h("y",N),new m(k,N,o.ONE,o.mul(k,N))}static fromBytes(y,k=!1){const N=o.BYTES,{a:x,d:T}=i;y=ao(Jn(y,N,"point")),ri(k,"zip215");const S=ao(y),v=y[N-1];S[N-1]=v&-129;const A=Es(S),_=k?l:o.ORDER;Jr("point.y",A,Oo,_);const B=o.sqr(A),C=o.sub(B,o.ONE),E=o.sub(o.mulN(T,B),x);let{isValid:P,value:I}=u(C,E);if(!P)throw new Error("bad point: invalid y coordinate");const D=d(I),M=(v&128)!==0;if(!k&&o.is0(I)&&M)throw new Error("bad point: x=0 and x_0=1");return M!==D&&(I=o.neg(I)),m.fromAffine({x:I,y:A})}static fromHex(y,k=!1){return m.fromBytes(Mv(y),k)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=6,k=!0){return w.setWindowSize(this,y),k||this.multiply(Fo),this}assertValidity(){const y=this,{a:k,d:N}=i;if(y.is0())throw new Error("bad point: ZERO");const{X:x,Y:T,Z:S,T:v}=y,A=o.sqr(x),_=o.sqr(T),B=o.sqr(S),C=o.sqr(B),E=o.mul(A,k),P=o.mul(o.add(E,_),B),I=o.add(C,o.mul(N,o.mul(A,_)));if(!o.eql(P,I))throw new Error("bad point: equation left != right (1)");const D=o.mul(x,T),M=o.mul(S,v);if(!o.eql(D,M))throw new Error("bad point: equation left != right (2)")}equals(y){g(y);const{X:k,Y:N,Z:x}=this,{X:T,Y:S,Z:v}=y,A=o.mul(k,v),_=o.mul(T,x),B=o.mul(N,v),C=o.mul(S,x);return o.eql(A,_)&&o.eql(B,C)}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:y,Y:k,Z:N}=this,x=o.sqr(y),T=o.sqr(k),S=o.mul(o.sqr(N),Fo),v=f(x),A=o.addN(y,k),_=o.sub(o.subN(o.sqr(A),x),T),B=o.addN(v,T),C=o.subN(B,S),E=o.subN(v,T),P=o.mul(_,C),I=o.mul(B,E),D=o.mul(_,E),M=o.mul(C,B);return new m(P,I,M,D)}add(y){g(y);const{d:k}=i,{X:N,Y:x,Z:T,T:S}=this,{X:v,Y:A,Z:_,T:B}=y,C=o.mul(N,v),E=o.mul(x,A),P=o.mul(o.mulN(S,k),B),I=o.mul(T,_),D=o.sub(o.subN(o.mulN(o.addN(N,x),o.addN(v,A)),C),E),M=o.subN(I,P),F=o.addN(I,P),L=o.sub(E,f(C)),$=o.mul(D,M),H=o.mul(F,L),U=o.mul(D,L),q=o.mul(M,F);return new m($,H,q,U)}subtract(y){return g(y),this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");const{p:k,f:N}=w.mulSecret(this,y,a,b);return b([k,N])[0]}multiplyUnsafe(y){if(!s.isValid(y))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return y===Oo?m.ZERO:this.is0()||y===Do?this:w.mulUnsafe(this,y,b)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.mulUnsafe(this,i.n).is0()}toAffine(y){const k=this;let N=y;if(N!=null&&typeof N!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof N);const{X:x,Y:T,Z:S}=k,v=k.is0();N==null&&(N=v?o.create(Fd):o.inv(S));const A=o.mul(x,N),_=o.mul(T,N),B=o.mul(S,N);if(v)return{x:o.ZERO,y:o.ONE};if(!o.eql(B,o.ONE))throw new Error("invZ was invalid");return{x:A,y:_}}clearCofactor(){return a===Do?this:a===Fo?this.double():a===gS?this.double().double():a===Fd?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){const{x:y,y:k}=this.toAffine(),N=o.toBytes(k);return N[N.length-1]|=d(y)?128:0,N}toHex(){return Fv(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const b=R=>nS(m,R),w=new uS(m,c);return w.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}const tn=BigInt(0),Ze=BigInt(1),Mo=BigInt(2);function Md(t,e){return t+e-(e>>Ze<<Ze)}function yS(t){const e=BigInt(6)*t;return(n,r,o)=>{const s=r+o,a=((e+o-r)*n+r)%t;return{x_2:a,x_3:s-a}}}function bS(t){return As(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...t})}function vS(t){const e=bS(t),{P:n,type:r,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=e.scalarMultBase,c=r==="x25519";if(!c&&r!=="x448")throw new Error("invalid type");const l=i===void 0?Qh:i,d=c?255:448,u=yS(n),f=c?32:56,h=BigInt(c?9:5),g=BigInt(c?121665:39081),m=c?Mo**BigInt(254):Mo**BigInt(447),b=c?BigInt(8)*(Mo**BigInt(251)-Ze):BigInt(4)*(Mo**BigInt(445)-Ze),w=m+b+Ze,R=I=>le(I,n),y=k(h);function k(I){return rp(R(I),f)}function N(I){const D=ao(Jn(I,f,"uCoordinate"));return c&&(D[31]&=127),R(Es(D))}function x(I){return Es(o(ao(Jn(I,f,"scalar"))))}const T=new Set(c?[tn,Ze,n-Ze,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[tn,Ze,n-Ze]);function S(I,D){const M=N(D);if(T.has(M))throw new Error("invalid private or public key received");const F=B(M,x(I));if(F===tn)throw new Error("invalid private or public key received");return k(F)}function v(I){if(a===void 0)return S(I,y);const D=x(I);Jr("scalar",D,m,w);const M=R(a(D));if(M===tn)throw new Error("invalid private or public key received");return k(M)}const A=v,_=S;function B(I,D){Jr("u",I,tn,n),Jr("scalar",D,m,w);const M=D,F=I;let L=Ze,$=tn,H=I,U=Ze;const q=M^M>>Ze;for(let z=BigInt(d-1);z>=tn;z--){const W=Md(n,q>>z);({x_2:L,x_3:H}=u(W,L,H)),{x_2:$,x_3:U}=u(W,$,U);const V=L+$,Y=R(V*V),Q=L-$,ae=R(Q*Q),ce=Y-ae,ie=H+U,$e=H-U,ke=R($e*V),Ge=R(ie*Q),en=ke+Ge,Oe=ke-Ge;H=R(en*en),U=R(F*R(Oe*Oe)),L=R(Y*ae),$=R(ce*(Y+R(g*ce)))}const K=Md(n,M);({x_2:L,x_3:H}=u(K,L,H)),{x_2:$,x_3:U}=u(K,$,U);const X=s($);return R(L*X)}const C={secretKey:f,publicKey:f,seed:f},E=I=>(I=I===void 0?l(f):I,Jn(I,C.seed,"seed"),I),P={randomSecretKey:E};return Object.freeze(C),Object.freeze(P),Object.freeze({keygen:pS(E,A),getSharedSecret:_,getPublicKey:A,scalarMult:S,scalarMultBase:v,utils:P,GuBytes:y.slice(),lengths:C})}const jd=BigInt(0),SS=BigInt(1),Ud=BigInt(2),xS=BigInt(3),ES=BigInt(5),AS=BigInt(8),oi=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),kS={p:oi,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:AS,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function pp(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=oi,a=t*t%s*t%s,c=ot(a,Ud,s)*a%s,l=ot(c,SS,s)*t%s,d=ot(l,ES,s)*l%s,u=ot(d,e,s)*d%s,f=ot(u,n,s)*u%s,h=ot(f,r,s)*f%s,g=ot(h,o,s)*h%s,m=ot(g,o,s)*h%s,b=ot(m,e,s)*d%s;return{pow_p_5_8:ot(b,Ud,s)*t%s,b2:a}}function CS(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const $d=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function IS(t,e){const n=oi,r=le(e*e*e,n),o=le(r*r*e,n),s=pp(t*o).pow_p_5_8;let i=le(t*r*s,n);const a=le(e*i*i,n),c=i,l=le(i*$d,n),d=a===t,u=a===le(-t,n),f=a===le(-t*$d,n);return d&&(i=c),(u||f)&&(i=l),Zv(i,n)&&(i=le(-i,n)),{isValid:d||u,value:i}}const Hd=wS(kS,{uvRatio:IS}),jo=(()=>{const t=oi,e=n=>{const{pow_p_5_8:r,b2:o}=pp(n);return le(ot(r,xS,t)*o,t)};return vS({P:t,type:"x25519",powPminus2:e,adjustScalarBytes:CS,scalarMultBase:n=>{const r=le(n,Hd.Fn.ORDER);if(r===jd)return jd;const o=Hd.BASE.multiply(r);return le((o.Z+o.Y)*e(le(o.Z-o.Y,t)),t)}})})();class qd{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,n){if(ol(e),Bt(n,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?e.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),hn(o)}update(e){return Ss(this),this.iHash.update(e),this}digestInto(e){Ss(this),Vh(e,this),this.finished=!0;const n=e.subarray(0,this.outputLen);this.iHash.digestInto(n),this.oHash.update(n),this.oHash.digestInto(n),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});const{oHash:n,iHash:r,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const gp=(()=>{const t=((e,n,r)=>new qd(e,n).update(r).digest());return t.create=(e,n)=>new qd(e,n),t})();function Kd(){const t={};return t.promise=new Promise((e,n)=>{t.resolve=e,t.reject=n}),t}class zd{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}}class Ui{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new zd(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const n=this.head;this.head=n.next=new zd(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){const n=this.tail.next;this.tail.next=null,this.tail=n,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}class RS extends Error{type;code;constructor(e,n){super(e??"The operation was aborted"),this.type="aborted",this.code=n??"ABORT_ERR"}}function TS(t={}){return PS(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}},t)}function PS(t,e){e=e??{};let n=e.onEnd,r=new Ui,o,s,i,a=Kd();const c=async()=>{try{return r.isEmpty()?i?{done:!0}:await new Promise((b,w)=>{s=R=>{s=null,r.push(R);try{b(t(r))}catch(y){w(y)}return o}}):t(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Kd()})}},l=b=>s!=null?s(b):(r.push(b),o),d=b=>(r=new Ui,s!=null?s({error:b}):(r.push({error:b}),o)),u=b=>{if(i)return o;if(e?.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})),h=()=>(r=new Ui,f(),{done:!0}),g=b=>(f(b),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:g,push:u,end:f,get readableLength(){return r.size},onEmpty:async b=>{const w=b?.signal;if(w?.throwIfAborted(),r.isEmpty())return;let R,y;w!=null&&(R=new Promise((k,N)=>{y=()=>{N(new RS)},w.addEventListener("abort",y)}));try{await Promise.race([a.promise,R])}finally{y!=null&&w!=null&&w?.removeEventListener("abort",y)}}},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 fl extends Error{name="TimeoutError";constructor(e,n){super(e,n),Error.captureStackTrace?.(this,fl)}}const Wd=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function NS(t,e){const{milliseconds:n,fallback:r,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e;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(Wd(i));return}if(i&&(c=()=>{f(Wd(i))},i.addEventListener("abort",c,{once:!0})),t.then(u,f),n===Number.POSITIVE_INFINITY)return;const h=new fl;a=s.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){f(g)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?u():o instanceof Error?f(o):(h.message=o??`Promise timed out after ${n} milliseconds`,f(h))},n)}).finally(()=>{d.clear(),c&&i&&i.removeEventListener("abort",c)});return d.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},d}const LS=t=>{const e=t.addEventListener||t.on||t.addListener,n=t.removeEventListener||t.off||t.removeListener;if(!e||!n)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:n.bind(t)}};function BS(t,e,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=[e].flat(),c=[],{addListener:l,removeListener:d}=LS(t),u=async(...h)=>{const g=n.multiArgs?h:h[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=(...h)=>{r(),i(n.rejectionMultiArgs?h:h[0])};r=()=>{for(const h of a)d(h,u);for(const h of n.rejectionEvents)a.includes(h)||d(h,f)};for(const h of a)l(h,u);for(const h of n.rejectionEvents)a.includes(h)||l(h,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=NS(o,{milliseconds:n.timeout});return s.cancel=()=>{r(),s.clear()},s}return o}function _S(t,e,n){typeof n=="function"&&(n={filter:n}),n={...n,count:1,resolveImmediately:!1};const r=BS(t,e,n),o=r.then(s=>s[0]);return o.cancel=r.cancel,o}class Cs extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class OS extends Error{static name="StreamClosedError";name="StreamClosedError"}function DS(t){return t.reason}function mp(t,e,n){if(e==null||t==null)return t;const r=DS;if(e.aborted)return t.catch(()=>{}),Promise.reject(r(e));let o;return Promise.race([t,new Promise((s,i)=>{o=()=>{i(r(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}const FS=Math.pow(2,20)*4;class wp extends Xm{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??FS,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new se,this.writeBuffer=new se,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 OS)};this.addEventListener("close",r)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),mp(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;const e=TS(),n=s=>{e.push(s.data)};this.addEventListener("message",n);const r=s=>{e.end(s.error)};this.addEventListener("close",r);const o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",n),this.removeEventListener("close",r),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Pr(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(n){this.log("failed to send reset to remote - %e",n)}this.dispatchEvent(new pv(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Pr("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 Pr("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Pr(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Pr(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");const e=new fv;this.dispatchEvent(new gv(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new rl))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0;const 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){e=!1;break}const s=this.writeBuffer.sublist(0,o),i=new se(s);this.writeBuffer.consume(s.byteLength);const a=this.sendData(s);if(e=a.canSendMore,r+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",r,n,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}const e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new hv(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Id(`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 Id(`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 MS=4194304;class Vd extends Error{static name="UnwrappedError";name="UnwrappedError"}class yp extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class jS extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class US extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function $S(t){return typeof t?.closeRead=="function"}function HS(t){return typeof t?.close=="function"}function $i(t){return $S(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:HS(t)?t.status!=="open":!1}function qS(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function KS(t,e){const n=e?.maxBufferSize??MS,r=new se;let o,s=!1;if(!qS(t))throw new Wh("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()};t.addEventListener("message",i);const a=d=>{d.error!=null?o?.reject(d.error):o?.resolve()};t.addEventListener("close",a);const c=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",c);const l={readBuffer:r,async read(d){if(s===!0)throw new Vd("Stream was unwrapped");if($i(t)){if(d?.bytes==null)return null;if(r.byteLength<d.bytes)throw t.log.error("closed after reading %d/%d bytes",r.byteLength,d.bytes),new Cs(`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 mp(o.promise,d?.signal),$i(t)){if(r.byteLength===0&&d?.bytes==null)return null;break}o=Promise.withResolvers()}const f=d?.bytes??r.byteLength;if(r.byteLength<f){if($i(t))throw t.log.error("closed while reading %d/%d bytes",r.byteLength,f),new Cs(`Unexpected EOF - stream closed while reading ${r.byteLength}/${f} bytes`);return l.read(d)}const h=r.sublist(0,f);return r.consume(f),h},async write(d,u){if(s===!0)throw new Vd("Stream was unwrapped");t.send(d)||await _S(t,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",i),t.removeEventListener("close",a),t.removeEventListener("remoteCloseWrite",c),r.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",r.byteLength),t.push(r))),t}};return l}function Gd(t,e={}){const n=KS(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=An(e.maxDataLength));const r=e?.lengthDecoder??Ch,o=e?.lengthEncoder??Yb;return{async read(i){let a=-1;const c=new se;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 yp("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new US(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new jS(`Message length too long - ${a} > ${e.maxDataLength}`);const l=await n.read({...i,bytes:a});if(l==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new Cs(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw t.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Cs(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await n.write(new se(o(i.byteLength),i),a)},async writeV(i,a){const c=new se(...i.flatMap(l=>[o(l.byteLength),l]));await n.write(c,a)},unwrap(){return n.unwrap()}}}const zS=1024*1024*4,WS=1024*1024*4;class VS{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new se,this.maxBufferSize=e.maxBufferSize??zS,this.maxDataLength=e.maxDataLength??WS,this.lengthDecoder=e.lengthDecoder??Ch,this.encodingLength=e.encodingLength??An}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new Wh(`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 yp("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 GS={};const uo=65535,Xd=uo-16,Ao=!!GS?.DUMP_SESSION_KEYS,Yd=16;function Za(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const Is=t=>t?`"${t}" `:"";function Ja(t,e=""){if(typeof t!="boolean")throw new TypeError(Is(e)+"expected boolean, got type="+typeof t);return t}function er(t,e=""){if(typeof t!="number")throw new TypeError(Is(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(Is(e)+"expected integer >= 0, got "+t);return t}function xe(t,e,n=""){if(Za(t)&&(e===void 0||t.length===e))return t;e!==void 0&&er(e,"length");const r=Za(t),o=e!==void 0?` of length ${e}`:"",s=r?`length=${t.length}`:`type=${typeof t}`,i=Is(n)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}const Zd=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`)};function Jd(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function XS(t,e){xe(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function Ct(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Xt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function YS(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const tr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ZS(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function JS(t){for(let e=0;e<t.length;e++)t[e]=ZS(t[e]);return t}const ln=tr?t=>t:JS;function QS(t,e){return!t.byteLength||!e.byteLength?!1:t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function ex(t,e){if(QS(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function tx(t,e){return Zd(t,"defaults"),Zd(e,"opts"),Object.assign(t,e)}function nx(t,e){if(t=xe(t),e=xe(e),t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}function rx(t,e,n){const r=e,o=(()=>[]),s=(a,c)=>r(c,...o(a)).update(a).digest(),i=r(new Uint8Array(t),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>r(a,...c),s}const ox=(t,e)=>{function n(r,...o){if(xe(r,void 0,"key"),t.nonceLength!==void 0){const u=o[0];xe(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}const s=t.tagLength,i=t.nonceLength!==void 0?1:0;if(!t.withAAD){for(let u=i;u<o.length;u++)if(Za(o[u]))throw new Error("AAD not supported")}t.withAAD&&o[i]!==void 0&&xe(o[i],void 0,"AAD");const a=e(r,...o),c=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");xe(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,xe(u,void 0,"data"),c(a.encrypt.length,f),a.encrypt(u,f)},decrypt(u,f){if(xe(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,t),n};function Qa(t,e,n=!0){if(e===void 0)return new Uint8Array(t);if(xe(e,t,"output"),n&&!Rs(e))throw new Error("invalid output, must be aligned");return e}function sx(t,e,n){er(t),er(e),Ja(n);const r=new Uint8Array(16),o=YS(r);return o.setBigUint64(0,BigInt(e),n),o.setBigUint64(8,BigInt(t),n),r}function Rs(t){return t.byteOffset%4===0}function Ts(t){return Uint8Array.from(xe(t))}const bp=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),ix=ln(Ct(bp("expand 16-byte k"))),ax=ln(Ct(bp("expand 32-byte k")));function ne(t,e){return t<<e|t>>>32-e}const Nr=64,cx=16,ec=2**32-1,Qd=Uint32Array.of();function lx(t,e,n,r,o,s,i,a){const c=o.length,l=new Uint8Array(Nr),d=Ct(l),u=tr&&Rs(o)&&Rs(s),f=u?Ct(o):Qd,h=u?Ct(s):Qd;if(!tr){for(let g=0;g<c;i++){if(t(e,n,r,d,i,a),ln(d),i>=ec)throw new Error("arx: counter overflow");const m=Math.min(Nr,c-g);for(let b=0,w;b<m;b++)w=g+b,s[w]=o[w]^l[b];g+=m}return}for(let g=0;g<c;i++){if(t(e,n,r,d,i,a),i>=ec)throw new Error("arx: counter overflow");const m=Math.min(Nr,c-g);if(u&&m===Nr){const b=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,R;w<cx;w++)R=b+w,h[R]=f[R]^d[w];g+=Nr;continue}for(let b=0,w;b<m;b++)w=g+b,s[w]=o[w]^l[b];g+=m}}function dx(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:s,rounds:i}=tx({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return er(o),er(i),Ja(s),Ja(n),(a,c,l,d,u=0)=>{xe(a,void 0,"key"),xe(c,void 0,"nonce"),xe(l,void 0,"data");const f=l.length,h=d!==void 0;if(d=Qa(f,d,!1),h&&ex(l,d),er(u),u<0||u>=ec)throw new Error("arx: counter overflow");const g=[];let m=a.length,b,w;if(m===32)g.push(b=Ts(a)),w=ax;else if(m===16&&n)b=new Uint8Array(32),b.set(a),b.set(a,16),w=ix,g.push(b);else throw xe(a,32,"arx key"),new Error("invalid key size");(!tr||!Rs(c))&&g.push(c=Ts(c));let R=Ct(b);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");const N=c.subarray(0,16);if(tr)r(w,R,Ct(N),R);else{const x=ln(Uint32Array.from(w));r(x,R,Ct(N),R),Xt(x),ln(R)}c=c.subarray(16)}else tr||ln(R);const y=16-o;if(y!==c.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){const N=new Uint8Array(12);N.set(c,s?0:12-c.length),c=N,g.push(c)}const k=ln(Ct(c));try{return lx(t,w,R,k,l,d,u,i),d}finally{Xt(...g)}}}function Ce(t,e){return t[e++]&255|(t[e++]&255)<<8}class ux{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=Ts(xe(e,32,"key"));const n=Ce(e,0),r=Ce(e,2),o=Ce(e,4),s=Ce(e,6),i=Ce(e,8),a=Ce(e,10),c=Ce(e,12),l=Ce(e,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]=Ce(e,16+2*d)}process(e,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],h=i[6],g=i[7],m=i[8],b=i[9],w=Ce(e,n+0),R=Ce(e,n+2),y=Ce(e,n+4),k=Ce(e,n+6),N=Ce(e,n+8),x=Ce(e,n+10),T=Ce(e,n+12),S=Ce(e,n+14);let v=s[0]+(w&8191),A=s[1]+((w>>>13|R<<3)&8191),_=s[2]+((R>>>10|y<<6)&8191),B=s[3]+((y>>>7|k<<9)&8191),C=s[4]+((k>>>4|N<<12)&8191),E=s[5]+(N>>>1&8191),P=s[6]+((N>>>14|x<<2)&8191),I=s[7]+((x>>>11|T<<5)&8191),D=s[8]+((T>>>8|S<<8)&8191),M=s[9]+(S>>>5|o),F=0,L=F+v*a+A*(5*b)+_*(5*m)+B*(5*g)+C*(5*h);F=L>>>13,L&=8191,L+=E*(5*f)+P*(5*u)+I*(5*d)+D*(5*l)+M*(5*c),F+=L>>>13,L&=8191;let $=F+v*c+A*a+_*(5*b)+B*(5*m)+C*(5*g);F=$>>>13,$&=8191,$+=E*(5*h)+P*(5*f)+I*(5*u)+D*(5*d)+M*(5*l),F+=$>>>13,$&=8191;let H=F+v*l+A*c+_*a+B*(5*b)+C*(5*m);F=H>>>13,H&=8191,H+=E*(5*g)+P*(5*h)+I*(5*f)+D*(5*u)+M*(5*d),F+=H>>>13,H&=8191;let U=F+v*d+A*l+_*c+B*a+C*(5*b);F=U>>>13,U&=8191,U+=E*(5*m)+P*(5*g)+I*(5*h)+D*(5*f)+M*(5*u),F+=U>>>13,U&=8191;let q=F+v*u+A*d+_*l+B*c+C*a;F=q>>>13,q&=8191,q+=E*(5*b)+P*(5*m)+I*(5*g)+D*(5*h)+M*(5*f),F+=q>>>13,q&=8191;let K=F+v*f+A*u+_*d+B*l+C*c;F=K>>>13,K&=8191,K+=E*a+P*(5*b)+I*(5*m)+D*(5*g)+M*(5*h),F+=K>>>13,K&=8191;let X=F+v*h+A*f+_*u+B*d+C*l;F=X>>>13,X&=8191,X+=E*c+P*a+I*(5*b)+D*(5*m)+M*(5*g),F+=X>>>13,X&=8191;let z=F+v*g+A*h+_*f+B*u+C*d;F=z>>>13,z&=8191,z+=E*l+P*c+I*a+D*(5*b)+M*(5*m),F+=z>>>13,z&=8191;let W=F+v*m+A*g+_*h+B*f+C*u;F=W>>>13,W&=8191,W+=E*d+P*l+I*c+D*a+M*(5*b),F+=W>>>13,W&=8191;let V=F+v*b+A*m+_*g+B*h+C*f;F=V>>>13,V&=8191,V+=E*u+P*d+I*l+D*c+M*a,F+=V>>>13,V&=8191,F=(F<<2)+F|0,F=F+L|0,L=F&8191,F=F>>>13,$+=F,s[0]=L,s[1]=$,s[2]=H,s[3]=U,s[4]=q,s[5]=K,s[6]=X,s[7]=z,s[8]=W,s[9]=V}finalize(){const{h:e,pad:n}=this,r=new Uint16Array(10);let o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[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++)e[a]=e[a]&s|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+n[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+n[a]|0)+(i>>>16)|0,e[a]=i&65535;Xt(r)}update(e){Jd(this),xe(e),e=Ts(e);const{buffer:n,blockLen:r}=this,o=e.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(e,s);continue}n.set(e.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,Xt(this.h,this.r,this.buffer,this.pad)}digestInto(e){Jd(this),XS(e,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++)e[s++]=r[i]>>>0,e[s++]=r[i]>>>8}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}}const fx=rx(32,t=>new ux(t));function hx(t,e,n,r,o,s=20){let i=t[0],a=t[1],c=t[2],l=t[3],d=e[0],u=e[1],f=e[2],h=e[3],g=e[4],m=e[5],b=e[6],w=e[7],R=o,y=n[0],k=n[1],N=n[2],x=i,T=a,S=c,v=l,A=d,_=u,B=f,C=h,E=g,P=m,I=b,D=w,M=R,F=y,L=k,$=N;for(let U=0;U<s;U+=2)x=x+A|0,M=ne(M^x,16),E=E+M|0,A=ne(A^E,12),x=x+A|0,M=ne(M^x,8),E=E+M|0,A=ne(A^E,7),T=T+_|0,F=ne(F^T,16),P=P+F|0,_=ne(_^P,12),T=T+_|0,F=ne(F^T,8),P=P+F|0,_=ne(_^P,7),S=S+B|0,L=ne(L^S,16),I=I+L|0,B=ne(B^I,12),S=S+B|0,L=ne(L^S,8),I=I+L|0,B=ne(B^I,7),v=v+C|0,$=ne($^v,16),D=D+$|0,C=ne(C^D,12),v=v+C|0,$=ne($^v,8),D=D+$|0,C=ne(C^D,7),x=x+_|0,$=ne($^x,16),I=I+$|0,_=ne(_^I,12),x=x+_|0,$=ne($^x,8),I=I+$|0,_=ne(_^I,7),T=T+B|0,M=ne(M^T,16),D=D+M|0,B=ne(B^D,12),T=T+B|0,M=ne(M^T,8),D=D+M|0,B=ne(B^D,7),S=S+C|0,F=ne(F^S,16),E=E+F|0,C=ne(C^E,12),S=S+C|0,F=ne(F^S,8),E=E+F|0,C=ne(C^E,7),v=v+A|0,L=ne(L^v,16),P=P+L|0,A=ne(A^P,12),v=v+A|0,L=ne(L^v,8),P=P+L|0,A=ne(A^P,7);let H=0;r[H++]=i+x|0,r[H++]=a+T|0,r[H++]=c+S|0,r[H++]=l+v|0,r[H++]=d+A|0,r[H++]=u+_|0,r[H++]=f+B|0,r[H++]=h+C|0,r[H++]=g+E|0,r[H++]=m+P|0,r[H++]=b+I|0,r[H++]=w+D|0,r[H++]=R+M|0,r[H++]=y+F|0,r[H++]=k+L|0,r[H++]=N+$|0}const px=dx(hx,{counterRight:!1,counterLength:4,allowShortKeys:!1}),gx=new Uint8Array(16),eu=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(gx.subarray(n))},mx=new Uint8Array(32);function tu(t,e,n,r,o){o!==void 0&&xe(o,void 0,"AAD");const s=t(e,n,mx),i=sx(r.length,o?o.length:0,!0),a=fx.create(s);o&&eu(a,o),eu(a,r),a.update(i);const c=a.digest();return Xt(s,i),c}const wx=t=>(e,n,r)=>({encrypt(s,i){const a=s.length;i=Qa(a+16,i,!1),i.set(s);const c=i.subarray(0,-16);t(e,n,c,c,1);const l=tu(t,e,n,c,r);return i.set(l,a),Xt(l),i},decrypt(s,i){i=Qa(s.length-16,i,!1);const a=s.subarray(0,-16),c=s.subarray(-16),l=tu(t,e,n,a,r);if(!nx(c,l))throw Xt(l),new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,n,i,i,1),Xt(l),i}}),nu=ox({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},wx(px));function yx(t,e,n){return ol(t),n===void 0&&(n=new Uint8Array(t.outputLen)),gp(t,n,e)}const Lr=Uint8Array.of(0),bx=Uint8Array.of();function vx(t,e,n,r=32,o){ol(t),Lt(r,"length"),Bt(e,void 0,"prk");const s=t.outputLen;if(e.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=bx:Bt(n,void 0,"info"),!i)return new Uint8Array;const a=new Uint8Array(i*s),{iHash:c,oHash:l}=gp.create(t,e),d=new Uint8Array(s),u=i>1?t.create():void 0;for(let h=0;h<i-1;h++){Lr[0]=h+1;const g=c._cloneInto(u);h&&g.update(d),g.update(n).update(Lr).digestInto(d),l._cloneInto(u).update(d).digestInto(d),a.set(d,s*h)}if(Lr[0]=i,i>1&&c.update(d),c.update(n).update(Lr).digestInto(d),l.update(d).digestInto(d),a.set(d,s*(i-1)),c.destroy(),l.destroy(),u?.destroy(),d!==a&&hn(d),hn(Lr),r===a.length)return a;const f=a.slice(0,r);return hn(a),f}const vp={hashSHA256(t){return Fi(t.subarray())},getHKDF(t,e){const n=yx(Fi,e,t),o=vx(Fi,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 t=jo.utils.randomSecretKey();return{publicKey:jo.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:jo.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return jo.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,n,r){return nu(r,e,n).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,n,r,o){return nu(r,e,n).decrypt(t.subarray(),o)}},Sx=vp;function xx(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,n)=>t.generateX25519SharedKey(e.privateKey,n).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}const Ps=t=>{const e=Pt(2);return e[0]=t>>8,e[1]=t,e};Ps.bytes=2;const Ns=t=>{if(t.length<2)throw RangeError("Could not decode int16BE");if(t instanceof Uint8Array){let e=0;return e+=t[0]<<8,e+=t[1],e}return t.getUint16(0)};Ns.bytes=2;function Ex(t){return{xxHandshakeSuccesses:t.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:t.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:t.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:t.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:t.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Sp(t,e){!e.enabled||!Ao||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${te(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${te(t.privateKey,"hex")}`)):e("Missing local static keys."))}function xp(t,e){!e.enabled||!Ao||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${te(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${te(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Ax(t,e){!e.enabled||!Ao||e(t?`REMOTE_STATIC_PUBLIC_KEY ${te(t.subarray(),"hex")}`:"Missing remote static public key.")}function Ep(t,e){!e.enabled||!Ao||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${te(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Ap(t,e,n){!n.enabled||!Ao||(n(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&te(t.k,"hex")}`),n(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&te(e.k,"hex")}`))}class Qr extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=Qr.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}const kx=0,Cx=4294967295,Ix="Cipherstate has reached maximum n, a new handshake must be performed";class Rx{n;bytes;view;constructor(e=kx){this.n=e,this.bytes=He(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>Cx)throw new Error(Ix)}}const nr=He(0);class Uo{k;n;crypto;constructor(e,n=void 0,r=0){this.crypto=e,this.k=n,this.n=new Rx(r)}hasKey(){return!!this.k}encryptWithAd(e,n){if(!this.hasKey())return n;this.n.assertValue();const r=this.crypto.encrypt(n,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,n,r){if(!this.hasKey())return n;this.n.assertValue();const o=this.crypto.decrypt(n,this.n.getBytes(),e,this.k,r);return this.n.increment(),o}}class Tx{cs;ck;h;crypto;constructor(e,n){this.crypto=e;const r=be(n,"utf-8");this.h=Nx(e,r),this.ck=this.h,this.cs=new Uo(e)}mixKey(e){const[n,r]=this.crypto.hkdf(this.ck,e);this.ck=n,this.cs=new Uo(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new se(this.h,e))}encryptAndHash(e){const n=this.cs.encryptWithAd(this.h,e);return this.mixHash(n),n}decryptAndHash(e){const n=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),n}split(){const[e,n]=this.crypto.hkdf(this.ck,nr);return[new Uo(this.crypto,e),new Uo(this.crypto,n)]}}class Px{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:n,protocolName:r,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=n,this.ss=new Tx(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 e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,n=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<n+32)throw new Error("message is not long enough");this.re=e.sublist(n,n+32),this.ss.mixHash(this.re)}readS(e,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(e.byteLength<n+r)throw new Error("message is not long enough");const o=e.sublist(n,n+r);return this.rs=this.ss.decryptAndHash(o),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class kp extends Px{writeMessageA(e){return new se(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const n=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new se(n,r,this.ss.encryptAndHash(e))}writeMessageC(e){const n=this.writeS();return this.writeSE(),new se(n,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(n){throw new Qr(`handshake stage 0 validation fail: ${n.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();const n=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+n))}catch(n){throw new Qr(`handshake stage 1 validation fail: ${n.message}`)}}readMessageC(e){try{const n=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(n))}catch(n){throw new Qr(`handshake stage 2 validation fail: ${n.message}`)}}}function Nx(t,e){if(e.length<=32){const n=He(32);return n.set(e),n}else return t.hash(e)}var Ls;(function(t){let e;t.codec=()=>(e==null&&(e=ti((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 Ed('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 Ed('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(n.string());break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>ei(n,t.codec()),t.decode=(n,r)=>Qs(n,t.codec(),r)})(Ls||(Ls={}));var Bs;(function(t){let e;t.codec=()=>(e==null&&(e=ti((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),Ls.codec().encode(n.extensions,r)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={identityKey:He(0),identitySig:He(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=Ls.codec().decode(n,n.uint32(),{limits:o.limits?.extensions});break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>ei(n,t.codec()),t.decode=(n,r)=>Qs(n,t.codec(),r)})(Bs||(Bs={}));async function Cp(t,e,n){const r=await t.sign(Rp(e));return Bs.encode({identityKey:ni(t.publicKey),identitySig:r,extensions:n})}async function Ip(t,e,n){try{const r=Bs.decode(t),o=Va(r.identityKey);if(n?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${n}`);if(!e)throw new Error("Remote static does not exist");const s=Rp(e);if(!await o.verify(s,r.identitySig))throw new Error("Invalid payload signature");return r}catch(r){throw new Hm(r.message)}}function Rp(t){const e=be("noise-libp2p-static-key:");return t instanceof Uint8Array?Da([e,t],e.length+t.length):(t.prepend(e),t)}class Lx extends wp{stream;handshake;metrics;decoder;constructor(e,n,r){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=n,this.metrics=r,this.decoder=new VS({lengthDecoder:Ns,maxBufferSize:16*1024*1024,encodingLength:()=>2});const o=c=>{try{for(const l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);const s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);const i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);const a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){const n=new se;for(let r=0;r<e.byteLength;r+=Xd){let o=r+Xd;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(r,o)):s=this.handshake.encrypt(e.sublist(r,o)),this.metrics?.encryptedPackets.increment(),n.append(Ps(s.byteLength)),n.append(s)}return n}decrypt(e){const n=new se;for(let r=0;r<e.byteLength;r+=uo){let o=r+uo;if(o>e.byteLength&&(o=e.byteLength),o-Yd<r)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(r,o):s=e.sublist(r,o);const i=e.subarray(r,o-Yd);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(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}}function ru(t,e,n){return new Lx(t,e,n)}async function Bx(t,e){const{log:n,connection:r,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Cp(s,a.publicKey,l),u=new kp({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Sp(u.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(u.writeMessageA(nr),e),n.trace("Stage 0 - Initiator finished sending first message."),xp(u.e,n),n.trace("Stage 1 - Initiator waiting to receive first message from responder...");const f=u.readMessageB(await r.read(e));n.trace("Stage 1 - Initiator received the message."),Ep(u.re,n),Ax(u.rs,n),n.trace("Initiator going to check remote's signature...");const h=await Ip(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),e),n.trace("Stage 2 - Initiator sent message with signed payload.");const[g,m]=u.ss.split();return Ap(g,m,n),{payload:h,encrypt:b=>g.encryptWithAd(nr,b),decrypt:(b,w)=>m.decryptWithAd(nr,b,w)}}async function _x(t,e){const{log:n,connection:r,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Cp(s,a.publicKey,l),u=new kp({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Sp(u.s,n),n.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await r.read(e)),n.trace("Stage 0 - Responder received first message."),Ep(u.re,n),n.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await r.write(u.writeMessageB(d),e),n.trace("Stage 1 - Responder sent the second handshake message with signed payload."),xp(u.e,n),n.trace("Stage 2 - Responder waiting for third handshake message...");const f=u.readMessageC(await r.read(e));n.trace("Stage 2 - Responder received the message, finished handshake.");const h=await Ip(f,u.rs,c),[g,m]=u.ss.split();return Ap(g,m,n),{payload:h,encrypt:b=>m.encryptWithAd(nr,b),decrypt:(b,w)=>g.decryptWithAd(nr,b,w)}}class Ox{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,n={}){const{staticNoiseKey:r,extensions:o,crypto:s,prologueBytes:i}=n,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");const c=s??Sx;this.crypto=xx(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Ex(a):void 0,r?this.staticKey=c.generateX25519KeyPairFromSeed(r):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??He(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Ym]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,n){const r=e.log?.newScope("noise")??this.log,o=Gd(e,{lengthEncoder:Ps,lengthDecoder:Ns,maxDataLength:uo}),s=await this.performHandshakeInitiator(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=Va(s.payload.identityKey);return{connection:ru(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:dr(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;const n=this.components.upgrader.getStreamMuxers();if(n!=null)for(const r of e){const o=n.get(r);if(o!=null)return o}if(e.length)throw new qm("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,n){const r=e.log?.newScope("noise")??this.log,o=Gd(e,{lengthEncoder:Ps,lengthDecoder:Ns,maxDataLength:uo}),s=await this.performHandshakeResponder(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=Va(s.payload.identityKey);return{connection:ru(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:dr(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,n,r,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Bx({connection:e,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(e,n,r,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await _x({connection:e,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 Dx(t={}){return e=>new Ox(e,t)}const Fx="termdock-e2ee-v1",tc=3600*1e3,ou=512*1024*1024,nc=4*1024*1024,Jo=()=>{},si=Object.assign(Jo,{enabled:!1,error:Jo,trace:Jo,newScope:()=>si});Object.freeze(si);async function Tp(){const t=await tv();return{privateKey:t,peerId:dr(t.publicKey).toString()}}function Mx(t){return btoa(String.fromCharCode(...ov(t.privateKey)))}function su(t){if(t.length>512||!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Invalid identity encoding");const e=rv(Uint8Array.from(atob(t),n=>n.charCodeAt(0)));if(e.type!=="Ed25519")throw new Error("Only Ed25519 device identities are supported");return{privateKey:e,peerId:dr(e.publicKey).toString()}}class Pp{constructor(e=Jo){this.consumed=e}consumed;chunks=[];size=0;ended=!1;error;wake;push(e){if(this.ended)throw this.error??new Error("Byte stream closed");if(this.size+e.byteLength>nc)throw new Error("Secure stream buffer limit exceeded");this.chunks.push(e.slice()),this.size+=e.byteLength,this.wake?.()}end(e){this.ended=!0,this.error??=e,this.wake?.()}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const e=this.chunks.shift();if(e)this.size-=e.byteLength,yield e,this.consumed();else{if(this.ended)return;await new Promise(n=>{this.wake=n})}}}}class jx extends wp{constructor(e,n){super({log:si,direction:n?"outbound":"inbound",maxReadBufferLength:nc,maxWriteBufferLength:nc}),this.duplex=e,this.finished=e.sink(this.outgoing).catch(r=>{this.abort(ur(r))}),this.readTransport()}duplex;outgoing=new Pp(()=>this.onMuxerDrain());finished;async readTransport(){try{for await(const e of this.duplex.source)this.onData(e.slice());this.onTransportClosed()}catch(e){this.onTransportClosed(ur(e))}}sendData(e){return this.outgoing.push(e.subarray()),{sentBytes:e.byteLength,canSendMore:!1}}sendReset(e){this.outgoing.end(e),this.duplex.close?.(e)}sendPause(){}sendResume(){}async close(){this.outgoing.end(),this.duplex.close?.(),this.onTransportClosed(),await this.finished}}function ur(t){return t instanceof Error?t:new Error("Secure transport failed")}class Ux extends Error{code="E2EE_REHANDSHAKE_REQUIRED";constructor(){super("Encrypted connection lifetime reached; establish a new handshake without replaying pending input")}}function $x(t){const e=t?.maxAgeMs??tc,n=t?.maxBytesPerDirection??ou;if(!Number.isSafeInteger(e)||e<=0||e>tc||!Number.isSafeInteger(n)||n<=0||n>ou)throw new Error("Encrypted connection limits cannot exceed the production maximum");return{maxAgeMs:e,maxBytesPerDirection:n}}async function Hx(t){const{identity:e,duplex:n,initiator:r,targetPinnedPeerId:o,signal:s}=t,i=$x(t.limits);if(typeof Reflect.get(Promise,"withResolvers")!="function"||typeof globalThis.crypto?.getRandomValues!="function")throw new Error("End-to-end encryption requires Node.js 22+ or a modern browser with Promise.withResolvers and secure random support");if(r&&!o)throw new Error("A pinned target identity is required");const a=o?cv(o):void 0;if(a&&a.type!=="Ed25519")throw new Error("Only Ed25519 target identities are supported");if(e.peerId!==dr(e.privateKey.publicKey).toString())throw new Error("Local identity mismatch");if(s?.aborted)throw s.reason??new Error("Connection aborted");const c=new jx(n,r),l=new AbortController,d=setTimeout(()=>{const h=new Error("Encrypted handshake timed out");l.abort(h),c.abort(h)},15e3),u=()=>{l.abort(s?.reason),c.abort(ur(s?.reason))};s?.addEventListener("abort",u,{once:!0}),c.addEventListener("close",()=>s?.removeEventListener("abort",u),{once:!0});const f=Dx({crypto:vp,prologueBytes:new TextEncoder().encode(Fx)})({privateKey:e.privateKey,peerId:dr(e.privateKey.publicKey),logger:{forComponent:()=>si},upgrader:{getStreamMuxers:()=>new Map}});try{const h=await(r?f.secureOutbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}):f.secureInbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}));if(h.remotePeer.type!=="Ed25519")throw new Error("Unsupported remote identity");return{authenticatedPeerId:h.remotePeer.toString(),duplex:qx(h.connection,i)}}catch(h){throw c.abort(ur(h)),h}finally{clearTimeout(d),s?.removeEventListener("abort",u)}}function qx(t,e){const n=new Pp,r=performance.now(),o=Date.now();let s=0,i=0,a;const c=()=>(a??=new Ux,n.end(a),t.abort(a),a),l=setTimeout(c,e.maxAgeMs);typeof l=="object"&&l.unref?.();const d=(f,h)=>{if(a)throw a;if(Math.max(performance.now()-r,Date.now()-o)>=e.maxAgeMs||f+h>=e.maxBytesPerDirection)throw c()};t.addEventListener("message",f=>{try{d(i,f.data.byteLength),i+=f.data.byteLength,n.push(f.data.subarray())}catch(h){t.abort(ur(h))}}),t.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 h of f)d(s,h.byteLength),s+=h.byteLength,t.send(h)||await t.onDrain()}catch(h){throw t.abort(ur(h)),h}},close(f){f?t.abort(f):t.close()}}}const Np=1012,Lp="Encrypted transport renewed";class hl{constructor(e=64){this.limit=e}limit;items=[];wake;ended=!1;error;push(e){if(this.ended)throw new Error("Channel closed");if(this.items.length>=this.limit)throw this.end(new Error("Channel queue exceeded")),this.error;this.items.push(e),this.wake?.()}end(e){this.ended=!0,this.error??=e,this.wake?.()}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const e=this.items.shift();if(e!==void 0){yield e;continue}if(this.ended)return;await new Promise(n=>{this.wake=n}),this.wake=void 0}}}const Hi=2*1024*1024,Kx=new TextEncoder,zx=new TextDecoder("utf-8",{fatal:!0});class Wx{constructor(e){this.duplex=e;const n=this;this.done=e.sink((async function*(){for await(const r of n.outgoing)try{yield r}finally{n.outgoingBytes-=r.byteLength}})()),this.done.catch(r=>this.close(r instanceof Error?r:new Error("Transport failed")))}duplex;outgoing=new hl(256);outgoingBytes=0;get hasPendingWrites(){return this.outgoingBytes>0}done;send(e){const n=Kx.encode(JSON.stringify(e));if(n.length>Hi)throw new Error("Record too large");const r=new Uint8Array(n.length+4);if(new DataView(r.buffer).setUint32(0,n.length),r.set(n,4),this.outgoingBytes+r.byteLength>4*1024*1024)throw new Error("Record queue byte budget exceeded");this.outgoingBytes+=r.byteLength;try{this.outgoing.push(r)}catch(o){throw this.outgoingBytes-=r.byteLength,o}}close(e){this.outgoing.end(e),this.duplex.close?.(e)}async*read(){let e=new Uint8Array(0);for await(const n of this.duplex.source){if(e.length+n.length>Hi*2+8)throw new Error("Record buffer exceeded");const r=new Uint8Array(e.length+n.length);for(r.set(e),r.set(n,e.length),e=r;e.length>=4;){const o=new DataView(e.buffer,e.byteOffset,4).getUint32(0);if(o>Hi||o===0)throw new Error("Invalid record size");if(e.length<o+4)break;const s=JSON.parse(zx.decode(e.subarray(4,o+4)));if(!s||typeof s!="object"||typeof s.id!="string"||typeof s.type!="string")throw new Error("Invalid record");yield s,e=e.slice(o+4)}}if(e.length)throw new Error("Truncated record")}}function Bp(t){let e="";for(let n=0;n<t.length;n+=8192)e+=String.fromCharCode(...t.subarray(n,n+8192));return btoa(e)}function _p(t){const e=atob(t);return Uint8Array.from(e,n=>n.charCodeAt(0))}function Vx(t){const e=new hl(64);t.binaryType="arraybuffer";const n=r=>{e.end(r),t.close(1e3)};return t.addEventListener("message",r=>{try{if(!(r.data instanceof ArrayBuffer)||r.data.byteLength>1024*1024)throw new Error("Invalid encrypted frame");e.push(new Uint8Array(r.data))}catch{n(new Error("Encrypted transport rejected frame"))}}),t.addEventListener("close",()=>e.end()),t.addEventListener("error",()=>e.end(new Error("Encrypted transport disconnected"))),{source:e,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(;t.bufferedAmount>256*1024;){if(t.readyState!==1||Date.now()-i>15e3)throw new Error("Encrypted transport congested");await new Promise(a=>setTimeout(a,10))}if(t.readyState!==1)throw new Error("Encrypted transport closed");t.send(o.subarray(s,s+64*1024))}}catch(o){throw n(o instanceof Error?o:new Error("Encrypted transport failed")),o}}}}const Op=8,Dp=128,Gx=5*1024*1024,Xx=Dp+Op+8,Yx=256,$o=3e4,Br=64*1024;function zt(t){return t instanceof Error?t:new Error(String(t??"Secure connection closed"))}function iu(t){if(!t.startsWith("/")||t.startsWith("//")||t.includes("#"))throw new Error("A local API path is required");return t}class Fp extends EventTarget{constructor(e,n,r){super(),this.url=e,this.transmit=n,this.disconnect=r}url;transmit;disconnect;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;binaryType="arraybuffer";bufferedAmount=0;protocol="termdock-e2ee-v1";extensions="";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;send(e){if(this.readyState!==1)throw new Error("Secure socket is not open");if(typeof e!="string"||new TextEncoder().encode(e).length>1024*1024)throw new Error("Unsupported socket payload");this.transmit(e)}close(e=1e3,n=""){this.readyState!==3&&(this.disconnect(),this.finish(e,n))}accept(e){if(this.readyState!==3)if(e.type==="ws-ready"){this.readyState=1;const n=new Event("open");this.dispatchEvent(n),this.onopen?.(n)}else if(e.type==="ws-data"&&typeof e.data=="string"){const n=new MessageEvent("message",{data:e.data});this.dispatchEvent(n),this.onmessage?.(n)}else e.type==="ws-close"?this.finish(typeof e.code=="number"?e.code:1e3,typeof e.reason=="string"?e.reason:""):e.type==="error"&&this.fail(zt(e.error))}fail(e){if(this.readyState===3)return;const n=new Event("error");this.dispatchEvent(n),this.onerror?.(n),this.finish(1006,e.message)}finish(e,n){if(this.readyState===3)return;this.readyState=3;const r=new CloseEvent("close",{code:e,reason:n,wasClean:e===1e3});this.dispatchEvent(r),this.onclose?.(r)}}class Zx{constructor(e,n,r){this.channel=e,this.identity=n,this.targetPeerId=r,this.read().catch(o=>this.close(zt(o))),e.done.catch(o=>this.close(zt(o)))}channel;identity;targetPeerId;establishedAt=performance.now();establishedWallTime=Date.now();lastInputAt=-1/0;pending=new Map;waiting=[];stopped=!1;closeReason;get canSwitchTransport(){return!this.channel.hasPendingWrites&&performance.now()-this.lastInputAt>=2e3&&![...this.pending.values()].some(e=>e.kind!=="socket")&&!this.waiting.some(e=>e.kind!=="socket")}get renewalDue(){return!this.stopped&&Math.max(performance.now()-this.establishedAt,Date.now()-this.establishedWallTime)>=tc-5*6e4}get closed(){return this.stopped}hasCapacity(e){if(this.pending.size>=Xx)return!1;const n=[...this.pending.values()].filter(r=>r.kind===e).length;return e==="http"?n<Op:e==="socket"?n<Dp:!0}allocate(e){if(this.stopped)throw this.closeReason??new Error("Secure connection closed");const n=crypto.randomUUID(),r=new hl(4);return this.pending.set(n,{queue:r,kind:e}),{id:n,queue:r}}reserve(e,n){return n?.aborted?Promise.reject(n.reason):this.stopped?Promise.reject(this.closeReason??new Error("Secure connection closed")):this.hasCapacity(e)?Promise.resolve(this.allocate(e)):this.waiting.length>=Yx?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("连接等待超时,请重试。")),$o),c={kind:e,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 e=0;e<this.waiting.length;){const n=this.waiting[e];if(!this.hasCapacity(n.kind)){e++;continue}this.waiting.splice(e,1),n.cleanup(),n.resolve(this.allocate(n.kind))}}async read(){try{for await(const e of this.channel.read()){const n=this.pending.get(e.id);n&&(n.socket?(n.socket.accept(e),(e.type==="ws-close"||e.type==="error")&&this.release(e.id)):(n.queue.push(e),(e.type==="end"||e.type==="error")&&(n.cancelUpload?.(),this.release(e.id))))}}finally{this.close(new Error("Secure connection closed"))}}release(e){this.pending.get(e)?.queue.end(),this.pending.delete(e),this.dispatchWaiting()}async request(e,n){const{id:r,queue:o}=await this.reserve("request"),s=setTimeout(()=>this.close(new Error("Secure connection timed out")),Math.max(1e3,Math.min($o,n?.timeoutMs??$o)));try{if(this.stopped)throw this.closeReason;this.channel.send({...e,id:r});const i=(await o[Symbol.asyncIterator]().next()).value;if(!i)throw new Error("Secure request closed");if(i.type==="error")throw zt(i.error);return i}finally{clearTimeout(s),this.release(r)}}openSocket(e){iu(e);let n;const r=new AbortController,o=new Fp(e,s=>{if(n){try{JSON.parse(s)?.type==="input"&&(this.lastInputAt=performance.now())}catch{}this.channel.send({id:n,type:"ws-data",data:s})}},()=>{if(r.abort(),n)try{this.channel.send({id:n,type:"ws-close"})}finally{this.release(n)}});return this.reserve("socket",r.signal).then(s=>{if(n=s.id,o.readyState===3){this.release(n);return}const i=this.pending.get(n);if(!i)throw new Error("Secure connection closed");i.socket=o,this.channel.send({id:n,type:"ws-open",path:e})}).catch(s=>{n&&this.release(n),o.fail(zt(s))}),o}async fetch(e,n){const r=typeof location>"u"?"https://termdock.invalid":location.origin,o=e instanceof Request?e:null,s=new URL(o?.url??String(e),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=iu(s.pathname+s.search),l=s.pathname==="/api/terminal/fs/upload"?110*1024*1024:Gx;if(i.signal.aborted)throw i.signal.reason;const d={};i.headers.forEach((k,N)=>{["cookie","authorization","host","connection","content-length"].includes(N)||(d[N]=k)});const{id:u,queue:f}=await this.reserve("http",i.signal),h=f[Symbol.asyncIterator]();let g;const m=()=>{g?.cancel().catch(()=>{})},b=this.pending.get(u);if(!b)throw new Error("Secure connection closed");b.cancelUpload=m;const w=()=>{m();try{this.channel.send({id:u,type:"cancel"})}catch{}f.end(zt(i.signal.reason??"Request aborted")),this.release(u)};i.signal.addEventListener("abort",w,{once:!0});const R=()=>{i.signal.removeEventListener("abort",w),this.release(u)},y=async()=>{let k;try{const N=(await Promise.race([h.next(),new Promise((x,T)=>{k=setTimeout(()=>T(new Error("服务响应超时,请重试。")),$o)})])).value;if(!N)throw new Error("Secure response ended unexpectedly");if(N.type==="error")throw zt(N.error);return N}finally{clearTimeout(k)}};try{if(i.signal.aborted)throw i.signal.reason;if(this.channel.send({id:u,type:"http",method:a,path:c,headers:d}),i.body){const S=i.body.getReader();g=S;let v=0,A=0;try{for(;;){const{done:_,value:B}=await S.read();if(_)break;if(v+=B.byteLength,v>l)throw new Error("Request body exceeds upload limit");for(let C=0;C<B.byteLength;C+=Br){if(this.channel.send({id:u,type:"upload",data:Bp(B.subarray(C,C+Br))}),(await y()).type!=="upload-ack")throw new Error("Invalid upload acknowledgement");A+=Math.min(Br,B.byteLength-C),n?.onUploadProgress?.(A)}}}catch(_){throw await S.cancel(_).catch(()=>{}),_}finally{g=void 0,S.releaseLock()}}if(i.signal.aborted||this.stopped)throw new Error("Request aborted");this.channel.send({id:u,type:"upload-end"});const k=await y();if(k.type!=="head"||typeof k.status!="number")throw new Error("Invalid response header");const N=new Headers(k.headers);if(a==="HEAD"||[204,205,304].includes(k.status)){if((await y()).type!=="end")throw new Error("Unexpected response body");return R(),new Response(null,{status:k.status,headers:N})}let x=!1;const T=new ReadableStream({pull:async S=>{try{x&&(this.channel.send({id:u,type:"ack"}),x=!1);const v=await y();if(v.type==="end"){S.close(),R();return}if(v.type!=="chunk"||typeof v.data!="string")throw new Error("Invalid response chunk");const A=_p(v.data);if(A.length>Br)throw new Error("Response chunk exceeds budget");S.enqueue(A),x=!0}catch(v){S.error(v),w(),R()}},cancel:()=>{w(),R()}},{highWaterMark:Br,size:S=>S.byteLength});return new Response(T,{status:k.status,headers:N})}catch(k){throw w(),R(),k}}retire(){for(const e of this.pending.values())e.socket?.accept({id:"",type:"ws-close",code:Np,reason:Lp});this.close()}close(e=new Error("Secure connection closed")){if(!this.stopped){this.stopped=!0,this.closeReason=e;for(const n of this.waiting.splice(0))n.cleanup(),n.reject(e);for(const n of this.pending.values())n.queue.end(e),n.cancelUpload?.(),n.socket?.fail(e);this.pending.clear(),this.channel.close(e)}}}async function bn(t){const e=new URL(t.url);if(!["wss:","ws:"].includes(e.protocol))throw new Error("A WebSocket endpoint is required");if(e.protocol==="ws:"&&!["127.0.0.1","localhost","[::1]"].includes(e.hostname))throw new Error("Remote secure channels require WSS");const n=t.identity??await Tp(),r=(t.socketFactory??(c=>new WebSocket(c)))(e.href),o=Vx(r),s=new AbortController,i=setTimeout(()=>s.abort(new Error("Secure handshake timed out")),2e4),a=t.signal?AbortSignal.any([t.signal,s.signal]):s.signal;try{await new Promise((d,u)=>{if(a.aborted){u(a.reason);return}const f=()=>{a.removeEventListener("abort",m),r.removeEventListener("open",h),r.removeEventListener("error",g),r.removeEventListener("close",g)},h=()=>{f(),d()},g=()=>{f(),u(new Error("Secure transport unavailable"))},m=()=>{f(),u(a.reason)};a.addEventListener("abort",m,{once:!0}),r.addEventListener("open",h),r.addEventListener("error",g),r.addEventListener("close",g),r.readyState===1&&h()});const c=await Hx({identity:n,duplex:o,initiator:!0,targetPinnedPeerId:t.targetPeerId,signal:a}),l=new Zx(new Wx(c.duplex),n,c.authenticatedPeerId);if(t.pairingCode)try{await l.request({type:"pair",code:t.pairingCode})}catch(d){throw l.close(zt(d)),d}return l}catch(c){throw r.close(),c}finally{clearTimeout(i)}}const au=256*1024,Jx=1024*1024;class Qx extends EventTarget{constructor(e,n,r=o=>new WebSocket(o)){if(super(),this.url=e,!/^[a-zA-Z0-9_.:-]{1,160}$/.test(n))throw new Error("Invalid target identity");this.upstream=r(e),this.deadline=setTimeout(()=>this.fail("Relay connection timed out"),2e4),this.upstream.addEventListener("message",o=>{if(this.readyState!==3)try{if(typeof o.data!="string"||new TextEncoder().encode(o.data).length>au)throw new Error("Invalid relay envelope");const s=JSON.parse(o.data);if(s.type==="ready"&&!this.requested){this.requested=!0,this.transmit({type:"open",streamId:this.streamId,serviceId:n});return}if(s.streamId!==this.streamId)return;if(s.type==="opened"&&this.readyState===0){clearTimeout(this.deadline),this.readyState=1;const l=new Event("open");this.dispatchEvent(l),this.onopen?.(l);return}if(s.type==="close"){this.finish(1001,"Relay route closed"),this.upstream.close();return}if(s.type!=="data"||this.readyState!==1||s.encoding!=="base64"||typeof s.payload!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(s.payload))throw new Error("Invalid ciphertext relay frame");const i=_p(s.payload),a=this.binaryType==="blob"?new Blob([i]):i.buffer,c=new MessageEvent("message",{data:a});this.dispatchEvent(c),this.onmessage?.(c)}catch{this.fail("Relay protocol rejected frame")}}),this.upstream.addEventListener("close",o=>this.finish(o.code||1006,"Relay disconnected")),this.upstream.addEventListener("error",()=>this.fail("Relay transport unavailable"))}url;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;protocol="";extensions="";binaryType="arraybuffer";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;upstream;streamId=crypto.randomUUID();requested=!1;deadline;get bufferedAmount(){return this.upstream.bufferedAmount}transmit(e){const n=JSON.stringify(e);if(this.upstream.readyState!==1||this.upstream.bufferedAmount+n.length>Jx||n.length>au)throw new Error("Relay unavailable or congested");this.upstream.send(n)}send(e){if(this.readyState!==1)throw new Error("Relay socket is not open");let n;if(ArrayBuffer.isView(e))n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof ArrayBuffer)n=new Uint8Array(e);else throw new Error("Relay secure transport requires binary bytes");try{this.transmit({type:"data",streamId:this.streamId,encoding:"base64",payload:Bp(n)})}catch(r){throw this.fail("Relay transport congested"),r}}close(e=1e3,n=""){if(this.readyState!==3){try{this.requested&&this.transmit({type:"close",streamId:this.streamId})}catch{}this.finish(e,n),this.upstream.close()}}fail(e){if(this.readyState===3)return;const n=new Event("error");this.dispatchEvent(n),this.onerror?.(n),this.finish(1006,e),this.upstream.close()}finish(e,n){if(this.readyState===3)return;clearTimeout(this.deadline),this.readyState=3;const r=new CloseEvent("close",{code:e,reason:n,wasClean:e===1e3});this.dispatchEvent(r),this.onclose?.(r)}}function Mp(t){return e=>new Qx(e,t)}function eE(t){if(typeof t!="string"||!t.startsWith("/api/")||/[\\\x00-\x20\x7f#]/.test(t))return null;const e=t.split("?")[0];if(e.includes("//"))return null;try{const r=e.split("/").map((o,s)=>{if(s===0||o===""&&s===e.split("/").length-1)return o;const i=decodeURIComponent(o);if(!i||i==="."||i===".."||/[\\/\x00-\x1f\x7f]/.test(i)||/%[a-f0-9]{2}/i.test(i))throw new Error("Ambiguous API path");return i}).join("/");return r.endsWith("/")&&!r.startsWith("/api/terminal/fs/preview/")?null:r}catch{return null}}function tE(t){if(!("serviceWorker"in navigator))return()=>{};const e=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/")||e.size>=32||typeof i!="string"||c!==void 0&&(!(c instanceof ArrayBuffer)||c.byteLength>5*1024*1024)){o.postMessage({type:"error"}),o.close();return}if(d!==void 0&&(typeof d!="string"||!d.endsWith("/")||!/^\/api\/terminal\/fs\/preview\/[a-f0-9]{32}\//.test(d)||!["GET","HEAD"].includes(i)||!eE(u.pathname)?.startsWith(d))){o.postMessage({type:"error"}),o.close();return}const f=new AbortController;let h,g,m=!1,b=!1;const w=()=>{b||(b=!0,e.delete(w),f.abort(),h?.cancel().catch(()=>{}),o.close())};e.add(w),o.onmessage=R=>{if(R.data?.type==="cancel"){w();return}R.data?.type!=="pull"||m||b||(m=!0,(async()=>{if(!h){o.postMessage({type:"end"}),w();return}if(!g?.length){const k=await h.read();if(k.done){o.postMessage({type:"end"}),w();return}g=k.value}const y=g.slice(0,64*1024);g=g.subarray(y.length),o.postMessage({type:"chunk",data:y.buffer},[y.buffer])})().catch(()=>{o.postMessage({type:"error"}),w()}).finally(()=>{m=!1}))},o.onmessageerror=w,o.start(),(async()=>{const R=await t();if(b)return;if(l&&l!==R.targetPeerId)throw new Error("Preview target changed");const y=await R.fetch(u.pathname+u.search,{method:i,headers:a,body:["GET","HEAD"].includes(i)?void 0:c,signal:f.signal});if(b){await y.body?.cancel();return}h=y.body?.getReader();const k={};y.headers.forEach((N,x)=>{k[x]=N}),o.postMessage({type:"head",status:y.status,headers:k,bodyless:!h,targetPeerId:R.targetPeerId})})().catch(()=>{b||(o.postMessage({type:"error"}),w())})};return navigator.serviceWorker.addEventListener("message",n),()=>{navigator.serviceWorker.removeEventListener("message",n);for(const r of[...e])r()}}class et extends Error{constructor(){super("Device authorization expired or revoked")}}const Ho=new WeakMap;function yr(t,e={}){const n=Ho.get(t);if(!t.closed&&n&&(!n.settled||Date.now()-n.at<(e.maxAgeMs??1e3)))return n.pending;const r={at:Date.now(),settled:!1,pending:void 0},o=nE(t,e.timeoutMs??5e3).then(s=>(r.at=Date.now(),r.settled=!0,s),s=>{throw Ho.get(t)===r&&Ho.delete(t),s});return r.pending=o,Ho.set(t,r),o}async function nE(t,e){const n=await t.request({type:"permissions"},{timeoutMs:e});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 et;return{fullService:o,grants:r,canManage:o&&r.length>0||r.some(s=>s.actions.includes("authorization.manage"))}}const jp="termdock-secure-last-path:",rE=10*6e4;function Up(t){try{const e=JSON.parse(sessionStorage.getItem(jp+t)||"null");return e&&typeof e.key=="string"&&Date.now()-e.at<rE?e.key:void 0}catch{return}}function rc(t,e){try{sessionStorage.setItem(jp+t,JSON.stringify({key:e,at:Date.now()}))}catch{}}function $p(t,e,n=!1){return new Promise((r,o)=>{let s=0,i=0,a=!1,c,l;const d=new Set,u=()=>{clearTimeout(l);for(const h of d)h.abort();d.clear()},f=()=>{if(a)return;if(s>=t.length){i||(a=!0,u(),o(c||new Error("没有可用的连接路线。")));return}if(i>=(n?1:2))return;const h=t[s++],g=performance.now(),m=w=>{performance.getEntriesByName("termdock:connection-path").length>64&&performance.clearMeasures("termdock:connection-path"),performance.measure("termdock:connection-path",{start:g,end:performance.now(),detail:{path:h.key.startsWith("relay:")?"relay":"direct",ok:w}})},b=new AbortController;d.add(b),i++,h.run(b.signal).then(w=>{if(m(!0),d.delete(b),a){e(w);return}a=!0,u(),r({value:w,key:h.key})},w=>{if(m(!1),d.delete(b),i--,!a){if(c=w,w instanceof et){a=!0,u(),o(w);return}f()}}),clearTimeout(l),!n&&s<t.length&&(l=setTimeout(f,400))};f()})}const oE=3,sE=1/0,iE=10,Hp="termdock-secure-workspace-limit";function qp(t){return t===1/0||Number.isInteger(t)&&t>=3&&t<=iE}function aE(){try{const t=localStorage.getItem(Hp),e=t==="unlimited"?1/0:Number(t);if(qp(e))return e}catch{}return navigator.maxTouchPoints>0?oE:sE}function cE(t,e,n,r){if(t.length<=r)return t;const o=new Set(["root",e,...n?[n]:[]]),s=[...t].reverse().sort((i,a)=>a.touchedAt-i.touchedAt);for(const i of s){if(o.size>=r)break;o.add(i.key)}return t.filter(i=>o.has(i.key))}const Kp="termdock-workspace",fo="termdock:workspace-visibility",oc="termdock:workspace-activate";function ii(){return window.parent!==window&&location.pathname==="/workspace.html"&&new URLSearchParams(location.search).get(Kp)||"root"}let cu,lu;function ht(){try{if(window.parent===window)return window.__termdockWorkspaceHost;const t=window.parent.__termdockWorkspaceHost;return t&&t!==cu&&(cu=t,lu={...t,subscribe(e){const n=t.subscribe(e,ii()),r=o=>{o.persisted||n()};return window.addEventListener("pagehide",r),()=>{n(),window.removeEventListener("pagehide",r)}}}),t?lu:void 0}catch{return}}function Qo(){const t=ht();return!t||t.snapshot().activeKey===ii()}function _s(t,e=!0){return ht()?.activate(t,e)??!1}function Un(t){ht()?.report(ii(),t)}const sc="termdock-secure-workspace-session:",zp="termdock-secure-last-workspace";function lE(){for(const t of["sessionStorage","localStorage"])try{const e=window[t].getItem(zp);if(e)return e}catch{}return null}function dE(t){for(const e of["sessionStorage","localStorage"])try{window[e].setItem(zp,t)}catch{}}function aR(t){if(t)try{const e=JSON.parse(localStorage.getItem(sc+t)||"null");return localStorage.removeItem(sc+t),e&&typeof e.sessionId=="string"&&Date.now()-e.at<6e4?e.sessionId:void 0}catch{return}}function uE(t){if(window.parent!==window||window.termdockDesktop)return;if(window.__termdockWorkspaceHost)return window.__termdockWorkspaceHost;let e={activeKey:"root",items:[{key:"root",service:t,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]};try{const u=lE(),f=t&&u!==t.targetPeerId?mn().find(h=>h.targetPeerId===u):void 0;f?.targetPeerId&&(e={activeKey:f.targetPeerId,items:[...e.items,{key:f.targetPeerId,service:f,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]})}catch{}let n=aE(),r=e.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=cE(e.items,e.activeKey,r,n),f=new Set(u.map(h=>h.key));e={...e,items:u};for(const[h,g]of o)g&&!f.has(g)&&o.delete(h);for(const h of s.keys())f.has(h)||s.delete(h);for(const h of i)f.has(h)||i.delete(h)},l=(u,f)=>{try{const h=f.document.createEvent("CustomEvent");if(h.initCustomEvent(fo,!1,!1,{active:e.activeKey===u}),f.dispatchEvent(h),e.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(oc,!1,!1),f.dispatchEvent(m)}}else f.document.activeElement?.blur?.()}catch{}},d={snapshot:()=>e,subscribe:(u,f)=>(o.set(u,f),()=>{o.delete(u)}),present(u){r=u},retentionLimit:()=>n,setRetentionLimit(u){if(qp(u)){n=u;try{localStorage.setItem(Hp,u===1/0?"unlimited":String(u))}catch{}c(),a()}},activate(u,f=!0){const h=zs(u);if(!h?.targetPeerId)return!1;const g=e.items.find(w=>w.service?.targetPeerId===h.targetPeerId),m=g?.key||h.targetPeerId,b=g?{...g,service:h,touchedAt:Date.now()}:{key:m,service:h,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()};e={activeKey:m,items:g?e.items.map(w=>w===g?b:w):[...e.items,b]},c(),dE(h.targetPeerId),f&&i.add(m),a();for(const[w,R]of s)l(w,R);return!0},report(u,f){const h=e.items.find(m=>m.key===u);if(!h||f.service&&h.service?.targetPeerId&&f.service.targetPeerId!==h.service.targetPeerId)return;const g={...h,...f};JSON.stringify(g)!==JSON.stringify(h)&&(e={...e,items:e.items.map(m=>m===h?g:m)},a())},attach(u,f){f&&e.items.some(h=>h.key===u)?(s.set(u,f),l(u,f)):s.delete(u)},focusSession(u,f){const h=mn().find(m=>m.targetPeerId===u);if(!h)return!1;try{localStorage.setItem(sc+u,JSON.stringify({sessionId:f,at:Date.now()}))}catch{return!1}d.activate(h,!1);const g=s.get(e.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 qi;async function tt(){return qi||(qi=(async()=>{const t=await new Promise((e,n)=>{const r=indexedDB.open("termdock-device-identity",1);r.onupgradeneeded=()=>r.result.createObjectStore("keys"),r.onsuccess=()=>e(r.result),r.onerror=()=>n(r.error)});try{const e=await new Promise((o,s)=>{const i=t.transaction("keys").objectStore("keys").get("identity");i.onsuccess=()=>o(i.result),i.onerror=()=>s(i.error)});if(e)return su(e);const n=await Tp();let r=n;return await new Promise((o,s)=>{const i=t.transaction("keys","readwrite"),a=i.objectStore("keys"),c=a.get("identity");c.onsuccess=()=>{typeof c.result=="string"?r=su(c.result):a.put(Mx(n),"identity")},i.oncomplete=()=>o(),i.onerror=()=>s(i.error)}),r}finally{t.close()}})()),qi}const Je="termdock:secure-state";let J,$n,Me,fr="direct",es=!1,du=0,ts=!1,uu=-1/0;const hr=globalThis.fetch.bind(globalThis);function re(){return Fc()}function rn(){return J}function fE(){return Me}function Wp(){J?.close(),Me?.close(),J=void 0,Me=void 0}async function Vp(){const t=await hr("/api/auth/status",{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error("Failed to query auth status");return t.json()}async function hE(){if(re()){await st();return}if((await Vp()).enabled)return;const t=await hr("/api/auth/open/parameters",{cache:"no-store"});if(!t.ok)throw new Error("Open service unavailable");const{serviceIdentity:e}=await t.json();if(typeof e!="string"||!e)throw new Error("Invalid service identity");await Qe({url:location.origin,targetPeerId:e,serviceName:location.hostname})}async function pE(t,e){const{startPasswordBootstrap:n,finishPasswordBootstrap:r}=await Jt(async()=>{const{startPasswordBootstrap:l,finishPasswordBootstrap:d}=await import("./passwordBootstrap-kiljsfOw.js");return{startPasswordBootstrap:l,finishPasswordBootstrap:d}},__vite__mapDeps([0,1,2,3])),o=l=>t===location.origin?l:new URL(l,t).href,s=async(l,d)=>{const u=await hr(o(l),{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(15e3),...d?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}:{}});if(!u.ok)throw new Error(u.status===429?"尝试次数较多,请稍后再试。":u.status===401?"密码不正确,请重新输入。":"暂时无法登录这台服务,请稍后重试。");return u.json()},{saltHex:i}=await s("/api/auth/password/parameters"),a=await tt(),c=await n(e,i);try{const l=await s("/api/auth/password/start",{startLoginRequest:c.startLoginRequest,clientIdentity:a.peerId});let d;try{d=await r(c,l,{clientIdentity:a.peerId,origin:location.origin})}catch{throw new Error("密码不正确,或服务身份无法验证。请检查后重试。")}return await s("/api/auth/password/finish",{attemptId:d.attemptId,finishLoginRequest:d.finishLoginRequest}),{url:t,targetPeerId:d.serverIdentity,serviceName:new URL(t).host,serviceOrigin:t}}finally{c.passwordKey=""}}async function pl(t,e){const n=re();if(n&&(n.serviceOrigin||n.url)===t)return await ic(n,e),n;try{return await pE(t,e)}catch(r){if(!(r instanceof TypeError)&&!(r instanceof DOMException))throw r;const o=(await Ke()).find(i=>i.targetPeerId&&(i.serviceOrigin||i.url)===t);if(!o?.targetPeerId)throw new Error("暂时连不上这台服务,请检查地址和网络。");const s={...o,targetPeerId:o.targetPeerId,serviceName:o.label};return await ic(s,e),s}}async function ic(t,e){const n=await gl(t),{startPasswordBootstrap:r,finishPasswordBootstrap:o}=await Jt(async()=>{const{startPasswordBootstrap:i,finishPasswordBootstrap:a}=await import("./passwordBootstrap-kiljsfOw.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(e,String(i.saltHex));const a=await n.request({type:"password-start",startLoginRequest:s.startLoginRequest,origin:location.origin}),c=await o(s,a,{clientIdentity:(await tt()).peerId,origin:location.origin});if(c.serverIdentity!==t.targetPeerId)throw new Error("服务身份发生变化。");await n.request({type:"password-finish",attemptId:c.attemptId,finishLoginRequest:c.finishLoginRequest})}catch{throw new Error("暂时无法登录,请检查目标服务密码与入口授权后重试。")}finally{s&&(s.passwordKey=""),n.close()}}async function gE(t){try{const e=re(),n=e?.serviceOrigin||location.origin,r=await pl(n,t);return await Qe({...r,routes:e?.routes,serviceName:e?.serviceName||r.serviceName}),Response.json({ok:!0})}catch(e){return Response.json({error:e instanceof Error?e.message:"暂时无法登录,请重试。",code:"INVALID_PASSWORD"},{status:401})}}async function fu(t,e){const n=_e(t),r=(await Ke()).find(i=>(i.serviceOrigin||i.url)===n&&i.targetPeerId);if(e===void 0&&r?.targetPeerId)try{return await Qe({...r,targetPeerId:r.targetPeerId,serviceName:r.label}),{}}catch(i){if(!(i instanceof et))throw i}if(e!==void 0){const i=await pl(n,e);if(r?.targetPeerId&&r.targetPeerId!==i.targetPeerId)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await Qe({...i,routes:r?.routes,serviceName:r?.label||i.serviceName}),{}}const o=await hr(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 Qe({url:n,targetPeerId:s,serviceName:r?.label||new URL(n).host,serviceOrigin:n}),{}}function Zt(t){const e=[...t.routes||[]];if(t.entryServiceId&&t.entryServiceId!==t.targetPeerId&&e.unshift({url:t.url,targetPeerId:t.entryServiceId}),!e.length&&t.routes===void 0)try{const n=JSON.parse(localStorage.getItem(Dc)||"null");n&&n.targetPeerId!==t.targetPeerId&&new URL(n.url).host===new URL(t.url).host&&e.push(n)}catch{}return e.flatMap((n,r)=>{try{return n.targetPeerId&&n.targetPeerId!==t.targetPeerId&&e.findIndex(o=>o.targetPeerId===n.targetPeerId)===r?[{url:_e(n.url),targetPeerId:n.targetPeerId}]:[]}catch{return[]}}).slice(0,4)}function br(t){const e=Zt(t),n=[t.serviceOrigin||t.url,...(t.routes||[]).slice(0,4).filter(o=>o.targetPeerId===t.targetPeerId).map(o=>o.url)],r=new Set;for(const o of n)try{const s=_e(o);e.some(i=>i.url===s)||r.add(s)}catch{}return[...r]}function vn(t){const e=new URL("/api/federation/secure",_e(t));return e.protocol=e.protocol==="https:"?"wss:":"ws:",e.href}async function Qt(t,e){return bn({url:vn(t.url),targetPeerId:t.targetPeerId,identity:await tt(),signal:e?AbortSignal.any([e,AbortSignal.timeout(5e3)]):AbortSignal.timeout(5e3)})}async function gl(t,e){const n=await tt(),r=br(t).map(i=>({key:`direct:${i}`,run:a=>bn({url:vn(i),targetPeerId:t.targetPeerId,identity:n,signal:AbortSignal.any([a,AbortSignal.timeout(8e3),...e?[e]:[]])})}));for(const i of Zt(t))r.push({key:`relay:${i.targetPeerId}:${i.url}`,run:async a=>{e&&(a=AbortSignal.any([a,e]));const c=[J,Me].find(d=>d&&!d.closed&&d.targetPeerId===i.targetPeerId),l=c||await Qt(i,a);try{if(a.aborted)throw a.reason;const d=await l.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(a.aborted)throw a.reason;if(typeof d.routeToken!="string")throw new Error("入口未允许此设备连接该服务。");const u=new URL(vn(i.url));return u.pathname="/api/federation/relay",u.searchParams.set("routeToken",d.routeToken),await bn({url:u.href,targetPeerId:t.targetPeerId,identity:n,socketFactory:Mp(t.targetPeerId),signal:AbortSignal.any([a,AbortSignal.timeout(8e3)])})}finally{c||l.close()}}});const o=Up(t.targetPeerId);r.sort((i,a)=>+(a.key===o)-+(i.key===o));const s=await $p(r,i=>i.close());return rc(t.targetPeerId,s.key),s.value}async function mE(t,e){const n=await gl(t,e);try{const o=(await n.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node;if(o?.serviceId!==t.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");return{...o,serviceId:t.targetPeerId}}finally{n.close()}}async function wE(t,e){const n=await gl(t,e),r=()=>n.close();e.addEventListener("abort",r,{once:!0});try{if(e.aborted||(await yr(n,{timeoutMs:3e3}),e.aborted))throw e.reason;return n}catch(o){throw n.close(),o}finally{e.removeEventListener("abort",r)}}async function Qe(t,e={}){const n=J,r=Me,o=await tt(),s=_e(t.serviceOrigin||t.url),i=(await Ke()).find(w=>w.targetPeerId===t.targetPeerId),a={...t,routes:t.routes??i?.routes},c=Zt(a),l=br(a);let d,u,f=t.pairingCode,h="direct";const g=new Set,m=new Map,b=async(w,R)=>{if(n&&!n.closed&&n.targetPeerId===w.targetPeerId)return n;if(r&&!r.closed&&r.targetPeerId===w.targetPeerId)return r;const y=m.get(w.targetPeerId);if(y&&!y.closed)return y;const k=await Qt(w,R);return g.add(k),m.set(w.targetPeerId,k),k};try{if(t.routeCode&&t.entryServiceId){const S=c.find(_=>_.targetPeerId===t.entryServiceId);if(!S)throw new Error("邀请缺少入口信息。");if((await(await b(S)).request({type:"route-pair",code:t.routeCode})).serviceId!==t.targetPeerId)throw new Error("邀请的目标服务不一致。");t.routeOnly&&await Tt({id:t.targetPeerId,url:s,label:t.serviceName||new URL(s).host,targetPeerId:t.targetPeerId,serviceOrigin:s,routes:c})}const w=[],R=async(S,v)=>{const A=()=>S.close();v.addEventListener("abort",A,{once:!0});try{if(v.aborted||(await yr(S),v.aborted))throw v.reason}catch(_){throw S.close(),_}finally{v.removeEventListener("abort",A)}};for(const S of l)w.push({key:`direct:${S}`,run:async v=>{const A=await bn({url:vn(S),targetPeerId:t.targetPeerId,pairingCode:f,identity:o,signal:AbortSignal.any([v,AbortSignal.timeout(8e3)])});return f=void 0,await R(A,v),{client:A,path:"direct"}}});for(const S of c)w.push({key:`relay:${S.targetPeerId}:${S.url}`,run:async v=>{let A,_;try{if(A=await b(S,v),v.aborted)throw v.reason;const B=await A.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(v.aborted)throw v.reason;if(typeof B.routeToken!="string"||!B.routeToken)throw new Error("入口未允许此设备连接该服务。");const C=new URL(vn(S.url));return C.pathname="/api/federation/relay",C.searchParams.set("routeToken",B.routeToken),_=await bn({url:C.href,targetPeerId:t.targetPeerId,pairingCode:f,identity:o,socketFactory:Mp(t.targetPeerId),signal:AbortSignal.any([v,AbortSignal.timeout(8e3)])}),f=void 0,await R(_,v),{client:_,entry:A,path:"relay"}}catch(B){throw _?.close(),A&&A!==r&&A!==n&&A.close(),B}}});const y=Up(t.targetPeerId);w.sort((S,v)=>+(v.key===y)-+(S.key===y));const k=await $p(w,S=>{S.client.close(),S.entry&&S.entry!==n&&S.entry!==r&&S.entry.close()},!!f);if(d=k.value.client,u=k.value.entry,h=k.value.path,e.renewIfCurrent){if(J!==e.renewIfCurrent||n!==e.renewIfCurrent||n.closed||!n.canSwitchTransport||re()?.targetPeerId!==t.targetPeerId){d.close();for(const S of g)S!==Me&&S!==J&&S.close();return J??n}J=d,fr=h,Me=u,rc(t.targetPeerId,k.key),n.retire();for(const S of new Set([r,...g]))S&&S!==n&&S!==d&&S!==u&&S.close();return window.dispatchEvent(new Event(Je)),d}if(rc(t.targetPeerId,k.key),J!==n&&J&&!J.closed&&J.targetPeerId===t.targetPeerId){d.close();for(const S of g)S!==Me&&S.close();return J}h==="direct"&&new URL(s).host===location.host&&Mm(t.targetPeerId);const N=(await Ke()).find(S=>S.targetPeerId===t.targetPeerId||!S.targetPeerId&&(S.serviceOrigin||S.url)===s),x=N?.label||t.serviceName||new URL(s).host,T={url:s,targetPeerId:t.targetPeerId,serviceName:x,serviceOrigin:s,routes:a.routes??c};if(await(e.rememberOnly?Um:Tt)({id:N?.id||t.targetPeerId,...T,label:x}),Wn!=="unpaired"&&Wn!==t.targetPeerId&&ht()&&_s({id:N?.id||t.targetPeerId,...T,label:x})){d.close();for(const S of g)S!==n&&S!==r&&S.close();return n||d}Rf(T),J=d,fr=h,Me=u;for(const S of new Set([n,r,...g]))S&&S!==d&&S!==u&&S.close();return Wn!==t.targetPeerId?(location.reload(),new Promise(()=>{})):(window.dispatchEvent(new Event(Je)),d)}catch(w){d?.close();for(const R of g)R!==r&&R.close();throw w}}async function yE(){const t=J,e=re();if(!(ts||es||$n||!t?.renewalDue||!t.canSwitchTransport||!e||performance.now()-uu<3e4)){uu=performance.now(),ts=!0;try{await Qe(e,{renewIfCurrent:t})}catch(n){console.debug("[connection] renewal deferred",{reason:n instanceof Error?n.message:"unknown"})}finally{ts=!1}}}async function bE(){const t=J,e=re();if(Date.now()-du<6e4||ts||es||fr!=="relay"||!t||t.closed||!t.canSwitchTransport||!e?.serviceOrigin)return;es=!0,du=Date.now();let n;try{for(const o of br(e))try{n=await bn({url:vn(o),targetPeerId:e.targetPeerId,identity:await tt(),signal:AbortSignal.timeout(3e3)}),await yr(n);break}catch(s){if(n?.close(),n=void 0,s instanceof et)throw s}if(!n||J!==t||!t.canSwitchTransport)return;const r=Me;J=n,n=void 0,Me=void 0,fr="direct",t.close(),r?.close(),window.dispatchEvent(new Event(Je))}catch(r){r instanceof et&&J===t&&(Wp(),window.dispatchEvent(new Event("auth:unauthorized")))}finally{n?.close(),es=!1}}function vE(){return fr}async function SE(t){return t?(t.throwIfAborted(),new Promise((e,n)=>{const r=()=>n(t.reason);t.addEventListener("abort",r,{once:!0}),st().then(o=>{t.removeEventListener("abort",r),t.aborted?n(t.reason):e(o)},o=>{t.removeEventListener("abort",r),n(o)})})):st()}async function st(){if(J&&!J.closed){const e=J;return yE(),e}if(J=void 0,$n)return $n;const t=re();if(!t)throw new Error("DEVICE_PAIRING_REQUIRED");return $n=Qe(t,{rememberOnly:!0}).catch(e=>{if(J&&!J.closed&&J.targetPeerId===t.targetPeerId)return J;throw e}).finally(()=>{$n=void 0}),$n}function Gp(t){const e=new URL(t,location.href);if(J&&!J.closed)return J.openSocket(e.pathname+e.search);let n;const r=new Fp(t,o=>n?.send(o),()=>n?.close());return st().then(o=>{r.readyState!==3&&(n=o.openSocket(e.pathname+e.search),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 xE(){tE(st),window.fetch=async(t,e)=>{const n=new URL(t instanceof Request?t.url:String(t),location.href);if(!n.pathname.startsWith("/api/"))return hr(t,e);if(n.origin!==location.origin)throw new Error("Remote business API requires a paired encrypted service");if(n.pathname==="/api/meta")return hr(t,e);if(n.pathname==="/api/auth/status"){if(!re()){const s=await Vp();return Response.json({enabled:s.enabled,authenticated:!1})}try{const s=await yr(await st());return Response.json({enabled:s.grants.length>0,authenticated:!0})}catch(s){if(s instanceof et)return Response.json({enabled:!0,authenticated:!1});throw s}}if(n.pathname==="/api/auth/login"){const i=await new Request(t instanceof Request?t:n.href,e).json();return gE(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 J&&!J.closed&&await J.request({type:"logout"}),J?.close(),Me?.close(),J=void 0,Me=void 0,Fm(),location.reload(),Response.json({ok:!0});const r=e?.signal!==void 0?e.signal:t instanceof Request?t.signal:void 0,o=await SE(r);return t instanceof Request?o.fetch(t,e):o.fetch(n.pathname+n.search,e)}}async function EE(t){if(!t.targetPeerId)throw new Error("请先连接这台服务,再查看可中转的服务。");for(const e of br({...t,targetPeerId:t.targetPeerId})){let n;const r={url:e,targetPeerId:t.targetPeerId};try{n=await Qt(r)}catch{continue}try{const o=await n.request({type:"route-targets"},{timeoutMs:5e3});if(!Array.isArray(o.items))throw new Error("入口服务需要更新后才能查看中转列表。");return{route:r,canManage:o.canManage===!0,items:o.items}}catch(o){throw o instanceof Error&&/UNKNOWN|UNSUPPORTED/i.test(o.message)?new Error("入口服务需要更新后才能查看中转列表。"):o}finally{n.close()}}throw new Error("暂时连不上中转入口,请检查地址和网络后重试。")}async function AE(t,e){const n=await Qt(t);try{const r=await n.request({type:"route-targets"},{timeoutMs:5e3}),o=(Array.isArray(r.items)?r.items:[]).find(c=>c.serviceId===e);if(!o)throw new Error("该服务已不可见,请刷新列表或请入口管理员授权。");if(!o.available)throw new Error("入口暂时无法中转到这台服务,请稍后重试。");const s=(await Ke()).find(c=>c.targetPeerId===o.serviceId),i=[t,...(s?.routes||[]).filter(c=>c.targetPeerId!==t.targetPeerId)];if(i.length>4)throw new Error("这台服务已保存 4 个备用连接,请先移除一个后重试。");if(!o.authorized){if(!r.canManage)throw new Error("请先让入口管理员授权此设备。");await n.request({type:"route-grant",serviceId:o.serviceId,subjectId:(await tt()).peerId})}const a=s?.serviceOrigin||s?.url||o.url||t.url;return{url:a,serviceOrigin:a,targetPeerId:o.serviceId,serviceName:s?.label||o.label||(o.url?new URL(o.url).host:`中转服务 ${o.serviceId.slice(0,8)}`),routes:i}}finally{n.close()}}async function kE(t,e){const n=await Qt(t);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),o=(await tt()).peerId;return{canManage:r.canManage===!0,grants:(Array.isArray(r.grants)?r.grants:[]).filter(s=>s.subjectId===o&&s.targetServiceId===e)}}finally{n.close()}}async function CE(t,e,n){if(n!==void 0&&(await pl(_e(e.url),n)).targetPeerId!==e.targetPeerId)throw new Error("入口服务的身份已改变,请重新连接并确认。");const r=await Qt(e);try{await r.request({type:"route-grant",serviceId:t.targetPeerId,subjectId:(await tt()).peerId,url:_e(t.serviceOrigin||t.url)})}finally{r.close()}}async function IE(t,e){const n=await Qt(e);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),o=(await tt()).peerId,s=(Array.isArray(r.grants)?r.grants:[]).filter(i=>i.subjectId===o&&i.targetServiceId===t&&i.active);for(const i of s)await n.request({type:"route-revoke",grantId:i.id})}finally{n.close()}}async function Xp(t,e){const n=await Qt(e);try{const r=await n.request({type:"route-invite-create",serviceId:t.targetPeerId});if(typeof r.routeCode!="string"||typeof r.expiresAt!="number")throw new Error("暂时无法生成备用连接邀请。");return{routeCode:r.routeCode,expiresAt:r.expiresAt}}finally{n.close()}}async function ns(t,e){const n=(await Ke()).find(o=>o.id===t.id||t.targetPeerId&&o.targetPeerId===t.targetPeerId)||t;await Tt({...n,url:n.serviceOrigin||n.url,entryServiceId:void 0,routes:e});const r=re();r&&r.targetPeerId===t.targetPeerId&&Rf({...r,url:r.serviceOrigin||r.url,entryServiceId:void 0,routes:e})}async function RE(t,e){const n=t.targetPeerId;if(!n)throw new Error("请先连接这台服务,再添加备用地址。");let r;try{r=_e(e)}catch{throw new Error("请输入有效的 HTTPS 地址,例如 https://电脑地址:9834。")}const o=async()=>(await Ke()).find(a=>a.targetPeerId===n)||t,s=a=>{const c=a.routes??Zt({...a,targetPeerId:n});if(_e(a.serviceOrigin||a.url)===r||c.some(l=>_e(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 bn({url:vn(r),targetPeerId:n,identity:await tt(),signal:AbortSignal.timeout(5e3)}),await yr(i)}catch(l){throw l instanceof et?new Error("这台服务尚未授权当前设备,请先恢复设备授权。"):new Error("无法验证这个地址。请确认能访问该地址、HTTPS 证书受信任,且运行的是同一台 Termdock 服务。")}const a=await o(),c=s(a);if(await ns(a,c),re()?.targetPeerId===n&&Wn===n&&(!J||J.closed)){const l=J,d=Me;J=i,i=void 0,Me=void 0,fr="direct",l?.close(),d?.close(),window.dispatchEvent(new Event(Je))}return c}finally{i?.close()}}async function hu(t,e){await ic(t,e),await Qe({...t,pairingCode:void 0,routeCode:void 0})}function TE(){let t=!1,e=!1,n=!1,r;const o=new Map,s=new Set,i=new Map,a=async(f,h,g)=>{const m=JSON.stringify(g);if(o.get(h.serviceId)===m)return;const b=AbortSignal.timeout(1e4),w=await f.fetch("/api/csrf-token",{signal:b});if(!w.ok)throw new Error("CONNECTION_AUTHORIZATION_REQUIRED");const R=await w.json();if(typeof R.csrfToken!="string")throw new Error("INVALID_CSRF_TOKEN");const y=await f.fetch("/api/terminal/operations/collaboration-connections",{method:"POST",signal:b,headers:{"Content-Type":"application/json","X-XSRF-TOKEN":R.csrfToken},body:JSON.stringify({origin:h.origin,nodes:g})});if(!y.ok){const k=await y.json().catch(()=>({}));throw new Error(k.error||`HTTP_${y.status}`)}o.set(h.serviceId,m)},c=async()=>{if(t){n=!0;return}const f=re(),h=rn();if(!(e||!f||!h||h.closed)){t=!0,n=!1;try{let g;const m=await Promise.race([Ke(),new Promise((N,x)=>{g=setTimeout(()=>x(new Error("SERVICE_DIRECTORY_TIMEOUT")),8e3)})]).finally(()=>clearTimeout(g));m.some(N=>N.targetPeerId===f.targetPeerId)||m.push({...f,id:f.targetPeerId,label:f.serviceName||f.url});const b=[...new Map(m.filter(N=>!!N.targetPeerId).map(N=>[N.targetPeerId,N])).values()].slice(0,64);if(b.length<2)return;const w=[];for(const N of b)try{const x=`${N.targetPeerId}:${N.serviceOrigin||N.url}`;let T=i.get(x);if(!T){const S=N.targetPeerId===f.targetPeerId?(await h.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node:await mE({...N,targetPeerId:N.targetPeerId},AbortSignal.timeout(8e3));if(S?.serviceId!==N.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");const v=S.origin||N.serviceOrigin||N.url,A=new URL(v);if(A.protocol!=="https:"||A.origin!==v)throw new Error("INVALID_SERVICE_ORIGIN");T={serviceId:S.serviceId,origin:v,...S.caFingerprint256?{caFingerprint256:S.caFingerprint256}:{}},i.set(x,T)}w.push({service:N,node:T})}catch{}if(e||rn()!==h||re()?.targetPeerId!==f.targetPeerId)return;const R=w.find(N=>N.node.serviceId===f.targetPeerId);if(!R||w.length<2){l(3e4);return}const y=w.map(N=>N.node).sort((N,x)=>N.serviceId.localeCompare(x.serviceId));await a(h,R.node,y);let k=w.length<b.length;for(const N of w){if(N===R||o.get(N.node.serviceId)===JSON.stringify(y))continue;let x;try{x=await wE({...N.service,targetPeerId:N.node.serviceId},AbortSignal.timeout(8e3)),await a(x,N.node,y)}catch{let T=s.has(N.node.serviceId);if(!T&&x)try{(await x.request({type:"collaboration-scoped-peer",origin:N.node.origin,node:R.node},{timeoutMs:8e3})).type==="result"&&(s.add(N.node.serviceId),T=!0)}catch{}T||(k=!0)}finally{x?.close()}}window.dispatchEvent(new CustomEvent("termdock:collaboration-enrollment",{detail:{ok:!0}})),k&&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{t=!1,n&&l(100)}}};function l(f=100){e||(clearTimeout(r),r=setTimeout(()=>{c()},f))}const d=()=>{l()},u=Ws(d);window.addEventListener(Je,d),window.addEventListener("termdock:collaboration-enroll",d),window.addEventListener("online",d),window.addEventListener("pageshow",d),window.addEventListener("pagehide",f=>{f.persisted||(e=!0,clearTimeout(r),u(),window.removeEventListener("termdock:collaboration-enroll",d),window.removeEventListener(Je,d),window.removeEventListener("online",d),window.removeEventListener("pageshow",d))}),l()}var qo={},pu;function PE(){if(pu)return qo;pu=1;var t=Rm();return qo.createRoot=t.createRoot,qo.hydrateRoot=t.hydrateRoot,qo}var NE=PE();const LE=If(NE);const Yp=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim();const BE=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const _E=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,r)=>r?r.toUpperCase():n.toLowerCase());const gu=t=>{const e=_E(t);return e.charAt(0).toUpperCase()+e.slice(1)};var Ki={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 OE=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1},DE=O.createContext({}),FE=()=>O.useContext(DE),ME=O.forwardRef(({color:t,size:e,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:h=""}=FE()??{},g=r??u?Number(n??d)*24/Number(e??l):n??d;return O.createElement("svg",{ref:c,...Ki,width:e??l??Ki.width,height:e??l??Ki.height,stroke:t??f,strokeWidth:g,className:Yp("lucide",h,o),...!s&&!OE(a)&&{"aria-hidden":"true"},...a},[...i.map(([m,b])=>O.createElement(m,b)),...Array.isArray(s)?s:[s]])});const Ae=(t,e)=>{const n=O.forwardRef(({className:r,...o},s)=>O.createElement(ME,{ref:s,iconNode:e,className:Yp(`lucide-${BE(gu(t))}`,`lucide-${t}`,r),...o}));return n.displayName=gu(t),n};const jE=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Zp=Ae("arrow-left",jE);const UE=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],$E=Ae("arrow-right",UE);const HE=[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]],qE=Ae("arrow-up-right",HE);const KE=[["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"}]],Jp=Ae("bell-dot",KE);const zE=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Os=Ae("check",zE);const WE=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Qp=Ae("chevron-down",WE);const VE=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Sn=Ae("chevron-right",VE);const GE=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],XE=Ae("chevron-up",GE);const YE=[["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"}]],eg=Ae("copy",YE);const ZE=[["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"}]],tg=Ae("ellipsis",ZE);const JE=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],je=Ae("loader-circle",JE);const QE=[["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"}]],e1=Ae("monitor",QE);const t1=[["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"}]],n1=Ae("pencil",t1);const r1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],ng=Ae("plus",r1);const o1=[["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"}]],ai=Ae("server",o1);const s1=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],rg=Ae("smartphone",s1);const i1=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],a1=Ae("terminal",i1);const c1=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],og=Ae("x",c1),l1={},mu=t=>{let e;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(e):d;if(!Object.is(f,e)){const h=e;e=u??(typeof f!="object"||f===null)?f:Object.assign({},e,f),n.forEach(g=>g(e,h))}},o=()=>e,c={setState:r,getState:o,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(l1?"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=e=t(r,o,c);return c},d1=t=>t?mu(t):mu;var zi={exports:{}},Wi={},Vi={exports:{}},Gi={};var wu;function u1(){if(wu)return Gi;wu=1;var t=_c();function e(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var n=typeof Object.is=="function"?Object.is:e,r=t.useState,o=t.useEffect,s=t.useLayoutEffect,i=t.useDebugValue;function a(u,f){var h=f(),g=r({inst:{value:h,getSnapshot:f}}),m=g[0].inst,b=g[1];return s(function(){m.value=h,m.getSnapshot=f,c(m)&&b({inst:m})},[u,h,f]),o(function(){return c(m)&&b({inst:m}),u(function(){c(m)&&b({inst:m})})},[u]),i(h),h}function c(u){var f=u.getSnapshot;u=u.value;try{var h=f();return!n(u,h)}catch{return!0}}function l(u,f){return f()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?l:a;return Gi.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:d,Gi}var yu;function f1(){return yu||(yu=1,Vi.exports=u1()),Vi.exports}var bu;function h1(){if(bu)return Wi;bu=1;var t=_c(),e=f1();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=e.useSyncExternalStore,s=t.useRef,i=t.useEffect,a=t.useMemo,c=t.useDebugValue;return Wi.useSyncExternalStoreWithSelector=function(l,d,u,f,h){var g=s(null);if(g.current===null){var m={hasValue:!1,value:null};g.current=m}else m=g.current;g=a(function(){function w(x){if(!R){if(R=!0,y=x,x=f(x),h!==void 0&&m.hasValue){var T=m.value;if(h(T,x))return k=T}return k=x}if(T=k,r(y,x))return T;var S=f(x);return h!==void 0&&h(T,S)?(y=x,T):(y=x,k=S)}var R=!1,y,k,N=u===void 0?null:u;return[function(){return w(d())},N===null?void 0:function(){return w(N())}]},[d,u,f,h]);var b=o(l,g[0],g[1]);return i(function(){m.hasValue=!0,m.value=b},[b]),c(b),b},Wi}var vu;function p1(){return vu||(vu=1,zi.exports=h1()),zi.exports}var g1=p1();const m1=If(g1),sg={},{useDebugValue:w1}=We,{useSyncExternalStoreWithSelector:y1}=m1;let Su=!1;const b1=t=>t;function v1(t,e=b1,n){(sg?"production":void 0)!=="production"&&n&&!Su&&(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"),Su=!0);const r=y1(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,n);return w1(r),r}const xu=t=>{(sg?"production":void 0)!=="production"&&typeof t!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof t=="function"?d1(t):t,n=(r,o)=>v1(e,r,o);return Object.assign(n,e),n},ci=t=>t?xu(t):xu,ml=t=>`@collaboration:${t}`,ig=ci(t=>({activePaneId:null,setActivePane:e=>t({activePaneId:e}),docks:{},hosts:{},setDock:(e,n)=>t(r=>{const o={...r.docks};return n?o[e]=n:delete o[e],{docks:o,...!n&&r.activePaneId===ml(e)?{activePaneId:r.docks[e]?.sessionId??null}:{}}}),setHost:(e,n)=>t(r=>{const o={...r.hosts};return n?o[e]=n:delete o[e],{hosts:o}})})),dn=new Map;let eo;function ag(){const t=ig.getState().activePaneId;for(const[n,r]of dn)if(r.requiresFocus&&t===ml(n))return r.receive;const e=dn.get(eo??"");return e&&!e.requiresFocus?e.receive:void 0}function cR(t){const e=dn.get(t);e&&(e.requiresFocus?ig.getState().setActivePane(ml(t)):eo=t)}function S1(t){const e=ag();return!e||!t?!1:(e(t),!0)}function lR(t,e="default",n=!1){dn.set(e,{receive:t,requiresFocus:n}),n||(eo=e);const r=o=>{const{text:s,nonce:i}=o.detail??{};!s||ag()!==t||(t(s),o.stopImmediatePropagation(),i&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:i,ok:!0}})))};return window.addEventListener("termdock-insert-reference",r,!0),()=>{dn.get(e)?.receive===t&&(dn.delete(e),eo===e&&(eo=[...dn.keys()].at(-1))),window.removeEventListener("termdock-insert-reference",r,!0)}}const x1=/^[A-Za-z0-9_@%+=:,./-]$/;function E1(t){return Array.from(t,e=>(e.codePointAt(0)??0)>127||x1.test(e)?e:`\\${e}`).join("")}function A1(t,e){if(!e)return!1;try{const n=new URL(e.serviceOrigin||e.url);return n.origin===t&&/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})$/.test(n.hostname)&&!(e.routes??[]).some(r=>r.targetPeerId!==e.targetPeerId)}catch{return!1}}function k1(t){const e=s=>s.target instanceof Element?s.target.closest("[data-termdock-terminal-dropzone]"):null,n=()=>!A1(location.origin,Fc()),r=s=>{const i=e(s);!i||!n()||!s.dataTransfer?.types.includes("Files")||(s.preventDefault(),s.stopImmediatePropagation(),s.dataTransfer.dropEffect="copy",i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="remote")},o=s=>{const i=e(s),a=Array.from(s.dataTransfer?.files??[]);if(!i||!a.length||!n())return;s.preventDefault(),s.stopImmediatePropagation();const c=i.dataset.termdockTerminalDropzone??"";i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="uploading",Jt(async()=>{const{uploadFiles:l}=await Promise.resolve().then(()=>O2);return{uploadFiles:l}},void 0).then(({uploadFiles:l})=>l("/tmp",a)).then(l=>{if(l.files.length!==a.length||l.files.some(d=>!d.path))throw new Error("Upload did not return every file path");delete i.dataset.nativeFileDrag,delete i.dataset.nativeFileDropState,t({sessionKey:c,paths:l.files.map(d=>d.path)})}).catch(l=>{i.dataset.nativeFileDropState="error",i.dispatchEvent(new CustomEvent("termdock:file-drop-error",{bubbles:!0,detail:l instanceof Error?l.message:"File upload failed"})),window.setTimeout(()=>{i.dataset.nativeFileDropState==="error"&&(delete i.dataset.nativeFileDrag,delete i.dataset.nativeFileDropState)},3e3)})};return window.addEventListener("dragover",r,!0),window.addEventListener("drop",o,!0),()=>{window.removeEventListener("dragover",r,!0),window.removeEventListener("drop",o,!0)}}function nt(){return typeof window>"u"?null:window.termdockDesktop??null}const Xi=new Set;let Eu=!1;function dR(t){const e=nt();if(!e)return()=>{};if(Xi.add(t),!Eu){const n=r=>{if(!S1(r.paths.map(E1).join(" ")+" "))for(const o of Xi)o(r)};k1(n),e.onNativeFileDrop(n),Eu=!0}return()=>{Xi.delete(t)}}function cg(t=navigator.userAgent,e=navigator.maxTouchPoints){const n=/iPad/.test(t)||/Macintosh/.test(t)&&e>1?"iPad":/iPhone/.test(t)?"iPhone":/Android/.test(t)?"Android":/Windows/.test(t)?"Windows":/Macintosh|Mac OS X/.test(t)?"Mac":/Linux/.test(t)?"Linux":"设备",r=/Electron/.test(t)?"Termdock":/Edg\//.test(t)?"Edge":/Firefox|FxiOS/.test(t)?"Firefox":/Chrome|CriOS/.test(t)?"Chrome":/Safari/.test(t)?"Safari":"浏览器";return`${n} · ${r}`}let C1;function I1(){return C1??=(async()=>{const t=navigator.userAgent,[e,n]=cg().split(" · "),r=/(?:Edg|Firefox|FxiOS|Chrome|CriOS|Version)\/([\d.]+)/g,o=[...t.matchAll(r)],s=/(?:CPU (?:iPhone )?OS |Mac OS X |Android )([\d._]+)/.exec(t)?.[1]?.replaceAll("_","."),i={system:`${e}${s?` ${s}`:""}`,client:`${n}${o.length?` ${o.at(-1)[1]}`:""}`,mode:matchMedia("(display-mode: standalone)").matches||navigator.standalone?"已安装的网页应用":"网页"},a=nt();if(a){i.mode="桌面客户端";const l=/Electron\/([\d.]+)/.exec(t)?.[1];i.client=l?`Termdock(Electron ${l})`:"Termdock";try{Object.assign(i,await a.deviceInfo?.())}catch{}return i}const c=navigator.userAgentData;try{const l=await c?.getHighEntropyValues(["model","architecture","bitness","platformVersion"]);typeof l?.model=="string"&&l.model&&(i.model=l.model),typeof l?.architecture=="string"&&l.architecture&&(i.arch=`${l.architecture}${l.bitness?` ${l.bitness} 位`:""}`)}catch{}return i})()}function R1({service:t,onBusyChange:e,onConnect:n,onConnectWithPassword:r}){const[o,s]=O.useState(),[i,a]=O.useState(!0),[c,l]=O.useState(!1),[d,u]=O.useState(""),[f,h]=O.useState(0),[g,m]=O.useState(),[b,w]=O.useState("");O.useEffect(()=>{let k=!1,N=!1,x;a(!0),u(""),s(void 0);const T=async S=>{try{const v=await EE(t);if(k)return;N=!0,s(v),u("")}catch(v){!k&&(!N||S)&&u(v instanceof Error?v.message:"暂时无法读取中转列表,请重试。")}finally{k||(a(!1),x=setTimeout(()=>{T(!1)},2e3))}};return T(!0),()=>{k=!0,clearTimeout(x)}},[t.id,t.url,f]);const R=async k=>{if(!c){l(!0),e(!0),u("");try{await k()}catch(N){u(N instanceof Error?N.message:"暂时无法连接,请重试。")}finally{l(!1),e(!1)}}},y=async k=>{const N=await AE(o.route,k.serviceId);try{await n(N)}catch(x){if(!(x instanceof et))throw x;m(N)}};return p.jsxs("div",{className:"service-form",children:[g?p.jsxs("form",{className:"service-form",onSubmit:k=>{k.preventDefault(),R(async()=>{try{await r?.(g,b)}finally{w("")}})},children:[p.jsxs("p",{className:"service-help",children:["已通过“",t.label,"”连接到“",g.serviceName,"”。请登录目标服务,完成此设备的访问授权。"]}),r?p.jsxs(p.Fragment,{children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"目标服务密码"}),p.jsx("input",{type:"password",autoFocus:!0,required:!0,autoComplete:"current-password",value:b,disabled:c,onChange:k=>w(k.target.value)})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:c||!b,children:c?"正在登录…":"登录并连接"})]}):p.jsx("p",{className:"service-help",children:"请让目标服务管理员邀请此设备后再连接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>{m(void 0),w(""),u(""),h(k=>k+1)},children:"返回中转列表"})]}):p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["通过“",t.label,"”连接下方服务。",o?.canManage?"选择未授权的服务会授权此设备使用该中转。":"这里只显示已授权给此设备的中转。","目标服务会单独验证访问权限。"]}),i?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(je,{size:16,className:"service-spinning"}),"正在读取可中转的服务…"]}):o&&p.jsxs("div",{className:"service-list",children:[o.items.map(k=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:c||!k.available,onClick:()=>{R(()=>y(k))},children:[p.jsx("span",{className:"service-icon",children:p.jsx(ai,{size:19})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:k.label||(k.url?new URL(k.url).host:`中转服务 ${k.serviceId.slice(0,8)}`)}),p.jsx("span",{className:"service-description",children:k.available?k.authorized?"已获中转授权 · 连接":"授权此设备并连接":"中转暂不可用"})]}),p.jsx(Sn,{size:16})]},k.serviceId)),o.items.length===0&&p.jsx("p",{className:"service-empty",children:o.canManage?"暂无可中转的服务。可在本机 Mac 客户端连接目标服务,或在目标服务的“备用连接”中启用本入口。":"暂无已授权的中转服务,请让入口管理员分享备用连接邀请。"})]}),c&&p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(je,{size:16,className:"service-spinning"}),"正在授权并连接目标服务…"]}),!i&&p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>h(k=>k+1),children:"刷新列表"})]}),d&&p.jsx("p",{className:"service-error",role:"alert",children:d})]})}const ac="#termdock-invite=";function lg(t){const e=new URL(t.entryUrl);e.hash="",e.search="",e.pathname="/";const n=new TextEncoder().encode(JSON.stringify(t));return e.hash=ac.slice(1)+btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.href}function Ds(t){const e=new URL(t);if(!["https:","http:"].includes(e.protocol)||!e.hash.startsWith(ac))throw new Error("这不是有效的 Termdock 邀请链接");const n=e.hash.slice(ac.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!==e.origin||o.username||o.password||!["https:","http:"].includes(o.protocol))throw new Error("邀请地址与服务不一致");if(o.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(o.hostname))throw new Error("远程邀请需要 HTTPS");if(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 T1({service:t,onBusyChange:e}){const n={...t,targetPeerId:t.targetPeerId,serviceName:t.label},[r,o]=O.useState(()=>t.routes??Zt(n)),[s,i]=O.useState([]),[a,c]=O.useState(!0),[l,d]=O.useState(!1),[u,f]=O.useState(""),h=L=>{d(L),e(L)},[g,m]=O.useState(),[b,w]=O.useState(""),[R,y]=O.useState(""),[k,N]=O.useState(""),[x,T]=O.useState(!1),[S,v]=O.useState(),[A,_]=O.useState(),[B,C]=O.useState(!1);O.useEffect(()=>{let L=!1;return Ke().then($=>{L||i($.filter(H=>H.targetPeerId&&H.targetPeerId!==t.targetPeerId))}).catch(()=>{L||f("暂时无法读取可用服务。")}).finally(()=>{L||c(!1)}),()=>{L=!0}},[t.targetPeerId]);const E=L=>s.find($=>$.targetPeerId===L.targetPeerId)?.label||new URL(L.url).host,P=async L=>{h(!0),f(""),N("");try{await L()}catch($){const H=$ instanceof Error?$.message:"";f(/AUTHORIZATION|DENIED/.test(H)?"当前设备没有入口管理权限。请让管理员分享备用连接邀请,或使用入口密码授权。":"暂时无法完成。请确认入口能连接目标服务,且目标地址、证书和授权有效。")}finally{h(!1)}},I=async(L,$)=>{const H={url:L.serviceOrigin||L.url,targetPeerId:L.targetPeerId};await P(async()=>{const U=await kE(H,n.targetPeerId);if(!U.grants.some(K=>K.active)){if(!U.canManage&&$===void 0){m(L);return}await CE(n,H,$)}const q=[...r.filter(K=>K.targetPeerId!==H.targetPeerId),H];await ns(t,q),o(q),m(void 0),w("")})};if(A)return p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["把链接发给需要使用此备用连接的人。它只允许通过入口连接“",t.label,"”,对方仍需获得目标服务的访问权限。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用连接邀请"}),p.jsx("input",{readOnly:!0,value:A,onFocus:L=>L.target.select()})]}),p.jsxs("button",{type:"button",className:"service-button service-primary",onClick:()=>{navigator.clipboard.writeText(A).then(()=>C(!0)).catch(()=>f("无法自动复制,请长按链接复制。"))},children:[p.jsx(eg,{size:16}),B?"已复制":"复制邀请链接"]}),p.jsx("button",{type:"button",className:"service-button service-secondary",onClick:()=>{_(void 0),C(!1)},children:"返回备用连接"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});if(g)return p.jsxs("form",{className:"service-form",onSubmit:L=>{L.preventDefault(),I(g,b).finally(()=>w(""))},children:[p.jsxs("p",{className:"service-help",children:["需要“",g.label,"”的管理员授权。若这是你的服务,可以使用它的密码;否则请管理员分享备用连接邀请。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"入口服务密码"}),p.jsx("input",{type:"password",required:!0,value:b,onChange:L=>w(L.target.value),autoComplete:"current-password",disabled:l,autoFocus:!0})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||!b,children:l?"正在授权…":"授权并启用"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{m(void 0),w("")},children:"取消"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});const D=r.filter(L=>L.targetPeerId===n.targetPeerId),M=r.filter(L=>L.targetPeerId!==n.targetPeerId),F=async()=>{if(!l){h(!0),T(!0),f(""),N("");try{o(await RE({...t,routes:r},R)),y(""),N("备用地址已验证并保存。")}catch(L){f(L instanceof Error?L.message:"暂时无法添加地址,请重试。")}finally{h(!1),T(!1)}}};return p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"电脑换了网络?添加它在新网络下的地址,原地址连不上时会自动尝试。只接受同一台服务。"}),p.jsxs("form",{className:"service-form",onSubmit:L=>{L.preventDefault(),F()},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用地址"}),p.jsx("input",{value:R,onChange:L=>{y(L.target.value),f(""),N("")},required:!0,disabled:l||r.length>=4,inputMode:"url",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:192.168.10.20:9834"})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||r.length>=4||!R.trim(),children:x?p.jsxs(p.Fragment,{children:[p.jsx(je,{size:16,className:"service-spinning"}),"正在验证…"]}):"验证并添加"})]}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u}),k&&p.jsx("p",{role:"status",className:"service-help",children:k}),r.length>=4&&p.jsx("p",{className:"service-help",children:"已保存 4 个备用连接。移除不再使用的地址或入口后,可以继续添加。"}),p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"首选地址"}),p.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url})]}),D.length>0&&p.jsx("div",{className:"service-list",children:D.map(L=>p.jsxs("div",{className:"service-route-item",children:[p.jsxs("div",{className:"service-route-line",children:[p.jsx("span",{className:"service-address service-route-address",children:L.url}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`移除地址 ${L.url}`,disabled:l,onClick:()=>v(L),children:"移除"})]}),S?.targetPeerId===L.targetPeerId&&S.url===L.url&&p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"从备用连接中移除此地址?不会停止正在运行的终端。"}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>v(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{P(async()=>{const $=r.filter(H=>H.targetPeerId!==L.targetPeerId||H.url!==L.url);await ns(t,$),o($),v(void 0)})},children:"确认移除"})]})]})]},L.url))}),p.jsxs("details",{className:"service-relay-options",children:[p.jsxs("summary",{children:["通过其他服务中转",M.length?`(${M.length})`:""]}),p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"所有直连地址都不可用时,尝试下方已授权入口;直连恢复后自动切回。"}),M.length>0&&p.jsx("div",{className:"service-list",children:M.map(L=>p.jsxs("div",{className:"service-route-item",children:[p.jsxs("div",{className:"service-route-line",children:[p.jsx("span",{className:"service-icon",children:p.jsx(ai,{size:18})}),p.jsx("span",{className:"service-name",children:E(L)}),p.jsx(Os,{size:16,className:"service-selected"})]}),S?.targetPeerId===L.targetPeerId?p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["撤销此设备经“",E(L),"”连接目标的权限?如当前无法直连,目标服务将断开。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>v(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{P(async()=>{await IE(n.targetPeerId,L);const $=r.filter(H=>H.targetPeerId!==L.targetPeerId);await ns(t,$),o($),v(void 0)})},children:"确认撤销"})]})]}):p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{P(async()=>{const $=await Xp(n,L);_(lg({v:1,routeOnly:!0,serviceId:n.targetPeerId,name:t.label,serviceUrl:t.serviceOrigin||t.url,entryUrl:L.url,entryServiceId:L.targetPeerId,routeCode:$.routeCode}))})},children:"分享备用连接"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>v(L),children:"撤销授权"})]})]},L.targetPeerId))}),a?p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(je,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"添加中转入口"}),s.filter(L=>!r.some($=>$.targetPeerId===L.targetPeerId)).map(L=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:l||r.length>=4,onClick:()=>{I(L)},children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:L.label}),p.jsx("span",{className:"service-description",children:"验证并授权后启用"})]}),p.jsx(Sn,{size:16})]},L.id)),s.length===0&&p.jsx("p",{className:"service-empty",children:"添加并登录另一台服务后,可以将它设为中转入口。"})]})]})]}),l&&!x&&p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(je,{size:16,className:"service-spinning"}),"正在验证连接与授权…"]})]})}function P1({current:t,renderRoutes:e,renderRelayServices:n,onOpen:r,onAdd:o,onInvite:s,hideHeader:i,onNavigation:a,onBusyChange:c,initiallyAdding:l=!1}){const[d,u]=O.useState([]),[f,h]=O.useState(!0),[g,m]=O.useState(l?{kind:"add"}:{kind:"list"}),[b,w]=O.useState(!1),R=O.useCallback(C=>{w(C),c?.(C)},[c]),[y,k]=O.useState(""),N=O.useCallback(()=>{m(C=>C.kind==="routes"||C.kind==="relay-services"?{kind:"edit",service:C.service}:{kind:"list"}),k("")},[]),x=g.kind==="add"?"添加服务":g.kind==="edit"?"服务设置":g.kind==="routes"?"备用连接":g.kind==="relay-services"?"可中转的服务":void 0;O.useEffect(()=>{a?.({title:x,...x?{back:N}:{}})},[x,N,a]),O.useEffect(()=>{let C=!1,E=0;const P=async()=>{const D=++E;try{const M=await Ke();!C&&E===D&&(u(M),k(""))}catch{!C&&E===D&&k("暂时无法读取服务列表,请重试。")}finally{!C&&E===D&&h(!1)}};P();const I=Ws(()=>{P()});return()=>{C=!0,I()}},[]);const T=async C=>{if(!b){R(!0),k("");try{await C()}catch(E){k(E instanceof Error?E.message:"暂时无法完成,请重试。")}finally{R(!1)}}},S=g.kind==="edit"||g.kind==="routes"||g.kind==="relay-services"?d.find(C=>At(C,g.service))||g.service:void 0,v=t?d.find(C=>At(C,t))||t:void 0,A=d.filter(C=>!t||!At(C,t)),_=v?[v,...A]:A,B=p.jsxs(p.Fragment,{children:[f?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(je,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{className:"service-list",children:[_.map(C=>{const E=!!t&&At(C,t);return p.jsxs("div",{className:"service-row",children:[p.jsxs("button",{type:"button",className:"service-row-open",disabled:b||E,onClick:()=>{T(async()=>{(await r(C))?.passwordRequired&&m({kind:"add",input:C.serviceOrigin||C.url,passwordRequired:!0})})},"aria-label":E?`当前服务 ${C.label}`:`打开 ${C.label}`,children:[p.jsx("span",{className:"service-icon",children:p.jsx(ai,{size:20})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:C.label}),p.jsx("span",{className:"service-description",children:E?"当前服务":new URL(C.serviceOrigin||C.url).host})]}),E?p.jsx(Os,{size:17,className:"service-selected"}):p.jsx(Sn,{size:16,className:"service-muted"})]}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`管理 ${C.label}`,disabled:b,onClick:()=>{m({kind:"edit",service:C}),k("")},children:p.jsx(tg,{size:19})})]},C.id)}),_.length===0&&p.jsx("p",{className:"service-empty",children:"还没有添加服务。连接你的电脑,或粘贴收到的邀请链接。"})]}),p.jsxs("div",{className:`service-actions${s?" service-actions-pair":""}`,children:[p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:b,onClick:()=>{m({kind:"add"}),k("")},children:[p.jsx(ng,{size:16}),"添加服务"]}),s&&p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:b,onClick:s,children:[p.jsx(rg,{size:16}),"邀请设备"]})]})]});return p.jsxs("div",{className:"service-manager",children:[!i&&p.jsxs("div",{className:"service-heading",children:[x&&p.jsx("button",{type:"button",className:"service-icon-button","aria-label":"返回服务",disabled:b,onClick:N,children:p.jsx(Zp,{size:20})}),p.jsx("h2",{children:x||"服务"})]}),g.kind==="relay-services"?n?.(S,R):g.kind==="routes"?e?.(S,R):g.kind==="list"?B:g.kind==="add"?p.jsx(N1,{onSave:C=>T(async()=>{const E=_e(C);u(await Tt({id:E,url:E,label:new URL(E).host})),N()}),initialInput:g.input,passwordRequired:g.passwordRequired,busy:b,onSubmit:async(C,E)=>{let P;return await T(async()=>{P=await o(C,E),P?.passwordRequired||N()}),P}}):p.jsx(L1,{onRelayServices:n&&g.service.targetPeerId?()=>m({kind:"relay-services",service:g.service}):void 0,onRoutes:e&&g.service.targetPeerId?()=>m({kind:"routes",service:g.service}):void 0,service:S,busy:b,canRemove:!t||!At(g.service,t),onSave:C=>{T(async()=>{u(await Tt({...S,label:C})),N()})},onRemove:()=>{T(async()=>{u(await $m(g.service.id)),N()})}}),y&&p.jsx("p",{className:"service-error",role:"alert",children:y})]})}function N1({busy:t,onSubmit:e,onSave:n,initialInput:r="",passwordRequired:o=!1}){const[s,i]=O.useState(r),[a,c]=O.useState(""),[l,d]=O.useState(o);return p.jsxs("form",{className:"service-form",onSubmit:async u=>{u.preventDefault(),(await e(s.trim(),l?a:void 0))?.passwordRequired&&d(!0),c("")},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务地址或邀请链接"}),p.jsx("input",{value:s,onChange:u=>{i(u.target.value),d(!1),c("")},disabled:t,required:!0,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:电脑地址:9834 或 https://…"})]}),l?p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务密码"}),p.jsx("input",{type:"password",value:a,onChange:u=>c(u.target.value),disabled:t,required:!0,autoFocus:!0,autoComplete:"current-password",placeholder:"输入这台服务的密码"})]}):p.jsx("p",{className:"service-help",children:"连接自己的服务,输入地址即可;收到邀请时,粘贴完整链接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:t||!s.trim()||s.includes("#termdock-invite="),onClick:()=>{n(s.trim())},children:"仅保存,不连接"}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:t||!s.trim()||l&&!a,children:t?p.jsxs(p.Fragment,{children:[p.jsx(je,{size:16,className:"service-spinning"}),"正在连接…"]}):l?"登录并连接":"继续"})]})}function L1({service:t,busy:e,canRemove:n,onSave:r,onRemove:o,onRoutes:s,onRelayServices:i}){const[a,c]=O.useState(t.label),[l,d]=O.useState(!1);return p.jsxs("form",{className:"service-form",onSubmit:u=>{u.preventDefault(),r(a.trim())},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务名称"}),p.jsx("input",{value:a,onChange:u=>c(u.target.value),disabled:e,required:!0,maxLength:120,placeholder:"例如:办公室电脑"})]}),p.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:e||!a.trim(),children:"保存名称"}),i&&p.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:i,children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:"可中转的服务"}),p.jsx("span",{className:"service-description",children:"通过这台服务连接其他电脑"})]}),p.jsx(Sn,{size:16})]}),s&&p.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:s,children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:"备用连接"}),p.jsx("span",{className:"service-description",children:"添加其他网络地址或授权入口"})]}),p.jsx(Sn,{size:16})]}),n&&p.jsx("div",{className:"service-remove",children:l?p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["从列表移除“",t.label,"”?不会停止服务或删除终端。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:e,onClick:()=>d(!1),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:o,children:"确认移除"})]})]}):p.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:()=>d(!0),children:"移除服务"})})]})}var Dn={},Yi,Au;function B1(){return Au||(Au=1,Yi=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Yi}var Zi={},$t={},ku;function kn(){if(ku)return $t;ku=1;let t;const e=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return $t.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},$t.getSymbolTotalCodewords=function(r){return e[r]},$t.getBCHDigit=function(n){let r=0;for(;n!==0;)r++,n>>>=1;return r},$t.setToSJISFunction=function(r){if(typeof r!="function")throw new Error('"toSJISFunc" is not a valid function.');t=r},$t.isKanjiModeEnabled=function(){return typeof t<"u"},$t.toSJIS=function(r){return t(r)},$t}var Ji={},Cu;function wl(){return Cu||(Cu=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+n)}}t.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},t.from=function(r,o){if(t.isValid(r))return r;try{return e(r)}catch{return o}}})(Ji)),Ji}var Qi,Iu;function _1(){if(Iu)return Qi;Iu=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(e){const n=Math.floor(e/8);return(this.buffer[n]>>>7-e%8&1)===1},put:function(e,n){for(let r=0;r<n;r++)this.putBit((e>>>n-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const n=Math.floor(this.length/8);this.buffer.length<=n&&this.buffer.push(0),e&&(this.buffer[n]|=128>>>this.length%8),this.length++}},Qi=t,Qi}var ea,Ru;function O1(){if(Ru)return ea;Ru=1;function t(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return t.prototype.set=function(e,n,r,o){const s=e*this.size+n;this.data[s]=r,o&&(this.reservedBit[s]=!0)},t.prototype.get=function(e,n){return this.data[e*this.size+n]},t.prototype.xor=function(e,n,r){this.data[e*this.size+n]^=r},t.prototype.isReserved=function(e,n){return this.reservedBit[e*this.size+n]},ea=t,ea}var ta={},Tu;function D1(){return Tu||(Tu=1,(function(t){const e=kn().getSymbolSize;t.getRowColCoords=function(r){if(r===1)return[];const o=Math.floor(r/7)+2,s=e(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()},t.getPositions=function(r){const o=[],s=t.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}})(ta)),ta}var na={},Pu;function F1(){if(Pu)return na;Pu=1;const t=kn().getSymbolSize,e=7;return na.getPositions=function(r){const o=t(r);return[[0,0],[o-e,0],[0,o-e]]},na}var ra={},Nu;function M1(){return Nu||(Nu=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},t.from=function(o){return t.isValid(o)?parseInt(o,10):void 0},t.getPenaltyN1=function(o){const s=o.size;let i=0,a=0,c=0,l=null,d=null;for(let u=0;u<s;u++){a=c=0,l=d=null;for(let f=0;f<s;f++){let h=o.get(u,f);h===l?a++:(a>=5&&(i+=e.N1+(a-5)),l=h,a=1),h=o.get(f,u),h===d?c++:(c>=5&&(i+=e.N1+(c-5)),d=h,c=1)}a>=5&&(i+=e.N1+(a-5)),c>=5&&(i+=e.N1+(c-5))}return i},t.getPenaltyN2=function(o){const s=o.size;let i=0;for(let a=0;a<s-1;a++)for(let c=0;c<s-1;c++){const l=o.get(a,c)+o.get(a,c+1)+o.get(a+1,c)+o.get(a+1,c+1);(l===4||l===0)&&i++}return i*e.N2},t.getPenaltyN3=function(o){const s=o.size;let i=0,a=0,c=0;for(let l=0;l<s;l++){a=c=0;for(let d=0;d<s;d++)a=a<<1&2047|o.get(l,d),d>=10&&(a===1488||a===93)&&i++,c=c<<1&2047|o.get(d,l),d>=10&&(c===1488||c===93)&&i++}return i*e.N3},t.getPenaltyN4=function(o){let s=0;const i=o.data.length;for(let c=0;c<i;c++)s+=o.data[c];return Math.abs(Math.ceil(s*100/i/5)-10)*e.N4};function n(r,o,s){switch(r){case t.Patterns.PATTERN000:return(o+s)%2===0;case t.Patterns.PATTERN001:return o%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(o+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return o*s%2+o*s%3===0;case t.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case t.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}t.applyMask=function(o,s){const i=s.size;for(let a=0;a<i;a++)for(let c=0;c<i;c++)s.isReserved(c,a)||s.xor(c,a,n(o,c,a))},t.getBestMask=function(o,s){const i=Object.keys(t.Patterns).length;let a=0,c=1/0;for(let l=0;l<i;l++){s(l),t.applyMask(l,o);const d=t.getPenaltyN1(o)+t.getPenaltyN2(o)+t.getPenaltyN3(o)+t.getPenaltyN4(o);t.applyMask(l,o),d<c&&(c=d,a=l)}return a}})(ra)),ra}var Ko={},Lu;function dg(){if(Lu)return Ko;Lu=1;const t=wl(),e=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],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 Ko.getBlocksCount=function(o,s){switch(s){case t.L:return e[(o-1)*4+0];case t.M:return e[(o-1)*4+1];case t.Q:return e[(o-1)*4+2];case t.H:return e[(o-1)*4+3];default:return}},Ko.getTotalCodewordsCount=function(o,s){switch(s){case t.L:return n[(o-1)*4+0];case t.M:return n[(o-1)*4+1];case t.Q:return n[(o-1)*4+2];case t.H:return n[(o-1)*4+3];default:return}},Ko}var oa={},_r={},Bu;function j1(){if(Bu)return _r;Bu=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let r=1;for(let o=0;o<255;o++)t[o]=r,e[r]=o,r<<=1,r&256&&(r^=285);for(let o=255;o<512;o++)t[o]=t[o-255]})(),_r.log=function(r){if(r<1)throw new Error("log("+r+")");return e[r]},_r.exp=function(r){return t[r]},_r.mul=function(r,o){return r===0||o===0?0:t[e[r]+e[o]]},_r}var _u;function U1(){return _u||(_u=1,(function(t){const e=j1();t.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]^=e.mul(r[i],o[a]);return s},t.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]^=e.mul(o[c],i);let a=0;for(;a<s.length&&s[a]===0;)a++;s=s.slice(a)}return s},t.generateECPolynomial=function(r){let o=new Uint8Array([1]);for(let s=0;s<r;s++)o=t.mul(o,new Uint8Array([1,e.exp(s)]));return o}})(oa)),oa}var sa,Ou;function $1(){if(Ou)return sa;Ou=1;const t=U1();function e(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(r){this.degree=r,this.genPoly=t.generateECPolynomial(this.degree)},e.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=t.mod(o,this.genPoly),i=this.degree-s.length;if(i>0){const a=new Uint8Array(this.degree);return a.set(s,i),a}return s},sa=e,sa}var ia={},aa={},ca={},Du;function ug(){return Du||(Du=1,ca.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),ca}var ut={},Fu;function fg(){if(Fu)return ut;Fu=1;const t="[0-9]+",e="[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
3
+ ]))+`;ut.KANJI=new RegExp(n,"g"),ut.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),ut.BYTE=new RegExp(r,"g"),ut.NUMERIC=new RegExp(t,"g"),ut.ALPHANUMERIC=new RegExp(e,"g");const o=new RegExp("^"+n+"$"),s=new RegExp("^"+t+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return ut.testKanji=function(c){return o.test(c)},ut.testNumeric=function(c){return s.test(c)},ut.testAlphanumeric=function(c){return i.test(c)},ut}var Mu;function Cn(){return Mu||(Mu=1,(function(t){const e=ug(),n=fg();t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(s,i){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!e.isValid(i))throw new Error("Invalid version: "+i);return i>=1&&i<10?s.ccBits[0]:i<27?s.ccBits[1]:s.ccBits[2]},t.getBestModeForData=function(s){return n.testNumeric(s)?t.NUMERIC:n.testAlphanumeric(s)?t.ALPHANUMERIC:n.testKanji(s)?t.KANJI:t.BYTE},t.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},t.isValid=function(s){return s&&s.bit&&s.ccBits};function r(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+o)}}t.from=function(s,i){if(t.isValid(s))return s;try{return r(s)}catch{return i}}})(aa)),aa}var ju;function H1(){return ju||(ju=1,(function(t){const e=kn(),n=dg(),r=wl(),o=Cn(),s=ug(),i=7973,a=e.getBCHDigit(i);function c(f,h,g){for(let m=1;m<=40;m++)if(h<=t.getCapacity(m,g,f))return m}function l(f,h){return o.getCharCountIndicator(f,h)+4}function d(f,h){let g=0;return f.forEach(function(m){const b=l(m.mode,h);g+=b+m.getBitsLength()}),g}function u(f,h){for(let g=1;g<=40;g++)if(d(f,g)<=t.getCapacity(g,h,o.MIXED))return g}t.from=function(h,g){return s.isValid(h)?parseInt(h,10):g},t.getCapacity=function(h,g,m){if(!s.isValid(h))throw new Error("Invalid QR Code version");typeof m>"u"&&(m=o.BYTE);const b=e.getSymbolTotalCodewords(h),w=n.getTotalCodewordsCount(h,g),R=(b-w)*8;if(m===o.MIXED)return R;const y=R-l(m,h);switch(m){case o.NUMERIC:return Math.floor(y/10*3);case o.ALPHANUMERIC:return Math.floor(y/11*2);case o.KANJI:return Math.floor(y/13);case o.BYTE:default:return Math.floor(y/8)}},t.getBestVersionForData=function(h,g){let m;const b=r.from(g,r.M);if(Array.isArray(h)){if(h.length>1)return u(h,b);if(h.length===0)return 1;m=h[0]}else m=h;return c(m.mode,m.getLength(),b)},t.getEncodedBits=function(h){if(!s.isValid(h)||h<7)throw new Error("Invalid QR Code version");let g=h<<12;for(;e.getBCHDigit(g)-a>=0;)g^=i<<e.getBCHDigit(g)-a;return h<<12|g}})(ia)),ia}var la={},Uu;function q1(){if(Uu)return la;Uu=1;const t=kn(),e=1335,n=21522,r=t.getBCHDigit(e);return la.getEncodedBits=function(s,i){const a=s.bit<<3|i;let c=a<<10;for(;t.getBCHDigit(c)-r>=0;)c^=e<<t.getBCHDigit(c)-r;return(a<<10|c)^n},la}var da={},ua,$u;function K1(){if($u)return ua;$u=1;const t=Cn();function e(n){this.mode=t.NUMERIC,this.data=n.toString()}return e.getBitsLength=function(r){return 10*Math.floor(r/3)+(r%3?r%3*3+1:0)},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(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))},ua=e,ua}var fa,Hu;function z1(){if(Hu)return fa;Hu=1;const t=Cn(),e=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function n(r){this.mode=t.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=e.indexOf(this.data[s])*45;i+=e.indexOf(this.data[s+1]),o.put(i,11)}this.data.length%2&&o.put(e.indexOf(this.data[s]),6)},fa=n,fa}var ha,qu;function W1(){if(qu)return ha;qu=1;const t=Cn();function e(n){this.mode=t.BYTE,typeof n=="string"?this.data=new TextEncoder().encode(n):this.data=new Uint8Array(n)}return e.getBitsLength=function(r){return r*8},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(n){for(let r=0,o=this.data.length;r<o;r++)n.put(this.data[r],8)},ha=e,ha}var pa,Ku;function V1(){if(Ku)return pa;Ku=1;const t=Cn(),e=kn();function n(r){this.mode=t.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=e.toSJIS(this.data[o]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
4
+ Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),r.put(s,13)}},pa=n,pa}var ga={exports:{}},zu;function G1(){return zu||(zu=1,(function(t){var e={single_source_shortest_paths:function(n,r,o){var s={},i={};i[r]=0;var a=e.PriorityQueue.make();a.push(r,0);for(var c,l,d,u,f,h,g,m,b;!a.empty();){c=a.pop(),l=c.value,u=c.cost,f=n[l]||{};for(d in f)f.hasOwnProperty(d)&&(h=f[d],g=u+h,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 w=["Could not find a path from ",r," to ",o,"."].join("");throw new Error(w)}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=e.single_source_shortest_paths(n,r,o);return e.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(n){var r=e.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}}};t.exports=e})(ga)),ga.exports}var Wu;function X1(){return Wu||(Wu=1,(function(t){const e=Cn(),n=K1(),r=z1(),o=W1(),s=V1(),i=fg(),a=kn(),c=G1();function l(w){return unescape(encodeURIComponent(w)).length}function d(w,R,y){const k=[];let N;for(;(N=w.exec(y))!==null;)k.push({data:N[0],index:N.index,mode:R,length:N[0].length});return k}function u(w){const R=d(i.NUMERIC,e.NUMERIC,w),y=d(i.ALPHANUMERIC,e.ALPHANUMERIC,w);let k,N;return a.isKanjiModeEnabled()?(k=d(i.BYTE,e.BYTE,w),N=d(i.KANJI,e.KANJI,w)):(k=d(i.BYTE_KANJI,e.BYTE,w),N=[]),R.concat(y,k,N).sort(function(T,S){return T.index-S.index}).map(function(T){return{data:T.data,mode:T.mode,length:T.length}})}function f(w,R){switch(R){case e.NUMERIC:return n.getBitsLength(w);case e.ALPHANUMERIC:return r.getBitsLength(w);case e.KANJI:return s.getBitsLength(w);case e.BYTE:return o.getBitsLength(w)}}function h(w){return w.reduce(function(R,y){const k=R.length-1>=0?R[R.length-1]:null;return k&&k.mode===y.mode?(R[R.length-1].data+=y.data,R):(R.push(y),R)},[])}function g(w){const R=[];for(let y=0;y<w.length;y++){const k=w[y];switch(k.mode){case e.NUMERIC:R.push([k,{data:k.data,mode:e.ALPHANUMERIC,length:k.length},{data:k.data,mode:e.BYTE,length:k.length}]);break;case e.ALPHANUMERIC:R.push([k,{data:k.data,mode:e.BYTE,length:k.length}]);break;case e.KANJI:R.push([k,{data:k.data,mode:e.BYTE,length:l(k.data)}]);break;case e.BYTE:R.push([{data:k.data,mode:e.BYTE,length:l(k.data)}])}}return R}function m(w,R){const y={},k={start:{}};let N=["start"];for(let x=0;x<w.length;x++){const T=w[x],S=[];for(let v=0;v<T.length;v++){const A=T[v],_=""+x+v;S.push(_),y[_]={node:A,lastCount:0},k[_]={};for(let B=0;B<N.length;B++){const C=N[B];y[C]&&y[C].node.mode===A.mode?(k[C][_]=f(y[C].lastCount+A.length,A.mode)-f(y[C].lastCount,A.mode),y[C].lastCount+=A.length):(y[C]&&(y[C].lastCount=A.length),k[C][_]=f(A.length,A.mode)+4+e.getCharCountIndicator(A.mode,R))}}N=S}for(let x=0;x<N.length;x++)k[N[x]].end=0;return{map:k,table:y}}function b(w,R){let y;const k=e.getBestModeForData(w);if(y=e.from(R,k),y!==e.BYTE&&y.bit<k.bit)throw new Error('"'+w+'" cannot be encoded with mode '+e.toString(y)+`.
5
+ Suggested mode is: `+e.toString(k));switch(y===e.KANJI&&!a.isKanjiModeEnabled()&&(y=e.BYTE),y){case e.NUMERIC:return new n(w);case e.ALPHANUMERIC:return new r(w);case e.KANJI:return new s(w);case e.BYTE:return new o(w)}}t.fromArray=function(R){return R.reduce(function(y,k){return typeof k=="string"?y.push(b(k,null)):k.data&&y.push(b(k.data,k.mode)),y},[])},t.fromString=function(R,y){const k=u(R,a.isKanjiModeEnabled()),N=g(k),x=m(N,y),T=c.find_path(x.map,"start","end"),S=[];for(let v=1;v<T.length-1;v++)S.push(x.table[T[v]].node);return t.fromArray(h(S))},t.rawSplit=function(R){return t.fromArray(u(R,a.isKanjiModeEnabled()))}})(da)),da}var Vu;function Y1(){if(Vu)return Zi;Vu=1;const t=kn(),e=wl(),n=_1(),r=O1(),o=D1(),s=F1(),i=M1(),a=dg(),c=$1(),l=H1(),d=q1(),u=Cn(),f=X1();function h(x,T){const S=x.size,v=s.getPositions(T);for(let A=0;A<v.length;A++){const _=v[A][0],B=v[A][1];for(let C=-1;C<=7;C++)if(!(_+C<=-1||S<=_+C))for(let E=-1;E<=7;E++)B+E<=-1||S<=B+E||(C>=0&&C<=6&&(E===0||E===6)||E>=0&&E<=6&&(C===0||C===6)||C>=2&&C<=4&&E>=2&&E<=4?x.set(_+C,B+E,!0,!0):x.set(_+C,B+E,!1,!0))}}function g(x){const T=x.size;for(let S=8;S<T-8;S++){const v=S%2===0;x.set(S,6,v,!0),x.set(6,S,v,!0)}}function m(x,T){const S=o.getPositions(T);for(let v=0;v<S.length;v++){const A=S[v][0],_=S[v][1];for(let B=-2;B<=2;B++)for(let C=-2;C<=2;C++)B===-2||B===2||C===-2||C===2||B===0&&C===0?x.set(A+B,_+C,!0,!0):x.set(A+B,_+C,!1,!0)}}function b(x,T){const S=x.size,v=l.getEncodedBits(T);let A,_,B;for(let C=0;C<18;C++)A=Math.floor(C/3),_=C%3+S-8-3,B=(v>>C&1)===1,x.set(A,_,B,!0),x.set(_,A,B,!0)}function w(x,T,S){const v=x.size,A=d.getEncodedBits(T,S);let _,B;for(_=0;_<15;_++)B=(A>>_&1)===1,_<6?x.set(_,8,B,!0):_<8?x.set(_+1,8,B,!0):x.set(v-15+_,8,B,!0),_<8?x.set(8,v-_-1,B,!0):_<9?x.set(8,15-_-1+1,B,!0):x.set(8,15-_-1,B,!0);x.set(v-8,8,1,!0)}function R(x,T){const S=x.size;let v=-1,A=S-1,_=7,B=0;for(let C=S-1;C>0;C-=2)for(C===6&&C--;;){for(let E=0;E<2;E++)if(!x.isReserved(A,C-E)){let P=!1;B<T.length&&(P=(T[B]>>>_&1)===1),x.set(A,C-E,P),_--,_===-1&&(B++,_=7)}if(A+=v,A<0||S<=A){A-=v,v=-v;break}}}function y(x,T,S){const v=new n;S.forEach(function(E){v.put(E.mode.bit,4),v.put(E.getLength(),u.getCharCountIndicator(E.mode,x)),E.write(v)});const A=t.getSymbolTotalCodewords(x),_=a.getTotalCodewordsCount(x,T),B=(A-_)*8;for(v.getLengthInBits()+4<=B&&v.put(0,4);v.getLengthInBits()%8!==0;)v.putBit(0);const C=(B-v.getLengthInBits())/8;for(let E=0;E<C;E++)v.put(E%2?17:236,8);return k(v,x,T)}function k(x,T,S){const v=t.getSymbolTotalCodewords(T),A=a.getTotalCodewordsCount(T,S),_=v-A,B=a.getBlocksCount(T,S),C=v%B,E=B-C,P=Math.floor(v/B),I=Math.floor(_/B),D=I+1,M=P-I,F=new c(M);let L=0;const $=new Array(B),H=new Array(B);let U=0;const q=new Uint8Array(x.buffer);for(let V=0;V<B;V++){const Y=V<E?I:D;$[V]=q.slice(L,L+Y),H[V]=F.encode($[V]),L+=Y,U=Math.max(U,Y)}const K=new Uint8Array(v);let X=0,z,W;for(z=0;z<U;z++)for(W=0;W<B;W++)z<$[W].length&&(K[X++]=$[W][z]);for(z=0;z<M;z++)for(W=0;W<B;W++)K[X++]=H[W][z];return K}function N(x,T,S,v){let A;if(Array.isArray(x))A=f.fromArray(x);else if(typeof x=="string"){let P=T;if(!P){const I=f.rawSplit(x);P=l.getBestVersionForData(I,S)}A=f.fromString(x,P||40)}else throw new Error("Invalid data");const _=l.getBestVersionForData(A,S);if(!_)throw new Error("The amount of data is too big to be stored in a QR Code");if(!T)T=_;else if(T<_)throw new Error(`
6
6
  The chosen QR Code version cannot contain this amount of data.
7
7
  Minimum version required to store current data is: `+_+`.
8
- `);const B=y(T,S,A),I=t.getSymbolSize(T),E=new r(I);return h(E,T),g(E),m(E,T),w(E,S,0),T>=7&&b(E,T),R(E,B),isNaN(v)&&(v=i.getBestMask(E,w.bind(null,E,S))),i.applyMask(v,E),w(E,S,v),{modules:E,version:T,errorCorrectionLevel:S,maskPattern:v,segments:A}}return Zi.create=function(T,S){if(typeof T>"u"||T==="")throw new Error("No input text");let v=e.M,A,_;return typeof S<"u"&&(v=e.from(S.errorCorrectionLevel,e.M),A=l.from(S.version),_=i.from(S.maskPattern),S.toSJISFunc&&t.setToSJISFunction(S.toSJISFunc)),N(T,A,v,_)},Zi}var ma={},wa={},Vu;function hg(){return Vu||(Vu=1,(function(t){function e(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("")}}t.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:e(r.color.dark||"#000000ff"),light:e(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},t.getScale=function(r,o){return o.width&&o.width>=r+o.margin*2?o.width/(r+o.margin*2):o.scale},t.getImageWidth=function(r,o){const s=t.getScale(r,o);return Math.floor((r+o.margin*2)*s)},t.qrToImageData=function(r,o,s){const i=o.modules.size,a=o.modules.data,c=t.getScale(i,s),l=Math.floor((i+s.margin*2)*c),d=s.margin*c,u=[s.color.light,s.color.dark];for(let f=0;f<l;f++)for(let h=0;h<l;h++){let g=(f*l+h)*4,m=s.color.light;if(f>=d&&h>=d&&f<l-d&&h<l-d){const b=Math.floor((f-d)/c),w=Math.floor((h-d)/c);m=u[a[b*i+w]?1:0]}r[g++]=m.r,r[g++]=m.g,r[g++]=m.b,r[g]=m.a}}})(wa)),wa}var Xu;function Z1(){return Xu||(Xu=1,(function(t){const e=hg();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")}}t.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=e.getOptions(c);const d=e.getImageWidth(s.modules.size,c),u=l.getContext("2d"),f=u.createImageData(d,d);return e.qrToImageData(f.data,s,c),n(u,l,d),u.putImageData(f,0,0),l},t.renderToDataURL=function(s,i,a){let c=a;typeof c>"u"&&(!i||!i.getContext)&&(c=i,i=void 0),c||(c={});const l=t.render(s,i,c),d=c.type||"image/png",u=c.rendererOpts||{};return l.toDataURL(d,u.quality)}})(ma)),ma}var ya={},Yu;function J1(){if(Yu)return ya;Yu=1;const t=hg();function e(o,s){const i=o.a/255,a=s+'="'+o.hex+'"';return i<1?a+" "+s+'-opacity="'+i.toFixed(2).slice(1)+'"':a}function 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),h=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+h+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 ya.render=function(s,i,a){const c=t.getOptions(i),l=s.modules.size,d=s.modules.data,u=l+c.margin*2,f=c.color.light.a?"<path "+e(c.color.light,"fill")+' d="M0 0h'+u+"v"+u+'H0z"/>':"",h="<path "+e(c.color.dark,"stroke")+' d="'+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+h+`</svg>
9
- `;return typeof a=="function"&&a(null,b),b},ya}var Zu;function Q1(){if(Zu)return Dn;Zu=1;const t=B1(),e=Y1(),n=Z1(),r=J1();function o(s,i,a,c,l){const d=[].slice.call(arguments,1),u=d.length,f=typeof d[u-1]=="function";if(!f&&!t())throw new Error("Callback required as last argument");if(f){if(u<2)throw new Error("Too few arguments provided");u===2?(l=a,a=i,i=c=void 0):u===3&&(i.getContext&&typeof l>"u"?(l=c,c=void 0):(l=c,c=a,a=i,i=void 0))}else{if(u<1)throw new Error("Too few arguments provided");return u===1?(a=i,i=c=void 0):u===2&&!i.getContext&&(c=a,a=i,i=void 0),new Promise(function(h,g){try{const m=e.create(a,c);h(s(m,i,c))}catch(m){g(m)}})}try{const h=e.create(a,c);l(null,s(h,i,c))}catch(h){l(h)}}return Dn.create=e.create,Dn.toCanvas=o.bind(null,n.render),Dn.toDataURL=o.bind(null,n.renderToDataURL),Dn.toString=o.bind(null,function(s,i,a){return r.render(s,a)}),Dn}var eA=Q1();const Or="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",Ye="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",Fn=`${Ye} bg-primary text-primary-foreground hover:opacity-90`;function tA(t){return t.serviceName||new URL(t.url).hostname}function Ju(t){return t.includes("service:*")?"完整权限":t.includes("session.input")?"可操作":t.includes("session.view")?"只读":t.includes("route.use")?"仅中转":"自定义权限"}function nA({profile:t,subjectId:e}){return p.jsxs("details",{className:"mt-2 text-xs text-muted-foreground",children:[p.jsx("summary",{className:"cursor-pointer leading-relaxed",children:[t?.model||t?.hostname||t?.system,t?.route,`ID ${e.slice(-8)}`].filter(Boolean).join(" · ")}),p.jsxs("dl",{className:"mt-2 space-y-2 rounded-lg bg-surface-2 p-3",children:[[["设备型号",t?.model],["主机名称",t?.hostname],["操作系统",t?.system],["客户端",t?.client],["打开方式",t?.mode],["处理器",t?.cpu],["架构",t?.arch],["最近连接路径",t?.route],["首次记录",t?.firstSeenAt?new Date(t.firstSeenAt).toLocaleString():void 0],["最近连接",t?.lastSeenAt?new Date(t.lastSeenAt).toLocaleString():void 0],["设备标识",e]].filter(([,n])=>n).map(([n,r])=>p.jsxs("div",{children:[p.jsx("dt",{children:n}),p.jsx("dd",{className:"mt-0.5 select-text break-all text-foreground",children:r})]},n)),p.jsx("p",{className:"leading-relaxed",children:t?"系统、硬件与路径由设备报告;连接时间由服务记录。":"此设备尚未报告详情,更新客户端并重新连接后可补齐。"})]})]})}function rA(){const t=getComputedStyle(document.documentElement),e=t.getPropertyValue("--background").trim(),n=t.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(!e||!n)throw new Error("Theme unavailable");return r(e)<r(n)?{dark:e,light:n}:{dark:n,light:e}}function oA({onConnect:t,onClose:e,onConnectWithPassword:n,onAddService:r,onOpenService:o,currentIdentity:s,currentServiceName:i,currentServiceId:a,currentServiceOrigin:c,hasBackup:l=!1,inviteAddresses:d=[],paired:u=!1,initialInvite:f,sessions:h=[],grants:g=[],onCreateInvite:m,onRevoke:b,onRename:w,loading:R=!1,loadError:y,onRetry:k}){const[N,x]=O.useState(!1),[T,S]=O.useState(""),[v,A]=O.useState({}),[_,B]=O.useState(""),[I,E]=O.useState(""),[P,C]=O.useState(!1),[D,M]=O.useState(!1),[F,L]=O.useState(!u),[$,H]=O.useState(!0),[U,q]=O.useState(""),[K,X]=O.useState(""),[z,W]=O.useState("read"),[G,Y]=O.useState("all"),[Q,ae]=O.useState([]),[ce,ie]=O.useState(!1),[$e,ke]=O.useState(""),[Ve,en]=O.useState(""),[Oe,gi]=O.useState(),[vr,jl]=O.useState(""),[_t,vm]=O.useState("services"),[Tn,mi]=O.useState(),[wi,Ul]=O.useState(""),[Sr,$l]=O.useState(!1),[Hl,xr]=O.useState(),[mt,ko]=O.useState(!1),[Pn,ql]=O.useState([]),yi=g.filter(j=>j.revokedAt===void 0&&(!j.expiresAt||j.expiresAt>Date.now())),bi=g.filter(j=>!yi.includes(j)),Er=[...new Set(yi.map(j=>j.subjectId))].map(j=>{const V=yi.filter(me=>me.subjectId===j);return{subjectId:j,grants:V,name:j===s?"此设备":V.find(me=>me.label)?.label||"未命名设备"}}).sort((j,V)=>+(V.subjectId===s)-+(j.subjectId===s)),Nn=!Tn&&!Sr&&u&&!F&&!D&&!f,Sm=()=>{mi(void 0),$l(!1),L(!1),M(!1),gi(void 0),ie(!1),B(""),E(""),xr(void 0),q(""),X("")},Kl=()=>{M(!0),L(!1),ie(!1),B(""),E("")},xm=j=>j.subjectId===s?"此设备":j.label||"未命名设备",vi=()=>{mt?ko(!1):e()},Ar=O.useRef(null);O.useEffect(()=>{const j=document.activeElement;return Ar.current?.focus(),()=>{j?.focus()}},[]),O.useEffect(()=>{let j=!1;if(jl(""),Oe)try{eA.toDataURL(Oe.url,{width:220,margin:3,errorCorrectionLevel:"M",color:rA()}).then(V=>{j||jl(V)}).catch(()=>{})}catch{}return()=>{j=!0}},[Oe]);async function Si(j){C(!0),B(""),E("");try{await t(j);const{url:V,targetPeerId:me,serviceName:Xe,serviceOrigin:Ln}=j;await Tt({id:me,url:V,targetPeerId:me,label:Xe||new URL(V).host,serviceOrigin:Ln,entryServiceId:j.entryServiceId}),L(!1),E("已连接。")}catch(V){j.routeOnly&&V instanceof et?x(!0):B("暂时无法连接,请检查网络,或确认邀请是否仍然有效。")}finally{C(!1)}}async function Em(j){if(j.preventDefault(),!m)return;B(""),E("");const V=Q.filter(wt=>h.some(xi=>xi.sessionId===wt));if(z!=="full"&&G==="selected"&&!V.length){B("请选择至少一个 Session。");return}const me=V.map(wt=>h.find(xi=>xi.sessionId===wt)?.sourceSessionId||wt),Xe=Ve?new Date(Ve).getTime():void 0;if(Xe!==void 0&&(!Number.isFinite(Xe)||Xe<=Date.now())){B("授权到期时间必须晚于现在。");return}let Ln;if(U==="custom")try{Ln=_e(K)}catch{B("请输入有效的接入地址,例如 https://192.168.1.23:9834。");return}else U&&(Ln=U);C(!0);try{const wt=await m({...l?{includeBackup:$}:{},...Ln?{entryAddress:Ln}:{},scope:z==="full"||G==="all"?{kind:"service"}:{kind:"sessions",sessionIds:me},actions:z==="full"?["service:*"]:z==="write"?["session.view","session.input","session.resize"]:["session.view"],...$e.trim()?{label:$e.trim()}:{},...Xe===void 0?{}:{expiresAt:Xe}});gi(wt)}catch(wt){B(wt instanceof Error&&wt.message.startsWith("无法分享备用连接:")?"无法分享备用连接:需要入口管理员授权。你也可以关闭“包含备用连接”,生成直连邀请。":"暂时无法生成邀请,请确认当前设备有授权管理权限。")}finally{C(!1)}}async function Am(){if(Oe)try{await navigator.clipboard.writeText(Oe.url),E("邀请链接已复制。")}catch{B("浏览器未允许复制,请长按下方链接复制。")}}const km=v.title||(Tn?"设备名称":Sr?_t==="devices"?"授权详情":"连接详情":mt?"选择终端":D?"邀请设备":F&&u?"添加服务":u?"服务与设备":"连接 Termdock"),Im=!!v.back||!!Tn||Sr||mt||u&&(F||D),Cm=()=>{if(v.back){v.back();return}mt?ko(!1):Sm()},zl=j=>j.every(V=>V.routeTargetServiceId)?`${new Set(j.map(V=>V.routeTargetServiceId)).size} 台服务`:j.some(V=>V.scope.kind==="service")?"全部终端":`${new Set(j.flatMap(V=>V.scope.kind==="sessions"?V.scope.sessionIds:[])).size} 个终端`;return Oc.createPortal(p.jsx("div",{className:"fixed inset-0 z-modal-backdrop flex items-end justify-center bg-[var(--app-backdrop)] backdrop-blur-sm sm:items-center sm:p-6","data-sidebar-gesture-ignore":!0,onMouseDown:j=>{j.target===j.currentTarget&&!P&&vi()},children:p.jsxs("div",{ref:Ar,tabIndex:-1,role:"dialog","aria-modal":"true","aria-labelledby":"federation-title",className:"z-modal-panel flex max-h-[calc(100dvh-env(safe-area-inset-top)-12px)] w-full max-w-lg flex-col overflow-hidden rounded-t-2xl border border-border bg-surface font-sans text-foreground shadow-xl outline-none sm:max-h-[min(720px,90dvh)] sm:rounded-2xl",onKeyDown:j=>{if(j.key==="Escape"&&!P&&(j.stopPropagation(),vi()),j.key!=="Tab")return;const V=Ar.current?.querySelectorAll('button:not(:disabled), input:not(:disabled), textarea:not(:disabled), select:not(:disabled), [tabindex="0"], summary');if(!V?.length){j.preventDefault();return}const me=V[0],Xe=V[V.length-1];j.shiftKey&&(document.activeElement===me||document.activeElement===Ar.current)?(j.preventDefault(),Xe.focus()):!j.shiftKey&&(document.activeElement===Xe||document.activeElement===Ar.current)&&(j.preventDefault(),me.focus())},children:[p.jsxs("header",{className:"shrink-0 border-b border-border px-5 pt-3",children:[p.jsxs("div",{className:"flex min-h-12 items-center gap-2 pb-2",children:[Im&&p.jsx("button",{type:"button",className:`${Ye} -ml-3 inline-flex w-11 items-center justify-center text-muted-foreground`,disabled:P,onClick:Cm,"aria-label":mt?"取消选择终端":_t==="devices"?"返回设备":"返回服务",children:p.jsx(Zp,{size:20})}),p.jsx("h2",{id:"federation-title",className:"min-w-0 flex-1 text-base font-semibold",children:km}),p.jsx("button",{type:"button",className:`${Ye} -mr-3 inline-flex w-11 items-center justify-center text-muted-foreground`,disabled:P,onClick:vi,"aria-label":"关闭",children:p.jsx(og,{size:20})})]}),Nn&&!v.title&&p.jsx("div",{className:"flex gap-6",role:"tablist","aria-label":"管理内容",children:[["services","服务"],["devices","设备"]].map(([j,V])=>p.jsxs("button",{type:"button",role:"tab","aria-selected":_t===j,"aria-controls":`federation-${j}`,id:`federation-tab-${j}`,className:`min-h-11 border-b-2 px-1 text-sm transition ${_t===j?"border-primary font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"}`,onClick:()=>{vm(j),ie(!1),xr(void 0),B(""),E("")},children:[V,j==="devices"&&Er.length>0&&p.jsx("span",{className:"ml-1.5 text-xs text-muted-foreground",children:Er.length})]},j))})]}),p.jsxs("div",{className:"min-h-0 overflow-y-auto overscroll-contain px-5 py-4 pb-[max(20px,env(safe-area-inset-bottom))]",children:[(Nn&&_t==="services"||F&&!D&&!f)&&p.jsx(P1,{renderRelayServices:(j,V)=>p.jsx(R1,{service:j,onBusyChange:V,onConnect:t,onConnectWithPassword:n}),renderRoutes:(j,V)=>p.jsx(T1,{service:j,onBusyChange:V}),hideHeader:!0,initiallyAdding:F,current:a?{id:a,targetPeerId:a,url:c||location.origin,label:i||"当前服务"}:void 0,onNavigation:A,onBusyChange:C,onInvite:m?Kl:void 0,onOpen:async j=>{if(o)return o(j);j.targetPeerId?await Si({...j,targetPeerId:j.targetPeerId,serviceName:j.label}):r&&await r(j.url)},onAdd:async(j,V)=>{if(r)return r(j,V);await Si(Ds(j))}}),Nn&&_t==="devices"&&p.jsxs("section",{role:"tabpanel",id:"federation-devices","aria-labelledby":"federation-tab-devices",children:[p.jsx("p",{className:"mb-2 text-xs leading-relaxed text-muted-foreground",children:"可访问此服务的设备"}),R?p.jsxs("p",{role:"status",className:"flex items-center gap-2 py-5 text-sm text-muted-foreground",children:[p.jsx(je,{size:16,className:"animate-spin"}),"正在读取设备…"]}):p.jsxs("div",{className:"divide-y divide-border",children:[Er.map(j=>p.jsxs("div",{className:"py-3",children:[p.jsxs("div",{className:"flex items-center gap-3",children:[p.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-surface-2 text-muted-foreground",children:/iPhone|iPad|Android|手机|平板/i.test(j.grants.find(V=>V.label)?.label||(j.subjectId===s?navigator.userAgent:""))?p.jsx(rg,{size:19}):p.jsx(e1,{size:19})}),p.jsxs("div",{className:"min-w-0 flex-1",children:[p.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[p.jsx("p",{className:"truncate text-sm font-medium",children:j.name}),w&&(b||j.subjectId===s)&&p.jsx("button",{type:"button","aria-label":`重命名 ${j.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:()=>{mi(j.subjectId),Ul(j.grants.find(V=>V.label)?.label||"")},children:p.jsx(n1,{size:14})})]}),j.subjectId===s&&j.grants.find(V=>V.label)?.label&&p.jsx("p",{className:"truncate text-xs text-muted-foreground",children:j.grants.find(V=>V.label)?.label}),p.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[Ju(j.grants.flatMap(V=>V.actions))," · ",zl(j.grants)]})]}),b&&j.subjectId!==s&&Hl!==j.subjectId&&p.jsx("button",{type:"button",className:`${Ye} -mr-2 text-xs text-muted-foreground hover:text-destructive`,disabled:P,"aria-label":`撤销 ${j.name} 的访问权限`,onClick:()=>xr(j.subjectId),children:"撤销"})]}),p.jsx(nA,{profile:j.grants.find(V=>V.deviceProfile)?.deviceProfile,subjectId:j.subjectId}),Hl===j.subjectId&&p.jsxs("div",{className:"mt-3 rounded-lg border border-border bg-background p-3",children:[p.jsx("p",{className:"text-xs leading-relaxed",children:"撤销后,这台设备将断开连接,需重新邀请才能访问。"}),p.jsxs("div",{className:"mt-2 flex justify-end gap-2",children:[p.jsx("button",{type:"button",className:`${Ye} text-xs text-muted-foreground`,disabled:P,onClick:()=>xr(void 0),children:"取消"}),p.jsx("button",{type:"button",className:`${Ye} text-xs text-destructive`,disabled:P,onClick:async()=>{C(!0),B("");try{for(const V of j.grants)await b?.(V.id);xr(void 0),E("设备访问权限已撤销。")}catch{B("暂时无法撤销,请重试。")}finally{C(!1)}},children:"确认撤销"})]})]})]},j.subjectId)),Er.length===0&&!y&&p.jsxs("p",{className:"py-5 text-sm text-muted-foreground",children:["暂无设备授权。",m?"可通过邀请添加设备。":""]})]}),m&&p.jsxs("button",{type:"button",className:`${Ye} mt-4 inline-flex w-full items-center justify-center gap-2 border border-border text-sm`,disabled:P,onClick:Kl,children:[p.jsx(ng,{size:16}),"邀请设备"]}),bi.length>0&&p.jsxs("details",{className:"mt-4 text-xs text-muted-foreground",children:[p.jsxs("summary",{className:"cursor-pointer py-2",children:["已失效的授权(",bi.length,")"]}),p.jsx("div",{className:"mt-1 space-y-2 border-l border-border pl-3",children:bi.map(j=>p.jsxs("p",{className:"flex gap-3",children:[p.jsx("span",{className:"min-w-0 flex-1 truncate",children:xm(j)}),p.jsx("span",{className:"shrink-0",children:j.revokedAt!==void 0?"已撤销":"已到期"})]},j.id))})]})]}),Tn&&p.jsxs("form",{className:"space-y-4",onSubmit:async j=>{j.preventDefault(),C(!0),B("");try{await w?.(Tn,wi.trim()),mi(void 0)}catch{B("暂时无法保存设备名称,请重试。")}finally{C(!1)}},children:[p.jsxs("label",{className:"block space-y-2 text-sm",children:[p.jsx("span",{children:"设备名称"}),p.jsx("input",{autoFocus:!0,className:Or,maxLength:80,required:!0,value:wi,onChange:j=>Ul(j.target.value),placeholder:"例如:我的 iPhone、办公室电脑"})]}),p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"为设备起一个容易辨认的名字,会同步显示在此服务的设备列表中。"}),p.jsx("button",{type:"submit",className:`${Fn} w-full`,disabled:P||!wi.trim(),children:P?"正在保存…":"保存名称"})]}),Sr&&p.jsx("section",{className:"space-y-5",children:_t==="devices"?Er.map(j=>p.jsxs("div",{className:"space-y-3",children:[p.jsx("h3",{className:"text-sm font-medium",children:j.name}),p.jsxs("dl",{className:"space-y-3 rounded-xl bg-surface-2 p-3 text-xs",children:[p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"访问权限"}),p.jsxs("dd",{className:"mt-1",children:[Ju(j.grants.flatMap(V=>V.actions))," · ",zl(j.grants)]})]}),j.grants.map(V=>p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:V.routeTargetServiceId?"允许经此入口访问":V.scope.kind==="sessions"?"可访问终端":"有效期"}),p.jsx("dd",{className:"mt-1 leading-relaxed",children:V.routeTargetServiceId?V.routeTargetName||"指定服务":V.scope.kind==="sessions"?V.scope.sessionIds.map(me=>h.find(Xe=>Xe.sessionId===me)?.name||me).join("、"):V.expiresAt?new Date(V.expiresAt).toLocaleString():"保留至撤销"}),V.routeTargetServiceId&&b&&p.jsx("button",{type:"button",className:`${Ye} mt-1 -ml-3 text-xs text-destructive`,disabled:P,onClick:async()=>{C(!0),B("");try{await b(V.id)}catch{B("暂时无法撤销,请重试。")}finally{C(!1)}},children:"撤销此中转权限"})]},V.id)),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"设备标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed text-muted-foreground select-text",children:j.subjectId})]})]})]},j.subjectId)):p.jsxs("dl",{className:"space-y-4 text-xs",children:[p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"当前服务"}),p.jsx("dd",{className:"mt-1 text-sm",children:i||"当前服务"})]}),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"服务标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed select-text",children:a})]}),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"本设备标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed select-text",children:s})]})]})}),f&&!D&&p.jsxs("section",{className:"space-y-5 py-1",children:[p.jsxs("div",{className:"flex items-center gap-3",children:[p.jsx("span",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-surface-2 text-muted-foreground",children:p.jsx(ai,{size:22})}),p.jsxs("div",{className:"min-w-0",children:[p.jsx("p",{className:"text-xs text-muted-foreground",children:"你受邀连接"}),p.jsx("p",{className:"mt-1 break-words text-base font-medium",children:tA(f)})]})]}),f.routeOnly&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"此邀请提供备用连接,目标服务仍会验证你的访问权限。"}),N?p.jsxs("form",{className:"space-y-3",onSubmit:async j=>{j.preventDefault(),C(!0),B("");try{await n?.(f,T)}catch(V){B(V instanceof Error?V.message:"暂时无法登录,请重试。")}finally{S(""),C(!1)}},children:[p.jsxs("label",{className:"block space-y-2 text-sm",children:[p.jsx("span",{children:"目标服务密码"}),p.jsx("input",{className:Or,type:"password",required:!0,autoFocus:!0,autoComplete:"current-password",value:T,onChange:j=>S(j.target.value)})]}),p.jsx("button",{className:`${Fn} w-full`,disabled:P||!T,children:P?"正在登录…":"登录并连接"})]}):p.jsx("button",{type:"button",className:`${Fn} w-full text-sm`,disabled:P,onClick:()=>{Si(f)},children:P?"正在连接…":"接受邀请"})]}),D&&!mt&&p.jsx("section",{children:Oe?p.jsxs("div",{className:"space-y-4 text-center",children:[p.jsx("p",{className:"text-sm font-medium",children:"用另一台设备扫描二维码"}),vr?p.jsx("img",{src:vr,width:220,height:220,className:"mx-auto max-w-full rounded-xl",alt:"设备邀请二维码"}):p.jsx("div",{className:"mx-auto flex h-48 w-48 items-center justify-center",children:p.jsx(je,{size:22,className:"animate-spin text-muted-foreground"})}),p.jsxs("p",{className:"text-xs leading-relaxed text-muted-foreground",children:["仅限一台设备使用 · ",new Date(Oe.expiresAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," 前有效"]}),p.jsxs("button",{type:"button",className:`${Fn} inline-flex w-full items-center justify-center gap-2 text-sm`,onClick:()=>{Am()},children:[p.jsx(eg,{size:16}),"复制邀请链接"]}),p.jsxs("details",{className:"text-left text-xs text-muted-foreground",children:[p.jsx("summary",{className:"cursor-pointer py-2",children:"查看链接"}),p.jsx("p",{className:"mt-2 select-all break-all",children:Oe.url})]})]}):p.jsxs("form",{className:"space-y-5",onSubmit:Em,children:[p.jsxs("fieldset",{children:[p.jsx("legend",{className:"mb-2 text-sm font-medium",children:"访问权限"}),p.jsx("div",{className:"space-y-2",children:[["read","仅查看","查看终端画面,不可输入命令"],["write","可操作","查看终端画面,并输入命令"],["full","完整访问","包括文件、设置和权限管理"]].map(([j,V,me])=>p.jsxs("label",{className:`flex cursor-pointer items-center gap-3 rounded-xl border px-3 py-2.5 transition focus-within:ring-2 focus-within:ring-ring ${z===j?"border-primary bg-primary/10":"border-border hover:bg-surface-2"}`,children:[p.jsx("input",{type:"radio",name:"federation-permission",value:j,checked:z===j,onChange:()=>W(j),className:"sr-only"}),p.jsx("span",{"aria-hidden":"true",className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border ${z===j?"border-primary bg-primary text-primary-foreground":"border-border bg-background"}`,children:z===j&&p.jsx(Os,{size:13,strokeWidth:3})}),p.jsxs("span",{className:"min-w-0",children:[p.jsx("span",{className:"block text-sm font-medium text-foreground",children:V}),p.jsx("span",{className:"mt-0.5 block text-xs leading-relaxed text-muted-foreground",children:me})]})]},j))})]}),z!=="full"&&p.jsxs("fieldset",{children:[p.jsx("legend",{className:"mb-2 text-sm font-medium",children:"可访问的终端"}),p.jsxs("div",{className:"flex gap-2",children:[p.jsx("button",{type:"button","aria-pressed":G==="all",className:`${Ye} flex-1 appearance-none border text-sm ${G==="all"?"border-primary bg-primary/10 text-foreground":"border-border text-muted-foreground"}`,onClick:()=>Y("all"),children:"全部终端"}),p.jsxs("button",{type:"button","aria-pressed":G==="selected",className:`${Ye} inline-flex flex-1 appearance-none items-center justify-center gap-1 border text-sm ${G==="selected"?"border-primary bg-primary/10 text-foreground":"border-border text-muted-foreground"}`,onClick:()=>{ql(Q),ko(!0)},children:[G==="selected"?`已选 ${Q.length} 个`:"选择终端",p.jsx(Sn,{size:14})]})]}),G==="all"&&p.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"包括之后新建的终端。"})]}),z==="write"&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"终端命令可读写该系统用户有权访问的文件。"}),z==="full"&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"拥有此服务的全部当前及未来权限。仅授予你完全信任的设备。"}),l&&p.jsxs("label",{className:"flex items-start gap-3 text-sm",children:[p.jsx("input",{type:"checkbox",className:"mt-0.5 h-4 w-4 accent-primary",checked:$,onChange:j=>H(j.target.checked)}),p.jsxs("span",{children:["让新设备也能使用备用连接",p.jsx("span",{className:"mt-1 block text-xs leading-relaxed text-muted-foreground",children:"需要入口管理员授权;关闭后生成直接连接邀请。"})]})]}),d.length>0&&p.jsxs("details",{className:"rounded-xl border border-border px-3 py-2 text-left",children:[p.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-foreground",children:["接入地址",p.jsx("span",{className:"ml-2 text-xs font-normal text-muted-foreground",children:"默认当前地址,可换用 IP 或域名"})]}),p.jsxs("fieldset",{className:"mt-2 space-y-2",children:[p.jsx("legend",{className:"sr-only",children:"受邀设备打开的地址"}),p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"受邀设备将打开这个地址。当前地址无法访问时,可改用其他可访问的 IP 或域名。"}),p.jsx("div",{className:"space-y-2",children:[["","当前地址",new URL(c||location.origin).host],...d.map(j=>[j.url,j.label,new URL(j.url).host]),["custom","自定义地址",""]].map(([j,V,me])=>p.jsxs("label",{className:`flex cursor-pointer items-center gap-3 rounded-xl border px-3 py-2.5 transition focus-within:ring-2 focus-within:ring-ring ${U===j?"border-primary bg-primary/10":"border-border hover:bg-surface-2"}`,children:[p.jsx("input",{type:"radio",name:"federation-entry-address",value:j,checked:U===j,onChange:()=>q(j),className:"sr-only"}),p.jsx("span",{"aria-hidden":"true",className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border ${U===j?"border-primary bg-primary text-primary-foreground":"border-border bg-background"}`,children:U===j&&p.jsx(Os,{size:13,strokeWidth:3})}),p.jsxs("span",{className:"min-w-0",children:[p.jsx("span",{className:"block text-sm font-medium text-foreground",children:V}),me&&p.jsx("span",{className:"block break-all text-xs leading-relaxed text-muted-foreground",children:me})]})]},j||"current"))}),U==="custom"&&p.jsx("input",{type:"text",className:Or,inputMode:"url",placeholder:"例如:https://192.168.1.23:9834",value:K,onChange:j=>X(j.target.value)})]})]}),p.jsxs("div",{children:[p.jsxs("button",{className:`${Fn} inline-flex w-full items-center justify-center gap-2 text-sm`,type:"submit",disabled:P||R,children:[P&&p.jsx(je,{size:16,className:"animate-spin"}),P?"正在生成…":"生成邀请"]}),p.jsxs("p",{className:"mt-2 text-center text-xs leading-relaxed text-muted-foreground",children:["链接 10 分钟内有效 · 访问权限",Ve?"按设定时间到期":"保留至撤销"]})]})]})}),mt&&p.jsxs("section",{children:[p.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"仅允许访问勾选的终端。"}),p.jsxs("div",{className:"space-y-1",children:[h.map(j=>p.jsxs("label",{className:"flex min-h-12 cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm hover:bg-surface-2",children:[p.jsx("input",{type:"checkbox",className:"h-4 w-4 accent-primary",checked:Pn.includes(j.sessionId),onChange:V=>ql(V.target.checked?[...Pn,j.sessionId]:Pn.filter(me=>me!==j.sessionId))}),p.jsx("span",{className:"min-w-0 break-words",children:j.name})]},j.sessionId)),!h.length&&p.jsx("p",{className:"py-4 text-sm text-muted-foreground",children:"当前没有可共享的终端。"})]})]}),y&&p.jsxs("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:[y,k&&p.jsx("button",{type:"button",className:`${Ye} ml-1 text-sm underline`,onClick:k,children:"重试"})]}),!v.title&&!F&&!Tn&&!Sr&&!mt&&!Oe&&p.jsxs("div",{className:"mt-4 border-t border-border pt-2",children:[p.jsxs("button",{type:"button",className:`${Ye} -ml-3 inline-flex items-center gap-1 bg-transparent text-xs text-muted-foreground`,"aria-expanded":Nn?void 0:ce,onClick:()=>Nn?$l(!0):ie(j=>!j),children:[D?"有效期与备注":F?"手动连接":_t==="devices"?"授权详情":"连接详情",Nn?p.jsx(Sn,{size:14}):p.jsx(Qp,{size:13,className:ce?"rotate-180":""})]}),ce&&p.jsxs("section",{className:"space-y-3 pb-1 pt-2",children:[D&&p.jsxs(p.Fragment,{children:[p.jsxs("label",{className:"block space-y-1 text-sm",children:[p.jsx("span",{children:"设备备注(可选)"}),p.jsx("input",{className:Or,value:$e,onChange:j=>ke(j.target.value),placeholder:"例如:工作电脑"})]}),p.jsxs("label",{className:"block space-y-1 text-sm",children:[p.jsx("span",{children:"授权到期时间"}),p.jsx("input",{type:"datetime-local",className:Or,value:Ve,onChange:j=>en(j.target.value)})]})]}),!D&&s&&p.jsxs("p",{className:"break-all text-xs leading-relaxed text-muted-foreground",children:["本设备身份:",s]})]})]}),_&&p.jsx("p",{role:"alert",className:"mt-3 text-sm text-destructive",children:_}),I&&p.jsx("p",{role:"status",className:"mt-3 text-sm text-muted-foreground",children:I})]}),mt&&p.jsx("footer",{className:"shrink-0 border-t border-border px-5 pt-3 pb-[max(16px,env(safe-area-inset-bottom))]",children:p.jsxs("button",{type:"button",className:`${Fn} w-full text-sm`,disabled:!Pn.length,onClick:()=>{ae(Pn),Y("selected"),ko(!1)},children:["使用所选终端(",Pn.length,")"]})})]})}),document.body)}const sA={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"},iA={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 aA(t){return t==="light"?iA:sA}const cc="termdock:open-services";function pg(){window.dispatchEvent(new Event(cc))}function cA({client:t,initialSessionId:e}){const[n,r]=O.useState([]),[o,s]=O.useState(),i=O.useRef();O.useEffect(()=>{if(!e||i.current===e)return;const f=n.find(h=>h.sessionId===e||h.sourceSessionId===e);f&&(i.current=e,s(f))},[n,e]);const[a,c]=O.useState("正在读取已授权 Session"),[l,d]=O.useState(()=>document.documentElement.dataset.theme==="light"?"light":"dark");O.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=O.useRef(null);return O.useEffect(()=>{let f=!0;const h=async()=>{try{const m=await t.request({type:"session-list"});if(f){const b=m.items;r(b),s(w=>{if(!w)return c(b.length?"选择一个已授权 Session":"暂无已授权的在线 Session"),w;const R=b.find(y=>y.sessionId===w.sessionId);if(!R){c("Session 已移除或授权失效");return}return R.canWrite===w.canWrite&&R.canResize===w.canResize?w:R})}}catch{f&&c("目标不可达或授权已失效")}};h();const g=setInterval(()=>{h()},15e3);return()=>{f=!1,clearInterval(g)}},[t]),O.useEffect(()=>{if(!o||!u.current)return;let f=!1,h=0,g;const m=new Tm({theme:aA(l),cursorBlink:o.canWrite,disableStdin:!o.canWrite,convertEol:!1}),b=new Pm;m.loadAddon(b),m.open(u.current),o.canResize&&b.fit(),c("正在建立加密终端连接");const w=t.openSocket(`/api/terminal/${encodeURIComponent(o.sessionId)}/ws?flow=2`),R=()=>{f||!o.canResize||(b.fit(),w.readyState===1&&w.send(JSON.stringify({type:"resize",cols:m.cols,rows:m.rows})))};w.onopen=()=>c(o.canWrite?"读写":"只读"),w.onmessage=x=>{try{const T=JSON.parse(x.data);if(f)return;if(T.type==="connected"){g=typeof T.streamEpoch=="string"?T.streamEpoch:void 0,h=Number.isSafeInteger(T.replayLastSeq)?T.replayLastSeq:0,!o.canResize&&Number.isSafeInteger(T.cols)&&Number.isSafeInteger(T.rows)&&T.cols>0&&T.rows>0&&m.resize(T.cols,T.rows);const S=Array.isArray(T.replayChunks)?T.replayChunks.filter(v=>typeof v=="string").join(""):"";m.write((T.replayOutOfWindow?"\x1Bc":"")+S,R)}else T.type==="data"&&typeof T.data=="string"?m.write(T.data,()=>{f||(Number.isSafeInteger(T.seq)&&(h=Math.max(h,T.seq)),w.readyState===1&&Number.isSafeInteger(T.flowSeq)&&w.send(JSON.stringify({type:"output-ack",flowSeq:T.flowSeq,since:h,epoch:g})))}):T.type==="pty-size"&&!o.canResize&&Number.isSafeInteger(T.cols)&&Number.isSafeInteger(T.rows)&&T.cols>0&&T.rows>0?m.resize(T.cols,T.rows):T.type==="error"&&c("目标拒绝终端操作,请检查有效授权")}catch{c("终端数据无效"),w.close()}},w.onclose=()=>c("连接已断开;画面已过期,重新选择 Session 可重连"),w.onerror=()=>c("目标不可达或授权不足");const y=m.onData(x=>{o.canWrite&&w.readyState===1&&w.send(JSON.stringify({type:"input",data:x}))}),k=setInterval(()=>{w.readyState===1&&w.send(JSON.stringify({type:"ping"}))},2e4),N=new ResizeObserver(R);return N.observe(u.current),()=>{f=!0,clearInterval(k),N.disconnect(),y.dispose(),w.onclose=null,w.onerror=null,w.close(),m.dispose()}},[t,o,l]),p.jsxs("div",{className:"flex h-dvh flex-col bg-background text-foreground",children:[p.jsxs("div",{className:"flex items-center gap-3 border-b border-border p-3 text-sm",children:[p.jsxs("span",{className:"min-w-0 flex-1",children:["已授权 Session · ",a]}),p.jsx("button",{type:"button",onClick:pg,className:"min-h-11 shrink-0 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2",children:"服务与设备"})]}),p.jsx("div",{className:"flex flex-wrap gap-2 p-2",children:n.map(f=>p.jsxs("button",{className:"rounded border border-border px-3 py-2 text-sm hover:bg-surface-2",onClick:()=>s({...f}),children:[f.name," · ",f.canWrite?"读写":"只读"]},`${t.targetPeerId}:${f.sessionId}`))}),p.jsx("div",{ref:u,className:"min-h-0 flex-1 overflow-auto p-2"})]})}function lA(t){const e=t.serviceLabel?.trim();if(!e||/^https?:\/\//i.test(e)||e===t.serviceOrigin)return"远端服务";try{const n=new URL(t.serviceOrigin??"");if(e===n.host||e===n.hostname)return"远端服务"}catch{}return e}function lc(t){if(!t.startsWith("remote:"))return null;const e=t.slice(7).split(":");if(e.length!==2)return null;try{const n=decodeURIComponent(e[0]),r=decodeURIComponent(e[1]);return!r||new URL(n).origin!==n||!/^https?:/.test(n)?null:{origin:n,id:r}}catch{return null}}class dA{constructor(e){this.source=e,this.peers={state:e.peerProtocol==="unsupported"?"unsupported":e.readPeers?"loading":"unavailable",checkedAt:null}}source;local=null;remote=[];peers;localInFlight=null;peerInFlight=null;listeners=new Set;disposed=!1;peerTimer;lastPeerAttempt=-1/0;generation=0;localHealthy=!1;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}snapshot(){if(!this.local)return null;const e=new Map;for(const n of this.local.groups)for(const r of n.remoteSessions??[]){const o=lc(r.sessionId);o&&o.origin!==this.source.origin&&o.origin!==this.source.peerOrigin&&e.set(r.sessionId,{...r,status:"offline",serviceConnected:!1})}for(const n of this.remote)e.set(n.sessionId,n);for(const n of this.local.sessions)e.set(n.sessionId,n);return{groups:this.local.groups.map(n=>({...n,remoteSessions:n.remoteSessions?.map(r=>e.get(r.sessionId)??r)})),sessions:[...e.values()],peers:this.peers,capabilities:this.local.capabilities}}emit(){if(this.disposed||!this.localHealthy)return;const e=this.snapshot();if(e)for(const n of this.listeners)n(e)}load(){if(this.disposed)return Promise.reject(new Error("协作连接已切换,请重新加载"));if(this.localInFlight)return this.localInFlight;this.refreshPeers();const e=this.generation,n=Promise.resolve().then(()=>this.source.readLocal()).then(r=>{if(this.disposed)throw new Error("协作连接已切换,请重新加载");if(e!==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 e===this.generation&&(this.localHealthy=!1),r}).finally(()=>{this.localInFlight===n&&(this.localInFlight=null)});return this.localInFlight=n,n}invalidate(){this.generation++,this.localInFlight=null,this.localHealthy=!1}refreshPeers(e=!1){if(this.disposed||!this.source.readPeers||this.peerInFlight||!e&&Date.now()-this.lastPeerAttempt<2e3)return;this.lastPeerAttempt=Date.now(),this.peers.checkedAt||(this.peers={state:"loading",checkedAt:null}),this.emit();const 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=lc(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}}).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 uA(t,e){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:t,filename:e},[r.port2])}catch{s(null)}})}const fA=4*1024*1024,hA=256*1024,pA=1440*6e4;let rr=0,Qu;function yl(){return typeof indexedDB>"u"?Promise.resolve(null):Qu??=new Promise(t=>{const e=indexedDB.open(`termdock-terminal-snapshots:${Wn}`,1);e.onupgradeneeded=()=>e.result.createObjectStore("snapshots",{keyPath:"id"}),e.onerror=()=>t(null),e.onblocked=()=>t(null),e.onsuccess=()=>{e.result.onversionchange=()=>{e.result.close(),Qu=void 0},t(e.result)}})}function dc(t){return!!t&&t.version===1&&typeof t.epoch=="string"&&t.epoch.length>0&&Number.isSafeInteger(t.cols)&&t.cols>0&&Number.isSafeInteger(t.rows)&&t.rows>0&&Number.isSafeInteger(t.seq)&&t.seq>0&&typeof t.data=="string"&&t.data.length*2<=hA&&t.savedAt<=Date.now()&&Date.now()-t.savedAt<pA}async function uR(t){const e=rr;try{const n=await yl();return!n||e!==rr?null:await new Promise(r=>{const o=n.transaction("snapshots").objectStore("snapshots").get(t);o.onerror=()=>r(null),o.onsuccess=()=>r(e===rr&&dc(o.result)?o.result:null)})}catch{return null}}async function fR(t){const e=rr;if(dc(t))try{const n=await yl();if(!n||e!==rr)return;await new Promise(r=>{const o=n.transaction("snapshots","readwrite"),s=o.objectStore("snapshots");s.put(t);const i=s.getAll();i.onsuccess=()=>{let a=0,c=0;for(const l of i.result.sort((d,u)=>u.savedAt-d.savedAt))a+=l.data.length*2,(++c>32||a>fA||!dc(l))&&s.delete(l.id)},o.oncomplete=()=>r(),o.onerror=o.onabort=()=>r()})}catch{}}async function gg(){rr+=1;try{(await yl())?.transaction("snapshots","readwrite").objectStore("snapshots").clear()}catch{}}typeof window<"u"&&window.addEventListener("auth:unauthorized",()=>{gg()});const vt=new Map,Wt=new Map,gA=32*1024*1024,mA=8*1024*1024,wA=48;let zr=0,uc=0;function bl(){uc+=1,vt.clear(),zr=0;for(const t of Wt.values())t.controller.abort();Wt.clear()}typeof window<"u"&&window.addEventListener("auth:unauthorized",bl);function yA(t,e){const n=vt.get(t);if(n&&(zr-=n.blob.size,vt.delete(t)),!(e.blob.size>mA))for(vt.set(t,e),zr+=e.blob.size;vt.size>wA||zr>gA;){const r=vt.keys().next().value;zr-=vt.get(r).blob.size,vt.delete(r)}}async function mg(t,e={}){const n=new URL(t,typeof location<"u"?location.origin:"http://localhost");if(!/^\/api\/terminal\/fs\/(read|blob)$/.test(n.pathname))return fetch(t,{signal:e.signal});if(e.signal?.aborted)throw e.signal.reason??new DOMException("Aborted","AbortError");n.searchParams.delete("requestSlotId"),n.searchParams.delete("action"),n.searchParams.sort();const r=n.href;let o=Wt.get(r);if(!o){const i=new AbortController,a=uc,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")),e.timeoutMs??15e3),f={controller:i,readers:0,promise:Promise.resolve(null)};f.promise=(async()=>{const h=await fetch(r,{headers:l,signal:i.signal,cache:"no-cache"});let g;return h.status===304&&c?g=c:g={blob:await h.blob(),headers:new Headers(h.headers),status:h.status},uc===a&&!i.signal.aborted&&g.status===200&&g.headers.has("ETag")&&yA(r,g),h.status===401&&bl(),g})().finally(()=>{clearTimeout(u),Wt.get(r)===f&&Wt.delete(r)}),o=f,Wt.set(r,o)}const s=o;return s.readers+=1,new Promise((i,a)=>{let c=!1;const l=()=>c?!1:(c=!0,e.signal?.removeEventListener("abort",d),s.readers-=1,s.readers===0&&Wt.get(r)===s&&(Wt.delete(r),s.controller.abort()),!0),d=()=>{l()&&a(e.signal?.reason??new DOMException("Aborted","AbortError"))};if(e.signal?.addEventListener("abort",d,{once:!0}),e.signal?.aborted){d();return}s.promise.then(u=>{l()&&i(new Response(u.blob,{status:u.status,headers:u.headers}))},u=>{l()&&a(u)})})}const vl="auth:unauthorized";let Kn=null;class Ce extends Error{constructor(e,n,r){super(e),this.status=n,this.code=r,this.name="TerminalApiError"}status;code}async function bA(){const t=await fetch("/api/terminal/update");if(!t.ok)throw new Ce("Failed to load update state",t.status);return t.json()}async function vA(){const t=await Z(),e=await fetch("/api/terminal/update/check",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Ce("Failed to check for updates",e.status);return e.json()}async function SA(){const t=await Z(),e=await fetch("/api/terminal/update/restart",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to restart Termdock"}));throw new Ce(n.error||"Failed to restart Termdock",e.status)}return e.json()}async function xA(){const t=await fetch("/api/terminal/quota");if(!t.ok)throw new Ce("Failed to fetch quota",t.status);return t.json()}async function EA(){const t=await Z(),e=await fetch("/api/terminal/quota/refresh",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Ce("Failed to refresh quota",e.status);return e.json()}const Cn=8e3,wg=6e4,AA=32e3,yg=125e3,pt=1e4,or=45e3,bg=8e3,vg=8e3,Sg=15e3,kA=1e4,pr=5e3;let IA=0;const rs=[];let ba=!1;function Ht(t,e={}){if(typeof window>"u")return;const n=JSON.stringify({level:t==="error"||t==="timeout_or_abort"||t==="response_body_timeout"||t==="response_body_parse_error"?"warn":"info",message:`DIFF_API ${t}`,data:{seq:++IA,ts:Date.now(),...e}});rs.push(n),CA()}async function CA(){if(!ba){ba=!0;try{for(;rs.length>0;){const t=rs[0];try{await fetch("/api/client-log",{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:!0}),rs.shift()}catch{break}}}finally{ba=!1}}}function Sl(t,e,n){const r=new AbortController;let o=setTimeout(()=>{r.abort(new DOMException(n,"TimeoutError"))},e);const s=()=>r.abort(t?.reason);return t&&(t.aborted?s():t.addEventListener("abort",s,{once:!0})),{signal:r.signal,cleanup:()=>{o&&(clearTimeout(o),o=null),t?.removeEventListener("abort",s)}}}async function ge(t,e,n,r){const{signal:o,cleanup:s}=Sl(e?.signal??void 0,n,r);try{return await fetch(t,{...e,signal:o})}catch(i){throw i instanceof DOMException&&i.name==="TimeoutError"?new Error(r):i}finally{s()}}async function xg(t,e,n){let r=null;const o=new Promise((s,i)=>{r=setTimeout(()=>i(new Error(n)),e)});try{return await Promise.race([t.text(),o])}finally{r&&clearTimeout(r)}}async function gr(t,e,n){const r=await xg(t,e,n);return JSON.parse(r)}if(typeof window<"u"&&!window.__termdockFetchPatched){window.__termdockFetchPatched=!0;const t=window.fetch.bind(window);window.fetch=async(...e)=>{const n=await t(...e);if(n.status===401){Kn=null,Tl();try{window.dispatchEvent(new CustomEvent(vl))}catch{}}return n}}async function Z(){if(Kn)return Kn;const t=await ge("/api/csrf-token",void 0,bg,"CSRF token request timed out");if(!t.ok)throw new Error("Failed to get CSRF token");const e=await gr(t,pr,"CSRF token response timed out");if(!e.csrfToken)throw new Error("Invalid CSRF token response");return Kn=e.csrfToken,Kn}function xl(){Tl(),Kn=null}const RA=2e4,ef=8e3,TA=1500,Eg=250,ye=new Map,El=new Map,PA=24,NA=40,LA=40;function BA(t){return t.retryState.retryCount>=2||t.pendingInputs.length>=LA?"congested":t.retryState.retryCount>=1||t.pendingInputs.length>=8?"degraded":"good"}function tf(t){if(t.pendingInputs.length===0||t.ws.readyState!==WebSocket.OPEN)return;const e=t.pendingInputs.splice(0);for(const n of e)try{t.ws.send(JSON.stringify({type:"input",data:n}))}catch{}}function Ag(t){if(t.ws.readyState!==WebSocket.OPEN)return;const e=BA(t);if(e==="good"){tf(t);return}if(t.inputFlushTimer)return;const n=e==="congested"?NA:PA;t.inputFlushTimer=setTimeout(()=>{t.inputFlushTimer=null,tf(t)},n)}const to=new Map;function _A(t,e,n,r){const o=to.get(t);o&&(to.delete(t),e?o.resolve({success:!0,layout:n}):o.reject(new Error(r||"Tmux action failed")))}const Hn=new Map;function OA(t,e,n,r){const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/terminal/${t}/ws`,i=new URLSearchParams({flow:"2",transport:"tmux-client",active:El.get(t)===!1?"0":"1"});e>0&&i.set("since",String(e)),n&&i.set("epoch",n);const a=r??Hn.get(t);return a&&(i.set("cols",String(a.cols)),i.set("rows",String(a.rows))),`${s}?${i}`}const fc=new Map,hc=new Map;function DA(t,e,n){fc.set(t,e),hc.set(t,n)}function FA(t){const e=ye.get(t);return e?.streamEpoch&&e.appliedSeq===e.lastSeq&&e.lastSeq>0?{seq:e.lastSeq,epoch:e.streamEpoch}:null}async function MA(t){const e=await Z(),n=await fetch("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({cols:t.cols||80,rows:t.rows||24,mode:t.mode||"shell",tmuxSessionName:t.tmuxSessionName,cwd:t.cwd,termType:t.termType})});if(!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 jA(t,e,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=fc.get(t)??0,u=hc.get(t);hc.delete(t),fc.delete(t);const f=[];let h=!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)},w=x=>{x.wakeProbe&&(clearTimeout(x.wakeProbe.timer),x.wakeProbe=void 0),x.heartbeatTimer&&(clearInterval(x.heartbeatTimer),x.heartbeatTimer=null),x.pongTimer&&(clearTimeout(x.pongTimer),x.pongTimer=null),x.inputFlushTimer&&(clearTimeout(x.inputFlushTimer),x.inputFlushTimer=null)},R=x=>{w(x),x.heartbeatTimer=setInterval(()=>{if(x.ws.readyState===WebSocket.OPEN){try{x.ws.send(JSON.stringify({type:"ping"}))}catch{}x.pongTimer&&clearTimeout(x.pongTimer),x.pongTimer=setTimeout(()=>{if(Date.now()-x.lastInboundAt>=ef){h=!0,w(x);try{x.ws.close()}catch{}N(new Error("WebSocket heartbeat timeout"),!1)}},ef)}},RA)},y=()=>{if(c.isClosed=!0,b(),l){w(l),ye.delete(t);try{l.ws.close()}catch{}l=null}},k=()=>{if(c.isClosed)return;if(l){m.add(l.ws),w(l);try{l.ws.close()}catch{}}const x=OA(t,d,u,r.getDimensions?.()),T=Vp(x);h=!1,c.connectionTimeoutId=setTimeout(()=>{T.readyState!==WebSocket.OPEN&&(h=!0,T.close(),N(new Error("WebSocket connection timeout"),!1))},a);const S={ws:T,onEvent:e,onError:n,reconnectNow:v=>{if(!c.isClosed&&(c.isSuspended=!1,!g)){if(b(),l){m.add(l.ws),w(l);try{l.ws.close()}catch{}}v?.silent||e({type:"reconnecting",attempt:Math.min(c.retryCount+1,o),maxAttempts:o}),c.retryCount=Math.min(c.retryCount+1,o),h=!0,g=setTimeout(()=>{g=null,h=!1,k()},0)}},suspendReconnect:()=>{c.isClosed||(c.isSuspended=!0,c.retryTimeout&&(clearTimeout(c.retryTimeout),c.retryTimeout=null))},retryState:c,lastSeq:d,pendingInputs:f,inputFlushTimer:null,heartbeatTimer:null,pongTimer:null,lastInboundAt:Date.now(),inboundSequence:0};T.onopen=()=>{c.isClosed||m.has(T)||h||(b(),c.retryCount=0,S.lastInboundAt=Date.now(),S.inboundSequence+=1,R(S),Ag(S))},T.onmessage=v=>{if(!(c.isClosed||m.has(T)||h)){S.lastInboundAt=Date.now(),S.inboundSequence+=1;try{const A=JSON.parse(v.data);if(S.wakeProbe&&ye.get(t)===S){const B=S.wakeProbe;S.wakeProbe=void 0,clearTimeout(B.timer);for(const I of B.listeners)I()}if(A.type==="pong"){S.pongTimer&&(clearTimeout(S.pongTimer),S.pongTimer=null);return}if(A.type==="tmux-result"&&A.reqId){_A(A.reqId,A.success!==!1,A.layout,A.error);return}if(A.type==="tmux-layout"&&A.layout){e({type:"tmux-layout",layout:A.layout});return}if(A.type==="tmux-screen-sync"&&Array.isArray(A.chunks)){e({type:"tmux-screen-sync",chunks:A.chunks.filter(B=>typeof B=="string"),cols:typeof A.cols=="number"?A.cols:void 0,rows:typeof A.rows=="number"?A.rows:void 0,generation:typeof A.generation=="number"?A.generation:void 0});return}if(A.type==="active-program"){e({type:"active-program",activeProgram:A.activeProgram,activeProgramRaw:A.activeProgramRaw,activeProgramSource:A.activeProgramSource});return}if(A.type==="cwd"){e({type:"cwd",cwd:A.cwd});return}if(A.type==="agent-status"){e({type:"agent-status",agentStatus:A.agentStatus??null,agentIndicator:A.agentIndicator??null,agentStatusDetail:A.agentStatusDetail??null,agent:A.agent??null,agentMessage:A.agentMessage??null,agentNativeSessionId:A.agentNativeSessionId??null,agentResumeRecovered:A.agentResumeRecovered===!0,agentRich:A.agentRich===!0,agentActivity:typeof A.agentActivity=="number"?A.agentActivity:0,agentCwd:A.agentCwd??null,reviewed:typeof A.reviewed=="boolean"?A.reviewed:null});return}if(A.type==="git-status"){e({type:"git-status",gitStatus:A.gitStatus??null});return}if(A.type==="quota-status"&&Array.isArray(A.providers)){window.dispatchEvent(new CustomEvent("termdock:quota-update",{detail:A.providers}));return}if(A.type==="focus-mode"){e({type:"focus-mode",focusTrackingRequested:A.focusTrackingRequested===!0});return}if(A.type==="resize-ack"){e({type:"resize-ack",seq:typeof A.seq=="number"?A.seq:void 0,cols:typeof A.cols=="number"?A.cols:void 0,rows:typeof A.rows=="number"?A.rows:void 0,ok:A.ok!==!1,error:typeof A.error=="string"?A.error:void 0,screenSyncPending:A.screenSyncPending===!0,screenSyncGeneration:typeof A.screenSyncGeneration=="number"?A.screenSyncGeneration:void 0});return}if(A.type==="pty-size"){e({type:"pty-size",cols:typeof A.cols=="number"?A.cols:void 0,rows:typeof A.rows=="number"?A.rows:void 0,source:typeof A.source=="string"?A.source:void 0});return}if(A.type==="shell-title"){e({type:"shell-title",title:typeof A.title=="string"?A.title:""});return}if(A.type==="prompt-state"){e({type:"prompt-state",state:A.state==="running"?"running":"idle",exitCode:typeof A.exitCode=="number"?A.exitCode:void 0});return}const _=A;if(_.type==="connected"){S.appliedSeq=void 0,u=_.streamEpoch,S.streamEpoch=u,S.outputProtocol=_.outputProtocol,typeof _.replayLastSeq=="number"&&_.replayLastSeq>=0&&(d=_.replayLastSeq,S.lastSeq=d),e(_),kg(t,El.get(t)??!0);return}if(_.type==="exit"){y(),e(_);return}if(_.type==="data"){if(S.appliedSeq=void 0,typeof _.seq=="number"&&_.seq<=d)return;typeof _.flowSeq=="number"&&(S.flowSeq=_.flowSeq)}e(_),_.type==="data"&&typeof _.seq=="number"&&Number.isFinite(_.seq)&&_.seq>d&&(d=_.seq,S.lastSeq=d)}catch(A){n?.(A,!1)}}},T.onerror=()=>{c.isClosed||m.has(T)||h||(b(),w(S),h||(h=!0,N(new Error("WebSocket connection error"),!1)))},T.onclose=v=>{if(!(c.isClosed||m.has(T)||h)){if(v.code===Np&&v.reason===Lp){S.reconnectNow({silent:!0});return}if(b(),w(S),h=!0,v.code===4001){console.warn("[Terminal] WS 4001: Session not found on server",{code:v.code,reason:v.reason,stack:new Error().stack}),N(new Error("Session not found on server"),!0);return}if(v.code===4003||v.code===4401){try{window.dispatchEvent(new CustomEvent(vl))}catch{}N(new Error("Authentication required"),!0);return}N(new Error("WebSocket connection closed"),!1)}},l=S,ye.set(t,l)},N=(x,T)=>{if(!c.isClosed)if(T)n?.(x,!0),y();else{c.retryCount=Math.min(c.retryCount+1,Math.max(1,o));const S=Math.min(s*Math.pow(2,c.retryCount-1),i);if(e({type:"reconnecting",attempt:c.retryCount,maxAttempts:o}),c.isSuspended)return;c.retryTimeout=setTimeout(()=>{c.isClosed||k()},S)}};return k(),y}async function UA(t,e){const n=ye.get(t);if(n){if(n.ws.readyState===WebSocket.OPEN){n.pendingInputs.push(e),Ag(n);return}if(n.ws.readyState===WebSocket.CONNECTING){n.pendingInputs.push(e);return}}const r=await Z(),o=await fetch(`/api/terminal/${t}/input`,{method:"POST",headers:{"Content-Type":"text/plain","X-XSRF-TOKEN":r},body:e});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to send input"}));throw new Error(s.error||"Failed to send terminal input")}}function $A(t,e,n={}){const r=ye.get(t);if(!r)return!1;if(r.retryState.isSuspended=!1,r.ws.readyState!==WebSocket.OPEN)return r.reconnectNow(),!0;const o=n.visible?Eg:TA,s=Date.now()+o,i=r.wakeProbe,a=i?.listeners??new Set;if(e&&a.add(e),i&&i.deadline<=s)return!0;i&&clearTimeout(i.timer);const c=setTimeout(()=>{ye.get(t)!==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 HA(t){const e=ye.get(t);return e?(e.reconnectNow(),!0):!1}function qA(){for(const t of ye.values())t.suspendReconnect()}function KA(t,e,n){const r=ye.get(t);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"focus",focused:e,reason:n}))}catch{}}function kg(t,e){El.set(t,e);const n=ye.get(t);!n||n.ws.readyState!==WebSocket.OPEN||n.outputProtocol!==2||n.ws.send(JSON.stringify({type:"output-subscription",active:e,since:n.lastSeq,epoch:n.streamEpoch}))}function zA(t){const e=ye.get(t);!e||e.ws.readyState!==WebSocket.OPEN||e.outputProtocol!==2||(e.appliedSeq=e.lastSeq,!(!e.flowSeq||e.flowSeq===e.acknowledgedFlowSeq)&&(e.acknowledgedFlowSeq=e.flowSeq,e.ws.send(JSON.stringify({type:"output-ack",flowSeq:e.flowSeq,since:e.appliedSeq,epoch:e.streamEpoch}))))}function WA(t,e,n){const r=ye.get(t);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"viewing",viewing:e,reason:n}))}catch{}}function pc(t){const e=ye.get(t);if(!(!e||e.ws.readyState!==WebSocket.OPEN))try{e.ws.send(JSON.stringify({type:"agent-review-ack"}))}catch{}}function GA(t,e,n){const r=ye.get(t);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"flow-control",paused:e,reason:n}))}catch{}}async function VA(t,e,n,r){Number.isFinite(e)&&Number.isFinite(n)&&e>=1&&n>=1&&(Hn.delete(t),Hn.set(t,{cols:Math.floor(e),rows:Math.floor(n)}),Hn.size>256&&Hn.delete(Hn.keys().next().value));const o=ye.get(t);if(o&&o.ws.readyState===WebSocket.OPEN)try{o.ws.send(JSON.stringify({type:"resize",cols:e,rows:n,seq:r}));return}catch{}const s=await Z(),i=await fetch(`/api/terminal/${t}/resize`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":s},body:JSON.stringify({cols:e,rows: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 XA(t,e){const n=ye.get(t);if(n&&n.ws.readyState===WebSocket.OPEN)return e.action==="scroll"?(n.ws.send(JSON.stringify({type:"tmux",...e})),{success:!0}):new Promise((s,i)=>{const a=Math.random().toString(36).substring(7);to.set(a,{resolve:s,reject:i}),n.ws.send(JSON.stringify({type:"tmux",reqId:a,...e})),setTimeout(()=>{to.has(a)&&(to.delete(a),i(new Error("Tmux action timed out")))},3e4)});const r=await Z(),o=await fetch(`/api/terminal/${t}/tmux`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(e)});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to execute tmux action"}));throw new Error(s.error||"Failed to execute tmux action")}return o.json()}async function YA(t){const e=ye.get(t);if(e){e.retryState.isClosed=!0;try{e.ws.close()}catch{}ye.delete(t)}const n=await Z(),r=await fetch(`/api/terminal/${t}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":n}});if(r.status!==404&&!r.ok){const o=await r.json().catch(()=>({error:"Failed to close terminal"}));throw new Error(o.error||"Failed to close terminal")}}async function ZA(t,e){const n=ye.get(t);if(n){n.retryState.isClosed=!0;try{n.ws.close()}catch{}ye.delete(t)}const r=await Z(),o=await fetch(`/api/terminal/${t}/restart`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify({...e.cwd?{cwd:e.cwd}:{},cols:e.cols??80,rows:e.rows??24,mode:e.mode,tmuxSessionName:e.tmuxSessionName})});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to restart terminal"}));throw new Error(s.error||"Failed to restart terminal session")}return o.json()}async function JA(t){const e=await ge(`/api/terminal/${t}/health`,{method:"GET"},vg,"Terminal health check timed out");if(!e.ok){if(e.status===404)return{healthy:!1,sessionId:t};const n=await gr(e,pr,"Terminal health error response timed out").catch(()=>({error:"Failed to check terminal health"}));throw new Error(n.error||"Failed to check terminal health")}return gr(e,pr,"Terminal health response timed out")}async function QA(t){const e=await Z(),n=await ge("/api/terminal/force-kill",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)},kA,"Terminal force-kill request timed out");if(!n.ok){const r=await gr(n,pr,"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 ek(){const t=await fetch("/api/terminal/tmux/sessions",{method:"GET"});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to list tmux sessions"}));throw new Error(n.error||"Failed to list tmux sessions")}const e=await t.json();return Array.isArray(e.sessions)?e.sessions:[]}async function tk(){const t=await fetch("/api/terminal/tmux/status",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to get tmux status"}));throw new Error(e.error||"Failed to get tmux status")}return t.json()}async function nk(t){const e=t.trim();if(!e)throw new Error("tmux session name is required");const n=await Z(),r=await fetch(`/api/terminal/tmux/sessions/${encodeURIComponent(e)}`,{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 rk(){const t=await Z(),e=await fetch("/api/terminal/tmux/recovery/restore-all",{method:"POST",headers:{"X-XSRF-TOKEN":t}}),n=await e.json().catch(()=>({}));if(!e.ok)throw new Ce(n.error||"Failed to restore tmux Agent sessions",e.status);return n}async function ok(){const t=await Z(),e=await fetch("/api/terminal/tmux/recovery",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Ce("Failed to dismiss tmux recovery",e.status)}const zo=new Map;function sk(t){return JSON.stringify({preferredFrontendSessionId:t.preferredFrontendSessionId??null,mode:t.mode??null,tmuxSessionName:t.tmuxSessionName??null,cwd:t.cwd??null,termType:t.termType??null,createIfEmpty:t.createIfEmpty===!0,requireExisting:t.requireExisting===!0})}async function Ig(){const t=await fetch("/api/terminal/session-inventory",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to load session inventory"}));throw new Error(e.error||"Failed to load session inventory")}return t.json()}async function Cg(t){const e=sk(t),n=zo.get(e);if(n)return n;const r=await Z(),o=ge("/api/terminal/session-inventory/open",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(t)},Sg,"Terminal session open request timed out").then(async s=>{if(!s.ok){const i=await gr(s,pr,"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 gr(s,pr,"Terminal session open response timed out")}).finally(()=>{zo.get(e)===o&&zo.delete(e)});return zo.set(e,o),o}async function os(t,e){const n=await Z(),r=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify(e)});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 Rg(t){const e=await Z(),n=await fetch("/api/terminal/session-inventory/reorder",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({sessionIds:t})});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 Tg(t){const e=await Z(),n=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});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 Pg(){const t=await Z(),e=await fetch("/api/terminal/session-inventory/sessions",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to clear sessions"}));throw new Error(n.error||"Failed to clear sessions")}}async function ik(){const t=await fetch("/api/terminal/toolbar-presets",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to load toolbar presets"}));throw new Error(e.error||"Failed to load toolbar presets")}return t.json()}async function ak(t){const e=await Z(),n=await fetch("/api/terminal/toolbar-presets",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});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 Dr=null,Wr=null;const Ng=1500;function sr(){return Wr&&Date.now()-Wr.readAt<Ng?Promise.resolve(Wr.value):Dr||(Dr=(async()=>{const t=await fetch("/api/terminal/settings",{method:"GET"});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to load settings"}));throw new Error(n.error||"Failed to load settings")}const e=await t.json();return Wr={value:e,readAt:Date.now()},e})().finally(()=>{Dr=null}),Dr)}async function Et(t){const e=await Z(),n=await fetch("/api/terminal/settings",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});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 Wr={value:r,readAt:Date.now()},r}async function ck(t=!1){const e=await fetch(`/api/terminal/auto-title/catalog${t?"?refresh=1":""}`);if(!e.ok)throw new Error("Failed to discover title models");const n=await e.json();return Array.isArray(n?.namers)?n.namers:[]}let Fr=null,Gr=null;function lk(){return Gr&&Date.now()-Gr.readAt<Ng?Promise.resolve(Gr.value):Fr||(Fr=(async()=>{const t=await fetch("/api/terminal/context-draft",{method:"GET"});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to load context draft"}));throw new Error(n.error||"Failed to load context draft")}const e=await t.json();return Gr={value:e,readAt:Date.now()},e})().finally(()=>{Fr=null}),Fr)}async function dk(t,e){const n=await Z(),r=await fetch("/api/terminal/context-draft",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify({text:t,origin:e})});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 Gr={value:o,readAt:Date.now()},o}async function Lg(t){const e=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:t})});if(e.ok)return xl(),{ok:!0};const n=await e.json().catch(()=>null);return e.status===429?{ok:!1,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,error:n?.error||"Login failed"}}async function uk(){bl(),gg();const t=await Z();await fetch("/api/auth/logout",{method:"POST",headers:{"X-XSRF-TOKEN":t}}),xl()}async function fk(){const t=await fetch("/api/terminal/agent-launchers");if(!t.ok)throw new Error("Failed to detect agent launchers");const e=await t.json();return Array.isArray(e?.agents)?e.agents:[]}async function hk(){const t=await fetch("/api/terminal/agent-hooks");if(!t.ok)throw new Error("Failed to get agent hooks");const e=await t.json();return Array.isArray(e?.agents)?e.agents:[]}async function pk(t){const e=await Z(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(t)}/install`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),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 gk(t){const e=await Z(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(t)}/uninstall`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to uninstall agent hooks");return r.summary??"Removed"}class Al extends Error{constructor(e,n,r){super(e),this.code=n,this.migration=r,this.name="AgentPluginManifestError"}code;migration}async function mk(){const t=await fetch("/api/terminal/agent-plugins");if(!t.ok)throw new Error("Failed to get agent plugins");return await t.json()}async function wk(t){const e=await Z(),n=await fetch("/api/terminal/agent-plugins",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Al(r.error||"Failed to create agent plugin",r.code,r.migration);return r}async function yk(t){const e=await Z(),n=await fetch("/api/terminal/agent-plugins/install",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({source:t})}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Al(r.error||"Failed to install agent plugin",r.code,r.migration);return r}async function bk(t){const e=await Z(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/check-update`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to check plugin updates");return r}async function vk(t){const e=await Z(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/update`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to update plugin");return r}async function Sk(t){const e=await Z(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/doctor`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to diagnose plugin");return r}async function xk(t){const e=await Z(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||"Failed to delete agent plugin")}}async function Ek(t){const e=await Z(),n=await fetch(`/api/terminal/${encodeURIComponent(t)}/agent-resume`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),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 Ak(){const t=await fetch("/api/terminal/agent-resume-history",{method:"GET"});if(!t.ok)throw new Error("Failed to load Agent resume history");const e=await t.json().catch(()=>({entries:[]}));return Array.isArray(e.entries)?e.entries:[]}async function kk(t){const e=await Z(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(t)}/prepare`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),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 Ik(t){const e=await Z(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!n.ok&&n.status!==404)throw new Error("Failed to remove Agent resume history")}async function Ck(t){const e=await Z(),n=await fetch("/api/terminal/program-rules",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});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 Rk(){const t=await Z(),e=await fetch("/api/terminal/program-rules",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Error("Failed to reset program rules");return e.json()}async function Tk(){const t=await fetch("/api/terminal/program-detection");if(!t.ok)throw new Error("Failed to get program detection config");return t.json()}async function Pk(t){const e=await Z(),n=await fetch("/api/terminal/program-detection",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!n.ok)throw new Error("Failed to save program detection config");return n.json()}async function Nk(){const t=await Z(),e=await fetch("/api/terminal/program-detection",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Error("Failed to reset program detection config");return e.json()}const Lk={".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 li(t){const e=t.lastIndexOf(".");return e<0?null:Lk[t.slice(e).toLowerCase()]??null}function Bk(t){return li(t)!==null}function Bg(t){const e=li(t);return e==="image/heic"||e==="image/heif"}const _k={".mp4":"video/mp4",".m4v":"video/x-m4v",".webm":"video/webm",".mov":"video/quicktime",".ogv":"video/ogg",".mpeg":"video/mpeg",".mpg":"video/mpeg"};function _g(t){const e=t.lastIndexOf(".");return e<0?null:_k[t.slice(e).toLowerCase()]??null}function Ok(t){return _g(t)!==null}function Dk(t){return`/api/terminal/fs/video?path=${encodeURIComponent(t)}&action=view_file`}const Og=[".stl",".glb",".gltf"];function kl(t){const e=t.lastIndexOf(".");if(e<0)return null;const n=t.slice(e).toLowerCase();return Og.includes(n)?n:null}function Fk(t){return kl(t)!==null}function Il(t){const e=t.toLowerCase();return e.endsWith(".kicad_sch")?".kicad_sch":e.endsWith(".kicad_pcb")?".kicad_pcb":null}function Mk(t){return Il(t)!==null}function jk(t){return Il(t)===".kicad_pcb"?"pcb-front":"schematic"}const Dg=[".html",".htm"];function Uk(t){const e=t.lastIndexOf(".");if(e<0)return!1;const n=t.slice(e).toLowerCase();return Dg.includes(n)}function $k(t){return`/api/terminal/fs/preview/${t.split(/[\\/]+/).filter(Boolean).map(n=>encodeURIComponent(n)).join("/")}`}const Hk={".stl":"model/stl",".glb":"model/gltf-binary",".gltf":"model/gltf+json"};async function qk(t,e,n,r="list_directory",o,s="name"){const i=new URLSearchParams({path:t});n&&i.set("showHidden","true"),s!=="name"&&i.set("sort",s),i.set("action",r),o&&i.set("requestSlotId",o);const a=await ge(`/api/terminal/fs/list?${i}`,{signal:e},Cn,"Directory listing took too long. The folder may be on slow storage or blocked by another process.");if(!a.ok){const c=await a.json().catch(()=>({error:"Failed to list directory"}));throw new Error(c.error||"Failed to list directory")}return a.json()}async function Kk(t,e,n,r,o,s="name",i,a={}){const c=new URLSearchParams({path:t,query:e,stream:"true"});o&&c.set("showHidden","true"),s==="content"&&c.set("mode","content"),i&&c.set("requestSlotId",i);for(const g of a.excludePatterns??[])c.append("exclude",g);a.caseSensitive&&c.set("caseSensitive","true"),a.wholeWord&&c.set("wholeWord","true"),a.regex&&c.set("regex","true");const l=await fetch(`/api/terminal/fs/search?${c}`,{signal: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 h=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(`
8
+ `);const B=y(T,S,A),C=t.getSymbolSize(T),E=new r(C);return h(E,T),g(E),m(E,T),w(E,S,0),T>=7&&b(E,T),R(E,B),isNaN(v)&&(v=i.getBestMask(E,w.bind(null,E,S))),i.applyMask(v,E),w(E,S,v),{modules:E,version:T,errorCorrectionLevel:S,maskPattern:v,segments:A}}return Zi.create=function(T,S){if(typeof T>"u"||T==="")throw new Error("No input text");let v=e.M,A,_;return typeof S<"u"&&(v=e.from(S.errorCorrectionLevel,e.M),A=l.from(S.version),_=i.from(S.maskPattern),S.toSJISFunc&&t.setToSJISFunction(S.toSJISFunc)),N(T,A,v,_)},Zi}var ma={},wa={},Gu;function hg(){return Gu||(Gu=1,(function(t){function e(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("")}}t.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:e(r.color.dark||"#000000ff"),light:e(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},t.getScale=function(r,o){return o.width&&o.width>=r+o.margin*2?o.width/(r+o.margin*2):o.scale},t.getImageWidth=function(r,o){const s=t.getScale(r,o);return Math.floor((r+o.margin*2)*s)},t.qrToImageData=function(r,o,s){const i=o.modules.size,a=o.modules.data,c=t.getScale(i,s),l=Math.floor((i+s.margin*2)*c),d=s.margin*c,u=[s.color.light,s.color.dark];for(let f=0;f<l;f++)for(let h=0;h<l;h++){let g=(f*l+h)*4,m=s.color.light;if(f>=d&&h>=d&&f<l-d&&h<l-d){const b=Math.floor((f-d)/c),w=Math.floor((h-d)/c);m=u[a[b*i+w]?1:0]}r[g++]=m.r,r[g++]=m.g,r[g++]=m.b,r[g]=m.a}}})(wa)),wa}var Xu;function Z1(){return Xu||(Xu=1,(function(t){const e=hg();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")}}t.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=e.getOptions(c);const d=e.getImageWidth(s.modules.size,c),u=l.getContext("2d"),f=u.createImageData(d,d);return e.qrToImageData(f.data,s,c),n(u,l,d),u.putImageData(f,0,0),l},t.renderToDataURL=function(s,i,a){let c=a;typeof c>"u"&&(!i||!i.getContext)&&(c=i,i=void 0),c||(c={});const l=t.render(s,i,c),d=c.type||"image/png",u=c.rendererOpts||{};return l.toDataURL(d,u.quality)}})(ma)),ma}var ya={},Yu;function J1(){if(Yu)return ya;Yu=1;const t=hg();function e(o,s){const i=o.a/255,a=s+'="'+o.hex+'"';return i<1?a+" "+s+'-opacity="'+i.toFixed(2).slice(1)+'"':a}function 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),h=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+h+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 ya.render=function(s,i,a){const c=t.getOptions(i),l=s.modules.size,d=s.modules.data,u=l+c.margin*2,f=c.color.light.a?"<path "+e(c.color.light,"fill")+' d="M0 0h'+u+"v"+u+'H0z"/>':"",h="<path "+e(c.color.dark,"stroke")+' d="'+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+h+`</svg>
9
+ `;return typeof a=="function"&&a(null,b),b},ya}var Zu;function Q1(){if(Zu)return Dn;Zu=1;const t=B1(),e=Y1(),n=Z1(),r=J1();function o(s,i,a,c,l){const d=[].slice.call(arguments,1),u=d.length,f=typeof d[u-1]=="function";if(!f&&!t())throw new Error("Callback required as last argument");if(f){if(u<2)throw new Error("Too few arguments provided");u===2?(l=a,a=i,i=c=void 0):u===3&&(i.getContext&&typeof l>"u"?(l=c,c=void 0):(l=c,c=a,a=i,i=void 0))}else{if(u<1)throw new Error("Too few arguments provided");return u===1?(a=i,i=c=void 0):u===2&&!i.getContext&&(c=a,a=i,i=void 0),new Promise(function(h,g){try{const m=e.create(a,c);h(s(m,i,c))}catch(m){g(m)}})}try{const h=e.create(a,c);l(null,s(h,i,c))}catch(h){l(h)}}return Dn.create=e.create,Dn.toCanvas=o.bind(null,n.render),Dn.toDataURL=o.bind(null,n.renderToDataURL),Dn.toString=o.bind(null,function(s,i,a){return r.render(s,a)}),Dn}var eA=Q1();const Or="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",Ye="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",Fn=`${Ye} bg-primary text-primary-foreground hover:opacity-90`;function tA(t){return t.serviceName||new URL(t.url).hostname}function Ju(t){return t.includes("service:*")?"完整权限":t.includes("session.input")?"可操作":t.includes("session.view")?"只读":t.includes("route.use")?"仅中转":"自定义权限"}function nA({profile:t,subjectId:e}){return p.jsxs("details",{className:"mt-2 text-xs text-muted-foreground",children:[p.jsx("summary",{className:"cursor-pointer leading-relaxed",children:[t?.model||t?.hostname||t?.system,t?.route,`ID ${e.slice(-8)}`].filter(Boolean).join(" · ")}),p.jsxs("dl",{className:"mt-2 space-y-2 rounded-lg bg-surface-2 p-3",children:[[["设备型号",t?.model],["主机名称",t?.hostname],["操作系统",t?.system],["客户端",t?.client],["打开方式",t?.mode],["处理器",t?.cpu],["架构",t?.arch],["最近连接路径",t?.route],["首次记录",t?.firstSeenAt?new Date(t.firstSeenAt).toLocaleString():void 0],["最近连接",t?.lastSeenAt?new Date(t.lastSeenAt).toLocaleString():void 0],["设备标识",e]].filter(([,n])=>n).map(([n,r])=>p.jsxs("div",{children:[p.jsx("dt",{children:n}),p.jsx("dd",{className:"mt-0.5 select-text break-all text-foreground",children:r})]},n)),p.jsx("p",{className:"leading-relaxed",children:t?"系统、硬件与路径由设备报告;连接时间由服务记录。":"此设备尚未报告详情,更新客户端并重新连接后可补齐。"})]})]})}function rA(){const t=getComputedStyle(document.documentElement),e=t.getPropertyValue("--background").trim(),n=t.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(!e||!n)throw new Error("Theme unavailable");return r(e)<r(n)?{dark:e,light:n}:{dark:n,light:e}}function oA({onConnect:t,onClose:e,onConnectWithPassword:n,onAddService:r,onOpenService:o,currentIdentity:s,currentServiceName:i,currentServiceId:a,currentServiceOrigin:c,hasBackup:l=!1,inviteAddresses:d=[],paired:u=!1,initialInvite:f,sessions:h=[],grants:g=[],onCreateInvite:m,onRevoke:b,onRename:w,loading:R=!1,loadError:y,onRetry:k}){const[N,x]=O.useState(!1),[T,S]=O.useState(""),[v,A]=O.useState({}),[_,B]=O.useState(""),[C,E]=O.useState(""),[P,I]=O.useState(!1),[D,M]=O.useState(!1),[F,L]=O.useState(!u),[$,H]=O.useState(!0),[U,q]=O.useState(""),[K,X]=O.useState(""),[z,W]=O.useState("read"),[V,Y]=O.useState("all"),[Q,ae]=O.useState([]),[ce,ie]=O.useState(!1),[$e,ke]=O.useState(""),[Ge,en]=O.useState(""),[Oe,gi]=O.useState(),[vr,jl]=O.useState(""),[_t,vm]=O.useState("services"),[Tn,mi]=O.useState(),[wi,Ul]=O.useState(""),[Sr,$l]=O.useState(!1),[Hl,xr]=O.useState(),[mt,ko]=O.useState(!1),[Pn,ql]=O.useState([]),yi=g.filter(j=>j.revokedAt===void 0&&(!j.expiresAt||j.expiresAt>Date.now())),bi=g.filter(j=>!yi.includes(j)),Er=[...new Set(yi.map(j=>j.subjectId))].map(j=>{const G=yi.filter(me=>me.subjectId===j);return{subjectId:j,grants:G,name:j===s?"此设备":G.find(me=>me.label)?.label||"未命名设备"}}).sort((j,G)=>+(G.subjectId===s)-+(j.subjectId===s)),Nn=!Tn&&!Sr&&u&&!F&&!D&&!f,Sm=()=>{mi(void 0),$l(!1),L(!1),M(!1),gi(void 0),ie(!1),B(""),E(""),xr(void 0),q(""),X("")},Kl=()=>{M(!0),L(!1),ie(!1),B(""),E("")},xm=j=>j.subjectId===s?"此设备":j.label||"未命名设备",vi=()=>{mt?ko(!1):e()},Ar=O.useRef(null);O.useEffect(()=>{const j=document.activeElement;return Ar.current?.focus(),()=>{j?.focus()}},[]),O.useEffect(()=>{let j=!1;if(jl(""),Oe)try{eA.toDataURL(Oe.url,{width:220,margin:3,errorCorrectionLevel:"M",color:rA()}).then(G=>{j||jl(G)}).catch(()=>{})}catch{}return()=>{j=!0}},[Oe]);async function Si(j){I(!0),B(""),E("");try{await t(j);const{url:G,targetPeerId:me,serviceName:Xe,serviceOrigin:Ln}=j;await Tt({id:me,url:G,targetPeerId:me,label:Xe||new URL(G).host,serviceOrigin:Ln,entryServiceId:j.entryServiceId}),L(!1),E("已连接。")}catch(G){j.routeOnly&&G instanceof et?x(!0):B("暂时无法连接,请检查网络,或确认邀请是否仍然有效。")}finally{I(!1)}}async function Em(j){if(j.preventDefault(),!m)return;B(""),E("");const G=Q.filter(wt=>h.some(xi=>xi.sessionId===wt));if(z!=="full"&&V==="selected"&&!G.length){B("请选择至少一个 Session。");return}const me=G.map(wt=>h.find(xi=>xi.sessionId===wt)?.sourceSessionId||wt),Xe=Ge?new Date(Ge).getTime():void 0;if(Xe!==void 0&&(!Number.isFinite(Xe)||Xe<=Date.now())){B("授权到期时间必须晚于现在。");return}let Ln;if(U==="custom")try{Ln=_e(K)}catch{B("请输入有效的接入地址,例如 https://192.168.1.23:9834。");return}else U&&(Ln=U);I(!0);try{const wt=await m({...l?{includeBackup:$}:{},...Ln?{entryAddress:Ln}:{},scope:z==="full"||V==="all"?{kind:"service"}:{kind:"sessions",sessionIds:me},actions:z==="full"?["service:*"]:z==="write"?["session.view","session.input","session.resize"]:["session.view"],...$e.trim()?{label:$e.trim()}:{},...Xe===void 0?{}:{expiresAt:Xe}});gi(wt)}catch(wt){B(wt instanceof Error&&wt.message.startsWith("无法分享备用连接:")?"无法分享备用连接:需要入口管理员授权。你也可以关闭“包含备用连接”,生成直连邀请。":"暂时无法生成邀请,请确认当前设备有授权管理权限。")}finally{I(!1)}}async function Am(){if(Oe)try{await navigator.clipboard.writeText(Oe.url),E("邀请链接已复制。")}catch{B("浏览器未允许复制,请长按下方链接复制。")}}const km=v.title||(Tn?"设备名称":Sr?_t==="devices"?"授权详情":"连接详情":mt?"选择终端":D?"邀请设备":F&&u?"添加服务":u?"服务与设备":"连接 Termdock"),Cm=!!v.back||!!Tn||Sr||mt||u&&(F||D),Im=()=>{if(v.back){v.back();return}mt?ko(!1):Sm()},zl=j=>j.every(G=>G.routeTargetServiceId)?`${new Set(j.map(G=>G.routeTargetServiceId)).size} 台服务`:j.some(G=>G.scope.kind==="service")?"全部终端":`${new Set(j.flatMap(G=>G.scope.kind==="sessions"?G.scope.sessionIds:[])).size} 个终端`;return Oc.createPortal(p.jsx("div",{className:"fixed inset-0 z-modal-backdrop flex items-end justify-center bg-[var(--app-backdrop)] backdrop-blur-sm sm:items-center sm:p-6","data-sidebar-gesture-ignore":!0,onMouseDown:j=>{j.target===j.currentTarget&&!P&&vi()},children:p.jsxs("div",{ref:Ar,tabIndex:-1,role:"dialog","aria-modal":"true","aria-labelledby":"federation-title",className:"z-modal-panel flex max-h-[calc(100dvh-env(safe-area-inset-top)-12px)] w-full max-w-lg flex-col overflow-hidden rounded-t-2xl border border-border bg-surface font-sans text-foreground shadow-xl outline-none sm:max-h-[min(720px,90dvh)] sm:rounded-2xl",onKeyDown:j=>{if(j.key==="Escape"&&!P&&(j.stopPropagation(),vi()),j.key!=="Tab")return;const G=Ar.current?.querySelectorAll('button:not(:disabled), input:not(:disabled), textarea:not(:disabled), select:not(:disabled), [tabindex="0"], summary');if(!G?.length){j.preventDefault();return}const me=G[0],Xe=G[G.length-1];j.shiftKey&&(document.activeElement===me||document.activeElement===Ar.current)?(j.preventDefault(),Xe.focus()):!j.shiftKey&&(document.activeElement===Xe||document.activeElement===Ar.current)&&(j.preventDefault(),me.focus())},children:[p.jsxs("header",{className:"shrink-0 border-b border-border px-5 pt-3",children:[p.jsxs("div",{className:"flex min-h-12 items-center gap-2 pb-2",children:[Cm&&p.jsx("button",{type:"button",className:`${Ye} -ml-3 inline-flex w-11 items-center justify-center text-muted-foreground`,disabled:P,onClick:Im,"aria-label":mt?"取消选择终端":_t==="devices"?"返回设备":"返回服务",children:p.jsx(Zp,{size:20})}),p.jsx("h2",{id:"federation-title",className:"min-w-0 flex-1 text-base font-semibold",children:km}),p.jsx("button",{type:"button",className:`${Ye} -mr-3 inline-flex w-11 items-center justify-center text-muted-foreground`,disabled:P,onClick:vi,"aria-label":"关闭",children:p.jsx(og,{size:20})})]}),Nn&&!v.title&&p.jsx("div",{className:"flex gap-6",role:"tablist","aria-label":"管理内容",children:[["services","服务"],["devices","设备"]].map(([j,G])=>p.jsxs("button",{type:"button",role:"tab","aria-selected":_t===j,"aria-controls":`federation-${j}`,id:`federation-tab-${j}`,className:`min-h-11 border-b-2 px-1 text-sm transition ${_t===j?"border-primary font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"}`,onClick:()=>{vm(j),ie(!1),xr(void 0),B(""),E("")},children:[G,j==="devices"&&Er.length>0&&p.jsx("span",{className:"ml-1.5 text-xs text-muted-foreground",children:Er.length})]},j))})]}),p.jsxs("div",{className:"min-h-0 overflow-y-auto overscroll-contain px-5 py-4 pb-[max(20px,env(safe-area-inset-bottom))]",children:[(Nn&&_t==="services"||F&&!D&&!f)&&p.jsx(P1,{renderRelayServices:(j,G)=>p.jsx(R1,{service:j,onBusyChange:G,onConnect:t,onConnectWithPassword:n}),renderRoutes:(j,G)=>p.jsx(T1,{service:j,onBusyChange:G}),hideHeader:!0,initiallyAdding:F,current:a?{id:a,targetPeerId:a,url:c||location.origin,label:i||"当前服务"}:void 0,onNavigation:A,onBusyChange:I,onInvite:m?Kl:void 0,onOpen:async j=>{if(o)return o(j);j.targetPeerId?await Si({...j,targetPeerId:j.targetPeerId,serviceName:j.label}):r&&await r(j.url)},onAdd:async(j,G)=>{if(r)return r(j,G);await Si(Ds(j))}}),Nn&&_t==="devices"&&p.jsxs("section",{role:"tabpanel",id:"federation-devices","aria-labelledby":"federation-tab-devices",children:[p.jsx("p",{className:"mb-2 text-xs leading-relaxed text-muted-foreground",children:"可访问此服务的设备"}),R?p.jsxs("p",{role:"status",className:"flex items-center gap-2 py-5 text-sm text-muted-foreground",children:[p.jsx(je,{size:16,className:"animate-spin"}),"正在读取设备…"]}):p.jsxs("div",{className:"divide-y divide-border",children:[Er.map(j=>p.jsxs("div",{className:"py-3",children:[p.jsxs("div",{className:"flex items-center gap-3",children:[p.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-surface-2 text-muted-foreground",children:/iPhone|iPad|Android|手机|平板/i.test(j.grants.find(G=>G.label)?.label||(j.subjectId===s?navigator.userAgent:""))?p.jsx(rg,{size:19}):p.jsx(e1,{size:19})}),p.jsxs("div",{className:"min-w-0 flex-1",children:[p.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[p.jsx("p",{className:"truncate text-sm font-medium",children:j.name}),w&&(b||j.subjectId===s)&&p.jsx("button",{type:"button","aria-label":`重命名 ${j.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:()=>{mi(j.subjectId),Ul(j.grants.find(G=>G.label)?.label||"")},children:p.jsx(n1,{size:14})})]}),j.subjectId===s&&j.grants.find(G=>G.label)?.label&&p.jsx("p",{className:"truncate text-xs text-muted-foreground",children:j.grants.find(G=>G.label)?.label}),p.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[Ju(j.grants.flatMap(G=>G.actions))," · ",zl(j.grants)]})]}),b&&j.subjectId!==s&&Hl!==j.subjectId&&p.jsx("button",{type:"button",className:`${Ye} -mr-2 text-xs text-muted-foreground hover:text-destructive`,disabled:P,"aria-label":`撤销 ${j.name} 的访问权限`,onClick:()=>xr(j.subjectId),children:"撤销"})]}),p.jsx(nA,{profile:j.grants.find(G=>G.deviceProfile)?.deviceProfile,subjectId:j.subjectId}),Hl===j.subjectId&&p.jsxs("div",{className:"mt-3 rounded-lg border border-border bg-background p-3",children:[p.jsx("p",{className:"text-xs leading-relaxed",children:"撤销后,这台设备将断开连接,需重新邀请才能访问。"}),p.jsxs("div",{className:"mt-2 flex justify-end gap-2",children:[p.jsx("button",{type:"button",className:`${Ye} text-xs text-muted-foreground`,disabled:P,onClick:()=>xr(void 0),children:"取消"}),p.jsx("button",{type:"button",className:`${Ye} text-xs text-destructive`,disabled:P,onClick:async()=>{I(!0),B("");try{for(const G of j.grants)await b?.(G.id);xr(void 0),E("设备访问权限已撤销。")}catch{B("暂时无法撤销,请重试。")}finally{I(!1)}},children:"确认撤销"})]})]})]},j.subjectId)),Er.length===0&&!y&&p.jsxs("p",{className:"py-5 text-sm text-muted-foreground",children:["暂无设备授权。",m?"可通过邀请添加设备。":""]})]}),m&&p.jsxs("button",{type:"button",className:`${Ye} mt-4 inline-flex w-full items-center justify-center gap-2 border border-border text-sm`,disabled:P,onClick:Kl,children:[p.jsx(ng,{size:16}),"邀请设备"]}),bi.length>0&&p.jsxs("details",{className:"mt-4 text-xs text-muted-foreground",children:[p.jsxs("summary",{className:"cursor-pointer py-2",children:["已失效的授权(",bi.length,")"]}),p.jsx("div",{className:"mt-1 space-y-2 border-l border-border pl-3",children:bi.map(j=>p.jsxs("p",{className:"flex gap-3",children:[p.jsx("span",{className:"min-w-0 flex-1 truncate",children:xm(j)}),p.jsx("span",{className:"shrink-0",children:j.revokedAt!==void 0?"已撤销":"已到期"})]},j.id))})]})]}),Tn&&p.jsxs("form",{className:"space-y-4",onSubmit:async j=>{j.preventDefault(),I(!0),B("");try{await w?.(Tn,wi.trim()),mi(void 0)}catch{B("暂时无法保存设备名称,请重试。")}finally{I(!1)}},children:[p.jsxs("label",{className:"block space-y-2 text-sm",children:[p.jsx("span",{children:"设备名称"}),p.jsx("input",{autoFocus:!0,className:Or,maxLength:80,required:!0,value:wi,onChange:j=>Ul(j.target.value),placeholder:"例如:我的 iPhone、办公室电脑"})]}),p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"为设备起一个容易辨认的名字,会同步显示在此服务的设备列表中。"}),p.jsx("button",{type:"submit",className:`${Fn} w-full`,disabled:P||!wi.trim(),children:P?"正在保存…":"保存名称"})]}),Sr&&p.jsx("section",{className:"space-y-5",children:_t==="devices"?Er.map(j=>p.jsxs("div",{className:"space-y-3",children:[p.jsx("h3",{className:"text-sm font-medium",children:j.name}),p.jsxs("dl",{className:"space-y-3 rounded-xl bg-surface-2 p-3 text-xs",children:[p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"访问权限"}),p.jsxs("dd",{className:"mt-1",children:[Ju(j.grants.flatMap(G=>G.actions))," · ",zl(j.grants)]})]}),j.grants.map(G=>p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:G.routeTargetServiceId?"允许经此入口访问":G.scope.kind==="sessions"?"可访问终端":"有效期"}),p.jsx("dd",{className:"mt-1 leading-relaxed",children:G.routeTargetServiceId?G.routeTargetName||"指定服务":G.scope.kind==="sessions"?G.scope.sessionIds.map(me=>h.find(Xe=>Xe.sessionId===me)?.name||me).join("、"):G.expiresAt?new Date(G.expiresAt).toLocaleString():"保留至撤销"}),G.routeTargetServiceId&&b&&p.jsx("button",{type:"button",className:`${Ye} mt-1 -ml-3 text-xs text-destructive`,disabled:P,onClick:async()=>{I(!0),B("");try{await b(G.id)}catch{B("暂时无法撤销,请重试。")}finally{I(!1)}},children:"撤销此中转权限"})]},G.id)),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"设备标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed text-muted-foreground select-text",children:j.subjectId})]})]})]},j.subjectId)):p.jsxs("dl",{className:"space-y-4 text-xs",children:[p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"当前服务"}),p.jsx("dd",{className:"mt-1 text-sm",children:i||"当前服务"})]}),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"服务标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed select-text",children:a})]}),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"本设备标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed select-text",children:s})]})]})}),f&&!D&&p.jsxs("section",{className:"space-y-5 py-1",children:[p.jsxs("div",{className:"flex items-center gap-3",children:[p.jsx("span",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-surface-2 text-muted-foreground",children:p.jsx(ai,{size:22})}),p.jsxs("div",{className:"min-w-0",children:[p.jsx("p",{className:"text-xs text-muted-foreground",children:"你受邀连接"}),p.jsx("p",{className:"mt-1 break-words text-base font-medium",children:tA(f)})]})]}),f.routeOnly&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"此邀请提供备用连接,目标服务仍会验证你的访问权限。"}),N?p.jsxs("form",{className:"space-y-3",onSubmit:async j=>{j.preventDefault(),I(!0),B("");try{await n?.(f,T)}catch(G){B(G instanceof Error?G.message:"暂时无法登录,请重试。")}finally{S(""),I(!1)}},children:[p.jsxs("label",{className:"block space-y-2 text-sm",children:[p.jsx("span",{children:"目标服务密码"}),p.jsx("input",{className:Or,type:"password",required:!0,autoFocus:!0,autoComplete:"current-password",value:T,onChange:j=>S(j.target.value)})]}),p.jsx("button",{className:`${Fn} w-full`,disabled:P||!T,children:P?"正在登录…":"登录并连接"})]}):p.jsx("button",{type:"button",className:`${Fn} w-full text-sm`,disabled:P,onClick:()=>{Si(f)},children:P?"正在连接…":"接受邀请"})]}),D&&!mt&&p.jsx("section",{children:Oe?p.jsxs("div",{className:"space-y-4 text-center",children:[p.jsx("p",{className:"text-sm font-medium",children:"用另一台设备扫描二维码"}),vr?p.jsx("img",{src:vr,width:220,height:220,className:"mx-auto max-w-full rounded-xl",alt:"设备邀请二维码"}):p.jsx("div",{className:"mx-auto flex h-48 w-48 items-center justify-center",children:p.jsx(je,{size:22,className:"animate-spin text-muted-foreground"})}),p.jsxs("p",{className:"text-xs leading-relaxed text-muted-foreground",children:["仅限一台设备使用 · ",new Date(Oe.expiresAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," 前有效"]}),p.jsxs("button",{type:"button",className:`${Fn} inline-flex w-full items-center justify-center gap-2 text-sm`,onClick:()=>{Am()},children:[p.jsx(eg,{size:16}),"复制邀请链接"]}),p.jsxs("details",{className:"text-left text-xs text-muted-foreground",children:[p.jsx("summary",{className:"cursor-pointer py-2",children:"查看链接"}),p.jsx("p",{className:"mt-2 select-all break-all",children:Oe.url})]})]}):p.jsxs("form",{className:"space-y-5",onSubmit:Em,children:[p.jsxs("fieldset",{children:[p.jsx("legend",{className:"mb-2 text-sm font-medium",children:"访问权限"}),p.jsx("div",{className:"space-y-2",children:[["read","仅查看","查看终端画面,不可输入命令"],["write","可操作","查看终端画面,并输入命令"],["full","完整访问","包括文件、设置和权限管理"]].map(([j,G,me])=>p.jsxs("label",{className:`flex cursor-pointer items-center gap-3 rounded-xl border px-3 py-2.5 transition focus-within:ring-2 focus-within:ring-ring ${z===j?"border-primary bg-primary/10":"border-border hover:bg-surface-2"}`,children:[p.jsx("input",{type:"radio",name:"federation-permission",value:j,checked:z===j,onChange:()=>W(j),className:"sr-only"}),p.jsx("span",{"aria-hidden":"true",className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border ${z===j?"border-primary bg-primary text-primary-foreground":"border-border bg-background"}`,children:z===j&&p.jsx(Os,{size:13,strokeWidth:3})}),p.jsxs("span",{className:"min-w-0",children:[p.jsx("span",{className:"block text-sm font-medium text-foreground",children:G}),p.jsx("span",{className:"mt-0.5 block text-xs leading-relaxed text-muted-foreground",children:me})]})]},j))})]}),z!=="full"&&p.jsxs("fieldset",{children:[p.jsx("legend",{className:"mb-2 text-sm font-medium",children:"可访问的终端"}),p.jsxs("div",{className:"flex gap-2",children:[p.jsx("button",{type:"button","aria-pressed":V==="all",className:`${Ye} flex-1 appearance-none border text-sm ${V==="all"?"border-primary bg-primary/10 text-foreground":"border-border text-muted-foreground"}`,onClick:()=>Y("all"),children:"全部终端"}),p.jsxs("button",{type:"button","aria-pressed":V==="selected",className:`${Ye} inline-flex flex-1 appearance-none items-center justify-center gap-1 border text-sm ${V==="selected"?"border-primary bg-primary/10 text-foreground":"border-border text-muted-foreground"}`,onClick:()=>{ql(Q),ko(!0)},children:[V==="selected"?`已选 ${Q.length} 个`:"选择终端",p.jsx(Sn,{size:14})]})]}),V==="all"&&p.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"包括之后新建的终端。"})]}),z==="write"&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"终端命令可读写该系统用户有权访问的文件。"}),z==="full"&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"拥有此服务的全部当前及未来权限。仅授予你完全信任的设备。"}),l&&p.jsxs("label",{className:"flex items-start gap-3 text-sm",children:[p.jsx("input",{type:"checkbox",className:"mt-0.5 h-4 w-4 accent-primary",checked:$,onChange:j=>H(j.target.checked)}),p.jsxs("span",{children:["让新设备也能使用备用连接",p.jsx("span",{className:"mt-1 block text-xs leading-relaxed text-muted-foreground",children:"需要入口管理员授权;关闭后生成直接连接邀请。"})]})]}),d.length>0&&p.jsxs("details",{className:"rounded-xl border border-border px-3 py-2 text-left",children:[p.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-foreground",children:["接入地址",p.jsx("span",{className:"ml-2 text-xs font-normal text-muted-foreground",children:"默认当前地址,可换用 IP 或域名"})]}),p.jsxs("fieldset",{className:"mt-2 space-y-2",children:[p.jsx("legend",{className:"sr-only",children:"受邀设备打开的地址"}),p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"受邀设备将打开这个地址。当前地址无法访问时,可改用其他可访问的 IP 或域名。"}),p.jsx("div",{className:"space-y-2",children:[["","当前地址",new URL(c||location.origin).host],...d.map(j=>[j.url,j.label,new URL(j.url).host]),["custom","自定义地址",""]].map(([j,G,me])=>p.jsxs("label",{className:`flex cursor-pointer items-center gap-3 rounded-xl border px-3 py-2.5 transition focus-within:ring-2 focus-within:ring-ring ${U===j?"border-primary bg-primary/10":"border-border hover:bg-surface-2"}`,children:[p.jsx("input",{type:"radio",name:"federation-entry-address",value:j,checked:U===j,onChange:()=>q(j),className:"sr-only"}),p.jsx("span",{"aria-hidden":"true",className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border ${U===j?"border-primary bg-primary text-primary-foreground":"border-border bg-background"}`,children:U===j&&p.jsx(Os,{size:13,strokeWidth:3})}),p.jsxs("span",{className:"min-w-0",children:[p.jsx("span",{className:"block text-sm font-medium text-foreground",children:G}),me&&p.jsx("span",{className:"block break-all text-xs leading-relaxed text-muted-foreground",children:me})]})]},j||"current"))}),U==="custom"&&p.jsx("input",{type:"text",className:Or,inputMode:"url",placeholder:"例如:https://192.168.1.23:9834",value:K,onChange:j=>X(j.target.value)})]})]}),p.jsxs("div",{children:[p.jsxs("button",{className:`${Fn} inline-flex w-full items-center justify-center gap-2 text-sm`,type:"submit",disabled:P||R,children:[P&&p.jsx(je,{size:16,className:"animate-spin"}),P?"正在生成…":"生成邀请"]}),p.jsxs("p",{className:"mt-2 text-center text-xs leading-relaxed text-muted-foreground",children:["链接 10 分钟内有效 · 访问权限",Ge?"按设定时间到期":"保留至撤销"]})]})]})}),mt&&p.jsxs("section",{children:[p.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"仅允许访问勾选的终端。"}),p.jsxs("div",{className:"space-y-1",children:[h.map(j=>p.jsxs("label",{className:"flex min-h-12 cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm hover:bg-surface-2",children:[p.jsx("input",{type:"checkbox",className:"h-4 w-4 accent-primary",checked:Pn.includes(j.sessionId),onChange:G=>ql(G.target.checked?[...Pn,j.sessionId]:Pn.filter(me=>me!==j.sessionId))}),p.jsx("span",{className:"min-w-0 break-words",children:j.name})]},j.sessionId)),!h.length&&p.jsx("p",{className:"py-4 text-sm text-muted-foreground",children:"当前没有可共享的终端。"})]})]}),y&&p.jsxs("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:[y,k&&p.jsx("button",{type:"button",className:`${Ye} ml-1 text-sm underline`,onClick:k,children:"重试"})]}),!v.title&&!F&&!Tn&&!Sr&&!mt&&!Oe&&p.jsxs("div",{className:"mt-4 border-t border-border pt-2",children:[p.jsxs("button",{type:"button",className:`${Ye} -ml-3 inline-flex items-center gap-1 bg-transparent text-xs text-muted-foreground`,"aria-expanded":Nn?void 0:ce,onClick:()=>Nn?$l(!0):ie(j=>!j),children:[D?"有效期与备注":F?"手动连接":_t==="devices"?"授权详情":"连接详情",Nn?p.jsx(Sn,{size:14}):p.jsx(Qp,{size:13,className:ce?"rotate-180":""})]}),ce&&p.jsxs("section",{className:"space-y-3 pb-1 pt-2",children:[D&&p.jsxs(p.Fragment,{children:[p.jsxs("label",{className:"block space-y-1 text-sm",children:[p.jsx("span",{children:"设备备注(可选)"}),p.jsx("input",{className:Or,value:$e,onChange:j=>ke(j.target.value),placeholder:"例如:工作电脑"})]}),p.jsxs("label",{className:"block space-y-1 text-sm",children:[p.jsx("span",{children:"授权到期时间"}),p.jsx("input",{type:"datetime-local",className:Or,value:Ge,onChange:j=>en(j.target.value)})]})]}),!D&&s&&p.jsxs("p",{className:"break-all text-xs leading-relaxed text-muted-foreground",children:["本设备身份:",s]})]})]}),_&&p.jsx("p",{role:"alert",className:"mt-3 text-sm text-destructive",children:_}),C&&p.jsx("p",{role:"status",className:"mt-3 text-sm text-muted-foreground",children:C})]}),mt&&p.jsx("footer",{className:"shrink-0 border-t border-border px-5 pt-3 pb-[max(16px,env(safe-area-inset-bottom))]",children:p.jsxs("button",{type:"button",className:`${Fn} w-full text-sm`,disabled:!Pn.length,onClick:()=>{ae(Pn),Y("selected"),ko(!1)},children:["使用所选终端(",Pn.length,")"]})})]})}),document.body)}const sA={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"},iA={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 aA(t){return t==="light"?iA:sA}const cc="termdock:open-services";function pg(){window.dispatchEvent(new Event(cc))}function cA({client:t,initialSessionId:e}){const[n,r]=O.useState([]),[o,s]=O.useState(),i=O.useRef();O.useEffect(()=>{if(!e||i.current===e)return;const f=n.find(h=>h.sessionId===e||h.sourceSessionId===e);f&&(i.current=e,s(f))},[n,e]);const[a,c]=O.useState("正在读取已授权 Session"),[l,d]=O.useState(()=>document.documentElement.dataset.theme==="light"?"light":"dark");O.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=O.useRef(null);return O.useEffect(()=>{let f=!0;const h=async()=>{try{const m=await t.request({type:"session-list"});if(f){const b=m.items;r(b),s(w=>{if(!w)return c(b.length?"选择一个已授权 Session":"暂无已授权的在线 Session"),w;const R=b.find(y=>y.sessionId===w.sessionId);if(!R){c("Session 已移除或授权失效");return}return R.canWrite===w.canWrite&&R.canResize===w.canResize?w:R})}}catch{f&&c("目标不可达或授权已失效")}};h();const g=setInterval(()=>{h()},15e3);return()=>{f=!1,clearInterval(g)}},[t]),O.useEffect(()=>{if(!o||!u.current)return;let f=!1,h=0,g;const m=new Tm({theme:aA(l),cursorBlink:o.canWrite,disableStdin:!o.canWrite,convertEol:!1}),b=new Pm;m.loadAddon(b),m.open(u.current),o.canResize&&b.fit(),c("正在建立加密终端连接");const w=t.openSocket(`/api/terminal/${encodeURIComponent(o.sessionId)}/ws?flow=2`),R=()=>{f||!o.canResize||(b.fit(),w.readyState===1&&w.send(JSON.stringify({type:"resize",cols:m.cols,rows:m.rows})))};w.onopen=()=>c(o.canWrite?"读写":"只读"),w.onmessage=x=>{try{const T=JSON.parse(x.data);if(f)return;if(T.type==="connected"){g=typeof T.streamEpoch=="string"?T.streamEpoch:void 0,h=Number.isSafeInteger(T.replayLastSeq)?T.replayLastSeq:0,!o.canResize&&Number.isSafeInteger(T.cols)&&Number.isSafeInteger(T.rows)&&T.cols>0&&T.rows>0&&m.resize(T.cols,T.rows);const S=Array.isArray(T.replayChunks)?T.replayChunks.filter(v=>typeof v=="string").join(""):"";m.write((T.replayOutOfWindow?"\x1Bc":"")+S,R)}else T.type==="data"&&typeof T.data=="string"?m.write(T.data,()=>{f||(Number.isSafeInteger(T.seq)&&(h=Math.max(h,T.seq)),w.readyState===1&&Number.isSafeInteger(T.flowSeq)&&w.send(JSON.stringify({type:"output-ack",flowSeq:T.flowSeq,since:h,epoch:g})))}):T.type==="pty-size"&&!o.canResize&&Number.isSafeInteger(T.cols)&&Number.isSafeInteger(T.rows)&&T.cols>0&&T.rows>0?m.resize(T.cols,T.rows):T.type==="error"&&c("目标拒绝终端操作,请检查有效授权")}catch{c("终端数据无效"),w.close()}},w.onclose=()=>c("连接已断开;画面已过期,重新选择 Session 可重连"),w.onerror=()=>c("目标不可达或授权不足");const y=m.onData(x=>{o.canWrite&&w.readyState===1&&w.send(JSON.stringify({type:"input",data:x}))}),k=setInterval(()=>{w.readyState===1&&w.send(JSON.stringify({type:"ping"}))},2e4),N=new ResizeObserver(R);return N.observe(u.current),()=>{f=!0,clearInterval(k),N.disconnect(),y.dispose(),w.onclose=null,w.onerror=null,w.close(),m.dispose()}},[t,o,l]),p.jsxs("div",{className:"flex h-dvh flex-col bg-background text-foreground",children:[p.jsxs("div",{className:"flex items-center gap-3 border-b border-border p-3 text-sm",children:[p.jsxs("span",{className:"min-w-0 flex-1",children:["已授权 Session · ",a]}),p.jsx("button",{type:"button",onClick:pg,className:"min-h-11 shrink-0 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2",children:"服务与设备"})]}),p.jsx("div",{className:"flex flex-wrap gap-2 p-2",children:n.map(f=>p.jsxs("button",{className:"rounded border border-border px-3 py-2 text-sm hover:bg-surface-2",onClick:()=>s({...f}),children:[f.name," · ",f.canWrite?"读写":"只读"]},`${t.targetPeerId}:${f.sessionId}`))}),p.jsx("div",{ref:u,className:"min-h-0 flex-1 overflow-auto p-2"})]})}function lA(t){const e=t.serviceLabel?.trim();if(!e||/^https?:\/\//i.test(e)||e===t.serviceOrigin)return"远端服务";try{const n=new URL(t.serviceOrigin??"");if(e===n.host||e===n.hostname)return"远端服务"}catch{}return e}function lc(t){if(!t.startsWith("remote:"))return null;const e=t.slice(7).split(":");if(e.length!==2)return null;try{const n=decodeURIComponent(e[0]),r=decodeURIComponent(e[1]);return!r||new URL(n).origin!==n||!/^https?:/.test(n)?null:{origin:n,id:r}}catch{return null}}class dA{constructor(e){this.source=e,this.peers={state:e.peerProtocol==="unsupported"?"unsupported":e.readPeers?"loading":"unavailable",checkedAt:null}}source;local=null;remote=[];peers;localInFlight=null;peerInFlight=null;listeners=new Set;disposed=!1;peerTimer;lastPeerAttempt=-1/0;generation=0;localHealthy=!1;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}snapshot(){if(!this.local)return null;const e=new Map;for(const n of this.local.groups)for(const r of n.remoteSessions??[]){const o=lc(r.sessionId);o&&o.origin!==this.source.origin&&o.origin!==this.source.peerOrigin&&e.set(r.sessionId,{...r,status:"offline",serviceConnected:!1})}for(const n of this.remote)e.set(n.sessionId,n);for(const n of this.local.sessions)e.set(n.sessionId,n);return{groups:this.local.groups.map(n=>({...n,remoteSessions:n.remoteSessions?.map(r=>e.get(r.sessionId)??r)})),sessions:[...e.values()],peers:this.peers,capabilities:this.local.capabilities}}emit(){if(this.disposed||!this.localHealthy)return;const e=this.snapshot();if(e)for(const n of this.listeners)n(e)}load(){if(this.disposed)return Promise.reject(new Error("协作连接已切换,请重新加载"));if(this.localInFlight)return this.localInFlight;this.refreshPeers();const e=this.generation,n=Promise.resolve().then(()=>this.source.readLocal()).then(r=>{if(this.disposed)throw new Error("协作连接已切换,请重新加载");if(e!==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 e===this.generation&&(this.localHealthy=!1),r}).finally(()=>{this.localInFlight===n&&(this.localInFlight=null)});return this.localInFlight=n,n}invalidate(){this.generation++,this.localInFlight=null,this.localHealthy=!1}refreshPeers(e=!1){if(this.disposed||!this.source.readPeers||this.peerInFlight||!e&&Date.now()-this.lastPeerAttempt<2e3)return;this.lastPeerAttempt=Date.now(),this.peers.checkedAt||(this.peers={state:"loading",checkedAt:null}),this.emit();const 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=lc(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}}).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 uA(t,e){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:t,filename:e},[r.port2])}catch{s(null)}})}const fA=4*1024*1024,hA=256*1024,pA=1440*6e4;let rr=0,Qu;function yl(){return typeof indexedDB>"u"?Promise.resolve(null):Qu??=new Promise(t=>{const e=indexedDB.open(`termdock-terminal-snapshots:${Wn}`,1);e.onupgradeneeded=()=>e.result.createObjectStore("snapshots",{keyPath:"id"}),e.onerror=()=>t(null),e.onblocked=()=>t(null),e.onsuccess=()=>{e.result.onversionchange=()=>{e.result.close(),Qu=void 0},t(e.result)}})}function dc(t){return!!t&&t.version===1&&typeof t.epoch=="string"&&t.epoch.length>0&&Number.isSafeInteger(t.cols)&&t.cols>0&&Number.isSafeInteger(t.rows)&&t.rows>0&&Number.isSafeInteger(t.seq)&&t.seq>0&&typeof t.data=="string"&&t.data.length*2<=hA&&t.savedAt<=Date.now()&&Date.now()-t.savedAt<pA}async function uR(t){const e=rr;try{const n=await yl();return!n||e!==rr?null:await new Promise(r=>{const o=n.transaction("snapshots").objectStore("snapshots").get(t);o.onerror=()=>r(null),o.onsuccess=()=>r(e===rr&&dc(o.result)?o.result:null)})}catch{return null}}async function fR(t){const e=rr;if(dc(t))try{const n=await yl();if(!n||e!==rr)return;await new Promise(r=>{const o=n.transaction("snapshots","readwrite"),s=o.objectStore("snapshots");s.put(t);const i=s.getAll();i.onsuccess=()=>{let a=0,c=0;for(const l of i.result.sort((d,u)=>u.savedAt-d.savedAt))a+=l.data.length*2,(++c>32||a>fA||!dc(l))&&s.delete(l.id)},o.oncomplete=()=>r(),o.onerror=o.onabort=()=>r()})}catch{}}async function gg(){rr+=1;try{(await yl())?.transaction("snapshots","readwrite").objectStore("snapshots").clear()}catch{}}typeof window<"u"&&window.addEventListener("auth:unauthorized",()=>{gg()});const vt=new Map,Wt=new Map,gA=32*1024*1024,mA=8*1024*1024,wA=48;let zr=0,uc=0;function bl(){uc+=1,vt.clear(),zr=0;for(const t of Wt.values())t.controller.abort();Wt.clear()}typeof window<"u"&&window.addEventListener("auth:unauthorized",bl);function yA(t,e){const n=vt.get(t);if(n&&(zr-=n.blob.size,vt.delete(t)),!(e.blob.size>mA))for(vt.set(t,e),zr+=e.blob.size;vt.size>wA||zr>gA;){const r=vt.keys().next().value;zr-=vt.get(r).blob.size,vt.delete(r)}}async function mg(t,e={}){const n=new URL(t,typeof location<"u"?location.origin:"http://localhost");if(!/^\/api\/terminal\/fs\/(read|blob)$/.test(n.pathname))return fetch(t,{signal:e.signal});if(e.signal?.aborted)throw e.signal.reason??new DOMException("Aborted","AbortError");n.searchParams.delete("requestSlotId"),n.searchParams.delete("action"),n.searchParams.sort();const r=n.href;let o=Wt.get(r);if(!o){const i=new AbortController,a=uc,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")),e.timeoutMs??15e3),f={controller:i,readers:0,promise:Promise.resolve(null)};f.promise=(async()=>{const h=await fetch(r,{headers:l,signal:i.signal,cache:"no-cache"});let g;return h.status===304&&c?g=c:g={blob:await h.blob(),headers:new Headers(h.headers),status:h.status},uc===a&&!i.signal.aborted&&g.status===200&&g.headers.has("ETag")&&yA(r,g),h.status===401&&bl(),g})().finally(()=>{clearTimeout(u),Wt.get(r)===f&&Wt.delete(r)}),o=f,Wt.set(r,o)}const s=o;return s.readers+=1,new Promise((i,a)=>{let c=!1;const l=()=>c?!1:(c=!0,e.signal?.removeEventListener("abort",d),s.readers-=1,s.readers===0&&Wt.get(r)===s&&(Wt.delete(r),s.controller.abort()),!0),d=()=>{l()&&a(e.signal?.reason??new DOMException("Aborted","AbortError"))};if(e.signal?.addEventListener("abort",d,{once:!0}),e.signal?.aborted){d();return}s.promise.then(u=>{l()&&i(new Response(u.blob,{status:u.status,headers:u.headers}))},u=>{l()&&a(u)})})}const vl="auth:unauthorized";let Kn=null;class Ie extends Error{constructor(e,n,r){super(e),this.status=n,this.code=r,this.name="TerminalApiError"}status;code}async function bA(){const t=await fetch("/api/terminal/update");if(!t.ok)throw new Ie("Failed to load update state",t.status);return t.json()}async function vA(){const t=await Z(),e=await fetch("/api/terminal/update/check",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Ie("Failed to check for updates",e.status);return e.json()}async function SA(){const t=await Z(),e=await fetch("/api/terminal/update/restart",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to restart Termdock"}));throw new Ie(n.error||"Failed to restart Termdock",e.status)}return e.json()}async function xA(){const t=await fetch("/api/terminal/quota");if(!t.ok)throw new Ie("Failed to fetch quota",t.status);return t.json()}async function EA(){const t=await Z(),e=await fetch("/api/terminal/quota/refresh",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Ie("Failed to refresh quota",e.status);return e.json()}const In=8e3,wg=6e4,AA=32e3,yg=125e3,pt=1e4,or=45e3,bg=8e3,vg=8e3,Sg=15e3,kA=1e4,pr=5e3;let CA=0;const rs=[];let ba=!1;function Ht(t,e={}){if(typeof window>"u")return;const n=JSON.stringify({level:t==="error"||t==="timeout_or_abort"||t==="response_body_timeout"||t==="response_body_parse_error"?"warn":"info",message:`DIFF_API ${t}`,data:{seq:++CA,ts:Date.now(),...e}});rs.push(n),IA()}async function IA(){if(!ba){ba=!0;try{for(;rs.length>0;){const t=rs[0];try{await fetch("/api/client-log",{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:!0}),rs.shift()}catch{break}}}finally{ba=!1}}}function Sl(t,e,n){const r=new AbortController;let o=setTimeout(()=>{r.abort(new DOMException(n,"TimeoutError"))},e);const s=()=>r.abort(t?.reason);return t&&(t.aborted?s():t.addEventListener("abort",s,{once:!0})),{signal:r.signal,cleanup:()=>{o&&(clearTimeout(o),o=null),t?.removeEventListener("abort",s)}}}async function ge(t,e,n,r){const{signal:o,cleanup:s}=Sl(e?.signal??void 0,n,r);try{return await fetch(t,{...e,signal:o})}catch(i){throw i instanceof DOMException&&i.name==="TimeoutError"?new Error(r):i}finally{s()}}async function xg(t,e,n){let r=null;const o=new Promise((s,i)=>{r=setTimeout(()=>i(new Error(n)),e)});try{return await Promise.race([t.text(),o])}finally{r&&clearTimeout(r)}}async function gr(t,e,n){const r=await xg(t,e,n);return JSON.parse(r)}if(typeof window<"u"&&!window.__termdockFetchPatched){window.__termdockFetchPatched=!0;const t=window.fetch.bind(window);window.fetch=async(...e)=>{const n=await t(...e);if(n.status===401){Kn=null,Tl();try{window.dispatchEvent(new CustomEvent(vl))}catch{}}return n}}async function Z(){if(Kn)return Kn;const t=await ge("/api/csrf-token",void 0,bg,"CSRF token request timed out");if(!t.ok)throw new Error("Failed to get CSRF token");const e=await gr(t,pr,"CSRF token response timed out");if(!e.csrfToken)throw new Error("Invalid CSRF token response");return Kn=e.csrfToken,Kn}function xl(){Tl(),Kn=null}const RA=2e4,ef=8e3,TA=1500,Eg=250,ye=new Map,El=new Map,PA=24,NA=40,LA=40;function BA(t){return t.retryState.retryCount>=2||t.pendingInputs.length>=LA?"congested":t.retryState.retryCount>=1||t.pendingInputs.length>=8?"degraded":"good"}function tf(t){if(t.pendingInputs.length===0||t.ws.readyState!==WebSocket.OPEN)return;const e=t.pendingInputs.splice(0);for(const n of e)try{t.ws.send(JSON.stringify({type:"input",data:n}))}catch{}}function Ag(t){if(t.ws.readyState!==WebSocket.OPEN)return;const e=BA(t);if(e==="good"){tf(t);return}if(t.inputFlushTimer)return;const n=e==="congested"?NA:PA;t.inputFlushTimer=setTimeout(()=>{t.inputFlushTimer=null,tf(t)},n)}const to=new Map;function _A(t,e,n,r){const o=to.get(t);o&&(to.delete(t),e?o.resolve({success:!0,layout:n}):o.reject(new Error(r||"Tmux action failed")))}const Hn=new Map;function OA(t,e,n,r){const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/terminal/${t}/ws`,i=new URLSearchParams({flow:"2",transport:"tmux-client",active:El.get(t)===!1?"0":"1"});e>0&&i.set("since",String(e)),n&&i.set("epoch",n);const a=r??Hn.get(t);return a&&(i.set("cols",String(a.cols)),i.set("rows",String(a.rows))),`${s}?${i}`}const fc=new Map,hc=new Map;function DA(t,e,n){fc.set(t,e),hc.set(t,n)}function FA(t){const e=ye.get(t);return e?.streamEpoch&&e.appliedSeq===e.lastSeq&&e.lastSeq>0?{seq:e.lastSeq,epoch:e.streamEpoch}:null}async function MA(t){const e=await Z(),n=await fetch("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({cols:t.cols||80,rows:t.rows||24,mode:t.mode||"shell",tmuxSessionName:t.tmuxSessionName,cwd:t.cwd,termType:t.termType})});if(!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 jA(t,e,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=fc.get(t)??0,u=hc.get(t);hc.delete(t),fc.delete(t);const f=[];let h=!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)},w=x=>{x.wakeProbe&&(clearTimeout(x.wakeProbe.timer),x.wakeProbe=void 0),x.heartbeatTimer&&(clearInterval(x.heartbeatTimer),x.heartbeatTimer=null),x.pongTimer&&(clearTimeout(x.pongTimer),x.pongTimer=null),x.inputFlushTimer&&(clearTimeout(x.inputFlushTimer),x.inputFlushTimer=null)},R=x=>{w(x),x.heartbeatTimer=setInterval(()=>{if(x.ws.readyState===WebSocket.OPEN){try{x.ws.send(JSON.stringify({type:"ping"}))}catch{}x.pongTimer&&clearTimeout(x.pongTimer),x.pongTimer=setTimeout(()=>{if(Date.now()-x.lastInboundAt>=ef){h=!0,w(x);try{x.ws.close()}catch{}N(new Error("WebSocket heartbeat timeout"),!1)}},ef)}},RA)},y=()=>{if(c.isClosed=!0,b(),l){w(l),ye.delete(t);try{l.ws.close()}catch{}l=null}},k=()=>{if(c.isClosed)return;if(l){m.add(l.ws),w(l);try{l.ws.close()}catch{}}const x=OA(t,d,u,r.getDimensions?.()),T=Gp(x);h=!1,c.connectionTimeoutId=setTimeout(()=>{T.readyState!==WebSocket.OPEN&&(h=!0,T.close(),N(new Error("WebSocket connection timeout"),!1))},a);const S={ws:T,onEvent:e,onError:n,reconnectNow:v=>{if(!c.isClosed&&(c.isSuspended=!1,!g)){if(b(),l){m.add(l.ws),w(l);try{l.ws.close()}catch{}}v?.silent||e({type:"reconnecting",attempt:Math.min(c.retryCount+1,o),maxAttempts:o}),c.retryCount=Math.min(c.retryCount+1,o),h=!0,g=setTimeout(()=>{g=null,h=!1,k()},0)}},suspendReconnect:()=>{c.isClosed||(c.isSuspended=!0,c.retryTimeout&&(clearTimeout(c.retryTimeout),c.retryTimeout=null))},retryState:c,lastSeq:d,pendingInputs:f,inputFlushTimer:null,heartbeatTimer:null,pongTimer:null,lastInboundAt:Date.now(),inboundSequence:0};T.onopen=()=>{c.isClosed||m.has(T)||h||(b(),c.retryCount=0,S.lastInboundAt=Date.now(),S.inboundSequence+=1,R(S),Ag(S))},T.onmessage=v=>{if(!(c.isClosed||m.has(T)||h)){S.lastInboundAt=Date.now(),S.inboundSequence+=1;try{const A=JSON.parse(v.data);if(S.wakeProbe&&ye.get(t)===S){const B=S.wakeProbe;S.wakeProbe=void 0,clearTimeout(B.timer);for(const C of B.listeners)C()}if(A.type==="pong"){S.pongTimer&&(clearTimeout(S.pongTimer),S.pongTimer=null);return}if(A.type==="tmux-result"&&A.reqId){_A(A.reqId,A.success!==!1,A.layout,A.error);return}if(A.type==="tmux-layout"&&A.layout){e({type:"tmux-layout",layout:A.layout});return}if(A.type==="tmux-screen-sync"&&Array.isArray(A.chunks)){e({type:"tmux-screen-sync",chunks:A.chunks.filter(B=>typeof B=="string"),cols:typeof A.cols=="number"?A.cols:void 0,rows:typeof A.rows=="number"?A.rows:void 0,generation:typeof A.generation=="number"?A.generation:void 0});return}if(A.type==="active-program"){e({type:"active-program",activeProgram:A.activeProgram,activeProgramRaw:A.activeProgramRaw,activeProgramSource:A.activeProgramSource});return}if(A.type==="cwd"){e({type:"cwd",cwd:A.cwd});return}if(A.type==="agent-status"){e({type:"agent-status",agentStatus:A.agentStatus??null,agentIndicator:A.agentIndicator??null,agentStatusDetail:A.agentStatusDetail??null,agent:A.agent??null,agentMessage:A.agentMessage??null,agentNativeSessionId:A.agentNativeSessionId??null,agentResumeRecovered:A.agentResumeRecovered===!0,agentRich:A.agentRich===!0,agentActivity:typeof A.agentActivity=="number"?A.agentActivity:0,agentCwd:A.agentCwd??null,reviewed:typeof A.reviewed=="boolean"?A.reviewed:null});return}if(A.type==="git-status"){e({type:"git-status",gitStatus:A.gitStatus??null});return}if(A.type==="quota-status"&&Array.isArray(A.providers)){window.dispatchEvent(new CustomEvent("termdock:quota-update",{detail:A.providers}));return}if(A.type==="focus-mode"){e({type:"focus-mode",focusTrackingRequested:A.focusTrackingRequested===!0});return}if(A.type==="resize-ack"){e({type:"resize-ack",seq:typeof A.seq=="number"?A.seq:void 0,cols:typeof A.cols=="number"?A.cols:void 0,rows:typeof A.rows=="number"?A.rows:void 0,ok:A.ok!==!1,error:typeof A.error=="string"?A.error:void 0,screenSyncPending:A.screenSyncPending===!0,screenSyncGeneration:typeof A.screenSyncGeneration=="number"?A.screenSyncGeneration:void 0});return}if(A.type==="pty-size"){e({type:"pty-size",cols:typeof A.cols=="number"?A.cols:void 0,rows:typeof A.rows=="number"?A.rows:void 0,source:typeof A.source=="string"?A.source:void 0});return}if(A.type==="shell-title"){e({type:"shell-title",title:typeof A.title=="string"?A.title:""});return}if(A.type==="prompt-state"){e({type:"prompt-state",state:A.state==="running"?"running":"idle",exitCode:typeof A.exitCode=="number"?A.exitCode:void 0});return}const _=A;if(_.type==="connected"){S.appliedSeq=void 0,u=_.streamEpoch,S.streamEpoch=u,S.outputProtocol=_.outputProtocol,typeof _.replayLastSeq=="number"&&_.replayLastSeq>=0&&(d=_.replayLastSeq,S.lastSeq=d),e(_),kg(t,El.get(t)??!0);return}if(_.type==="exit"){y(),e(_);return}if(_.type==="data"){if(S.appliedSeq=void 0,typeof _.seq=="number"&&_.seq<=d)return;typeof _.flowSeq=="number"&&(S.flowSeq=_.flowSeq)}e(_),_.type==="data"&&typeof _.seq=="number"&&Number.isFinite(_.seq)&&_.seq>d&&(d=_.seq,S.lastSeq=d)}catch(A){n?.(A,!1)}}},T.onerror=()=>{c.isClosed||m.has(T)||h||(b(),w(S),h||(h=!0,N(new Error("WebSocket connection error"),!1)))},T.onclose=v=>{if(!(c.isClosed||m.has(T)||h)){if(v.code===Np&&v.reason===Lp){S.reconnectNow({silent:!0});return}if(b(),w(S),h=!0,v.code===4001){console.warn("[Terminal] WS 4001: Session not found on server",{code:v.code,reason:v.reason,stack:new Error().stack}),N(new Error("Session not found on server"),!0);return}if(v.code===4003||v.code===4401){try{window.dispatchEvent(new CustomEvent(vl))}catch{}N(new Error("Authentication required"),!0);return}N(new Error("WebSocket connection closed"),!1)}},l=S,ye.set(t,l)},N=(x,T)=>{if(!c.isClosed)if(T)n?.(x,!0),y();else{c.retryCount=Math.min(c.retryCount+1,Math.max(1,o));const S=Math.min(s*Math.pow(2,c.retryCount-1),i);if(e({type:"reconnecting",attempt:c.retryCount,maxAttempts:o}),c.isSuspended)return;c.retryTimeout=setTimeout(()=>{c.isClosed||k()},S)}};return k(),y}async function UA(t,e){const n=ye.get(t);if(n){if(n.ws.readyState===WebSocket.OPEN){n.pendingInputs.push(e),Ag(n);return}if(n.ws.readyState===WebSocket.CONNECTING){n.pendingInputs.push(e);return}}const r=await Z(),o=await fetch(`/api/terminal/${t}/input`,{method:"POST",headers:{"Content-Type":"text/plain","X-XSRF-TOKEN":r},body:e});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to send input"}));throw new Error(s.error||"Failed to send terminal input")}}function $A(t,e,n={}){const r=ye.get(t);if(!r)return!1;if(r.retryState.isSuspended=!1,r.ws.readyState!==WebSocket.OPEN)return r.reconnectNow(),!0;const o=n.visible?Eg:TA,s=Date.now()+o,i=r.wakeProbe,a=i?.listeners??new Set;if(e&&a.add(e),i&&i.deadline<=s)return!0;i&&clearTimeout(i.timer);const c=setTimeout(()=>{ye.get(t)!==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 HA(t){const e=ye.get(t);return e?(e.reconnectNow(),!0):!1}function qA(){for(const t of ye.values())t.suspendReconnect()}function KA(t,e,n){const r=ye.get(t);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"focus",focused:e,reason:n}))}catch{}}function kg(t,e){El.set(t,e);const n=ye.get(t);!n||n.ws.readyState!==WebSocket.OPEN||n.outputProtocol!==2||n.ws.send(JSON.stringify({type:"output-subscription",active:e,since:n.lastSeq,epoch:n.streamEpoch}))}function zA(t){const e=ye.get(t);!e||e.ws.readyState!==WebSocket.OPEN||e.outputProtocol!==2||(e.appliedSeq=e.lastSeq,!(!e.flowSeq||e.flowSeq===e.acknowledgedFlowSeq)&&(e.acknowledgedFlowSeq=e.flowSeq,e.ws.send(JSON.stringify({type:"output-ack",flowSeq:e.flowSeq,since:e.appliedSeq,epoch:e.streamEpoch}))))}function WA(t,e,n){const r=ye.get(t);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"viewing",viewing:e,reason:n}))}catch{}}function pc(t){const e=ye.get(t);if(!(!e||e.ws.readyState!==WebSocket.OPEN))try{e.ws.send(JSON.stringify({type:"agent-review-ack"}))}catch{}}function VA(t,e,n){const r=ye.get(t);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"flow-control",paused:e,reason:n}))}catch{}}async function GA(t,e,n,r){Number.isFinite(e)&&Number.isFinite(n)&&e>=1&&n>=1&&(Hn.delete(t),Hn.set(t,{cols:Math.floor(e),rows:Math.floor(n)}),Hn.size>256&&Hn.delete(Hn.keys().next().value));const o=ye.get(t);if(o&&o.ws.readyState===WebSocket.OPEN)try{o.ws.send(JSON.stringify({type:"resize",cols:e,rows:n,seq:r}));return}catch{}const s=await Z(),i=await fetch(`/api/terminal/${t}/resize`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":s},body:JSON.stringify({cols:e,rows: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 XA(t,e){const n=ye.get(t);if(n&&n.ws.readyState===WebSocket.OPEN)return e.action==="scroll"?(n.ws.send(JSON.stringify({type:"tmux",...e})),{success:!0}):new Promise((s,i)=>{const a=Math.random().toString(36).substring(7);to.set(a,{resolve:s,reject:i}),n.ws.send(JSON.stringify({type:"tmux",reqId:a,...e})),setTimeout(()=>{to.has(a)&&(to.delete(a),i(new Error("Tmux action timed out")))},3e4)});const r=await Z(),o=await fetch(`/api/terminal/${t}/tmux`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(e)});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to execute tmux action"}));throw new Error(s.error||"Failed to execute tmux action")}return o.json()}async function YA(t){const e=ye.get(t);if(e){e.retryState.isClosed=!0;try{e.ws.close()}catch{}ye.delete(t)}const n=await Z(),r=await fetch(`/api/terminal/${t}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":n}});if(r.status!==404&&!r.ok){const o=await r.json().catch(()=>({error:"Failed to close terminal"}));throw new Error(o.error||"Failed to close terminal")}}async function ZA(t,e){const n=ye.get(t);if(n){n.retryState.isClosed=!0;try{n.ws.close()}catch{}ye.delete(t)}const r=await Z(),o=await fetch(`/api/terminal/${t}/restart`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify({...e.cwd?{cwd:e.cwd}:{},cols:e.cols??80,rows:e.rows??24,mode:e.mode,tmuxSessionName:e.tmuxSessionName})});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to restart terminal"}));throw new Error(s.error||"Failed to restart terminal session")}return o.json()}async function JA(t){const e=await ge(`/api/terminal/${t}/health`,{method:"GET"},vg,"Terminal health check timed out");if(!e.ok){if(e.status===404)return{healthy:!1,sessionId:t};const n=await gr(e,pr,"Terminal health error response timed out").catch(()=>({error:"Failed to check terminal health"}));throw new Error(n.error||"Failed to check terminal health")}return gr(e,pr,"Terminal health response timed out")}async function QA(t){const e=await Z(),n=await ge("/api/terminal/force-kill",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)},kA,"Terminal force-kill request timed out");if(!n.ok){const r=await gr(n,pr,"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 ek(){const t=await fetch("/api/terminal/tmux/sessions",{method:"GET"});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to list tmux sessions"}));throw new Error(n.error||"Failed to list tmux sessions")}const e=await t.json();return Array.isArray(e.sessions)?e.sessions:[]}async function tk(){const t=await fetch("/api/terminal/tmux/status",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to get tmux status"}));throw new Error(e.error||"Failed to get tmux status")}return t.json()}async function nk(t){const e=t.trim();if(!e)throw new Error("tmux session name is required");const n=await Z(),r=await fetch(`/api/terminal/tmux/sessions/${encodeURIComponent(e)}`,{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 rk(){const t=await Z(),e=await fetch("/api/terminal/tmux/recovery/restore-all",{method:"POST",headers:{"X-XSRF-TOKEN":t}}),n=await e.json().catch(()=>({}));if(!e.ok)throw new Ie(n.error||"Failed to restore tmux Agent sessions",e.status);return n}async function ok(){const t=await Z(),e=await fetch("/api/terminal/tmux/recovery",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Ie("Failed to dismiss tmux recovery",e.status)}const zo=new Map;function sk(t){return JSON.stringify({preferredFrontendSessionId:t.preferredFrontendSessionId??null,mode:t.mode??null,tmuxSessionName:t.tmuxSessionName??null,cwd:t.cwd??null,termType:t.termType??null,createIfEmpty:t.createIfEmpty===!0,requireExisting:t.requireExisting===!0})}async function Cg(){const t=await fetch("/api/terminal/session-inventory",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to load session inventory"}));throw new Error(e.error||"Failed to load session inventory")}return t.json()}async function Ig(t){const e=sk(t),n=zo.get(e);if(n)return n;const r=await Z(),o=ge("/api/terminal/session-inventory/open",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(t)},Sg,"Terminal session open request timed out").then(async s=>{if(!s.ok){const i=await gr(s,pr,"Terminal session open error response timed out").catch(()=>({error:"Failed to open session"}));throw new Ie(i.error||"Failed to open session",s.status,typeof i.code=="string"?i.code:void 0)}return gr(s,pr,"Terminal session open response timed out")}).finally(()=>{zo.get(e)===o&&zo.delete(e)});return zo.set(e,o),o}async function os(t,e){const n=await Z(),r=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify(e)});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 Rg(t){const e=await Z(),n=await fetch("/api/terminal/session-inventory/reorder",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({sessionIds:t})});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 Tg(t){const e=await Z(),n=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});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 Pg(){const t=await Z(),e=await fetch("/api/terminal/session-inventory/sessions",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to clear sessions"}));throw new Error(n.error||"Failed to clear sessions")}}async function ik(){const t=await fetch("/api/terminal/toolbar-presets",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to load toolbar presets"}));throw new Error(e.error||"Failed to load toolbar presets")}return t.json()}async function ak(t){const e=await Z(),n=await fetch("/api/terminal/toolbar-presets",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});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 Dr=null,Wr=null;const Ng=1500;function sr(){return Wr&&Date.now()-Wr.readAt<Ng?Promise.resolve(Wr.value):Dr||(Dr=(async()=>{const t=await fetch("/api/terminal/settings",{method:"GET"});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to load settings"}));throw new Error(n.error||"Failed to load settings")}const e=await t.json();return Wr={value:e,readAt:Date.now()},e})().finally(()=>{Dr=null}),Dr)}async function Et(t){const e=await Z(),n=await fetch("/api/terminal/settings",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});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 Wr={value:r,readAt:Date.now()},r}async function ck(t=!1){const e=await fetch(`/api/terminal/auto-title/catalog${t?"?refresh=1":""}`);if(!e.ok)throw new Error("Failed to discover title models");const n=await e.json();return Array.isArray(n?.namers)?n.namers:[]}let Fr=null,Vr=null;function lk(){return Vr&&Date.now()-Vr.readAt<Ng?Promise.resolve(Vr.value):Fr||(Fr=(async()=>{const t=await fetch("/api/terminal/context-draft",{method:"GET"});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to load context draft"}));throw new Error(n.error||"Failed to load context draft")}const e=await t.json();return Vr={value:e,readAt:Date.now()},e})().finally(()=>{Fr=null}),Fr)}async function dk(t,e){const n=await Z(),r=await fetch("/api/terminal/context-draft",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify({text:t,origin:e})});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 Vr={value:o,readAt:Date.now()},o}async function Lg(t){const e=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:t})});if(e.ok)return xl(),{ok:!0};const n=await e.json().catch(()=>null);return e.status===429?{ok:!1,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,error:n?.error||"Login failed"}}async function uk(){bl(),gg();const t=await Z();await fetch("/api/auth/logout",{method:"POST",headers:{"X-XSRF-TOKEN":t}}),xl()}async function fk(){const t=await fetch("/api/terminal/agent-launchers");if(!t.ok)throw new Error("Failed to detect agent launchers");const e=await t.json();return Array.isArray(e?.agents)?e.agents:[]}async function hk(){const t=await fetch("/api/terminal/agent-hooks");if(!t.ok)throw new Error("Failed to get agent hooks");const e=await t.json();return Array.isArray(e?.agents)?e.agents:[]}async function pk(t){const e=await Z(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(t)}/install`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),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 gk(t){const e=await Z(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(t)}/uninstall`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to uninstall agent hooks");return r.summary??"Removed"}class Al extends Error{constructor(e,n,r){super(e),this.code=n,this.migration=r,this.name="AgentPluginManifestError"}code;migration}async function mk(){const t=await fetch("/api/terminal/agent-plugins");if(!t.ok)throw new Error("Failed to get agent plugins");return await t.json()}async function wk(t){const e=await Z(),n=await fetch("/api/terminal/agent-plugins",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Al(r.error||"Failed to create agent plugin",r.code,r.migration);return r}async function yk(t){const e=await Z(),n=await fetch("/api/terminal/agent-plugins/install",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({source:t})}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Al(r.error||"Failed to install agent plugin",r.code,r.migration);return r}async function bk(t){const e=await Z(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/check-update`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to check plugin updates");return r}async function vk(t){const e=await Z(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/update`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to update plugin");return r}async function Sk(t){const e=await Z(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/doctor`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to diagnose plugin");return r}async function xk(t){const e=await Z(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||"Failed to delete agent plugin")}}async function Ek(t){const e=await Z(),n=await fetch(`/api/terminal/${encodeURIComponent(t)}/agent-resume`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Ie(r.error||"Failed to resume agent session",n.status,typeof r.code=="string"?r.code:void 0);return{command:r.command??""}}async function Ak(){const t=await fetch("/api/terminal/agent-resume-history",{method:"GET"});if(!t.ok)throw new Error("Failed to load Agent resume history");const e=await t.json().catch(()=>({entries:[]}));return Array.isArray(e.entries)?e.entries:[]}async function kk(t){const e=await Z(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(t)}/prepare`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Ie(r.error||"Failed to prepare Agent session resume",n.status,typeof r.code=="string"?r.code:void 0);return r}async function Ck(t){const e=await Z(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!n.ok&&n.status!==404)throw new Error("Failed to remove Agent resume history")}async function Ik(t){const e=await Z(),n=await fetch("/api/terminal/program-rules",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});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 Rk(){const t=await Z(),e=await fetch("/api/terminal/program-rules",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Error("Failed to reset program rules");return e.json()}async function Tk(){const t=await fetch("/api/terminal/program-detection");if(!t.ok)throw new Error("Failed to get program detection config");return t.json()}async function Pk(t){const e=await Z(),n=await fetch("/api/terminal/program-detection",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!n.ok)throw new Error("Failed to save program detection config");return n.json()}async function Nk(){const t=await Z(),e=await fetch("/api/terminal/program-detection",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Error("Failed to reset program detection config");return e.json()}const Lk={".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 li(t){const e=t.lastIndexOf(".");return e<0?null:Lk[t.slice(e).toLowerCase()]??null}function Bk(t){return li(t)!==null}function Bg(t){const e=li(t);return e==="image/heic"||e==="image/heif"}const _k={".mp4":"video/mp4",".m4v":"video/x-m4v",".webm":"video/webm",".mov":"video/quicktime",".ogv":"video/ogg",".mpeg":"video/mpeg",".mpg":"video/mpeg"};function _g(t){const e=t.lastIndexOf(".");return e<0?null:_k[t.slice(e).toLowerCase()]??null}function Ok(t){return _g(t)!==null}function Dk(t){return`/api/terminal/fs/video?path=${encodeURIComponent(t)}&action=view_file`}const Og=[".stl",".glb",".gltf"];function kl(t){const e=t.lastIndexOf(".");if(e<0)return null;const n=t.slice(e).toLowerCase();return Og.includes(n)?n:null}function Fk(t){return kl(t)!==null}function Cl(t){const e=t.toLowerCase();return e.endsWith(".kicad_sch")?".kicad_sch":e.endsWith(".kicad_pcb")?".kicad_pcb":null}function Mk(t){return Cl(t)!==null}function jk(t){return Cl(t)===".kicad_pcb"?"pcb-front":"schematic"}const Dg=[".html",".htm"];function Uk(t){const e=t.lastIndexOf(".");if(e<0)return!1;const n=t.slice(e).toLowerCase();return Dg.includes(n)}function $k(t){return`/api/terminal/fs/preview/${t.split(/[\\/]+/).filter(Boolean).map(n=>encodeURIComponent(n)).join("/")}`}const Hk={".stl":"model/stl",".glb":"model/gltf-binary",".gltf":"model/gltf+json"};async function qk(t,e,n,r="list_directory",o,s="name"){const i=new URLSearchParams({path:t});n&&i.set("showHidden","true"),s!=="name"&&i.set("sort",s),i.set("action",r),o&&i.set("requestSlotId",o);const a=await ge(`/api/terminal/fs/list?${i}`,{signal:e},In,"Directory listing took too long. The folder may be on slow storage or blocked by another process.");if(!a.ok){const c=await a.json().catch(()=>({error:"Failed to list directory"}));throw new Error(c.error||"Failed to list directory")}return a.json()}async function Kk(t,e,n,r,o,s="name",i,a={}){const c=new URLSearchParams({path:t,query:e,stream:"true"});o&&c.set("showHidden","true"),s==="content"&&c.set("mode","content"),i&&c.set("requestSlotId",i);for(const g of a.excludePatterns??[])c.append("exclude",g);a.caseSensitive&&c.set("caseSensitive","true"),a.wholeWord&&c.set("wholeWord","true"),a.regex&&c.set("regex","true");const l=await fetch(`/api/terminal/fs/search?${c}`,{signal: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 h=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(`
10
10
  `);for(;b>=0;)h(f.slice(0,b)),f=f.slice(b+1),b=f.indexOf(`
11
11
  `)}f+=u.decode(),h(f)}async function zk(t,e,n){const r=new URLSearchParams;for(const d of t)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){e(u.events);const f=u.events.find(h=>h.type==="rescan-required"&&h.reason!=="event-storm"&&h.reason!=="reconnected"&&h.reason!=="directory-rescan"&&h.reason!=="polling-fallback");f?.reason&&(c=f.reason)}};for(;;){const{value:d,done:u}=await s.read();if(u)break;a+=i.decode(d,{stream:!0});let f=a.indexOf(`
12
12
  `);for(;f>=0;)l(a.slice(0,f)),a=a.slice(f+1),f=a.indexOf(`
13
- `)}if(a+=i.decode(),l(a),c)throw new Error(c)}function Wk(t){if(!t)return;const e=new URLSearchParams({requestSlotId:t,action:"cancel_io_slot"});fetch(`/api/terminal/fs/cancel-slot?${e}`,{method:"GET",keepalive:!0}).catch(()=>{})}async function Gk(t,e,n="view_file",r){const o=new URLSearchParams({path:t,action:n});r&&o.set("requestSlotId",r);const s=await mg(`/api/terminal/fs/read?${o}`,{signal:e,timeoutMs:Cn});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 Vk(t,e,n="HEAD",r,o="ref"){const s=new URLSearchParams({path:t,cwd:e,ref:n,action:"git_blob"});o==="index"&&s.set("source","index");const i=await ge(`/api/terminal/fs/git-blob?${s}`,{signal:r},Cn,"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 Xk(t,e,n="view_file",r){const o=new URLSearchParams({path:t,action:n});r&&o.set("requestSlotId",r);const s=await mg(`/api/terminal/fs/blob?${o}`,{signal:e,timeoutMs:Bg(t)?AA:Cn});if(!s.ok){const c=await s.json().catch(()=>({error:"Failed to load image preview"}));throw new Error(c.error||"Failed to load image preview")}const i=await s.blob(),a=s.headers.get("Content-Length");return{blob:i,path:t,size:a?Number(a):null,modified:s.headers.get("Last-Modified"),mimeType:s.headers.get("Content-Type")||i.type||li(t)||"application/octet-stream"}}function Cl(t,e){try{const n=decodeURIComponent(t.headers.get("X-Termdock-Source-Path")||"");return n.startsWith("/")&&!/[\r\n\0]/.test(n)?n:e}catch{return e}}async function Yk(t,e,n,r="view_file",o){const s=new URLSearchParams({path:t,view:e,action:r});o&&s.set("requestSlotId",o);const i="KiCad preview rendering or transfer timed out.",a=Sl(n,yg,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:Cl(c,t),view:e,size:d?Number(d):null,modified:c.headers.get("Last-Modified"),mimeType:c.headers.get("Content-Type")||l.type||"image/svg+xml"}}catch(c){throw a.signal.aborted&&!n?.aborted?new Error(i):c}finally{a.cleanup()}}async function Zk(t,e,n,r,o){const s=new URLSearchParams({path:t,view:e,x:String(n),y:String(r)}),i=await ge(`/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 Jk(t,e,n="view_file",r){const o=new URLSearchParams({path:t,action:n});r&&o.set("requestSlotId",r);const i=Sl(e,wg,"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=kl(t)??"";return{blob:c,path:Cl(a,t),size:l?Number(l):null,modified:a.headers.get("Last-Modified"),ext:d,mimeType:a.headers.get("Content-Type")||c.type||Hk[d]||"application/octet-stream"}}finally{i.cleanup()}}function nf(){return typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}async function Qk(t){const e=`/api/terminal/fs/download?path=${encodeURIComponent(t)}`,n=await fetch(e);if(!n.ok){const c=await n.json().catch(()=>({error:"Failed to download file"}));throw new Error(c.error||"Failed to download file")}const r=await n.blob(),o=Fg(n.headers.get("Content-Disposition")||"")??t.split("/").pop()?.split("\\").pop()??"download",s=window.showSaveFilePicker;if(typeof s=="function")try{const l=await(await s({suggestedName:o})).createWritable();await l.write(r),await l.close();return}catch(c){if(c instanceof DOMException&&c.name==="AbortError")return}if(nf()){const c=new File([r],o,{type:r.type||"application/octet-stream"});if(typeof navigator<"u"&&"share"in navigator&&(!navigator.canShare||navigator.canShare({files:[c]})))try{await navigator.share({files:[c]});return}catch(d){if(d instanceof DOMException&&d.name==="AbortError")return}}if(nf()){const c=await uA(r,o);if(c){window.location.assign(c);return}}const i=URL.createObjectURL(r),a=document.createElement("a");a.href=i,a.download=o,a.rel="noopener",a.style.display="none",document.body.appendChild(a),a.click(),setTimeout(()=>{URL.revokeObjectURL(i),a.remove()},4e3)}async function e2(t){const e=await Z(),n=new URLSearchParams({path:t,confirm:"true"}),r=await ge(`/api/terminal/fs/file?${n}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}},Cn,"File deletion took too long.");if(!r.ok){const o=await r.json().catch(()=>({error:"Failed to delete file"}));throw new Error(o.error||"Failed to delete file")}}async function t2(t,e,n,r){const o=new FormData;for(const u of e)o.append("files",u);const s=`/api/terminal/fs/upload?dir=${encodeURIComponent(t)}`,i=await Z();r?.(0);const a={"X-XSRF-TOKEN":i};let c=o;if(r){const u=new Response(o);a["Content-Type"]=u.headers.get("Content-Type"),c=await u.blob()}const l=await ge(s,{method:"POST",headers:a,body:c,signal:n,onUploadProgress:c instanceof Blob&&r?u=>r(Math.min(99,Math.floor(u/Math.max(1,c.size)*100))):void 0},12e4,"Upload timed out");if(!l.ok){const u=await l.json().catch(()=>({error:"Upload failed"}));throw new Error(u.error||"Upload failed")}const d=await l.json();return r?.(100),d}async function n2(t){const e=await ge("/api/terminal/fs/local-open-availability",{signal:t},Cn,"Local file browser availability check timed out");return e.ok?e.json():{available:!1}}async function r2(t){const e=await Z(),n=await ge("/api/terminal/fs/open-in-file-browser",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({path:t})},Cn,"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 Fg(t){if(!t)return null;const e=/(?:^|;)\s*filename\*=\s*(?:UTF-8'')?([^;]+)/i.exec(t);if(e){const r=e[1].trim().replace(/^"|"$/g,"");try{return decodeURIComponent(r)}catch{return r}}const n=/(?:^|;)\s*filename=\s*(?:"([^"]*)"|([^;]+))/i.exec(t);return n?(n[1]??n[2]).trim():null}function o2(t,e){e?.algorithm&&e.algorithm!=="default"&&t.set("algorithm",e.algorithm),e?.whitespace&&e.whitespace!=="default"&&t.set("whitespace",e.whitespace),e?.context==="all"?t.set("context","all"):typeof e?.context=="number"&&t.set("context",String(e.context))}async function s2(t,e,n,r,o=t?"view_diff":"view_all_changes",s,i,a,c){const l=new URLSearchParams;t&&l.set("path",t),n&&l.set("cwd",n),l.set("action",o),o2(l,c),s&&l.set("traceId",s),i&&l.set("interactionId",i);const d=!!t&&o==="view_diff",u=typeof performance<"u"?performance.now():Date.now();Ht("request_start",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:n,action:o,cached:!!e,algorithm:c?.algorithm??"default",whitespace:c?.whitespace??"default",context:c?.context===void 0?"default":String(c.context),timeoutMs:d?or:pt});const f=await ge(`/api/terminal/fs/diff?${l}`,{signal:r},d?or:pt,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 Ht("timeout_or_abort",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,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(Ht("response_headers",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,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 Ht("error",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:n,action:o,status:f.status,message:m.error||"Failed to get diff"}),new Error(m.error||"Failed to get diff")}Ht("response_body_start",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:n,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),contentLength:f.headers.get("Content-Length")});let h;try{h=await xg(f,d?or:pt,d?"Git diff response body is still loading for this file.":"Git diff response body took too long.")}catch(m){throw Ht("response_body_timeout",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,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(h)}catch(m){throw Ht("response_body_parse_error",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:n,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),bytes:h.length,snippet:h.slice(0,160),message:m instanceof Error?m.message:String(m)}),m}return Ht("response_body",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,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 i2(t,e,n="load_git_details",r){const o=new URLSearchParams;t&&o.set("cwd",t),o.set("action",n),r&&o.set("requestSlotId",r);const s=o.toString(),i=await ge(`/api/terminal/fs/git-context${s?`?${s}`:""}`,{signal:e},pt,"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 a2(t={},e){const n=new URLSearchParams;t.workspaceRoot&&n.set("workspaceRoot",t.workspaceRoot),t.repoRoot&&n.set("repoRoot",t.repoRoot);const r=n.toString(),o=await ge(`/api/terminal/fs/change-audit${r?`?${r}`:""}`,{signal:e},pt,"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 c2(t,e){const n=new URLSearchParams;t.cwd&&n.set("cwd",t.cwd),t.repoRoot&&n.set("repoRoot",t.repoRoot),n.set("base",t.base),t.head&&n.set("head",t.head),t.includeUncommitted===!1&&n.set("includeUncommitted","0"),n.set("action","load_branch_diff"),t.requestSlotId&&n.set("requestSlotId",t.requestSlotId);const r=await ge(`/api/terminal/fs/branch-diff?${n}`,{signal:e},or,"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 l2(t,e){const n=new URLSearchParams;t.cwd&&n.set("cwd",t.cwd),t.repoRoot&&n.set("repoRoot",t.repoRoot),n.set("commit",t.commit),n.set("action","load_commit_diff"),t.requestSlotId&&n.set("requestSlotId",t.requestSlotId);const r=await ge(`/api/terminal/fs/commit-diff?${n}`,{signal:e},or,"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 d2(t,e){const n=new URLSearchParams;t.cwd&&n.set("cwd",t.cwd),t.repoRoot&&n.set("repoRoot",t.repoRoot),n.set("limit",String(t.limit)),typeof t.skip=="number"&&n.set("skip",String(t.skip)),t.query&&n.set("query",t.query),n.set("action","load_recent_commits"),t.requestSlotId&&n.set("requestSlotId",t.requestSlotId);const r=await ge(`/api/terminal/fs/git-recent-commits?${n}`,{signal:e},pt,"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 u2(t={},e){const n=new URLSearchParams;t.workspaceRoot&&n.set("workspaceRoot",t.workspaceRoot),t.repoRoot&&n.set("repoRoot",t.repoRoot),t.baseRef&&n.set("baseRef",t.baseRef),t.branchName&&n.set("branchName",t.branchName);const r=n.toString(),o=await ge(`/api/terminal/fs/branch-audit${r?`?${r}`:""}`,{signal:e},pt,"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 f2(t={}){const e=await Z(),n=await ge("/api/terminal/fs/change-audit",{method:"DELETE",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)},pt,"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 h2(t={}){const e=await Z(),n=await ge("/api/terminal/fs/branch-audit",{method:"DELETE",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)},pt,"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 p2(t,e,n){const r=new URLSearchParams;t&&r.set("cwd",t),r.set("action","load_untracked_files"),n&&r.set("requestSlotId",n);const o=r.toString();return(await ge(`/api/terminal/fs/untracked-files${o?`?${o}`:""}`,{signal:e},or,"Untracked file scan took too long. The repository may be busy, on slow storage, or locked by another Git process.")).json()}async function g2(t,e,n={}){const r=new URLSearchParams;t&&r.set("cwd",t),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:e}):await ge(s,{signal:e},n.requestTimeoutMs??pt,"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 m2(t){const e=await Z(),n=await fetch("/api/terminal/fs/git-action",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});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 w2(t){const e=new URLSearchParams;t.cwd&&e.set("cwd",t.cwd),t.action&&e.set("action",t.action),t.jobId&&e.set("jobId",t.jobId);const n=await fetch(`/api/terminal/fs/git-action/status?${e}`);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 y2(t){const e=await Z(),n=await fetch("/api/terminal/fs/apply-hunk",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});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 Ue(t,e){const n=e?.method?.toUpperCase()??"GET",r=new Headers(e?.headers);n!=="GET"&&n!=="HEAD"&&r.set("X-XSRF-TOKEN",await Z()),e?.body&&r.set("Content-Type","application/json");const o=await fetch(`/api/terminal/operations${t}`,{...e,headers:r});if(!o.ok){const s=await o.json().catch(()=>({error:"操作失败"}));throw new Ce(s.error||"操作失败",o.status)}return o.status===204?void 0:await o.json()}function b2(){return Ue("/automations")}function v2(t){return Ue("/automations",{method:"POST",body:JSON.stringify(t)})}function S2(t){return Ue(`/automations/${encodeURIComponent(t)}/run`,{method:"POST"})}function x2(t,e){return Ue(`/automations/${encodeURIComponent(t)}/enabled`,{method:"POST",body:JSON.stringify({enabled:e})})}function E2(t){return Ue(`/automations/${encodeURIComponent(t)}`,{method:"DELETE"})}let Gt=null,rf="";const gc=new Set;Ws(()=>Gt?.refreshPeers(!0));function Rl(){return Ue("/collaboration-groups",{signal:AbortSignal.timeout(1e4)})}function Rn(){const t=Fc(),e=t?.serviceOrigin??window.location?.origin??"",n=`${t?.targetPeerId??""}:${e}`;return(!Gt||n!==rf)&&(Gt?.dispose(),rf=n,Gt=new dA({origin:e,readLocal:Rl,readPeers:async()=>{const r=await Ue("/collaboration-directory",{signal:AbortSignal.timeout(1e4)});let o;const s=await Promise.race([Ke().catch(()=>[]),new Promise(a=>{o=setTimeout(()=>a([]),1e3)})]).finally(()=>clearTimeout(o)),i=new Map((r.services??[]).map(a=>{const c=s.find(d=>a.serviceId&&d.targetPeerId===a.serviceId)??s.find(d=>!a.serviceId&&(d.serviceOrigin||d.url)===a.origin),l=lA({serviceLabel:c?.label||a.label,serviceOrigin:a.origin});return[a.origin,l]}));return{...r,origin:e,services:r.services?.map(a=>({...a,label:i.get(a.origin)??a.label})),sessions:r.sessions.map(a=>({...a,serviceLabel:i.get(a.serviceOrigin??"")??a.serviceLabel}))}},peerProtocol:"v2"}),Gt.subscribe(r=>{for(const o of gc)o(r)})),Gt}function Tl(){Gt?.dispose(),Gt=null}function A2(t){return gc.add(t),()=>{gc.delete(t)}}function k2(){window.dispatchEvent(new Event("termdock:collaboration-enroll")),Rn().refreshPeers(!0)}function I2(){return Rn().load()}async function C2(t){const e=await Rl(),n=t.id?e.groups.find(c=>c.id===t.id):void 0;if(t.id&&!n)throw new Ce("协作组已删除,请刷新列表",404);if(n&&t.expectedUpdatedAt!==void 0&&t.expectedUpdatedAt!==n.updatedAt)throw new Ce("协作组已被修改,请重新打开成员管理后再保存",409);const r=[...new Set(t.sessionIds)];if(!t.name.trim()||r.length<2)throw new Ce("协作组至少需要两个有效会话",400);const o=new Set([...e.sessions.map(c=>c.sessionId),...n?.sessionIds??[]]);if(r.filter(c=>!o.has(c)).some(c=>!lc(c)))throw new Ce("所选会话已变化,请刷新后重新选择;尚未保存任何修改",409);const i={...t,sessionIds:r,...n?{expectedUpdatedAt:t.expectedUpdatedAt??n.updatedAt}:{}},a=await Ue("/collaboration-groups",{method:"POST",body:JSON.stringify(i)});return Rn().invalidate(),a}async function R2(t){if((await Rl()).capabilities?.groupMove!==1)throw new Ce("当前服务需要升级后才能在协作组之间移动成员;原成员关系未修改",409);await Ue("/collaboration-groups/move-member",{method:"POST",body:JSON.stringify(t)}),Rn().invalidate()}function T2(t,e){return Ue(`/collaboration-groups/${encodeURIComponent(t)}/spawn`,{method:"POST",body:JSON.stringify(e)}).then(n=>(Rn().invalidate(),n))}function P2(t,e,n){return Ue(`/collaboration-groups/${encodeURIComponent(t)}/role`,{method:"POST",body:JSON.stringify({sessionId:e,role:n})}).then(r=>(Rn().invalidate(),r))}function N2(t,e){const n=e===void 0?"":`?expectedUpdatedAt=${encodeURIComponent(e)}`;return Ue(`/collaboration-groups/${encodeURIComponent(t)}${n}`,{method:"DELETE"}).then(()=>{Rn().invalidate()})}function L2(t){return Ue(`/collaboration-groups/${encodeURIComponent(t)}/messages`)}function B2(t,e){return Ue(`/collaboration-groups/${encodeURIComponent(t)}/messages`,{method:"POST",body:JSON.stringify(e)})}function _2(t){return Ue(`/session-search?q=${encodeURIComponent(t)}`)}const O2=Object.freeze(Object.defineProperty({__proto__:null,AUTH_UNAUTHORIZED_EVENT:vl,AgentPluginManifestError:Al,EDA_PREVIEW_REQUEST_TIMEOUT_MS:yg,HTML_EXTENSIONS:Dg,MODEL_3D_EXTS:Og,MODEL_PREVIEW_REQUEST_TIMEOUT_MS:wg,TERMINAL_CSRF_REQUEST_TIMEOUT_MS:bg,TERMINAL_HEALTH_REQUEST_TIMEOUT_MS:vg,TERMINAL_SESSION_OPEN_REQUEST_TIMEOUT_MS:Sg,TerminalApiError:Ce,VISIBLE_WAKEUP_PROBE_TIMEOUT_MS:Eg,acknowledgeTerminalOutput:zA,applyDiffHunk:y2,buildHtmlPreviewUrl:$k,buildVideoPreviewUrl:Dk,cancelIoSlot:Wk,checkAgentPluginUpdate:bk,checkTermdockUpdate:vA,checkTerminalHealth:JA,clearBranchAuditRecords:h2,clearChangeAuditRecords:f2,clearSessionInventoryEntries:Pg,closeTerminal:YA,confirmTermdockUpdateRestart:SA,connectTerminalStream:jA,createAgentPlugin:wk,createTerminalSession:MA,deleteAgentPlugin:xk,deleteFile:e2,dismissTmuxRecovery:ok,doctorAgentPlugin:Sk,downloadFile:Qk,fetchQuota:xA,forceKillTerminal:QA,getAgentHooks:hk,getAgentLaunchers:fk,getAgentPlugins:mk,getAppliedTerminalCursor:FA,getBranchAuditRecords:u2,getBranchDiff:c2,getChangeAuditRecords:a2,getCommitDiff:l2,getContextDraft:lk,getDefaultEdaPreviewView:jk,getEdaExtForPath:Il,getFileDiff:s2,getGitActionStatus:w2,getGitBlobContent:Vk,getGitBundle:g2,getGitContext:i2,getImageMimeTypeForPath:li,getLocalFileBrowserAvailability:n2,getModel3dExtForPath:kl,getProgramDetection:Tk,getRecentCommits:d2,getSessionInventory:Ig,getSettings:sr,getTermdockUpdateState:bA,getTitleNamerCatalog:ck,getTmuxStatus:tk,getToolbarPresetsDoc:ik,getUntrackedFiles:p2,getVideoMimeTypeForPath:_g,inspectEdaPoint:Zk,installAgentHooks:pk,installAgentPluginSource:yk,isHeicImagePath:Bg,isPreviewableEdaPath:Mk,isPreviewableHtmlPath:Uk,isPreviewableImagePath:Bk,isPreviewableModel3dPath:Fk,isPreviewableVideoPath:Ok,killTmuxSession:nk,listAgentAutomations:b2,listAgentResumeHistory:Ak,listCollaborationGroups:I2,listCollaborationMessages:L2,listDirectory:qk,listTmuxSessions:ek,loginWithPassword:Lg,logout:uk,moveCollaborationMember:R2,openInFileBrowser:r2,openSessionInventoryEntry:Cg,parseFilenameFromContentDisposition:Fg,prepareAgentResumeHistory:kk,probeTerminalConnection:$A,readEdaPreviewBlob:Yk,readFileContent:Gk,readImagePreviewBlob:Xk,readModel3dBlob:Jk,readPreviewSourcePath:Cl,reconnectTerminalConnectionNow:HA,refreshQuota:EA,removeAgentAutomation:E2,removeAgentResumeHistory:Ik,removeCollaborationGroup:N2,removeSessionInventoryEntry:Tg,reorderSessionInventoryEntries:Rg,replaceProgramDetection:Pk,replaceProgramRules:Ck,replaceToolbarPresetsDoc:ak,resetCollaborationDirectory:Tl,resetCsrfTokenCache:xl,resetProgramDetection:Nk,resetProgramRules:Rk,resizeTerminal:VA,restartTerminalSession:ZA,restoreAllTmuxAgentSessions:rk,resumeAgentSession:Ek,retryCollaborationPeers:k2,runAgentAutomation:S2,runGitAction:m2,saveAgentAutomation:v2,saveCollaborationGroup:C2,searchFilesStream:Kk,searchTerminalSessions:_2,sendAgentReviewAck:pc,sendCollaborationMessage:B2,sendTerminalFlowControlState:GA,sendTerminalFocusState:KA,sendTerminalInput:UA,sendTerminalViewingState:WA,sendTmuxAction:XA,setAgentAutomationEnabled:x2,setCollaborationMemberRole:P2,setTerminalOutputSubscription:kg,setTerminalSnapshotCursor:DA,spawnCollaborationAgent:T2,subscribeCollaborationGroups:A2,suspendTerminalConnectionReconnects:qA,uninstallAgentHooks:gk,updateAgentPlugin:vk,updateContextDraft:dk,updateSessionInventoryEntry:os,updateSettings:Et,uploadFiles:t2,watchFileSystem:zk},Symbol.toStringTag,{value:"Module"})),D2={app:{name:"Termdock"},common:{cancel:"Cancel",close:"Close",save:"Save",reset:"Reset",loading:"Loading…",error:"Error",retry:"Retry",refresh:"Refresh",search:"Search",clear:"Clear",delete:"Delete",on:"On",off:"Off",back:"Back",copy:"Copy",decrease:"Decrease",increase:"Increase",use:"Use",previous:"Previous",next:"Next"},login:{prompt:"termdock login",placeholder:"Enter password",placeholderBlocked:({s:t})=>`Please wait ${t}s`,submit:"Sign in",invalidPassword:"Incorrect password",failed:"Login failed"},sidebar:{sessions:"Sessions",noSessions:"No open sessions yet.",noMatchingSessions:"No matching sessions.",toggleSearch:"Toggle search",settings:"Settings",moreActions:"More actions",subscriptionQuota:"Subscription quota",pinSidebar:"Keep sidebar open",unpinSidebar:"Stop keeping sidebar open",runningSessionButton:"Running sessions button",runningSessionButtonHint:"Tap to cycle, swipe sideways to select, hold to drag",updateAvailable:({version:t})=>`Termdock ${t} is available`,updateInstalling:"Installing in the background without interrupting this service.",updateReady:"The update is installed and ready for a confirmed restart.",updateRestart:"Restart and finish update",updateRestartConfirm:({version:t})=>`Restart Termdock and switch to ${t}? This page will reconnect briefly and sessions will stay open.`,updateRestarting:"Restarting; this page will reconnect automatically…",updateFailed:"Automatic installation failed. This reminder will remain.",updateRetry:"Try again",filterSessions:"Filter sessions",clearSearch:"Clear search",groupByFolder:"Group by folder",groupByFolderTitle:"Collapse sessions into groups by working directory. Mutually exclusive with drag sorting.",ungrouped:"Other",needsAttention:"Needs attention",waitingForYou:"Waiting for you",completedUnread:"Completed · unread",closeSession:({name:t})=>`Close ${t}`,newShell:"Shell",newTmux:"Tmux",newTmuxDisabled:"tmux not available on server",confirmNewShell:"Create Shell?",confirmNewTmux:"Create Tmux?",newSession:"New terminal",newSessionWithAgent:({agent:t})=>`New ${t}`,moreLaunchOptions:"More launch options",recoverableSessions:"Recoverable sessions",refreshRecoverableSessions:"Refresh recoverable sessions",restoreRecoverableSession:({name:t})=>`Restore ${t}`,restoringRecoverableSession:"Restoring…",restore:"Restore",newSessionAdvanced:"Quick-launch agent",newSessionComposerTitle:"Start a session",newSessionHint:"Choose how and where it starts",launchSessionWith:({name:t})=>`Start ${t}`,setNewSessionDefault:({name:t})=>`Set ${t} as default`,currentNewSessionDefault:({name:t})=>`${t} is the current default`,currentDefaultAgent:({name:t})=>`Current default: ${t}`,defaultAgent:"Default",makeDefault:"Make default",sessionMode:"Run mode",tmuxKeepsRunning:"Keeps running after disconnect",resumeHistory:"Recent conversations",resumeHistoryCount:({n:t})=>`${t} saved`,resumeHistoryLoading:"Loading recent Agent conversations…",resumeHistoryAction:({title:t})=>`Resume ${t}`,resumeHistoryRemove:({title:t})=>`Remove ${t} from recent conversations`,resumeHistoryLoadFailed:"Could not load recent Agent conversations.",resumeHistoryFailed:"Could not prepare this Agent conversation for resume.",resumeHistoryRemoveFailed:"Could not remove the conversation from history.",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",insertCurrentFolder:"Insert current folder reference",insertCurrentFolderShort:"Insert",pinnedFolders:"Pinned",unpinFolder:({name:t})=>`Unpin ${t}`,fileWatchUnavailable:({message:t})=>`File watcher unavailable: ${t}. Click to refresh manually.`,browsingOutsideProject:"Browsing outside current project",browsingOutsideProjectHint:"Git and Changes still use the current project. File references from here are inserted as external paths.",toggleSearch:"Toggle search",refreshGit:"Refresh Git status",gitLastUpdated:({time:t})=>`Last updated: ${t}`,close:"Close",filterChanges:"Filter changes or files",searchPlaceholderContent:"Search text in files…",searchModeName:"File",searchModeContent:"Content",clearSearch:"Clear search",searchScope:"Scope",searchScopePlaceholder:"Relative folder or absolute path",resetSearchScope:"Reset to current folder",searchOptions:"Search options",searchExclude:"Exclude",searchExcludePlaceholder:"dist/**, *.lock",clearSearchExclude:"Clear exclusions",contentSearchOptions:"Content search options",matchCase:"Match case",matchWholeWord:"Whole word",useRegex:"Regex",insertGitContext:"Insert current Git context into terminal",copyGitContext:"Copy Git context",insertChangeAuditPrompt:"Explain changes",insertChangeAuditPromptTitle:"Insert the change audit prompt into the current session",changeAuditShort:"Explain changes",changeAuditLoading:"Loading hunk explanations…",changeAuditLoaded:({count:t})=>`${t} hunk explanation${t===1?"":"s"} loaded`,changeAuditLoadedAt:({time:t})=>`Generated ${t}`,changeAuditRegenerate:"Regenerate",changeAuditRefreshStale:"Fill stale",changeAuditRefreshStaleTitle:"Insert a prompt to refresh stale hunk explanations",clearChangeAudit:"Clear",clearChangeAuditTitle:"Clear hunk explanations for the current repository",changeAuditClearFailed:({message:t})=>`Failed to clear hunk explanations: ${t}`,changeAuditScopeAll:"All repositories",changeAuditScopeLabel:"Explain scope",branchAuditTitle:"Branch explanation",branchAuditShort:"Explain branch changes",branchAuditBaseLabel:"Base branch",branchAuditBasePlaceholder:"Base branch, e.g. master",branchAuditBaseSearchPlaceholder:"Search base branch",branchAuditBaseEmpty:"No branch options. Type a branch name directly.",branchAuditGenerate:"Generate",branchAuditRegenerate:"Regenerate",branchAuditGenerateTitle:"Insert a prompt to explain this branch against the base branch",branchAuditViewDiff:"View diff",branchAuditViewDiffTitle:"View target branch changes against the base branch",branchAuditDiffLoading:"Loading branch diff...",branchAuditDiffEmpty:"No changes between this branch and the base branch.",branchAuditMissingBase:({repo:t})=>`${t} has no base branch set`,branchAuditRefreshDiff:"Refresh diff",branchAuditRefreshStale:"Fill stale",branchAuditRefreshStaleTitle:"Insert a prompt to refresh stale branch explanations",branchAuditClearTitle:"Clear current branch explanation",branchAuditClearFailed:({message:t})=>`Failed to clear branch explanation: ${t}`,branchAuditCommitCount:({count:t})=>`${t} commit${t===1?"":"s"}`,branchAuditFileCount:({count:t})=>`${t} file${t===1?"":"s"}`,branchAuditTruncated:"diff truncated",branchAuditCurrent:"Saved explanation",branchAuditStale:"Explanation is stale",branchAuditEmpty:"No branch explanation yet. Generate one to persist it here for later review.",branchAuditView:"View explanations",branchAuditSaved:({count:t})=>`${t} hunk explanation${t===1?"":"s"} saved`,branchAuditGeneratedAt:({time:t})=>`Generated ${t}`,insertPreset:({label:t})=>`Insert: ${t}`,tabChanges:"Changes",tabGit:"Git",tabFiles:"Files",inserted:"Inserted",copied:"Copied",toggleContextDraft:"Toggle context draft",contextDraftTitle:"Context draft",contextDraftHint:"References are added here while enabled. Keep browsing, add instructions, then insert once.",contextDraftPlaceholder:"Compose a longer prompt here. Keep using sidebar references to add context…",contextDraftCollapse:"Collapse context draft",contextDraftExpand:"Expand context draft",contextDraftDisable:"Disable context draft",contextDraftClear:"Clear draft",contextDraftInsert:"Insert",contextDraftInsertAndSend:"Insert & send",contextDraftInserted:"Inserted",contextDraftSent:"Sent",contextDraftSend:"Send draft",contextDraftAppended:"Reference added",contextDraftResize:"Drag to resize, double-click for default height",contextDraftAutoCollapseAfterSend:"Collapse after insert/send",contextDraftInsertFailed:"Terminal disconnected — draft kept",contextDraftCharacterCount:({count:t})=>`${t} chars`,selectFilePrompt:"Select a file to preview its contents",backToFileList:"Back to file list",backToPreviousPreview:"Back to source document",insertLineRef:({lineLabel:t})=>`Insert ${t}`,insertFileRef:"Insert",copyFileRef:"Copy file reference",findInFile:"Find in file",findInFilePlaceholder:"Find in this file…",previousSearchMatch:"Previous match",nextSearchMatch:"Next match",closeFileSearch:"Close file search",downloadFile:"Download file",downloadFailed:"Download failed",uploadFile:"Upload file",uploadFiles:"Upload files",insertLocalFile:"Insert local file",insertLocalImage:"Insert local image",layoutMode:"Display mode",layoutModeAuto:"Auto",layoutModeNarrow:"Narrow",layoutModeWide:"Wide",dropToUpload:"Drop files to upload",uploading:"Uploading…",uploadSuccess:({count:t})=>`${t} file${t===1?"":"s"} uploaded`,uploadFailed:"Upload failed",binaryPreviewHint:"Binary files cannot be previewed. Use the download button above to save it.",selectedLineHint:({lineLabel:t})=>`Selected ${t} · tap "Insert" below to add to terminal`,multiLineHint:"Multi-line select: tap start line, then end line",loadingImage:"Loading image…",imagePreviewHint:"Pinch or ⌘/Ctrl + scroll to zoom · double-tap to reset",imageLoadFailed:"Failed to load image preview",loadingVideo:"Loading video…",videoPreviewHint:"Click to play · hold for 2× · drag to seek",videoLoadFailed:"Failed to load video preview",videoUnsupported:"Your browser does not support this video format",videoPlay:"Play",videoPause:"Pause",videoLongPressSpeed:"Playing at 2×",videoRotate:"Rotate 90° clockwise",videoFullscreenEnter:"Enter fullscreen",videoFullscreenExit:"Exit fullscreen",model3dLoading:"Loading 3D model…",model3dExplode:"Exploded view",model3dExplodeAxis:"Explosion axis (viewer coordinates)",model3dExplodeAmount:"Explosion amount",model3dHome:"Reset view",model3dFit:"Fit visible parts",model3dFront:"Front view",model3dTop:"Top view",model3dRight:"Right view",model3dAssemble:"Restore assembly",model3dExplodedNotice:"Exploded · dimensions and references remain assembled",model3dLoadFailed:"Failed to load 3D model preview",model3dTimeout:"3D model transfer timed out. Check your connection and retry.",model3dDimensions:({dims:t})=>`Dimensions: ${t}`,model3dHintMouse:"Drag to orbit · two-finger pan · pinch or scroll to zoom",model3dHintTouch:"One finger to orbit · two fingers to zoom & pan",model3dFullscreenEnter:"Fullscreen",model3dFullscreenExit:"Exit fullscreen",model3dBgToLight:"Light background",model3dBgToDark:"Dark background",model3dRefresh:"Reload model",model3dClipToggle:"Section view",model3dClipPosition:"Section position",model3dClipFlip:"Flip section direction",model3dFeatureToggle:"Features",model3dFeatureStatus:({total:t,positioned:e})=>`Features: ${t} · positioned ${e}`,model3dFeatureInsert:"Insert reference",model3dGlossaryToggle:"Modeling terms",model3dPickToggle:"Select part / reference",model3dPickHint:"Select a part to hide it or insert a point reference",model3dHidePart:"Hide part",model3dShowAllParts:({count:t})=>`Show all (${t})`,model3dParts:"Parts",model3dCloseParts:"Close parts",model3dSearchParts:"Find a part",model3dClearPartSearch:"Clear part search",model3dHiddenParts:({count:t})=>`${t} hidden`,model3dShowNamedPart:({name:t})=>`Show ${t}`,model3dHideNamedPart:({name:t})=>`Hide ${t}`,model3dIsolateNamedPart:({name:t})=>`Only show ${t}`,model3dIsolatePart:"Only this part",model3dShowPart:"Show part",model3dNoParts:"No matching parts",model3dUndoVisibility:"Undo",model3dClearSelection:"Clear selection",model3dAllPartsVisible:"All parts visible",model3dInspectHint:"Drag to orbit · double-tap to zoom · double-tap empty space to fit",model3dUnnamedPart:({index:t})=>`Part ${t}`,model3dCanvas:"3D model",model3dMore:"More model options",edaLoading:"Rendering KiCad file…",reviewTargetChanged:"The active session changed. Return to the original session before inserting this reference.",reviewReference:"Review reference",reviewReferenceHint:"Add context, then insert. Nothing is sent automatically.",reviewSnapshot:"Snapshot of the selected viewer",reviewCapturing:"Capturing this view…",reviewIncludeImage:"Include snapshot (stored temporarily on this server)",reviewCaptureFailed:"Snapshot unavailable; location can still be inserted.",reviewNote:"Your comment (optional)",reviewNotePlaceholder:"What should change here?",reviewDetails:"View location and quoted content",reviewUploading:"Preparing reference…",reviewAddToDraft:"Add to context draft",reviewInsert:"Insert reference",reviewUploadFailed:"Could not prepare the reference. Your comment is kept. Retry, or uncheck the snapshot to insert text only.",edaLoadFailed:"Failed to render KiCad preview",edaTimeout:"KiCad preview rendering or transfer timed out. Please retry.",edaRefresh:"Render again",edaPickHint:"Click a schematic or PCB location to create an electronics annotation",edaPickedPosition:({x:t,y:e})=>`Selected ${t}%, ${e}%`,edaPickedBoardPosition:({x:t,y:e,object:n})=>`Board ${t}, ${e} mm · ${n}`,edaInspecting:"Reading board coordinates and nearby object…",edaNoNearbyObject:"No nearby object",edaInsertAnnotation:"Insert electronics annotation",csvUnnamedColumn:({index:t})=>`Column ${t}`,csvSelectedCell:({row:t,column:e})=>`Row ${t} · ${e}`,csvPickHint:({rows:t,columns:e})=>`${t} records · ${e} columns; click a cell to reference`,csvInsertAnnotation:"Insert table annotation",csvTablePreview:"Table preview: select a cell to reference its record",kicadLocalStateNotice:"This is local UI state and is not part of schematic, PCB, or manufacturing review.",kicadShowRawJson:"Show raw JSON",kicadProjectPickHint:"Select a setting to insert a reference",kicadInsertSetting:"Insert setting",markdownPreview:"Preview",markdownSource:"Source",markdownPreviewHint:"Tap a line/section to reference, tap another to extend; drag the left rail to select a range",htmlPreview:"Preview",htmlSource:"Source",htmlPreviewHint:"Sandboxed iframe preview; scripts run sandboxed",htmlFullscreenEnter:"Enter fullscreen preview",htmlFullscreenExit:"Exit fullscreen preview",markdownOutline:"Markdown outline",markdownOutlineShort:"Outline",closeMarkdownOutline:"Close outline",changedFromPath:({path:t})=>`from ${t}`,selectedLineFooter:({lineLabel:t})=>`Selected ${t}`,clearSelection:"Clear",allChanges:"All changes",backToChangeList:"Back to list",allRepositories:"All repositories",allRepositoriesShort:"All",repositories:"Repositories",gitRepositorySectionTitle:"Repository",gitRepositoryLabel:"Repository",gitRepositoryPlaceholder:"Select repository",gitRepositorySearchPlaceholder:"Search repositories",gitRepositoryEmpty:"No available repositories",selectRepositoryForGitActions:"Select a repository before running Git actions",selectRepositoryForDiff:"Select a repository or file to view diff",repoNotLoaded:"Tap to load",repoChangedCount:({count:t})=>`${t} change${t===1?"":"s"}`,repoStagedCount:({count:t})=>`${t} staged`,noChanges:"No changes",noMatchingChanges:"No matching changes",loadingGitChanges:"Loading Git changes…",loadingGitChangesSlow:"Large repositories can take a few seconds.",refreshingGitChanges:"Refreshing Git changes…",gitChangesLoadFailed:"Unable to load Git changes",retryGitChanges:"Retry",insertThisFile:"Insert this file reference into terminal",viewDiff:"View diff",diffViewMode:"Change file display mode",diffViewModeList:"Flat list",diffViewModeTree:"Folder tree",diffViewModeAi:"AI walkthrough",changeWalkthroughEmpty:"No AI walkthrough yet. Generate explanations to show the overview, flow, and checks here.",gitInfo:"Git context",wrapLongLines:"Wrap long lines",wrapOn:"Wrapped",wrapOff:"Raw",multiRepoScan:"Sub-repos",multiRepoScanTitle:"Scan this workspace for nested Git repositories. Off keeps a single-repo view, which opens much faster on large repos.",horizontalScrollHint:"Swipe left/right to see the full diff",stageFile:"Stage",stageAll:"Stage all",unstageFile:"Unstage",stashFile:"Stash",stashAll:"Stash all",restoreFile:"Restore",gitQuickActions:"Git Actions",gitUnavailable:"Current directory is not a Git repository",branchSectionTitle:"Current branch",currentBranchLabel:"Branch",switchBranchPlaceholder:"Select branch",switchBranchSearchPlaceholder:"Search local branch",switchNoBranches:"No local branches",switchBranch:"Switch",noStagedChangesShort:"no staged",stagedCount:({count:t})=>`${t} staged`,stagedCountShort:({count:t})=>`${t} staged`,commitSectionTitle:"Commit",commitReadyHint:({count:t})=>`${t} file${t===1?"":"s"} ready`,commitMessagePlaceholder:"Commit message",commitChanges:"Commit",commitNeedsStaged:"Stage changes before committing",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:t})=>`${t}`,pushBranchSearchPlaceholder:"Search branch",pushNoBranches:"No branches",pushUpstreamBadge:"upstream",pushCurrentBranchBadge:"current",pushNoUpstream:"No upstream configured",pushUpToDate:"Up to date with remote",pushAheadCount:({count:t})=>`${t} commit${t===1?"":"s"} to push`,pushBehindCount:({count:t})=>`${t} commit${t===1?"":"s"} to pull`,pushDivergedCount:({ahead:t,behind:e})=>`${t} ahead / ${e} behind`,pullChanges:"Pull",pushChanges:"Push",gitActionRunning:"Running…",gitActionFailed:({message:t})=>`Git action failed: ${t}`,confirmRestoreTitle:"Discard changes?",confirmRestoreDescription:({path:t})=>`This will discard unstaged changes in ${t}. Termdock cannot recover them.`,confirmRestorePhrase:"discard changes",confirmRestorePlaceholder:"Type “discard changes” to confirm",confirmStashAllTitle:"Stash all changes?",confirmStashAllDescription:"This moves current working tree changes, including untracked files, into a stash.",confirmAction:"Confirm",renderingHtml:"Rendering HTML…",footnotes:"Footnotes",backToFootnote:({index:t})=>`Back to footnote ${t}`,openMermaidDiagram:"Open Mermaid diagram",mermaidDiagram:"Mermaid diagram",renderingDiagram:"Rendering diagram…",markdownImage:"Markdown image",image:"Image",previousImage:"Previous image",nextImage:"Next image",closeImagePreview:"Close image preview",emptyFile:"Empty file.",insertReference:({reference:t})=>`Insert reference: ${t}`,copyReference:({reference:t})=>`Copy reference: ${t}`,byteCount:({count:t})=>`${t} bytes`,previewTruncated:"Preview truncated to 1 MB",branchCandidatesLoading:"Loading branch candidates…",includeUncommitted:"Include local uncommitted changes",includeUncommittedHint:"Include working tree and untracked diffs when viewing or explaining changes",missingBaseReposSkipped:({repositories:t})=>`Repositories without a base branch will be skipped: ${t}`,localBranch:"local",remoteBranch:"remote"},fileTree:{insertRef:"Insert",insertRefTitle:"Insert file reference into active terminal",openDirRoot:"Open",openDirRootTitle:"Use this folder as the current browsing root",openInFileBrowser:"Reveal in Finder",openInFileBrowserTitle:"Open this item in the system file browser",openInFileBrowserFailed:"Failed to open file browser",moreDirActions:"More folder actions",searchFromDir:"Search from here",searchFromDirTitle:"Search only this folder and its descendants",pinDir:"Pin",pinDirTitle:"Pin this folder to the current project",unpinDir:"Pinned",unpinDirTitle:"Unpin this folder",pinFileTitle:"Pin this file to the current project",unpinFileTitle:"Unpin this file",pinFile:"Pin",unpinFile:"Unpin",moreFileActions:"More file actions",deleteFile:"Delete file",deleteFileConfirm:({name:t})=>`Delete “${t}”? This action cannot be undone.`,deleteFileFailed:({message:t})=>`Failed to delete file: ${t}`,noWorkingDir:"No working directory detected.",emptyDir:"Empty directory.",noMatchingFiles:"No matching files.",searching:"Searching files…",searchingWithCount:({count:t})=>`Searching… ${t} found`,searchResults:({count:t})=>`${t} results`,searchScope:"Search scope",searchTruncatedHint:({count:t})=>`Fallback search scanned a large directory and stopped after ${t} matches. Install ripgrep or refine the query for complete results.`,searchStillRunning:"Search is still running. More results will appear automatically.",showingSearchResults:({shown:t,total:e})=>`Showing ${t} of ${e}`,loadMoreSearchResults:({shown:t,total:e})=>`Show more (${t}/${e})`,contentMatchesCount:({count:t})=>`${t} file${t===1?"":"s"} with matches`,moreMatches:({count:t})=>`+${t} more match${t===1?"":"es"}`,noContentMatches:"No matches found in file contents.",contentSearchNeedsRipgrep:"Content search requires ripgrep (rg). Install it on the server to search inside files.",truncatedHint:"Showing first 1000 entries. Use search or open a smaller folder for better performance.",dropToUploadHere:"Upload here",symbolicLink:"Symbolic link",sortByModified:"Sort by recent changes",sortByName:"Sort by name",sortedByModified:"Sorted by recent changes"},diffViewer:{noFileChanges:"No changes in this file.",noUnstagedChanges:"No unstaged changes.",emptyHint:"Make some changes, or pull from a remote.",loading:"Loading diff…",insertAllDiff:"Insert current diff as context",insertFileDiff:"Insert this file's diff",insertHunkDiff:"Insert this hunk",insertHunkShort:"Insert",insertFileShort:"Insert",insertAllShort:"Insert all",stageHunk:"Stage",stageHunkTitle:"Stage only this hunk (git apply --cached)",revertHunk:"Revert",revertHunkTitle:"Revert this hunk in the worktree (cannot be undone)",revertHunkConfirm:"Confirm revert?",hunkActionApplying:"Applying…",hunkActionUnavailable:"Cannot build a patch for this hunk",hunkActionFailed:({message:t})=>`Failed: ${t}. If the changes moved on, refresh and retry.`,auditExplanation:"Change meaning",auditStale:"Explanation stale",auditClear:"Clear explanation",auditGeneratedAt:({time:t})=>`Generated ${t}`,allDiffLabel:"all changes",allChangesLabel:"all changes",workingTree:"Working tree changes",allUnstaged:"All unstaged changes",binaryOrEmpty:"No textual changes to display.",noFinalNewline:"No newline at end of file",noHunks:"No hunks",hunkOutline:"Hunks",expandHunkRail:"Show hunk list",collapseHunkRail:"Hide hunk list",prevHunk:"Previous hunk",nextHunk:"Next hunk",prevFile:"Previous",nextFile:"Next",expandFile:"Expand file",collapseFile:"Collapse file",expandAll:"Expand all",collapseAll:"Collapse all",collapseHunk:"Collapse hunk",useBracketKeysHint:"Press [ / ] to jump between hunks",unified:"Unified",unifiedMode:"Unified view",split:"Split",splitMode:"Side-by-side view",moreActions:"More actions",view:"View",loadingPreviousFile:"Loading previous file…",loadingNextFile:"Loading next file…",resizeNavigation:"Resize diff navigation",focusPathHint:"Select a label to focus its path",whitespace:"Whitespace",whitespaceDefault:"Default",whitespaceTrim:"Ignore trailing",whitespaceIgnore:"Ignore all",whitespaceIgnoreBlankLines:"Ignore blank lines",context:"Context",contextLines:({count:t})=>`${t} lines`,contextAll:"All"},settings:{title:"Settings",font:"Font",render:"Render",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.",desktopUpdateDownloading:"A new version is downloading in the background…",desktopUpdateReady:"The desktop update is downloaded and ready to install.",desktopUpdateInstalling:"Restarting to install the desktop update…",desktopUpdateCheck:"Check desktop app",desktopUpdateCheckAgain:"Check again",desktopUpdateRestart:"Restart and install",desktopUpdateRestartConfirm:"Restart Termdock and install the downloaded desktop update? The terminal service and tmux sessions will remain running.",notifications:"Notify",notificationsTitle:"Notification settings",notificationsHint:"Notify when an AI task finishes while Termdock is hidden.",notificationsPageHint:"Choose which Termdock events can send system notifications. The master switch controls browser permission and delivery; event switches decide what should notify you.",notificationsMaster:"System notifications",notificationsMasterHint:"Allow Termdock to send notifications when it is hidden or running as an installed PWA.",notificationsIOSInstallHint:"On iPhone and iPad, install Termdock to the Home Screen before enabling notifications.",notificationsPermission:"Permission",notificationsPermissionSystem:"Managed by macOS",notificationsTest:"Send test",notificationsTestChecking:"Waiting for macOS to confirm delivery…",notificationsTestDelivered:"Delivered to Notification Center. If no banner appeared, check the alert style and Focus.",notificationsTestFailed:"macOS did not deliver the notification. Allow Termdock in System Settings.",notificationsOpenSystemSettings:"Open system notification settings",notificationsAlertStyle:"Alert style",notificationsAlertStyleHint:"Browsers and Android still decide the final heads-up behavior. Termdock can only request quiet/default/sticky notification options.",notificationsStyleNormal:"Default",notificationsStyleNormalHint:"Sound/vibration if allowed",notificationsStyleQuiet:"Quiet",notificationsStyleQuietHint:"Status tray, no sound",notificationsStylePersistent:"Sticky",notificationsStylePersistentHint:"Stay until dismissed",notificationsEvents:"Events",notificationsAiFinished:"AI task finished",notificationsAiFinishedHint:"Notify when an AI agent stops while Termdock is in the background.",notificationsSessionExited:"Terminal exited",notificationsSessionExitedHint:"Notify when a terminal process exits on its own (closing it yourself does not trigger; delivered via Web Push).",notificationsFutureHint:"More notification types can be added here later without changing the top-level settings layout.",notificationsOffSummary:"System notifications disabled",notificationsAiOnSummary:"AI task finished enabled",notificationsExitOnSummary:"Terminal exit enabled",notificationsBothOnSummary:"AI task finished and terminal exit enabled",notificationsNoEventsSummary:"No notification events enabled",notificationsDenied:"Browser notification permission is blocked. Enable it in site settings.",notificationsUnsupported:"Notifications require a secure context and service worker support.",notificationsTestBody:"Notifications are enabled. You will be notified when an AI task finishes in the background.",shell:"Shell",tmux:"Tmux",auto:"Auto",webgl:"WebGL",canvas:"Built-in",tmuxServer:"Tmux server",tmuxUnavailable:"unavailable",noTmuxSessions:"No tmux sessions on the server.",installTmuxHint:"Install tmux on the server to enable.",refresh:"Refresh",attached:"Attached",restorable:"Restorable",attach:"Attach",attaching:"Attaching…",destroy:"Destroy",sessions:({n:t})=>`${t} session${t===1?"":"s"}`,windows:({n:t})=>`${t} window${t===1?"":"s"}`,keyboardToolbar:"Keyboard toolbar",aiAgentDetection:"AI agent detection",signOut:"Sign out",language:"Language",programNamePlaceholder:"Program name (e.g. claude)",patternPlaceholder:"Regex pattern (e.g. Thinking|Generating)",statusPlaceholder:"Status",addProgram:"Add program",addPattern:"Add pattern",resetDefaults:"Reset defaults",invalidRegex:"Invalid regex",removeProgram:"Remove program",removeRule:"Remove rule",keepLabel:"keep",customColor:"Custom color",tabIndicator:"Tab indicator style",toolbarPresets:"Toolbar presets",detectionRules:"Detection rules",agentHooksHint:"With hooks installed, agents report their own status: working (green), waiting for you (amber), turn done (check) — and you get a notification the moment one needs your input. Hooks install globally but only fire inside termdock terminals.",agentHooksInstall:"Install",agentHooksInstalled:"Installed",agentHooksOutdated:"Outdated",agentHooksNeedsApproval:"Needs approval",agentHooksApprovalHint:"Run /hooks in Codex and approve the Termdock hooks",agentHooksNotInstalled:"Not installed",agentHooksUninstall:"Uninstall",agentHooksReinstall:"Reinstall",agentHooksDevMode:"Dev mode: hooks point at TS sources and need a built install to fire",agentHooksTarget:"writes to",agentAutoRename:"Automatic session titles",agentAutoRenameHint:"Update the title from recent work when an agent finishes a turn. Off by default; manual titles are never overwritten. External plugin CLIs run only after their title feature is enabled.",agentAutoRenameToggle:"Toggle automatic titles for this agent",agentAutoRenameShort:"Auto title",agentAutoRenameNamer:"Title agent",agentAutoRenameFollow:"Follow current session",agentAutoRenameModelsFromCli:"Models discovered from local CLIs",agentAutoRenameRefreshModels:"Refresh CLI models",agentAutoRenameCliDefault:"CLI default model",agentAutoRenameAutomatic:"Automatic selection",agentAutoRenameNoCli:"No supported title CLI detected",agentAutoRenameAdvanced:"Advanced title preferences",agentAutoRenamePreference:"Additional preferences",agentAutoRenamePreferenceHint:"Optional. Add preferences for title style or emphasis; Termdock keeps its default naming rules. Saved when you leave the field.",agentAutoRenamePreferencePlaceholder:"For example: emphasize user value; use action phrases; avoid technical jargon",agentAutoRenamePayloadLimit:"User-message context limit (characters)",agentAutoRenamePayloadLimitHint:"Total raw prompt-submit payload characters retained. Default 12000; range 1000–64000.",agentPlugins:"Agent Plugins",agentPluginAdd:"Add Plugin",agentPluginHint:"Install from an HTTPS Git repository or local directory after reviewing the source. Hooks and executable title CLIs require separate user opt-in.",agentPluginCreate:"Create Plugin",agentPluginDelete:"Delete Plugin",agentPluginInvalid:"Invalid plugin manifest",agentPluginCopyAiPrompt:"Copy AI fix prompt",agentPluginCopied:"Copied",agentPluginSourcePlaceholder:"https://github.com/user/agent-plugin or local directory",agentPluginInstallPackage:"Install plugin",agentPluginAdvancedManifest:"Advanced: paste manifest.json",agentPluginUpdateAvailable:"Update available",agentPluginManualSource:"Manual manifest",agentPluginUpdate:"Update",agentPluginCheck:"Check",agentPluginDoctor:"Diagnose",agentPluginDoctorHint:"Explicitly probe plugin models without generating a title",agentPluginDoctorStatusOk:"Title and model capabilities are healthy",agentPluginDoctorStatusMissing:"titleNamer is not declared",agentPluginDoctorStatusCliDefault:"Titles are available using the CLI default model",agentPluginDoctorStatusNoModels:"No usable model data was returned",agentPluginDoctorStatusFailed:"Model probe failed",agentPluginDoctorModels:"usable models",agentPluginDoctorAutomatic:"automatic",agentPluginDoctorCliDefault:"When no model is specified, the Agent CLI default model is used",agentAutoRenameInterval:"Recheck interval",agentAutoRenameMinutes:"minutes",mobileKeyboard:"Mobile keyboard",saving:"Saving…",rulesHint:"Configure regex patterns to detect what an AI tool is doing in a terminal tab. Each rule can choose its label, color, icon style and how long the indicator is kept after output quiets down. When it stops and you haven't viewed the tab yet, the tab keeps a yellow review hint.",programsHelp:"Supports multiple programs in one config. Separate with commas.",programLabelResolution:"Program label resolution",rawCommandMapping:"Raw command mapping",rawCommandMappingHint:"Rules below map the raw command line to the tab display label. User rules run before built-ins.",genericProgramNames:"Generic program names",genericProgramNamesHint:"Trigger ps-based deep detection (e.g. node, python)",wrapperScriptNames:"Wrapper script names",wrapperScriptNamesHint:"CLI wrappers that launch another tool (e.g. aiden, npx)",shellNamesConfig:"Shell names",shellNamesHint:"Filtered out from tab display (e.g. bash, zsh)",addTag:"+ add",customRules:"Custom rules",addRule:"Add rule",localAccess:"Local access",localAccessHint:"Use this LAN URL from your phone after trusting the local CA. Open Mobile setup on your phone to download the CA certificate.",resetAutoName:"Reset auto",onboardingUrl:"Mobile setup",httpsActive:"HTTPS active",httpsInactive:"HTTPS inactive",caMissing:"CA download unavailable",closeSettings:"Close settings",desktopTitle:"Termdock Desktop",desktopStatusLoading:"Reading native macOS status…",desktopSwitchService:"Switch service",desktopInstallCli:"Install / Repair CLI",desktopCliUpdated:"CLI status updated",desktopOpenDataDirectory:"Open data directory"},toolbarPresets:{preview:"Preview",presets:"Presets",label:"Label",new:"New",reset:"Reset",presetLabelPlaceholder:"Preset label",deletePreset:({name:t})=>`Delete preset ${t}`,matchPrograms:"Match programs",typeEnterHint:"Type & Enter",programsPlaceholder:"vim, nvim, /^claude(-code)?$/i …",programsHelp:"Plain names match as case-insensitive substrings. Wrap in /…/flags for regex (tested against the lowercase program name).",altSlot:"Alt modifier slot",altSlotHint:"Reserve one preview slot for the Alt key.",desktopVisibility:"Show on desktop",desktopVisibilityHint:"Desktop shows only this preset’s custom actions, not the basic keyboard shortcuts.",rowLayout:"Row layout",rowLayoutHint:"Buttons per expanded row.",addRow:"Row",rowN:({n:t})=>`Row ${t}`,del:"Del",buttons:"Buttons",buttonsHint:"Tap to edit. Use ↑↓ to reorder.",addButton:"Add button",noCustomButtons:"No custom buttons yet. Add one to override the default toolbar.",moveUp:"Move up",moveDown:"Move down",removeRow:({n:t})=>`Remove row ${t}`,removeAction:({name:t})=>`Remove ${t}`,labelField:"Label",labelPlaceholder:"Label shown on the button",sequence:"Sequence",sequencePlaceholder:"e.g. /undo or \\t or /||undo",sequenceHint:"Double-tap sequence",doubleTap:"Double-tap sequence",doubleTapAdd:"+ Add",doubleTapPlaceholder:"e.g. /undo\\r or /||undo ||\\r",remove:"Remove",noSequence:"No sequence",preset:"Preset",overCapacityHint:"More buttons than slots. Extra rows will use the last row size."},agentRules:{ruleColors:{green:"Green",yellow:"Yellow",red:"Red",blue:"Blue",purple:"Purple",orange:"Orange",gray:"Gray"}},tab:{session:"Session",new:"New session",rename:"Rename",renameHint:"Change the tab display name",renamePlaceholder:"Leave empty to reset to default",copyCwd:"Copy cwd",copyCwdHint:"Copy the current working directory",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:t})=>`${t} conversation available`,resumeAgentRecoveredHint:"This terminal was rebuilt after an interruption. Continue where you left off.",resumeAgentNow:"Resume",resumeAgentLater:"Dismiss for now",resumeAgentSubmitting:"Submitting the native resume command…",resumeAgentWaiting:"Waiting for the Agent to confirm the restored conversation…",resumeAgentSuccess:({agent:t})=>`${t} conversation restored`,resumeAgentFailed:"Could not resume the Agent conversation. You can retry.",resumeAgentConflict:"This Agent conversation is already open in another terminal.",resumeAgentBusy:"Wait for the current Agent turn to finish before resuming.",resumeAgentTimeout:"The Agent did not confirm the restored conversation. Check the terminal or retry.",tmuxRecoveryTitle:({count:t})=>`tmux exited unexpectedly; ${t} Agent session(s) can be restored`,tmuxRecoveryHint:"Termdock kept the native session IDs. Restore continues each conversation in its original tab.",tmuxRecoveryRestoreAll:"Restore all",tmuxRecoveryRestoring:"Restoring…",tmuxRecoveryDismiss:"Not now",tmuxRecoveryPartial:({restored:t,failed:e})=>`Restored ${t}; ${e} still need attention.`,tmuxRecoveryFailed:"Recovery failed. Check the terminals and try again.",tmuxRecoveryDismissFailed:"Could not dismiss the recovery notice.",copied:"Copied",close:"Close session",closeHint:"Remove this tab from the list",longPressTip:"Tip: hold a tab still for a moment to open actions; hold and drag to reorder.",sessionsTitle:"Sessions",explorerTitle:"Explorer",split:"Split",splitTitle:"Add to split workspace",splitNew:"New session in workspace",splitNewHint:"Uses the current directory and default type; add as many panes as needed",splitExisting:"Choose a session or workspace",splitExistingHint:"Create multiple independent workspaces; choosing another workspace merges them",splitCurrent:"Current",splitClose:"Exit split",splitLayout:"Split layout",splitHorizontal:"Side by side",splitVertical:"Stacked",splitGrid:"Grid",splitWorkspace:"Split group",splitWorkspaces:"Split workspaces",splitRename:"Rename split group",splitRemovePane:"Remove from split",splitExistingGroups:"Existing split groups",splitAvailableSessions:"Available sessions",splitOccupied:"Grouped",splitUnavailableGrouped:"Grouped mode only supports sessions in the same directory",splitEndedGrouped:"Split ended: grouped mode does not support mixed directories",splitNoOtherSessions:"No other sessions are available",sessionCount:({count:t})=>`${t} session${t===1?"":"s"}`,closeChooserTitle:"Destroy tmux session?",closeChooserDescription:"This will stop the session and every process inside it. This cannot be undone.",destroySession:"Destroy session",confirmDestroySession:"Confirm destroy",destroySessionHint:"Stop the tmux session and every process inside it.",dragToClose:"Drag here to close",releaseToClose:"Release to confirm"},agent:{aiRunning:"AI running",needsReview:"Needs review",finishedReview:"AI finished — needs review",aiWaiting:"AI waiting",copyMode:"Copy mode",jumpToNext:"Jump to next session needing attention",jumpToNextRunning:"Jump to next running session",selectRunningSession:"Select a running session",runningSessionGestureHint:"Tap to cycle · swipe sideways to select · hold to drag",currentSession:"Current"},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:t})=>`${t} left`,updated:({time:t})=>`Updated ${t}`,refresh:"Refresh",close:"Close"},errorBoundary:{title:"Something went wrong",unexpected:"An unexpected error occurred",retry:"Try Again",copyDetails:"Copy error details",copied:"Copied",copyFailed:"Copy failed"},error:{type:{network:"Network error",session:"Session error",terminal:"Terminal error",auth:"Authentication error",validation:"Validation error",unknown:"Unknown error"},severity:{low:"Notice: ",medium:"Warning: ",high:"Error: ",critical:"Critical: "},suggestion:{networkCheck:"Check your network connection",networkRetry:"Try reconnecting",networkProxy:"Check proxy settings",networkWait:"Wait for the network to recover",sessionRecreate:"Recreate the session",sessionServer:"Check the server status",sessionCache:"Clear your browser cache",terminalRestart:"Restart the terminal",terminalConfig:"Check the terminal configuration",terminalClear:"Clear the terminal output",authRelogin:"Sign in again",authCredentials:"Check your credentials",authAdmin:"Contact the administrator",validationFormat:"Check the input format",validationParams:"Verify your parameters",validationDocs:"See the documentation",unknownReload:"Reload the page",unknownApp:"Restart the app",unknownSupport:"Contact support"}}},F2={app:{name:"Termdock"},common:{cancel:"取消",close:"关闭",save:"保存",reset:"重置",loading:"加载中…",error:"错误",retry:"重试",refresh:"刷新",search:"搜索",clear:"清除",delete:"删除",on:"开",off:"关",back:"返回",copy:"复制",decrease:"减少",increase:"增加",use:"使用",previous:"上一个",next:"下一个"},login:{prompt:"termdock login",placeholder:"请输入密码",placeholderBlocked:({s:t})=>`请稍候 ${t}s`,submit:"登录",invalidPassword:"密码错误",failed:"登录失败"},sidebar:{sessions:"会话",noSessions:"暂无打开的会话。",noMatchingSessions:"没有匹配的会话。",toggleSearch:"切换搜索",settings:"设置",moreActions:"更多操作",subscriptionQuota:"订阅额度",pinSidebar:"常驻边栏",unpinSidebar:"取消常驻",runningSessionButton:"运行中会话按钮",runningSessionButtonHint:"轻点循环,横向滑动选择,长按拖动",updateAvailable:({version:t})=>`Termdock ${t} 可用`,updateInstalling:"正在后台安装,不会中断当前服务。",updateReady:"更新已安装,确认后将重启服务。",updateRestart:"重启并完成更新",updateRestartConfirm:({version:t})=>`确认重启 Termdock 并切换到 ${t}?当前网页会短暂重连,会话不会被关闭。`,updateRestarting:"正在重启,网页将自动重连…",updateFailed:"自动安装失败,提醒会保留。",updateRetry:"重新尝试",filterSessions:"过滤会话",clearSearch:"清除搜索",groupByFolder:"按文件夹分组",groupByFolderTitle:"按工作目录把会话归组折叠;与拖拽排序互斥。",ungrouped:"其他",needsAttention:"待处理",waitingForYou:"等你操作",completedUnread:"完成待查看",closeSession:({name:t})=>`关闭 ${t}`,newShell:"Shell",newTmux:"Tmux",newTmuxDisabled:"服务端未安装 tmux",confirmNewShell:"创建 Shell?",confirmNewTmux:"创建 Tmux?",newSession:"新建 Terminal",newSessionWithAgent:({agent:t})=>`新建 ${t}`,moreLaunchOptions:"更多启动选项",recoverableSessions:"可恢复会话",refreshRecoverableSessions:"刷新可恢复会话",restoreRecoverableSession:({name:t})=>`恢复 ${t}`,restoringRecoverableSession:"恢复中…",restore:"恢复",newSessionAdvanced:"快速启动 Agent",newSessionComposerTitle:"开始新会话",newSessionHint:"选好运行方式和目录后再启动",launchSessionWith:({name:t})=>`启动 ${t}`,setNewSessionDefault:({name:t})=>`将 ${t} 设为默认`,currentNewSessionDefault:({name:t})=>`${t} 是当前默认`,currentDefaultAgent:({name:t})=>`当前默认:${t}`,defaultAgent:"默认",makeDefault:"设为默认",sessionMode:"运行方式",tmuxKeepsRunning:"断开后继续运行",resumeHistory:"最近会话",resumeHistoryCount:({n:t})=>`已保存 ${t} 条`,resumeHistoryLoading:"正在载入最近的 Agent 会话…",resumeHistoryAction:({title:t})=>`恢复 ${t}`,resumeHistoryRemove:({title:t})=>`从最近会话中移除 ${t}`,resumeHistoryLoadFailed:"无法载入最近的 Agent 会话。",resumeHistoryFailed:"无法准备恢复该 Agent 会话。",resumeHistoryRemoveFailed:"无法从历史中移除该会话。",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:"不显示隐藏文件",insertCurrentFolder:"引用当前目录",insertCurrentFolderShort:"引用",pinnedFolders:"固定",unpinFolder:({name:t})=>`取消固定 ${t}`,fileWatchUnavailable:({message:t})=>`文件监听不可用:${t}。可点击手动刷新。`,browsingOutsideProject:"正在浏览当前项目外目录",browsingOutsideProjectHint:"Git 和改动仍使用当前项目;这里引用的文件会按外部路径插入。",toggleSearch:"切换搜索",refreshGit:"刷新 Git 状态",gitLastUpdated:({time:t})=>`上次更新:${t}`,close:"关闭",filterChanges:"过滤改动或文件",searchPlaceholderContent:"在文件内容中搜索…",searchModeName:"文件",searchModeContent:"内容",clearSearch:"清除搜索",searchScope:"范围",searchScopePlaceholder:"相对目录或绝对路径",resetSearchScope:"恢复搜索当前目录",searchOptions:"搜索选项",searchExclude:"排除",searchExcludePlaceholder:"dist/**, *.lock",clearSearchExclude:"清空排除规则",contentSearchOptions:"内容搜索选项",matchCase:"区分大小写",matchWholeWord:"全词",useRegex:"正则",insertGitContext:"把当前 Git 信息插入 Terminal",copyGitContext:"复制 Git 信息",insertChangeAuditPrompt:"解释当前改动",insertChangeAuditPromptTitle:"把更改审计提示词插入当前会话",changeAuditShort:"解释当前改动",changeAuditLoading:"正在加载 hunk 解释…",changeAuditLoaded:({count:t})=>`已加载 ${t} 条 hunk 解释`,changeAuditLoadedAt:({time:t})=>`最近生成 ${t}`,changeAuditRegenerate:"重新生成",changeAuditRefreshStale:"补充失效",changeAuditRefreshStaleTitle:"为已失效的 hunk 解释插入补充生成提示词",clearChangeAudit:"清理",clearChangeAuditTitle:"清理当前仓库的 hunk 解释",changeAuditClearFailed:({message:t})=>`清理 hunk 解释失败:${t}`,changeAuditScopeAll:"全部仓库",changeAuditScopeLabel:"解释范围",branchAuditTitle:"分支解释",branchAuditShort:"解释分支改动",branchAuditBaseLabel:"基线分支",branchAuditBasePlaceholder:"基线分支,例如 master",branchAuditBaseSearchPlaceholder:"搜索基线分支",branchAuditBaseEmpty:"没有可选分支,可直接输入分支名",branchAuditGenerate:"生成解释",branchAuditRegenerate:"重新生成",branchAuditGenerateTitle:"生成当前分支相对于基线分支的解释提示词",branchAuditViewDiff:"查看对比",branchAuditViewDiffTitle:"查看目标分支相对于基线分支的改动",branchAuditDiffLoading:"正在加载分支对比…",branchAuditDiffEmpty:"当前分支相对于基线分支暂无改动。",branchAuditMissingBase:({repo:t})=>`${t} 未设置基线分支`,branchAuditRefreshDiff:"刷新对比",branchAuditRefreshStale:"补充失效",branchAuditRefreshStaleTitle:"为已失效的分支解释插入补充生成提示词",branchAuditClearTitle:"清理当前分支解释",branchAuditClearFailed:({message:t})=>`清理分支解释失败:${t}`,branchAuditCommitCount:({count:t})=>`${t} 个提交`,branchAuditFileCount:({count:t})=>`${t} 个文件`,branchAuditTruncated:"diff 已截断",branchAuditCurrent:"已保存解释",branchAuditStale:"解释已失效",branchAuditEmpty:"暂无分支解释。生成后会持久化保存,可随时回来查看。",branchAuditView:"查看解释",branchAuditSaved:({count:t})=>`已保存 ${t} 条 hunk 解释`,branchAuditGeneratedAt:({time:t})=>`生成于 ${t}`,insertPreset:({label:t})=>`插入:${t}`,tabChanges:"改动",tabGit:"Git",tabFiles:"文件",inserted:"已插入",copied:"已复制",toggleContextDraft:"切换上下文草稿",contextDraftTitle:"上下文草稿",contextDraftHint:"启用后,引用会追加到这里;可以继续浏览、补写描述,最后一次插入。",contextDraftPlaceholder:"在这里组织长提示词,继续点击侧栏中的引用来追加上下文…",contextDraftCollapse:"收起上下文草稿",contextDraftExpand:"展开上下文草稿",contextDraftDisable:"停用上下文草稿",contextDraftClear:"清空草稿",contextDraftInsert:"插入",contextDraftInsertAndSend:"插入并发送",contextDraftInserted:"已插入",contextDraftSent:"已发送",contextDraftSend:"发送草稿",contextDraftAppended:"已追加引用",contextDraftResize:"拖动调整高度,双击恢复默认",contextDraftAutoCollapseAfterSend:"插入/发送后收起",contextDraftInsertFailed:"终端未连接,草稿已保留",contextDraftCharacterCount:({count:t})=>`${t} 字`,selectFilePrompt:"选择文件以预览内容",backToFileList:"返回文件列表",backToPreviousPreview:"返回来源文档",insertLineRef:({lineLabel:t})=>`引用${t}`,insertFileRef:"引用",copyFileRef:"复制文件引用",findInFile:"在文件内查找",findInFilePlaceholder:"在当前文件中查找…",previousSearchMatch:"上一个匹配项",nextSearchMatch:"下一个匹配项",closeFileSearch:"关闭文件搜索",downloadFile:"下载文件",downloadFailed:"下载失败",uploadFile:"上传文件",uploadFiles:"上传文件",insertLocalFile:"插入本地文件",insertLocalImage:"插入本地图片",layoutMode:"显示模式",layoutModeAuto:"自动",layoutModeNarrow:"窄版",layoutModeWide:"宽版",dropToUpload:"拖放文件以上传",uploading:"上传中…",uploadSuccess:({count:t})=>`已上传 ${t} 个文件`,uploadFailed:"上传失败",binaryPreviewHint:"二进制文件无法预览,请使用上方下载按钮保存到本地",selectedLineHint:({lineLabel:t})=>`已选 ${t} · 点下方「引用」按钮插入`,multiLineHint:"多行引用:先点起始行,再点结束行",loadingImage:"正在加载图片…",imagePreviewHint:"双指捏合或 ⌘/Ctrl + 滚动缩放 · 双击还原",imageLoadFailed:"图片预览加载失败",loadingVideo:"正在加载视频…",videoPreviewHint:"点击播放 · 长按 2× · 可拖动进度条",videoLoadFailed:"视频预览加载失败",videoUnsupported:"当前浏览器不支持该视频格式",videoPlay:"播放",videoPause:"暂停",videoLongPressSpeed:"长按 2× 播放",videoRotate:"顺时针旋转 90°",videoFullscreenEnter:"全屏播放",videoFullscreenExit:"退出全屏",model3dLoading:"正在加载 3D 模型…",model3dExplode:"爆炸展开",model3dExplodeAxis:"展开方向(查看器坐标)",model3dExplodeAmount:"展开程度",model3dHome:"回正并看全",model3dFit:"看全可见零件",model3dFront:"正视图",model3dTop:"俯视图",model3dRight:"右视图",model3dAssemble:"恢复装配",model3dExplodedNotice:"爆炸展示 · 尺寸与引用仍为原始装配坐标",model3dLoadFailed:"3D 模型预览加载失败",model3dTimeout:"3D 模型传输超时,请检查连接后重试。",model3dDimensions:({dims:t})=>`尺寸: ${t}`,model3dHintMouse:"拖拽旋转 / 双指平移 / 捏合或滚轮缩放",model3dHintTouch:"单指旋转 / 双指缩放平移",model3dFullscreenEnter:"全屏查看",model3dFullscreenExit:"退出全屏",model3dBgToLight:"切换为白底",model3dBgToDark:"切换为黑底",model3dRefresh:"重新加载模型",model3dClipToggle:"切面查看",model3dClipPosition:"切面位置",model3dClipFlip:"反转切面方向",model3dFeatureToggle:"特征标注",model3dFeatureStatus:({total:t,positioned:e})=>`特征: ${t} 个 · 已定位 ${e}`,model3dFeatureInsert:"引用",model3dGlossaryToggle:"建模名词说明",model3dPickToggle:"选择零件 / 引用",model3dPickHint:"点选零件后可临时隐藏,或引用所选位置",model3dHidePart:"隐藏零件",model3dShowAllParts:({count:t})=>`显示全部(${t})`,model3dParts:"零件",model3dCloseParts:"关闭零件列表",model3dSearchParts:"查找零件",model3dClearPartSearch:"清空零件搜索",model3dHiddenParts:({count:t})=>`已隐藏 ${t}`,model3dShowNamedPart:({name:t})=>`显示 ${t}`,model3dHideNamedPart:({name:t})=>`隐藏 ${t}`,model3dIsolateNamedPart:({name:t})=>`只看 ${t}`,model3dIsolatePart:"只看此件",model3dShowPart:"显示零件",model3dNoParts:"没有匹配的零件",model3dUndoVisibility:"撤销",model3dClearSelection:"取消选择",model3dAllPartsVisible:"全部可见",model3dInspectHint:"单指旋转 · 双指缩放平移 · 双击局部放大,双击空白看全",model3dUnnamedPart:({index:t})=>`零件 ${t}`,model3dCanvas:"三维模型",model3dMore:"更多模型选项",edaLoading:"正在渲染 KiCad 文件…",reviewTargetChanged:"当前会话已切换,请回到创建这条引用的会话后再插入。",reviewReference:"审阅引用",reviewReferenceHint:"补充意见后插入,不会自动发送。",reviewSnapshot:"选中位置的视图快照",reviewCapturing:"正在截取当前视图…",reviewIncludeImage:"附带截图(临时保存在当前服务器)",reviewCaptureFailed:"截图未成功,仍可插入定位信息。",reviewNote:"你的意见(可选)",reviewNotePlaceholder:"例如:这里太厚了,能否减薄?",reviewDetails:"查看定位信息和引用原文",reviewUploading:"正在准备引用…",reviewAddToDraft:"加入引用草稿",reviewInsert:"插入引用",reviewUploadFailed:"引用准备失败,意见已保留。请重试,或取消附带截图后只插入文字。",edaLoadFailed:"KiCad 预览渲染失败",edaTimeout:"KiCad 预览生成或传输超时,请重试。",edaRefresh:"重新渲染",edaPickHint:"点击原理图或 PCB 上的问题位置,生成电子标注",edaPickedPosition:({x:t,y:e})=>`已选位置 ${t}%, ${e}%`,edaPickedBoardPosition:({x:t,y:e,object:n})=>`板坐标 ${t}, ${e} mm · ${n}`,edaInspecting:"正在读取板坐标和附近对象…",edaNoNearbyObject:"附近无对象",edaInsertAnnotation:"引用电子标注",csvUnnamedColumn:({index:t})=>`第 ${t} 列`,csvSelectedCell:({row:t,column:e})=>`已选第 ${t} 行 · ${e}`,csvPickHint:({rows:t,columns:e})=>`${t} 条记录 · ${e} 列,点击单元格引用`,csvInsertAnnotation:"引用表格标注",csvTablePreview:"表格预览:点击单元格后可引用完整记录",kicadLocalStateNotice:"这是本机界面状态文件,不参与原理图、PCB 或生产审查。",kicadShowRawJson:"查看原始 JSON",kicadProjectPickHint:"点击一项配置后可插入引用",kicadInsertSetting:"引用配置",markdownPreview:"预览",markdownSource:"源码",markdownPreviewHint:"点按行/段落引用,再点一行扩选;拖左侧竖条可连续框选",htmlPreview:"预览",htmlSource:"源码",htmlPreviewHint:"HTML 沙箱 iframe 预览,脚本受限",htmlFullscreenEnter:"全屏预览",htmlFullscreenExit:"退出全屏预览",markdownOutline:"Markdown 目录",markdownOutlineShort:"目录",closeMarkdownOutline:"关闭目录",changedFromPath:({path:t})=>`来自 ${t}`,selectedLineFooter:({lineLabel:t})=>`已选 ${t}`,clearSelection:"清除",allChanges:"全部改动",backToChangeList:"返回目录",allRepositories:"全部仓库",allRepositoriesShort:"全部",repositories:"仓库",gitRepositorySectionTitle:"操作仓库",gitRepositoryLabel:"仓库",gitRepositoryPlaceholder:"选择仓库",gitRepositorySearchPlaceholder:"搜索仓库",gitRepositoryEmpty:"没有可操作的仓库",selectRepositoryForGitActions:"请选择一个仓库后再执行 Git 操作",selectRepositoryForDiff:"选择一个仓库或文件查看 diff",repoNotLoaded:"点击加载",repoChangedCount:({count:t})=>`${t} 个改动`,repoStagedCount:({count:t})=>`${t} 已暂存`,noChanges:"没有改动",noMatchingChanges:"没有匹配的改动",loadingGitChanges:"正在加载 Git 改动…",loadingGitChangesSlow:"仓库较大时可能需要几秒。",refreshingGitChanges:"正在刷新 Git 改动…",gitChangesLoadFailed:"无法加载 Git 改动",retryGitChanges:"重试",insertThisFile:"把这个文件引用插入 Terminal",viewDiff:"查看 diff",diffViewMode:"改动文件展示方式",diffViewModeList:"平铺列表",diffViewModeTree:"目录结构",diffViewModeAi:"AI 导览",changeWalkthroughEmpty:"暂无 AI 导览。生成解释后会在这里展示总览、链路和验证点。",gitInfo:"Git 信息",wrapLongLines:"长行换行",wrapOn:"已换行",wrapOff:"原始",multiRepoScan:"多子仓",multiRepoScanTitle:"扫描当前工作区下的嵌套 Git 仓库。关闭时只看单个仓库,大仓库打开更快。",horizontalScrollHint:"左右滑动查看完整 diff",stageFile:"暂存",stageAll:"全部暂存",unstageFile:"取消暂存",stashFile:"贮藏",stashAll:"全部贮藏",restoreFile:"丢弃",gitQuickActions:"Git 操作",gitUnavailable:"当前目录不是 Git 仓库",branchSectionTitle:"当前分支",currentBranchLabel:"分支",switchBranchPlaceholder:"选择分支",switchBranchSearchPlaceholder:"搜索本地分支",switchNoBranches:"没有本地分支",switchBranch:"切换",noStagedChangesShort:"无暂存",stagedCount:({count:t})=>`已暂存 ${t}`,stagedCountShort:({count:t})=>`已暂存 ${t}`,commitSectionTitle:"提交",commitReadyHint:({count:t})=>`${t} 个文件已准备提交`,commitMessagePlaceholder:"提交信息",commitChanges:"提交",commitNeedsStaged:"请先暂存要提交的改动",commitAhead:"↑ 待推送",commitBehind:"↓ 待拉取",commitSynced:"已同步",recentCommitsTitle:"近期提交",recentCommitsSearchPlaceholder:"搜索提交 hash 或信息",recentCommitsLoadMore:"加载更多提交",recentCommitsEmpty:"暂无提交历史",pushSectionTitle:"同步远端",pushRemoteLabel:"Remote",pushRemotePlaceholder:"origin",pushRemoteSearchPlaceholder:"搜索 Remote",pushNoRemotes:"没有 Remote",pushBranchLabel:"目标分支",pushBranchPlaceholder:({branch:t})=>`${t}`,pushBranchSearchPlaceholder:"搜索分支",pushNoBranches:"没有分支",pushUpstreamBadge:"upstream",pushCurrentBranchBadge:"当前",pushNoUpstream:"当前分支未设置 upstream",pushUpToDate:"与远端同步",pushAheadCount:({count:t})=>`领先远端 ${t} 个提交`,pushBehindCount:({count:t})=>`落后远端 ${t} 个提交`,pushDivergedCount:({ahead:t,behind:e})=>`领先 ${t} / 落后 ${e} 个提交`,pullChanges:"拉取",pushChanges:"推送",gitActionRunning:"执行中…",gitActionFailed:({message:t})=>`Git 操作失败:${t}`,confirmRestoreTitle:"确认丢弃改动",confirmRestoreDescription:({path:t})=>`将丢弃 ${t} 的未暂存改动,此操作不可从 Termdock 恢复。`,confirmRestorePhrase:"丢弃改动",confirmRestorePlaceholder:"输入“丢弃改动”确认",confirmStashAllTitle:"确认贮藏全部改动",confirmStashAllDescription:"会把当前工作区改动(包含未跟踪文件)移入贮藏。",confirmAction:"确认",renderingHtml:"正在渲染 HTML…",footnotes:"脚注",backToFootnote:({index:t})=>`返回脚注 ${t}`,openMermaidDiagram:"打开 Mermaid 图表",mermaidDiagram:"Mermaid 图表",renderingDiagram:"正在渲染图表…",markdownImage:"Markdown 图片",image:"图片",previousImage:"上一张图片",nextImage:"下一张图片",closeImagePreview:"关闭图片预览",emptyFile:"空文件。",insertReference:({reference:t})=>`插入引用:${t}`,copyReference:({reference:t})=>`复制引用:${t}`,byteCount:({count:t})=>`${t} 字节`,previewTruncated:"预览已截断至 1 MB",branchCandidatesLoading:"正在加载分支候选…",includeUncommitted:"包含本地未提交改动",includeUncommittedHint:"查看对比或生成解释时纳入工作区和未跟踪文件的 diff",missingBaseReposSkipped:({repositories:t})=>`未设置基线的仓库会跳过:${t}`,localBranch:"本地",remoteBranch:"远端"},fileTree:{insertRef:"引用",insertRefTitle:"Insert file reference into active terminal",openDirRoot:"进入",openDirRootTitle:"把这个目录作为当前浏览根目录",openInFileBrowser:"在 Finder 中显示",openInFileBrowserTitle:"在系统文件浏览器中打开这个项目",openInFileBrowserFailed:"打开文件浏览器失败",moreDirActions:"更多目录操作",searchFromDir:"从这里搜索",searchFromDirTitle:"只搜索这个目录及其子目录",pinDir:"固定",pinDirTitle:"固定这个目录到当前项目",unpinDir:"已固定",unpinDirTitle:"取消固定这个目录",pinFileTitle:"固定这个文件到当前项目",unpinFileTitle:"取消固定这个文件",pinFile:"固定",unpinFile:"已固定",moreFileActions:"更多文件操作",deleteFile:"删除文件",deleteFileConfirm:({name:t})=>`确认删除“${t}”?此操作无法撤销。`,deleteFileFailed:({message:t})=>`删除文件失败:${t}`,noWorkingDir:"未检测到工作目录。",emptyDir:"空目录。",noMatchingFiles:"没有匹配的文件。",searching:"正在搜索文件…",searchingWithCount:({count:t})=>`搜索中…已找到 ${t} 项`,searchResults:({count:t})=>`${t} 个结果`,searchScope:"搜索范围",searchTruncatedHint:({count:t})=>`降级搜索已扫描大量目录并在找到 ${t} 项后停止。安装 ripgrep 或输入更精确关键词可获得完整结果。`,searchStillRunning:"搜索仍在进行,更多结果会自动出现。",showingSearchResults:({shown:t,total:e})=>`正在展示 ${t}/${e}`,loadMoreSearchResults:({shown:t,total:e})=>`查看更多(${t}/${e})`,contentMatchesCount:({count:t})=>`${t} 个文件命中`,moreMatches:({count:t})=>`还有 ${t} 处匹配`,noContentMatches:"文件内容中没有匹配。",contentSearchNeedsRipgrep:"内容搜索需要 ripgrep(rg),请在服务端安装后再在文件内搜索。",truncatedHint:"仅展示前 1000 项。使用搜索或打开更小的文件夹以获得更好性能。",dropToUploadHere:"上传到这里",symbolicLink:"符号链接",sortByModified:"按最近修改排序",sortByName:"按名称排序",sortedByModified:"已按最近修改排序"},diffViewer:{noFileChanges:"此文件无改动。",noUnstagedChanges:"没有未暂存的改动。",emptyHint:"做一些改动,或从远程拉取。",loading:"正在加载 diff…",insertAllDiff:"把当前 diff 内容作为上下文插入 Terminal",insertFileDiff:"引用这个文件的 diff",insertHunkDiff:"引用这段 diff hunk",insertHunkShort:"引用",insertFileShort:"引用",insertAllShort:"全部",stageHunk:"暂存",stageHunkTitle:"只把这个 hunk 加入暂存区 (git apply --cached)",revertHunk:"撤销",revertHunkTitle:"撤销这个 hunk 的工作区改动(不可恢复)",revertHunkConfirm:"确认撤销?",hunkActionApplying:"应用中…",hunkActionUnavailable:"无法为这个 hunk 构造补丁",hunkActionFailed:({message:t})=>`操作失败:${t}。如改动已变化,请刷新后重试。`,auditExplanation:"更改意义",auditStale:"解释已失效",auditClear:"清除解释",auditGeneratedAt:({time:t})=>`生成于 ${t}`,allDiffLabel:"全部 diff",allChangesLabel:"全部改动",workingTree:"工作区改动",allUnstaged:"所有未暂存改动",binaryOrEmpty:"没有可显示的文本改动。",noFinalNewline:"文件末尾没有换行符",noHunks:"没有 hunk",hunkOutline:"Hunk 列表",expandHunkRail:"显示 hunk 列表",collapseHunkRail:"隐藏 hunk 列表",prevHunk:"上一个 hunk",nextHunk:"下一个 hunk",prevFile:"上一个",nextFile:"下一个",expandFile:"展开文件",collapseFile:"折叠文件",expandAll:"全部展开",collapseAll:"全部折叠",collapseHunk:"折叠 hunk",useBracketKeysHint:"按 [ / ] 在 hunk 之间跳转",unified:"统一",unifiedMode:"统一视图",split:"分屏",splitMode:"左右分屏视图",moreActions:"更多操作",view:"视图",loadingPreviousFile:"正在加载上一个文件…",loadingNextFile:"正在加载下一个文件…",resizeNavigation:"调整 diff 导航宽度",focusPathHint:"点击标注聚焦路径",whitespace:"空白",whitespaceDefault:"默认",whitespaceTrim:"忽略行尾空白",whitespaceIgnore:"忽略所有空白",whitespaceIgnoreBlankLines:"忽略空行",context:"上下文",contextLines:({count:t})=>`${t} 行`,contextAll:"全部"},settings:{title:"设置",font:"字体",render:"渲染",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:"桌面版已是最新版本。",desktopUpdateDownloading:"发现新版本,正在后台下载…",desktopUpdateReady:"桌面版更新已下载,可以重启安装。",desktopUpdateInstalling:"正在重启并安装桌面版更新…",desktopUpdateCheck:"检查桌面版",desktopUpdateCheckAgain:"再次检查",desktopUpdateRestart:"重启并安装",desktopUpdateRestartConfirm:"重启 Termdock 并安装已下载的桌面版更新?终端服务和 tmux 会话不会被停止。",notifications:"通知",notificationsTitle:"通知设置",notificationsHint:"Termdock 在后台时,AI 任务结束后发送系统通知。",notificationsPageHint:"选择哪些 Termdock 事件可以发送系统通知。总开关负责浏览器权限和投递,事件开关决定具体哪些内容提醒你。",notificationsMaster:"系统通知",notificationsMasterHint:"允许 Termdock 在隐藏或作为 PWA 安装运行时发送通知。",notificationsIOSInstallHint:"在 iPhone 或 iPad 上,请先将 Termdock 添加到主屏幕,再开启通知。",notificationsPermission:"权限",notificationsPermissionSystem:"由 macOS 管理",notificationsTest:"发送测试",notificationsTestChecking:"正在等待 macOS 确认投递…",notificationsTestDelivered:"已投递到通知中心;若没有横幅,请检查提醒样式和专注模式。",notificationsTestFailed:"macOS 未投递通知,请在系统设置中允许 Termdock 通知。",notificationsOpenSystemSettings:"打开系统通知设置",notificationsAlertStyle:"提醒方式",notificationsAlertStyleHint:"最终是否横幅弹出仍由浏览器和 Android 系统决定。Termdock 只能请求静默、默认或持续显示等通知选项。",notificationsStyleNormal:"默认",notificationsStyleNormalHint:"允许时声音/震动",notificationsStyleQuiet:"静默",notificationsStyleQuietHint:"仅状态栏,无声音",notificationsStylePersistent:"持续",notificationsStylePersistentHint:"保留到手动关闭",notificationsEvents:"事件",notificationsAiFinished:"AI 任务结束",notificationsAiFinishedHint:"当 Termdock 在后台时,AI agent 停止后发送通知。",notificationsSessionExited:"终端退出",notificationsSessionExitedHint:"终端进程自行结束时发送通知(主动关闭不触发,经 Web Push 投递)。",notificationsFutureHint:"后续可以在这里继续增加更多通知类型,不需要改变顶层设置布局。",notificationsOffSummary:"系统通知已关闭",notificationsAiOnSummary:"AI 任务结束通知已开启",notificationsExitOnSummary:"终端退出通知已开启",notificationsBothOnSummary:"AI 任务结束、终端退出通知已开启",notificationsNoEventsSummary:"暂无开启的通知事件",notificationsDenied:"浏览器通知权限已被阻止,请在站点设置中开启。",notificationsUnsupported:"通知需要安全上下文和 Service Worker 支持。",notificationsTestBody:"通知已开启。后台 AI 任务结束后会提醒你。",shell:"Shell",tmux:"Tmux",auto:"自动",webgl:"WebGL",canvas:"内置",tmuxServer:"Tmux 服务",tmuxUnavailable:"不可用",noTmuxSessions:"服务端没有 tmux 会话。",installTmuxHint:"请在服务端安装 tmux 后启用。",refresh:"刷新",attached:"已连接",restorable:"可恢复",attach:"连接",attaching:"连接中…",destroy:"销毁",sessions:({n:t})=>`${t} 个会话`,windows:({n:t})=>`${t} 个窗口`,keyboardToolbar:"键盘工具栏",aiAgentDetection:"AI 代理检测",signOut:"退出登录",language:"语言",programNamePlaceholder:"程序名(如 claude)",patternPlaceholder:"正则表达式(如 Thinking|Generating)",statusPlaceholder:"状态",addProgram:"添加程序",addPattern:"添加规则",resetDefaults:"恢复默认",invalidRegex:"无效的正则",removeProgram:"移除程序",removeRule:"移除规则",keepLabel:"保持",customColor:"自定义颜色",tabIndicator:"标签指示器样式",toolbarPresets:"工具栏预设",detectionRules:"检测规则",agentHooksHint:"安装 hooks 后,agent 会主动上报状态:回合进行中(绿)、等你授权/回答(黄)、回合完成(对勾),并在等待你输入时推送通知。hooks 全局安装但只在 termdock 的终端里生效。",agentHooksInstall:"安装",agentHooksInstalled:"已安装",agentHooksOutdated:"需更新",agentHooksNeedsApproval:"待授权",agentHooksApprovalHint:"在 Codex 中输入 /hooks,批准 Termdock Hook 后生效",agentHooksNotInstalled:"未安装",agentHooksUninstall:"卸载",agentHooksReinstall:"重新安装",agentHooksDevMode:"开发模式:hooks 指向 TS 源码,需要构建后的版本才能生效",agentHooksTarget:"写入",agentAutoRename:"自动更新会话标题",agentAutoRenameHint:"Agent 完成一轮后,根据近期内容更新标题。默认全部关闭,手工命名的会话不会被覆盖;启用外部插件标题后才会执行其 CLI。",agentAutoRenameToggle:"切换此 Agent 的自动标题",agentAutoRenameShort:"自动标题",agentAutoRenameNamer:"起名 Agent",agentAutoRenameFollow:"跟随当前会话",agentAutoRenameModelsFromCli:"模型由本机 CLI 动态提供",agentAutoRenameRefreshModels:"重新查询 CLI 模型",agentAutoRenameCliDefault:"CLI 默认模型",agentAutoRenameAutomatic:"自动选择",agentAutoRenameNoCli:"未检测到可用于起名的 CLI",agentAutoRenameAdvanced:"高级标题偏好",agentAutoRenamePreference:"补充偏好",agentAutoRenamePreferenceHint:"可选。仅补充你对标题风格或重点的偏好;Termdock 的默认起名规则仍会保留。离开输入框时自动保存。",agentAutoRenamePreferencePlaceholder:"例如:突出用户收益;优先使用动宾结构;避免技术术语",agentAutoRenamePayloadLimit:"用户消息上下文上限(字符)",agentAutoRenamePayloadLimitHint:"保留 prompt-submit 原始 payload 的总字符数,默认 12000,可设置 1000–64000。",agentPlugins:"Agent 插件",agentPluginAdd:"添加插件",agentPluginHint:"从 HTTPS Git 仓库或本地目录安装;请先审查来源。Hooks 和可执行的标题 CLI 均需用户分别启用。",agentPluginCreate:"创建插件",agentPluginDelete:"删除插件",agentPluginInvalid:"插件配置无效",agentPluginCopyAiPrompt:"复制 AI 修复提示",agentPluginCopied:"已复制",agentPluginSourcePlaceholder:"https://github.com/user/agent-plugin 或本地目录",agentPluginInstallPackage:"安装插件",agentPluginAdvancedManifest:"高级:直接粘贴 manifest.json",agentPluginUpdateAvailable:"有更新",agentPluginManualSource:"手动 manifest",agentPluginUpdate:"更新",agentPluginCheck:"检查更新",agentPluginDoctor:"诊断",agentPluginDoctorHint:"显式运行插件模型探测,不会调用标题生成",agentPluginDoctorStatusOk:"标题与模型能力正常",agentPluginDoctorStatusMissing:"未声明 titleNamer",agentPluginDoctorStatusCliDefault:"标题可用,使用 CLI 默认模型",agentPluginDoctorStatusNoModels:"没有可用的模型数据",agentPluginDoctorStatusFailed:"模型探测失败",agentPluginDoctorModels:"个可用模型",agentPluginDoctorAutomatic:"自动选择",agentPluginDoctorCliDefault:"未指定模型时使用 Agent CLI 默认模型",agentAutoRenameInterval:"重新判断间隔",agentAutoRenameMinutes:"分钟",mobileKeyboard:"移动键盘",saving:"保存中…",rulesHint:"配置正则表达式来识别 AI 工具在终端标签中的状态。每条规则可独立设置标签、颜色、图标样式以及输出静默后指示器保留的时长。停止后若你未查看该标签,标签会保留一个黄色待查看提示。",programsHelp:"支持在一个配置中匹配多个程序,用英文逗号分隔。",programLabelResolution:"程序名识别",rawCommandMapping:"原始命令映射",rawCommandMappingHint:"以下规则将原始命令行映射为标签显示名。用户规则优先于内置规则。",genericProgramNames:"通用程序名",genericProgramNamesHint:"触发 ps 深度识别(如 node, python)",wrapperScriptNames:"包装脚本名",wrapperScriptNamesHint:"CLI 包装器,启动其他工具(如 aiden, npx)",shellNamesConfig:"Shell 名称",shellNamesHint:"从标签显示中过滤(如 bash, zsh)",addTag:"+ 添加",customRules:"自定义规则",addRule:"添加规则",localAccess:"本地访问",localAccessHint:"手机信任本地 CA 后,可通过这个局域网地址访问。请先在手机上打开「手机引导」地址下载 CA 证书。",resetAutoName:"恢复自动",onboardingUrl:"手机引导",httpsActive:"HTTPS 已启用",httpsInactive:"HTTPS 未启用",caMissing:"未配置 CA 下载",closeSettings:"关闭设置",desktopTitle:"Termdock 桌面端",desktopStatusLoading:"正在读取 macOS 原生状态…",desktopSwitchService:"切换服务",desktopInstallCli:"安装 / 修复 CLI",desktopCliUpdated:"CLI 状态已更新",desktopOpenDataDirectory:"打开数据目录"},toolbarPresets:{preview:"预览",presets:"预设",label:"标签",new:"新建",reset:"重置",presetLabelPlaceholder:"预设名称",deletePreset:({name:t})=>`删除预设 ${t}`,matchPrograms:"匹配程序",typeEnterHint:"输入后回车",programsPlaceholder:"vim, nvim, /^claude(-code)?$/i …",programsHelp:"纯字符串按大小写不敏感子串匹配。用 /…/flags 包裹则为正则(针对小写程序名测试)。",altSlot:"Alt 修饰键槽",altSlotHint:"在预览中保留一个 Alt 键槽位。",desktopVisibility:"桌面端显示",desktopVisibilityHint:"桌面端只显示该预设的自定义按钮,不显示基础快捷键。",rowLayout:"行布局",rowLayoutHint:"每行按钮数。",addRow:"行",rowN:({n:t})=>`第 ${t} 行`,del:"删",buttons:"按钮",buttonsHint:"点击编辑,使用 ↑↓ 排序。",addButton:"添加按钮",noCustomButtons:"暂无自定义按钮。添加一个来覆盖默认工具栏。",moveUp:"上移",moveDown:"下移",removeRow:({n:t})=>`移除第 ${t} 行`,removeAction:({name:t})=>`移除 ${t}`,labelField:"标签",labelPlaceholder:"按钮上显示的文本",sequence:"序列",sequencePlaceholder:"例如 /undo 或 \\t 或 /||undo",sequenceHint:"双击序列",doubleTap:"双击序列",doubleTapAdd:"+ 添加",doubleTapPlaceholder:"例如 /undo\\r 或 /||undo ||\\r",remove:"移除",noSequence:"无序列",preset:"预设",overCapacityHint:"按钮数超过槽位,多余按钮将使用最后一行的尺寸。"},agentRules:{ruleColors:{green:"绿",yellow:"黄",red:"红",blue:"蓝",purple:"紫",orange:"橙",gray:"灰"}},tab:{session:"会话",new:"新建会话",rename:"重命名",renameHint:"修改标签的显示名称",renamePlaceholder:"留空则恢复默认名称",copyCwd:"复制当前目录",copyCwdHint:"复制当前工作目录",fontSize:"字体大小",fontSizeHint:"仅对这个会话生效",fontSizeReset:"跟随全局",resumeAgent:"恢复 Agent 会话",resumeAgentHint:"用原生 session id 恢复上次对话",resumeAgentAvailable:"有可恢复的 Agent 对话",resumeAgentRecoveredTitle:({agent:t})=>`可继续上次的 ${t} 对话`,resumeAgentRecoveredHint:"Terminal 曾异常中断,已重新创建;可以从上次对话继续。",resumeAgentNow:"恢复",resumeAgentLater:"暂不恢复",resumeAgentSubmitting:"正在提交原生恢复命令…",resumeAgentWaiting:"正在等待 Agent 确认已载入原会话…",resumeAgentSuccess:({agent:t})=>`${t} 会话已恢复`,resumeAgentFailed:"Agent 会话恢复失败,可以重试。",resumeAgentConflict:"该 Agent 会话已在另一个 Terminal 中打开。",resumeAgentBusy:"当前 Agent 回合尚未结束,暂时不能恢复。",resumeAgentTimeout:"Agent 未确认已载入原会话,请查看 Terminal 输出或重试。",tmuxRecoveryTitle:({count:t})=>`检测到 tmux 异常退出,${t} 个 Agent 可恢复`,tmuxRecoveryHint:"Termdock 保留了原生会话 ID。恢复操作会在原标签页中继续之前的对话。",tmuxRecoveryRestoreAll:"恢复全部",tmuxRecoveryRestoring:"正在恢复…",tmuxRecoveryDismiss:"暂不处理",tmuxRecoveryPartial:({restored:t,failed:e})=>`已恢复 ${t} 个,${e} 个需要重试。`,tmuxRecoveryFailed:"恢复失败,请检查终端状态后重试。",tmuxRecoveryDismissFailed:"暂时无法关闭该恢复提示。",copied:"已复制",close:"关闭会话",closeHint:"从列表移除该标签",longPressTip:"提示:按住标签不动约半秒打开操作菜单,按住并拖动可排序。",sessionsTitle:"会话",explorerTitle:"资源管理器",split:"分屏",splitTitle:"添加到分屏工作区",splitNew:"新建会话并加入",splitNewHint:"沿用当前目录和默认会话类型;可连续加入多个会话",splitExisting:"选择已有会话或工作区",splitExistingHint:"会话可组成多个独立工作区;选择另一工作区会将两组合并",splitCurrent:"当前",splitClose:"退出分屏",splitLayout:"分屏布局",splitHorizontal:"左右",splitVertical:"上下",splitGrid:"网格",splitWorkspace:"分屏组",splitWorkspaces:"分屏工作区",splitRename:"重命名分屏组",splitRemovePane:"移出分屏",splitExistingGroups:"已有分屏组",splitAvailableSessions:"可加入的会话",splitOccupied:"已成组",splitUnavailableGrouped:"分组模式下只能分屏同一目录的会话",splitEndedGrouped:"已退出分屏:分组模式不支持跨目录组合",splitNoOtherSessions:"没有可组合的其他会话",sessionCount:({count:t})=>`${t} 个会话`,closeChooserTitle:"销毁 Tmux 会话?",closeChooserDescription:"确认后会终止该会话及其中的所有进程,此操作无法撤销。",destroySession:"销毁会话",confirmDestroySession:"确认销毁",destroySessionHint:"终止 tmux 会话及其中的所有进程。",dragToClose:"拖到此处关闭",releaseToClose:"松手后确认"},agent:{aiRunning:"AI 运行中",needsReview:"需要查看",finishedReview:"AI 已完成 — 需要查看",aiWaiting:"AI 等待中",copyMode:"Copy 模式",jumpToNext:"跳到下一个待处理",jumpToNextRunning:"跳到下一个运行中会话",selectRunningSession:"选择运行中的 Session",runningSessionGestureHint:"轻点循环 · 横向滑动选择 · 长按拖动",currentSession:"当前"},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:t})=>`剩余 ${t}`,updated:({time:t})=>`${t} 更新`,refresh:"刷新",close:"关闭"},errorBoundary:{title:"出现了一些问题",unexpected:"发生意外错误",retry:"重试",copyDetails:"复制错误信息",copied:"已复制",copyFailed:"复制失败"},error:{type:{network:"网络连接错误",session:"会话错误",terminal:"终端错误",auth:"认证错误",validation:"验证错误",unknown:"未知错误"},severity:{low:"提示:",medium:"警告:",high:"错误:",critical:"严重错误:"},suggestion:{networkCheck:"检查网络连接",networkRetry:"尝试重新连接",networkProxy:"检查代理设置",networkWait:"等待网络恢复",sessionRecreate:"重新创建会话",sessionServer:"检查服务器状态",sessionCache:"清理浏览器缓存",terminalRestart:"重启终端",terminalConfig:"检查终端配置",terminalClear:"清除终端输出",authRelogin:"重新登录",authCredentials:"检查凭证",authAdmin:"联系管理员",validationFormat:"检查输入格式",validationParams:"验证参数",validationDocs:"参考文档",unknownReload:"刷新页面",unknownApp:"重启应用",unknownSupport:"联系技术支持"}}},M2=["en","zh"],mr="en",mc="termdock:locale",ss={en:D2,zh:F2};function j2(t){return typeof t=="string"&&M2.includes(t)}function U2(){if(typeof window>"u")return mr;try{const e=window.localStorage.getItem(mc);if(j2(e))return e}catch{}return(window.navigator?.language?.toLowerCase()??"").startsWith("zh")?"zh":mr}const Mg=O.createContext(null);function wc(t,e){const n=e.split(".");let r=t;for(const o of n)if(r&&typeof r=="object"&&o in r)r=r[o];else return;return r}function yc(t,e){return typeof t=="function"?t(e??{}):typeof t!="string"?String(t):e?t.replace(/\{(\w+)\}/g,(n,r)=>Object.prototype.hasOwnProperty.call(e,r)?String(e[r]):n):t}function $2({children:t}){const[e,n]=O.useState(()=>U2()),r=We.useRef(!1);O.useEffect(()=>{typeof window>"u"||sr().then(c=>{if(c?.locale==="zh"||c?.locale==="en"){if(c.locale===e||c.locale==="en"&&e!=="en")return;n(c.locale);try{window.localStorage.setItem(mc,c.locale)}catch{}}}).catch(()=>{})},[]),O.useEffect(()=>{if(!(typeof window>"u")){try{window.localStorage.setItem(mc,e)}catch{}r.current&&(r.current=!1,Et({locale:e}).catch(()=>{})),document.documentElement.lang=e==="zh"?"zh-CN":"en"}},[e]);const o=O.useCallback(c=>{r.current=!0,n(c)},[]),s=ss[e]??ss[mr],i=O.useCallback((c,l)=>{const d=wc(s,c);if(d===void 0){const u=wc(ss[mr],c);return u===void 0?c:yc(u,l)}return yc(d,l)},[s]),a=O.useMemo(()=>({locale:e,setLocale:o,t:i}),[e,o,i]);return p.jsx(Mg.Provider,{value:a,children:t})}function di(){const t=O.useContext(Mg);return t||{locale:mr,setLocale:()=>{},t:(e,n)=>{const r=wc(ss[mr],e);return r===void 0?e:yc(r,n)}}}const H2=String.raw`
13
+ `)}if(a+=i.decode(),l(a),c)throw new Error(c)}function Wk(t){if(!t)return;const e=new URLSearchParams({requestSlotId:t,action:"cancel_io_slot"});fetch(`/api/terminal/fs/cancel-slot?${e}`,{method:"GET",keepalive:!0}).catch(()=>{})}async function Vk(t,e,n="view_file",r){const o=new URLSearchParams({path:t,action:n});r&&o.set("requestSlotId",r);const s=await mg(`/api/terminal/fs/read?${o}`,{signal:e,timeoutMs:In});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 Gk(t,e,n="HEAD",r,o="ref"){const s=new URLSearchParams({path:t,cwd:e,ref:n,action:"git_blob"});o==="index"&&s.set("source","index");const i=await ge(`/api/terminal/fs/git-blob?${s}`,{signal:r},In,"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 Xk(t,e,n="view_file",r){const o=new URLSearchParams({path:t,action:n});r&&o.set("requestSlotId",r);const s=await mg(`/api/terminal/fs/blob?${o}`,{signal:e,timeoutMs:Bg(t)?AA:In});if(!s.ok){const c=await s.json().catch(()=>({error:"Failed to load image preview"}));throw new Error(c.error||"Failed to load image preview")}const i=await s.blob(),a=s.headers.get("Content-Length");return{blob:i,path:t,size:a?Number(a):null,modified:s.headers.get("Last-Modified"),mimeType:s.headers.get("Content-Type")||i.type||li(t)||"application/octet-stream"}}function Il(t,e){try{const n=decodeURIComponent(t.headers.get("X-Termdock-Source-Path")||"");return n.startsWith("/")&&!/[\r\n\0]/.test(n)?n:e}catch{return e}}async function Yk(t,e,n,r="view_file",o){const s=new URLSearchParams({path:t,view:e,action:r});o&&s.set("requestSlotId",o);const i="KiCad preview rendering or transfer timed out.",a=Sl(n,yg,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:Il(c,t),view:e,size:d?Number(d):null,modified:c.headers.get("Last-Modified"),mimeType:c.headers.get("Content-Type")||l.type||"image/svg+xml"}}catch(c){throw a.signal.aborted&&!n?.aborted?new Error(i):c}finally{a.cleanup()}}async function Zk(t,e,n,r,o){const s=new URLSearchParams({path:t,view:e,x:String(n),y:String(r)}),i=await ge(`/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 Jk(t,e,n="view_file",r){const o=new URLSearchParams({path:t,action:n});r&&o.set("requestSlotId",r);const i=Sl(e,wg,"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=kl(t)??"";return{blob:c,path:Il(a,t),size:l?Number(l):null,modified:a.headers.get("Last-Modified"),ext:d,mimeType:a.headers.get("Content-Type")||c.type||Hk[d]||"application/octet-stream"}}finally{i.cleanup()}}function nf(){return typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}async function Qk(t){const e=`/api/terminal/fs/download?path=${encodeURIComponent(t)}`,n=await fetch(e);if(!n.ok){const c=await n.json().catch(()=>({error:"Failed to download file"}));throw new Error(c.error||"Failed to download file")}const r=await n.blob(),o=Fg(n.headers.get("Content-Disposition")||"")??t.split("/").pop()?.split("\\").pop()??"download",s=window.showSaveFilePicker;if(typeof s=="function")try{const l=await(await s({suggestedName:o})).createWritable();await l.write(r),await l.close();return}catch(c){if(c instanceof DOMException&&c.name==="AbortError")return}if(nf()){const c=new File([r],o,{type:r.type||"application/octet-stream"});if(typeof navigator<"u"&&"share"in navigator&&(!navigator.canShare||navigator.canShare({files:[c]})))try{await navigator.share({files:[c]});return}catch(d){if(d instanceof DOMException&&d.name==="AbortError")return}}if(nf()){const c=await uA(r,o);if(c){window.location.assign(c);return}}const i=URL.createObjectURL(r),a=document.createElement("a");a.href=i,a.download=o,a.rel="noopener",a.style.display="none",document.body.appendChild(a),a.click(),setTimeout(()=>{URL.revokeObjectURL(i),a.remove()},4e3)}async function e2(t){const e=await Z(),n=new URLSearchParams({path:t,confirm:"true"}),r=await ge(`/api/terminal/fs/file?${n}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}},In,"File deletion took too long.");if(!r.ok){const o=await r.json().catch(()=>({error:"Failed to delete file"}));throw new Error(o.error||"Failed to delete file")}}async function t2(t,e,n,r){const o=new FormData;for(const u of e)o.append("files",u);const s=`/api/terminal/fs/upload?dir=${encodeURIComponent(t)}`,i=await Z();r?.(0);const a={"X-XSRF-TOKEN":i};let c=o;if(r){const u=new Response(o);a["Content-Type"]=u.headers.get("Content-Type"),c=await u.blob()}const l=await ge(s,{method:"POST",headers:a,body:c,signal:n,onUploadProgress:c instanceof Blob&&r?u=>r(Math.min(99,Math.floor(u/Math.max(1,c.size)*100))):void 0},12e4,"Upload timed out");if(!l.ok){const u=await l.json().catch(()=>({error:"Upload failed"}));throw new Error(u.error||"Upload failed")}const d=await l.json();return r?.(100),d}async function n2(t){const e=await ge("/api/terminal/fs/local-open-availability",{signal:t},In,"Local file browser availability check timed out");return e.ok?e.json():{available:!1}}async function r2(t){const e=await Z(),n=await ge("/api/terminal/fs/open-in-file-browser",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({path:t})},In,"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 Fg(t){if(!t)return null;const e=/(?:^|;)\s*filename\*=\s*(?:UTF-8'')?([^;]+)/i.exec(t);if(e){const r=e[1].trim().replace(/^"|"$/g,"");try{return decodeURIComponent(r)}catch{return r}}const n=/(?:^|;)\s*filename=\s*(?:"([^"]*)"|([^;]+))/i.exec(t);return n?(n[1]??n[2]).trim():null}function o2(t,e){e?.algorithm&&e.algorithm!=="default"&&t.set("algorithm",e.algorithm),e?.whitespace&&e.whitespace!=="default"&&t.set("whitespace",e.whitespace),e?.context==="all"?t.set("context","all"):typeof e?.context=="number"&&t.set("context",String(e.context))}async function s2(t,e,n,r,o=t?"view_diff":"view_all_changes",s,i,a,c){const l=new URLSearchParams;t&&l.set("path",t),n&&l.set("cwd",n),l.set("action",o),o2(l,c),s&&l.set("traceId",s),i&&l.set("interactionId",i);const d=!!t&&o==="view_diff",u=typeof performance<"u"?performance.now():Date.now();Ht("request_start",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:n,action:o,cached:!!e,algorithm:c?.algorithm??"default",whitespace:c?.whitespace??"default",context:c?.context===void 0?"default":String(c.context),timeoutMs:d?or:pt});const f=await ge(`/api/terminal/fs/diff?${l}`,{signal:r},d?or:pt,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 Ht("timeout_or_abort",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,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(Ht("response_headers",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,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 Ht("error",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:n,action:o,status:f.status,message:m.error||"Failed to get diff"}),new Error(m.error||"Failed to get diff")}Ht("response_body_start",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:n,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),contentLength:f.headers.get("Content-Length")});let h;try{h=await xg(f,d?or:pt,d?"Git diff response body is still loading for this file.":"Git diff response body took too long.")}catch(m){throw Ht("response_body_timeout",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,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(h)}catch(m){throw Ht("response_body_parse_error",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:n,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),bytes:h.length,snippet:h.slice(0,160),message:m instanceof Error?m.message:String(m)}),m}return Ht("response_body",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,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 i2(t,e,n="load_git_details",r){const o=new URLSearchParams;t&&o.set("cwd",t),o.set("action",n),r&&o.set("requestSlotId",r);const s=o.toString(),i=await ge(`/api/terminal/fs/git-context${s?`?${s}`:""}`,{signal:e},pt,"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 a2(t={},e){const n=new URLSearchParams;t.workspaceRoot&&n.set("workspaceRoot",t.workspaceRoot),t.repoRoot&&n.set("repoRoot",t.repoRoot);const r=n.toString(),o=await ge(`/api/terminal/fs/change-audit${r?`?${r}`:""}`,{signal:e},pt,"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 c2(t,e){const n=new URLSearchParams;t.cwd&&n.set("cwd",t.cwd),t.repoRoot&&n.set("repoRoot",t.repoRoot),n.set("base",t.base),t.head&&n.set("head",t.head),t.includeUncommitted===!1&&n.set("includeUncommitted","0"),n.set("action","load_branch_diff"),t.requestSlotId&&n.set("requestSlotId",t.requestSlotId);const r=await ge(`/api/terminal/fs/branch-diff?${n}`,{signal:e},or,"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 l2(t,e){const n=new URLSearchParams;t.cwd&&n.set("cwd",t.cwd),t.repoRoot&&n.set("repoRoot",t.repoRoot),n.set("commit",t.commit),n.set("action","load_commit_diff"),t.requestSlotId&&n.set("requestSlotId",t.requestSlotId);const r=await ge(`/api/terminal/fs/commit-diff?${n}`,{signal:e},or,"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 d2(t,e){const n=new URLSearchParams;t.cwd&&n.set("cwd",t.cwd),t.repoRoot&&n.set("repoRoot",t.repoRoot),n.set("limit",String(t.limit)),typeof t.skip=="number"&&n.set("skip",String(t.skip)),t.query&&n.set("query",t.query),n.set("action","load_recent_commits"),t.requestSlotId&&n.set("requestSlotId",t.requestSlotId);const r=await ge(`/api/terminal/fs/git-recent-commits?${n}`,{signal:e},pt,"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 u2(t={},e){const n=new URLSearchParams;t.workspaceRoot&&n.set("workspaceRoot",t.workspaceRoot),t.repoRoot&&n.set("repoRoot",t.repoRoot),t.baseRef&&n.set("baseRef",t.baseRef),t.branchName&&n.set("branchName",t.branchName);const r=n.toString(),o=await ge(`/api/terminal/fs/branch-audit${r?`?${r}`:""}`,{signal:e},pt,"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 f2(t={}){const e=await Z(),n=await ge("/api/terminal/fs/change-audit",{method:"DELETE",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)},pt,"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 h2(t={}){const e=await Z(),n=await ge("/api/terminal/fs/branch-audit",{method:"DELETE",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)},pt,"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 p2(t,e,n){const r=new URLSearchParams;t&&r.set("cwd",t),r.set("action","load_untracked_files"),n&&r.set("requestSlotId",n);const o=r.toString();return(await ge(`/api/terminal/fs/untracked-files${o?`?${o}`:""}`,{signal:e},or,"Untracked file scan took too long. The repository may be busy, on slow storage, or locked by another Git process.")).json()}async function g2(t,e,n={}){const r=new URLSearchParams;t&&r.set("cwd",t),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:e}):await ge(s,{signal:e},n.requestTimeoutMs??pt,"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 m2(t){const e=await Z(),n=await fetch("/api/terminal/fs/git-action",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});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 w2(t){const e=new URLSearchParams;t.cwd&&e.set("cwd",t.cwd),t.action&&e.set("action",t.action),t.jobId&&e.set("jobId",t.jobId);const n=await fetch(`/api/terminal/fs/git-action/status?${e}`);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 y2(t){const e=await Z(),n=await fetch("/api/terminal/fs/apply-hunk",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});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 Ue(t,e){const n=e?.method?.toUpperCase()??"GET",r=new Headers(e?.headers);n!=="GET"&&n!=="HEAD"&&r.set("X-XSRF-TOKEN",await Z()),e?.body&&r.set("Content-Type","application/json");const o=await fetch(`/api/terminal/operations${t}`,{...e,headers:r});if(!o.ok){const s=await o.json().catch(()=>({error:"操作失败"}));throw new Ie(s.error||"操作失败",o.status)}return o.status===204?void 0:await o.json()}function b2(){return Ue("/automations")}function v2(t){return Ue("/automations",{method:"POST",body:JSON.stringify(t)})}function S2(t){return Ue(`/automations/${encodeURIComponent(t)}/run`,{method:"POST"})}function x2(t,e){return Ue(`/automations/${encodeURIComponent(t)}/enabled`,{method:"POST",body:JSON.stringify({enabled:e})})}function E2(t){return Ue(`/automations/${encodeURIComponent(t)}`,{method:"DELETE"})}let Vt=null,rf="";const gc=new Set;Ws(()=>Vt?.refreshPeers(!0));function Rl(){return Ue("/collaboration-groups",{signal:AbortSignal.timeout(1e4)})}function Rn(){const t=Fc(),e=t?.serviceOrigin??window.location?.origin??"",n=`${t?.targetPeerId??""}:${e}`;return(!Vt||n!==rf)&&(Vt?.dispose(),rf=n,Vt=new dA({origin:e,readLocal:Rl,readPeers:async()=>{const r=await Ue("/collaboration-directory",{signal:AbortSignal.timeout(1e4)});let o;const s=await Promise.race([Ke().catch(()=>[]),new Promise(a=>{o=setTimeout(()=>a([]),1e3)})]).finally(()=>clearTimeout(o)),i=new Map((r.services??[]).map(a=>{const c=s.find(d=>a.serviceId&&d.targetPeerId===a.serviceId)??s.find(d=>!a.serviceId&&(d.serviceOrigin||d.url)===a.origin),l=lA({serviceLabel:c?.label||a.label,serviceOrigin:a.origin});return[a.origin,l]}));return{...r,origin:e,services:r.services?.map(a=>({...a,label:i.get(a.origin)??a.label})),sessions:r.sessions.map(a=>({...a,serviceLabel:i.get(a.serviceOrigin??"")??a.serviceLabel}))}},peerProtocol:"v2"}),Vt.subscribe(r=>{for(const o of gc)o(r)})),Vt}function Tl(){Vt?.dispose(),Vt=null}function A2(t){return gc.add(t),()=>{gc.delete(t)}}function k2(){window.dispatchEvent(new Event("termdock:collaboration-enroll")),Rn().refreshPeers(!0)}function C2(){return Rn().load()}async function I2(t){const e=await Rl(),n=t.id?e.groups.find(c=>c.id===t.id):void 0;if(t.id&&!n)throw new Ie("协作组已删除,请刷新列表",404);if(n&&t.expectedUpdatedAt!==void 0&&t.expectedUpdatedAt!==n.updatedAt)throw new Ie("协作组已被修改,请重新打开成员管理后再保存",409);const r=[...new Set(t.sessionIds)];if(!t.name.trim()||r.length<2)throw new Ie("协作组至少需要两个有效会话",400);const o=new Set([...e.sessions.map(c=>c.sessionId),...n?.sessionIds??[]]);if(r.filter(c=>!o.has(c)).some(c=>!lc(c)))throw new Ie("所选会话已变化,请刷新后重新选择;尚未保存任何修改",409);const i={...t,sessionIds:r,...n?{expectedUpdatedAt:t.expectedUpdatedAt??n.updatedAt}:{}},a=await Ue("/collaboration-groups",{method:"POST",body:JSON.stringify(i)});return Rn().invalidate(),a}async function R2(t){if((await Rl()).capabilities?.groupMove!==1)throw new Ie("当前服务需要升级后才能在协作组之间移动成员;原成员关系未修改",409);await Ue("/collaboration-groups/move-member",{method:"POST",body:JSON.stringify(t)}),Rn().invalidate()}function T2(t,e){return Ue(`/collaboration-groups/${encodeURIComponent(t)}/spawn`,{method:"POST",body:JSON.stringify(e)}).then(n=>(Rn().invalidate(),n))}function P2(t,e,n){return Ue(`/collaboration-groups/${encodeURIComponent(t)}/role`,{method:"POST",body:JSON.stringify({sessionId:e,role:n})}).then(r=>(Rn().invalidate(),r))}function N2(t,e){const n=e===void 0?"":`?expectedUpdatedAt=${encodeURIComponent(e)}`;return Ue(`/collaboration-groups/${encodeURIComponent(t)}${n}`,{method:"DELETE"}).then(()=>{Rn().invalidate()})}function L2(t){return Ue(`/collaboration-groups/${encodeURIComponent(t)}/messages`)}function B2(t,e){return Ue(`/collaboration-groups/${encodeURIComponent(t)}/messages`,{method:"POST",body:JSON.stringify(e)})}function _2(t){return Ue(`/session-search?q=${encodeURIComponent(t)}`)}const O2=Object.freeze(Object.defineProperty({__proto__:null,AUTH_UNAUTHORIZED_EVENT:vl,AgentPluginManifestError:Al,EDA_PREVIEW_REQUEST_TIMEOUT_MS:yg,HTML_EXTENSIONS:Dg,MODEL_3D_EXTS:Og,MODEL_PREVIEW_REQUEST_TIMEOUT_MS:wg,TERMINAL_CSRF_REQUEST_TIMEOUT_MS:bg,TERMINAL_HEALTH_REQUEST_TIMEOUT_MS:vg,TERMINAL_SESSION_OPEN_REQUEST_TIMEOUT_MS:Sg,TerminalApiError:Ie,VISIBLE_WAKEUP_PROBE_TIMEOUT_MS:Eg,acknowledgeTerminalOutput:zA,applyDiffHunk:y2,buildHtmlPreviewUrl:$k,buildVideoPreviewUrl:Dk,cancelIoSlot:Wk,checkAgentPluginUpdate:bk,checkTermdockUpdate:vA,checkTerminalHealth:JA,clearBranchAuditRecords:h2,clearChangeAuditRecords:f2,clearSessionInventoryEntries:Pg,closeTerminal:YA,confirmTermdockUpdateRestart:SA,connectTerminalStream:jA,createAgentPlugin:wk,createTerminalSession:MA,deleteAgentPlugin:xk,deleteFile:e2,dismissTmuxRecovery:ok,doctorAgentPlugin:Sk,downloadFile:Qk,fetchQuota:xA,forceKillTerminal:QA,getAgentHooks:hk,getAgentLaunchers:fk,getAgentPlugins:mk,getAppliedTerminalCursor:FA,getBranchAuditRecords:u2,getBranchDiff:c2,getChangeAuditRecords:a2,getCommitDiff:l2,getContextDraft:lk,getDefaultEdaPreviewView:jk,getEdaExtForPath:Cl,getFileDiff:s2,getGitActionStatus:w2,getGitBlobContent:Gk,getGitBundle:g2,getGitContext:i2,getImageMimeTypeForPath:li,getLocalFileBrowserAvailability:n2,getModel3dExtForPath:kl,getProgramDetection:Tk,getRecentCommits:d2,getSessionInventory:Cg,getSettings:sr,getTermdockUpdateState:bA,getTitleNamerCatalog:ck,getTmuxStatus:tk,getToolbarPresetsDoc:ik,getUntrackedFiles:p2,getVideoMimeTypeForPath:_g,inspectEdaPoint:Zk,installAgentHooks:pk,installAgentPluginSource:yk,isHeicImagePath:Bg,isPreviewableEdaPath:Mk,isPreviewableHtmlPath:Uk,isPreviewableImagePath:Bk,isPreviewableModel3dPath:Fk,isPreviewableVideoPath:Ok,killTmuxSession:nk,listAgentAutomations:b2,listAgentResumeHistory:Ak,listCollaborationGroups:C2,listCollaborationMessages:L2,listDirectory:qk,listTmuxSessions:ek,loginWithPassword:Lg,logout:uk,moveCollaborationMember:R2,openInFileBrowser:r2,openSessionInventoryEntry:Ig,parseFilenameFromContentDisposition:Fg,prepareAgentResumeHistory:kk,probeTerminalConnection:$A,readEdaPreviewBlob:Yk,readFileContent:Vk,readImagePreviewBlob:Xk,readModel3dBlob:Jk,readPreviewSourcePath:Il,reconnectTerminalConnectionNow:HA,refreshQuota:EA,removeAgentAutomation:E2,removeAgentResumeHistory:Ck,removeCollaborationGroup:N2,removeSessionInventoryEntry:Tg,reorderSessionInventoryEntries:Rg,replaceProgramDetection:Pk,replaceProgramRules:Ik,replaceToolbarPresetsDoc:ak,resetCollaborationDirectory:Tl,resetCsrfTokenCache:xl,resetProgramDetection:Nk,resetProgramRules:Rk,resizeTerminal:GA,restartTerminalSession:ZA,restoreAllTmuxAgentSessions:rk,resumeAgentSession:Ek,retryCollaborationPeers:k2,runAgentAutomation:S2,runGitAction:m2,saveAgentAutomation:v2,saveCollaborationGroup:I2,searchFilesStream:Kk,searchTerminalSessions:_2,sendAgentReviewAck:pc,sendCollaborationMessage:B2,sendTerminalFlowControlState:VA,sendTerminalFocusState:KA,sendTerminalInput:UA,sendTerminalViewingState:WA,sendTmuxAction:XA,setAgentAutomationEnabled:x2,setCollaborationMemberRole:P2,setTerminalOutputSubscription:kg,setTerminalSnapshotCursor:DA,spawnCollaborationAgent:T2,subscribeCollaborationGroups:A2,suspendTerminalConnectionReconnects:qA,uninstallAgentHooks:gk,updateAgentPlugin:vk,updateContextDraft:dk,updateSessionInventoryEntry:os,updateSettings:Et,uploadFiles:t2,watchFileSystem:zk},Symbol.toStringTag,{value:"Module"})),D2={app:{name:"Termdock"},android:{device:"Device",selectDevice:"Select device",noDevices:"No device found",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…",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",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.",quality:"Quality",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:t})=>`Please wait ${t}s`,submit:"Sign in",invalidPassword:"Incorrect password",failed:"Login failed"},sidebar:{sessions:"Sessions",noSessions:"No open sessions yet.",noMatchingSessions:"No matching sessions.",toggleSearch:"Toggle search",settings:"Settings",moreActions:"More actions",subscriptionQuota:"Subscription quota",pinSidebar:"Keep sidebar open",unpinSidebar:"Stop keeping sidebar open",runningSessionButton:"Running sessions button",runningSessionButtonHint:"Tap to cycle, swipe sideways to select, hold to drag",updateAvailable:({version:t})=>`Termdock ${t} is available`,updateInstalling:"Installing in the background without interrupting this service.",updateReady:"The update is installed and ready for a confirmed restart.",updateRestart:"Restart and finish update",updateRestartConfirm:({version:t})=>`Restart Termdock and switch to ${t}? This page will reconnect briefly and sessions will stay open.`,updateRestarting:"Restarting; this page will reconnect automatically…",updateFailed:"Automatic installation failed. This reminder will remain.",updateRetry:"Try again",filterSessions:"Filter sessions",clearSearch:"Clear search",groupByFolder:"Group by folder",groupByFolderTitle:"Collapse sessions into groups by working directory. Mutually exclusive with drag sorting.",ungrouped:"Other",needsAttention:"Needs attention",waitingForYou:"Waiting for you",completedUnread:"Completed · unread",closeSession:({name:t})=>`Close ${t}`,newShell:"Shell",newTmux:"Tmux",newTmuxDisabled:"tmux not available on server",confirmNewShell:"Create Shell?",confirmNewTmux:"Create Tmux?",newSession:"New terminal",newSessionWithAgent:({agent:t})=>`New ${t}`,moreLaunchOptions:"More launch options",recoverableSessions:"Recoverable sessions",refreshRecoverableSessions:"Refresh recoverable sessions",restoreRecoverableSession:({name:t})=>`Restore ${t}`,restoringRecoverableSession:"Restoring…",restore:"Restore",newSessionAdvanced:"Quick-launch agent",newSessionComposerTitle:"Start a session",newSessionHint:"Choose how and where it starts",launchSessionWith:({name:t})=>`Start ${t}`,setNewSessionDefault:({name:t})=>`Set ${t} as default`,currentNewSessionDefault:({name:t})=>`${t} is the current default`,currentDefaultAgent:({name:t})=>`Current default: ${t}`,defaultAgent:"Default",makeDefault:"Make default",sessionMode:"Run mode",tmuxKeepsRunning:"Keeps running after disconnect",resumeHistory:"Recent conversations",resumeHistoryCount:({n:t})=>`${t} saved`,resumeHistoryLoading:"Loading recent Agent conversations…",resumeHistoryAction:({title:t})=>`Resume ${t}`,resumeHistoryRemove:({title:t})=>`Remove ${t} from recent conversations`,resumeHistoryLoadFailed:"Could not load recent Agent conversations.",resumeHistoryFailed:"Could not prepare this Agent conversation for resume.",resumeHistoryRemoveFailed:"Could not remove the conversation from history.",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",insertCurrentFolder:"Insert current folder reference",insertCurrentFolderShort:"Insert",pinnedFolders:"Pinned",unpinFolder:({name:t})=>`Unpin ${t}`,fileWatchUnavailable:({message:t})=>`File watcher unavailable: ${t}. Click to refresh manually.`,browsingOutsideProject:"Browsing outside current project",browsingOutsideProjectHint:"Git and Changes still use the current project. File references from here are inserted as external paths.",toggleSearch:"Toggle search",refreshGit:"Refresh Git status",gitLastUpdated:({time:t})=>`Last updated: ${t}`,close:"Close",filterChanges:"Filter changes or files",searchPlaceholderContent:"Search text in files…",searchModeName:"File",searchModeContent:"Content",clearSearch:"Clear search",searchScope:"Scope",searchScopePlaceholder:"Relative folder or absolute path",resetSearchScope:"Reset to current folder",searchOptions:"Search options",searchExclude:"Exclude",searchExcludePlaceholder:"dist/**, *.lock",clearSearchExclude:"Clear exclusions",contentSearchOptions:"Content search options",matchCase:"Match case",matchWholeWord:"Whole word",useRegex:"Regex",insertGitContext:"Insert current Git context into terminal",copyGitContext:"Copy Git context",insertChangeAuditPrompt:"Explain changes",insertChangeAuditPromptTitle:"Insert the change audit prompt into the current session",changeAuditShort:"Explain changes",changeAuditLoading:"Loading hunk explanations…",changeAuditLoaded:({count:t})=>`${t} hunk explanation${t===1?"":"s"} loaded`,changeAuditLoadedAt:({time:t})=>`Generated ${t}`,changeAuditRegenerate:"Regenerate",changeAuditRefreshStale:"Fill stale",changeAuditRefreshStaleTitle:"Insert a prompt to refresh stale hunk explanations",clearChangeAudit:"Clear",clearChangeAuditTitle:"Clear hunk explanations for the current repository",changeAuditClearFailed:({message:t})=>`Failed to clear hunk explanations: ${t}`,changeAuditScopeAll:"All repositories",changeAuditScopeLabel:"Explain scope",branchAuditTitle:"Branch explanation",branchAuditShort:"Explain branch changes",branchAuditBaseLabel:"Base branch",branchAuditBasePlaceholder:"Base branch, e.g. master",branchAuditBaseSearchPlaceholder:"Search base branch",branchAuditBaseEmpty:"No branch options. Type a branch name directly.",branchAuditGenerate:"Generate",branchAuditRegenerate:"Regenerate",branchAuditGenerateTitle:"Insert a prompt to explain this branch against the base branch",branchAuditViewDiff:"View diff",branchAuditViewDiffTitle:"View target branch changes against the base branch",branchAuditDiffLoading:"Loading branch diff...",branchAuditDiffEmpty:"No changes between this branch and the base branch.",branchAuditMissingBase:({repo:t})=>`${t} has no base branch set`,branchAuditRefreshDiff:"Refresh diff",branchAuditRefreshStale:"Fill stale",branchAuditRefreshStaleTitle:"Insert a prompt to refresh stale branch explanations",branchAuditClearTitle:"Clear current branch explanation",branchAuditClearFailed:({message:t})=>`Failed to clear branch explanation: ${t}`,branchAuditCommitCount:({count:t})=>`${t} commit${t===1?"":"s"}`,branchAuditFileCount:({count:t})=>`${t} file${t===1?"":"s"}`,branchAuditTruncated:"diff truncated",branchAuditCurrent:"Saved explanation",branchAuditStale:"Explanation is stale",branchAuditEmpty:"No branch explanation yet. Generate one to persist it here for later review.",branchAuditView:"View explanations",branchAuditSaved:({count:t})=>`${t} hunk explanation${t===1?"":"s"} saved`,branchAuditGeneratedAt:({time:t})=>`Generated ${t}`,insertPreset:({label:t})=>`Insert: ${t}`,tabChanges:"Changes",tabGit:"Git",tabFiles:"Files",tabAndroid:"Device",showAndroidTab:"Show device 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",contextDraftInsertFailed:"Terminal disconnected — draft kept",contextDraftCharacterCount:({count:t})=>`${t} chars`,selectFilePrompt:"Select a file to preview its contents",backToFileList:"Back to file list",backToPreviousPreview:"Back to source document",insertLineRef:({lineLabel:t})=>`Insert ${t}`,insertFileRef:"Insert",copyFileRef:"Copy file reference",findInFile:"Find in file",findInFilePlaceholder:"Find in this file…",previousSearchMatch:"Previous match",nextSearchMatch:"Next match",closeFileSearch:"Close file search",downloadFile:"Download file",downloadFailed:"Download failed",uploadFile:"Upload file",uploadFiles:"Upload files",insertLocalFile:"Insert local file",insertLocalImage:"Insert local image",layoutMode:"Display mode",layoutModeAuto:"Auto",layoutModeNarrow:"Narrow",layoutModeWide:"Wide",dropToUpload:"Drop files to upload",uploading:"Uploading…",uploadSuccess:({count:t})=>`${t} file${t===1?"":"s"} uploaded`,uploadFailed:"Upload failed",binaryPreviewHint:"Binary files cannot be previewed. Use the download button above to save it.",selectedLineHint:({lineLabel:t})=>`Selected ${t} · tap "Insert" below to add to terminal`,multiLineHint:"Multi-line select: tap start line, then end line",loadingImage:"Loading image…",imagePreviewHint:"Pinch or ⌘/Ctrl + scroll to zoom · double-tap to reset",imageLoadFailed:"Failed to load image preview",loadingVideo:"Loading video…",videoPreviewHint:"Click to play · hold for 2× · drag to seek",videoLoadFailed:"Failed to load video preview",videoUnsupported:"Your browser does not support this video format",videoPlay:"Play",videoPause:"Pause",videoLongPressSpeed:"Playing at 2×",videoRotate:"Rotate 90° clockwise",videoFullscreenEnter:"Enter fullscreen",videoFullscreenExit:"Exit fullscreen",model3dLoading:"Loading 3D model…",model3dExplode:"Exploded view",model3dExplodeAxis:"Explosion axis (viewer coordinates)",model3dExplodeAmount:"Explosion amount",model3dHome:"Reset view",model3dFit:"Fit visible parts",model3dFront:"Front view",model3dTop:"Top view",model3dRight:"Right view",model3dAssemble:"Restore assembly",model3dExplodedNotice:"Exploded · dimensions and references remain assembled",model3dLoadFailed:"Failed to load 3D model preview",model3dTimeout:"3D model transfer timed out. Check your connection and retry.",model3dDimensions:({dims:t})=>`Dimensions: ${t}`,model3dHintMouse:"Drag to orbit · two-finger pan · pinch or scroll to zoom",model3dHintTouch:"One finger to orbit · two fingers to zoom & pan",model3dFullscreenEnter:"Fullscreen",model3dFullscreenExit:"Exit fullscreen",model3dBgToLight:"Light background",model3dBgToDark:"Dark background",model3dRefresh:"Reload model",model3dClipToggle:"Section view",model3dClipPosition:"Section position",model3dClipFlip:"Flip section direction",model3dFeatureToggle:"Features",model3dFeatureStatus:({total:t,positioned:e})=>`Features: ${t} · positioned ${e}`,model3dFeatureInsert:"Insert reference",model3dGlossaryToggle:"Modeling terms",model3dPickToggle:"Select part / reference",model3dPickHint:"Select a part to hide it or insert a point reference",model3dHidePart:"Hide part",model3dShowAllParts:({count:t})=>`Show all (${t})`,model3dParts:"Parts",model3dCloseParts:"Close parts",model3dSearchParts:"Find a part",model3dClearPartSearch:"Clear part search",model3dHiddenParts:({count:t})=>`${t} hidden`,model3dShowNamedPart:({name:t})=>`Show ${t}`,model3dHideNamedPart:({name:t})=>`Hide ${t}`,model3dIsolateNamedPart:({name:t})=>`Only show ${t}`,model3dIsolatePart:"Only this part",model3dShowPart:"Show part",model3dNoParts:"No matching parts",model3dUndoVisibility:"Undo",model3dClearSelection:"Clear selection",model3dAllPartsVisible:"All parts visible",model3dInspectHint:"Drag to orbit · double-tap to zoom · double-tap empty space to fit",model3dUnnamedPart:({index:t})=>`Part ${t}`,model3dCanvas:"3D model",model3dMore:"More model options",edaLoading:"Rendering KiCad file…",reviewTargetChanged:"The active session changed. Return to the original session before inserting this reference.",reviewReference:"Review reference",reviewReferenceHint:"Add context, then insert. Nothing is sent automatically.",reviewSnapshot:"Snapshot of the selected viewer",reviewCapturing:"Capturing this view…",reviewIncludeImage:"Include snapshot (stored temporarily on this server)",reviewCaptureFailed:"Snapshot unavailable; location can still be inserted.",reviewNote:"Your comment (optional)",reviewNotePlaceholder:"What should change here?",reviewDetails:"View location and quoted content",reviewUploading:"Preparing reference…",reviewAddToDraft:"Add to context draft",reviewInsert:"Insert reference",reviewUploadFailed:"Could not prepare the reference. Your comment is kept. Retry, or uncheck the snapshot to insert text only.",edaLoadFailed:"Failed to render KiCad preview",edaTimeout:"KiCad preview rendering or transfer timed out. Please retry.",edaRefresh:"Render again",edaPickHint:"Click a schematic or PCB location to create an electronics annotation",edaPickedPosition:({x:t,y:e})=>`Selected ${t}%, ${e}%`,edaPickedBoardPosition:({x:t,y:e,object:n})=>`Board ${t}, ${e} mm · ${n}`,edaInspecting:"Reading board coordinates and nearby object…",edaNoNearbyObject:"No nearby object",edaInsertAnnotation:"Insert electronics annotation",csvUnnamedColumn:({index:t})=>`Column ${t}`,csvSelectedCell:({row:t,column:e})=>`Row ${t} · ${e}`,csvPickHint:({rows:t,columns:e})=>`${t} records · ${e} columns; click a cell to reference`,csvInsertAnnotation:"Insert table annotation",csvTablePreview:"Table preview: select a cell to reference its record",kicadLocalStateNotice:"This is local UI state and is not part of schematic, PCB, or manufacturing review.",kicadShowRawJson:"Show raw JSON",kicadProjectPickHint:"Select a setting to insert a reference",kicadInsertSetting:"Insert setting",markdownPreview:"Preview",markdownSource:"Source",markdownPreviewHint:"Tap a line/section to reference, tap another to extend; drag the left rail to select a range",htmlPreview:"Preview",htmlSource:"Source",htmlPreviewHint:"Sandboxed iframe preview; scripts run sandboxed",htmlFullscreenEnter:"Enter fullscreen preview",htmlFullscreenExit:"Exit fullscreen preview",markdownOutline:"Markdown outline",markdownOutlineShort:"Outline",closeMarkdownOutline:"Close outline",changedFromPath:({path:t})=>`from ${t}`,selectedLineFooter:({lineLabel:t})=>`Selected ${t}`,clearSelection:"Clear",allChanges:"All changes",backToChangeList:"Back to list",allRepositories:"All repositories",allRepositoriesShort:"All",repositories:"Repositories",gitRepositorySectionTitle:"Repository",gitRepositoryLabel:"Repository",gitRepositoryPlaceholder:"Select repository",gitRepositorySearchPlaceholder:"Search repositories",gitRepositoryEmpty:"No available repositories",selectRepositoryForGitActions:"Select a repository before running Git actions",selectRepositoryForDiff:"Select a repository or file to view diff",repoNotLoaded:"Tap to load",repoChangedCount:({count:t})=>`${t} change${t===1?"":"s"}`,repoStagedCount:({count:t})=>`${t} staged`,noChanges:"No changes",noMatchingChanges:"No matching changes",loadingGitChanges:"Loading Git changes…",loadingGitChangesSlow:"Large repositories can take a few seconds.",refreshingGitChanges:"Refreshing Git changes…",gitChangesLoadFailed:"Unable to load Git changes",retryGitChanges:"Retry",insertThisFile:"Insert this file reference into terminal",viewDiff:"View diff",diffViewMode:"Change file display mode",diffViewModeList:"Flat list",diffViewModeTree:"Folder tree",diffViewModeAi:"AI walkthrough",changeWalkthroughEmpty:"No AI walkthrough yet. Generate explanations to show the overview, flow, and checks here.",gitInfo:"Git context",wrapLongLines:"Wrap long lines",wrapOn:"Wrapped",wrapOff:"Raw",multiRepoScan:"Sub-repos",multiRepoScanTitle:"Scan this workspace for nested Git repositories. Off keeps a single-repo view, which opens much faster on large repos.",horizontalScrollHint:"Swipe left/right to see the full diff",stageFile:"Stage",stageAll:"Stage all",unstageFile:"Unstage",stashFile:"Stash",stashAll:"Stash all",restoreFile:"Restore",gitQuickActions:"Git Actions",gitUnavailable:"Current directory is not a Git repository",branchSectionTitle:"Current branch",currentBranchLabel:"Branch",switchBranchPlaceholder:"Select branch",switchBranchSearchPlaceholder:"Search local branch",switchNoBranches:"No local branches",switchBranch:"Switch",noStagedChangesShort:"no staged",stagedCount:({count:t})=>`${t} staged`,stagedCountShort:({count:t})=>`${t} staged`,commitSectionTitle:"Commit",commitReadyHint:({count:t})=>`${t} file${t===1?"":"s"} ready`,commitMessagePlaceholder:"Commit message",commitChanges:"Commit",commitNeedsStaged:"Stage changes before committing",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:t})=>`${t}`,pushBranchSearchPlaceholder:"Search branch",pushNoBranches:"No branches",pushUpstreamBadge:"upstream",pushCurrentBranchBadge:"current",pushNoUpstream:"No upstream configured",pushUpToDate:"Up to date with remote",pushAheadCount:({count:t})=>`${t} commit${t===1?"":"s"} to push`,pushBehindCount:({count:t})=>`${t} commit${t===1?"":"s"} to pull`,pushDivergedCount:({ahead:t,behind:e})=>`${t} ahead / ${e} behind`,pullChanges:"Pull",pushChanges:"Push",gitActionRunning:"Running…",gitActionFailed:({message:t})=>`Git action failed: ${t}`,confirmRestoreTitle:"Discard changes?",confirmRestoreDescription:({path:t})=>`This will discard unstaged changes in ${t}. Termdock cannot recover them.`,confirmRestorePhrase:"discard changes",confirmRestorePlaceholder:"Type “discard changes” to confirm",confirmStashAllTitle:"Stash all changes?",confirmStashAllDescription:"This moves current working tree changes, including untracked files, into a stash.",confirmAction:"Confirm",renderingHtml:"Rendering HTML…",footnotes:"Footnotes",backToFootnote:({index:t})=>`Back to footnote ${t}`,openMermaidDiagram:"Open Mermaid diagram",mermaidDiagram:"Mermaid diagram",renderingDiagram:"Rendering diagram…",markdownImage:"Markdown image",image:"Image",previousImage:"Previous image",nextImage:"Next image",closeImagePreview:"Close image preview",emptyFile:"Empty file.",insertReference:({reference:t})=>`Insert reference: ${t}`,copyReference:({reference:t})=>`Copy reference: ${t}`,byteCount:({count:t})=>`${t} bytes`,previewTruncated:"Preview truncated to 1 MB",branchCandidatesLoading:"Loading branch candidates…",includeUncommitted:"Include local uncommitted changes",includeUncommittedHint:"Include working tree and untracked diffs when viewing or explaining changes",missingBaseReposSkipped:({repositories:t})=>`Repositories without a base branch will be skipped: ${t}`,localBranch:"local",remoteBranch:"remote"},fileTree:{insertRef:"Insert",insertRefTitle:"Insert file reference into active terminal",openDirRoot:"Open",openDirRootTitle:"Use this folder as the current browsing root",openInFileBrowser:"Reveal in Finder",openInFileBrowserTitle:"Open this item in the system file browser",openInFileBrowserFailed:"Failed to open file browser",moreDirActions:"More folder actions",searchFromDir:"Search from here",searchFromDirTitle:"Search only this folder and its descendants",pinDir:"Pin",pinDirTitle:"Pin this folder to the current project",unpinDir:"Pinned",unpinDirTitle:"Unpin this folder",pinFileTitle:"Pin this file to the current project",unpinFileTitle:"Unpin this file",pinFile:"Pin",unpinFile:"Unpin",moreFileActions:"More file actions",deleteFile:"Delete file",deleteFileConfirm:({name:t})=>`Delete “${t}”? This action cannot be undone.`,deleteFileFailed:({message:t})=>`Failed to delete file: ${t}`,noWorkingDir:"No working directory detected.",emptyDir:"Empty directory.",noMatchingFiles:"No matching files.",searching:"Searching files…",searchingWithCount:({count:t})=>`Searching… ${t} found`,searchResults:({count:t})=>`${t} results`,searchScope:"Search scope",searchTruncatedHint:({count:t})=>`Fallback search scanned a large directory and stopped after ${t} matches. Install ripgrep or refine the query for complete results.`,searchStillRunning:"Search is still running. More results will appear automatically.",showingSearchResults:({shown:t,total:e})=>`Showing ${t} of ${e}`,loadMoreSearchResults:({shown:t,total:e})=>`Show more (${t}/${e})`,contentMatchesCount:({count:t})=>`${t} file${t===1?"":"s"} with matches`,moreMatches:({count:t})=>`+${t} more match${t===1?"":"es"}`,noContentMatches:"No matches found in file contents.",contentSearchNeedsRipgrep:"Content search requires ripgrep (rg). Install it on the server to search inside files.",truncatedHint:"Showing first 1000 entries. Use search or open a smaller folder for better performance.",dropToUploadHere:"Upload here",symbolicLink:"Symbolic link",sortByModified:"Sort by recent changes",sortByName:"Sort by name",sortedByModified:"Sorted by recent changes"},diffViewer:{noFileChanges:"No changes in this file.",noUnstagedChanges:"No unstaged changes.",emptyHint:"Make some changes, or pull from a remote.",loading:"Loading diff…",insertAllDiff:"Insert current diff as context",insertFileDiff:"Insert this file's diff",insertHunkDiff:"Insert this hunk",insertHunkShort:"Insert",insertFileShort:"Insert",insertAllShort:"Insert all",stageHunk:"Stage",stageHunkTitle:"Stage only this hunk (git apply --cached)",revertHunk:"Revert",revertHunkTitle:"Revert this hunk in the worktree (cannot be undone)",revertHunkConfirm:"Confirm revert?",hunkActionApplying:"Applying…",hunkActionUnavailable:"Cannot build a patch for this hunk",hunkActionFailed:({message:t})=>`Failed: ${t}. If the changes moved on, refresh and retry.`,auditExplanation:"Change meaning",auditStale:"Explanation stale",auditClear:"Clear explanation",auditGeneratedAt:({time:t})=>`Generated ${t}`,allDiffLabel:"all changes",allChangesLabel:"all changes",workingTree:"Working tree changes",allUnstaged:"All unstaged changes",binaryOrEmpty:"No textual changes to display.",noFinalNewline:"No newline at end of file",noHunks:"No hunks",hunkOutline:"Hunks",expandHunkRail:"Show hunk list",collapseHunkRail:"Hide hunk list",prevHunk:"Previous hunk",nextHunk:"Next hunk",prevFile:"Previous",nextFile:"Next",expandFile:"Expand file",collapseFile:"Collapse file",expandAll:"Expand all",collapseAll:"Collapse all",collapseHunk:"Collapse hunk",useBracketKeysHint:"Press [ / ] to jump between hunks",unified:"Unified",unifiedMode:"Unified view",split:"Split",splitMode:"Side-by-side view",moreActions:"More actions",view:"View",loadingPreviousFile:"Loading previous file…",loadingNextFile:"Loading next file…",resizeNavigation:"Resize diff navigation",focusPathHint:"Select a label to focus its path",whitespace:"Whitespace",whitespaceDefault:"Default",whitespaceTrim:"Ignore trailing",whitespaceIgnore:"Ignore all",whitespaceIgnoreBlankLines:"Ignore blank lines",context:"Context",contextLines:({count:t})=>`${t} lines`,contextAll:"All"},settings:{title:"Settings",font:"Font",render:"Render",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.",desktopUpdateDownloading:"A new version is downloading in the background…",desktopUpdateReady:"The desktop update is downloaded and ready to install.",desktopUpdateInstalling:"Restarting to install the desktop update…",desktopUpdateCheck:"Check desktop app",desktopUpdateCheckAgain:"Check again",desktopUpdateRestart:"Restart and install",desktopUpdateRestartConfirm:"Restart Termdock and install the downloaded desktop update? The terminal service and tmux sessions will remain running.",notifications:"Notify",notificationsTitle:"Notification settings",notificationsHint:"Notify when an AI task finishes while Termdock is hidden.",notificationsPageHint:"Choose which Termdock events can send system notifications. The master switch controls browser permission and delivery; event switches decide what should notify you.",notificationsMaster:"System notifications",notificationsMasterHint:"Allow Termdock to send notifications when it is hidden or running as an installed PWA.",notificationsIOSInstallHint:"On iPhone and iPad, install Termdock to the Home Screen before enabling notifications.",notificationsPermission:"Permission",notificationsPermissionSystem:"Managed by macOS",notificationsTest:"Send test",notificationsTestChecking:"Waiting for macOS to confirm delivery…",notificationsTestDelivered:"Delivered to Notification Center. If no banner appeared, check the alert style and Focus.",notificationsTestFailed:"macOS did not deliver the notification. Allow Termdock in System Settings.",notificationsOpenSystemSettings:"Open system notification settings",notificationsAlertStyle:"Alert style",notificationsAlertStyleHint:"Browsers and Android still decide the final heads-up behavior. Termdock can only request quiet/default/sticky notification options.",notificationsStyleNormal:"Default",notificationsStyleNormalHint:"Sound/vibration if allowed",notificationsStyleQuiet:"Quiet",notificationsStyleQuietHint:"Status tray, no sound",notificationsStylePersistent:"Sticky",notificationsStylePersistentHint:"Stay until dismissed",notificationsEvents:"Events",notificationsAiFinished:"AI task finished",notificationsAiFinishedHint:"Notify when an AI agent stops while Termdock is in the background.",notificationsSessionExited:"Terminal exited",notificationsSessionExitedHint:"Notify when a terminal process exits on its own (closing it yourself does not trigger; delivered via Web Push).",notificationsFutureHint:"More notification types can be added here later without changing the top-level settings layout.",notificationsOffSummary:"System notifications disabled",notificationsAiOnSummary:"AI task finished enabled",notificationsExitOnSummary:"Terminal exit enabled",notificationsBothOnSummary:"AI task finished and terminal exit enabled",notificationsNoEventsSummary:"No notification events enabled",notificationsDenied:"Browser notification permission is blocked. Enable it in site settings.",notificationsUnsupported:"Notifications require a secure context and service worker support.",notificationsTestBody:"Notifications are enabled. You will be notified when an AI task finishes in the background.",shell:"Shell",tmux:"Tmux",auto:"Auto",webgl:"WebGL",canvas:"Built-in",tmuxServer:"Tmux server",tmuxUnavailable:"unavailable",noTmuxSessions:"No tmux sessions on the server.",installTmuxHint:"Install tmux on the server to enable.",refresh:"Refresh",attached:"Attached",restorable:"Restorable",attach:"Attach",attaching:"Attaching…",destroy:"Destroy",sessions:({n:t})=>`${t} session${t===1?"":"s"}`,windows:({n:t})=>`${t} window${t===1?"":"s"}`,keyboardToolbar:"Keyboard toolbar",aiAgentDetection:"AI agent detection",signOut:"Sign out",language:"Language",programNamePlaceholder:"Program name (e.g. claude)",patternPlaceholder:"Regex pattern (e.g. Thinking|Generating)",statusPlaceholder:"Status",addProgram:"Add program",addPattern:"Add pattern",resetDefaults:"Reset defaults",invalidRegex:"Invalid regex",removeProgram:"Remove program",removeRule:"Remove rule",keepLabel:"keep",customColor:"Custom color",tabIndicator:"Tab indicator style",toolbarPresets:"Toolbar presets",detectionRules:"Detection rules",agentHooksHint:"With hooks installed, agents report their own status: working (green), waiting for you (amber), turn done (check) — and you get a notification the moment one needs your input. Hooks install globally but only fire inside termdock terminals.",agentHooksInstall:"Install",agentHooksInstalled:"Installed",agentHooksOutdated:"Outdated",agentHooksNeedsApproval:"Needs approval",agentHooksApprovalHint:"Run /hooks in Codex and approve the Termdock hooks",agentHooksNotInstalled:"Not installed",agentHooksUninstall:"Uninstall",agentHooksReinstall:"Reinstall",agentHooksDevMode:"Dev mode: hooks point at TS sources and need a built install to fire",agentHooksTarget:"writes to",agentAutoRename:"Automatic session titles",agentAutoRenameHint:"Update the title from recent work when an agent finishes a turn. Off by default; manual titles are never overwritten. External plugin CLIs run only after their title feature is enabled.",agentAutoRenameToggle:"Toggle automatic titles for this agent",agentAutoRenameShort:"Auto title",agentAutoRenameNamer:"Title agent",agentAutoRenameFollow:"Follow current session",agentAutoRenameModelsFromCli:"Models discovered from local CLIs",agentAutoRenameRefreshModels:"Refresh CLI models",agentAutoRenameCliDefault:"CLI default model",agentAutoRenameAutomatic:"Automatic selection",agentAutoRenameNoCli:"No supported title CLI detected",agentAutoRenameAdvanced:"Advanced title preferences",agentAutoRenamePreference:"Additional preferences",agentAutoRenamePreferenceHint:"Optional. Add preferences for title style or emphasis; Termdock keeps its default naming rules. Saved when you leave the field.",agentAutoRenamePreferencePlaceholder:"For example: emphasize user value; use action phrases; avoid technical jargon",agentAutoRenamePayloadLimit:"User-message context limit (characters)",agentAutoRenamePayloadLimitHint:"Total raw prompt-submit payload characters retained. Default 12000; range 1000–64000.",agentPlugins:"Agent Plugins",agentPluginAdd:"Add Plugin",agentPluginHint:"Install from an HTTPS Git repository or local directory after reviewing the source. Hooks and executable title CLIs require separate user opt-in.",agentPluginCreate:"Create Plugin",agentPluginDelete:"Delete Plugin",agentPluginInvalid:"Invalid plugin manifest",agentPluginCopyAiPrompt:"Copy AI fix prompt",agentPluginCopied:"Copied",agentPluginSourcePlaceholder:"https://github.com/user/agent-plugin or local directory",agentPluginInstallPackage:"Install plugin",agentPluginAdvancedManifest:"Advanced: paste manifest.json",agentPluginUpdateAvailable:"Update available",agentPluginManualSource:"Manual manifest",agentPluginUpdate:"Update",agentPluginCheck:"Check",agentPluginDoctor:"Diagnose",agentPluginDoctorHint:"Explicitly probe plugin models without generating a title",agentPluginDoctorStatusOk:"Title and model capabilities are healthy",agentPluginDoctorStatusMissing:"titleNamer is not declared",agentPluginDoctorStatusCliDefault:"Titles are available using the CLI default model",agentPluginDoctorStatusNoModels:"No usable model data was returned",agentPluginDoctorStatusFailed:"Model probe failed",agentPluginDoctorModels:"usable models",agentPluginDoctorAutomatic:"automatic",agentPluginDoctorCliDefault:"When no model is specified, the Agent CLI default model is used",agentAutoRenameInterval:"Recheck interval",agentAutoRenameMinutes:"minutes",mobileKeyboard:"Mobile keyboard",saving:"Saving…",rulesHint:"Configure regex patterns to detect what an AI tool is doing in a terminal tab. Each rule can choose its label, color, icon style and how long the indicator is kept after output quiets down. When it stops and you haven't viewed the tab yet, the tab keeps a yellow review hint.",programsHelp:"Supports multiple programs in one config. Separate with commas.",programLabelResolution:"Program label resolution",rawCommandMapping:"Raw command mapping",rawCommandMappingHint:"Rules below map the raw command line to the tab display label. User rules run before built-ins.",genericProgramNames:"Generic program names",genericProgramNamesHint:"Trigger ps-based deep detection (e.g. node, python)",wrapperScriptNames:"Wrapper script names",wrapperScriptNamesHint:"CLI wrappers that launch another tool (e.g. aiden, npx)",shellNamesConfig:"Shell names",shellNamesHint:"Filtered out from tab display (e.g. bash, zsh)",addTag:"+ add",customRules:"Custom rules",addRule:"Add rule",localAccess:"Local access",localAccessHint:"Use this LAN URL from your phone after trusting the local CA. Open Mobile setup on your phone to download the CA certificate.",resetAutoName:"Reset auto",onboardingUrl:"Mobile setup",httpsActive:"HTTPS active",httpsInactive:"HTTPS inactive",caMissing:"CA download unavailable",closeSettings:"Close settings",desktopTitle:"Termdock Desktop",desktopStatusLoading:"Reading native macOS status…",desktopSwitchService:"Switch service",desktopInstallCli:"Install / Repair CLI",desktopCliUpdated:"CLI status updated",desktopOpenDataDirectory:"Open data directory"},toolbarPresets:{preview:"Preview",presets:"Presets",label:"Label",new:"New",reset:"Reset",presetLabelPlaceholder:"Preset label",deletePreset:({name:t})=>`Delete preset ${t}`,matchPrograms:"Match programs",typeEnterHint:"Type & Enter",programsPlaceholder:"vim, nvim, /^claude(-code)?$/i …",programsHelp:"Plain names match as case-insensitive substrings. Wrap in /…/flags for regex (tested against the lowercase program name).",altSlot:"Alt modifier slot",altSlotHint:"Reserve one preview slot for the Alt key.",desktopVisibility:"Show on desktop",desktopVisibilityHint:"Desktop shows only this preset’s custom actions, not the basic keyboard shortcuts.",rowLayout:"Row layout",rowLayoutHint:"Buttons per expanded row.",addRow:"Row",rowN:({n:t})=>`Row ${t}`,del:"Del",buttons:"Buttons",buttonsHint:"Tap to edit. Use ↑↓ to reorder.",addButton:"Add button",noCustomButtons:"No custom buttons yet. Add one to override the default toolbar.",moveUp:"Move up",moveDown:"Move down",removeRow:({n:t})=>`Remove row ${t}`,removeAction:({name:t})=>`Remove ${t}`,labelField:"Label",labelPlaceholder:"Label shown on the button",sequence:"Sequence",sequencePlaceholder:"e.g. /undo or \\t or /||undo",sequenceHint:"Double-tap sequence",doubleTap:"Double-tap sequence",doubleTapAdd:"+ Add",doubleTapPlaceholder:"e.g. /undo\\r or /||undo ||\\r",remove:"Remove",noSequence:"No sequence",preset:"Preset",overCapacityHint:"More buttons than slots. Extra rows will use the last row size."},agentRules:{ruleColors:{green:"Green",yellow:"Yellow",red:"Red",blue:"Blue",purple:"Purple",orange:"Orange",gray:"Gray"}},tab:{session:"Session",new:"New session",rename:"Rename",renameHint:"Change the tab display name",renamePlaceholder:"Leave empty to reset to default",copyCwd:"Copy cwd",copyCwdHint:"Copy the current working directory",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:t})=>`${t} conversation available`,resumeAgentRecoveredHint:"This terminal was rebuilt after an interruption. Continue where you left off.",resumeAgentNow:"Resume",resumeAgentLater:"Dismiss for now",resumeAgentSubmitting:"Submitting the native resume command…",resumeAgentWaiting:"Waiting for the Agent to confirm the restored conversation…",resumeAgentSuccess:({agent:t})=>`${t} conversation restored`,resumeAgentFailed:"Could not resume the Agent conversation. You can retry.",resumeAgentConflict:"This Agent conversation is already open in another terminal.",resumeAgentBusy:"Wait for the current Agent turn to finish before resuming.",resumeAgentTimeout:"The Agent did not confirm the restored conversation. Check the terminal or retry.",tmuxRecoveryTitle:({count:t})=>`tmux exited unexpectedly; ${t} Agent session(s) can be restored`,tmuxRecoveryHint:"Termdock kept the native session IDs. Restore continues each conversation in its original tab.",tmuxRecoveryRestoreAll:"Restore all",tmuxRecoveryRestoring:"Restoring…",tmuxRecoveryDismiss:"Not now",tmuxRecoveryPartial:({restored:t,failed:e})=>`Restored ${t}; ${e} still need attention.`,tmuxRecoveryFailed:"Recovery failed. Check the terminals and try again.",tmuxRecoveryDismissFailed:"Could not dismiss the recovery notice.",copied:"Copied",close:"Close session",closeHint:"Remove this tab from the list",longPressTip:"Tip: hold a tab still for a moment to open actions; hold and drag to reorder.",sessionsTitle:"Sessions",explorerTitle:"Explorer",split:"Split",splitTitle:"Add to split workspace",splitNew:"New session in workspace",splitNewHint:"Uses the current directory and default type; add as many panes as needed",splitExisting:"Choose a session or workspace",splitExistingHint:"Create multiple independent workspaces; choosing another workspace merges them",splitCurrent:"Current",splitClose:"Exit split",splitLayout:"Split layout",splitHorizontal:"Side by side",splitVertical:"Stacked",splitGrid:"Grid",splitWorkspace:"Split group",splitWorkspaces:"Split workspaces",splitRename:"Rename split group",splitRemovePane:"Remove from split",splitExistingGroups:"Existing split groups",splitAvailableSessions:"Available sessions",splitOccupied:"Grouped",splitUnavailableGrouped:"Grouped mode only supports sessions in the same directory",splitEndedGrouped:"Split ended: grouped mode does not support mixed directories",splitNoOtherSessions:"No other sessions are available",sessionCount:({count:t})=>`${t} session${t===1?"":"s"}`,closeChooserTitle:"Destroy tmux session?",closeChooserDescription:"This will stop the session and every process inside it. This cannot be undone.",destroySession:"Destroy session",confirmDestroySession:"Confirm destroy",destroySessionHint:"Stop the tmux session and every process inside it.",dragToClose:"Drag here to close",releaseToClose:"Release to confirm"},agent:{aiRunning:"AI running",needsReview:"Needs review",finishedReview:"AI finished — needs review",aiWaiting:"AI waiting",copyMode:"Copy mode",jumpToNext:"Jump to next session needing attention",jumpToNextRunning:"Jump to next running session",selectRunningSession:"Select a running session",runningSessionGestureHint:"Tap to cycle · swipe sideways to select · hold to drag",currentSession:"Current"},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:t})=>`${t} left`,updated:({time:t})=>`Updated ${t}`,refresh:"Refresh",close:"Close"},errorBoundary:{title:"Something went wrong",unexpected:"An unexpected error occurred",retry:"Try Again",copyDetails:"Copy error details",copied:"Copied",copyFailed:"Copy failed"},error:{type:{network:"Network error",session:"Session error",terminal:"Terminal error",auth:"Authentication error",validation:"Validation error",unknown:"Unknown error"},severity:{low:"Notice: ",medium:"Warning: ",high:"Error: ",critical:"Critical: "},suggestion:{networkCheck:"Check your network connection",networkRetry:"Try reconnecting",networkProxy:"Check proxy settings",networkWait:"Wait for the network to recover",sessionRecreate:"Recreate the session",sessionServer:"Check the server status",sessionCache:"Clear your browser cache",terminalRestart:"Restart the terminal",terminalConfig:"Check the terminal configuration",terminalClear:"Clear the terminal output",authRelogin:"Sign in again",authCredentials:"Check your credentials",authAdmin:"Contact the administrator",validationFormat:"Check the input format",validationParams:"Verify your parameters",validationDocs:"See the documentation",unknownReload:"Reload the page",unknownApp:"Restart the app",unknownSupport:"Contact support"}}},F2={app:{name:"Termdock"},android:{device:"设备",selectDevice:"选择设备",noDevices:"未发现设备",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:"连接断开,正在自动重连…",retry:"重试",idleHint:"选择设备开始投屏",noDevicesHint:"用 USB 连接手机并开启 USB 调试,或在此添加网络设备",back:"返回",home:"主页",recents:"多任务",notifications:"通知栏",rotate:"旋转屏幕",volumeUp:"音量 +",volumeDown:"音量 -",power:"电源",inputText:"输入文字",inputPlaceholder:"输入要发送到手机的文字",send:"发送",splitOpen:"在分屏中打开",splitClose:"退出分屏",splitDockedHint:"投屏已在分屏区域显示。",quality:"画质",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:t})=>`请稍候 ${t}s`,submit:"登录",invalidPassword:"密码错误",failed:"登录失败"},sidebar:{sessions:"会话",noSessions:"暂无打开的会话。",noMatchingSessions:"没有匹配的会话。",toggleSearch:"切换搜索",settings:"设置",moreActions:"更多操作",subscriptionQuota:"订阅额度",pinSidebar:"常驻边栏",unpinSidebar:"取消常驻",runningSessionButton:"运行中会话按钮",runningSessionButtonHint:"轻点循环,横向滑动选择,长按拖动",updateAvailable:({version:t})=>`Termdock ${t} 可用`,updateInstalling:"正在后台安装,不会中断当前服务。",updateReady:"更新已安装,确认后将重启服务。",updateRestart:"重启并完成更新",updateRestartConfirm:({version:t})=>`确认重启 Termdock 并切换到 ${t}?当前网页会短暂重连,会话不会被关闭。`,updateRestarting:"正在重启,网页将自动重连…",updateFailed:"自动安装失败,提醒会保留。",updateRetry:"重新尝试",filterSessions:"过滤会话",clearSearch:"清除搜索",groupByFolder:"按文件夹分组",groupByFolderTitle:"按工作目录把会话归组折叠;与拖拽排序互斥。",ungrouped:"其他",needsAttention:"待处理",waitingForYou:"等你操作",completedUnread:"完成待查看",closeSession:({name:t})=>`关闭 ${t}`,newShell:"Shell",newTmux:"Tmux",newTmuxDisabled:"服务端未安装 tmux",confirmNewShell:"创建 Shell?",confirmNewTmux:"创建 Tmux?",newSession:"新建 Terminal",newSessionWithAgent:({agent:t})=>`新建 ${t}`,moreLaunchOptions:"更多启动选项",recoverableSessions:"可恢复会话",refreshRecoverableSessions:"刷新可恢复会话",restoreRecoverableSession:({name:t})=>`恢复 ${t}`,restoringRecoverableSession:"恢复中…",restore:"恢复",newSessionAdvanced:"快速启动 Agent",newSessionComposerTitle:"开始新会话",newSessionHint:"选好运行方式和目录后再启动",launchSessionWith:({name:t})=>`启动 ${t}`,setNewSessionDefault:({name:t})=>`将 ${t} 设为默认`,currentNewSessionDefault:({name:t})=>`${t} 是当前默认`,currentDefaultAgent:({name:t})=>`当前默认:${t}`,defaultAgent:"默认",makeDefault:"设为默认",sessionMode:"运行方式",tmuxKeepsRunning:"断开后继续运行",resumeHistory:"最近会话",resumeHistoryCount:({n:t})=>`已保存 ${t} 条`,resumeHistoryLoading:"正在载入最近的 Agent 会话…",resumeHistoryAction:({title:t})=>`恢复 ${t}`,resumeHistoryRemove:({title:t})=>`从最近会话中移除 ${t}`,resumeHistoryLoadFailed:"无法载入最近的 Agent 会话。",resumeHistoryFailed:"无法准备恢复该 Agent 会话。",resumeHistoryRemoveFailed:"无法从历史中移除该会话。",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:"不显示隐藏文件",insertCurrentFolder:"引用当前目录",insertCurrentFolderShort:"引用",pinnedFolders:"固定",unpinFolder:({name:t})=>`取消固定 ${t}`,fileWatchUnavailable:({message:t})=>`文件监听不可用:${t}。可点击手动刷新。`,browsingOutsideProject:"正在浏览当前项目外目录",browsingOutsideProjectHint:"Git 和改动仍使用当前项目;这里引用的文件会按外部路径插入。",toggleSearch:"切换搜索",refreshGit:"刷新 Git 状态",gitLastUpdated:({time:t})=>`上次更新:${t}`,close:"关闭",filterChanges:"过滤改动或文件",searchPlaceholderContent:"在文件内容中搜索…",searchModeName:"文件",searchModeContent:"内容",clearSearch:"清除搜索",searchScope:"范围",searchScopePlaceholder:"相对目录或绝对路径",resetSearchScope:"恢复搜索当前目录",searchOptions:"搜索选项",searchExclude:"排除",searchExcludePlaceholder:"dist/**, *.lock",clearSearchExclude:"清空排除规则",contentSearchOptions:"内容搜索选项",matchCase:"区分大小写",matchWholeWord:"全词",useRegex:"正则",insertGitContext:"把当前 Git 信息插入 Terminal",copyGitContext:"复制 Git 信息",insertChangeAuditPrompt:"解释当前改动",insertChangeAuditPromptTitle:"把更改审计提示词插入当前会话",changeAuditShort:"解释当前改动",changeAuditLoading:"正在加载 hunk 解释…",changeAuditLoaded:({count:t})=>`已加载 ${t} 条 hunk 解释`,changeAuditLoadedAt:({time:t})=>`最近生成 ${t}`,changeAuditRegenerate:"重新生成",changeAuditRefreshStale:"补充失效",changeAuditRefreshStaleTitle:"为已失效的 hunk 解释插入补充生成提示词",clearChangeAudit:"清理",clearChangeAuditTitle:"清理当前仓库的 hunk 解释",changeAuditClearFailed:({message:t})=>`清理 hunk 解释失败:${t}`,changeAuditScopeAll:"全部仓库",changeAuditScopeLabel:"解释范围",branchAuditTitle:"分支解释",branchAuditShort:"解释分支改动",branchAuditBaseLabel:"基线分支",branchAuditBasePlaceholder:"基线分支,例如 master",branchAuditBaseSearchPlaceholder:"搜索基线分支",branchAuditBaseEmpty:"没有可选分支,可直接输入分支名",branchAuditGenerate:"生成解释",branchAuditRegenerate:"重新生成",branchAuditGenerateTitle:"生成当前分支相对于基线分支的解释提示词",branchAuditViewDiff:"查看对比",branchAuditViewDiffTitle:"查看目标分支相对于基线分支的改动",branchAuditDiffLoading:"正在加载分支对比…",branchAuditDiffEmpty:"当前分支相对于基线分支暂无改动。",branchAuditMissingBase:({repo:t})=>`${t} 未设置基线分支`,branchAuditRefreshDiff:"刷新对比",branchAuditRefreshStale:"补充失效",branchAuditRefreshStaleTitle:"为已失效的分支解释插入补充生成提示词",branchAuditClearTitle:"清理当前分支解释",branchAuditClearFailed:({message:t})=>`清理分支解释失败:${t}`,branchAuditCommitCount:({count:t})=>`${t} 个提交`,branchAuditFileCount:({count:t})=>`${t} 个文件`,branchAuditTruncated:"diff 已截断",branchAuditCurrent:"已保存解释",branchAuditStale:"解释已失效",branchAuditEmpty:"暂无分支解释。生成后会持久化保存,可随时回来查看。",branchAuditView:"查看解释",branchAuditSaved:({count:t})=>`已保存 ${t} 条 hunk 解释`,branchAuditGeneratedAt:({time:t})=>`生成于 ${t}`,insertPreset:({label:t})=>`插入:${t}`,tabChanges:"改动",tabGit:"Git",tabFiles:"文件",tabAndroid:"设备",showAndroidTab:"显示设备 Tab",inserted:"已插入",copied:"已复制",toggleContextDraft:"切换上下文草稿",contextDraftTitle:"上下文草稿",contextDraftHint:"启用后,引用会追加到这里;可以继续浏览、补写描述,最后一次插入。",contextDraftPlaceholder:"在这里组织长提示词,继续点击侧栏中的引用来追加上下文…",contextDraftCollapse:"收起上下文草稿",contextDraftExpand:"展开上下文草稿",contextDraftDisable:"停用上下文草稿",contextDraftClear:"清空草稿",contextDraftInsert:"插入",contextDraftInsertAndSend:"插入并发送",contextDraftInserted:"已插入",contextDraftSent:"已发送",contextDraftSend:"发送草稿",contextDraftAppended:"已追加引用",contextDraftResize:"拖动调整高度,双击恢复默认",contextDraftAutoCollapseAfterSend:"插入/发送后收起",contextDraftInsertFailed:"终端未连接,草稿已保留",contextDraftCharacterCount:({count:t})=>`${t} 字`,selectFilePrompt:"选择文件以预览内容",backToFileList:"返回文件列表",backToPreviousPreview:"返回来源文档",insertLineRef:({lineLabel:t})=>`引用${t}`,insertFileRef:"引用",copyFileRef:"复制文件引用",findInFile:"在文件内查找",findInFilePlaceholder:"在当前文件中查找…",previousSearchMatch:"上一个匹配项",nextSearchMatch:"下一个匹配项",closeFileSearch:"关闭文件搜索",downloadFile:"下载文件",downloadFailed:"下载失败",uploadFile:"上传文件",uploadFiles:"上传文件",insertLocalFile:"插入本地文件",insertLocalImage:"插入本地图片",layoutMode:"显示模式",layoutModeAuto:"自动",layoutModeNarrow:"窄版",layoutModeWide:"宽版",dropToUpload:"拖放文件以上传",uploading:"上传中…",uploadSuccess:({count:t})=>`已上传 ${t} 个文件`,uploadFailed:"上传失败",binaryPreviewHint:"二进制文件无法预览,请使用上方下载按钮保存到本地",selectedLineHint:({lineLabel:t})=>`已选 ${t} · 点下方「引用」按钮插入`,multiLineHint:"多行引用:先点起始行,再点结束行",loadingImage:"正在加载图片…",imagePreviewHint:"双指捏合或 ⌘/Ctrl + 滚动缩放 · 双击还原",imageLoadFailed:"图片预览加载失败",loadingVideo:"正在加载视频…",videoPreviewHint:"点击播放 · 长按 2× · 可拖动进度条",videoLoadFailed:"视频预览加载失败",videoUnsupported:"当前浏览器不支持该视频格式",videoPlay:"播放",videoPause:"暂停",videoLongPressSpeed:"长按 2× 播放",videoRotate:"顺时针旋转 90°",videoFullscreenEnter:"全屏播放",videoFullscreenExit:"退出全屏",model3dLoading:"正在加载 3D 模型…",model3dExplode:"爆炸展开",model3dExplodeAxis:"展开方向(查看器坐标)",model3dExplodeAmount:"展开程度",model3dHome:"回正并看全",model3dFit:"看全可见零件",model3dFront:"正视图",model3dTop:"俯视图",model3dRight:"右视图",model3dAssemble:"恢复装配",model3dExplodedNotice:"爆炸展示 · 尺寸与引用仍为原始装配坐标",model3dLoadFailed:"3D 模型预览加载失败",model3dTimeout:"3D 模型传输超时,请检查连接后重试。",model3dDimensions:({dims:t})=>`尺寸: ${t}`,model3dHintMouse:"拖拽旋转 / 双指平移 / 捏合或滚轮缩放",model3dHintTouch:"单指旋转 / 双指缩放平移",model3dFullscreenEnter:"全屏查看",model3dFullscreenExit:"退出全屏",model3dBgToLight:"切换为白底",model3dBgToDark:"切换为黑底",model3dRefresh:"重新加载模型",model3dClipToggle:"切面查看",model3dClipPosition:"切面位置",model3dClipFlip:"反转切面方向",model3dFeatureToggle:"特征标注",model3dFeatureStatus:({total:t,positioned:e})=>`特征: ${t} 个 · 已定位 ${e}`,model3dFeatureInsert:"引用",model3dGlossaryToggle:"建模名词说明",model3dPickToggle:"选择零件 / 引用",model3dPickHint:"点选零件后可临时隐藏,或引用所选位置",model3dHidePart:"隐藏零件",model3dShowAllParts:({count:t})=>`显示全部(${t})`,model3dParts:"零件",model3dCloseParts:"关闭零件列表",model3dSearchParts:"查找零件",model3dClearPartSearch:"清空零件搜索",model3dHiddenParts:({count:t})=>`已隐藏 ${t}`,model3dShowNamedPart:({name:t})=>`显示 ${t}`,model3dHideNamedPart:({name:t})=>`隐藏 ${t}`,model3dIsolateNamedPart:({name:t})=>`只看 ${t}`,model3dIsolatePart:"只看此件",model3dShowPart:"显示零件",model3dNoParts:"没有匹配的零件",model3dUndoVisibility:"撤销",model3dClearSelection:"取消选择",model3dAllPartsVisible:"全部可见",model3dInspectHint:"单指旋转 · 双指缩放平移 · 双击局部放大,双击空白看全",model3dUnnamedPart:({index:t})=>`零件 ${t}`,model3dCanvas:"三维模型",model3dMore:"更多模型选项",edaLoading:"正在渲染 KiCad 文件…",reviewTargetChanged:"当前会话已切换,请回到创建这条引用的会话后再插入。",reviewReference:"审阅引用",reviewReferenceHint:"补充意见后插入,不会自动发送。",reviewSnapshot:"选中位置的视图快照",reviewCapturing:"正在截取当前视图…",reviewIncludeImage:"附带截图(临时保存在当前服务器)",reviewCaptureFailed:"截图未成功,仍可插入定位信息。",reviewNote:"你的意见(可选)",reviewNotePlaceholder:"例如:这里太厚了,能否减薄?",reviewDetails:"查看定位信息和引用原文",reviewUploading:"正在准备引用…",reviewAddToDraft:"加入引用草稿",reviewInsert:"插入引用",reviewUploadFailed:"引用准备失败,意见已保留。请重试,或取消附带截图后只插入文字。",edaLoadFailed:"KiCad 预览渲染失败",edaTimeout:"KiCad 预览生成或传输超时,请重试。",edaRefresh:"重新渲染",edaPickHint:"点击原理图或 PCB 上的问题位置,生成电子标注",edaPickedPosition:({x:t,y:e})=>`已选位置 ${t}%, ${e}%`,edaPickedBoardPosition:({x:t,y:e,object:n})=>`板坐标 ${t}, ${e} mm · ${n}`,edaInspecting:"正在读取板坐标和附近对象…",edaNoNearbyObject:"附近无对象",edaInsertAnnotation:"引用电子标注",csvUnnamedColumn:({index:t})=>`第 ${t} 列`,csvSelectedCell:({row:t,column:e})=>`已选第 ${t} 行 · ${e}`,csvPickHint:({rows:t,columns:e})=>`${t} 条记录 · ${e} 列,点击单元格引用`,csvInsertAnnotation:"引用表格标注",csvTablePreview:"表格预览:点击单元格后可引用完整记录",kicadLocalStateNotice:"这是本机界面状态文件,不参与原理图、PCB 或生产审查。",kicadShowRawJson:"查看原始 JSON",kicadProjectPickHint:"点击一项配置后可插入引用",kicadInsertSetting:"引用配置",markdownPreview:"预览",markdownSource:"源码",markdownPreviewHint:"点按行/段落引用,再点一行扩选;拖左侧竖条可连续框选",htmlPreview:"预览",htmlSource:"源码",htmlPreviewHint:"HTML 沙箱 iframe 预览,脚本受限",htmlFullscreenEnter:"全屏预览",htmlFullscreenExit:"退出全屏预览",markdownOutline:"Markdown 目录",markdownOutlineShort:"目录",closeMarkdownOutline:"关闭目录",changedFromPath:({path:t})=>`来自 ${t}`,selectedLineFooter:({lineLabel:t})=>`已选 ${t}`,clearSelection:"清除",allChanges:"全部改动",backToChangeList:"返回目录",allRepositories:"全部仓库",allRepositoriesShort:"全部",repositories:"仓库",gitRepositorySectionTitle:"操作仓库",gitRepositoryLabel:"仓库",gitRepositoryPlaceholder:"选择仓库",gitRepositorySearchPlaceholder:"搜索仓库",gitRepositoryEmpty:"没有可操作的仓库",selectRepositoryForGitActions:"请选择一个仓库后再执行 Git 操作",selectRepositoryForDiff:"选择一个仓库或文件查看 diff",repoNotLoaded:"点击加载",repoChangedCount:({count:t})=>`${t} 个改动`,repoStagedCount:({count:t})=>`${t} 已暂存`,noChanges:"没有改动",noMatchingChanges:"没有匹配的改动",loadingGitChanges:"正在加载 Git 改动…",loadingGitChangesSlow:"仓库较大时可能需要几秒。",refreshingGitChanges:"正在刷新 Git 改动…",gitChangesLoadFailed:"无法加载 Git 改动",retryGitChanges:"重试",insertThisFile:"把这个文件引用插入 Terminal",viewDiff:"查看 diff",diffViewMode:"改动文件展示方式",diffViewModeList:"平铺列表",diffViewModeTree:"目录结构",diffViewModeAi:"AI 导览",changeWalkthroughEmpty:"暂无 AI 导览。生成解释后会在这里展示总览、链路和验证点。",gitInfo:"Git 信息",wrapLongLines:"长行换行",wrapOn:"已换行",wrapOff:"原始",multiRepoScan:"多子仓",multiRepoScanTitle:"扫描当前工作区下的嵌套 Git 仓库。关闭时只看单个仓库,大仓库打开更快。",horizontalScrollHint:"左右滑动查看完整 diff",stageFile:"暂存",stageAll:"全部暂存",unstageFile:"取消暂存",stashFile:"贮藏",stashAll:"全部贮藏",restoreFile:"丢弃",gitQuickActions:"Git 操作",gitUnavailable:"当前目录不是 Git 仓库",branchSectionTitle:"当前分支",currentBranchLabel:"分支",switchBranchPlaceholder:"选择分支",switchBranchSearchPlaceholder:"搜索本地分支",switchNoBranches:"没有本地分支",switchBranch:"切换",noStagedChangesShort:"无暂存",stagedCount:({count:t})=>`已暂存 ${t}`,stagedCountShort:({count:t})=>`已暂存 ${t}`,commitSectionTitle:"提交",commitReadyHint:({count:t})=>`${t} 个文件已准备提交`,commitMessagePlaceholder:"提交信息",commitChanges:"提交",commitNeedsStaged:"请先暂存要提交的改动",commitAhead:"↑ 待推送",commitBehind:"↓ 待拉取",commitSynced:"已同步",recentCommitsTitle:"近期提交",recentCommitsSearchPlaceholder:"搜索提交 hash 或信息",recentCommitsLoadMore:"加载更多提交",recentCommitsEmpty:"暂无提交历史",pushSectionTitle:"同步远端",pushRemoteLabel:"Remote",pushRemotePlaceholder:"origin",pushRemoteSearchPlaceholder:"搜索 Remote",pushNoRemotes:"没有 Remote",pushBranchLabel:"目标分支",pushBranchPlaceholder:({branch:t})=>`${t}`,pushBranchSearchPlaceholder:"搜索分支",pushNoBranches:"没有分支",pushUpstreamBadge:"upstream",pushCurrentBranchBadge:"当前",pushNoUpstream:"当前分支未设置 upstream",pushUpToDate:"与远端同步",pushAheadCount:({count:t})=>`领先远端 ${t} 个提交`,pushBehindCount:({count:t})=>`落后远端 ${t} 个提交`,pushDivergedCount:({ahead:t,behind:e})=>`领先 ${t} / 落后 ${e} 个提交`,pullChanges:"拉取",pushChanges:"推送",gitActionRunning:"执行中…",gitActionFailed:({message:t})=>`Git 操作失败:${t}`,confirmRestoreTitle:"确认丢弃改动",confirmRestoreDescription:({path:t})=>`将丢弃 ${t} 的未暂存改动,此操作不可从 Termdock 恢复。`,confirmRestorePhrase:"丢弃改动",confirmRestorePlaceholder:"输入“丢弃改动”确认",confirmStashAllTitle:"确认贮藏全部改动",confirmStashAllDescription:"会把当前工作区改动(包含未跟踪文件)移入贮藏。",confirmAction:"确认",renderingHtml:"正在渲染 HTML…",footnotes:"脚注",backToFootnote:({index:t})=>`返回脚注 ${t}`,openMermaidDiagram:"打开 Mermaid 图表",mermaidDiagram:"Mermaid 图表",renderingDiagram:"正在渲染图表…",markdownImage:"Markdown 图片",image:"图片",previousImage:"上一张图片",nextImage:"下一张图片",closeImagePreview:"关闭图片预览",emptyFile:"空文件。",insertReference:({reference:t})=>`插入引用:${t}`,copyReference:({reference:t})=>`复制引用:${t}`,byteCount:({count:t})=>`${t} 字节`,previewTruncated:"预览已截断至 1 MB",branchCandidatesLoading:"正在加载分支候选…",includeUncommitted:"包含本地未提交改动",includeUncommittedHint:"查看对比或生成解释时纳入工作区和未跟踪文件的 diff",missingBaseReposSkipped:({repositories:t})=>`未设置基线的仓库会跳过:${t}`,localBranch:"本地",remoteBranch:"远端"},fileTree:{insertRef:"引用",insertRefTitle:"Insert file reference into active terminal",openDirRoot:"进入",openDirRootTitle:"把这个目录作为当前浏览根目录",openInFileBrowser:"在 Finder 中显示",openInFileBrowserTitle:"在系统文件浏览器中打开这个项目",openInFileBrowserFailed:"打开文件浏览器失败",moreDirActions:"更多目录操作",searchFromDir:"从这里搜索",searchFromDirTitle:"只搜索这个目录及其子目录",pinDir:"固定",pinDirTitle:"固定这个目录到当前项目",unpinDir:"已固定",unpinDirTitle:"取消固定这个目录",pinFileTitle:"固定这个文件到当前项目",unpinFileTitle:"取消固定这个文件",pinFile:"固定",unpinFile:"已固定",moreFileActions:"更多文件操作",deleteFile:"删除文件",deleteFileConfirm:({name:t})=>`确认删除“${t}”?此操作无法撤销。`,deleteFileFailed:({message:t})=>`删除文件失败:${t}`,noWorkingDir:"未检测到工作目录。",emptyDir:"空目录。",noMatchingFiles:"没有匹配的文件。",searching:"正在搜索文件…",searchingWithCount:({count:t})=>`搜索中…已找到 ${t} 项`,searchResults:({count:t})=>`${t} 个结果`,searchScope:"搜索范围",searchTruncatedHint:({count:t})=>`降级搜索已扫描大量目录并在找到 ${t} 项后停止。安装 ripgrep 或输入更精确关键词可获得完整结果。`,searchStillRunning:"搜索仍在进行,更多结果会自动出现。",showingSearchResults:({shown:t,total:e})=>`正在展示 ${t}/${e}`,loadMoreSearchResults:({shown:t,total:e})=>`查看更多(${t}/${e})`,contentMatchesCount:({count:t})=>`${t} 个文件命中`,moreMatches:({count:t})=>`还有 ${t} 处匹配`,noContentMatches:"文件内容中没有匹配。",contentSearchNeedsRipgrep:"内容搜索需要 ripgrep(rg),请在服务端安装后再在文件内搜索。",truncatedHint:"仅展示前 1000 项。使用搜索或打开更小的文件夹以获得更好性能。",dropToUploadHere:"上传到这里",symbolicLink:"符号链接",sortByModified:"按最近修改排序",sortByName:"按名称排序",sortedByModified:"已按最近修改排序"},diffViewer:{noFileChanges:"此文件无改动。",noUnstagedChanges:"没有未暂存的改动。",emptyHint:"做一些改动,或从远程拉取。",loading:"正在加载 diff…",insertAllDiff:"把当前 diff 内容作为上下文插入 Terminal",insertFileDiff:"引用这个文件的 diff",insertHunkDiff:"引用这段 diff hunk",insertHunkShort:"引用",insertFileShort:"引用",insertAllShort:"全部",stageHunk:"暂存",stageHunkTitle:"只把这个 hunk 加入暂存区 (git apply --cached)",revertHunk:"撤销",revertHunkTitle:"撤销这个 hunk 的工作区改动(不可恢复)",revertHunkConfirm:"确认撤销?",hunkActionApplying:"应用中…",hunkActionUnavailable:"无法为这个 hunk 构造补丁",hunkActionFailed:({message:t})=>`操作失败:${t}。如改动已变化,请刷新后重试。`,auditExplanation:"更改意义",auditStale:"解释已失效",auditClear:"清除解释",auditGeneratedAt:({time:t})=>`生成于 ${t}`,allDiffLabel:"全部 diff",allChangesLabel:"全部改动",workingTree:"工作区改动",allUnstaged:"所有未暂存改动",binaryOrEmpty:"没有可显示的文本改动。",noFinalNewline:"文件末尾没有换行符",noHunks:"没有 hunk",hunkOutline:"Hunk 列表",expandHunkRail:"显示 hunk 列表",collapseHunkRail:"隐藏 hunk 列表",prevHunk:"上一个 hunk",nextHunk:"下一个 hunk",prevFile:"上一个",nextFile:"下一个",expandFile:"展开文件",collapseFile:"折叠文件",expandAll:"全部展开",collapseAll:"全部折叠",collapseHunk:"折叠 hunk",useBracketKeysHint:"按 [ / ] 在 hunk 之间跳转",unified:"统一",unifiedMode:"统一视图",split:"分屏",splitMode:"左右分屏视图",moreActions:"更多操作",view:"视图",loadingPreviousFile:"正在加载上一个文件…",loadingNextFile:"正在加载下一个文件…",resizeNavigation:"调整 diff 导航宽度",focusPathHint:"点击标注聚焦路径",whitespace:"空白",whitespaceDefault:"默认",whitespaceTrim:"忽略行尾空白",whitespaceIgnore:"忽略所有空白",whitespaceIgnoreBlankLines:"忽略空行",context:"上下文",contextLines:({count:t})=>`${t} 行`,contextAll:"全部"},settings:{title:"设置",font:"字体",render:"渲染",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:"桌面版已是最新版本。",desktopUpdateDownloading:"发现新版本,正在后台下载…",desktopUpdateReady:"桌面版更新已下载,可以重启安装。",desktopUpdateInstalling:"正在重启并安装桌面版更新…",desktopUpdateCheck:"检查桌面版",desktopUpdateCheckAgain:"再次检查",desktopUpdateRestart:"重启并安装",desktopUpdateRestartConfirm:"重启 Termdock 并安装已下载的桌面版更新?终端服务和 tmux 会话不会被停止。",notifications:"通知",notificationsTitle:"通知设置",notificationsHint:"Termdock 在后台时,AI 任务结束后发送系统通知。",notificationsPageHint:"选择哪些 Termdock 事件可以发送系统通知。总开关负责浏览器权限和投递,事件开关决定具体哪些内容提醒你。",notificationsMaster:"系统通知",notificationsMasterHint:"允许 Termdock 在隐藏或作为 PWA 安装运行时发送通知。",notificationsIOSInstallHint:"在 iPhone 或 iPad 上,请先将 Termdock 添加到主屏幕,再开启通知。",notificationsPermission:"权限",notificationsPermissionSystem:"由 macOS 管理",notificationsTest:"发送测试",notificationsTestChecking:"正在等待 macOS 确认投递…",notificationsTestDelivered:"已投递到通知中心;若没有横幅,请检查提醒样式和专注模式。",notificationsTestFailed:"macOS 未投递通知,请在系统设置中允许 Termdock 通知。",notificationsOpenSystemSettings:"打开系统通知设置",notificationsAlertStyle:"提醒方式",notificationsAlertStyleHint:"最终是否横幅弹出仍由浏览器和 Android 系统决定。Termdock 只能请求静默、默认或持续显示等通知选项。",notificationsStyleNormal:"默认",notificationsStyleNormalHint:"允许时声音/震动",notificationsStyleQuiet:"静默",notificationsStyleQuietHint:"仅状态栏,无声音",notificationsStylePersistent:"持续",notificationsStylePersistentHint:"保留到手动关闭",notificationsEvents:"事件",notificationsAiFinished:"AI 任务结束",notificationsAiFinishedHint:"当 Termdock 在后台时,AI agent 停止后发送通知。",notificationsSessionExited:"终端退出",notificationsSessionExitedHint:"终端进程自行结束时发送通知(主动关闭不触发,经 Web Push 投递)。",notificationsFutureHint:"后续可以在这里继续增加更多通知类型,不需要改变顶层设置布局。",notificationsOffSummary:"系统通知已关闭",notificationsAiOnSummary:"AI 任务结束通知已开启",notificationsExitOnSummary:"终端退出通知已开启",notificationsBothOnSummary:"AI 任务结束、终端退出通知已开启",notificationsNoEventsSummary:"暂无开启的通知事件",notificationsDenied:"浏览器通知权限已被阻止,请在站点设置中开启。",notificationsUnsupported:"通知需要安全上下文和 Service Worker 支持。",notificationsTestBody:"通知已开启。后台 AI 任务结束后会提醒你。",shell:"Shell",tmux:"Tmux",auto:"自动",webgl:"WebGL",canvas:"内置",tmuxServer:"Tmux 服务",tmuxUnavailable:"不可用",noTmuxSessions:"服务端没有 tmux 会话。",installTmuxHint:"请在服务端安装 tmux 后启用。",refresh:"刷新",attached:"已连接",restorable:"可恢复",attach:"连接",attaching:"连接中…",destroy:"销毁",sessions:({n:t})=>`${t} 个会话`,windows:({n:t})=>`${t} 个窗口`,keyboardToolbar:"键盘工具栏",aiAgentDetection:"AI 代理检测",signOut:"退出登录",language:"语言",programNamePlaceholder:"程序名(如 claude)",patternPlaceholder:"正则表达式(如 Thinking|Generating)",statusPlaceholder:"状态",addProgram:"添加程序",addPattern:"添加规则",resetDefaults:"恢复默认",invalidRegex:"无效的正则",removeProgram:"移除程序",removeRule:"移除规则",keepLabel:"保持",customColor:"自定义颜色",tabIndicator:"标签指示器样式",toolbarPresets:"工具栏预设",detectionRules:"检测规则",agentHooksHint:"安装 hooks 后,agent 会主动上报状态:回合进行中(绿)、等你授权/回答(黄)、回合完成(对勾),并在等待你输入时推送通知。hooks 全局安装但只在 termdock 的终端里生效。",agentHooksInstall:"安装",agentHooksInstalled:"已安装",agentHooksOutdated:"需更新",agentHooksNeedsApproval:"待授权",agentHooksApprovalHint:"在 Codex 中输入 /hooks,批准 Termdock Hook 后生效",agentHooksNotInstalled:"未安装",agentHooksUninstall:"卸载",agentHooksReinstall:"重新安装",agentHooksDevMode:"开发模式:hooks 指向 TS 源码,需要构建后的版本才能生效",agentHooksTarget:"写入",agentAutoRename:"自动更新会话标题",agentAutoRenameHint:"Agent 完成一轮后,根据近期内容更新标题。默认全部关闭,手工命名的会话不会被覆盖;启用外部插件标题后才会执行其 CLI。",agentAutoRenameToggle:"切换此 Agent 的自动标题",agentAutoRenameShort:"自动标题",agentAutoRenameNamer:"起名 Agent",agentAutoRenameFollow:"跟随当前会话",agentAutoRenameModelsFromCli:"模型由本机 CLI 动态提供",agentAutoRenameRefreshModels:"重新查询 CLI 模型",agentAutoRenameCliDefault:"CLI 默认模型",agentAutoRenameAutomatic:"自动选择",agentAutoRenameNoCli:"未检测到可用于起名的 CLI",agentAutoRenameAdvanced:"高级标题偏好",agentAutoRenamePreference:"补充偏好",agentAutoRenamePreferenceHint:"可选。仅补充你对标题风格或重点的偏好;Termdock 的默认起名规则仍会保留。离开输入框时自动保存。",agentAutoRenamePreferencePlaceholder:"例如:突出用户收益;优先使用动宾结构;避免技术术语",agentAutoRenamePayloadLimit:"用户消息上下文上限(字符)",agentAutoRenamePayloadLimitHint:"保留 prompt-submit 原始 payload 的总字符数,默认 12000,可设置 1000–64000。",agentPlugins:"Agent 插件",agentPluginAdd:"添加插件",agentPluginHint:"从 HTTPS Git 仓库或本地目录安装;请先审查来源。Hooks 和可执行的标题 CLI 均需用户分别启用。",agentPluginCreate:"创建插件",agentPluginDelete:"删除插件",agentPluginInvalid:"插件配置无效",agentPluginCopyAiPrompt:"复制 AI 修复提示",agentPluginCopied:"已复制",agentPluginSourcePlaceholder:"https://github.com/user/agent-plugin 或本地目录",agentPluginInstallPackage:"安装插件",agentPluginAdvancedManifest:"高级:直接粘贴 manifest.json",agentPluginUpdateAvailable:"有更新",agentPluginManualSource:"手动 manifest",agentPluginUpdate:"更新",agentPluginCheck:"检查更新",agentPluginDoctor:"诊断",agentPluginDoctorHint:"显式运行插件模型探测,不会调用标题生成",agentPluginDoctorStatusOk:"标题与模型能力正常",agentPluginDoctorStatusMissing:"未声明 titleNamer",agentPluginDoctorStatusCliDefault:"标题可用,使用 CLI 默认模型",agentPluginDoctorStatusNoModels:"没有可用的模型数据",agentPluginDoctorStatusFailed:"模型探测失败",agentPluginDoctorModels:"个可用模型",agentPluginDoctorAutomatic:"自动选择",agentPluginDoctorCliDefault:"未指定模型时使用 Agent CLI 默认模型",agentAutoRenameInterval:"重新判断间隔",agentAutoRenameMinutes:"分钟",mobileKeyboard:"移动键盘",saving:"保存中…",rulesHint:"配置正则表达式来识别 AI 工具在终端标签中的状态。每条规则可独立设置标签、颜色、图标样式以及输出静默后指示器保留的时长。停止后若你未查看该标签,标签会保留一个黄色待查看提示。",programsHelp:"支持在一个配置中匹配多个程序,用英文逗号分隔。",programLabelResolution:"程序名识别",rawCommandMapping:"原始命令映射",rawCommandMappingHint:"以下规则将原始命令行映射为标签显示名。用户规则优先于内置规则。",genericProgramNames:"通用程序名",genericProgramNamesHint:"触发 ps 深度识别(如 node, python)",wrapperScriptNames:"包装脚本名",wrapperScriptNamesHint:"CLI 包装器,启动其他工具(如 aiden, npx)",shellNamesConfig:"Shell 名称",shellNamesHint:"从标签显示中过滤(如 bash, zsh)",addTag:"+ 添加",customRules:"自定义规则",addRule:"添加规则",localAccess:"本地访问",localAccessHint:"手机信任本地 CA 后,可通过这个局域网地址访问。请先在手机上打开「手机引导」地址下载 CA 证书。",resetAutoName:"恢复自动",onboardingUrl:"手机引导",httpsActive:"HTTPS 已启用",httpsInactive:"HTTPS 未启用",caMissing:"未配置 CA 下载",closeSettings:"关闭设置",desktopTitle:"Termdock 桌面端",desktopStatusLoading:"正在读取 macOS 原生状态…",desktopSwitchService:"切换服务",desktopInstallCli:"安装 / 修复 CLI",desktopCliUpdated:"CLI 状态已更新",desktopOpenDataDirectory:"打开数据目录"},toolbarPresets:{preview:"预览",presets:"预设",label:"标签",new:"新建",reset:"重置",presetLabelPlaceholder:"预设名称",deletePreset:({name:t})=>`删除预设 ${t}`,matchPrograms:"匹配程序",typeEnterHint:"输入后回车",programsPlaceholder:"vim, nvim, /^claude(-code)?$/i …",programsHelp:"纯字符串按大小写不敏感子串匹配。用 /…/flags 包裹则为正则(针对小写程序名测试)。",altSlot:"Alt 修饰键槽",altSlotHint:"在预览中保留一个 Alt 键槽位。",desktopVisibility:"桌面端显示",desktopVisibilityHint:"桌面端只显示该预设的自定义按钮,不显示基础快捷键。",rowLayout:"行布局",rowLayoutHint:"每行按钮数。",addRow:"行",rowN:({n:t})=>`第 ${t} 行`,del:"删",buttons:"按钮",buttonsHint:"点击编辑,使用 ↑↓ 排序。",addButton:"添加按钮",noCustomButtons:"暂无自定义按钮。添加一个来覆盖默认工具栏。",moveUp:"上移",moveDown:"下移",removeRow:({n:t})=>`移除第 ${t} 行`,removeAction:({name:t})=>`移除 ${t}`,labelField:"标签",labelPlaceholder:"按钮上显示的文本",sequence:"序列",sequencePlaceholder:"例如 /undo 或 \\t 或 /||undo",sequenceHint:"双击序列",doubleTap:"双击序列",doubleTapAdd:"+ 添加",doubleTapPlaceholder:"例如 /undo\\r 或 /||undo ||\\r",remove:"移除",noSequence:"无序列",preset:"预设",overCapacityHint:"按钮数超过槽位,多余按钮将使用最后一行的尺寸。"},agentRules:{ruleColors:{green:"绿",yellow:"黄",red:"红",blue:"蓝",purple:"紫",orange:"橙",gray:"灰"}},tab:{session:"会话",new:"新建会话",rename:"重命名",renameHint:"修改标签的显示名称",renamePlaceholder:"留空则恢复默认名称",copyCwd:"复制当前目录",copyCwdHint:"复制当前工作目录",fontSize:"字体大小",fontSizeHint:"仅对这个会话生效",fontSizeReset:"跟随全局",resumeAgent:"恢复 Agent 会话",resumeAgentHint:"用原生 session id 恢复上次对话",resumeAgentAvailable:"有可恢复的 Agent 对话",resumeAgentRecoveredTitle:({agent:t})=>`可继续上次的 ${t} 对话`,resumeAgentRecoveredHint:"Terminal 曾异常中断,已重新创建;可以从上次对话继续。",resumeAgentNow:"恢复",resumeAgentLater:"暂不恢复",resumeAgentSubmitting:"正在提交原生恢复命令…",resumeAgentWaiting:"正在等待 Agent 确认已载入原会话…",resumeAgentSuccess:({agent:t})=>`${t} 会话已恢复`,resumeAgentFailed:"Agent 会话恢复失败,可以重试。",resumeAgentConflict:"该 Agent 会话已在另一个 Terminal 中打开。",resumeAgentBusy:"当前 Agent 回合尚未结束,暂时不能恢复。",resumeAgentTimeout:"Agent 未确认已载入原会话,请查看 Terminal 输出或重试。",tmuxRecoveryTitle:({count:t})=>`检测到 tmux 异常退出,${t} 个 Agent 可恢复`,tmuxRecoveryHint:"Termdock 保留了原生会话 ID。恢复操作会在原标签页中继续之前的对话。",tmuxRecoveryRestoreAll:"恢复全部",tmuxRecoveryRestoring:"正在恢复…",tmuxRecoveryDismiss:"暂不处理",tmuxRecoveryPartial:({restored:t,failed:e})=>`已恢复 ${t} 个,${e} 个需要重试。`,tmuxRecoveryFailed:"恢复失败,请检查终端状态后重试。",tmuxRecoveryDismissFailed:"暂时无法关闭该恢复提示。",copied:"已复制",close:"关闭会话",closeHint:"从列表移除该标签",longPressTip:"提示:按住标签不动约半秒打开操作菜单,按住并拖动可排序。",sessionsTitle:"会话",explorerTitle:"资源管理器",split:"分屏",splitTitle:"添加到分屏工作区",splitNew:"新建会话并加入",splitNewHint:"沿用当前目录和默认会话类型;可连续加入多个会话",splitExisting:"选择已有会话或工作区",splitExistingHint:"会话可组成多个独立工作区;选择另一工作区会将两组合并",splitCurrent:"当前",splitClose:"退出分屏",splitLayout:"分屏布局",splitHorizontal:"左右",splitVertical:"上下",splitGrid:"网格",splitWorkspace:"分屏组",splitWorkspaces:"分屏工作区",splitRename:"重命名分屏组",splitRemovePane:"移出分屏",splitExistingGroups:"已有分屏组",splitAvailableSessions:"可加入的会话",splitOccupied:"已成组",splitUnavailableGrouped:"分组模式下只能分屏同一目录的会话",splitEndedGrouped:"已退出分屏:分组模式不支持跨目录组合",splitNoOtherSessions:"没有可组合的其他会话",sessionCount:({count:t})=>`${t} 个会话`,closeChooserTitle:"销毁 Tmux 会话?",closeChooserDescription:"确认后会终止该会话及其中的所有进程,此操作无法撤销。",destroySession:"销毁会话",confirmDestroySession:"确认销毁",destroySessionHint:"终止 tmux 会话及其中的所有进程。",dragToClose:"拖到此处关闭",releaseToClose:"松手后确认"},agent:{aiRunning:"AI 运行中",needsReview:"需要查看",finishedReview:"AI 已完成 — 需要查看",aiWaiting:"AI 等待中",copyMode:"Copy 模式",jumpToNext:"跳到下一个待处理",jumpToNextRunning:"跳到下一个运行中会话",selectRunningSession:"选择运行中的 Session",runningSessionGestureHint:"轻点循环 · 横向滑动选择 · 长按拖动",currentSession:"当前"},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:t})=>`剩余 ${t}`,updated:({time:t})=>`${t} 更新`,refresh:"刷新",close:"关闭"},errorBoundary:{title:"出现了一些问题",unexpected:"发生意外错误",retry:"重试",copyDetails:"复制错误信息",copied:"已复制",copyFailed:"复制失败"},error:{type:{network:"网络连接错误",session:"会话错误",terminal:"终端错误",auth:"认证错误",validation:"验证错误",unknown:"未知错误"},severity:{low:"提示:",medium:"警告:",high:"错误:",critical:"严重错误:"},suggestion:{networkCheck:"检查网络连接",networkRetry:"尝试重新连接",networkProxy:"检查代理设置",networkWait:"等待网络恢复",sessionRecreate:"重新创建会话",sessionServer:"检查服务器状态",sessionCache:"清理浏览器缓存",terminalRestart:"重启终端",terminalConfig:"检查终端配置",terminalClear:"清除终端输出",authRelogin:"重新登录",authCredentials:"检查凭证",authAdmin:"联系管理员",validationFormat:"检查输入格式",validationParams:"验证参数",validationDocs:"参考文档",unknownReload:"刷新页面",unknownApp:"重启应用",unknownSupport:"联系技术支持"}}},M2=["en","zh"],mr="en",mc="termdock:locale",ss={en:D2,zh:F2};function j2(t){return typeof t=="string"&&M2.includes(t)}function U2(){if(typeof window>"u")return mr;try{const e=window.localStorage.getItem(mc);if(j2(e))return e}catch{}return(window.navigator?.language?.toLowerCase()??"").startsWith("zh")?"zh":mr}const Mg=O.createContext(null);function wc(t,e){const n=e.split(".");let r=t;for(const o of n)if(r&&typeof r=="object"&&o in r)r=r[o];else return;return r}function yc(t,e){return typeof t=="function"?t(e??{}):typeof t!="string"?String(t):e?t.replace(/\{(\w+)\}/g,(n,r)=>Object.prototype.hasOwnProperty.call(e,r)?String(e[r]):n):t}function $2({children:t}){const[e,n]=O.useState(()=>U2()),r=We.useRef(!1);O.useEffect(()=>{typeof window>"u"||sr().then(c=>{if(c?.locale==="zh"||c?.locale==="en"){if(c.locale===e||c.locale==="en"&&e!=="en")return;n(c.locale);try{window.localStorage.setItem(mc,c.locale)}catch{}}}).catch(()=>{})},[]),O.useEffect(()=>{if(!(typeof window>"u")){try{window.localStorage.setItem(mc,e)}catch{}r.current&&(r.current=!1,Et({locale:e}).catch(()=>{})),document.documentElement.lang=e==="zh"?"zh-CN":"en"}},[e]);const o=O.useCallback(c=>{r.current=!0,n(c)},[]),s=ss[e]??ss[mr],i=O.useCallback((c,l)=>{const d=wc(s,c);if(d===void 0){const u=wc(ss[mr],c);return u===void 0?c:yc(u,l)}return yc(d,l)},[s]),a=O.useMemo(()=>({locale:e,setLocale:o,t:i}),[e,o,i]);return p.jsx(Mg.Provider,{value:a,children:t})}function di(){const t=O.useContext(Mg);return t||{locale:mr,setLocale:()=>{},t:(e,n)=>{const r=wc(ss[mr],e);return r===void 0?e:yc(r,n)}}}const H2=String.raw`
14
14
  ████████ ███████ ██████ ███ ███ ██████ ██████ ██████ ██ ██
15
15
  ██ ██ ██ ██ ████ ████ ██ ██ ██ ██ ██ ██ ██
16
16
  ██ █████ ██████ ██ ████ ██ ██ ██ ██ ██ ██ █████
@@ -26,10 +26,10 @@ Minimum version required to store current data is: `+_+`.
26
26
  animation: terminal-blink 1.05s steps(1, end) infinite;
27
27
  color: var(--primary);
28
28
  }
29
- `})]})}const K2={activeKey:"root",items:[]},z2=()=>()=>{},W2=()=>K2,bc="termdock:open-saved-service";function G2(t,e){try{const n=new URL(t.serviceOrigin||t.url);return t.label!==n.host&&t.label!==n.origin?t.label:!e.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 t.label}}function hR(t,e,n){O.useEffect(()=>{window.termdockDesktop?.reportServiceActivity?.({runningCount:t,reviewCount:e})},[t,e]),O.useEffect(()=>{Un({runningCount:t,reviewCount:e,attentionSessions:n})},[t,e,n])}function V2({onReselect:t}){return window.termdockDesktop?null:p.jsx(X2,{onReselect:t})}function X2({onReselect:t}){const[e,n]=O.useState([]),[r,o]=O.useState([]),[s,i]=O.useState(re()?.targetPeerId),[a,c]=O.useState(""),[l,d]=O.useState(!1),[u,f]=O.useState(!1),h=O.useRef(0),g=O.useRef(!1);O.useEffect(()=>{let x=!1;const T=()=>{const S=h.current;sr().then(v=>{!x&&!g.current&&S===h.current&&d(v.serviceSwitcherExpanded===!0)}).catch(()=>{})};return T(),window.addEventListener(Je,T),()=>{x=!0,window.removeEventListener(Je,T)}},[]);const m=async()=>{if(g.current)return;const x=l;h.current+=1,g.current=!0,f(!0),d(!x),c("");try{const T=await Et({serviceSwitcherExpanded:!x});d(T.serviceSwitcherExpanded===!0)}catch{d(x),c("展开状态保存失败,请重试")}finally{g.current=!1,f(!1)}},b=O.useRef(null),w=ht(),R=O.useSyncExternalStore(w?.subscribe||z2,w?.snapshot||W2);O.useEffect(()=>{let x=!1,T=0;const S=()=>{const _=++T;i(re()?.targetPeerId),Ke().then(B=>{if(!(x||_!==T)){try{const I="termdock-secure-service-order",E=JSON.parse(localStorage.getItem(I)||"[]"),P=Array.isArray(E)?E.filter(F=>typeof F=="string"):[],C=F=>F.targetPeerId||F.id,D=[...P.filter(F=>B.some(L=>C(L)===F)),...B.map(C).filter(F=>!P.includes(F))];B.sort((F,L)=>D.indexOf(C(F))-D.indexOf(C(L)));const M=JSON.stringify(D);M!==localStorage.getItem(I)&&localStorage.setItem(I,M)}catch{}n(B)}}).catch(()=>{})};S();const v=Ws(S),A=window.termdockDesktop?.onServiceActivity?.(o);return window.addEventListener(Je,S),()=>{x=!0,v(),A?.(),window.removeEventListener(Je,S)}},[]),O.useEffect(()=>{const x=b.current,T=x?.querySelector('[aria-current="page"]');if(!x||!T)return;const S=T.offsetLeft,v=S+T.offsetWidth;S<x.scrollLeft?x.scrollLeft=S:v>x.scrollLeft+x.clientWidth&&(x.scrollLeft=v-x.clientWidth)},[s,e,l]);const y=async x=>{if(c(""),x.targetPeerId&&x.targetPeerId===s){t?.();return}try{const T=window.termdockDesktop;if(T?.openServiceConnection){const S=await T.openServiceConnection(x);if(!S.ok)throw new Error(S.error||"暂时无法打开服务")}else _s(x)||window.dispatchEvent(new CustomEvent(bc,{detail:x}))}catch(T){c(T instanceof Error?T.message:"暂时无法切换服务")}},k=x=>{const T=R.items.find(v=>v.service?.targetPeerId===x.targetPeerId),S=r.find(v=>v.targetPeerId&&v.targetPeerId===x.targetPeerId||v.origin===(x.serviceOrigin||x.url));return{phase:T?.phase,running:T?.runningCount??S?.runningCount??0,review:T?.reviewCount??S?.reviewCount??0}},N=x=>{const T=k(x);return T.review?p.jsxs("span",{className:"inline-flex shrink-0 items-center gap-0.5 text-[color:var(--warning)]",title:"等待处理",children:[p.jsx(Jp,{size:11}),T.review]}):T.phase==="connecting"||T.phase==="reconnecting"?p.jsx(je,{size:12,className:"shrink-0 animate-spin","aria-label":"正在连接"}):T.phase==="offline"||T.phase==="login"?p.jsx("span",{className:"shrink-0 text-[color:var(--warning)]",title:T.phase==="login"?"需要登录":"连接已断开",children:"!"}):T.running?p.jsx("span",{className:"shrink-0 text-[color:var(--success)]",title:"运行中",children:T.running}):null};return e.length<=1?null:p.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:[p.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?p.jsx(Qp,{size:16}):p.jsx(XE,{size:16})}),l&&p.jsxs("div",{className:"flex w-full items-center gap-1 md:gap-0 md:rounded-xl md:bg-surface md:p-1",children:[p.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:e.map(x=>p.jsx("button",{type:"button",onClick:()=>{y(x)},"aria-current":x.targetPeerId===s?"page":void 0,"aria-label":x.label,title:x.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 ${e.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 ${x.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:p.jsxs("span",{className:`inline-flex min-w-0 items-center justify-center gap-1 rounded-lg px-2 py-1.5 ${x.targetPeerId===s?"bg-surface-elevated md:bg-transparent":""}`,children:[p.jsx("span",{className:"max-w-[11rem] truncate md:hidden",children:G2(x,e)}),p.jsx("span",{className:"hidden truncate md:inline",children:x.label}),N(x)]})},x.id))}),p.jsx("button",{type:"button",onClick:pg,"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:p.jsx(tg,{size:18})})]}),a&&p.jsx("p",{role:"alert",className:"mt-1 text-[11px] text-[color:var(--warning)]",children:a})]})}function Wo(t,e,n=new Set){for(const r of t.keys()){if(t.size<=e)break;n.has(r)||t.delete(r)}return t}function gt(t,e){if(typeof window>"u")return null;try{const n=window.localStorage.getItem(t);if(n===null||n==="")return null;const r=JSON.parse(n);return e(r)?r:null}catch{return null}}function Ge(t,e){if(!(typeof window>"u"))try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}function Mr(t){if(!(typeof window>"u"))try{window.localStorage.removeItem(t)}catch{}}const no=new Map,ir=new Map,is=new Map;function pR(t,e,n){if(typeof window>"u")return;const r=Date.now(),o=is.get(t)??0,s=r-o;if(s>=n){is.set(t,r),Ge(t,e);return}if(ir.set(t,e),no.has(t))return;const i=n-s,a=setTimeout(()=>{no.delete(t);const c=ir.get(t);ir.delete(t),is.set(t,Date.now()),c!==void 0&&Ge(t,c)},i);no.set(t,a)}function Y2(t){const e=no.get(t);e&&(clearTimeout(e),no.delete(t));const n=ir.get(t);n!==void 0&&(ir.delete(t),is.set(t,Date.now()),Ge(t,n))}function gR(t,e){if(t===e)return!0;try{return JSON.stringify(t)===JSON.stringify(e)}catch{return!1}}if(typeof window<"u"){const t=()=>{for(const e of ir.keys())Y2(e)};window.addEventListener("pagehide",t),window.addEventListener("termdock:before-update",t),document.addEventListener("visibilitychange",()=>{document.hidden&&t()})}const Z2=600,ho=320,J2=280,Q2=5;function mR(t,e,n=0){const r=Math.max(ho,e-Math.max(0,n)-Q2*(n>0?2:1)-J2);return Math.min(r,Math.max(ho,t))}const jg="termdock:right-sidebar:tabs-by-session:v2",Ug="termdock:right-sidebar:explorer-roots-by-session:v2",Pl="termdock:right-sidebar:pinned-explorer-roots:v1",$g="termdock:right-sidebar:selected-files-by-session:v2",Hg="termdock:right-sidebar:show-hidden-files:v1",vc="termdock:right-sidebar:file-sort-modes:v1",Sc="termdock:right-sidebar:nested-git-scan-roots:v1",of="termdock-sidebar-group-by-folder",qg="termdock-sidebar-collapsed-folder-groups",Kg="termdock-left-sidebar-pinned",zg="termdock-left-sidebar-width",Wg="termdock-right-sidebar-pinned",Nl="termdock:right-sidebar:pinned-by-session:v1",Gg="termdock-right-sidebar-width",Ll="termdock:right-sidebar:widths-by-session:v1",Vg="termdock:right-sidebar:split-state-initialized:v1",Xg="termdock-right-sidebar-layout-preference";function eI(){if(typeof window>"u")return!0;try{const t=window.localStorage.getItem(Kg);return t===null?!0:t==="1"}catch{return!0}}function sf(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Kg,t?"1":"0")}catch{}}function tI(){if(typeof window>"u")return 300;try{const t=window.localStorage.getItem(zg);if(!t)return 300;const e=parseInt(t,10);return Number.isFinite(e)&&e>=200&&e<=500?e:300}catch{return 300}}function nI(t){if(!(typeof window>"u"))try{window.localStorage.setItem(zg,String(t))}catch{}}function as(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Wg)==="1"}catch{return!1}}function rI(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Wg,t?"1":"0")}catch{}}function Fs(){return gt(Nl,t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.values(t).every(e=>typeof e=="boolean"))??{}}function va(t,e){if(!t){rI(e);return}Ge(Nl,{...Fs(),[t]:e})}function cs(){if(typeof window>"u")return 760;try{const t=window.localStorage.getItem(Gg);if(!t)return 760;const e=parseInt(t,10);return Number.isFinite(e)&&e>=ho?e:760}catch{return 760}}function oI(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Gg,String(t))}catch{}}function sI(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="number"&&Number.isFinite(e)&&e>=ho)}function Ms(){return gt(Ll,sI)??{}}function af(t,e){if(!t){oI(e);return}Ge(Ll,{...Ms(),[t]:e})}function iI(){if(typeof window>"u")return"auto";try{const t=window.localStorage.getItem(Xg);return t==="narrow"||t==="wide"?t:"auto"}catch{return"auto"}}function aI(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Xg,t)}catch{}}function wR(t,e,n){return!e||n==="auto"?t<Z2:n==="narrow"}function cI(){return!0}function cf(t){if(!(typeof window>"u"))try{t?window.localStorage.setItem(of,"1"):window.localStorage.setItem(of,"0")}catch{}}function lI(){if(typeof window>"u")return new Set;try{const t=window.localStorage.getItem(qg);if(!t)return new Set;const e=JSON.parse(t);return Array.isArray(e)?new Set(e.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function dI(t){if(!(typeof window>"u"))try{window.localStorage.setItem(qg,JSON.stringify([...t]))}catch{}}function uI(t){return t==="git"||t==="files"||t==="diff"}function fI(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(uI)}function xc(){return gt(jg,fI)??{}}function Sa(t,e){t&&Ge(jg,{...xc(),[t]:e})}function hI(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string")}function lf(){return gt(Ug,hI)??{}}function Go(t){Ge(Ug,t)}function pI(t){return t!==null&&typeof t=="object"&&typeof t.path=="string"&&(t.kind==="file"||t.kind==="directory")}function gI(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>Array.isArray(e)&&e.every(n=>typeof n=="string"||pI(n)))}function Yg(t){const e=new Set,n=[];for(const r of t){const o=typeof r=="string"?{path:r,kind:"directory"}:r;!o.path||e.has(o.path)||(e.add(o.path),n.push(o))}return n}function mI(){const t=gt(Pl,gI)??{},e={};for(const[n,r]of Object.entries(t))e[n]=Yg(r);return e}function df(t){Ge(Pl,t)}function wI(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string")}function Ec(){return gt($g,wI)??{}}function jr(t,e){if(!t)return;const n={...Ec()};e?n[t]=e:delete n[t],Ge($g,n)}function po(t,e){return e?t?`${t}\0${e}`:e:null}function js(t,e,n){return n?`split-workspace\0${n}`:po(t,e)}function yR(t,e,n){const r=Ms(),o=js(t,e,n);if(o&&r[o]!==void 0)return r[o];if(n){const s=po(t,e);if(s&&r[s]!==void 0)return r[s]}return cs()}function bR(t,e,n){const r=Fs(),o=js(t,e,n);if(o&&r[o]!==void 0)return r[o];if(n){const s=po(t,e);if(s&&r[s]!==void 0)return r[s]}return as()}function Zg(){const t=gt(Vg,e=>Array.isArray(e)&&e.every(n=>typeof n=="string"));return new Set(t??[])}function yI(t){const e=Zg();e.has(t)||(e.add(t),Ge(Vg,[...e]))}function bI(t){return typeof t=="boolean"}function vI(){return gt(Hg,bI)??!1}function SI(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>e==="modified")}function xI(){return gt(vc,SI)??{}}function EI(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>e===!0)}function AI(){return gt(Sc,EI)??{}}let Ur=null;const xa=new Map;let $r=null;const Vo=new Map;let Hr=null;const Ea=globalThis.crypto?.randomUUID?.()??`pins-${Math.random().toString(36).slice(2)}`;function kI(t){const e=t.replace(/\/+$/,"")||"/";return e==="/"?"/":e.slice(0,e.lastIndexOf("/"))||"/"}function Mn(t,e){const n=t.replace(/\/+$/,"")||"/";return e===n||e.startsWith(`${n}/`)}function uf(t,e="name"){return[...t].sort((n,r)=>{if(n.type==="directory"&&r.type!=="directory")return-1;if(n.type!=="directory"&&r.type==="directory")return 1;if(e==="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 II(t){return t.entry?{name:t.entry.name,path:t.entry.path,type:t.entry.type,isSymlink:t.entry.isSymlink,modified:t.entry.modified,expanded:!1,loaded:!1,children:t.entry.type==="directory"?[]:void 0}:null}const De=ci(t=>({leftOpen:!1,rightOpen:!1,leftPinned:eI(),leftSidebarWidth:tI(),rightPinned:as(),rightSidebarWidth:cs(),rightSidebarLayoutPreference:iI(),rightTab:"files",rightSearchOpen:!1,rootPath:null,contextKey:null,rightSidebarWidthContextKey:null,explorerRoot:null,explorerRootCache:lf(),pinnedExplorerRootsCache:mI(),pinnedExplorerRootsHydrated:!1,expandedPaths:new Set,selectedFilePath:null,directoryCache:new Map,fileSortModes:xI(),fileSortModesHydrated:!1,nestedGitScanRoots:AI(),nestedGitScanRootsHydrated:!1,showHiddenFiles:vI(),groupByFolder:cI(),collapsedGroups:lI(),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:()=>t({leftOpen:!0}),closeLeft:()=>t({leftOpen:!1}),toggleLeft:()=>t(e=>({leftOpen:!e.leftOpen,rightOpen:e.leftOpen?e.rightOpen:!1})),toggleLeftPinned:()=>t(e=>{const n=!e.leftPinned;return sf(n),{leftPinned:n,leftOpen:!0}}),setLeftPinned:e=>t(()=>(sf(e),{leftPinned:e})),setLeftSidebarWidth:e=>t(n=>{const r=Math.min(Math.max(e,200),500);return n.leftSidebarWidth===r?n:(nI(r),{leftSidebarWidth:r})}),toggleRightPinned:()=>t(e=>{const n=!e.rightPinned;return va(e.rightSidebarWidthContextKey,n),{rightPinned:n,rightOpen:!0}}),setRightPinned:e=>t(n=>(va(n.rightSidebarWidthContextKey,e),{rightPinned:e})),setRightSidebarWidth:e=>t(n=>{const r=Math.max(e,ho);return n.rightSidebarWidth===r?n:(af(n.rightSidebarWidthContextKey,r),{rightSidebarWidth:r})}),setRightSidebarLayoutPreference:e=>t(n=>n.rightSidebarLayoutPreference===e?n:(aI(e),{rightSidebarLayoutPreference:e})),openRight:()=>t({rightOpen:!0}),closeRight:()=>t({rightOpen:!1,rightSearchOpen:!1}),toggleRight:()=>t(e=>({rightOpen:!e.rightOpen,rightSearchOpen:e.rightOpen?!1:e.rightSearchOpen,leftOpen:e.rightOpen?e.leftOpen:!1})),closeAll:()=>t({leftOpen:!1,rightOpen:!1,rightSearchOpen:!1}),setRightTab:e=>t(n=>(Sa(n.contextKey,e),{rightTab:e})),openRightSearch:()=>t({rightSearchOpen:!0}),closeRightSearch:()=>t({rightSearchOpen:!1}),setRightSearchOpen:e=>t({rightSearchOpen:e}),setRootPath:(e,n=null,r=null)=>t(o=>{const s=po(n,e),i=js(n,e,r),a=r?i:s;if(o.contextKey===a&&o.rightSidebarWidthContextKey===i)return e===o.rootPath?o:{rootPath:e};const c=new Map(o.rootDataCache);o.rootPath&&c.set(o.rootPath,{directoryCache:o.directoryCache,changedFiles:o.changedFiles,gitBundleError:o.gitBundleError,gitBundleLastLoadedAt:o.gitBundleLastLoadedAt,gitBundleCacheInfo:o.gitBundleCacheInfo}),Wo(c,12,new Set(e?[e]:[]));const l=e?c.get(e):void 0,d=e===o.rootPath,u=new Map(o.projectStateCache);o.contextKey&&u.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 f=r?Zg().has(r):!1;let h={...lf(),...o.explorerRootCache};const g=!!r&&!f,m=g&&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}:u.get(s):void 0;if(g&&r){const S=m?.rightTab??(s?xc()[s]:void 0)??"files",v=m?.explorerRoot??(s?o.explorerRootCache[s]:void 0)??e,A=m?.selectedFilePath??(s?Ec()[s]:void 0)??null,_={rightTab:S,explorerRoot:v,expandedPaths:new Set(m?.expandedPaths??[]),selectedFilePath:A,directoryCache:new Map(m?.directoryCache??[]),changedFiles:new Map(m?.changedFiles??[]),gitBundleError:m?.gitBundleError??null,gitBundleLastLoadedAt:m?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:m?.gitBundleCacheInfo??null};a&&(u.set(a,_),Sa(a,S),jr(a,A),v&&(h={...h,[a]:v},Go(h))),yI(r)}Wo(u,12,new Set(a?[a]:[]));const b=a?u.get(a):void 0,w=a?xc()[a]:void 0,R=Ms();let y=i?R[i]:void 0;r&&i&&y===void 0&&(y=(s?R[s]:void 0)??cs(),af(i,y));const k=a?h[a]:void 0,N=Fs();let x=i?N[i]:void 0;r&&i&&x===void 0&&(x=(s?N[s]:void 0)??as(),va(i,x));const T=a?Ec()[a]:void 0;return{rootPath:e,contextKey:a,rightSidebarWidthContextKey:i,rightSidebarWidth:y??cs(),rightPinned:x??as(),rightOpen:o.rightSidebarWidthContextKey===i?o.rightOpen:!1,rightTab:b?.rightTab??w??"files",explorerRoot:b?.explorerRoot??k??e,expandedPaths:b?new Set(b.expandedPaths):new Set,selectedFilePath:b?.selectedFilePath??T??null,explorerRootCache:h,directoryCache:l?.directoryCache??new Map,changedFiles:l?.changedFiles??new Map,gitBundleLoading:d?o.gitBundleLoading:!1,gitBundleSlow:d?o.gitBundleSlow:!1,gitBundleLoadingOwner:d?o.gitBundleLoadingOwner:null,gitBundleError:l?.gitBundleError??null,gitBundleLastLoadedAt:l?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:l?.gitBundleCacheInfo??null,rootDataCache:c,projectStateCache:u}}),inheritRightSidebarStateFromSplitWorkspace:(e,n)=>t(r=>{if(!e||n.length===0)return r;const o=Ms(),s=js(null,null,e);if(!s)return r;const i=o[s]??(r.rightSidebarWidthContextKey===s?r.rightSidebarWidth:void 0),a=Fs(),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};for(const h of n){const g=po(h.sessionId,h.rootPath);g&&(i!==void 0&&(d[g]=i),c!==void 0&&(a[g]=c),l&&(u.set(g,{...l,expandedPaths:new Set(l.expandedPaths),directoryCache:new Map(l.directoryCache),changedFiles:new Map(l.changedFiles)}),Sa(g,l.rightTab),jr(g,l.selectedFilePath),l.explorerRoot?f[g]=l.explorerRoot:delete f[g]))}return i!==void 0&&Ge(Ll,d),l&&Go(f),c!==void 0&&Ge(Nl,a),Wo(u,12,new Set(r.contextKey?[r.contextKey]:[])),{projectStateCache:u,explorerRootCache:f}}),setExplorerRoot:e=>t(n=>{if(n.explorerRoot===e)return n;const r={...n.explorerRootCache};return n.contextKey&&e&&(r[n.contextKey]=e,Go(r)),{explorerRoot:e,explorerRootCache:r}}),resetExplorerToProject:()=>t(e=>{if(e.explorerRoot===e.rootPath)return e;const n={...e.explorerRootCache};return e.contextKey&&e.rootPath&&(n[e.contextKey]=e.rootPath,Go(n)),{explorerRoot:e.rootPath,explorerRootCache:n}}),pinExplorerRoot:(e,n="directory")=>t(r=>{if(!r.rootPath||!e)return r;const o=r.rootPath,s=r.pinnedExplorerRootsCache[r.rootPath]??[];if(s.some(a=>a.path===e))return r;const i={...r.pinnedExplorerRootsCache,[r.rootPath]:[{path:e,kind:n},...s].slice(0,12)};return df(i),(async()=>{try{await De.getState().hydratePinnedExplorerRoots();const a=await Et({pinnedExplorerRoot:{rootPath:o,path:e,kind:n,pinned:!0},pinnedExplorerRootsOrigin:Ea});De.getState().syncPinnedExplorerRoots(a.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:i}}),unpinExplorerRoot:e=>t(n=>{if(!n.rootPath||!e)return n;const r=n.rootPath,o=n.pinnedExplorerRootsCache[n.rootPath]??[],s=o.find(c=>c.path===e);if(!o.some(c=>c.path===e))return n;const i=o.filter(c=>c.path!==e),a={...n.pinnedExplorerRootsCache};return i.length>0?a[n.rootPath]=i:delete a[n.rootPath],df(a),(async()=>{try{await De.getState().hydratePinnedExplorerRoots();const c=await Et({pinnedExplorerRoot:{rootPath:r,path:e,kind:s?.kind??"directory",pinned:!1},pinnedExplorerRootsOrigin:Ea});De.getState().syncPinnedExplorerRoots(c.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:a}}),hydratePinnedExplorerRoots:async()=>{if(!De.getState().pinnedExplorerRootsHydrated)return Hr||(Hr=(async()=>{const e=De.getState().pinnedExplorerRootsCache;let r=(await sr()).pinnedExplorerRoots??{};Object.keys(r).length===0&&Object.keys(e).length>0&&(r=(await Et({pinnedExplorerRoots:e,pinnedExplorerRootsOrigin:Ea})).pinnedExplorerRoots??e),De.getState().syncPinnedExplorerRoots(r)})().finally(()=>{Hr=null}),Hr)},syncPinnedExplorerRoots:e=>t(()=>{const n={};for(const[r,o]of Object.entries(e)){const s=Yg(o);s.length>0&&(n[r]=s.slice(0,12))}return Mr(Pl),{pinnedExplorerRootsCache:n,pinnedExplorerRootsHydrated:!0}}),toggleExpanded:e=>t(n=>{const r=new Set(n.expandedPaths);return r.has(e)?r.delete(e):r.add(e),{expandedPaths:r}}),selectFile:e=>t(n=>(jr(n.contextKey,e),{selectedFilePath:e})),toggleShowHiddenFiles:()=>t(e=>{const n=!e.showHiddenFiles;Ge(Hg,n);const r=new Map(e.projectStateCache);for(const[o,s]of r)r.set(o,{...s,directoryCache:new Map});return{showHiddenFiles:n,directoryCache:new Map,projectStateCache:r}}),toggleGroupByFolder:()=>t(e=>{const n=!e.groupByFolder;return cf(n),{groupByFolder:n}}),setGroupByFolder:e=>t(n=>n.groupByFolder===e?n:(cf(e),{groupByFolder:e})),toggleGroupCollapsed:e=>t(n=>{const r=new Set(n.collapsedGroups);return r.has(e)?r.delete(e):r.add(e),dI(r),{collapsedGroups:r}}),setDirectoryCache:(e,n)=>t(r=>{const o=new Map(r.directoryCache);return o.delete(e),o.set(e,n),Wo(o,128,new Set([...r.expandedPaths,e,r.explorerRoot??r.rootPath??""])),{directoryCache:o}}),reconcileDirectoryCache:(e,n)=>t(r=>{const o=r.directoryCache.get(e);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(e,uf(c,r.fileSortModes[e]??"name"));for(const d of o)if(!i.has(d.path))for(const u of a.keys())Mn(d.path,u)&&a.delete(u);let l=r.selectedFilePath;return l&&o.find(u=>!i.has(u.path)&&Mn(u.path,l))&&(l=null,jr(r.rootPath,null)),{directoryCache:a,selectedFilePath:l}}),hydrateFileSortModes:async()=>{if(!De.getState().fileSortModesHydrated)return Ur||(Ur=(async()=>{const e=De.getState().fileSortModes;let r=(await sr()).fileSortModes??{};Object.keys(r).length===0&&Object.keys(e).length>0&&(r=(await Et({fileSortModes:e})).fileSortModes??e),Mr(vc),t({fileSortModes:r,fileSortModesHydrated:!0,directoryCache:new Map})})().finally(()=>{Ur=null}),Ur)},setDirectorySortMode:async(e,n)=>{try{await De.getState().hydrateFileSortModes()}catch{}const r=De.getState().fileSortModes[e]??"name",o=(xa.get(e)??0)+1;xa.set(e,o),t(s=>{const i={...s.fileSortModes};n==="modified"?i[e]=n:delete i[e];const a=new Map(s.directoryCache);return a.delete(e),{fileSortModes:i,fileSortModesHydrated:!0,directoryCache:a}});try{await Et({fileSortMode:{path:e,mode:n}}),Mr(vc)}catch{if(xa.get(e)!==o)return;t(s=>{const i={...s.fileSortModes};r==="modified"?i[e]=r:delete i[e];const a=new Map(s.directoryCache);return a.delete(e),{fileSortModes:i,directoryCache:a}})}},hydrateNestedGitScanRoots:async()=>{if(!De.getState().nestedGitScanRootsHydrated)return $r||($r=(async()=>{const n=(await sr()).nestedGitScanRoots??{};Mr(Sc),t({nestedGitScanRoots:n,nestedGitScanRootsHydrated:!0})})().finally(()=>{$r=null}),$r)},setNestedGitScanRoot:async(e,n)=>{try{await De.getState().hydrateNestedGitScanRoots()}catch{}const r=!!De.getState().nestedGitScanRoots[e],o=(Vo.get(e)??0)+1;Vo.set(e,o),t(s=>{const i={...s.nestedGitScanRoots};return n?i[e]=!0:delete i[e],{nestedGitScanRoots:i,nestedGitScanRootsHydrated:!0}});try{const s=await Et({nestedGitScanRoot:{rootPath:e,enabled:n}});if(Vo.get(e)!==o)return;t({nestedGitScanRoots:s.nestedGitScanRoots??{}}),Mr(Sc)}catch{if(Vo.get(e)!==o)return;t(s=>{const i={...s.nestedGitScanRoots};return r?i[e]=!0:delete i[e],{nestedGitScanRoots:i}})}},invalidateDirectoryCache:(e,n=!1)=>t(r=>{const o=new Map(r.directoryCache);for(const s of o.keys())(s===e||n&&Mn(e,s))&&o.delete(s);return{directoryCache:o}}),applyFileWatchEvents:e=>t(n=>{if(e.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 e){if(d.type==="rescan-required"){c=!0,s&&Mn(d.path,s)&&l(s);continue}const u=kI(d.path),f=r.get(u);if(d.type==="deleted"){if(l(d.path),s&&Mn(d.path,s)&&(s=null,jr(n.rootPath,null)),f){const b=f.filter(w=>w.path!==d.path);b.length!==f.length&&(r.set(u,b),i=!0)}for(const b of r.keys())Mn(d.path,b)&&(r.delete(b),i=!0);continue}l(d.path);const h=II(d);if(!h||!f)continue;const g=f.find(b=>b.path===h.path),m=uf(g?f.map(b=>b.path===h.path?{...b,...h,children:b.children}:b):[...f,h],n.fileSortModes[u]??"name");r.set(u,m),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:()=>t(e=>({fileWatchEpoch:e.fileWatchEpoch+1})),setChangedFiles:e=>t({changedFiles:e}),beginGitBundleLoading:e=>t({gitBundleLoading:!0,gitBundleSlow:!1,gitBundleLoadingOwner:e}),setGitBundleSlowFor:(e,n)=>t(r=>r.gitBundleLoadingOwner===e?{gitBundleSlow:n}:r),finishGitBundleLoading:e=>t(n=>n.gitBundleLoadingOwner===e?{gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}:n),resetGitBundleLoading:()=>t({gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}),setGitBundleError:e=>t({gitBundleError:e}),markGitBundleLoaded:(e=null)=>t({gitBundleLastLoadedAt:Date.now(),gitBundleCacheInfo:e})})),Aa=(()=>{if(location.hash.startsWith("#termdock-invite="))try{return Ds(location.href)}catch{return}finally{history.replaceState(null,"",location.pathname+location.search)}})(),Ac="termdock-secure-open-session";let ka,qr;function CI(){try{const t=JSON.parse(sessionStorage.getItem(Ac)??"null");return t?.serviceId===re()?.targetPeerId?t.sessionId:void 0}catch{return}}function RI({children:t}){const[e,n]=O.useState(Aa),[r,o]=O.useState(!1),[s,i]=O.useState(!!Aa),[a,c]=O.useState(!Aa),[l,d]=O.useState(!1),[u,f]=O.useState("正在连接服务…"),[h,g]=O.useState([]),[m,b]=O.useState([]),[w,R]=O.useState(!1),[y,k]=O.useState(!1),[N,x]=O.useState(""),[T,S]=O.useState(!1),[v,A]=O.useState(""),[_,B]=O.useState(re()?.serviceName??location.hostname),[I,E]=O.useState(CI);O.useEffect(()=>{(!r&&!a||r&&(!w||I))&&Un({rendered:!0})},[r,a,w,I]),O.useEffect(()=>{tt().then(U=>x(U.peerId)).catch(()=>d(!0))},[]),O.useEffect(()=>{const U=q=>{const{origin:K,sessionId:X}=q.detail;try{const W=JSON.parse(localStorage.getItem("termdock.federation.connections.v1")??"[]").find(G=>br(G).some(Y=>new URL(Y).origin===new URL(K).origin));if(!W){i(!0);return}if(ht()?.focusSession(W.targetPeerId,X))return;sessionStorage.setItem(Ac,JSON.stringify({serviceId:W.targetPeerId,sessionId:X})),Qe(W).then(()=>{E(X),o(!0)}).catch(()=>{d(!0),i(!0)})}catch{i(!0)}};return window.addEventListener("termdock:open-remote-session",U),()=>window.removeEventListener("termdock:open-remote-session",U)},[]);const P=async(U=5e3)=>{const q=await st(),K=await yr(q,{timeoutMs:U}),X=vE(),z=fE()?.targetPeerId;Promise.all([C1(),Ke()]).then(([G,Y])=>{const Q=Y.find(ce=>ce.targetPeerId===z),ae=X==="relay"?`经 ${Q?.label||z?.slice(-12)||"入口服务"} 中转`:"直连";return q.request({type:"device-name",name:cg(),onlyIfMissing:!0,profile:{...G,route:ae}})}).catch(()=>{}),R(K.fullService),k(K.canManage),o(!0),c(!1),d(!1);const W=re();Un({phase:"ready",...W?{service:{...W,id:W.targetPeerId,label:W.serviceName||location.host}}:{}}),Qo()&&bE()};O.useEffect(()=>{let U=!1,q=!1,K=0,X;const z=async()=>{if(U||q||K&&(document.hidden||!Qo()))return;if(!navigator.onLine){c(!0),d(!0),f("网络已断开,恢复后会自动连接"),Un({phase:"offline"});return}q=!0,clearTimeout(X);const ie=performance.now(),$e=rn();try{if(Hs&&!re())throw new Error("工作区的服务记录已移除,请重新添加服务。");qr??=window.termdockDesktop?.getServiceConnection?.();const ke=await qr;if(ke?.invitation){n(Ds(ke.invitation)),i(!0),c(!1);return}if(!re()){if(e){c(!1);return}if(ka??=(async()=>{if(ke?.targetPeerId){await Qe({...ke,targetPeerId:ke.targetPeerId,serviceName:ke.label});return}const Ve=await window.termdockDesktop?.getLocalInvite?.();Ve?await Qe(Ve):await hE()})(),await ka,!re()){U||(o(!1),c(!1),d(!1));return}}U||await P($e?.canSwitchTransport?2500:5e3),K=0,performance.measure("termdock:connection-ready",{start:ie,end:performance.now()})}catch(ke){if(U)return;ke instanceof et?(o(!1),c(!1),i(!1),d(!1),Un({phase:"login"})):($e&&rn()===$e&&Wp(),d(!0),c(!0),ka=void 0,f("连接暂未恢复,正在重试…"),Un({phase:"reconnecting"}),K++,X=setTimeout(()=>{z()},Math.min(5e3,300*2**Math.min(K-1,5))),console.debug("[connection] retry",{elapsedMs:Math.round(performance.now()-ie),attempt:K,reason:ke instanceof Error?ke.message:"unknown"}))}finally{q=!1}},W=()=>{document.visibilityState==="visible"&&Qo()&&z()},G=W,Y=()=>{K=0,W()},Q=()=>{De.getState().openLeft(),W()};window.addEventListener(fo,W),window.addEventListener(oc,Q),ht()?.attach(ii(),window),z(),document.addEventListener("visibilitychange",G),window.addEventListener("focus",W),window.addEventListener("online",Y);const ae=navigator.connection;ae?.addEventListener("change",Y),window.addEventListener("auth:unauthorized",W),window.addEventListener(Je,W);const ce=setInterval(W,3e4);return()=>{U=!0,clearTimeout(X),clearInterval(ce),window.removeEventListener(fo,W),window.removeEventListener(oc,Q),document.removeEventListener("visibilitychange",G),window.removeEventListener("focus",W),window.removeEventListener("online",Y),ae?.removeEventListener("change",Y),window.removeEventListener("auth:unauthorized",W),window.removeEventListener(Je,W)}},[]);const C=async()=>{const U=rn();if(U){S(!0),A("");try{const q=await U.request({type:"session-list"});b(q.items)}catch{A("暂时无法读取终端列表,请重试。")}try{if(y){const q=await U.request({type:"grants-list"}),K=q.subjectLabels??{},X=await U.request({type:"route-access"}),z=await Ke(),W=(Array.isArray(X.grants)?X.grants:[]).map(G=>({id:`route:${G.id}`,subjectId:G.subjectId,scope:{kind:"service"},actions:["route.use"],routeTargetServiceId:G.targetServiceId,routeTargetName:z.find(Y=>Y.targetPeerId===G.targetServiceId)?.label||"指定服务",...G.active?{}:{revokedAt:G.revokedAt??0}}));g([...q.grants,...W].map(G=>({...G,label:K[G.subjectId],deviceProfile:q.deviceProfiles?.[G.subjectId]})))}else{const q=await U.request({type:"permissions"});g(q.grants??[])}}catch{A("暂时无法读取设备权限,请重试。")}finally{S(!1)}}};O.useEffect(()=>{const U=()=>{i(!0),r&&C()};return window.addEventListener(cc,U),()=>window.removeEventListener(cc,U)},[r,y]);const[D,M]=O.useState([]);O.useEffect(()=>{if(!s||!y||D.length)return;let U=!1;return(async()=>{const X=await(await(await st()).fetch("/api/terminal/settings")).json();if(U)return;const z=X.localAccess??{},W=[],G=(Y,Q)=>{try{const ae=new URL(Y);if(ae.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(ae.hostname))return;const ce=ae.origin;if(ce===location.origin||W.some(ie=>ie.url===ce))return;W.push({url:ce,label:Q})}catch{}};if(typeof z.url=="string"&&G(z.url,"服务域名"),Array.isArray(z.interfaces))for(const Y of z.interfaces){const Q=Y;typeof Q.url=="string"&&G(Q.url,typeof Q.label=="string"&&Q.label||typeof Q.name=="string"&&Q.name||"IP 地址")}M(W)})().catch(()=>{}),()=>{U=!0}},[s,y,D.length]);const F=async U=>{if(!U.pairingCode&&!U.routeCode&&re()?.targetPeerId!==U.targetPeerId&&ht()){const q={...U,id:U.targetPeerId,label:U.serviceName||new URL(U.serviceOrigin||U.url).host};if(await Tt(q),_s(q)){i(!1);return}}await Qe(U),qr&&(qr=qr.then(q=>q?{...q,invitation:void 0}:null)),n(void 0),E(void 0),sessionStorage.removeItem(Ac),B(U.serviceName??new URL(U.url).hostname),await P(),i(!1),d(!1)},L=async U=>{const q=window.termdockDesktop;if(q?.openServiceConnection){const K=await q.openServiceConnection(U);if(!K.ok)throw new Error(K.error||"暂时无法打开这台服务。");i(!1);return}if(_s(U)){i(!1);return}if(U.targetPeerId)try{await F({...U,targetPeerId:U.targetPeerId,serviceName:U.label});return}catch(K){if(!(K instanceof et))throw K}return fu(U.serviceOrigin||U.url)};O.useEffect(()=>{const U=q=>{L(q.detail).catch(K=>{i(!0),A(K instanceof Error?K.message:"暂时无法打开服务")})};return window.addEventListener(bc,U),()=>window.removeEventListener(bc,U)});const $=async(U,q)=>{if(U.includes("#termdock-invite=")){const X=Ds(U);if(window.termdockDesktop?.openServiceConnection){const z=await window.termdockDesktop.openServiceConnection({id:X.targetPeerId,url:X.url,label:X.serviceName||new URL(X.serviceOrigin||X.url).host,targetPeerId:X.targetPeerId,serviceOrigin:X.serviceOrigin,entryServiceId:X.entryServiceId},U);if(!z.ok)throw new Error(z.error||"暂时无法打开邀请。");i(!1);return}if(q!==void 0&&X.routeOnly){await hu(X,q),await P(),i(!1);return}try{await F(X)}catch(z){if(X.routeOnly&&z instanceof et)return{passwordRequired:!0};throw z}return}const K=_e(U);return window.termdockDesktop?.openServiceConnection?L({id:K,url:K,label:new URL(K).host}):fu(K,q)},H=async U=>{const q=await st(),{includeBackup:K=!0,entryAddress:X,...z}=U,W=re(),G=W?Zt(W):[];let Y;if(K&&G.length){for(const ce of G)try{const ie=await Xp({...W,targetPeerId:q.targetPeerId},ce);Y={...ce,routeCode:ie.routeCode};break}catch{}if(!Y)throw new Error("无法分享备用连接:需要入口管理员授权。也可以关闭此选项,生成直接连接邀请。")}let Q=W?.serviceOrigin||location.origin;if(X)try{Q=new URL(X).origin}catch{throw new Error("邀请接入地址无效。")}else if(["localhost","127.0.0.1","[::1]"].includes(new URL(Q).hostname)){const ie=await(await q.fetch("/api/terminal/settings")).json();typeof ie.localAccess?.url=="string"&&(Q=ie.localAccess.url)}const ae=await q.request({type:"invite-create",...z});if(typeof ae.code!="string"||typeof ae.expiresAt!="number")throw new Error("暂时无法生成邀请。");return{url:lg({v:1,serviceId:q.targetPeerId,code:ae.code,entryUrl:Y?.url||Q,serviceUrl:Q,name:_,entryServiceId:Y?.targetPeerId,routeCode:Y?.routeCode}),expiresAt:ae.expiresAt}};return p.jsxs(p.Fragment,{children:[r?w&&!I?t:p.jsx(cA,{client:rn(),initialSessionId:I}):a?p.jsx("div",{className:"flex h-full min-h-0 flex-col items-center justify-center bg-[var(--chrome-bg)] px-6 text-foreground",children:p.jsxs("div",{className:"flex w-full max-w-xs flex-col items-center text-center",children:[p.jsx("div",{className:"mb-5 flex h-12 w-12 items-center justify-center rounded-2xl bg-surface-2 text-muted-foreground","aria-hidden":"true",children:p.jsx(a1,{size:24,strokeWidth:1.5})}),p.jsx("h1",{className:"max-w-full truncate text-base font-medium tracking-tight",title:_,children:_}),p.jsxs("div",{role:"status",className:"mt-2 flex max-w-full items-center justify-center gap-2 text-xs leading-5 text-muted-foreground",children:[!l&&p.jsx(je,{size:13,className:"shrink-0 animate-spin motion-reduce:animate-none","aria-hidden":"true"}),p.jsx("span",{children:u})]}),l&&p.jsx("p",{className:"mt-2 text-xs leading-5 text-muted-foreground",children:"登录信息已保留"}),p.jsx("button",{type:"button",className:"mt-6 min-h-11 rounded-lg px-4 text-xs text-muted-foreground transition-colors hover:bg-surface-2 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>i(!0),children:"管理服务"})]})}):p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"fixed left-0 right-0 top-[var(--safe-top-inset)] z-chrome sm:right-auto sm:w-72",children:p.jsx(V2,{})}),p.jsx(q2,{onLoginSuccess:()=>{P().catch(()=>d(!0))}})]}),s&&p.jsx(oA,{onConnect:F,onClose:()=>i(!1),onAddService:$,onOpenService:L,onConnectWithPassword:async(U,q)=>{await hu(U,q),await P(),i(!1)},paired:r||!!re(),initialInvite:e,currentServiceName:_,currentServiceId:rn()?.targetPeerId||re()?.targetPeerId,currentServiceOrigin:re()?.serviceOrigin,currentIdentity:N,grants:h,sessions:m,loading:T,loadError:v,onRetry:()=>{C()},onRename:async(U,q)=>{await(await st()).request({type:"device-name",subjectId:U,name:q}),await C()},hasBackup:!!re()&&Zt(re()).length>0,inviteAddresses:D,onCreateInvite:y?H:void 0,onRevoke:y?async U=>{await(await st()).request(U.startsWith("route:")?{type:"route-revoke",grantId:U.slice(6)}:{type:"revoke",grantId:U}),await C()}:void 0})]})}function TI(t,e,n){const r=t?.name||"Error",o=t?.message||"Unexpected error";return["Termdock error report",`Time: ${n.capturedAt}`,`URL: ${n.url}`,`User agent: ${n.userAgent}`,"",`${r}: ${o}`,t?.stack?`
29
+ `})]})}const K2={activeKey:"root",items:[]},z2=()=>()=>{},W2=()=>K2,bc="termdock:open-saved-service";function V2(t,e){try{const n=new URL(t.serviceOrigin||t.url);return t.label!==n.host&&t.label!==n.origin?t.label:!e.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 t.label}}function hR(t,e,n){O.useEffect(()=>{window.termdockDesktop?.reportServiceActivity?.({runningCount:t,reviewCount:e})},[t,e]),O.useEffect(()=>{Un({runningCount:t,reviewCount:e,attentionSessions:n})},[t,e,n])}function G2({onReselect:t}){return window.termdockDesktop?null:p.jsx(X2,{onReselect:t})}function X2({onReselect:t}){const[e,n]=O.useState([]),[r,o]=O.useState([]),[s,i]=O.useState(re()?.targetPeerId),[a,c]=O.useState(""),[l,d]=O.useState(!1),[u,f]=O.useState(!1),h=O.useRef(0),g=O.useRef(!1);O.useEffect(()=>{let x=!1;const T=()=>{const S=h.current;sr().then(v=>{!x&&!g.current&&S===h.current&&d(v.serviceSwitcherExpanded===!0)}).catch(()=>{})};return T(),window.addEventListener(Je,T),()=>{x=!0,window.removeEventListener(Je,T)}},[]);const m=async()=>{if(g.current)return;const x=l;h.current+=1,g.current=!0,f(!0),d(!x),c("");try{const T=await Et({serviceSwitcherExpanded:!x});d(T.serviceSwitcherExpanded===!0)}catch{d(x),c("展开状态保存失败,请重试")}finally{g.current=!1,f(!1)}},b=O.useRef(null),w=ht(),R=O.useSyncExternalStore(w?.subscribe||z2,w?.snapshot||W2);O.useEffect(()=>{let x=!1,T=0;const S=()=>{const _=++T;i(re()?.targetPeerId),Ke().then(B=>{if(!(x||_!==T)){try{const C="termdock-secure-service-order",E=JSON.parse(localStorage.getItem(C)||"[]"),P=Array.isArray(E)?E.filter(F=>typeof F=="string"):[],I=F=>F.targetPeerId||F.id,D=[...P.filter(F=>B.some(L=>I(L)===F)),...B.map(I).filter(F=>!P.includes(F))];B.sort((F,L)=>D.indexOf(I(F))-D.indexOf(I(L)));const M=JSON.stringify(D);M!==localStorage.getItem(C)&&localStorage.setItem(C,M)}catch{}n(B)}}).catch(()=>{})};S();const v=Ws(S),A=window.termdockDesktop?.onServiceActivity?.(o);return window.addEventListener(Je,S),()=>{x=!0,v(),A?.(),window.removeEventListener(Je,S)}},[]),O.useEffect(()=>{const x=b.current,T=x?.querySelector('[aria-current="page"]');if(!x||!T)return;const S=T.offsetLeft,v=S+T.offsetWidth;S<x.scrollLeft?x.scrollLeft=S:v>x.scrollLeft+x.clientWidth&&(x.scrollLeft=v-x.clientWidth)},[s,e,l]);const y=async x=>{if(c(""),x.targetPeerId&&x.targetPeerId===s){t?.();return}try{const T=window.termdockDesktop;if(T?.openServiceConnection){const S=await T.openServiceConnection(x);if(!S.ok)throw new Error(S.error||"暂时无法打开服务")}else _s(x)||window.dispatchEvent(new CustomEvent(bc,{detail:x}))}catch(T){c(T instanceof Error?T.message:"暂时无法切换服务")}},k=x=>{const T=R.items.find(v=>v.service?.targetPeerId===x.targetPeerId),S=r.find(v=>v.targetPeerId&&v.targetPeerId===x.targetPeerId||v.origin===(x.serviceOrigin||x.url));return{phase:T?.phase,running:T?.runningCount??S?.runningCount??0,review:T?.reviewCount??S?.reviewCount??0}},N=x=>{const T=k(x);return T.review?p.jsxs("span",{className:"inline-flex shrink-0 items-center gap-0.5 text-[color:var(--warning)]",title:"等待处理",children:[p.jsx(Jp,{size:11}),T.review]}):T.phase==="connecting"||T.phase==="reconnecting"?p.jsx(je,{size:12,className:"shrink-0 animate-spin","aria-label":"正在连接"}):T.phase==="offline"||T.phase==="login"?p.jsx("span",{className:"shrink-0 text-[color:var(--warning)]",title:T.phase==="login"?"需要登录":"连接已断开",children:"!"}):T.running?p.jsx("span",{className:"shrink-0 text-[color:var(--success)]",title:"运行中",children:T.running}):null};return e.length<=1?null:p.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:[p.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?p.jsx(Qp,{size:16}):p.jsx(XE,{size:16})}),l&&p.jsxs("div",{className:"flex w-full items-center gap-1 md:gap-0 md:rounded-xl md:bg-surface md:p-1",children:[p.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:e.map(x=>p.jsx("button",{type:"button",onClick:()=>{y(x)},"aria-current":x.targetPeerId===s?"page":void 0,"aria-label":x.label,title:x.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 ${e.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 ${x.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:p.jsxs("span",{className:`inline-flex min-w-0 items-center justify-center gap-1 rounded-lg px-2 py-1.5 ${x.targetPeerId===s?"bg-surface-elevated md:bg-transparent":""}`,children:[p.jsx("span",{className:"max-w-[11rem] truncate md:hidden",children:V2(x,e)}),p.jsx("span",{className:"hidden truncate md:inline",children:x.label}),N(x)]})},x.id))}),p.jsx("button",{type:"button",onClick:pg,"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:p.jsx(tg,{size:18})})]}),a&&p.jsx("p",{role:"alert",className:"mt-1 text-[11px] text-[color:var(--warning)]",children:a})]})}function Wo(t,e,n=new Set){for(const r of t.keys()){if(t.size<=e)break;n.has(r)||t.delete(r)}return t}function gt(t,e){if(typeof window>"u")return null;try{const n=window.localStorage.getItem(t);if(n===null||n==="")return null;const r=JSON.parse(n);return e(r)?r:null}catch{return null}}function Ve(t,e){if(!(typeof window>"u"))try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}function Mr(t){if(!(typeof window>"u"))try{window.localStorage.removeItem(t)}catch{}}const no=new Map,ir=new Map,is=new Map;function pR(t,e,n){if(typeof window>"u")return;const r=Date.now(),o=is.get(t)??0,s=r-o;if(s>=n){is.set(t,r),Ve(t,e);return}if(ir.set(t,e),no.has(t))return;const i=n-s,a=setTimeout(()=>{no.delete(t);const c=ir.get(t);ir.delete(t),is.set(t,Date.now()),c!==void 0&&Ve(t,c)},i);no.set(t,a)}function Y2(t){const e=no.get(t);e&&(clearTimeout(e),no.delete(t));const n=ir.get(t);n!==void 0&&(ir.delete(t),is.set(t,Date.now()),Ve(t,n))}function gR(t,e){if(t===e)return!0;try{return JSON.stringify(t)===JSON.stringify(e)}catch{return!1}}if(typeof window<"u"){const t=()=>{for(const e of ir.keys())Y2(e)};window.addEventListener("pagehide",t),window.addEventListener("termdock:before-update",t),document.addEventListener("visibilitychange",()=>{document.hidden&&t()})}const Z2=600,ho=320,J2=280,Q2=5;function mR(t,e,n=0){const r=Math.max(ho,e-Math.max(0,n)-Q2*(n>0?2:1)-J2);return Math.min(r,Math.max(ho,t))}const jg="termdock:right-sidebar:tabs-by-session:v2",Ug="termdock:right-sidebar:explorer-roots-by-session:v2",Pl="termdock:right-sidebar:pinned-explorer-roots:v1",$g="termdock:right-sidebar:selected-files-by-session:v2",Hg="termdock:right-sidebar:show-hidden-files:v1",vc="termdock:right-sidebar:file-sort-modes:v1",Sc="termdock:right-sidebar:nested-git-scan-roots:v1",of="termdock-sidebar-group-by-folder",qg="termdock-sidebar-collapsed-folder-groups",Kg="termdock-left-sidebar-pinned",zg="termdock-left-sidebar-width",Wg="termdock-right-sidebar-pinned",Nl="termdock:right-sidebar:pinned-by-session:v1",Vg="termdock-right-sidebar-width",Ll="termdock:right-sidebar:widths-by-session:v1",Gg="termdock:right-sidebar:split-state-initialized:v1",Xg="termdock-right-sidebar-layout-preference";function eC(){if(typeof window>"u")return!0;try{const t=window.localStorage.getItem(Kg);return t===null?!0:t==="1"}catch{return!0}}function sf(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Kg,t?"1":"0")}catch{}}function tC(){if(typeof window>"u")return 300;try{const t=window.localStorage.getItem(zg);if(!t)return 300;const e=parseInt(t,10);return Number.isFinite(e)&&e>=200&&e<=500?e:300}catch{return 300}}function nC(t){if(!(typeof window>"u"))try{window.localStorage.setItem(zg,String(t))}catch{}}function as(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Wg)==="1"}catch{return!1}}function rC(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Wg,t?"1":"0")}catch{}}function Fs(){return gt(Nl,t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.values(t).every(e=>typeof e=="boolean"))??{}}function va(t,e){if(!t){rC(e);return}Ve(Nl,{...Fs(),[t]:e})}function cs(){if(typeof window>"u")return 760;try{const t=window.localStorage.getItem(Vg);if(!t)return 760;const e=parseInt(t,10);return Number.isFinite(e)&&e>=ho?e:760}catch{return 760}}function oC(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Vg,String(t))}catch{}}function sC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="number"&&Number.isFinite(e)&&e>=ho)}function Ms(){return gt(Ll,sC)??{}}function af(t,e){if(!t){oC(e);return}Ve(Ll,{...Ms(),[t]:e})}function iC(){if(typeof window>"u")return"auto";try{const t=window.localStorage.getItem(Xg);return t==="narrow"||t==="wide"?t:"auto"}catch{return"auto"}}function aC(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Xg,t)}catch{}}function wR(t,e,n){return!e||n==="auto"?t<Z2:n==="narrow"}function cC(){return!0}function cf(t){if(!(typeof window>"u"))try{t?window.localStorage.setItem(of,"1"):window.localStorage.setItem(of,"0")}catch{}}function lC(){if(typeof window>"u")return new Set;try{const t=window.localStorage.getItem(qg);if(!t)return new Set;const e=JSON.parse(t);return Array.isArray(e)?new Set(e.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function dC(t){if(!(typeof window>"u"))try{window.localStorage.setItem(qg,JSON.stringify([...t]))}catch{}}function uC(t){return t==="git"||t==="files"||t==="diff"||t==="android"}function fC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(uC)}function xc(){return gt(jg,fC)??{}}function Sa(t,e){t&&Ve(jg,{...xc(),[t]:e})}function hC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string")}function lf(){return gt(Ug,hC)??{}}function Vo(t){Ve(Ug,t)}function pC(t){return t!==null&&typeof t=="object"&&typeof t.path=="string"&&(t.kind==="file"||t.kind==="directory")}function gC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>Array.isArray(e)&&e.every(n=>typeof n=="string"||pC(n)))}function Yg(t){const e=new Set,n=[];for(const r of t){const o=typeof r=="string"?{path:r,kind:"directory"}:r;!o.path||e.has(o.path)||(e.add(o.path),n.push(o))}return n}function mC(){const t=gt(Pl,gC)??{},e={};for(const[n,r]of Object.entries(t))e[n]=Yg(r);return e}function df(t){Ve(Pl,t)}function wC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string")}function Ec(){return gt($g,wC)??{}}function jr(t,e){if(!t)return;const n={...Ec()};e?n[t]=e:delete n[t],Ve($g,n)}function po(t,e){return e?t?`${t}\0${e}`:e:null}function js(t,e,n){return n?`split-workspace\0${n}`:po(t,e)}function yR(t,e,n){const r=Ms(),o=js(t,e,n);if(o&&r[o]!==void 0)return r[o];if(n){const s=po(t,e);if(s&&r[s]!==void 0)return r[s]}return cs()}function bR(t,e,n){const r=Fs(),o=js(t,e,n);if(o&&r[o]!==void 0)return r[o];if(n){const s=po(t,e);if(s&&r[s]!==void 0)return r[s]}return as()}function Zg(){const t=gt(Gg,e=>Array.isArray(e)&&e.every(n=>typeof n=="string"));return new Set(t??[])}function yC(t){const e=Zg();e.has(t)||(e.add(t),Ve(Gg,[...e]))}function bC(t){return typeof t=="boolean"}function vC(){return gt(Hg,bC)??!1}function SC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>e==="modified")}function xC(){return gt(vc,SC)??{}}function EC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>e===!0)}function AC(){return gt(Sc,EC)??{}}let Ur=null;const xa=new Map;let $r=null;const Go=new Map;let Hr=null;const Ea=globalThis.crypto?.randomUUID?.()??`pins-${Math.random().toString(36).slice(2)}`;function kC(t){const e=t.replace(/\/+$/,"")||"/";return e==="/"?"/":e.slice(0,e.lastIndexOf("/"))||"/"}function Mn(t,e){const n=t.replace(/\/+$/,"")||"/";return e===n||e.startsWith(`${n}/`)}function uf(t,e="name"){return[...t].sort((n,r)=>{if(n.type==="directory"&&r.type!=="directory")return-1;if(n.type!=="directory"&&r.type==="directory")return 1;if(e==="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 CC(t){return t.entry?{name:t.entry.name,path:t.entry.path,type:t.entry.type,isSymlink:t.entry.isSymlink,modified:t.entry.modified,expanded:!1,loaded:!1,children:t.entry.type==="directory"?[]:void 0}:null}const De=ci(t=>({leftOpen:!1,rightOpen:!1,leftPinned:eC(),leftSidebarWidth:tC(),rightPinned:as(),rightSidebarWidth:cs(),rightSidebarLayoutPreference:iC(),rightTab:"files",rightSearchOpen:!1,rootPath:null,contextKey:null,rightSidebarWidthContextKey:null,explorerRoot:null,explorerRootCache:lf(),pinnedExplorerRootsCache:mC(),pinnedExplorerRootsHydrated:!1,expandedPaths:new Set,selectedFilePath:null,directoryCache:new Map,fileSortModes:xC(),fileSortModesHydrated:!1,nestedGitScanRoots:AC(),nestedGitScanRootsHydrated:!1,showHiddenFiles:vC(),groupByFolder:cC(),collapsedGroups:lC(),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:()=>t({leftOpen:!0}),closeLeft:()=>t({leftOpen:!1}),toggleLeft:()=>t(e=>({leftOpen:!e.leftOpen,rightOpen:e.leftOpen?e.rightOpen:!1})),toggleLeftPinned:()=>t(e=>{const n=!e.leftPinned;return sf(n),{leftPinned:n,leftOpen:!0}}),setLeftPinned:e=>t(()=>(sf(e),{leftPinned:e})),setLeftSidebarWidth:e=>t(n=>{const r=Math.min(Math.max(e,200),500);return n.leftSidebarWidth===r?n:(nC(r),{leftSidebarWidth:r})}),toggleRightPinned:()=>t(e=>{const n=!e.rightPinned;return va(e.rightSidebarWidthContextKey,n),{rightPinned:n,rightOpen:!0}}),setRightPinned:e=>t(n=>(va(n.rightSidebarWidthContextKey,e),{rightPinned:e})),setRightSidebarWidth:e=>t(n=>{const r=Math.max(e,ho);return n.rightSidebarWidth===r?n:(af(n.rightSidebarWidthContextKey,r),{rightSidebarWidth:r})}),setRightSidebarLayoutPreference:e=>t(n=>n.rightSidebarLayoutPreference===e?n:(aC(e),{rightSidebarLayoutPreference:e})),openRight:()=>t({rightOpen:!0}),closeRight:()=>t({rightOpen:!1,rightSearchOpen:!1}),toggleRight:()=>t(e=>({rightOpen:!e.rightOpen,rightSearchOpen:e.rightOpen?!1:e.rightSearchOpen,leftOpen:e.rightOpen?e.leftOpen:!1})),closeAll:()=>t({leftOpen:!1,rightOpen:!1,rightSearchOpen:!1}),setRightTab:e=>t(n=>(Sa(n.contextKey,e),{rightTab:e})),openRightSearch:()=>t({rightSearchOpen:!0}),closeRightSearch:()=>t({rightSearchOpen:!1}),setRightSearchOpen:e=>t({rightSearchOpen:e}),setRootPath:(e,n=null,r=null)=>t(o=>{const s=po(n,e),i=js(n,e,r),a=r?i:s;if(o.contextKey===a&&o.rightSidebarWidthContextKey===i)return e===o.rootPath?o:{rootPath:e};const c=new Map(o.rootDataCache);o.rootPath&&c.set(o.rootPath,{directoryCache:o.directoryCache,changedFiles:o.changedFiles,gitBundleError:o.gitBundleError,gitBundleLastLoadedAt:o.gitBundleLastLoadedAt,gitBundleCacheInfo:o.gitBundleCacheInfo}),Wo(c,12,new Set(e?[e]:[]));const l=e?c.get(e):void 0,d=e===o.rootPath,u=new Map(o.projectStateCache);o.contextKey&&u.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 f=r?Zg().has(r):!1;let h={...lf(),...o.explorerRootCache};const g=!!r&&!f,m=g&&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}:u.get(s):void 0;if(g&&r){const S=m?.rightTab??(s?xc()[s]:void 0)??"files",v=m?.explorerRoot??(s?o.explorerRootCache[s]:void 0)??e,A=m?.selectedFilePath??(s?Ec()[s]:void 0)??null,_={rightTab:S,explorerRoot:v,expandedPaths:new Set(m?.expandedPaths??[]),selectedFilePath:A,directoryCache:new Map(m?.directoryCache??[]),changedFiles:new Map(m?.changedFiles??[]),gitBundleError:m?.gitBundleError??null,gitBundleLastLoadedAt:m?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:m?.gitBundleCacheInfo??null};a&&(u.set(a,_),Sa(a,S),jr(a,A),v&&(h={...h,[a]:v},Vo(h))),yC(r)}Wo(u,12,new Set(a?[a]:[]));const b=a?u.get(a):void 0,w=a?xc()[a]:void 0,R=Ms();let y=i?R[i]:void 0;r&&i&&y===void 0&&(y=(s?R[s]:void 0)??cs(),af(i,y));const k=a?h[a]:void 0,N=Fs();let x=i?N[i]:void 0;r&&i&&x===void 0&&(x=(s?N[s]:void 0)??as(),va(i,x));const T=a?Ec()[a]:void 0;return{rootPath:e,contextKey:a,rightSidebarWidthContextKey:i,rightSidebarWidth:y??cs(),rightPinned:x??as(),rightOpen:o.rightSidebarWidthContextKey===i?o.rightOpen:!1,rightTab:b?.rightTab??w??"files",explorerRoot:b?.explorerRoot??k??e,expandedPaths:b?new Set(b.expandedPaths):new Set,selectedFilePath:b?.selectedFilePath??T??null,explorerRootCache:h,directoryCache:l?.directoryCache??new Map,changedFiles:l?.changedFiles??new Map,gitBundleLoading:d?o.gitBundleLoading:!1,gitBundleSlow:d?o.gitBundleSlow:!1,gitBundleLoadingOwner:d?o.gitBundleLoadingOwner:null,gitBundleError:l?.gitBundleError??null,gitBundleLastLoadedAt:l?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:l?.gitBundleCacheInfo??null,rootDataCache:c,projectStateCache:u}}),inheritRightSidebarStateFromSplitWorkspace:(e,n)=>t(r=>{if(!e||n.length===0)return r;const o=Ms(),s=js(null,null,e);if(!s)return r;const i=o[s]??(r.rightSidebarWidthContextKey===s?r.rightSidebarWidth:void 0),a=Fs(),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};for(const h of n){const g=po(h.sessionId,h.rootPath);g&&(i!==void 0&&(d[g]=i),c!==void 0&&(a[g]=c),l&&(u.set(g,{...l,expandedPaths:new Set(l.expandedPaths),directoryCache:new Map(l.directoryCache),changedFiles:new Map(l.changedFiles)}),Sa(g,l.rightTab),jr(g,l.selectedFilePath),l.explorerRoot?f[g]=l.explorerRoot:delete f[g]))}return i!==void 0&&Ve(Ll,d),l&&Vo(f),c!==void 0&&Ve(Nl,a),Wo(u,12,new Set(r.contextKey?[r.contextKey]:[])),{projectStateCache:u,explorerRootCache:f}}),setExplorerRoot:e=>t(n=>{if(n.explorerRoot===e)return n;const r={...n.explorerRootCache};return n.contextKey&&e&&(r[n.contextKey]=e,Vo(r)),{explorerRoot:e,explorerRootCache:r}}),resetExplorerToProject:()=>t(e=>{if(e.explorerRoot===e.rootPath)return e;const n={...e.explorerRootCache};return e.contextKey&&e.rootPath&&(n[e.contextKey]=e.rootPath,Vo(n)),{explorerRoot:e.rootPath,explorerRootCache:n}}),pinExplorerRoot:(e,n="directory")=>t(r=>{if(!r.rootPath||!e)return r;const o=r.rootPath,s=r.pinnedExplorerRootsCache[r.rootPath]??[];if(s.some(a=>a.path===e))return r;const i={...r.pinnedExplorerRootsCache,[r.rootPath]:[{path:e,kind:n},...s].slice(0,12)};return df(i),(async()=>{try{await De.getState().hydratePinnedExplorerRoots();const a=await Et({pinnedExplorerRoot:{rootPath:o,path:e,kind:n,pinned:!0},pinnedExplorerRootsOrigin:Ea});De.getState().syncPinnedExplorerRoots(a.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:i}}),unpinExplorerRoot:e=>t(n=>{if(!n.rootPath||!e)return n;const r=n.rootPath,o=n.pinnedExplorerRootsCache[n.rootPath]??[],s=o.find(c=>c.path===e);if(!o.some(c=>c.path===e))return n;const i=o.filter(c=>c.path!==e),a={...n.pinnedExplorerRootsCache};return i.length>0?a[n.rootPath]=i:delete a[n.rootPath],df(a),(async()=>{try{await De.getState().hydratePinnedExplorerRoots();const c=await Et({pinnedExplorerRoot:{rootPath:r,path:e,kind:s?.kind??"directory",pinned:!1},pinnedExplorerRootsOrigin:Ea});De.getState().syncPinnedExplorerRoots(c.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:a}}),hydratePinnedExplorerRoots:async()=>{if(!De.getState().pinnedExplorerRootsHydrated)return Hr||(Hr=(async()=>{const e=De.getState().pinnedExplorerRootsCache;let r=(await sr()).pinnedExplorerRoots??{};Object.keys(r).length===0&&Object.keys(e).length>0&&(r=(await Et({pinnedExplorerRoots:e,pinnedExplorerRootsOrigin:Ea})).pinnedExplorerRoots??e),De.getState().syncPinnedExplorerRoots(r)})().finally(()=>{Hr=null}),Hr)},syncPinnedExplorerRoots:e=>t(()=>{const n={};for(const[r,o]of Object.entries(e)){const s=Yg(o);s.length>0&&(n[r]=s.slice(0,12))}return Mr(Pl),{pinnedExplorerRootsCache:n,pinnedExplorerRootsHydrated:!0}}),toggleExpanded:e=>t(n=>{const r=new Set(n.expandedPaths);return r.has(e)?r.delete(e):r.add(e),{expandedPaths:r}}),selectFile:e=>t(n=>(jr(n.contextKey,e),{selectedFilePath:e})),toggleShowHiddenFiles:()=>t(e=>{const n=!e.showHiddenFiles;Ve(Hg,n);const r=new Map(e.projectStateCache);for(const[o,s]of r)r.set(o,{...s,directoryCache:new Map});return{showHiddenFiles:n,directoryCache:new Map,projectStateCache:r}}),toggleGroupByFolder:()=>t(e=>{const n=!e.groupByFolder;return cf(n),{groupByFolder:n}}),setGroupByFolder:e=>t(n=>n.groupByFolder===e?n:(cf(e),{groupByFolder:e})),toggleGroupCollapsed:e=>t(n=>{const r=new Set(n.collapsedGroups);return r.has(e)?r.delete(e):r.add(e),dC(r),{collapsedGroups:r}}),setDirectoryCache:(e,n)=>t(r=>{const o=new Map(r.directoryCache);return o.delete(e),o.set(e,n),Wo(o,128,new Set([...r.expandedPaths,e,r.explorerRoot??r.rootPath??""])),{directoryCache:o}}),reconcileDirectoryCache:(e,n)=>t(r=>{const o=r.directoryCache.get(e);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(e,uf(c,r.fileSortModes[e]??"name"));for(const d of o)if(!i.has(d.path))for(const u of a.keys())Mn(d.path,u)&&a.delete(u);let l=r.selectedFilePath;return l&&o.find(u=>!i.has(u.path)&&Mn(u.path,l))&&(l=null,jr(r.rootPath,null)),{directoryCache:a,selectedFilePath:l}}),hydrateFileSortModes:async()=>{if(!De.getState().fileSortModesHydrated)return Ur||(Ur=(async()=>{const e=De.getState().fileSortModes;let r=(await sr()).fileSortModes??{};Object.keys(r).length===0&&Object.keys(e).length>0&&(r=(await Et({fileSortModes:e})).fileSortModes??e),Mr(vc),t({fileSortModes:r,fileSortModesHydrated:!0,directoryCache:new Map})})().finally(()=>{Ur=null}),Ur)},setDirectorySortMode:async(e,n)=>{try{await De.getState().hydrateFileSortModes()}catch{}const r=De.getState().fileSortModes[e]??"name",o=(xa.get(e)??0)+1;xa.set(e,o),t(s=>{const i={...s.fileSortModes};n==="modified"?i[e]=n:delete i[e];const a=new Map(s.directoryCache);return a.delete(e),{fileSortModes:i,fileSortModesHydrated:!0,directoryCache:a}});try{await Et({fileSortMode:{path:e,mode:n}}),Mr(vc)}catch{if(xa.get(e)!==o)return;t(s=>{const i={...s.fileSortModes};r==="modified"?i[e]=r:delete i[e];const a=new Map(s.directoryCache);return a.delete(e),{fileSortModes:i,directoryCache:a}})}},hydrateNestedGitScanRoots:async()=>{if(!De.getState().nestedGitScanRootsHydrated)return $r||($r=(async()=>{const n=(await sr()).nestedGitScanRoots??{};Mr(Sc),t({nestedGitScanRoots:n,nestedGitScanRootsHydrated:!0})})().finally(()=>{$r=null}),$r)},setNestedGitScanRoot:async(e,n)=>{try{await De.getState().hydrateNestedGitScanRoots()}catch{}const r=!!De.getState().nestedGitScanRoots[e],o=(Go.get(e)??0)+1;Go.set(e,o),t(s=>{const i={...s.nestedGitScanRoots};return n?i[e]=!0:delete i[e],{nestedGitScanRoots:i,nestedGitScanRootsHydrated:!0}});try{const s=await Et({nestedGitScanRoot:{rootPath:e,enabled:n}});if(Go.get(e)!==o)return;t({nestedGitScanRoots:s.nestedGitScanRoots??{}}),Mr(Sc)}catch{if(Go.get(e)!==o)return;t(s=>{const i={...s.nestedGitScanRoots};return r?i[e]=!0:delete i[e],{nestedGitScanRoots:i}})}},invalidateDirectoryCache:(e,n=!1)=>t(r=>{const o=new Map(r.directoryCache);for(const s of o.keys())(s===e||n&&Mn(e,s))&&o.delete(s);return{directoryCache:o}}),applyFileWatchEvents:e=>t(n=>{if(e.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 e){if(d.type==="rescan-required"){c=!0,s&&Mn(d.path,s)&&l(s);continue}const u=kC(d.path),f=r.get(u);if(d.type==="deleted"){if(l(d.path),s&&Mn(d.path,s)&&(s=null,jr(n.rootPath,null)),f){const b=f.filter(w=>w.path!==d.path);b.length!==f.length&&(r.set(u,b),i=!0)}for(const b of r.keys())Mn(d.path,b)&&(r.delete(b),i=!0);continue}l(d.path);const h=CC(d);if(!h||!f)continue;const g=f.find(b=>b.path===h.path),m=uf(g?f.map(b=>b.path===h.path?{...b,...h,children:b.children}:b):[...f,h],n.fileSortModes[u]??"name");r.set(u,m),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:()=>t(e=>({fileWatchEpoch:e.fileWatchEpoch+1})),setChangedFiles:e=>t({changedFiles:e}),beginGitBundleLoading:e=>t({gitBundleLoading:!0,gitBundleSlow:!1,gitBundleLoadingOwner:e}),setGitBundleSlowFor:(e,n)=>t(r=>r.gitBundleLoadingOwner===e?{gitBundleSlow:n}:r),finishGitBundleLoading:e=>t(n=>n.gitBundleLoadingOwner===e?{gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}:n),resetGitBundleLoading:()=>t({gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}),setGitBundleError:e=>t({gitBundleError:e}),markGitBundleLoaded:(e=null)=>t({gitBundleLastLoadedAt:Date.now(),gitBundleCacheInfo:e})})),Aa=(()=>{if(location.hash.startsWith("#termdock-invite="))try{return Ds(location.href)}catch{return}finally{history.replaceState(null,"",location.pathname+location.search)}})(),Ac="termdock-secure-open-session";let ka,qr;function IC(){try{const t=JSON.parse(sessionStorage.getItem(Ac)??"null");return t?.serviceId===re()?.targetPeerId?t.sessionId:void 0}catch{return}}function RC({children:t}){const[e,n]=O.useState(Aa),[r,o]=O.useState(!1),[s,i]=O.useState(!!Aa),[a,c]=O.useState(!Aa),[l,d]=O.useState(!1),[u,f]=O.useState("正在连接服务…"),[h,g]=O.useState([]),[m,b]=O.useState([]),[w,R]=O.useState(!1),[y,k]=O.useState(!1),[N,x]=O.useState(""),[T,S]=O.useState(!1),[v,A]=O.useState(""),[_,B]=O.useState(re()?.serviceName??location.hostname),[C,E]=O.useState(IC);O.useEffect(()=>{(!r&&!a||r&&(!w||C))&&Un({rendered:!0})},[r,a,w,C]),O.useEffect(()=>{tt().then(U=>x(U.peerId)).catch(()=>d(!0))},[]),O.useEffect(()=>{const U=q=>{const{origin:K,sessionId:X}=q.detail;try{const W=JSON.parse(localStorage.getItem("termdock.federation.connections.v1")??"[]").find(V=>br(V).some(Y=>new URL(Y).origin===new URL(K).origin));if(!W){i(!0);return}if(ht()?.focusSession(W.targetPeerId,X))return;sessionStorage.setItem(Ac,JSON.stringify({serviceId:W.targetPeerId,sessionId:X})),Qe(W).then(()=>{E(X),o(!0)}).catch(()=>{d(!0),i(!0)})}catch{i(!0)}};return window.addEventListener("termdock:open-remote-session",U),()=>window.removeEventListener("termdock:open-remote-session",U)},[]);const P=async(U=5e3)=>{const q=await st(),K=await yr(q,{timeoutMs:U}),X=vE(),z=fE()?.targetPeerId;Promise.all([I1(),Ke()]).then(([V,Y])=>{const Q=Y.find(ce=>ce.targetPeerId===z),ae=X==="relay"?`经 ${Q?.label||z?.slice(-12)||"入口服务"} 中转`:"直连";return q.request({type:"device-name",name:cg(),onlyIfMissing:!0,profile:{...V,route:ae}})}).catch(()=>{}),R(K.fullService),k(K.canManage),o(!0),c(!1),d(!1);const W=re();Un({phase:"ready",...W?{service:{...W,id:W.targetPeerId,label:W.serviceName||location.host}}:{}}),Qo()&&bE()};O.useEffect(()=>{let U=!1,q=!1,K=0,X;const z=async()=>{if(U||q||K&&(document.hidden||!Qo()))return;if(!navigator.onLine){c(!0),d(!0),f("网络已断开,恢复后会自动连接"),Un({phase:"offline"});return}q=!0,clearTimeout(X);const ie=performance.now(),$e=rn();try{if(Hs&&!re())throw new Error("工作区的服务记录已移除,请重新添加服务。");qr??=window.termdockDesktop?.getServiceConnection?.();const ke=await qr;if(ke?.invitation){n(Ds(ke.invitation)),i(!0),c(!1);return}if(!re()){if(e){c(!1);return}if(ka??=(async()=>{if(ke?.targetPeerId){await Qe({...ke,targetPeerId:ke.targetPeerId,serviceName:ke.label});return}const Ge=await window.termdockDesktop?.getLocalInvite?.();Ge?await Qe(Ge):await hE()})(),await ka,!re()){U||(o(!1),c(!1),d(!1));return}}U||await P($e?.canSwitchTransport?2500:5e3),K=0,performance.measure("termdock:connection-ready",{start:ie,end:performance.now()})}catch(ke){if(U)return;ke instanceof et?(o(!1),c(!1),i(!1),d(!1),Un({phase:"login"})):($e&&rn()===$e&&Wp(),d(!0),c(!0),ka=void 0,f("连接暂未恢复,正在重试…"),Un({phase:"reconnecting"}),K++,X=setTimeout(()=>{z()},Math.min(5e3,300*2**Math.min(K-1,5))),console.debug("[connection] retry",{elapsedMs:Math.round(performance.now()-ie),attempt:K,reason:ke instanceof Error?ke.message:"unknown"}))}finally{q=!1}},W=()=>{document.visibilityState==="visible"&&Qo()&&z()},V=W,Y=()=>{K=0,W()},Q=()=>{De.getState().openLeft(),W()};window.addEventListener(fo,W),window.addEventListener(oc,Q),ht()?.attach(ii(),window),z(),document.addEventListener("visibilitychange",V),window.addEventListener("focus",W),window.addEventListener("online",Y);const ae=navigator.connection;ae?.addEventListener("change",Y),window.addEventListener("auth:unauthorized",W),window.addEventListener(Je,W);const ce=setInterval(W,3e4);return()=>{U=!0,clearTimeout(X),clearInterval(ce),window.removeEventListener(fo,W),window.removeEventListener(oc,Q),document.removeEventListener("visibilitychange",V),window.removeEventListener("focus",W),window.removeEventListener("online",Y),ae?.removeEventListener("change",Y),window.removeEventListener("auth:unauthorized",W),window.removeEventListener(Je,W)}},[]);const I=async()=>{const U=rn();if(U){S(!0),A("");try{const q=await U.request({type:"session-list"});b(q.items)}catch{A("暂时无法读取终端列表,请重试。")}try{if(y){const q=await U.request({type:"grants-list"}),K=q.subjectLabels??{},X=await U.request({type:"route-access"}),z=await Ke(),W=(Array.isArray(X.grants)?X.grants:[]).map(V=>({id:`route:${V.id}`,subjectId:V.subjectId,scope:{kind:"service"},actions:["route.use"],routeTargetServiceId:V.targetServiceId,routeTargetName:z.find(Y=>Y.targetPeerId===V.targetServiceId)?.label||"指定服务",...V.active?{}:{revokedAt:V.revokedAt??0}}));g([...q.grants,...W].map(V=>({...V,label:K[V.subjectId],deviceProfile:q.deviceProfiles?.[V.subjectId]})))}else{const q=await U.request({type:"permissions"});g(q.grants??[])}}catch{A("暂时无法读取设备权限,请重试。")}finally{S(!1)}}};O.useEffect(()=>{const U=()=>{i(!0),r&&I()};return window.addEventListener(cc,U),()=>window.removeEventListener(cc,U)},[r,y]);const[D,M]=O.useState([]);O.useEffect(()=>{if(!s||!y||D.length)return;let U=!1;return(async()=>{const X=await(await(await st()).fetch("/api/terminal/settings")).json();if(U)return;const z=X.localAccess??{},W=[],V=(Y,Q)=>{try{const ae=new URL(Y);if(ae.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(ae.hostname))return;const ce=ae.origin;if(ce===location.origin||W.some(ie=>ie.url===ce))return;W.push({url:ce,label:Q})}catch{}};if(typeof z.url=="string"&&V(z.url,"服务域名"),Array.isArray(z.interfaces))for(const Y of z.interfaces){const Q=Y;typeof Q.url=="string"&&V(Q.url,typeof Q.label=="string"&&Q.label||typeof Q.name=="string"&&Q.name||"IP 地址")}M(W)})().catch(()=>{}),()=>{U=!0}},[s,y,D.length]);const F=async U=>{if(!U.pairingCode&&!U.routeCode&&re()?.targetPeerId!==U.targetPeerId&&ht()){const q={...U,id:U.targetPeerId,label:U.serviceName||new URL(U.serviceOrigin||U.url).host};if(await Tt(q),_s(q)){i(!1);return}}await Qe(U),qr&&(qr=qr.then(q=>q?{...q,invitation:void 0}:null)),n(void 0),E(void 0),sessionStorage.removeItem(Ac),B(U.serviceName??new URL(U.url).hostname),await P(),i(!1),d(!1)},L=async U=>{const q=window.termdockDesktop;if(q?.openServiceConnection){const K=await q.openServiceConnection(U);if(!K.ok)throw new Error(K.error||"暂时无法打开这台服务。");i(!1);return}if(_s(U)){i(!1);return}if(U.targetPeerId)try{await F({...U,targetPeerId:U.targetPeerId,serviceName:U.label});return}catch(K){if(!(K instanceof et))throw K}return fu(U.serviceOrigin||U.url)};O.useEffect(()=>{const U=q=>{L(q.detail).catch(K=>{i(!0),A(K instanceof Error?K.message:"暂时无法打开服务")})};return window.addEventListener(bc,U),()=>window.removeEventListener(bc,U)});const $=async(U,q)=>{if(U.includes("#termdock-invite=")){const X=Ds(U);if(window.termdockDesktop?.openServiceConnection){const z=await window.termdockDesktop.openServiceConnection({id:X.targetPeerId,url:X.url,label:X.serviceName||new URL(X.serviceOrigin||X.url).host,targetPeerId:X.targetPeerId,serviceOrigin:X.serviceOrigin,entryServiceId:X.entryServiceId},U);if(!z.ok)throw new Error(z.error||"暂时无法打开邀请。");i(!1);return}if(q!==void 0&&X.routeOnly){await hu(X,q),await P(),i(!1);return}try{await F(X)}catch(z){if(X.routeOnly&&z instanceof et)return{passwordRequired:!0};throw z}return}const K=_e(U);return window.termdockDesktop?.openServiceConnection?L({id:K,url:K,label:new URL(K).host}):fu(K,q)},H=async U=>{const q=await st(),{includeBackup:K=!0,entryAddress:X,...z}=U,W=re(),V=W?Zt(W):[];let Y;if(K&&V.length){for(const ce of V)try{const ie=await Xp({...W,targetPeerId:q.targetPeerId},ce);Y={...ce,routeCode:ie.routeCode};break}catch{}if(!Y)throw new Error("无法分享备用连接:需要入口管理员授权。也可以关闭此选项,生成直接连接邀请。")}let Q=W?.serviceOrigin||location.origin;if(X)try{Q=new URL(X).origin}catch{throw new Error("邀请接入地址无效。")}else if(["localhost","127.0.0.1","[::1]"].includes(new URL(Q).hostname)){const ie=await(await q.fetch("/api/terminal/settings")).json();typeof ie.localAccess?.url=="string"&&(Q=ie.localAccess.url)}const ae=await q.request({type:"invite-create",...z});if(typeof ae.code!="string"||typeof ae.expiresAt!="number")throw new Error("暂时无法生成邀请。");return{url:lg({v:1,serviceId:q.targetPeerId,code:ae.code,entryUrl:Y?.url||Q,serviceUrl:Q,name:_,entryServiceId:Y?.targetPeerId,routeCode:Y?.routeCode}),expiresAt:ae.expiresAt}};return p.jsxs(p.Fragment,{children:[r?w&&!C?t:p.jsx(cA,{client:rn(),initialSessionId:C}):a?p.jsx("div",{className:"flex h-full min-h-0 flex-col items-center justify-center bg-[var(--chrome-bg)] px-6 text-foreground",children:p.jsxs("div",{className:"flex w-full max-w-xs flex-col items-center text-center",children:[p.jsx("div",{className:"mb-5 flex h-12 w-12 items-center justify-center rounded-2xl bg-surface-2 text-muted-foreground","aria-hidden":"true",children:p.jsx(a1,{size:24,strokeWidth:1.5})}),p.jsx("h1",{className:"max-w-full truncate text-base font-medium tracking-tight",title:_,children:_}),p.jsxs("div",{role:"status",className:"mt-2 flex max-w-full items-center justify-center gap-2 text-xs leading-5 text-muted-foreground",children:[!l&&p.jsx(je,{size:13,className:"shrink-0 animate-spin motion-reduce:animate-none","aria-hidden":"true"}),p.jsx("span",{children:u})]}),l&&p.jsx("p",{className:"mt-2 text-xs leading-5 text-muted-foreground",children:"登录信息已保留"}),p.jsx("button",{type:"button",className:"mt-6 min-h-11 rounded-lg px-4 text-xs text-muted-foreground transition-colors hover:bg-surface-2 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>i(!0),children:"管理服务"})]})}):p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"fixed left-0 right-0 top-[var(--safe-top-inset)] z-chrome sm:right-auto sm:w-72",children:p.jsx(G2,{})}),p.jsx(q2,{onLoginSuccess:()=>{P().catch(()=>d(!0))}})]}),s&&p.jsx(oA,{onConnect:F,onClose:()=>i(!1),onAddService:$,onOpenService:L,onConnectWithPassword:async(U,q)=>{await hu(U,q),await P(),i(!1)},paired:r||!!re(),initialInvite:e,currentServiceName:_,currentServiceId:rn()?.targetPeerId||re()?.targetPeerId,currentServiceOrigin:re()?.serviceOrigin,currentIdentity:N,grants:h,sessions:m,loading:T,loadError:v,onRetry:()=>{I()},onRename:async(U,q)=>{await(await st()).request({type:"device-name",subjectId:U,name:q}),await I()},hasBackup:!!re()&&Zt(re()).length>0,inviteAddresses:D,onCreateInvite:y?H:void 0,onRevoke:y?async U=>{await(await st()).request(U.startsWith("route:")?{type:"route-revoke",grantId:U.slice(6)}:{type:"revoke",grantId:U}),await I()}:void 0})]})}function TC(t,e,n){const r=t?.name||"Error",o=t?.message||"Unexpected error";return["Termdock error report",`Time: ${n.capturedAt}`,`URL: ${n.url}`,`User agent: ${n.userAgent}`,"",`${r}: ${o}`,t?.stack?`
30
30
  Stack:
31
31
  ${t.stack}`:"",e?`
32
32
  React component stack:
33
33
  ${e.trim()}`:""].filter(Boolean).join(`
34
- `)}async function PI(t){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(t),!0}catch{}const e=document.createElement("textarea");e.value=t,e.setAttribute("readonly",""),e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select();try{return document.execCommand("copy")}catch{return!1}finally{e.remove()}}function NI({error:t,componentStack:e}){const{t:n}=di(),[r,o]=We.useState("idle"),s=async()=>{const i=TI(t,e,{url:window.location.href,userAgent:navigator.userAgent,capturedAt:new Date().toISOString()});o(await PI(i)?"copied":"failed")};return p.jsx("div",{className:"flex h-full items-center justify-center p-4",children:p.jsxs("div",{className:"flex flex-col items-center gap-3 text-center max-w-md",children:[p.jsx("div",{className:"w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center",children:p.jsx("svg",{className:"w-6 h-6 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:p.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),p.jsxs("div",{className:"space-y-1",children:[p.jsx("h3",{className:"font-medium text-foreground",children:n("errorBoundary.title")}),p.jsx("p",{className:"text-sm text-muted-foreground",children:t?.message||n("errorBoundary.unexpected")})]}),p.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-center gap-2",children:[p.jsx("button",{type:"button",onClick:()=>{s()},className:"rounded-full bg-surface-2 px-5 py-2.5 text-sm font-medium text-foreground ring-1 ring-border/15 transition hover:bg-surface-elevated active:scale-[0.97]",children:n(r==="copied"?"errorBoundary.copied":r==="failed"?"errorBoundary.copyFailed":"errorBoundary.copyDetails")}),p.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"rounded-full bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground shadow-sm transition-all hover:bg-primary/90 active:scale-[0.97]",children:n("errorBoundary.retry")})]})]})})}class LI extends We.Component{state={hasError:!1,error:null,componentStack:""};static getDerivedStateFromError(e){return{hasError:!0,error:e,componentStack:""}}componentDidCatch(e,n){console.error("Terminal error caught by boundary:",e,n),this.setState({componentStack:n.componentStack??""})}render(){return this.state.hasError?this.props.fallback?this.props.fallback:p.jsx(NI,{error:this.state.error,componentStack:this.state.componentStack}):this.props.children}}function we(){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 BI="debug",_I="termdock:debug";function ff(t){return t?new Set(t.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean)):new Set}function OI(){if(typeof window>"u")return new Set;const t=ff(new URLSearchParams(window.location.search).get(BI));let e=new Set;try{e=ff(window.localStorage.getItem(_I))}catch{e=new Set}const n=new Set([...t,...e]);return n.has("1")||n.has("true")||n.has("*")||n.has("all")?new Set(["*"]):n}function DI(t){const e=OI();return e.has("*")||e.has(t)}function FI(t){const e=DI(t);return(...n)=>{e&&console.log(`[debug:${t}]`,...n)}}const hf=80,MI=60,jI="termdock:viewport-keyboard-change",UI="termdock:viewport-layout-change",Ct=240,pf=640,gf=360,$I=1500;function HI({measuredHeight:t,documentVisible:e,editableFocused:n}){return e&&n&&t>0}function Ia(){if(typeof document>"u")return!1;const t=document.activeElement;return t instanceof HTMLElement&&t.matches('input:not([type="hidden"]), textarea, select, [contenteditable]:not([contenteditable="false"])')}const Us=t=>{const e=typeof t=="number"?t:Number.parseFloat(typeof t=="string"?t:"0");return Number.isFinite(e)&&e>0?Math.round(e):0},Jg=(t,e)=>{const n=t.map(Us).filter(r=>r>0);return n.find(r=>r>=Ct)??n[0]??e},ro=()=>typeof window>"u"?pf:Jg([we().innerHeight,document.documentElement?.clientHeight,document.body?.clientHeight,we().visualViewport?.height,window.screen?.availHeight,window.screen?.height],pf),Qg=()=>typeof window>"u"?gf:Jg([we().innerWidth,document.documentElement?.clientWidth,document.body?.clientWidth,we().visualViewport?.width,window.screen?.availWidth,window.screen?.width],gf),qt=t=>{const e=Number.parseFloat(t||"0");return Number.isFinite(e)?Math.max(0,Math.round(e)):0},em=()=>typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,qI=()=>typeof window>"u"?!1:we().navigator.standalone===!0||we().matchMedia?.("(display-mode: standalone)").matches===!0,tm=()=>{if(typeof window>"u"||!em()||!qI())return{top:0,right:0,bottom:0,left:0};if(!(ro()>=Qg()))return{top:0,right:0,bottom:0,left:0};const e=window.screen?.width||window.innerWidth,n=window.screen?.height||window.innerHeight,r=Math.min(e,n),o=Math.max(e,n);return r>=700?{top:20,right:0,bottom:20,left:0}:o<780?{top:20,right:0,bottom:0,left:0}:{top:o>=852?59:o>=844?47:44,right:0,bottom:34,left:0}};function KI(t="--app-vh"){if(typeof window>"u"||typeof document>"u")return;const e=Us(we().visualViewport?.height),n=Math.max(0,Math.round(we().visualViewport?.offsetTop??0)),r=ro(),s=e>=Ct?Math.min(r,e+n):r,i=Math.max(r,s),a=document.documentElement.style;a.setProperty(t,`${Math.max(s,Ct)}px`),a.setProperty("--app-base-vh",`${Math.max(i,Ct)}px`),a.setProperty("--app-visible-vh",`${Math.max(s,Ct)}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=tm();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 vR(t={}){const{cssVarName:e="--app-vh"}=t,n=We.useMemo(()=>FI("viewport"),[]),r=We.useCallback(()=>{if(typeof window>"u")return 0;const d=we().visualViewport,u=ro();if(!d)return u;const f=Us(d.height);if(f<Ct&&u>=Ct)return u;const h=d.offsetTop,m=f<u-1&&h>0&&h<=96?f+h:f,b=Math.max(0,Math.min(u,m));return b>0?Math.round(b):u},[]),[o,s]=We.useState(r),i=We.useRef(0),a=We.useRef(0),c=We.useRef(0),l=We.useRef(!1);return We.useEffect(()=>{if(typeof window>"u")return;let d=null,u=0,f=null,h="",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 C={top:0,right:0,bottom:0,left:0};try{const L=m();if(L){const $=getComputedStyle(L);C={top:qt($.paddingTop),right:qt($.paddingRight),bottom:qt($.paddingBottom),left:qt($.paddingLeft)}}}catch{}const D=we();if(D!==window){const L=D.getComputedStyle(D.document.documentElement);C={top:Math.max(C.top,qt(L.getPropertyValue("--safe-top-inset"))),right:Math.max(C.right,qt(L.getPropertyValue("--safe-right-inset"))),bottom:Math.max(C.bottom,qt(L.getPropertyValue("--safe-bottom-inset"))),left:Math.max(C.left,qt(L.getPropertyValue("--safe-left-inset")))}}const M=tm(),F={top:Math.max(C.top,M.top),right:Math.max(C.right,M.right),bottom:Math.max(C.bottom,M.bottom),left:Math.max(C.left,M.left)};return document.documentElement.style.setProperty("--safe-top-inset",`${F.top}px`),document.documentElement.style.setProperty("--safe-right-inset",`${F.right}px`),document.documentElement.style.setProperty("--safe-bottom-inset",`${F.bottom}px`),document.documentElement.style.setProperty("--safe-left-inset",`${F.left}px`),F},w=(C,D,M,F)=>{const L=Math.max(D,M);if(i.current===0){i.current=L,a.current=C,document.documentElement.style.setProperty("--app-base-vh",`${L}px`);return}const $=Math.abs(C-a.current),H=F<=hf;($>MI||H)&&(i.current=L,a.current=C,document.documentElement.style.setProperty("--app-base-vh",`${L}px`))},R=(C="event")=>{d=null;const D=r(),M=Math.round(we().visualViewport?.offsetTop??0),F=Us(we().visualViewport?.height),L=F>=Ct?F:D,$=ro(),H=Qg(),U=Math.max(0,L+M),q=b(),K=q.bottom,X=Math.max(0,i.current-U-K);w(H,$,U,X),s(vr=>vr===D?vr:D);const z=Number.parseInt(document.documentElement.style.getPropertyValue(e)||"0",10);document.documentElement.style.setProperty(e,`${D}px`),document.documentElement.style.setProperty("--app-vv-offset-top",`${M}px`);const W=i.current,G=Math.min(D,L),Y=Math.max(0,Math.min(W,U)),Q=Math.max(0,Math.round(W-G-K)),ae=Ia(),ce=HI({measuredHeight:Q,documentVisible:document.visibilityState==="visible",editableFocused:ae}),ie=ce?Q:0,$e=ie>=hf,ke=-ie,Ve=ie;document.documentElement.style.setProperty("--kb-translate-y",`${ke}px`),document.documentElement.style.setProperty("--kb-margin-top",`${Ve}px`),document.documentElement.style.setProperty("--kb-height",`${ie}px`),document.documentElement.style.setProperty("--app-visible-vh",`${Y}px`);const en=Math.abs(ie-c.current)>1,Oe=$e!==l.current;(en||Oe)&&(c.current=ie,l.current=$e,document.dispatchEvent(new CustomEvent(jI,{detail:{baseHeight:W,visibleHeight:Y,visualViewportHeight:L,offsetTop:M,keyboardHeight:ie,isOpen:$e,source:C}}))),(z!==D||M>0||en||Oe)&&n("sync",{cssVarName:e,innerHeight:$,baseHeight:W,rawViewportHeight:L,offsetTop:M,visibleHeight:Y,rawHeight:D,appliedHeight:D,keyboardViewportHeight:G,measuredKeyboardHeight:Q,editableFocused:ae,applyKeyboardInset:ce,keyboardHeight:ie,isKeyboardOpen:$e,safeAreaInsets:q,source:C}),document.dispatchEvent(new CustomEvent(UI,{detail:{height:D,baseHeight:W,visibleHeight:Y,offsetTop:M,source:C}}))},y=()=>{d===null&&(d=window.requestAnimationFrame(()=>{d=null;const C=we(),D=C.visualViewport,M=[C.innerWidth,C.innerHeight,D?.width,D?.height,D?.offsetTop,D?.offsetLeft,document.visibilityState,Ia()].join(":"),F=f;f=null,(F||M!==h)&&(h=M,R(F||"viewport.settle")),performance.now()<u&&y()}))},k=(C="event")=>{(C.includes("visibilitychange")||C.includes("pageshow"))&&n("schedule",{source:C}),f=C,em()&&document.visibilityState==="visible"&&(u=performance.now()+$I),y()};k("mount");const N=()=>k("resize"),x=()=>k("orientationchange"),T=()=>k("visualViewport.resize"),S=()=>k("visualViewport.scroll"),v=()=>k("focusin"),A=()=>k("focusout"),_=C=>{u=0;const D=document.activeElement;D instanceof HTMLElement&&Ia()&&D.blur(),c.current=0,l.current=!1;const M=Math.max(i.current,ro(),Ct),F=document.documentElement.style;F.setProperty(e,`${M}px`),F.setProperty("--app-visible-vh",`${M}px`),F.setProperty("--app-vv-offset-top","0px"),F.setProperty("--kb-translate-y","0px"),F.setProperty("--kb-margin-top","0px"),F.setProperty("--kb-height","0px"),s(L=>L===M?L:M),n("keyboard session reset",{source:C,baseHeight:M})};window.addEventListener("resize",N),window.addEventListener("orientationchange",x),we().visualViewport?.addEventListener("resize",T),we().visualViewport?.addEventListener("scroll",S),document.addEventListener("focusin",v),document.addEventListener("focusout",A);const B=C=>{n("resume",{source:C,innerHeight:Math.round(window.innerHeight),visualViewport:we().visualViewport?{width:Math.round(we().visualViewport.width),height:Math.round(we().visualViewport.height),offsetTop:Math.round(we().visualViewport.offsetTop)}:null,hidden:document.hidden}),k(C)},I=()=>{document.hidden?_("visibilitychange:hidden"):B("visibilitychange")},E=()=>B("pageshow"),P=()=>_("pagehide");return document.addEventListener("visibilitychange",I),window.addEventListener("pageshow",E),window.addEventListener("pagehide",P),()=>{window.removeEventListener("resize",N),window.removeEventListener("orientationchange",x),we().visualViewport?.removeEventListener("resize",T),we().visualViewport?.removeEventListener("scroll",S),document.removeEventListener("focusin",v),document.removeEventListener("focusout",A),document.removeEventListener("visibilitychange",I),window.removeEventListener("pageshow",E),window.removeEventListener("pagehide",P),d!==null&&window.cancelAnimationFrame(d),g?.remove()}},[e,n,r]),o}const zI=1e3,WI=2e4,GI=9e4,VI=5e3,ee={ws:null,listeners:new Set,reconnectAttempt:0,reconnectTimer:null,idleCloseTimer:null,closing:!1};let Xo=0,ar=null;function XI(){return typeof window>"u"?null:`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/control/ws`}function nm(){ee.idleCloseTimer&&(clearTimeout(ee.idleCloseTimer),ee.idleCloseTimer=null)}function YI(){nm(),!(ee.ws&&ee.ws.readyState===WebSocket.OPEN)&&(ee.idleCloseTimer=setTimeout(()=>{ee.idleCloseTimer=null,ee.listeners.size===0&&ZI()},VI))}function ZI(){if(ee.ws){try{ee.ws.close()}catch{}ee.ws=null}ar&&(clearInterval(ar),ar=null)}function mf(){if(ee.reconnectTimer)return;const t=Math.min(zI*Math.pow(2,ee.reconnectAttempt),WI);ee.reconnectAttempt+=1,ee.reconnectTimer=setTimeout(()=>{ee.reconnectTimer=null,rm()},t)}function rm(){const t=XI();if(!t||ee.ws&&ee.ws.readyState===WebSocket.OPEN)return;let e;try{e=Vp(t)}catch{mf();return}ee.ws=e,e.onopen=()=>{ee.reconnectAttempt=0,Xo=Date.now(),ar||(ar=setInterval(()=>{if(!(!ee.ws||ee.ws.readyState!==WebSocket.OPEN)&&Xo>0&&Date.now()-Xo>GI)try{ee.ws.close()}catch{}},3e4),ar.unref?.())},e.onmessage=n=>{Xo=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 ee.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 ee.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 ee.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 ee.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 ee.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 ee.listeners)try{i(s)}catch(a){console.error("[clientStateSync] listener threw:",a)}},e.onclose=()=>{ee.ws===e&&(ee.ws=null),ee.listeners.size>0&&mf()},e.onerror=()=>{}}function om(t){return ee.listeners.add(t),nm(),ee.ws||rm(),()=>{ee.listeners.delete(t),ee.listeners.size===0&&YI()}}const Ca=ci(t=>({unread:{},viewing:null,receive:(e,n)=>t(r=>{const o=r.unread[e]??[];return r.viewing===e||o.includes(n)?r:{unread:{...r.unread,[e]:[...o,n]}}}),view:e=>t(n=>{if(!e||!n.unread[e])return n.viewing===e?n:{viewing:e};const r={...n.unread};return delete r[e],{viewing:e,unread:r}})})),sm=new Set(["bash","zsh","fish","sh","dash","ksh","tcsh","csh","nu"]);function zn(t){if(!t)return null;if(t==="/")return"/";const e=t.replace(/\/+$/,"").split("/");return e[e.length-1]||t}function JI(t,e,n,r=sm,o=null,s=null){if(t.customName)return{primary:t.name,secondary:zn(n)};if(o){const a=zn(n),c=o===n||o===a;if(s!=="idle"&&!r.has(o)&&!c)return{primary:o,secondary:a}}if(e&&!r.has(e))return{primary:e,secondary:zn(n)};const i=zn(n);return i?{primary:i,secondary:null}:{primary:t.name,secondary:null}}function QI(t,e,n,r=sm,o=null,s=null){return JI(t,e,n,r,o,s).primary}function eC(t,e,n){const r=[],o=new Map;for(const s of t){const i=e(s),a=i&&i.trim().length>0?i:"";let c=o.get(a);c||(c={key:a,label:a?zn(a)??a:n,sessions:[]},o.set(a,c),r.push(c)),c.sessions.push(s)}return r.sort((s,i)=>(s.key===""?1:0)-(i.key===""?1:0))}function SR(t){return t&&t.trim().length>0?t:""}function xR(t,e,n){const r=[...t],[o]=r.splice(e,1);return o?(r.splice(n,0,o),r.flatMap(s=>s.sessions.map(i=>i.id))):t.flatMap(s=>s.sessions.map(i=>i.id))}function tC(t,e){const n=new Set;return t.flatMap(r=>{const o=[...new Set(r.sessionIds)].filter(s=>e.has(s)&&!n.has(s));return o.length<(r.federated?1:2)?[]:(o.forEach(s=>n.add(s)),[{...r,sessionIds:o}])})}function ER(t,e,n,r,o=[],s=[]){const i=new Map(t.map(g=>[g.id,g])),a=tC(s,new Set(i.keys())),c=new Map,l=new Map,d=o.filter(g=>g.sessionIds.length>=2&&g.sessionIds.every(m=>i.has(m))),u=(g,m)=>{const b=i.get(m);g.forEach(w=>{c.set(w,g),l.set(w,b)})};for(const g of a){const m=new Set(g.sessionIds),b=new Map;for(const y of d)y.sessionIds.every(k=>m.has(k))&&y.sessionIds.forEach(k=>b.set(k,y.sessionIds));const w=new Set,R=g.sessionIds.flatMap(y=>{if(w.has(y))return[];const k=b.get(y)??[y];return k.forEach(N=>w.add(N)),k});u(R,g.sessionIds[0])}for(const g of d)g.sessionIds.some(m=>c.has(m))||u(g.sessionIds,g.sessionIds[0]);const f=g=>{const m=new Set;return g.flatMap(b=>{if(m.has(b.id))return[];const w=c.get(b.id)??[b.id];return w.forEach(R=>m.add(R)),w.map(R=>i.get(R))})};if(!n)return{arranged:f(t),groups:[]};const h=eC(t,g=>e(l.get(g.id)??g),r).map(g=>({...g,sessions:f(g.sessions)}));return{arranged:h.flatMap(g=>g.sessions),groups:h}}function nC(t,e,n){const r=t.findIndex(o=>n(o)===e);return r<0?null:t[r+1]?n(t[r+1]):r>0?n(t[r-1]):null}const im="termdock-session-fonts-v1",wf=8,rC=32;function am(t){return Number.isFinite(t)?Math.max(wf,Math.min(rC,Math.round(t))):wf}function Bl(){if(typeof window>"u")return{};try{const t=window.localStorage.getItem(im);if(!t)return{};const e=JSON.parse(t);if(typeof e!="object"||e===null)return{};const n={};for(const[r,o]of Object.entries(e))typeof o=="number"&&Number.isFinite(o)&&(n[r]=am(o));return n}catch{return{}}}function cm(t){if(!(typeof window>"u"))try{window.localStorage.setItem(im,JSON.stringify(t))}catch{}}function AR(t){return Bl()[t]??null}function kR(t,e){if(typeof window>"u")return;const n=Bl(),r=e===null?null:am(e);r===null?delete n[t]:n[t]=r,cm(n),window.dispatchEvent(new CustomEvent("termfontchange",{detail:{sessionId:t,fontSize:r}}))}function oC(t){if(typeof window>"u")return;const e=Bl();t in e&&(delete e[t],cm(e))}const Ra="termdock-sessions",kc="termdock-active-session",_l="termdock-sessions-cache";function Ic(){try{const t=localStorage.getItem(kc);return t&&t.trim().length>0?t:null}catch{return null}}function jn(t){try{t?localStorage.setItem(kc,t):localStorage.removeItem(kc)}catch{}}function lm(){if(typeof window>"u")return null;try{const t=localStorage.getItem(_l);if(!t)return null;const e=JSON.parse(t);return Array.isArray(e)?e.filter(n=>typeof n=="object"&&n!==null&&typeof n.sessionId=="string"&&typeof n.name=="string"):null}catch{return null}}function nn(t){if(!(typeof window>"u"))try{localStorage.setItem(_l,JSON.stringify(t))}catch{}}function yf(){if(!(typeof window>"u"))try{localStorage.removeItem(_l)}catch{}}function dm(t){return t.map(e=>({...e,mode:e.mode==="tmux"?"tmux":"shell",tmuxSessionName:e.tmuxSessionName??null,customName:e.customName===!0}))}function bf(t){return dm(t.map(e=>({sessionId:e.sessionId,name:e.name,customName:e.customName===!0,backendSessionId:e.backendSessionId,mode:e.mode,tmuxSessionName:e.tmuxSessionName,createdAt:e.createdAt,lastActivity:e.lastActivity}))).map((e,n)=>({...e,activeProgram:t[n]?.activeProgram??null,cwd:t[n]?.cwd??null}))}function vf(t){return t.map(e=>`${e.sessionId}:${e.name}:${e.customName}:${e.backendSessionId}:${e.mode}:${e.tmuxSessionName}:${e.lastActivity}:${e.activeProgram??""}:${e.cwd??""}`).join("|")}function Cc(t,e){return t.length===0?null:e&&t.some(n=>n.sessionId===e)?e:t[0]?.sessionId??null}function sC(){const t=lm()??[];return{sessions:t,activeSessionId:Cc(t,Ic())}}function IR(){const t=O.useRef(lm()).current,e=O.useRef(Ic()).current,[n,r]=O.useState(t??[]),[o,s]=O.useState(null),[i,a]=O.useState(t&&t.length>0?Cc(t,e):e),[c,l]=O.useState(t===null),d=O.useRef(!1),u=O.useRef(null),f=O.useRef(t===null),h=O.useRef(0),g=O.useRef(new Set),m=O.useRef(0);O.useEffect(()=>{f.current=c},[c]),O.useEffect(()=>{u.current=i},[i]);const b=O.useCallback(E=>{const P=Cc(E,u.current??Ic());return a(C=>C===P?C:P),jn(P),u.current=P,P},[]),w=O.useCallback((E,P)=>{const C=E.filter(D=>!g.current.has(D.sessionId));r(D=>vf(D)===vf(C)?D:C),nn(C),P?.reconcileActive&&b(C)},[b]),R=O.useCallback((E,P)=>{const C=g.current.size===0?E:{...E,clientSessions:E.clientSessions.filter(D=>!g.current.has(D.sessionId))};s(C),w(bf(C.clientSessions),P)},[w]),y=O.useCallback(()=>typeof window>"u"?[]:localStorage.getItem(Ra)?(localStorage.removeItem(Ra),yf(),jn(null),r([]),a(null),console.info("[session-persist] discarded legacy local session cache"),[]):[],[]),k=O.useCallback(async()=>{if(typeof window>"u")return[];const E=m.current;try{const P=await Ig(),C=bf(P.clientSessions);return E!==m.current?(console.info("[session-inventory] ignored restore snapshot superseded by a local mutation"),C.filter(D=>!g.current.has(D.sessionId))):(R(P,{reconcileActive:!0}),C.length>0?C:y())}catch(P){console.error("Failed to restore sessions from server:",P);try{return y()}catch(C){console.error("Failed to discard legacy local sessions:",C)}}finally{l(!1)}return[]},[R,y]),N=O.useCallback(async E=>{const P=++m.current,C=await Cg(E);return P===m.current&&(R(C.inventory),a(C.session.sessionId),jn(C.session.sessionId)),C},[R]),x=O.useCallback(async(E,P)=>{++m.current,g.current.add(E),oC(E),r(C=>{const D=C.filter(L=>L.sessionId!==E),M=P!=null&&D.some(L=>L.sessionId===P),F=u.current===E?M?P:nC(C,E,L=>L.sessionId):u.current;return a(F),jn(F),nn(D),D});try{await Tg(E)}catch(C){console.error("Failed to remove session from inventory:",C)}},[]),T=O.useCallback(E=>{const P=Date.now();r(C=>{const D=C.map(M=>M.sessionId===E?{...M,lastActivity:P}:M);return nn(D),D})},[]),S=O.useCallback(E=>{a(E),jn(E)},[]),v=O.useCallback(async(E,P)=>{const C=P.trim();if(!C)return;const D=++m.current;r(M=>{const F=M.map(L=>L.sessionId===E?{...L,name:C,customName:!0}:L);return nn(F),F});try{const M=await os(E,{name:C,customName:!0});D===m.current&&R(M)}catch(M){console.error("Failed to rename session in inventory:",M)}},[R]),A=O.useCallback(async E=>{const P=++m.current;r(C=>{const D=C.map(M=>M.sessionId===E?{...M,customName:!1}:M);return nn(D),D});try{const C=await os(E,{customName:!1});P===m.current&&R(C)}catch(C){console.error("Failed to reset session name in inventory:",C)}},[R]),_=O.useCallback(async E=>{const P=++m.current;r(C=>{const D=new Map(C.map(H=>[H.sessionId,H])),M=E.map(H=>D.get(H)).filter(H=>H!==void 0),F=new Set(E),L=C.filter(H=>!F.has(H.sessionId)),$=[...M,...L];return nn($),$});try{const C=await Rg(E);P===m.current&&R(C)}catch(C){console.error("Failed to reorder sessions in inventory:",C)}},[R]),B=O.useCallback(async()=>{++m.current;for(const E of n)g.current.add(E.sessionId);r([]),s(null),a(null),jn(null),yf(),typeof window<"u"&&localStorage.removeItem(Ra);try{await Pg()}catch(E){console.error("Failed to clear session inventory:",E)}},[n]),I=O.useCallback(async(E,P)=>{const C=++m.current;r(D=>{const M=D.map(F=>F.sessionId===E?{...F,backendSessionId:P}:F);return nn(M),M});try{const D=await os(E,{backendSessionId:P});C===m.current&&R(D)}catch(D){console.error("Failed to update session backend in inventory:",D)}},[R]);return O.useEffect(()=>{d.current||(d.current=!0,k())},[k]),O.useEffect(()=>om(P=>{if(P.type!=="client-state"||f.current)return;const C=typeof P.seq=="number"?P.seq:null;if(C!==null){if(C<h.current){console.warn("[session-inventory] ignored stale control snapshot",{seq:C,latestSeq:h.current});return}h.current=C}if(P.inventory){R(P.inventory,{reconcileActive:!0});return}const D=dm(P.clientState.sessions||[]);w(D,{reconcileActive:!0})}),[R,w]),{sessions:n,inventory:o,activeSessionId:i,isLoading:c,openSession:N,removeSession:x,updateSessionActivity:T,setActiveSession:S,updateSessionBackendId:I,renameSession:v,resetSessionCustomName:A,reorderSessions:_,clearAllSessions:B,restoreSessions:k}}const iC=256*1024,aC=256*1024,cC=128;function Sf(t,e=iC){if(!t)return[];if(t.length<=e)return[t];const n=[];let r=0;for(;r<t.length;){let o=Math.min(r+e,t.length);if(o<t.length){const s=t.lastIndexOf(`
35
- `,o);s>r&&(o=s+1)}n.push(t.slice(r,o)),r=o}return n}function lC(t,e=aC,n=cC){const r=new Map;let o=0,s=0;for(const i of[...t.keys()]){const a=t.get(i);if(!a||a.length===0){t.delete(i);continue}const c=[];for(;a.length>0;){const l=a[0];if(s>0&&(s>=n||o+l.length>e))break;a.shift(),c.push(l),o+=l.length,s+=1}if(c.length>0&&r.set(i,c),t.delete(i),a.length>0&&t.set(i,a),s>=n||o>=e)break}return r}async function um(t,e=!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",e?"readwrite":"readonly"),a=t(i.objectStore("state"));i.oncomplete=()=>o(a.result),i.onabort=i.onerror=()=>s(i.error)})}finally{r.close()}}const dC=t=>um(e=>e.put(t,t.targetPeerId),!0),uC=t=>um(e=>e.delete(t),!0),fm="termdock-pwa-notifications-enabled",hm="termdock-pwa-ai-notifications-enabled",pm="termdock-pwa-exit-notifications-enabled",gm="termdock-pwa-notification-alert-style",fC="termdock-notification-claim:",Rc=5e3,hC=1500,Tc="termdock-push-last-sync",xf=360*60*1e3,pC=10080*60*1e3,oo=new Map;function Ol(){return nt()?!0:typeof window<"u"&&typeof Notification<"u"&&"serviceWorker"in navigator&&window.isSecureContext}function gC(){if(typeof navigator>"u")return!1;const t=navigator.userAgent;return/iPad|iPhone|iPod/.test(t)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}function mC(){return typeof window>"u"?!1:!!(window.matchMedia("(display-mode: standalone)").matches||"standalone"in navigator&&navigator.standalone===!0)}function wC(){return nt()?!0:!(!Ol()||gC()&&!mC())}function CR(){return nt()?"granted":typeof Notification>"u"?"unsupported":Notification.permission}function Dl(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(fm)==="true"}catch{return!1}}function RR(t){if(!(typeof window>"u"))try{window.localStorage.setItem(fm,String(t))}catch{}}function $s(){if(typeof window>"u")return!0;try{const t=window.localStorage.getItem(hm);return t===null?!0:t==="true"}catch{return!0}}function TR(t){if(!(typeof window>"u"))try{window.localStorage.setItem(hm,String(t))}catch{}}function Pc(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(pm)==="true"}catch{return!1}}function PR(t){if(!(typeof window>"u"))try{window.localStorage.setItem(pm,String(t))}catch{}}function go(){if(typeof window>"u")return"normal";try{const t=window.localStorage.getItem(gm);if(t==="quiet"||t==="persistent")return t}catch{}return"normal"}function NR(t){if(!(typeof window>"u"))try{window.localStorage.setItem(gm,t)}catch{}}async function LR(){return nt()?"granted":Ol()?Notification.permission==="default"?Notification.requestPermission():Notification.permission:"unsupported"}function yC(){return typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus()}function bC(t){for(const[e,n]of oo)t-n>Rc&&oo.delete(e)}function vC(t){return t.dedupKey?.trim()?t.dedupKey.trim():t.tag?.trim()?t.tag.trim():[t.data?.sessionId,t.title,t.body].filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()).join("|")}function SC(t){const e=vC(t);if(!e)return!0;const n=Date.now();bC(n);const r=oo.get(e)??0;if(n-r<Rc)return!1;try{if(typeof window<"u"&&window.localStorage){const o=`${fC}${e}`,s=Number(window.localStorage.getItem(o)??"0");if(Number.isFinite(s)&&n-s<Rc)return oo.set(e,s),!1;Number.isFinite(s)&&s>0&&window.localStorage.removeItem(o),window.localStorage.setItem(o,String(n))}}catch{}return oo.set(e,n),!0}async function ui(){if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;try{const t=await navigator.serviceWorker.getRegistration()??null;return t?.active?t:await Promise.race([navigator.serviceWorker.ready,new Promise(n=>{window.setTimeout(()=>n(null),hC)})])??t}catch{return null}}function xC(t){const e="=".repeat((4-t.length%4)%4),n=(t+e).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 Fl(t,e){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/${t}`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(e)})}async function EC(t=!1,e=!1){if(nt())return!0;if(!Dl()||!wC()||Notification.permission!=="granted")return!1;const n=await ui();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()<pC);if(!s)try{s=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:xC(o.publicKey)})}catch(d){return console.warn(`[PWA notifications] Push subscription missing; re-subscribe failed${e?" (user gesture)":""}:`,d),!1}const a=Number(window.localStorage.getItem(Tc)??"0"),c=!o.subscription||o.subscription.endpoint!==s.endpoint||Date.now()-(o.subscription.updatedAt??0)>=xf;if(t||c||Date.now()-a>=xf||i){if(!(await Fl("subscribe",{subscription:s.toJSON(),aiEnabled:$s(),exitEnabled:Pc(),alertStyle:go(),locale:navigator.language})).ok)return!1;window.localStorage.setItem(Tc,String(Date.now()))}const l=re();return l&&await dC({targetPeerId:l.targetPeerId,addresses:br(l),routes:Zt(l),publicKey:o.publicKey,preferences:{aiEnabled:$s(),exitEnabled:Pc(),alertStyle:go(),locale:navigator.language}}),!0}catch(r){return console.warn("[PWA notifications] Push subscription sync failed:",r),!1}}async function BR(){if(nt())return;const e=await(await ui())?.pushManager?.getSubscription();try{await Fl("unsubscribe",{endpoint:e?.endpoint})}finally{const n=re();n&&await uC(n.targetPeerId),await e?.unsubscribe();try{window.localStorage.removeItem(Tc)}catch{}}}async function _R(){if(nt()||!Dl())return;(await Fl("preferences",{aiEnabled:$s(),exitEnabled:Pc(),alertStyle:go(),locale:navigator.language})).status===404&&await EC(!0)}async function OR(){if(!nt())try{const t=navigator;typeof t.clearAppBadge=="function"&&await t.clearAppBadge()}catch{}}async function DR(t){if(!nt())try{const e=await ui();if(!e||typeof e.getNotifications!="function")return;const n=`agent:${t}`,r=await e.getNotifications({tag:n});for(const s of r)s.close();const o=navigator;if(typeof o.setAppBadge=="function"){const s=await e.getNotifications();await o.setAppBadge(s.length)}}catch{}}async function Ta(t){if(!Dl()||!Ol())return!1;if(t.requireHidden!==!1&&yC())return!0;const e=nt();if(e){const s=t.alertStyle??go(),i=await e.showNotification({title:t.title,body:t.body,tag:t.tag,sessionId:t.data?.sessionId,silent:s==="quiet",persistent:s==="persistent"});return e.notificationDeliveryConfirmation===!0&&i}if(Notification.permission!=="granted")return!1;const n=await ui();if(t.deferToPush&&await n?.pushManager?.getSubscription())return!0;if(t.requireHidden!==!1){if(await n?.pushManager?.getSubscription())return!0}if(!SC(t))return!0;const r=t.alertStyle??go(),o={body:t.body,tag:t.tag,icon:"/pwa-192x192.png",badge:"/maskable-icon-512x512.png",requireInteraction:r==="persistent",renotify:r==="persistent"?!!t.tag:!1,silent:r==="quiet",vibrate:r==="quiet"?[]:[80,40,80],data:{url:t.data?.url??"/",sessionId:t.data?.sessionId}};try{if(n&&typeof n.showNotification=="function")return await n.showNotification(t.title,o),!0;const s=new Notification(t.title,o);return s.onclick=()=>{window.focus(),t.data?.url&&window.location.href!==t.data.url&&window.location.assign(t.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(t.title,i):new Notification(t.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 AC(){try{return localStorage.getItem("termdock:locale")||"en"}catch{return"en"}}function kC(t,e){return t==="zh"?{waitingTitle:`${e} 需要你的处理`,waitingBody:`${e} 需要你的处理。`,doneTitle:`${e} 已完成`,doneBody:`${e} 已完成,点按查看结果。`,exitedTitle:`${e} 已退出`,exitedBody:`${e} 已退出,点按查看结果。`}:{waitingTitle:`${e} needs your input`,waitingBody:`${e} is waiting for your input.`,doneTitle:`${e} finished`,doneBody:"Tap to see the result.",exitedTitle:`${e} exited`,exitedBody:"Tap to see the result."}}const Ef=1e6;function Kt(t){return{sessionId:t,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 fi="termdock-shell-titles-v1";function hi(){if(typeof window>"u")return{};try{const t=localStorage.getItem(fi);if(!t)return{};const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:{}}catch{return{}}}function IC(t){return hi()[t]??null}function CC(t,e){if(!(typeof window>"u"))try{const n=hi();e?n[t]=e:delete n[t],localStorage.setItem(fi,JSON.stringify(n))}catch{}}function RC(t){if(!(typeof window>"u"))try{const e=hi();delete e[t],localStorage.setItem(fi,JSON.stringify(e))}catch{}}const pi="termdock-agent-cache-v1";function Ml(){if(typeof window>"u")return{};try{const t=localStorage.getItem(pi);if(!t)return{};const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:{}}catch{return{}}}function TC(t,e){if(!(typeof window>"u"))try{const n=Ml();e?n[t]=e:delete n[t],localStorage.setItem(pi,JSON.stringify(n))}catch{}}function PC(t){if(!(typeof window>"u"))try{const e=Ml();delete e[t],localStorage.setItem(pi,JSON.stringify(e))}catch{}}function NC(){if(!(typeof window>"u"))try{localStorage.removeItem(pi)}catch{}}function FR(t){return Ml()[t]??null}function LC(){if(!(typeof window>"u"))try{localStorage.removeItem(fi)}catch{}}const Pa=ci((t,e)=>{const n={pendingChunksBySession:new Map,activitySessionIds:new Set,batchFlushRafRef:null},r=(i,a)=>{const c=new Map;return t(l=>{const d=new Map(l.sessions);let u=l.nextChunkId;const f=Date.now();for(const[h,g]of i){const m=d.get(h)??Kt(h);let b=m.bufferChunks.length>0?[...m.bufferChunks]:[],w=m.bufferLength;for(const R of g){const y=u++;b.push({id:y,data:R}),c.set(h,y),w+=R.length}for(;w>Ef&&b.length>1;){const R=b.shift();if(!R)break;w-=R.data.length}d.set(h,{...m,bufferChunks:b,bufferLength:w,lastOutputAt:a.has(h)?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=lC(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=>e().sessions.get(i),setActiveSessionId:i=>{if(t({activeSessionId:i}),i){const a=e().sessions.get(i);if(a?.agentNeedsReview){const c=new Map(e().sessions);c.set(i,{...a,agentNeedsReview:!1,updatedAt:Date.now()}),t({sessions:c}),a.terminalSessionId&&pc(a.terminalSessionId)}}},setTerminalSession:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i),f=!d||d.terminalSessionId!==a.sessionId?Kt(i):d??Kt(i),h=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,agentResumeRecovered:d?.agentResumeRecovered??f.agentResumeRecovered,shellTitle:d?.shellTitle??hi()[i]??f.shellTitle,sessionId:i,isConnecting:!1,history:h,updatedAt:Date.now()}),{sessions:l}})},setSessionHistory:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??Kt(i);return l.set(i,{...d,history:a,updatedAt:Date.now()}),{sessions:l}})},setSessionActiveProgram:(i,a,c=null,l=null)=>{t(d=>{const u=new Map(d.sessions),f=u.get(i)??Kt(i);return u.set(i,{...f,activeProgram:a,activeProgramRaw:l,activeProgramSource:c,updatedAt:Date.now()}),{sessions:u}})},setSessionCwd:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??Kt(i);return l.set(i,{...d,cwd:a,updatedAt:Date.now()}),{sessions:l}})},setSessionShellTitle:(i,a)=>{t(c=>{const l=c.sessions.get(i);if(!l||l.shellTitle===a)return c;const d=new Map(c.sessions);return d.set(i,{...l,shellTitle:a,updatedAt:Date.now()}),{sessions:d}}),CC(i,a)},setSessionPromptState:(i,a,c)=>{t(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)=>{t(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)=>{t(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)=>{t(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})})},setSessionAgentStatus:(i,a)=>{const c=e(),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,h=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,w=a.agentRich??l.agentRich,R=a.agentActivity??l.agentActivity,y=a.agentCwd!==void 0?a.agentCwd:l.agentCwd,k=c.activeSessionId!==i,N=l.agentStatus==="working"||l.agentStatus==="waiting"||l.agentStatus==="done",x=a.reviewed===!1||a.reviewed===null&&d===null&&N&&k;if(l.agentStatus===d&&l.agentIndicator===u&&l.agentStatusDetail===f&&l.agent===h&&l.agentMessage===g&&l.agentNativeSessionId===m&&l.agentResumeRecovered===b&&l.agentRich===w&&l.agentActivity===R&&l.agentCwd===y&&l.agentNeedsReview===x)return;const T=new Map(c.sessions);if(T.set(i,{...l,agentStatus:d,agentIndicator:u,agentStatusDetail:f,agent:h,agentMessage:g,agentNativeSessionId:m,agentResumeRecovered:b,agentRich:w,agentActivity:R,agentCwd:y,agentNeedsReview:x,updatedAt:Date.now()}),t({sessions:T}),h&&TC(i,h),!$s())return;const S=h?.displayName??l.agent?.displayName??"Agent",v=AC(),A=kC(v,S);if(d==="waiting"&&l.agentStatus!=="waiting"&&k){Ta({title:A.waitingTitle,body:g??A.waitingBody,tag:`agent:${i}`,dedupKey:`agent:${i}:waiting:${R}`,data:{url:"/",sessionId:i},deferToPush:!0});return}if(d==="done"&&l.agentStatus!=="done"&&k){Ta({title:A.doneTitle,body:A.doneBody,tag:`agent:${i}`,dedupKey:`agent:${i}:done:${R}`,data:{url:"/",sessionId:i},deferToPush:!0});return}d===null&&(l.agentStatus==="working"||l.agentStatus==="waiting")&&k&&Ta({title:A.exitedTitle,body:A.exitedBody,tag:`agent:${i}`,dedupKey:`agent:${i}:exited:${R}`,data:{url:"/",sessionId:i},deferToPush:!0})},setAgentResumeRecovered:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??Kt(i);return d.agentResumeRecovered===a?c:(l.set(i,{...d,agentResumeRecovered:a,updatedAt:Date.now()}),{sessions:l})})},clearAgentNeedsReview:i=>{const a=e().sessions.get(i);a?.agentNeedsReview&&(t(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&&pc(a.terminalSessionId))},setConnecting:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??Kt(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(...Sf(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 e().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 t(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 h=[];let g=0;for(const m of a)if(m)for(const b of Sf(m)){const w=f++;h.push({id:w,data:b}),c=w,g+=b.length}for(;g>Ef&&h.length>1;){const m=h.shift();if(!m)break;g-=m.data.length}return d.set(i,{...u,bufferChunks:h,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),t(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),t(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),t(a=>{const c=new Map(a.sessions);return c.delete(i),{sessions:c}}),RC(i),PC(i)},clearAllTerminalSessions:()=>{n.pendingChunksBySession.clear(),n.activitySessionIds.clear(),n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),t({sessions:new Map,nextChunkId:1}),LC(),NC()}}}),Nc="termdock:session-notice";function BC(){return O.useEffect(()=>{const t=()=>Ca.getState().view(!document.hidden&&Qo()?Pa.getState().activeSessionId:null);t();const e=Pa.subscribe((n,r)=>{n.activeSessionId!==r.activeSessionId&&t()});return document.addEventListener("visibilitychange",t),window.addEventListener(fo,t),()=>{e(),document.removeEventListener("visibilitychange",t),window.removeEventListener(fo,t),Ca.getState().view(null)}},[]),O.useEffect(()=>om(t=>{if(t.type!=="session-notice")return;Ca.getState().receive(t.sessionId,t.id);const e=re()?.targetPeerId,n=ht(),r=window.parent,o=sC().sessions.find(u=>u.sessionId===t.sessionId),s=Pa.getState().sessions.get(t.sessionId),i=s?.shellTitle??IC(t.sessionId),a=i===s?.cwd||i===zn(s?.cwd??null)?null:i,c=QI(o??{name:t.sessionName},s?.activeProgram??null,null,void 0,a,s?.promptState??null),l={...t,sessionName:c,key:`${e??"local"}:${t.id}`,open:()=>e&&n?n.focusSession(e,t.sessionId):(window.dispatchEvent(new CustomEvent("termdock:focus-session",{detail:t.sessionId})),!0)},d=r.document.createEvent("CustomEvent");d.initCustomEvent(Nc,!1,!1,l),r.dispatchEvent(d)}),[]),null}function _C(){const{locale:t}=di(),e=t==="zh",[n,r]=O.useState([]);O.useEffect(()=>{const i=a=>{const c=a.detail;r(l=>l.some(d=>d.key===c.key)?l:[...l,c])};return window.addEventListener(Nc,i),()=>window.removeEventListener(Nc,i)},[]);const o=O.useCallback(i=>{r(a=>a.filter(c=>c.key!==i))},[]),s=n[0];return s?Oc.createPortal(p.jsx(OC,{notice:s,remaining:n.length-1,chinese:e,onDismiss:o},s.key),document.body):null}function OC({notice:t,remaining:e,chinese:n,onDismiss:r}){const[o,s]=O.useState(!1);return p.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:[p.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:()=>{t.open()?r(t.key):s(!0)},children:[p.jsx(Jp,{size:16,className:"mt-0.5 shrink-0 text-primary","aria-hidden":"true"}),p.jsxs("span",{className:"min-w-0 flex-1",role:"status","aria-live":"polite","aria-atomic":"true",children:[p.jsxs("span",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium",title:t.sessionName,children:t.sessionName}),p.jsx(qE,{size:13,className:"shrink-0 text-muted-foreground/60 transition-colors group-hover:text-primary","aria-hidden":"true"})]}),t.title&&p.jsx("span",{className:"mt-1 block truncate text-[11px] text-muted-foreground",children:t.title}),p.jsx("span",{className:"mt-1.5 line-clamp-3 whitespace-pre-wrap break-words text-[13px] leading-relaxed text-foreground/85",title:t.message,children:t.message}),e>0&&p.jsx("span",{className:"mt-2 block text-[10px] text-muted-foreground",children:n?`还有 ${e} 条`:`${e} more`}),o&&p.jsx("span",{role:"alert",className:"mt-2 block text-xs text-warning",children:n?"暂时无法打开该服务,请重试。":"Unable to open the service. Please retry."})]})]}),p.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(t.key),children:p.jsx(og,{size:14})})]})}const Af=5*6e4;let Lc,mm=!1,wm=!1,kf=!1;const Bc=new Set;function If(){mm=!0,Bc.forEach(t=>t())}function DC(){return O.useSyncExternalStore(t=>(Bc.add(t),()=>{Bc.delete(t)}),()=>mm,()=>!1)}function FC(){window.dispatchEvent(new Event("termdock:before-update")),wm=!0,Lc?.waiting?Lc.waiting.postMessage({type:"SKIP_WAITING"}):window.location.reload()}function MC(t,e){let n=t;return()=>{if(!n){n=!0;return}e()}}function jC(){if(kf||typeof window>"u"||!("serviceWorker"in navigator))return;kf=!0,navigator.serviceWorker.addEventListener("controllerchange",MC(!!navigator.serviceWorker.controller,()=>{wm?window.location.reload():If()}));const t=()=>{navigator.serviceWorker.register("/sw.js",{scope:"/",updateViaCache:"none"}).then(e=>{Lc=e;const n=()=>{e.waiting&&If()},r=()=>{const i=e.installing;i?.addEventListener("statechange",()=>{i.state==="installed"&&navigator.serviceWorker.controller&&n()})};e.addEventListener("updatefound",r),r(),n();let o=0;const s=()=>{document.visibilityState!=="visible"||Date.now()-o<Af||(o=Date.now(),e.update().then(n).catch(()=>{}))};s(),window.setInterval(s,Af),document.addEventListener("visibilitychange",s)}).catch(()=>{})};document.readyState==="complete"?t():window.addEventListener("load",t,{once:!0})}function UC(){const t=DC(),[e,n]=O.useState(!1),{locale:r}=di();if(!t||e)return null;const o=r==="zh";return p.jsxs("div",{role:"status",className:"fixed bottom-16 left-1/2 z-toast flex max-w-[calc(100%-2rem)] -translate-x-1/2 items-center gap-3 rounded-lg border border-border bg-background px-4 py-3 text-sm text-foreground shadow-lg",children:[p.jsx("span",{children:o?"新版本已就绪":"An update is ready"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-primary",onClick:FC,children:o?"重新加载":"Reload"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-muted-foreground",onClick:()=>n(!0),children:o?"稍后":"Later"})]})}function ym(t){const e=document.querySelector('meta[name="theme-color"]');e&&e.setAttribute("content",t==="light"?"#FFFCF0":"#1C1B1A")}const bm=O.createContext(void 0);function MR({children:t}){const e=O.useContext(bm),n=e===void 0?typeof document>"u"?null:document.body:e;return n?Oc.createPortal(t,n):null}const $C={activeKey:"root",items:[]},HC=()=>()=>{},qC=()=>$C;function KC({host:t,item:e,visible:n,active:r}){const o=O.useRef(null);return O.useEffect(()=>{o.current?.toggleAttribute("inert",!r)},[r]),O.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{}t.attach(e.key,null)}},[t,e.key]),p.jsx("iframe",{ref:o,title:e.service?.label||"服务工作区","data-workspace-key":e.key,src:`/workspace.html?${Kp}=${encodeURIComponent(e.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 zC({children:t}){const e=window.parent===window?ht():void 0,n=O.useSyncExternalStore(e?.subscribe||HC,e?.snapshot||qC),[r,o]=O.useState(null),[s,i]=O.useState(()=>n.activeKey==="root"?"root":null),[a,c]=O.useState(),[l,d]=O.useState(!1),[u,f]=O.useState(),h=n.items.find(y=>y.key===n.activeKey),g=h?.rendered||a===n.activeKey?n.activeKey:s,m=g!==n.activeKey,b=m&&s===null;O.useLayoutEffect(()=>{if(!m||b){f(void 0);return}const y=()=>{const k=Array.from(document.querySelectorAll("iframe[data-workspace-key]")).find(_=>_.dataset.workspaceKey===s),S=(s==="root"?r:k?.contentDocument)?.querySelector('nav[aria-label="切换服务"]')?.closest("[data-sidebar-gesture-ignore]")?.getBoundingClientRect();if(!S||S.width===0||S.right<=0){f(void 0);return}const v=k?.getBoundingClientRect(),A=S.top+(v?.top??0)>=160;f({left:S.left+(v?.left??0)+12,top:(A?S.top-8:S.bottom+8)+(v?.top??0),width:Math.max(0,S.width-24),transform:A?"translateY(-100%)":"none"})};return y(),window.addEventListener("resize",y),()=>window.removeEventListener("resize",y)},[m,b,s,r]),O.useLayoutEffect(()=>{e?.present(g),m||i(g),r?.toggleAttribute("inert",g!=="root"||m)},[e,r,g,m]),O.useEffect(()=>{if(d(!1),!m)return;const y=setTimeout(()=>d(!0),8e3);return()=>clearTimeout(y)},[n.activeKey,m]),O.useEffect(()=>{c(void 0)},[n.activeKey]);const w=n.items.find(y=>y.key===s),R=h?.phase==="offline"?"网络已断开,等待恢复…":h?.phase==="reconnecting"?"连接暂未恢复,正在重试…":l?"连接时间较长,仍在等待服务…":b?"正在恢复服务…":"正在切换服务…";return O.useEffect(()=>{if(!e)return;const y=()=>{try{const k=JSON.parse(localStorage.getItem("termdock-color-theme")||"null");(k==="dark"||k==="light")&&(document.documentElement.dataset.theme=k,ym(k))}catch{}};return window.addEventListener("storage",y),()=>window.removeEventListener("storage",y)},[e]),O.useEffect(()=>{if(!e||!("serviceWorker"in navigator))return;const y=x=>{if(x.source!==navigator.serviceWorker.controller)return;const T=x.data;T?.type==="termdock:focus-session"&&typeof T.targetPeerId=="string"&&typeof T.sessionId=="string"&&e.focusSession(T.targetPeerId,T.sessionId)&&(x.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),x.stopImmediatePropagation())},k=async()=>{if("caches"in window)try{const x=await caches.open("termdock-notification-target-v1"),T=await x.match("/__termdock-notification-target");if(!T)return;const S=await T.json();typeof S.targetPeerId=="string"&&typeof S.sessionId=="string"&&Date.now()-S.clickedAt<3e4&&e.focusSession(S.targetPeerId,S.sessionId)&&await x.delete("/__termdock-notification-target")}catch{}},N=()=>{document.hidden||k()};return navigator.serviceWorker.addEventListener("message",y),document.addEventListener("visibilitychange",N),k(),()=>{navigator.serviceWorker.removeEventListener("message",y),document.removeEventListener("visibilitychange",N)}},[e]),e?p.jsxs("div",{className:"relative h-full w-full overflow-hidden bg-[var(--chrome-bg)]",children:[p.jsx("div",{ref:o,className:"isolate h-full w-full","aria-hidden":g!=="root"||m,style:{visibility:g==="root"?"visible":"hidden"},children:p.jsx(bm.Provider,{value:r,children:t})}),n.items.filter(y=>y.key!=="root").map(y=>p.jsx(KC,{host:e,item:y,visible:g===y.key,active:!m&&g===y.key},y.key)),b&&p.jsx("div",{className:"termdock-boot z-modal-panel",role:"status","aria-live":"polite",children:l||h?.phase==="offline"||h?.phase==="reconnecting"?p.jsxs("div",{className:"flex max-w-xs flex-col items-center gap-3 text-center",children:[p.jsx(je,{size:16,className:"animate-spin motion-reduce:animate-none","aria-hidden":"true"}),p.jsx("div",{className:"max-w-full truncate text-sm",children:h?.service?.label||"Termdock"}),p.jsx("div",{className:"text-xs text-muted-foreground",children:R}),p.jsx("button",{type:"button",className:"min-h-11 rounded-lg bg-surface-2 px-4 text-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>c(n.activeKey),children:"查看连接页面"})]}):p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"termdock-boot-spinner","aria-hidden":"true"}),p.jsx("span",{children:"Loading Termdock"})]})}),m&&!b&&p.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:y=>{if(y.key==="Escape"&&w?.service&&(y.preventDefault(),e.activate(w.service)),y.key==="Tab"){const k=Array.from(y.currentTarget.querySelectorAll("button")),N=k[0],x=k[k.length-1];y.shiftKey&&document.activeElement===N?(y.preventDefault(),x?.focus()):!y.shiftKey&&document.activeElement===x&&(y.preventDefault(),N?.focus())}},children:p.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:[p.jsxs("div",{role:"status","aria-live":"polite",className:"flex min-w-0 flex-1 items-center gap-2",children:[p.jsx(je,{size:16,className:"shrink-0 animate-spin text-primary motion-reduce:animate-none","aria-hidden":"true"}),p.jsxs("div",{className:"min-w-0",children:[p.jsx("div",{className:"truncate text-sm font-medium",children:h?.service?.label||"服务工作区"}),p.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:R})]})]}),p.jsxs("div",{className:"flex items-center justify-end gap-1",children:[l&&p.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:"查看连接页面"}),w?.service&&p.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:()=>e.activate(w.service),children:"取消"})]})]})})]}):t}const WC=O.lazy(()=>Jt(()=>import("./App-DA7cQLR7.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,3,7,8]))),GC=O.lazy(()=>Jt(()=>import("./DagPlayground-BvY_KblL.js"),__vite__mapDeps([9,10,2,1,11,7,3])).then(t=>({default:t.DagPlayground}))),VC=O.lazy(()=>Jt(()=>import("./DiffLab-Dra7cEKx.js"),__vite__mapDeps([12,2,1,13,8,14,3])).then(t=>({default:t.DiffLab}))),XC=O.lazy(()=>Jt(()=>import("./DiffReviewLab-BF8Dada6.js"),__vite__mapDeps([15,2,1,16,5,6,11,13,8,14,3])).then(t=>({default:t.DiffReviewLab})));KI();xE();TE();window.parent===window&&jC();const Vr=re();Vr&&Jt(()=>import("./App-DA7cQLR7.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,3,7,8])).catch(()=>{});!new URLSearchParams(location.search).has("dag-playground")&&!new URLSearchParams(location.search).has("diff-lab")&&!new URLSearchParams(location.search).has("diff-review-lab")&&uE(Vr?{...Vr,id:Vr.targetPeerId,label:Vr.serviceName||location.host}:void 0);try{const t=JSON.parse(window.localStorage.getItem("termdock-color-theme")||"null");(t==="dark"||t==="light")&&(document.documentElement.dataset.theme=t,ym(t))}catch{}LE.createRoot(document.getElementById("root")).render(p.jsx(We.StrictMode,{children:p.jsxs($2,{children:[window.parent===window&&p.jsxs(p.Fragment,{children:[p.jsx(UC,{}),p.jsx(_C,{})]}),p.jsx(LI,{children:p.jsx(O.Suspense,{fallback:p.jsx("div",{className:"termdock-boot",role:"status",children:"Loading Termdock"}),children:(()=>{const t=new URLSearchParams(window.location.search);return t.get("dag-playground")==="1"?p.jsx(GC,{}):t.get("diff-review-lab")==="1"?p.jsx(XC,{}):t.get("diff-lab")==="1"?p.jsx(VC,{}):p.jsx(zC,{children:p.jsxs(RI,{children:[p.jsx(BC,{}),p.jsx(WC,{})]})})})()})})]})}));export{aR as $,Al as A,Jp as B,Os as C,sm as D,yg as E,Iv as F,vA as G,JA as H,mR as I,hn as J,h2 as K,je as L,iE as M,f2 as N,OR as O,Q2 as P,YA as Q,ml as R,ai as S,a1 as T,lA as U,UI as V,fo as W,og as X,SA as Y,jA as Z,Jt as _,Zp as a,gp as a$,ci as a0,wk as a1,FI as a2,Ae as a3,MA as a4,Di as a5,xk as a6,e2 as a7,ER as a8,DR as a9,Vk as aA,g2 as aB,i2 as aC,n2 as aD,Tk as aE,CR as aF,d2 as aG,js as aH,JI as aI,QI as aJ,AR as aK,sr as aL,$s as aM,Pc as aN,go as aO,Dl as aP,nt as aQ,bA as aR,aA as aS,ck as aT,tk as aU,ik as aV,p2 as aW,_g as aX,ht as aY,Ia as aZ,Xh as a_,ok as aa,Sk as ab,Qk as ac,E1 as ad,mg as ae,xA as af,Y2 as ag,cR as ah,SR as ai,QA as aj,st as ak,hk as al,fk as am,mk as an,FA as ao,u2 as ap,c2 as aq,FR as ar,IC as as,a2 as at,l2 as au,lk as av,zn as aw,jk as ax,s2 as ay,w2 as az,$E as b,m2 as b$,Zk as b0,pk as b1,yk as b2,Bg as b3,Mk as b4,Uk as b5,Bk as b6,Fk as b7,Ok as b8,wC as b9,bR as bA,yR as bB,uR as bC,HA as bD,EA as bE,lR as bF,lc as bG,E2 as bH,Ik as bI,N2 as bJ,xR as bK,Pk as bL,Ck as bM,ak as bN,Un as bO,LR as bP,Nk as bQ,Rk as bR,VA as bS,wR as bT,ZA as bU,rk as bV,Ek as bW,k2 as bX,rR as bY,S1 as bZ,S2 as b_,Ol as ba,Qo as bb,p as bc,iR as bd,nk as be,b2 as bf,Ak as bg,I2 as bh,L2 as bi,qk as bj,ek as bk,uk as bl,R2 as bm,tC as bn,r2 as bo,pg as bp,Cg as bq,nC as br,kk as bs,$A as bt,gt as bu,sC as bv,Yk as bw,Gk as bx,Xk as by,Jk as bz,Qp as c,v2 as c0,C2 as c1,re as c2,Kk as c3,_2 as c4,B2 as c5,GA as c6,KA as c7,UA as c8,WA as c9,dk as cA,os as cB,Et as cC,t2 as cD,ig as cE,di as cF,hR as cG,Ca as cH,IR as cI,De as cJ,Pa as cK,vR as cL,we as cM,zk as cN,ii as cO,Ge as cP,pR as cQ,fR as cR,XA as ca,x2 as cb,P2 as cc,kR as cd,TR as ce,PR as cf,NR as cg,RR as ch,kg as ci,DA as cj,Fi as ck,gR as cl,Ta as cm,T2 as cn,om as co,A2 as cp,dR as cq,qA as cr,oR as cs,_R as ct,EC as cu,ym as cv,nR as cw,gk as cx,BR as cy,vk as cz,Sn as d,XE as e,eg as f,tg as g,LI as h,wg as i,n1 as j,ng as k,V2 as l,Ce as m,MR as n,zA as o,ol as p,Lt as q,y2 as r,sR as s,eC as t,$k as u,Dk as v,sl as w,Wk as x,eE as y,bk as z};
34
+ `)}async function PC(t){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(t),!0}catch{}const e=document.createElement("textarea");e.value=t,e.setAttribute("readonly",""),e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select();try{return document.execCommand("copy")}catch{return!1}finally{e.remove()}}function NC({error:t,componentStack:e}){const{t:n}=di(),[r,o]=We.useState("idle"),s=async()=>{const i=TC(t,e,{url:window.location.href,userAgent:navigator.userAgent,capturedAt:new Date().toISOString()});o(await PC(i)?"copied":"failed")};return p.jsx("div",{className:"flex h-full items-center justify-center p-4",children:p.jsxs("div",{className:"flex flex-col items-center gap-3 text-center max-w-md",children:[p.jsx("div",{className:"w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center",children:p.jsx("svg",{className:"w-6 h-6 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:p.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),p.jsxs("div",{className:"space-y-1",children:[p.jsx("h3",{className:"font-medium text-foreground",children:n("errorBoundary.title")}),p.jsx("p",{className:"text-sm text-muted-foreground",children:t?.message||n("errorBoundary.unexpected")})]}),p.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-center gap-2",children:[p.jsx("button",{type:"button",onClick:()=>{s()},className:"rounded-full bg-surface-2 px-5 py-2.5 text-sm font-medium text-foreground ring-1 ring-border/15 transition hover:bg-surface-elevated active:scale-[0.97]",children:n(r==="copied"?"errorBoundary.copied":r==="failed"?"errorBoundary.copyFailed":"errorBoundary.copyDetails")}),p.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"rounded-full bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground shadow-sm transition-all hover:bg-primary/90 active:scale-[0.97]",children:n("errorBoundary.retry")})]})]})})}class LC extends We.Component{state={hasError:!1,error:null,componentStack:""};static getDerivedStateFromError(e){return{hasError:!0,error:e,componentStack:""}}componentDidCatch(e,n){console.error("Terminal error caught by boundary:",e,n),this.setState({componentStack:n.componentStack??""})}render(){return this.state.hasError?this.props.fallback?this.props.fallback:p.jsx(NC,{error:this.state.error,componentStack:this.state.componentStack}):this.props.children}}function we(){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 BC="debug",_C="termdock:debug";function ff(t){return t?new Set(t.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean)):new Set}function OC(){if(typeof window>"u")return new Set;const t=ff(new URLSearchParams(window.location.search).get(BC));let e=new Set;try{e=ff(window.localStorage.getItem(_C))}catch{e=new Set}const n=new Set([...t,...e]);return n.has("1")||n.has("true")||n.has("*")||n.has("all")?new Set(["*"]):n}function DC(t){const e=OC();return e.has("*")||e.has(t)}function FC(t){const e=DC(t);return(...n)=>{e&&console.log(`[debug:${t}]`,...n)}}const hf=80,MC=60,jC="termdock:viewport-keyboard-change",UC="termdock:viewport-layout-change",It=240,pf=640,gf=360,$C=1500;function HC({measuredHeight:t,documentVisible:e,editableFocused:n}){return e&&n&&t>0}function Ca(){if(typeof document>"u")return!1;const t=document.activeElement;return t instanceof HTMLElement&&t.matches('input:not([type="hidden"]), textarea, select, [contenteditable]:not([contenteditable="false"])')}const Us=t=>{const e=typeof t=="number"?t:Number.parseFloat(typeof t=="string"?t:"0");return Number.isFinite(e)&&e>0?Math.round(e):0},Jg=(t,e)=>{const n=t.map(Us).filter(r=>r>0);return n.find(r=>r>=It)??n[0]??e},ro=()=>typeof window>"u"?pf:Jg([we().innerHeight,document.documentElement?.clientHeight,document.body?.clientHeight,we().visualViewport?.height,window.screen?.availHeight,window.screen?.height],pf),Qg=()=>typeof window>"u"?gf:Jg([we().innerWidth,document.documentElement?.clientWidth,document.body?.clientWidth,we().visualViewport?.width,window.screen?.availWidth,window.screen?.width],gf),qt=t=>{const e=Number.parseFloat(t||"0");return Number.isFinite(e)?Math.max(0,Math.round(e)):0},em=()=>typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,qC=()=>typeof window>"u"?!1:we().navigator.standalone===!0||we().matchMedia?.("(display-mode: standalone)").matches===!0,tm=()=>{if(typeof window>"u"||!em()||!qC())return{top:0,right:0,bottom:0,left:0};if(!(ro()>=Qg()))return{top:0,right:0,bottom:0,left:0};const e=window.screen?.width||window.innerWidth,n=window.screen?.height||window.innerHeight,r=Math.min(e,n),o=Math.max(e,n);return r>=700?{top:20,right:0,bottom:20,left:0}:o<780?{top:20,right:0,bottom:0,left:0}:{top:o>=852?59:o>=844?47:44,right:0,bottom:34,left:0}};function KC(t="--app-vh"){if(typeof window>"u"||typeof document>"u")return;const e=Us(we().visualViewport?.height),n=Math.max(0,Math.round(we().visualViewport?.offsetTop??0)),r=ro(),s=e>=It?Math.min(r,e+n):r,i=Math.max(r,s),a=document.documentElement.style;a.setProperty(t,`${Math.max(s,It)}px`),a.setProperty("--app-base-vh",`${Math.max(i,It)}px`),a.setProperty("--app-visible-vh",`${Math.max(s,It)}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=tm();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 vR(t={}){const{cssVarName:e="--app-vh"}=t,n=We.useMemo(()=>FC("viewport"),[]),r=We.useCallback(()=>{if(typeof window>"u")return 0;const d=we().visualViewport,u=ro();if(!d)return u;const f=Us(d.height);if(f<It&&u>=It)return u;const h=d.offsetTop,m=f<u-1&&h>0&&h<=96?f+h:f,b=Math.max(0,Math.min(u,m));return b>0?Math.round(b):u},[]),[o,s]=We.useState(r),i=We.useRef(0),a=We.useRef(0),c=We.useRef(0),l=We.useRef(!1);return We.useEffect(()=>{if(typeof window>"u")return;let d=null,u=0,f=null,h="",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 I={top:0,right:0,bottom:0,left:0};try{const L=m();if(L){const $=getComputedStyle(L);I={top:qt($.paddingTop),right:qt($.paddingRight),bottom:qt($.paddingBottom),left:qt($.paddingLeft)}}}catch{}const D=we();if(D!==window){const L=D.getComputedStyle(D.document.documentElement);I={top:Math.max(I.top,qt(L.getPropertyValue("--safe-top-inset"))),right:Math.max(I.right,qt(L.getPropertyValue("--safe-right-inset"))),bottom:Math.max(I.bottom,qt(L.getPropertyValue("--safe-bottom-inset"))),left:Math.max(I.left,qt(L.getPropertyValue("--safe-left-inset")))}}const M=tm(),F={top:Math.max(I.top,M.top),right:Math.max(I.right,M.right),bottom:Math.max(I.bottom,M.bottom),left:Math.max(I.left,M.left)};return document.documentElement.style.setProperty("--safe-top-inset",`${F.top}px`),document.documentElement.style.setProperty("--safe-right-inset",`${F.right}px`),document.documentElement.style.setProperty("--safe-bottom-inset",`${F.bottom}px`),document.documentElement.style.setProperty("--safe-left-inset",`${F.left}px`),F},w=(I,D,M,F)=>{const L=Math.max(D,M);if(i.current===0){i.current=L,a.current=I,document.documentElement.style.setProperty("--app-base-vh",`${L}px`);return}const $=Math.abs(I-a.current),H=F<=hf;($>MC||H)&&(i.current=L,a.current=I,document.documentElement.style.setProperty("--app-base-vh",`${L}px`))},R=(I="event")=>{d=null;const D=r(),M=Math.round(we().visualViewport?.offsetTop??0),F=Us(we().visualViewport?.height),L=F>=It?F:D,$=ro(),H=Qg(),U=Math.max(0,L+M),q=b(),K=q.bottom,X=Math.max(0,i.current-U-K);w(H,$,U,X),s(vr=>vr===D?vr:D);const z=Number.parseInt(document.documentElement.style.getPropertyValue(e)||"0",10);document.documentElement.style.setProperty(e,`${D}px`),document.documentElement.style.setProperty("--app-vv-offset-top",`${M}px`);const W=i.current,V=Math.min(D,L),Y=Math.max(0,Math.min(W,U)),Q=Math.max(0,Math.round(W-V-K)),ae=Ca(),ce=HC({measuredHeight:Q,documentVisible:document.visibilityState==="visible",editableFocused:ae}),ie=ce?Q:0,$e=ie>=hf,ke=-ie,Ge=ie;document.documentElement.style.setProperty("--kb-translate-y",`${ke}px`),document.documentElement.style.setProperty("--kb-margin-top",`${Ge}px`),document.documentElement.style.setProperty("--kb-height",`${ie}px`),document.documentElement.style.setProperty("--app-visible-vh",`${Y}px`);const en=Math.abs(ie-c.current)>1,Oe=$e!==l.current;(en||Oe)&&(c.current=ie,l.current=$e,document.dispatchEvent(new CustomEvent(jC,{detail:{baseHeight:W,visibleHeight:Y,visualViewportHeight:L,offsetTop:M,keyboardHeight:ie,isOpen:$e,source:I}}))),(z!==D||M>0||en||Oe)&&n("sync",{cssVarName:e,innerHeight:$,baseHeight:W,rawViewportHeight:L,offsetTop:M,visibleHeight:Y,rawHeight:D,appliedHeight:D,keyboardViewportHeight:V,measuredKeyboardHeight:Q,editableFocused:ae,applyKeyboardInset:ce,keyboardHeight:ie,isKeyboardOpen:$e,safeAreaInsets:q,source:I}),document.dispatchEvent(new CustomEvent(UC,{detail:{height:D,baseHeight:W,visibleHeight:Y,offsetTop:M,source:I}}))},y=()=>{d===null&&(d=window.requestAnimationFrame(()=>{d=null;const I=we(),D=I.visualViewport,M=[I.innerWidth,I.innerHeight,D?.width,D?.height,D?.offsetTop,D?.offsetLeft,document.visibilityState,Ca()].join(":"),F=f;f=null,(F||M!==h)&&(h=M,R(F||"viewport.settle")),performance.now()<u&&y()}))},k=(I="event")=>{(I.includes("visibilitychange")||I.includes("pageshow"))&&n("schedule",{source:I}),f=I,em()&&document.visibilityState==="visible"&&(u=performance.now()+$C),y()};k("mount");const N=()=>k("resize"),x=()=>k("orientationchange"),T=()=>k("visualViewport.resize"),S=()=>k("visualViewport.scroll"),v=()=>k("focusin"),A=()=>k("focusout"),_=I=>{u=0;const D=document.activeElement;D instanceof HTMLElement&&Ca()&&D.blur(),c.current=0,l.current=!1;const M=Math.max(i.current,ro(),It),F=document.documentElement.style;F.setProperty(e,`${M}px`),F.setProperty("--app-visible-vh",`${M}px`),F.setProperty("--app-vv-offset-top","0px"),F.setProperty("--kb-translate-y","0px"),F.setProperty("--kb-margin-top","0px"),F.setProperty("--kb-height","0px"),s(L=>L===M?L:M),n("keyboard session reset",{source:I,baseHeight:M})};window.addEventListener("resize",N),window.addEventListener("orientationchange",x),we().visualViewport?.addEventListener("resize",T),we().visualViewport?.addEventListener("scroll",S),document.addEventListener("focusin",v),document.addEventListener("focusout",A);const B=I=>{n("resume",{source:I,innerHeight:Math.round(window.innerHeight),visualViewport:we().visualViewport?{width:Math.round(we().visualViewport.width),height:Math.round(we().visualViewport.height),offsetTop:Math.round(we().visualViewport.offsetTop)}:null,hidden:document.hidden}),k(I)},C=()=>{document.hidden?_("visibilitychange:hidden"):B("visibilitychange")},E=()=>B("pageshow"),P=()=>_("pagehide");return document.addEventListener("visibilitychange",C),window.addEventListener("pageshow",E),window.addEventListener("pagehide",P),()=>{window.removeEventListener("resize",N),window.removeEventListener("orientationchange",x),we().visualViewport?.removeEventListener("resize",T),we().visualViewport?.removeEventListener("scroll",S),document.removeEventListener("focusin",v),document.removeEventListener("focusout",A),document.removeEventListener("visibilitychange",C),window.removeEventListener("pageshow",E),window.removeEventListener("pagehide",P),d!==null&&window.cancelAnimationFrame(d),g?.remove()}},[e,n,r]),o}const zC=1e3,WC=2e4,VC=9e4,GC=5e3,ee={ws:null,listeners:new Set,reconnectAttempt:0,reconnectTimer:null,idleCloseTimer:null,closing:!1};let Xo=0,ar=null;function XC(){return typeof window>"u"?null:`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/control/ws`}function nm(){ee.idleCloseTimer&&(clearTimeout(ee.idleCloseTimer),ee.idleCloseTimer=null)}function YC(){nm(),!(ee.ws&&ee.ws.readyState===WebSocket.OPEN)&&(ee.idleCloseTimer=setTimeout(()=>{ee.idleCloseTimer=null,ee.listeners.size===0&&ZC()},GC))}function ZC(){if(ee.ws){try{ee.ws.close()}catch{}ee.ws=null}ar&&(clearInterval(ar),ar=null)}function mf(){if(ee.reconnectTimer)return;const t=Math.min(zC*Math.pow(2,ee.reconnectAttempt),WC);ee.reconnectAttempt+=1,ee.reconnectTimer=setTimeout(()=>{ee.reconnectTimer=null,rm()},t)}function rm(){const t=XC();if(!t||ee.ws&&ee.ws.readyState===WebSocket.OPEN)return;let e;try{e=Gp(t)}catch{mf();return}ee.ws=e,e.onopen=()=>{ee.reconnectAttempt=0,Xo=Date.now(),ar||(ar=setInterval(()=>{if(!(!ee.ws||ee.ws.readyState!==WebSocket.OPEN)&&Xo>0&&Date.now()-Xo>VC)try{ee.ws.close()}catch{}},3e4),ar.unref?.())},e.onmessage=n=>{Xo=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 ee.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 ee.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 ee.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 ee.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 ee.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 ee.listeners)try{i(s)}catch(a){console.error("[clientStateSync] listener threw:",a)}},e.onclose=()=>{ee.ws===e&&(ee.ws=null),ee.listeners.size>0&&mf()},e.onerror=()=>{}}function om(t){return ee.listeners.add(t),nm(),ee.ws||rm(),()=>{ee.listeners.delete(t),ee.listeners.size===0&&YC()}}const Ia=ci(t=>({unread:{},viewing:null,receive:(e,n)=>t(r=>{const o=r.unread[e]??[];return r.viewing===e||o.includes(n)?r:{unread:{...r.unread,[e]:[...o,n]}}}),view:e=>t(n=>{if(!e||!n.unread[e])return n.viewing===e?n:{viewing:e};const r={...n.unread};return delete r[e],{viewing:e,unread:r}})})),sm=new Set(["bash","zsh","fish","sh","dash","ksh","tcsh","csh","nu"]);function zn(t){if(!t)return null;if(t==="/")return"/";const e=t.replace(/\/+$/,"").split("/");return e[e.length-1]||t}function JC(t,e,n,r=sm,o=null,s=null){if(t.customName)return{primary:t.name,secondary:zn(n)};if(o){const a=zn(n),c=o===n||o===a;if(s!=="idle"&&!r.has(o)&&!c)return{primary:o,secondary:a}}if(e&&!r.has(e))return{primary:e,secondary:zn(n)};const i=zn(n);return i?{primary:i,secondary:null}:{primary:t.name,secondary:null}}function QC(t,e,n,r=sm,o=null,s=null){return JC(t,e,n,r,o,s).primary}function eI(t,e,n){const r=[],o=new Map;for(const s of t){const i=e(s),a=i&&i.trim().length>0?i:"";let c=o.get(a);c||(c={key:a,label:a?zn(a)??a:n,sessions:[]},o.set(a,c),r.push(c)),c.sessions.push(s)}return r.sort((s,i)=>(s.key===""?1:0)-(i.key===""?1:0))}function SR(t){return t&&t.trim().length>0?t:""}function xR(t,e,n){const r=[...t],[o]=r.splice(e,1);return o?(r.splice(n,0,o),r.flatMap(s=>s.sessions.map(i=>i.id))):t.flatMap(s=>s.sessions.map(i=>i.id))}function tI(t,e){const n=new Set;return t.flatMap(r=>{const o=[...new Set(r.sessionIds)].filter(s=>e.has(s)&&!n.has(s));return o.length<(r.federated?1:2)?[]:(o.forEach(s=>n.add(s)),[{...r,sessionIds:o}])})}function ER(t,e,n,r,o=[],s=[]){const i=new Map(t.map(g=>[g.id,g])),a=tI(s,new Set(i.keys())),c=new Map,l=new Map,d=o.filter(g=>g.sessionIds.length>=2&&g.sessionIds.every(m=>i.has(m))),u=(g,m)=>{const b=i.get(m);g.forEach(w=>{c.set(w,g),l.set(w,b)})};for(const g of a){const m=new Set(g.sessionIds),b=new Map;for(const y of d)y.sessionIds.every(k=>m.has(k))&&y.sessionIds.forEach(k=>b.set(k,y.sessionIds));const w=new Set,R=g.sessionIds.flatMap(y=>{if(w.has(y))return[];const k=b.get(y)??[y];return k.forEach(N=>w.add(N)),k});u(R,g.sessionIds[0])}for(const g of d)g.sessionIds.some(m=>c.has(m))||u(g.sessionIds,g.sessionIds[0]);const f=g=>{const m=new Set;return g.flatMap(b=>{if(m.has(b.id))return[];const w=c.get(b.id)??[b.id];return w.forEach(R=>m.add(R)),w.map(R=>i.get(R))})};if(!n)return{arranged:f(t),groups:[]};const h=eI(t,g=>e(l.get(g.id)??g),r).map(g=>({...g,sessions:f(g.sessions)}));return{arranged:h.flatMap(g=>g.sessions),groups:h}}function nI(t,e,n){const r=t.findIndex(o=>n(o)===e);return r<0?null:t[r+1]?n(t[r+1]):r>0?n(t[r-1]):null}const im="termdock-session-fonts-v1",wf=8,rI=32;function am(t){return Number.isFinite(t)?Math.max(wf,Math.min(rI,Math.round(t))):wf}function Bl(){if(typeof window>"u")return{};try{const t=window.localStorage.getItem(im);if(!t)return{};const e=JSON.parse(t);if(typeof e!="object"||e===null)return{};const n={};for(const[r,o]of Object.entries(e))typeof o=="number"&&Number.isFinite(o)&&(n[r]=am(o));return n}catch{return{}}}function cm(t){if(!(typeof window>"u"))try{window.localStorage.setItem(im,JSON.stringify(t))}catch{}}function AR(t){return Bl()[t]??null}function kR(t,e){if(typeof window>"u")return;const n=Bl(),r=e===null?null:am(e);r===null?delete n[t]:n[t]=r,cm(n),window.dispatchEvent(new CustomEvent("termfontchange",{detail:{sessionId:t,fontSize:r}}))}function oI(t){if(typeof window>"u")return;const e=Bl();t in e&&(delete e[t],cm(e))}const Ra="termdock-sessions",kc="termdock-active-session",_l="termdock-sessions-cache";function Cc(){try{const t=localStorage.getItem(kc);return t&&t.trim().length>0?t:null}catch{return null}}function jn(t){try{t?localStorage.setItem(kc,t):localStorage.removeItem(kc)}catch{}}function lm(){if(typeof window>"u")return null;try{const t=localStorage.getItem(_l);if(!t)return null;const e=JSON.parse(t);return Array.isArray(e)?e.filter(n=>typeof n=="object"&&n!==null&&typeof n.sessionId=="string"&&typeof n.name=="string"):null}catch{return null}}function nn(t){if(!(typeof window>"u"))try{localStorage.setItem(_l,JSON.stringify(t))}catch{}}function yf(){if(!(typeof window>"u"))try{localStorage.removeItem(_l)}catch{}}function dm(t){return t.map(e=>({...e,mode:e.mode==="tmux"?"tmux":"shell",tmuxSessionName:e.tmuxSessionName??null,customName:e.customName===!0}))}function bf(t){return dm(t.map(e=>({sessionId:e.sessionId,name:e.name,customName:e.customName===!0,backendSessionId:e.backendSessionId,mode:e.mode,tmuxSessionName:e.tmuxSessionName,createdAt:e.createdAt,lastActivity:e.lastActivity}))).map((e,n)=>({...e,activeProgram:t[n]?.activeProgram??null,cwd:t[n]?.cwd??null}))}function vf(t){return t.map(e=>`${e.sessionId}:${e.name}:${e.customName}:${e.backendSessionId}:${e.mode}:${e.tmuxSessionName}:${e.lastActivity}:${e.activeProgram??""}:${e.cwd??""}`).join("|")}function Ic(t,e){return t.length===0?null:e&&t.some(n=>n.sessionId===e)?e:t[0]?.sessionId??null}function sI(){const t=lm()??[];return{sessions:t,activeSessionId:Ic(t,Cc())}}function CR(){const t=O.useRef(lm()).current,e=O.useRef(Cc()).current,[n,r]=O.useState(t??[]),[o,s]=O.useState(null),[i,a]=O.useState(t&&t.length>0?Ic(t,e):e),[c,l]=O.useState(t===null),d=O.useRef(!1),u=O.useRef(null),f=O.useRef(t===null),h=O.useRef(0),g=O.useRef(new Set),m=O.useRef(0);O.useEffect(()=>{f.current=c},[c]),O.useEffect(()=>{u.current=i},[i]);const b=O.useCallback(E=>{const P=Ic(E,u.current??Cc());return a(I=>I===P?I:P),jn(P),u.current=P,P},[]),w=O.useCallback((E,P)=>{const I=E.filter(D=>!g.current.has(D.sessionId));r(D=>vf(D)===vf(I)?D:I),nn(I),P?.reconcileActive&&b(I)},[b]),R=O.useCallback((E,P)=>{const I=g.current.size===0?E:{...E,clientSessions:E.clientSessions.filter(D=>!g.current.has(D.sessionId))};s(I),w(bf(I.clientSessions),P)},[w]),y=O.useCallback(()=>typeof window>"u"?[]:localStorage.getItem(Ra)?(localStorage.removeItem(Ra),yf(),jn(null),r([]),a(null),console.info("[session-persist] discarded legacy local session cache"),[]):[],[]),k=O.useCallback(async()=>{if(typeof window>"u")return[];const E=m.current;try{const P=await Cg(),I=bf(P.clientSessions);return E!==m.current?(console.info("[session-inventory] ignored restore snapshot superseded by a local mutation"),I.filter(D=>!g.current.has(D.sessionId))):(R(P,{reconcileActive:!0}),I.length>0?I:y())}catch(P){console.error("Failed to restore sessions from server:",P);try{return y()}catch(I){console.error("Failed to discard legacy local sessions:",I)}}finally{l(!1)}return[]},[R,y]),N=O.useCallback(async E=>{const P=++m.current,I=await Ig(E);return P===m.current&&(R(I.inventory),a(I.session.sessionId),jn(I.session.sessionId)),I},[R]),x=O.useCallback(async(E,P)=>{++m.current,g.current.add(E),oI(E),r(I=>{const D=I.filter(L=>L.sessionId!==E),M=P!=null&&D.some(L=>L.sessionId===P),F=u.current===E?M?P:nI(I,E,L=>L.sessionId):u.current;return a(F),jn(F),nn(D),D});try{await Tg(E)}catch(I){console.error("Failed to remove session from inventory:",I)}},[]),T=O.useCallback(E=>{const P=Date.now();r(I=>{const D=I.map(M=>M.sessionId===E?{...M,lastActivity:P}:M);return nn(D),D})},[]),S=O.useCallback(E=>{a(E),jn(E)},[]),v=O.useCallback(async(E,P)=>{const I=P.trim();if(!I)return;const D=++m.current;r(M=>{const F=M.map(L=>L.sessionId===E?{...L,name:I,customName:!0}:L);return nn(F),F});try{const M=await os(E,{name:I,customName:!0});D===m.current&&R(M)}catch(M){console.error("Failed to rename session in inventory:",M)}},[R]),A=O.useCallback(async E=>{const P=++m.current;r(I=>{const D=I.map(M=>M.sessionId===E?{...M,customName:!1}:M);return nn(D),D});try{const I=await os(E,{customName:!1});P===m.current&&R(I)}catch(I){console.error("Failed to reset session name in inventory:",I)}},[R]),_=O.useCallback(async E=>{const P=++m.current;r(I=>{const D=new Map(I.map(H=>[H.sessionId,H])),M=E.map(H=>D.get(H)).filter(H=>H!==void 0),F=new Set(E),L=I.filter(H=>!F.has(H.sessionId)),$=[...M,...L];return nn($),$});try{const I=await Rg(E);P===m.current&&R(I)}catch(I){console.error("Failed to reorder sessions in inventory:",I)}},[R]),B=O.useCallback(async()=>{++m.current;for(const E of n)g.current.add(E.sessionId);r([]),s(null),a(null),jn(null),yf(),typeof window<"u"&&localStorage.removeItem(Ra);try{await Pg()}catch(E){console.error("Failed to clear session inventory:",E)}},[n]),C=O.useCallback(async(E,P)=>{const I=++m.current;r(D=>{const M=D.map(F=>F.sessionId===E?{...F,backendSessionId:P}:F);return nn(M),M});try{const D=await os(E,{backendSessionId:P});I===m.current&&R(D)}catch(D){console.error("Failed to update session backend in inventory:",D)}},[R]);return O.useEffect(()=>{d.current||(d.current=!0,k())},[k]),O.useEffect(()=>om(P=>{if(P.type!=="client-state"||f.current)return;const I=typeof P.seq=="number"?P.seq:null;if(I!==null){if(I<h.current){console.warn("[session-inventory] ignored stale control snapshot",{seq:I,latestSeq:h.current});return}h.current=I}if(P.inventory){R(P.inventory,{reconcileActive:!0});return}const D=dm(P.clientState.sessions||[]);w(D,{reconcileActive:!0})}),[R,w]),{sessions:n,inventory:o,activeSessionId:i,isLoading:c,openSession:N,removeSession:x,updateSessionActivity:T,setActiveSession:S,updateSessionBackendId:C,renameSession:v,resetSessionCustomName:A,reorderSessions:_,clearAllSessions:B,restoreSessions:k}}const iI=256*1024,aI=256*1024,cI=128;function Sf(t,e=iI){if(!t)return[];if(t.length<=e)return[t];const n=[];let r=0;for(;r<t.length;){let o=Math.min(r+e,t.length);if(o<t.length){const s=t.lastIndexOf(`
35
+ `,o);s>r&&(o=s+1)}n.push(t.slice(r,o)),r=o}return n}function lI(t,e=aI,n=cI){const r=new Map;let o=0,s=0;for(const i of[...t.keys()]){const a=t.get(i);if(!a||a.length===0){t.delete(i);continue}const c=[];for(;a.length>0;){const l=a[0];if(s>0&&(s>=n||o+l.length>e))break;a.shift(),c.push(l),o+=l.length,s+=1}if(c.length>0&&r.set(i,c),t.delete(i),a.length>0&&t.set(i,a),s>=n||o>=e)break}return r}async function um(t,e=!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",e?"readwrite":"readonly"),a=t(i.objectStore("state"));i.oncomplete=()=>o(a.result),i.onabort=i.onerror=()=>s(i.error)})}finally{r.close()}}const dI=t=>um(e=>e.put(t,t.targetPeerId),!0),uI=t=>um(e=>e.delete(t),!0),fm="termdock-pwa-notifications-enabled",hm="termdock-pwa-ai-notifications-enabled",pm="termdock-pwa-exit-notifications-enabled",gm="termdock-pwa-notification-alert-style",fI="termdock-notification-claim:",Rc=5e3,hI=1500,Tc="termdock-push-last-sync",xf=360*60*1e3,pI=10080*60*1e3,oo=new Map;function Ol(){return nt()?!0:typeof window<"u"&&typeof Notification<"u"&&"serviceWorker"in navigator&&window.isSecureContext}function gI(){if(typeof navigator>"u")return!1;const t=navigator.userAgent;return/iPad|iPhone|iPod/.test(t)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}function mI(){return typeof window>"u"?!1:!!(window.matchMedia("(display-mode: standalone)").matches||"standalone"in navigator&&navigator.standalone===!0)}function wI(){return nt()?!0:!(!Ol()||gI()&&!mI())}function IR(){return nt()?"granted":typeof Notification>"u"?"unsupported":Notification.permission}function Dl(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(fm)==="true"}catch{return!1}}function RR(t){if(!(typeof window>"u"))try{window.localStorage.setItem(fm,String(t))}catch{}}function $s(){if(typeof window>"u")return!0;try{const t=window.localStorage.getItem(hm);return t===null?!0:t==="true"}catch{return!0}}function TR(t){if(!(typeof window>"u"))try{window.localStorage.setItem(hm,String(t))}catch{}}function Pc(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(pm)==="true"}catch{return!1}}function PR(t){if(!(typeof window>"u"))try{window.localStorage.setItem(pm,String(t))}catch{}}function go(){if(typeof window>"u")return"normal";try{const t=window.localStorage.getItem(gm);if(t==="quiet"||t==="persistent")return t}catch{}return"normal"}function NR(t){if(!(typeof window>"u"))try{window.localStorage.setItem(gm,t)}catch{}}async function LR(){return nt()?"granted":Ol()?Notification.permission==="default"?Notification.requestPermission():Notification.permission:"unsupported"}function yI(){return typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus()}function bI(t){for(const[e,n]of oo)t-n>Rc&&oo.delete(e)}function vI(t){return t.dedupKey?.trim()?t.dedupKey.trim():t.tag?.trim()?t.tag.trim():[t.data?.sessionId,t.title,t.body].filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()).join("|")}function SI(t){const e=vI(t);if(!e)return!0;const n=Date.now();bI(n);const r=oo.get(e)??0;if(n-r<Rc)return!1;try{if(typeof window<"u"&&window.localStorage){const o=`${fI}${e}`,s=Number(window.localStorage.getItem(o)??"0");if(Number.isFinite(s)&&n-s<Rc)return oo.set(e,s),!1;Number.isFinite(s)&&s>0&&window.localStorage.removeItem(o),window.localStorage.setItem(o,String(n))}}catch{}return oo.set(e,n),!0}async function ui(){if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;try{const t=await navigator.serviceWorker.getRegistration()??null;return t?.active?t:await Promise.race([navigator.serviceWorker.ready,new Promise(n=>{window.setTimeout(()=>n(null),hI)})])??t}catch{return null}}function xI(t){const e="=".repeat((4-t.length%4)%4),n=(t+e).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 Fl(t,e){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/${t}`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(e)})}async function EI(t=!1,e=!1){if(nt())return!0;if(!Dl()||!wI()||Notification.permission!=="granted")return!1;const n=await ui();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()<pI);if(!s)try{s=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:xI(o.publicKey)})}catch(d){return console.warn(`[PWA notifications] Push subscription missing; re-subscribe failed${e?" (user gesture)":""}:`,d),!1}const a=Number(window.localStorage.getItem(Tc)??"0"),c=!o.subscription||o.subscription.endpoint!==s.endpoint||Date.now()-(o.subscription.updatedAt??0)>=xf;if(t||c||Date.now()-a>=xf||i){if(!(await Fl("subscribe",{subscription:s.toJSON(),aiEnabled:$s(),exitEnabled:Pc(),alertStyle:go(),locale:navigator.language})).ok)return!1;window.localStorage.setItem(Tc,String(Date.now()))}const l=re();return l&&await dI({targetPeerId:l.targetPeerId,addresses:br(l),routes:Zt(l),publicKey:o.publicKey,preferences:{aiEnabled:$s(),exitEnabled:Pc(),alertStyle:go(),locale:navigator.language}}),!0}catch(r){return console.warn("[PWA notifications] Push subscription sync failed:",r),!1}}async function BR(){if(nt())return;const e=await(await ui())?.pushManager?.getSubscription();try{await Fl("unsubscribe",{endpoint:e?.endpoint})}finally{const n=re();n&&await uI(n.targetPeerId),await e?.unsubscribe();try{window.localStorage.removeItem(Tc)}catch{}}}async function _R(){if(nt()||!Dl())return;(await Fl("preferences",{aiEnabled:$s(),exitEnabled:Pc(),alertStyle:go(),locale:navigator.language})).status===404&&await EI(!0)}async function OR(){if(!nt())try{const t=navigator;typeof t.clearAppBadge=="function"&&await t.clearAppBadge()}catch{}}async function DR(t){if(!nt())try{const e=await ui();if(!e||typeof e.getNotifications!="function")return;const n=`agent:${t}`,r=await e.getNotifications({tag:n});for(const s of r)s.close();const o=navigator;if(typeof o.setAppBadge=="function"){const s=await e.getNotifications();await o.setAppBadge(s.length)}}catch{}}async function Ta(t){if(!Dl()||!Ol())return!1;if(t.requireHidden!==!1&&yI())return!0;const e=nt();if(e){const s=t.alertStyle??go(),i=await e.showNotification({title:t.title,body:t.body,tag:t.tag,sessionId:t.data?.sessionId,silent:s==="quiet",persistent:s==="persistent"});return e.notificationDeliveryConfirmation===!0&&i}if(Notification.permission!=="granted")return!1;const n=await ui();if(t.deferToPush&&await n?.pushManager?.getSubscription())return!0;if(t.requireHidden!==!1){if(await n?.pushManager?.getSubscription())return!0}if(!SI(t))return!0;const r=t.alertStyle??go(),o={body:t.body,tag:t.tag,icon:"/pwa-192x192.png",badge:"/maskable-icon-512x512.png",requireInteraction:r==="persistent",renotify:r==="persistent"?!!t.tag:!1,silent:r==="quiet",vibrate:r==="quiet"?[]:[80,40,80],data:{url:t.data?.url??"/",sessionId:t.data?.sessionId}};try{if(n&&typeof n.showNotification=="function")return await n.showNotification(t.title,o),!0;const s=new Notification(t.title,o);return s.onclick=()=>{window.focus(),t.data?.url&&window.location.href!==t.data.url&&window.location.assign(t.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(t.title,i):new Notification(t.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 AI(){try{return localStorage.getItem("termdock:locale")||"en"}catch{return"en"}}function kI(t,e){return t==="zh"?{waitingTitle:`${e} 需要你的处理`,waitingBody:`${e} 需要你的处理。`,doneTitle:`${e} 已完成`,doneBody:`${e} 已完成,点按查看结果。`,exitedTitle:`${e} 已退出`,exitedBody:`${e} 已退出,点按查看结果。`}:{waitingTitle:`${e} needs your input`,waitingBody:`${e} is waiting for your input.`,doneTitle:`${e} finished`,doneBody:"Tap to see the result.",exitedTitle:`${e} exited`,exitedBody:"Tap to see the result."}}const Ef=1e6;function Kt(t){return{sessionId:t,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 fi="termdock-shell-titles-v1";function hi(){if(typeof window>"u")return{};try{const t=localStorage.getItem(fi);if(!t)return{};const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:{}}catch{return{}}}function CI(t){return hi()[t]??null}function II(t,e){if(!(typeof window>"u"))try{const n=hi();e?n[t]=e:delete n[t],localStorage.setItem(fi,JSON.stringify(n))}catch{}}function RI(t){if(!(typeof window>"u"))try{const e=hi();delete e[t],localStorage.setItem(fi,JSON.stringify(e))}catch{}}const pi="termdock-agent-cache-v1";function Ml(){if(typeof window>"u")return{};try{const t=localStorage.getItem(pi);if(!t)return{};const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:{}}catch{return{}}}function TI(t,e){if(!(typeof window>"u"))try{const n=Ml();e?n[t]=e:delete n[t],localStorage.setItem(pi,JSON.stringify(n))}catch{}}function PI(t){if(!(typeof window>"u"))try{const e=Ml();delete e[t],localStorage.setItem(pi,JSON.stringify(e))}catch{}}function NI(){if(!(typeof window>"u"))try{localStorage.removeItem(pi)}catch{}}function FR(t){return Ml()[t]??null}function LI(){if(!(typeof window>"u"))try{localStorage.removeItem(fi)}catch{}}const Pa=ci((t,e)=>{const n={pendingChunksBySession:new Map,activitySessionIds:new Set,batchFlushRafRef:null},r=(i,a)=>{const c=new Map;return t(l=>{const d=new Map(l.sessions);let u=l.nextChunkId;const f=Date.now();for(const[h,g]of i){const m=d.get(h)??Kt(h);let b=m.bufferChunks.length>0?[...m.bufferChunks]:[],w=m.bufferLength;for(const R of g){const y=u++;b.push({id:y,data:R}),c.set(h,y),w+=R.length}for(;w>Ef&&b.length>1;){const R=b.shift();if(!R)break;w-=R.data.length}d.set(h,{...m,bufferChunks:b,bufferLength:w,lastOutputAt:a.has(h)?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=lI(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=>e().sessions.get(i),setActiveSessionId:i=>{if(t({activeSessionId:i}),i){const a=e().sessions.get(i);if(a?.agentNeedsReview){const c=new Map(e().sessions);c.set(i,{...a,agentNeedsReview:!1,updatedAt:Date.now()}),t({sessions:c}),a.terminalSessionId&&pc(a.terminalSessionId)}}},setTerminalSession:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i),f=!d||d.terminalSessionId!==a.sessionId?Kt(i):d??Kt(i),h=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,agentResumeRecovered:d?.agentResumeRecovered??f.agentResumeRecovered,shellTitle:d?.shellTitle??hi()[i]??f.shellTitle,sessionId:i,isConnecting:!1,history:h,updatedAt:Date.now()}),{sessions:l}})},setSessionHistory:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??Kt(i);return l.set(i,{...d,history:a,updatedAt:Date.now()}),{sessions:l}})},setSessionActiveProgram:(i,a,c=null,l=null)=>{t(d=>{const u=new Map(d.sessions),f=u.get(i)??Kt(i);return u.set(i,{...f,activeProgram:a,activeProgramRaw:l,activeProgramSource:c,updatedAt:Date.now()}),{sessions:u}})},setSessionCwd:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??Kt(i);return l.set(i,{...d,cwd:a,updatedAt:Date.now()}),{sessions:l}})},setSessionShellTitle:(i,a)=>{t(c=>{const l=c.sessions.get(i);if(!l||l.shellTitle===a)return c;const d=new Map(c.sessions);return d.set(i,{...l,shellTitle:a,updatedAt:Date.now()}),{sessions:d}}),II(i,a)},setSessionPromptState:(i,a,c)=>{t(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)=>{t(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)=>{t(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)=>{t(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})})},setSessionAgentStatus:(i,a)=>{const c=e(),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,h=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,w=a.agentRich??l.agentRich,R=a.agentActivity??l.agentActivity,y=a.agentCwd!==void 0?a.agentCwd:l.agentCwd,k=c.activeSessionId!==i,N=l.agentStatus==="working"||l.agentStatus==="waiting"||l.agentStatus==="done",x=a.reviewed===!1||a.reviewed===null&&d===null&&N&&k;if(l.agentStatus===d&&l.agentIndicator===u&&l.agentStatusDetail===f&&l.agent===h&&l.agentMessage===g&&l.agentNativeSessionId===m&&l.agentResumeRecovered===b&&l.agentRich===w&&l.agentActivity===R&&l.agentCwd===y&&l.agentNeedsReview===x)return;const T=new Map(c.sessions);if(T.set(i,{...l,agentStatus:d,agentIndicator:u,agentStatusDetail:f,agent:h,agentMessage:g,agentNativeSessionId:m,agentResumeRecovered:b,agentRich:w,agentActivity:R,agentCwd:y,agentNeedsReview:x,updatedAt:Date.now()}),t({sessions:T}),h&&TI(i,h),!$s())return;const S=h?.displayName??l.agent?.displayName??"Agent",v=AI(),A=kI(v,S);if(d==="waiting"&&l.agentStatus!=="waiting"&&k){Ta({title:A.waitingTitle,body:g??A.waitingBody,tag:`agent:${i}`,dedupKey:`agent:${i}:waiting:${R}`,data:{url:"/",sessionId:i},deferToPush:!0});return}if(d==="done"&&l.agentStatus!=="done"&&k){Ta({title:A.doneTitle,body:A.doneBody,tag:`agent:${i}`,dedupKey:`agent:${i}:done:${R}`,data:{url:"/",sessionId:i},deferToPush:!0});return}d===null&&(l.agentStatus==="working"||l.agentStatus==="waiting")&&k&&Ta({title:A.exitedTitle,body:A.exitedBody,tag:`agent:${i}`,dedupKey:`agent:${i}:exited:${R}`,data:{url:"/",sessionId:i},deferToPush:!0})},setAgentResumeRecovered:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??Kt(i);return d.agentResumeRecovered===a?c:(l.set(i,{...d,agentResumeRecovered:a,updatedAt:Date.now()}),{sessions:l})})},clearAgentNeedsReview:i=>{const a=e().sessions.get(i);a?.agentNeedsReview&&(t(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&&pc(a.terminalSessionId))},setConnecting:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??Kt(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(...Sf(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 e().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 t(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 h=[];let g=0;for(const m of a)if(m)for(const b of Sf(m)){const w=f++;h.push({id:w,data:b}),c=w,g+=b.length}for(;g>Ef&&h.length>1;){const m=h.shift();if(!m)break;g-=m.data.length}return d.set(i,{...u,bufferChunks:h,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),t(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),t(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),t(a=>{const c=new Map(a.sessions);return c.delete(i),{sessions:c}}),RI(i),PI(i)},clearAllTerminalSessions:()=>{n.pendingChunksBySession.clear(),n.activitySessionIds.clear(),n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),t({sessions:new Map,nextChunkId:1}),LI(),NI()}}}),Nc="termdock:session-notice";function BI(){return O.useEffect(()=>{const t=()=>Ia.getState().view(!document.hidden&&Qo()?Pa.getState().activeSessionId:null);t();const e=Pa.subscribe((n,r)=>{n.activeSessionId!==r.activeSessionId&&t()});return document.addEventListener("visibilitychange",t),window.addEventListener(fo,t),()=>{e(),document.removeEventListener("visibilitychange",t),window.removeEventListener(fo,t),Ia.getState().view(null)}},[]),O.useEffect(()=>om(t=>{if(t.type!=="session-notice")return;Ia.getState().receive(t.sessionId,t.id);const e=re()?.targetPeerId,n=ht(),r=window.parent,o=sI().sessions.find(u=>u.sessionId===t.sessionId),s=Pa.getState().sessions.get(t.sessionId),i=s?.shellTitle??CI(t.sessionId),a=i===s?.cwd||i===zn(s?.cwd??null)?null:i,c=QC(o??{name:t.sessionName},s?.activeProgram??null,null,void 0,a,s?.promptState??null),l={...t,sessionName:c,key:`${e??"local"}:${t.id}`,open:()=>e&&n?n.focusSession(e,t.sessionId):(window.dispatchEvent(new CustomEvent("termdock:focus-session",{detail:t.sessionId})),!0)},d=r.document.createEvent("CustomEvent");d.initCustomEvent(Nc,!1,!1,l),r.dispatchEvent(d)}),[]),null}function _I(){const{locale:t}=di(),e=t==="zh",[n,r]=O.useState([]);O.useEffect(()=>{const i=a=>{const c=a.detail;r(l=>l.some(d=>d.key===c.key)?l:[...l,c])};return window.addEventListener(Nc,i),()=>window.removeEventListener(Nc,i)},[]);const o=O.useCallback(i=>{r(a=>a.filter(c=>c.key!==i))},[]),s=n[0];return s?Oc.createPortal(p.jsx(OI,{notice:s,remaining:n.length-1,chinese:e,onDismiss:o},s.key),document.body):null}function OI({notice:t,remaining:e,chinese:n,onDismiss:r}){const[o,s]=O.useState(!1);return p.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:[p.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:()=>{t.open()?r(t.key):s(!0)},children:[p.jsx(Jp,{size:16,className:"mt-0.5 shrink-0 text-primary","aria-hidden":"true"}),p.jsxs("span",{className:"min-w-0 flex-1",role:"status","aria-live":"polite","aria-atomic":"true",children:[p.jsxs("span",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium",title:t.sessionName,children:t.sessionName}),p.jsx(qE,{size:13,className:"shrink-0 text-muted-foreground/60 transition-colors group-hover:text-primary","aria-hidden":"true"})]}),t.title&&p.jsx("span",{className:"mt-1 block truncate text-[11px] text-muted-foreground",children:t.title}),p.jsx("span",{className:"mt-1.5 line-clamp-3 whitespace-pre-wrap break-words text-[13px] leading-relaxed text-foreground/85",title:t.message,children:t.message}),e>0&&p.jsx("span",{className:"mt-2 block text-[10px] text-muted-foreground",children:n?`还有 ${e} 条`:`${e} more`}),o&&p.jsx("span",{role:"alert",className:"mt-2 block text-xs text-warning",children:n?"暂时无法打开该服务,请重试。":"Unable to open the service. Please retry."})]})]}),p.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(t.key),children:p.jsx(og,{size:14})})]})}const Af=5*6e4;let Lc,mm=!1,wm=!1,kf=!1;const Bc=new Set;function Cf(){mm=!0,Bc.forEach(t=>t())}function DI(){return O.useSyncExternalStore(t=>(Bc.add(t),()=>{Bc.delete(t)}),()=>mm,()=>!1)}function FI(){window.dispatchEvent(new Event("termdock:before-update")),wm=!0,Lc?.waiting?Lc.waiting.postMessage({type:"SKIP_WAITING"}):window.location.reload()}function MI(t,e){let n=t;return()=>{if(!n){n=!0;return}e()}}function jI(){if(kf||typeof window>"u"||!("serviceWorker"in navigator))return;kf=!0,navigator.serviceWorker.addEventListener("controllerchange",MI(!!navigator.serviceWorker.controller,()=>{wm?window.location.reload():Cf()}));const t=()=>{navigator.serviceWorker.register("/sw.js",{scope:"/",updateViaCache:"none"}).then(e=>{Lc=e;const n=()=>{e.waiting&&Cf()},r=()=>{const i=e.installing;i?.addEventListener("statechange",()=>{i.state==="installed"&&navigator.serviceWorker.controller&&n()})};e.addEventListener("updatefound",r),r(),n();let o=0;const s=()=>{document.visibilityState!=="visible"||Date.now()-o<Af||(o=Date.now(),e.update().then(n).catch(()=>{}))};s(),window.setInterval(s,Af),document.addEventListener("visibilitychange",s)}).catch(()=>{})};document.readyState==="complete"?t():window.addEventListener("load",t,{once:!0})}function UI(){const t=DI(),[e,n]=O.useState(!1),{locale:r}=di();if(!t||e)return null;const o=r==="zh";return p.jsxs("div",{role:"status",className:"fixed bottom-16 left-1/2 z-toast flex max-w-[calc(100%-2rem)] -translate-x-1/2 items-center gap-3 rounded-lg border border-border bg-background px-4 py-3 text-sm text-foreground shadow-lg",children:[p.jsx("span",{children:o?"新版本已就绪":"An update is ready"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-primary",onClick:FI,children:o?"重新加载":"Reload"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-muted-foreground",onClick:()=>n(!0),children:o?"稍后":"Later"})]})}function ym(t){const e=document.querySelector('meta[name="theme-color"]');e&&e.setAttribute("content",t==="light"?"#FFFCF0":"#1C1B1A")}const bm=O.createContext(void 0);function MR({children:t}){const e=O.useContext(bm),n=e===void 0?typeof document>"u"?null:document.body:e;return n?Oc.createPortal(t,n):null}const $I={activeKey:"root",items:[]},HI=()=>()=>{},qI=()=>$I;function KI({host:t,item:e,visible:n,active:r}){const o=O.useRef(null);return O.useEffect(()=>{o.current?.toggleAttribute("inert",!r)},[r]),O.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{}t.attach(e.key,null)}},[t,e.key]),p.jsx("iframe",{ref:o,title:e.service?.label||"服务工作区","data-workspace-key":e.key,src:`/workspace.html?${Kp}=${encodeURIComponent(e.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 zI({children:t}){const e=window.parent===window?ht():void 0,n=O.useSyncExternalStore(e?.subscribe||HI,e?.snapshot||qI),[r,o]=O.useState(null),[s,i]=O.useState(()=>n.activeKey==="root"?"root":null),[a,c]=O.useState(),[l,d]=O.useState(!1),[u,f]=O.useState(),h=n.items.find(y=>y.key===n.activeKey),g=h?.rendered||a===n.activeKey?n.activeKey:s,m=g!==n.activeKey,b=m&&s===null;O.useLayoutEffect(()=>{if(!m||b){f(void 0);return}const y=()=>{const k=Array.from(document.querySelectorAll("iframe[data-workspace-key]")).find(_=>_.dataset.workspaceKey===s),S=(s==="root"?r:k?.contentDocument)?.querySelector('nav[aria-label="切换服务"]')?.closest("[data-sidebar-gesture-ignore]")?.getBoundingClientRect();if(!S||S.width===0||S.right<=0){f(void 0);return}const v=k?.getBoundingClientRect(),A=S.top+(v?.top??0)>=160;f({left:S.left+(v?.left??0)+12,top:(A?S.top-8:S.bottom+8)+(v?.top??0),width:Math.max(0,S.width-24),transform:A?"translateY(-100%)":"none"})};return y(),window.addEventListener("resize",y),()=>window.removeEventListener("resize",y)},[m,b,s,r]),O.useLayoutEffect(()=>{e?.present(g),m||i(g),r?.toggleAttribute("inert",g!=="root"||m)},[e,r,g,m]),O.useEffect(()=>{if(d(!1),!m)return;const y=setTimeout(()=>d(!0),8e3);return()=>clearTimeout(y)},[n.activeKey,m]),O.useEffect(()=>{c(void 0)},[n.activeKey]);const w=n.items.find(y=>y.key===s),R=h?.phase==="offline"?"网络已断开,等待恢复…":h?.phase==="reconnecting"?"连接暂未恢复,正在重试…":l?"连接时间较长,仍在等待服务…":b?"正在恢复服务…":"正在切换服务…";return O.useEffect(()=>{if(!e)return;const y=()=>{try{const k=JSON.parse(localStorage.getItem("termdock-color-theme")||"null");(k==="dark"||k==="light")&&(document.documentElement.dataset.theme=k,ym(k))}catch{}};return window.addEventListener("storage",y),()=>window.removeEventListener("storage",y)},[e]),O.useEffect(()=>{if(!e||!("serviceWorker"in navigator))return;const y=x=>{if(x.source!==navigator.serviceWorker.controller)return;const T=x.data;T?.type==="termdock:focus-session"&&typeof T.targetPeerId=="string"&&typeof T.sessionId=="string"&&e.focusSession(T.targetPeerId,T.sessionId)&&(x.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),x.stopImmediatePropagation())},k=async()=>{if("caches"in window)try{const x=await caches.open("termdock-notification-target-v1"),T=await x.match("/__termdock-notification-target");if(!T)return;const S=await T.json();typeof S.targetPeerId=="string"&&typeof S.sessionId=="string"&&Date.now()-S.clickedAt<3e4&&e.focusSession(S.targetPeerId,S.sessionId)&&await x.delete("/__termdock-notification-target")}catch{}},N=()=>{document.hidden||k()};return navigator.serviceWorker.addEventListener("message",y),document.addEventListener("visibilitychange",N),k(),()=>{navigator.serviceWorker.removeEventListener("message",y),document.removeEventListener("visibilitychange",N)}},[e]),e?p.jsxs("div",{className:"relative h-full w-full overflow-hidden bg-[var(--chrome-bg)]",children:[p.jsx("div",{ref:o,className:"isolate h-full w-full","aria-hidden":g!=="root"||m,style:{visibility:g==="root"?"visible":"hidden"},children:p.jsx(bm.Provider,{value:r,children:t})}),n.items.filter(y=>y.key!=="root").map(y=>p.jsx(KI,{host:e,item:y,visible:g===y.key,active:!m&&g===y.key},y.key)),b&&p.jsx("div",{className:"termdock-boot z-modal-panel",role:"status","aria-live":"polite",children:l||h?.phase==="offline"||h?.phase==="reconnecting"?p.jsxs("div",{className:"flex max-w-xs flex-col items-center gap-3 text-center",children:[p.jsx(je,{size:16,className:"animate-spin motion-reduce:animate-none","aria-hidden":"true"}),p.jsx("div",{className:"max-w-full truncate text-sm",children:h?.service?.label||"Termdock"}),p.jsx("div",{className:"text-xs text-muted-foreground",children:R}),p.jsx("button",{type:"button",className:"min-h-11 rounded-lg bg-surface-2 px-4 text-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>c(n.activeKey),children:"查看连接页面"})]}):p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"termdock-boot-spinner","aria-hidden":"true"}),p.jsx("span",{children:"Loading Termdock"})]})}),m&&!b&&p.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:y=>{if(y.key==="Escape"&&w?.service&&(y.preventDefault(),e.activate(w.service)),y.key==="Tab"){const k=Array.from(y.currentTarget.querySelectorAll("button")),N=k[0],x=k[k.length-1];y.shiftKey&&document.activeElement===N?(y.preventDefault(),x?.focus()):!y.shiftKey&&document.activeElement===x&&(y.preventDefault(),N?.focus())}},children:p.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:[p.jsxs("div",{role:"status","aria-live":"polite",className:"flex min-w-0 flex-1 items-center gap-2",children:[p.jsx(je,{size:16,className:"shrink-0 animate-spin text-primary motion-reduce:animate-none","aria-hidden":"true"}),p.jsxs("div",{className:"min-w-0",children:[p.jsx("div",{className:"truncate text-sm font-medium",children:h?.service?.label||"服务工作区"}),p.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:R})]})]}),p.jsxs("div",{className:"flex items-center justify-end gap-1",children:[l&&p.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:"查看连接页面"}),w?.service&&p.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:()=>e.activate(w.service),children:"取消"})]})]})})]}):t}const WI=O.lazy(()=>Jt(()=>import("./App-ySHLLxfl.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,3,7,8]))),VI=O.lazy(()=>Jt(()=>import("./DagPlayground-CBUX-s8X.js"),__vite__mapDeps([9,10,2,1,11,7,3])).then(t=>({default:t.DagPlayground}))),GI=O.lazy(()=>Jt(()=>import("./DiffLab-DD8m9b0G.js"),__vite__mapDeps([12,2,1,13,8,14,3])).then(t=>({default:t.DiffLab}))),XI=O.lazy(()=>Jt(()=>import("./DiffReviewLab-BS1rFkx9.js"),__vite__mapDeps([15,2,1,16,5,6,11,13,8,14,3])).then(t=>({default:t.DiffReviewLab})));KC();xE();TE();window.parent===window&&jI();const Gr=re();Gr&&Jt(()=>import("./App-ySHLLxfl.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,3,7,8])).catch(()=>{});!new URLSearchParams(location.search).has("dag-playground")&&!new URLSearchParams(location.search).has("diff-lab")&&!new URLSearchParams(location.search).has("diff-review-lab")&&uE(Gr?{...Gr,id:Gr.targetPeerId,label:Gr.serviceName||location.host}:void 0);try{const t=JSON.parse(window.localStorage.getItem("termdock-color-theme")||"null");(t==="dark"||t==="light")&&(document.documentElement.dataset.theme=t,ym(t))}catch{}LE.createRoot(document.getElementById("root")).render(p.jsx(We.StrictMode,{children:p.jsxs($2,{children:[window.parent===window&&p.jsxs(p.Fragment,{children:[p.jsx(UI,{}),p.jsx(_I,{})]}),p.jsx(LC,{children:p.jsx(O.Suspense,{fallback:p.jsx("div",{className:"termdock-boot",role:"status",children:"Loading Termdock"}),children:(()=>{const t=new URLSearchParams(window.location.search);return t.get("dag-playground")==="1"?p.jsx(VI,{}):t.get("diff-review-lab")==="1"?p.jsx(XI,{}):t.get("diff-lab")==="1"?p.jsx(GI,{}):p.jsx(zI,{children:p.jsxs(RC,{children:[p.jsx(BI,{}),p.jsx(WI,{})]})})})()})})]})}));export{jA as $,Al as A,Jp as B,Os as C,sm as D,yg as E,bk as F,Cv as G,vA as H,JA as I,mR as J,hn as K,je as L,iE as M,h2 as N,f2 as O,Q2 as P,OR as Q,YA as R,ai as S,a1 as T,ml as U,UC as V,fo as W,og as X,lA as Y,SA as Z,Jt as _,Zp as a,Xh as a$,aR as a0,ci as a1,wk as a2,FC as a3,Ae as a4,MA as a5,Di as a6,xk as a7,e2 as a8,ER as a9,w2 as aA,Gk as aB,g2 as aC,i2 as aD,n2 as aE,Tk as aF,IR as aG,d2 as aH,js as aI,JC as aJ,QC as aK,AR as aL,sr as aM,$s as aN,Pc as aO,go as aP,Dl as aQ,nt as aR,bA as aS,aA as aT,ck as aU,tk as aV,ik as aW,p2 as aX,_g as aY,ht as aZ,Ca as a_,DR as aa,ok as ab,Sk as ac,Qk as ad,E1 as ae,mg as af,xA as ag,Y2 as ah,cR as ai,SR as aj,QA as ak,st as al,hk as am,fk as an,mk as ao,FA as ap,u2 as aq,c2 as ar,FR as as,CI as at,a2 as au,l2 as av,lk as aw,zn as ax,jk as ay,s2 as az,$E as b,S2 as b$,gp as b0,Zk as b1,pk as b2,yk as b3,Bg as b4,Mk as b5,Uk as b6,Bk as b7,Fk as b8,Ok as b9,Jk as bA,bR as bB,yR as bC,uR as bD,HA as bE,EA as bF,lR as bG,lc as bH,E2 as bI,Ck as bJ,N2 as bK,xR as bL,Pk as bM,Ik as bN,ak as bO,Un as bP,LR as bQ,Nk as bR,Rk as bS,GA as bT,wR as bU,ZA as bV,rk as bW,Ek as bX,k2 as bY,rR as bZ,S1 as b_,wI as ba,Ol as bb,Qo as bc,p as bd,iR as be,nk as bf,b2 as bg,Ak as bh,C2 as bi,L2 as bj,qk as bk,ek as bl,uk as bm,R2 as bn,tI as bo,r2 as bp,pg as bq,Ig as br,nI as bs,kk as bt,$A as bu,gt as bv,sI as bw,Yk as bx,Vk as by,Xk as bz,Qp as c,m2 as c0,v2 as c1,I2 as c2,re as c3,Kk as c4,_2 as c5,Gp as c6,B2 as c7,VA as c8,KA as c9,BR as cA,vk as cB,dk as cC,os as cD,Et as cE,t2 as cF,ig as cG,di as cH,hR as cI,Ia as cJ,CR as cK,De as cL,Pa as cM,vR as cN,we as cO,zk as cP,ii as cQ,Ve as cR,pR as cS,fR as cT,UA as ca,WA as cb,XA as cc,x2 as cd,P2 as ce,kR as cf,TR as cg,PR as ch,NR as ci,RR as cj,kg as ck,DA as cl,Fi as cm,gR as cn,Ta as co,T2 as cp,om as cq,A2 as cr,dR as cs,qA as ct,oR as cu,_R as cv,EI as cw,ym as cx,nR as cy,gk as cz,Sn as d,XE as e,eg as f,tg as g,LC as h,wg as i,n1 as j,ng as k,G2 as l,rg as m,Ie as n,MR as o,zA as p,ol as q,Lt as r,y2 as s,sR as t,eI as u,$k as v,Dk as w,sl as x,Wk as y,eE as z};