@yuriai/web 0.3.6-beta.8 → 0.3.6

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 (275) hide show
  1. package/README.md +19 -3
  2. package/bin/install-portable.sh +102 -0
  3. package/bin/install-portable.test.js +112 -0
  4. package/bin/lib/DOCUMENTATION.md +2 -0
  5. package/bin/lib/cli-startup.js +7 -2
  6. package/bin/lib/cli-startup.portable.test.js +30 -0
  7. package/bin/lib/commands-serve.js +4 -1
  8. package/bin/lib/commands-update.js +3 -0
  9. package/bin/lib/commands-update.test.js +18 -0
  10. package/dist/assets/{AgentAvatar-COZrpK6y.js → AgentAvatar-BOvjZ-DI.js} +1 -1
  11. package/dist/assets/{AgentSelector-7iPujobN.js → AgentSelector-Dl_zIOMk.js} +1 -1
  12. package/dist/assets/ArchivedSessionsDialog-Cr9Ji-RY.js +1 -0
  13. package/dist/assets/{AssistantConversationSurface-C6tCgfuc.js → AssistantConversationSurface-CLdjNFeJ.js} +3 -3
  14. package/dist/assets/{AssistantSessionCard-BLKXoc6z.js → AssistantSessionCard-BufyrOfo.js} +2 -2
  15. package/dist/assets/{AssistantUnreadBadge-BSWBtgFe.js → AssistantUnreadBadge-Dn9HAEDr.js} +1 -1
  16. package/dist/assets/{AssistantView-YdmEtDcb.js → AssistantView-Cg0wPomu.js} +1 -1
  17. package/dist/assets/{AssistantWorkingAvatar-Cnl5oL-I.js → AssistantWorkingAvatar-1KNjr2A2.js} +1 -1
  18. package/dist/assets/{AssistantsSettingsPage-CqtitUB4.js → AssistantsSettingsPage-DeYfZAYH.js} +1 -1
  19. package/dist/assets/{BinaryFileFallback-ITV09rfY.js → BinaryFileFallback-DfD02fS_.js} +1 -1
  20. package/dist/assets/{BtwPanel-SwSsRp_l.js → BtwPanel-B_2w8P0X.js} +2 -2
  21. package/dist/assets/BusyDots-CAv4ygIO.js +4 -0
  22. package/dist/assets/{ChatContainer-C_-17prp.js → ChatContainer-Dgv075jT.js} +23 -23
  23. package/dist/assets/ChatView-Cr71C0ZB.js +3 -0
  24. package/dist/assets/{DiagramView-DDMO_6X5.js → DiagramView-CTnpBsWU.js} +1 -1
  25. package/dist/assets/{DiffView-DCQrow3l.js → DiffView-j_yWF1Mz.js} +2 -2
  26. package/dist/assets/{DiffViewToggle-uJM3Jn3y.js → DiffViewToggle-CYusbmY5.js} +1 -1
  27. package/dist/assets/{ErrorBoundary-BFXVt5ct.js → ErrorBoundary-yr_JeVdx.js} +1 -1
  28. package/dist/assets/{FadeInOnReveal-CrbIIB5N.js → FadeInOnReveal-C56koblQ.js} +1 -1
  29. package/dist/assets/{GuiPluginMount-FFI3j0Vq.js → GuiPluginMount-CBJiLdzR.js} +1 -1
  30. package/dist/assets/{GuiPluginPage-B9I2nkDa.js → GuiPluginPage-DJa8gFLk.js} +1 -1
  31. package/dist/assets/{GuiPluginSurface-D_IoxXvc.js → GuiPluginSurface-Cc7q80jp.js} +1 -1
  32. package/dist/assets/{GuiPluginTitlebarItems-C4eqm-dM.js → GuiPluginTitlebarItems-rbK3leaL.js} +1 -1
  33. package/dist/assets/{GuiPluginWindow-BMeBjsJ4.js → GuiPluginWindow-Cpg2HYWe.js} +1 -1
  34. package/dist/assets/{Icon-C1m8PihJ.js → Icon-C1rjS64C.js} +1 -1
  35. package/dist/assets/{ImageLoadingPlaceholder-CJmo4kkb.js → ImageLoadingPlaceholder-2hMqBtYh.js} +1 -1
  36. package/dist/assets/{LoadingImage-956pmYDm.js → LoadingImage-Bs-621ZL.js} +1 -1
  37. package/dist/assets/MarkdownRenderer-BZl_T1ng.js +2 -0
  38. package/dist/assets/{MarkdownRendererImpl-B0BDlD7a.js → MarkdownRendererImpl-DiCCNjDr.js} +3 -3
  39. package/dist/assets/{MarkstreamRendererImpl-CNodTwpI.js → MarkstreamRendererImpl-Bzz3OZlX.js} +2 -2
  40. package/dist/assets/{MobileAssistantSettingsPage-DMLyFaSP.js → MobileAssistantSettingsPage-pBhJR2t6.js} +1 -1
  41. package/dist/assets/{MobileAssistantTab-C8r9diC7.js → MobileAssistantTab-Ceo442NF.js} +1 -1
  42. package/dist/assets/{MobileBtwPage-CoQGTHvz.js → MobileBtwPage-DPPmDMA6.js} +1 -1
  43. package/dist/assets/{MobileChangesSurface-CmZpDOwU.js → MobileChangesSurface-DfDoSkTS.js} +1 -1
  44. package/dist/assets/{MobileChatScreen-Db2VIMuY.js → MobileChatScreen-DHTbrnAr.js} +1 -1
  45. package/dist/assets/{MobileDetailNavigation-DX3hD4c-.js → MobileDetailNavigation-e1u1y59T.js} +1 -1
  46. package/dist/assets/{MobileFilesSurface-BERQLtDW.js → MobileFilesSurface-CJoqR3By.js} +2 -2
  47. package/dist/assets/{MobileHtmlNetworkBoundary-5XyCoKjL.js → MobileHtmlNetworkBoundary-GBhYVYvu.js} +2 -2
  48. package/dist/assets/{MobileOverlayPanel-XkMrn5-W.js → MobileOverlayPanel-DzKTKeZX.js} +1 -1
  49. package/dist/assets/{MobileResizableSheet-CcOOlg4R.js → MobileResizableSheet-CkA7qhco.js} +1 -1
  50. package/dist/assets/{MobileSettingsTab-iRC8w_jI.js → MobileSettingsTab-Bv0HsXFH.js} +1 -1
  51. package/dist/assets/{MobileShareBridge-DSL2iOvl.js → MobileShareBridge-B-co2UPE.js} +1 -1
  52. package/dist/assets/{MobileSurface-CkgVejQ3.js → MobileSurface-D63k27t5.js} +1 -1
  53. package/dist/assets/{MobileTabPageHeader-DDqtoIoS.js → MobileTabPageHeader-FmtbGhwq.js} +1 -1
  54. package/dist/assets/{ModelLogo-DK6xHKii.js → ModelLogo-CMnp5fyy.js} +1 -1
  55. package/dist/assets/{ModelSelector-DMmMUIB2.js → ModelSelector-BF4wYwaz.js} +1 -1
  56. package/dist/assets/{MultiRunWindow-B6jL_lNE.js → MultiRunWindow-D0OU63re.js} +1 -1
  57. package/dist/assets/{OnboardingScreen-BCIOJR5C.js → OnboardingScreen-CDHtDQ0k.js} +1 -1
  58. package/dist/assets/{OverlayScrollbar-CbdvcSXs.js → OverlayScrollbar-m1EAqRES.js} +1 -1
  59. package/dist/assets/{PierreDiffViewer-Dn1NIerc.js → PierreDiffViewer-CZk1tZ3K.js} +1 -1
  60. package/dist/assets/{ProviderLogo-CmOgqmZH.js → ProviderLogo-BqQTME35.js} +1 -1
  61. package/dist/assets/{RemoteAssistantSessionCard-BydwHPmQ.js → RemoteAssistantSessionCard-CrbCVhqD.js} +1 -1
  62. package/dist/assets/{RemoteDesktopPanel-q0HrpV8w.js → RemoteDesktopPanel-BzLmzmjb.js} +1 -1
  63. package/dist/assets/ScheduledTasksDialog-DmtcDZHc.js +3 -0
  64. package/dist/assets/{ScrollableOverlay-DIkp2MKc.js → ScrollableOverlay-CEglrXfm.js} +1 -1
  65. package/dist/assets/{SettingsGroup-YUId7nD5.js → SettingsGroup-Bm-l3IIs.js} +1 -1
  66. package/dist/assets/{SettingsView-DLMfj0mQ.js → SettingsView-CYEjDYWC.js} +15 -15
  67. package/dist/assets/{SettingsWindow-DCPFcip-.js → SettingsWindow-CvJsxUyu.js} +1 -1
  68. package/dist/assets/{SetupTourDialog-0bzhfhsY.js → SetupTourDialog-DWaVtkY0.js} +1 -1
  69. package/dist/assets/{SyncActions-8f50jzAU.js → SyncActions-C0gph0P8.js} +1 -1
  70. package/dist/assets/TerminalView-Cm8Ts51w.js +9 -0
  71. package/dist/assets/{TextSelectionMenu-BozjXtuL.js → TextSelectionMenu-Dcv_PdES.js} +2 -2
  72. package/dist/assets/{ToolOutputDialog-BK0D8GxM.js → ToolOutputDialog-QJpQjmqK.js} +2 -2
  73. package/dist/assets/{YuriLogo-KR0TAQlB.js → YuriLogo-BbS_Wj4g.js} +1 -1
  74. package/dist/assets/{YuriWordmark-B0uXpGcz.js → YuriWordmark-CqkcfAJl.js} +1 -1
  75. package/dist/assets/{assistant-attachment-cache-BNDj8_aw.js → assistant-attachment-cache-CIij0OGm.js} +1 -1
  76. package/dist/assets/{assistantMessagePreview-Ccp5_-kq.js → assistantMessagePreview-wmP-d_oa.js} +1 -1
  77. package/dist/assets/{assistantQueries-DDTlQu6m.js → assistantQueries-Dpxq78yP.js} +1 -1
  78. package/dist/assets/{auto-read-context-C8RimaOE.js → auto-read-context-aRn5yhDb.js} +1 -1
  79. package/dist/assets/{capgoAdapter-DvATpyxN.js → capgoAdapter-BSnmtwX8.js} +1 -1
  80. package/dist/assets/{card-alsnQayp.js → card-aoveY4I3.js} +1 -1
  81. package/dist/assets/{chatUpwardIntent-D_Yt_quU.js → chatUpwardIntent-WxxmOppY.js} +1 -1
  82. package/dist/assets/{checkbox-LzFeQCyX.js → checkbox-CljLXON1.js} +1 -1
  83. package/dist/assets/{client-i5Q82JUc.js → client-CmtAKi5B.js} +1 -1
  84. package/dist/assets/{collapsible-HsY9X-Ve.js → collapsible-DkeWKEAb.js} +1 -1
  85. package/dist/assets/{connection-hint-DsbzB6Ms.js → connection-hint-DsKyICgn.js} +1 -1
  86. package/dist/assets/{context-menu-Dpuzxt3o.js → context-menu-XuMa5TsA.js} +1 -1
  87. package/dist/assets/{desktopHosts-DRAWu-NH.js → desktopHosts-COI-czjF.js} +1 -1
  88. package/dist/assets/{desktopRelayRestore-DFWsoSoG.js → desktopRelayRestore-BEPNc7qb.js} +1 -1
  89. package/dist/assets/device-TCHW5U2y.js +2 -0
  90. package/dist/assets/{diagram-COwAj2NM.js → diagram-DFv7Lh0h.js} +1 -1
  91. package/dist/assets/dialog-B6B8FIrL.css +1 -0
  92. package/dist/assets/{dialog-Cv20xnEj.js → dialog-Cx20I73q.js} +1 -1
  93. package/dist/assets/{dropdown-menu-B_P1dDl7.js → dropdown-menu-XdfySbu2.js} +1 -1
  94. package/dist/assets/es-CLAEdHpc.js +15 -0
  95. package/dist/assets/{fileMentionTouchSelection-BRu1cBlZ.js → fileMentionTouchSelection-pXNTKHAc.js} +1 -1
  96. package/dist/assets/{fileReferenceActions-FVCTQlDH.js → fileReferenceActions-wN7mWY3w.js} +1 -1
  97. package/dist/assets/fr-BOB0gfdQ.js +13 -0
  98. package/dist/assets/{gitApi-BH7j-M9u.js → gitApi-LXGRaDt8.js} +1 -1
  99. package/dist/assets/{gitApiHttp-Be5VpQHC.js → gitApiHttp-ZjM4HkSo.js} +2 -2
  100. package/dist/assets/{githubAuthQueries-Dli4cDU7.js → githubAuthQueries-3AJp5LD5.js} +1 -1
  101. package/dist/assets/{historyImportQueries-SUqjfVSc.js → historyImportQueries-B_mfphxe.js} +1 -1
  102. package/dist/assets/host-fTclNJST.js +1 -0
  103. package/dist/assets/{i18n-CBCskgqa.js → i18n-iu4pzqPi.js} +1 -1
  104. package/dist/assets/{icons-BQMGp0ts.js → icons-BWijARKS.js} +1 -1
  105. package/dist/assets/{imageSource-DoyhaY3E.js → imageSource-qzgDdfT4.js} +1 -1
  106. package/dist/assets/{input-CY-NU-bG.js → input-BMYgp87Q.js} +1 -1
  107. package/dist/assets/{input-store-C4dE7Hgl.js → input-store-CzG_3qFv.js} +1 -1
  108. package/dist/assets/insertionBoundaries-bmxIeFzH.js +1 -0
  109. package/dist/assets/ja-CfM9jZ6u.js +15 -0
  110. package/dist/assets/{kbd-DJnHCHPh.js → kbd-6RW-BxuR.js} +1 -1
  111. package/dist/assets/ko-DZOSVPHB.js +15 -0
  112. package/dist/assets/main-B-Wdp6An.js +169 -0
  113. package/dist/assets/main-BLBAaohb.js +2 -0
  114. package/dist/assets/{markdownHeightCache-BAuvVQZt.js → markdownHeightCache-ojT5txMS.js} +1 -1
  115. package/dist/assets/{mcpQueries-lBUNZsO9.js → mcpQueries-BRuytwhB.js} +1 -1
  116. package/dist/assets/miniChat-BsrHy2rU.js +2 -0
  117. package/dist/assets/mobile-B8SHiXyq.js +2 -0
  118. package/dist/assets/{mobileBackNavigation-BzQ0WYuk.js → mobileBackNavigation-CVrR_jtn.js} +1 -1
  119. package/dist/assets/{mobileConnections-CSyrEiXH.js → mobileConnections-iSUwFNqu.js} +2 -2
  120. package/dist/assets/{multirun-BUjPLUCQ.js → multirun-Y3K5yS-8.js} +1 -1
  121. package/dist/assets/{native-config-C-fqN2Cf.js → native-config-tvqKHwCC.js} +1 -1
  122. package/dist/assets/{nativeComposerCover-DT9d7IrX.js → nativeComposerCover-5rYz1E3W.js} +1 -1
  123. package/dist/assets/{navigation-D2V5N7IH.js → navigation-DFmCAq2g.js} +2 -2
  124. package/dist/assets/openRemoteProjectSession-CeSahDtQ.js +1 -0
  125. package/dist/assets/openSessionFromDeepLink-DsZnNy4W.js +2 -0
  126. package/dist/assets/pl-CaT81Sz8.js +15 -0
  127. package/dist/assets/platform-B2ylz14u.js +1 -0
  128. package/dist/assets/{pluginPresentation-CbOzLlWM.js → pluginPresentation-rls1AMJN.js} +2 -2
  129. package/dist/assets/{project-preview-ClK_VQFz.js → project-preview-yQerlKs2.js} +1 -1
  130. package/dist/assets/{projectActions-CD3dKulN.js → projectActions-B11KAI3f.js} +1 -1
  131. package/dist/assets/{prompt-attachment-upload-BG4nBKxi.js → prompt-attachment-upload-BzYqZdzd.js} +1 -1
  132. package/dist/assets/pt-BR-9p1IKCEF.js +15 -0
  133. package/dist/assets/pwa-BrLPfcLk.js +2 -0
  134. package/dist/assets/{queue-abort-optimistic-DcW7tzaK.js → queue-abort-optimistic-CXKdQu_T.js} +1 -1
  135. package/dist/assets/{quota-Cyq21PUF.js → quota-BhdKv_Wc.js} +1 -1
  136. package/dist/assets/{reference-history-BZIwpng4.js → reference-history-Bzn-aPYg.js} +1 -1
  137. package/dist/assets/{remote-input-store-CiwwBt7K.js → remote-input-store-DPw_n0MZ.js} +1 -1
  138. package/dist/assets/{remoteProjectQueries-CuuZggLJ.js → remoteProjectQueries-BQzoY_Y9.js} +1 -1
  139. package/dist/assets/{remoteSessionReference-DAt2R0UC.js → remoteSessionReference-DORvqUYQ.js} +1 -1
  140. package/dist/assets/{renderElectronMiniChatApp-C7YpH2qP.js → renderElectronMiniChatApp-DXKgwBat.js} +2 -2
  141. package/dist/assets/renderMobileApp-CKN6rWxR.js +17 -0
  142. package/dist/assets/{runtime-file-download-RzAqq2xr.js → runtime-file-download-CaeLqIEY.js} +1 -1
  143. package/dist/assets/{runtime-file-resource-COtIWnSi.js → runtime-file-resource-BGZ4tGr5.js} +1 -1
  144. package/dist/assets/{runtimeConfig-Byc5NYTD.js → runtimeConfig-BqUZF6Wt.js} +1 -1
  145. package/dist/assets/runtimeEndpointReset-Bu02gAs3.js +4 -0
  146. package/dist/assets/{scheduledTaskNavigation-DuM1gQ9g.js → scheduledTaskNavigation-r3g3DfXq.js} +1 -1
  147. package/dist/assets/{select-DxI3wkmK.js → select-BPIsJWhM.js} +1 -1
  148. package/dist/assets/{sessionLookup-UJH1iLm2.js → sessionLookup-DZhrkKRI.js} +1 -1
  149. package/dist/assets/{sessionOwnership-W4KQ8CbY.js → sessionOwnership-LoUNVeuJ.js} +1 -1
  150. package/dist/assets/{shortcuts-FWBXko6F.js → shortcuts-DMupfl7l.js} +1 -1
  151. package/dist/assets/{sortable-tabs-strip-Bq5JCAvR.js → sortable-tabs-strip-1bKw81VO.js} +1 -1
  152. package/dist/assets/{speechSettingsQueries-Cybc1zo2.js → speechSettingsQueries-C3JgzCqy.js} +1 -1
  153. package/dist/assets/src-BacdFOCS.css +2 -0
  154. package/dist/assets/{store-BRt8bo0A.js → store-BgsgBTwJ.js} +5 -5
  155. package/dist/assets/{switch-BDwSWOjd.js → switch-B4-v9kvg.js} +1 -1
  156. package/dist/assets/{terminalApi-BMMDklSX.js → terminalApi-wdwb9MVG.js} +1 -1
  157. package/dist/assets/{textarea-BshZJgqE.js → textarea-DExmj0ZR.js} +1 -1
  158. package/dist/assets/{timeFormat-7kWOlby7.js → timeFormat-BlSO2-ws.js} +1 -1
  159. package/dist/assets/{tooltip-Cdy71vjH.js → tooltip-Di-WRJUZ.js} +1 -1
  160. package/dist/assets/{truncated-path-YngMm0g8.js → truncated-path-nKzykV5p.js} +1 -1
  161. package/dist/assets/types-4xeqxklF.js +2 -0
  162. package/dist/assets/ui-BCYkB585.js +13 -0
  163. package/dist/assets/uk-BUSl_Y_1.js +15 -0
  164. package/dist/assets/useAppFontEffects-BCJPQstm.js +7 -0
  165. package/dist/assets/{useAssistantUIStore-LaS5RREA.js → useAssistantUIStore-BUWPTwNV.js} +1 -1
  166. package/dist/assets/{useDesktopWindowControlsLayout-Icn9KYUk.js → useDesktopWindowControlsLayout-BtpyMlOS.js} +1 -1
  167. package/dist/assets/{useDictation-C1sdxoEy.js → useDictation-4HBMkISY.js} +1 -1
  168. package/dist/assets/{useEffectiveDirectory-BnoYSkb7.js → useEffectiveDirectory-BYswRwIv.js} +1 -1
  169. package/dist/assets/useFontPreferences-C4dQT72k.js +1 -0
  170. package/dist/assets/{useGitStore-FAEWrkVE.js → useGitStore-DqBPgmf-.js} +1 -1
  171. package/dist/assets/{useInlineCommentDraftStore-CjyZgWKx.js → useInlineCommentDraftStore-CGJ6dM8d.js} +1 -1
  172. package/dist/assets/useMcpConfigStore-DEcxFuzW.js +1 -0
  173. package/dist/assets/{useMobileSwipeActions-3JgGyG-s.js → useMobileSwipeActions-DqlR4X-T.js} +1 -1
  174. package/dist/assets/useMobileTranscriptSyncHint-BDKcqtq_.js +10 -0
  175. package/dist/assets/{useModelLists-Cz7CBWNr.js → useModelLists-DsFTBlMr.js} +1 -1
  176. package/dist/assets/{useOpenCodeReadiness-DSTj-ijS.js → useOpenCodeReadiness-CHybAoBh.js} +1 -1
  177. package/dist/assets/usePluginsStore-BIBHPK4A.js +1 -0
  178. package/dist/assets/{useProjectGitActions-C0z5ldH7.js → useProjectGitActions-DeFcqi_O.js} +1 -1
  179. package/dist/assets/{useProjectGitStore-C6ZCDvmO.js → useProjectGitStore-JGZk-NCk.js} +1 -1
  180. package/dist/assets/{useProjectRuntimeAPIs-Fi6XrG43.js → useProjectRuntimeAPIs-BMBBtJB-.js} +1 -1
  181. package/dist/assets/{useQuotaStore-yM_EeU_A.js → useQuotaStore-C3qJTiD7.js} +1 -1
  182. package/dist/assets/{useSessionBtwStore-1yHVqSCf.js → useSessionBtwStore-D7P-pknd.js} +1 -1
  183. package/dist/assets/{useStreamingTextThrottle-BbawjMGN.js → useStreamingTextThrottle-CjWAE0oQ.js} +1 -1
  184. package/dist/assets/useTerminalStore-C_QzSEgP.js +1 -0
  185. package/dist/assets/{useUIStore-Dz0bOfkB.js → useUIStore-68ZPpgYA.js} +1 -1
  186. package/dist/assets/worktreeManager-pRvX5dQT.js +1 -0
  187. package/dist/assets/{worktreeSourceBranchPreference-BJrbhZ4m.js → worktreeSourceBranchPreference-B7d3RYcc.js} +1 -1
  188. package/dist/assets/zh-CN-BGKgQtWd.js +15 -0
  189. package/dist/assets/zh-TW-jM5lIKfe.js +15 -0
  190. package/dist/index.html +16 -16
  191. package/dist/mini-chat.html +16 -16
  192. package/dist/mobile.html +2 -2
  193. package/package.json +2 -1
  194. package/server/index.js +22 -10
  195. package/server/lib/assistants/DOCUMENTATION.md +11 -6
  196. package/server/lib/assistants/builtin-skills.js +19 -3
  197. package/server/lib/assistants/builtin-skills.test.js +17 -0
  198. package/server/lib/assistants/contact-tools.js +47 -3
  199. package/server/lib/assistants/contact-tools.test.js +59 -0
  200. package/server/lib/assistants/harness.js +5 -2
  201. package/server/lib/assistants/harness.test.js +1 -1
  202. package/server/lib/assistants/routes.js +1 -0
  203. package/server/lib/assistants/service.js +7 -2
  204. package/server/lib/assistants/yuri-tools.js +1 -1
  205. package/server/lib/assistants/yuri-tools.test.js +1 -1
  206. package/server/lib/gui-customization/DOCUMENTATION.md +32 -7
  207. package/server/lib/gui-customization/projects-client.mjs +1 -1
  208. package/server/lib/gui-customization/projects.js +6 -6
  209. package/server/lib/gui-customization/projects.test.js +13 -2
  210. package/server/lib/gui-customization/remote-connections-client.mjs +1 -1
  211. package/server/lib/gui-customization/remote-connections.js +7 -6
  212. package/server/lib/gui-customization/remote-connections.test.js +17 -0
  213. package/server/lib/gui-customization/session-skill.js +16 -4
  214. package/server/lib/gui-customization/session-skill.test.js +16 -0
  215. package/server/lib/gui-customization/skill/SKILL.md +2 -2
  216. package/server/lib/gui-customization/skill/references/deep-links.md +15 -11
  217. package/server/lib/gui-customization/skill/references/gui-api.md +50 -1
  218. package/server/lib/gui-customization/skill/references/projects.md +19 -0
  219. package/server/lib/gui-customization/skill/references/remote-connections.md +3 -0
  220. package/server/lib/gui-customization/skill-caller.js +18 -0
  221. package/server/lib/host-update/DOCUMENTATION.md +5 -0
  222. package/server/lib/host-update/cli.js +5 -2
  223. package/server/lib/host-update/cli.test.js +15 -2
  224. package/server/lib/opencode/DOCUMENTATION.md +2 -1
  225. package/server/lib/opencode/custom-provider.test.js +41 -0
  226. package/server/lib/opencode/feature-routes-runtime.js +20 -3
  227. package/server/lib/opencode/settings-helpers.js +5 -0
  228. package/server/lib/opencode/settings-helpers.test.js +10 -0
  229. package/server/lib/package-manager.js +14 -0
  230. package/server/lib/package-manager.test.js +7 -0
  231. package/server/lib/portable-installation.js +34 -0
  232. package/server/lib/portable-installation.test.js +38 -0
  233. package/server/lib/session-index/DOCUMENTATION.md +8 -0
  234. package/server/lib/session-index/adopt-unindexed-session.js +46 -0
  235. package/server/lib/session-index/adopt-unindexed-session.test.js +77 -0
  236. package/server/lib/session-index/event-ingest.js +14 -1
  237. package/server/lib/session-index/event-ingest.test.js +18 -0
  238. package/dist/assets/ArchivedSessionsDialog-DLZzsdyB.js +0 -1
  239. package/dist/assets/BusyDots-C2pMtufA.js +0 -4
  240. package/dist/assets/ChatView-CNNGCekk.js +0 -3
  241. package/dist/assets/MarkdownRenderer-GdoxOy4f.js +0 -2
  242. package/dist/assets/ScheduledTasksDialog-DY9GJF-s.js +0 -3
  243. package/dist/assets/TerminalView-B9AFgs54.js +0 -8
  244. package/dist/assets/device-gKeFQDLT.js +0 -2
  245. package/dist/assets/dialog-D9CkSNCA.css +0 -1
  246. package/dist/assets/es-BuXtFKUW.js +0 -15
  247. package/dist/assets/fr-BaZeffY9.js +0 -13
  248. package/dist/assets/host-CgzhgNKF.js +0 -1
  249. package/dist/assets/insertionBoundaries-DUMGOIsz.js +0 -1
  250. package/dist/assets/ja-CGVx5A8U.js +0 -15
  251. package/dist/assets/ko-C663nzbf.js +0 -15
  252. package/dist/assets/main-CSPEphQ0.js +0 -169
  253. package/dist/assets/main-VozcdE4o.js +0 -2
  254. package/dist/assets/miniChat-DuIhQwv6.js +0 -2
  255. package/dist/assets/mobile-zYF3NcbJ.js +0 -2
  256. package/dist/assets/openRemoteProjectSession-Dz9GJCUz.js +0 -1
  257. package/dist/assets/openSessionFromDeepLink-DHu8AmBy.js +0 -2
  258. package/dist/assets/pl-CeBOMwg9.js +0 -15
  259. package/dist/assets/platform-z1TeG-ky.js +0 -1
  260. package/dist/assets/pt-BR-r8268Pk6.js +0 -15
  261. package/dist/assets/pwa-Dc46OTi7.js +0 -2
  262. package/dist/assets/renderMobileApp-DkFS7I4O.js +0 -17
  263. package/dist/assets/runtimeEndpointReset-BOfBQwJk.js +0 -4
  264. package/dist/assets/src-DYCPWwUH.css +0 -2
  265. package/dist/assets/types-CjZZGQvx.js +0 -2
  266. package/dist/assets/ui-DeV7Us1B.js +0 -13
  267. package/dist/assets/uk-CeQ1XJ99.js +0 -15
  268. package/dist/assets/useAppFontEffects-CWZFjoHJ.js +0 -7
  269. package/dist/assets/useFontPreferences-CLUZvRho.js +0 -1
  270. package/dist/assets/useMcpConfigStore-n8Iyj2v9.js +0 -1
  271. package/dist/assets/useMobileTranscriptSyncHint-CgAaYuLF.js +0 -10
  272. package/dist/assets/usePluginsStore-CsChIifx.js +0 -1
  273. package/dist/assets/worktreeManager-XchvRN9O.js +0 -1
  274. package/dist/assets/zh-CN-Bv854olO.js +0 -15
  275. package/dist/assets/zh-TW-gx8cO-Cx.js +0 -15
@@ -0,0 +1 @@
1
+ import{n as e}from"./platform-B2ylz14u.js";import{C as t,D as n,I as r,L as i,M as a,O as o,P as s,S as c,T as l,_ as u,a as d,b as f,c as p,j as m,n as h,o as g,r as _,s as v,t as y,v as b,w as x,y as S}from"./vendor-opencode-client-BM2r1f0o.js";import{n as ee}from"./pathNormalization-ewtPqJWn.js";import{a as te}from"./vendor-tanstack-query-core-BSjXNgF_.js";import{b as ne,v as re}from"./runtime-file-resource-BGZ4tGr5.js";import{o as ie}from"./path-utils-jGozTg9d.js";import{a as ae,n as C}from"./vendor-aparajita-capacitor-secure-storage-xol_6BsB.js";import{Dt as oe,ht as se,mt as w,y as T}from"./vendor-effect-X1Hqc7ba.js";import{t as E}from"./native-errors-06if6eu-.js";import{a as ce,i as le,n as ue,o as de,r as fe,s as D}from"./appearance-DFsI3pnP.js";import{i as pe,o as me}from"./fileReferenceParser-1HHDBUum.js";import{a as he,r as O}from"./pages-CYkE04ml.js";import{n as ge,t as _e}from"./vendor-solid-js-BBVUd3Hw.js";import{a as ve,c as ye,d as be,f as k,g as A,h as j,i as M,l as N,m as xe,n as Se,o as P,p as F,r as Ce,s as we,t as Te,u as Ee}from"./vendor-opencode-plugin-ZhpPgHCL.js";var I={"@opencode/plugin/gui":P,"@opencode/plugin/gui/main":P,"@opencode/plugin/gui/file":ve,"@opencode/plugin/gui/review":M,"@opencode/plugin/gui/browser":Ce,"@opencode/plugin/rpc":Te,"@opencode/schema/rpc":Se,"@opencode/client":_,"@opencode/client/effect":h,"@opencode/client/solid":y,effect:T,"solid-js":s,"solid-js/web":ge,"solid-js/store":v},De=new Set(`assert assert/strict async_hooks buffer child_process cluster console constants crypto dgram diagnostics_channel dns dns/promises domain events fs fs/promises http http2 https inspector inspector/promises module net os path path/posix path/win32 perf_hooks process punycode querystring readline readline/promises repl stream stream/consumers stream/promises stream/web string_decoder sys timers timers/promises tls trace_events tty url util util/types v8 vm wasi worker_threads zlib`.split(` `));function Oe(){let e=new Proxy(function(){},{get:(t,n)=>n===`then`?void 0:n===Symbol.hasInstance?()=>!1:n===Symbol.toPrimitive||n===`toString`?()=>`[main-only module]`:e,apply:()=>e,construct:()=>e,set:()=>!0});return e}function L(e,t){if(e.length>16777216)throw Error(`GUI bundle exceeds 16 MiB`);let n={exports:{}};Function(`require`,`module`,`exports`,e)(e=>{if(Object.hasOwn(I,e))return I[e];if(e===`electron`||e.startsWith(`node:`)||De.has(e))return Oe();throw Error(`Unsupported GUI shared module: ${e}`)},n,n.exports);let r=n.exports,i=r&&typeof r==`object`&&`default`in r?r.default:r;if(!i||typeof i!=`object`)throw Error(`GUI bundle must default-export Plugin.define`);if((!(`setup`in i)||typeof i.setup!=`function`)&&!(t&&`main`in i&&typeof i.main==`function`))throw new E(`GUI_PLUGIN_UNSUPPORTED`,`This host requires a window setup; main-only plugins are unsupported`);if(`os`in i&&i.os!==void 0){if(!t)throw new E(`GUI_PLUGIN_UNSUPPORTED`,`OS-restricted plugins require the native GUI host`);if(!Array.isArray(i.os)||!i.os.includes(t))throw new E(`GUI_PLUGIN_UNSUPPORTED`,`GUI plugin is unavailable on this OS`)}if(`main`in i&&i.main!==void 0&&typeof i.main!=`function`)throw Error(`Invalid GUI main entry`);if(`stores`in i&&i.stores!==void 0){if(!i.stores||typeof i.stores!=`object`||Array.isArray(i.stores))throw Error(`Invalid GUI stores`);for(let e of Object.values(i.stores))if(!e||typeof e!=`object`||!(`schema`in e)||!oe(e.schema)||!(`scope`in e)||![`global`,`session`].includes(String(e.scope))||!(`initial`in e))throw Error(`Invalid GUI store declaration`)}if(`i18n`in i&&i.i18n!==void 0){if(!i.i18n||typeof i.i18n!=`object`||Array.isArray(i.i18n))throw Error(`Invalid GUI locale catalog`);for(let e of Object.values(i.i18n))if(!e||typeof e!=`object`||Array.isArray(e)||Object.values(e).some(e=>typeof e!=`string`))throw Error(`GUI locales must be inline string dictionaries`)}return i}function R(e){let t=e;if(/^file:/i.test(t)){let e=new URL(t);t=`${e.hostname&&e.hostname!==`localhost`?`//${e.hostname}`:``}${decodeURIComponent(e.pathname)}`,/^\/[a-z]:\//i.test(t)&&(t=t.slice(1))}let n=ee(t)??``;return n===`.`?``:n}var z=e=>/^(?:\/|[a-z]:\/)/i.test(e),B=()=>{throw Error(`Unsupported GUI file API: tree`)},V=class extends Error{},H=e=>new TextEncoder().encode(e).byteLength,ke=class{files;query;transport;root;api;ended=!1;states=new Map;inflight=new Map;watches=new Map;apiLeases=new Map;registeredOwners=new WeakSet;endedOwners=new WeakSet;leaseCount=0;rerun=new Set;selections=new Map;scrolls=new Map;subscriptions=new Map;constructor(e,t,n,r){this.files=e,this.query=t,this.transport=n,this.root=r,this.root=R(r),this.api={root:this.root,ready:()=>!this.ended,resolve:e=>this.resolve(e),absolute:z,get:e=>{let t=this.track(e,`file`);return this.states.get(t)},missing:e=>{let t=this.track(e,`missing`);return this.states.get(t)?.notFound===!0},sync:(e,t)=>{let n=o();return this.ended||n&&this.endedOwners.has(n)?Promise.resolve():(this.acquireApiLease(e),this.sync(e,t?.force))},unwatch:e=>this.releaseApiLease(o(),this.resolve(e)),exists:async e=>{try{if(this.files.statFile)return(await this.query.fetchQuery(this.statOptions(e))).isFile;let t=this.full(e);return(await this.files.listDirectory(t.slice(0,t.lastIndexOf(`/`)))).entries.some(e=>!e.isDirectory&&R(e.path)===t)}catch{return!1}},search:async(e,t)=>{if(t?.kind===`any`)throw Error(`Unsupported GUI file search: directories`);t?.signal?.throwIfAborted();let r=await this.query.fetchQuery({queryKey:[`gui-plugin-files`,n,this.root,`search`,e,t?.limit],gcTime:3e4,queryFn:async({signal:n})=>(n.throwIfAborted(),this.files.search({directory:this.root,query:e,maxResults:t?.limit??100}))});if(t?.signal?.throwIfAborted(),this.ended)throw new DOMException(`GUI file model was disposed`,`AbortError`);return r.map(e=>this.resolve(e.path))},selection:{get:e=>this.selections.get(this.track(e,`selection`)),set:(e,t)=>{let n=this.resolve(e),r=this.selections.get(n);r===t||r&&t&&r.start===t.start&&r.end===t.end&&r.side===t.side&&r.endSide===t.endSide||(this.selections.set(n,t),this.trim(this.selections,`selection`),this.changed(n,`selection`))}},scroll:{get:e=>this.scrolls.get(this.track(e,`scroll`))??{},set:(e,t)=>{let n=this.resolve(e),r=this.scrolls.get(n),i={...r,...t};(r?.top!==i.top||r?.left!==i.left)&&(this.scrolls.set(n,i),this.trim(this.scrolls,`scroll`),this.changed(n,`scroll`))}},tree:{list:B,state:B,sync:B,expand:B,collapse:B}}}resolve(e){let t=R(e);if(!z(t))return t;if(t===this.root)return``;let n=this.root.endsWith(`/`)?this.root:`${this.root}/`;return t.startsWith(n)?t.slice(n.length):t}full(e){let t=this.resolve(e);return z(t)?t:R(`${this.root}/${t}`)}input(e){return{scopeDirectory:this.root,path:this.full(e),options:{directory:this.root}}}statOptions(e){return{...ne(this.files,this.input(e),this.transport),gcTime:3e4}}track(e,t){let r=this.resolve(e),i=n();if(!i||this.ended)return r;let o=`${t}:${r}`,s=this.subscriptions.get(o);s||(s={revision:l(0),listeners:new Set},this.subscriptions.set(o,s));let c=s;return c.listeners.has(i)||(c.listeners.add(i),a(i,()=>m(()=>{c.listeners.delete(i),!c.listeners.size&&this.subscriptions.get(o)===c&&this.subscriptions.delete(o)}))),c.revision[0](),r}changed(e,t){this.ended||this.subscriptions.get(`${t}:${e}`)?.revision[1](e=>e+1)}trim(e,t){for(;e.size>64;){let n=e.keys().next().value;e.delete(n),this.changed(n,t)}}setState(e,t){let n=this.states.get(e);n?.content?.content===t.content?.content&&n?.content?.type===t.content?.type&&(t.content=n?.content),!(n&&n.loaded===t.loaded&&n.loading===t.loading&&n.error===t.error&&n.notFound===t.notFound&&n.content===t.content)&&(this.states.set(e,t),u(()=>{this.changed(e,`file`),n?.notFound===!0!=(t.notFound===!0)&&this.changed(e,`missing`)}))}acquireApiLease(e){let t=o();if(this.ended||t&&this.endedOwners.has(t)||!this.files.statFile)return;let n=this.resolve(e),r=this.apiLeases.get(t);if(r?.has(n))return;if(this.leaseCount>=256)throw Error(`GUI file consumer limit exceeded`);let i=this.watch(n);r||(r=new Map,this.apiLeases.set(t,r)),r.set(n,i),this.leaseCount++,t&&!this.registeredOwners.has(t)&&(this.registeredOwners.add(t),m(()=>{`fn`in t||this.endedOwners.add(t),this.registeredOwners.delete(t);for(let e of[...this.apiLeases.get(t)?.keys()??[]])this.releaseApiLease(t,e)}))}releaseApiLease(e,t){let n=this.apiLeases.get(e),r=n?.get(t);r&&(n.delete(t),this.leaseCount--,n.size||this.apiLeases.delete(e),r())}reserve(e){if(!this.states.has(e)){if(this.states.size>=64){let e=[...this.states.keys()].find(e=>!this.watches.has(e)&&!this.inflight.has(e));if(!e)throw Error(`GUI file cache limit exceeded`);let t=this.states.get(e)?.notFound===!0;this.states.delete(e),u(()=>{this.changed(e,`file`),t&&this.changed(e,`missing`)})}this.states.set(e,{path:e,name:e.split(`/`).at(-1)??e})}}async sync(e,t=!1){if(this.ended)return;let n=this.resolve(e);if(this.inflight.has(n))return t&&this.rerun.add(n),this.inflight.get(n);if(!t&&this.states.get(n)?.loaded&&!this.states.get(n)?.error)return;this.reserve(n);let r=this.states.get(n);this.setState(n,{...r,path:n,name:n.split(`/`).at(-1)??n,loading:!r?.loaded&&!this.watches.get(n)?.failed});let i=(async()=>{try{do{this.rerun.delete(n);let e=this.watches.get(n),r=e?.epoch;try{let i=re(this.files,this.input(n),this.transport),a=await this.query.fetchQuery({...i,gcTime:3e4,staleTime:t?0:3e4,queryFn:async()=>{if(!this.files.readFile)throw Error(`File content reads are unavailable in this runtime`);let e=await this.files.readFile(this.full(n),{directory:this.root});if(e.exists===!1)throw new V(`File does not exist`);let t=e.content;if(H(t)>131072)throw Error(`GUI file preview exceeds 128 KiB`);return t}});if(this.ended)return;if(H(a)>131072)throw Error(`GUI file preview exceeds 128 KiB`);(!e||e.epoch===r&&!e.failed)&&this.setState(n,{path:n,name:n.split(`/`).at(-1)??n,loaded:!0,loading:!1,content:{type:`text`,content:a}})}catch(t){if(this.ended)return;if((!e||e.epoch===r&&!e.failed)&&this.setState(n,{...this.states.get(n),loading:!1,...t instanceof V?{notFound:!0}:{},error:String(t)}),!this.rerun.has(n))throw t}t=!0}while(!this.ended&&this.rerun.has(n))}finally{this.inflight.delete(n),this.rerun.delete(n)}})();return this.inflight.set(n,i),i}watch(e){if(this.ended||!this.files.statFile)return()=>{};let t=this.resolve(e),n=this.watches.get(t);if(!n){if(this.watches.size>=64)throw Error(`GUI file watch limit exceeded`);this.reserve(t),n={count:0,epoch:0,failed:!1,stop:()=>{}};let e=n;this.watches.set(t,e);let r,i=new te(this.query,{...this.statOptions(t),refetchInterval:2e3,refetchIntervalInBackground:!1}),a=i.subscribe(n=>{if(this.ended||this.watches.get(t)!==e||n.isFetching)return;if(n.isError||n.isSuccess&&!n.data.isFile){e.failed=!0,e.epoch++,this.setState(t,{...this.states.get(t),loading:!1,notFound:n.isSuccess?!0:this.states.get(t)?.notFound,error:n.isError?String(n.error):`File does not exist`});return}if(!n.data||!n.isSuccess)return;let i=`${n.data.size}:${n.data.mtimeMs??``}`,a=e.failed||r!==void 0&&i!==r;e.failed=!1,r=i,a&&(e.epoch++,this.sync(t,!0).catch(()=>{}))});e.stop=()=>{a(),i.destroy()},this.states.get(t)?.loaded&&this.sync(t,!0).catch(()=>{})}n.count++;let r=!0;return()=>{r&&(r=!1,--n.count===0&&this.watches.get(t)===n&&this.stopWatch(t))}}stopWatch(e){this.watches.get(e)?.stop(),this.watches.delete(e)}dispose(){this.ended=!0;for(let e of this.watches.values())e.stop();this.watches.clear(),this.apiLeases.clear(),this.leaseCount=0,this.rerun.clear(),this.states.clear(),this.inflight.clear(),this.selections.clear(),this.scrolls.clear(),this.subscriptions.clear()}},U=256,W=2097152,G=e=>structuredClone(p(e)),Ae=class{backend;transport;memory=new Map;resets=new Map;constructor(e,t){this.backend=e,this.transport=t}forPlugin(e,t){let n=(t,n=`global`)=>{if(typeof n==`object`&&`session`in n&&!n.session.location)throw Error(`Unsupported GUI storage: session location is unknown`);let r=n===`global`?n:`session`in n?[n.session.server.id,n.session.id,n.session.location]:[n.server,n.directory];return`yuri.gui-plugin.${JSON.stringify([this.transport,e,r,t])}`},r=e=>{if(t.aborted)throw Error(`GUI plugin has been disposed`);if(e!==void 0)throw Error(`Unsupported GUI storage migration: from`)},i=new Map;return{store:(e,a)=>{r(a.from);let o=n(e,a.scope),s=i.get(o);if(s)return s;if(i.size>=U)throw Error(`GUI plugin store limit exceeded`);let c=w(a.schema),u=se(a.schema),d=c(u(G(a.initial)));if(JSON.stringify(u(d)).length>W)throw Error(`GUI plugin store exceeds 2 MiB`);let f=d,p=this.backend.getItem(o);if(p!==null&&p.length<=W)try{f=c(JSON.parse(p))}catch{f=d}let[m,h]=l(f),g=e=>{r();let t=JSON.stringify(u(G(e)));if(t.length>W)throw Error(`GUI plugin store exceeds 2 MiB`);let n=c(JSON.parse(t));this.backend.setItem(o,t),h(()=>n)},_={get value(){return m()},ready:()=>!0,set:g,update:e=>{let t=G(m());if(e(t)!==void 0)throw Error(`Store update must not return a replacement`);g(t)}},v=()=>h(()=>G(d)),y=this.resets.get(o)??new Set;return y.add(v),this.resets.set(o,y),t.addEventListener(`abort`,()=>{y.delete(v),y.size||this.resets.delete(o),i.clear()},{once:!0}),i.set(o,_),_},memory:(e,t)=>{r();let i=n(e),a=this.memory.get(i);if(a)return[a[0],e=>{r(),a[1](e)}];if(this.memory.size>=U)throw Error(`GUI plugin memory store limit exceeded`);if(JSON.stringify(t.initial).length>W)throw Error(`GUI plugin memory exceeds 2 MiB`);let[o,s]=d(G(t.initial)),c=[o,e=>{r();let t=G(p(o));if(e(t)!==void 0)throw Error(`Memory update must not return a replacement`);if(JSON.stringify(t).length>W)throw Error(`GUI plugin memory exceeds 2 MiB`);s(g(t))}];return this.memory.set(i,[o,e=>{let t=G(p(o));if(e(t)!==void 0)throw Error(`Memory update must not return a replacement`);if(JSON.stringify(t).length>W)throw Error(`GUI plugin memory exceeds 2 MiB`);s(g(t))}]),c},remove:(e,t)=>{r(t?.from);let i=n(e,t?.scope);this.backend.removeItem(i);for(let e of this.resets.get(i)??[])e()}}}dispose(){this.memory.clear(),this.resets.clear()}};function je(e){if(typeof e!=`string`||e.length>2097152)return;let t=e.trim();if(t)try{if(t.startsWith(`<`))return D(t);if(!/^data:/i.test(t))return t;let e=/^data:image\/(svg\+xml|png|jpeg|gif|webp|avif|x-icon|vnd\.microsoft\.icon)(?:;charset=utf-8)?(;base64)?,([\s\S]+)$/i.exec(t);if(!e)return;let[,n,r,i]=e;if(r&&!/^[A-Za-z0-9+/]+={0,2}$/.test(i))return;if(n.toLowerCase()===`svg+xml`){let e=r?new TextDecoder(`utf-8`,{fatal:!0}).decode(Uint8Array.from(atob(i),e=>e.charCodeAt(0))):decodeURIComponent(i);return D(e)}return!r||!atob(i).length?void 0:`data:image/${n.toLowerCase()};base64,${i}`}catch{return}}var K=e=>e===`yuri.exportPDF`||e===`yuri.exportLongImage`,Me=class{api;probe;clients=new Map;ended=!1;constructor(e){this.api=e}use(e,t){let n=this.clients.get(t),r=n?.get(e);if(r)return r.live;let[i,a]=l(this.api&&!t.aborted&&!this.ended?{status:`pending`}:{status:`inactive`,reason:`disabled`}),o=()=>{a({status:`inactive`,reason:`disabled`}),t.removeEventListener(`abort`,o),this.clients.delete(t)},s={live:A(i),stop:o};if(this.ended||t.aborted||(n||(n=new Map,this.clients.set(t,n)),n.set(e,s),t.addEventListener(`abort`,o,{once:!0}),!this.api))return s.live;let c=this.api;return this.probe??=Promise.resolve().then(()=>c.capabilities()),this.probe.then(n=>{if(this.ended||t.aborted)return;let r=e===`yuri.exportPDF`?`exportPDF`:`exportLongImage`;if(n.version!==1||!n[r]){a({status:`inactive`,reason:`disabled`});return}let o=async(e,n={})=>{if(this.ended||t.aborted||i().status!==`active`)return{status:`cancelled`};let o=AbortSignal.any([t,...n.signal?[n.signal]:[]]);try{return await c[r](e,{...n,signal:o})}catch(e){throw e&&typeof e==`object`&&`code`in e&&e.code===`EXPORT_UNSUPPORTED`&&a({status:`inactive`,reason:`failed`}),e}},s=Object.freeze(e===`yuri.exportPDF`?{version:1,limits:n.limits,exportPDF:o}:{version:1,limits:n.limits,exportLongImage:o});a({status:`active`,generation:1,value:s})}).catch(()=>{!this.ended&&!t.aborted&&a({status:`inactive`,reason:`failed`})}),s.live}dispose(){this.ended=!0;for(let e of this.clients.values())for(let t of e.values())t.stop();this.clients.clear()}};function Ne(e,t){let n=new Map,r=Object.freeze({dismiss(){}});return e.addEventListener(`abort`,()=>{for(let e of[...n.values()])e.handle.dismiss()},{once:!0}),Object.freeze({show(i){if(e.aborted)return r;if(!t)throw new E(`GUI_PLUGIN_UNSUPPORTED`,`GUI toast is unavailable`);if(!i||typeof i!=`object`)throw new E(`GUI_PLUGIN_INVALID_INPUT`,`Expected toast options`);let{title:a,description:o,variant:s=`default`,duration:c=5e3,persistent:l=!1,icon:u,actions:d}=i;if(typeof a!=`string`||o!==void 0&&typeof o!=`string`||![`default`,`success`,`error`,`loading`].includes(s)||typeof l!=`boolean`||typeof c!=`number`||!Number.isFinite(c)||c<0)throw new E(`GUI_PLUGIN_INVALID_INPUT`,`Invalid toast options`);if(u!==void 0||d!==void 0)throw new E(`GUI_PLUGIN_UNSUPPORTED`,`GUI toast icon/actions are unsupported`);if(e.aborted)return r;let f=JSON.stringify([a,o??null,s,c,l]),p=n.get(f),m=()=>{let e=n.get(f);!e||e.id!==h||(clearTimeout(e.timer),n.delete(f))},h=(s==="default"?t:t[s])(a,{id:p?.id,description:o,duration:l?1/0:c,onDismiss:m,onAutoClose:m}),g=p?.handle??Object.freeze({dismiss(){m(),t.dismiss(h)}});clearTimeout(p?.timer);let _=s===`loading`&&!l?setTimeout(()=>g.dismiss(),c):void 0;return n.set(f,{id:h,handle:g,timer:_}),g}})}var Pe=ae(`YuriMedia`);async function Fe(t){let n=/\.html?$/i.test(t.name)?`text/html`:`text/plain`,r=new Blob([t.content],{type:n});if(e()){if(!C.isPluginAvailable(`YuriMedia`))throw new E(`GUI_PLUGIN_UNSUPPORTED`,`Native file saving is unavailable`);if(r.size>33554432)throw new E(`GUI_PLUGIN_INVALID_INPUT`,`File exceeds maximum size`);let e=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>{if(typeof n.result!=`string`){t(Error(`Failed to encode file`));return}e(n.result.slice(n.result.indexOf(`,`)+1))},n.onerror=()=>t(n.error??Error(`Failed to encode file`)),n.readAsDataURL(r)});return!(await Pe.saveFile({dataBase64:e,mimeType:n,filename:t.name})).cancelled}let i=URL.createObjectURL(r),a=document.createElement(`a`);try{return a.href=i,a.download=t.name,document.body.append(a),a.click(),!0}finally{a.remove(),setTimeout(()=>URL.revokeObjectURL(i),1e3)}}var q=f();function Ie(e){return{version:1,register(t){let n=i(q);if(!n||n.plugin!==e||n.signal.aborted||e.aborted)throw Error(`Preview actions require the owning mounted panel`);let r=new AbortController,a=AbortSignal.any([e,n.signal,r.signal]),o,s=()=>{a.removeEventListener(`abort`,s),r.abort(),o?.remove()};m(s),a.addEventListener(`abort`,s,{once:!0});try{o=t.render({element:t.element,signal:a,async snapshot(e={}){let r=AbortSignal.any([a,...e.signal?[e.signal]:[]]);if(r.throwIfAborted(),!n.content.contains(t.element)||n.target.contains(t.element))throw Error(`Preview capture region is no longer in its owning panel`);let i=await t.capture({...e,signal:r});if(r.throwIfAborted(),!n.content.contains(t.element))throw Error(`Preview capture region was replaced`);return i}}),a.throwIfAborted(),n.target.append(o)}catch(e){throw s(),e}return s}}}function Le(e,t){return`gui-plugin:${JSON.stringify([e,t])}`}var Re=`yuri.work-status`;function J(e,t){return e===t||!!(e&&t&&Object.keys(e).length===Object.keys(t).length&&Object.keys(e).every(n=>e[n]===t[n]))}var Y=e=>e&&Object.freeze({...e});function ze(e,t,n){let r=new AbortController,[i,a]=l(!0),[o,s]=l(Y(e.project),{equals:J}),[c,d]=l(Y(e.worktree),{equals:J}),[f,p]=l(Object.freeze({...e.git}),{equals:J}),[m,h]=l(e.placement);return{props:Object.freeze({session:t,directory:e.directory,runtimeId:n,signal:r.signal,get active(){return i()},get project(){return o()},get worktree(){return c()},get git(){return f()},get placement(){return m()}}),matches:t=>t.sessionId===e.sessionId&&t.directory===e.directory&&t.scope===e.scope,update(e){r.signal.aborted||u(()=>{s(Y(e.project)),d(Y(e.worktree)),p(Object.freeze({...e.git})),h(e.placement)})},dispose(){r.signal.aborted||(a(!1),r.abort())}}}var Be=class{plugins=new Map;order=new Map;snapshot=Object.freeze([]);generation=0;listeners=new Set;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.snapshot;setOrder(e){e.length===this.order.size&&e.every((e,t)=>this.order.get(e)===t)||(this.order=new Map(e.map((e,t)=>[e,t])),this.publish())}replace(e,t,n){let r=this.plugins.get(e)??[],i=new Set,a=n.map(n=>{if(!n||typeof n!=`object`||!(`id`in n)||typeof n.id!=`string`||!n.id.trim()||n.id.length>128||i.has(n.id)||!(`render`in n)||typeof n.render!=`function`||`order`in n&&n.order!==void 0&&(typeof n.order!=`number`||!Number.isFinite(n.order)))throw Error(`Invalid or duplicate yuri.work-status contribution`);i.add(n.id);let a=JSON.stringify([e,n.id]),o=`order`in n&&typeof n.order==`number`?n.order:0,s=n.render,c=r.find(e=>e.key===a),l=c&&c.revision===t&&c.render===s?c.generation:++this.generation;return c&&c.revision===t&&c.render===s&&c.order===o?c:Object.freeze({key:a,pluginId:e,revision:t,generation:l,order:o,render:s})});a.length?this.plugins.set(e,a):this.plugins.delete(e),this.publish()}contains(e){return this.plugins.get(e.pluginId)?.some(t=>t.key===e.key&&t.generation===e.generation)??!1}remove(e){this.plugins.delete(e)&&this.publish()}dispose(){this.plugins.clear(),this.publish(),this.listeners.clear()}publish(){let e=[...this.plugins.values()].flat().sort((e,t)=>e.order-t.order||(this.order.get(e.pluginId)??2**53-1)-(this.order.get(t.pluginId)??2**53-1));if(!(e.length===this.snapshot.length&&e.every((e,t)=>e===this.snapshot[t]))){this.snapshot=Object.freeze(e);for(let e of this.listeners)r(e)}}},X=e=>{throw new E(`GUI_PLUGIN_UNSUPPORTED`,`Unsupported GUI host API: ${e}`)};function Z(e,t){return new Proxy(t,{get:(t,n)=>n in t?Reflect.get(t,n):X(`${e}.${String(n)}`)})}var Q=e=>Object.freeze(e.map(e=>Object.freeze(e)));function Ve(e,t){if(!e.fields||!t.fields)return!1;let n=Reflect.ownKeys(e.fields);return n.length===Reflect.ownKeys(t.fields).length&&n.every(n=>{let r=e.fields[n],i=t.fields[n];return i!==void 0&&`value`in r&&`value`in i&&Object.is(r.value,i.value)&&r.enumerable===i.enumerable&&r.configurable===i.configurable&&r.writable===i.writable})}function $(e,t){if(e){for(let n of e.owned??[])$(n,t);e.cleanups&&=e.cleanups.map(e=>()=>{try{Promise.resolve(e()).catch(t)}catch(e){t(e)}})}}var He=class{options;fileIcons=new de;appearanceCatalog=new le;workStatus=new Be;instances=new Map;listeners=new Set;commandShortcuts=Object.freeze([]);panelMounts=new Set;fileViews=new Map;changes=l(0);views=l(0);session=l();currentPage=l();mobilePageNetworkReady=l(!1);appearance;layouts=new Map;files;storage;ended=!1;contracts=new Map;snapshot=Object.freeze({plugins:Object.freeze([]),commands:Object.freeze([]),titlebarItems:Object.freeze([]),panels:Object.freeze([]),pages:Object.freeze([]),settings:Object.freeze([]),menuItems:Object.freeze([]),activePanel:null});#e;viewExports;constructor(e){this.options=e,this.viewExports=new Me(e.viewExport),this.appearance=l({locale:e.locale,mode:e.mode,narrow:e.narrow}),this.storage=new Ae(e.storage,e.transport);let t=()=>(this.session[0](),this.files?.api??X(`screen.file without a session`));this.#e=Z(`screen`,{get file(){return t()}})}subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.snapshot;changed(e=!1){let t=this.snapshot;this.changes[1](e=>e+1),e&&t===this.snapshot&&this.publish()}setSession(e){if(this.ended)return;let t=this.session[0]();if(t?.id===e?.id&&t?.directory===e?.directory)return;if(!e)for(let e of[...this.panelMounts])e();this.files?.dispose(),this.files=e?new ke(this.options.files,this.options.queryClient,this.options.transport,e.directory):void 0;let n=e?this.sessionReference(e):void 0,r=this.snapshot;this.session[1](n),r===this.snapshot&&this.publish()}sessionReference(e,t){let n=t?JSON.stringify(t.queryScope):this.options.transport,r=Z(`session.server`,{id:n,name:t?.location.hostId??this.options.transport,...t?{}:{client:this.options.client}});return Object.freeze(Z(`session`,{id:e.id,directory:e.directory,key:t?JSON.stringify([n,e.id]):`${this.options.transport}\n${e.id}`,tab:e.id,server:r,pending:!1,visit:{},location:t?Object.freeze({...t.location}):{directory:e.directory}}))}setAppearance(e){if(this.ended)return;let t=this.appearance[0]();(t.locale!==e.locale||t.mode!==e.mode||t.narrow!==e.narrow)&&this.appearance[1]({...e})}setPage(e){this.ended||this.currentPage[1](e)}setMobilePageNetworkReady(e){this.mobilePageNetworkReady[1](!this.ended&&e)}install(e,n,i){if(this.options.mobileNetworkRequired&&!this.mobilePageNetworkReady[0]()&&!this.ended)throw new E(`GUI_PLUGIN_UNAVAILABLE`,`Mobile plugin Relay is not ready`);let s=this.instances.get(e);if(this.ended||s?.status===`active`&&s.revision===n.revision&&s.native?.active!==!1){i?.dispose();return}s&&(this.instances.delete(e),this.release(s));let c={id:e,native:i,revision:n.revision,controller:new AbortController,status:`active`,cleanups:new Set,contributions:new Set,iconChanges:l(0),appearanceChanges:l(0),workStatusChanges:l(0),commands:[],titlebarItems:[],panels:[],pages:[],settings:[],menus:[]};this.instances.set(e,c);try{if(e===`yuri`||e.startsWith(`yuri.`))throw Error(`The yuri namespace is reserved to the host`);let s=L(n.code,i?.activation.os);x(e=>{c.dispose=e,c.root=o(),b(()=>S(j.Provider,{value:c.context=this.context(c,s,n.options),get children(){c.owner=o();let e=r(()=>s.setup?.(c.context));if(typeof e==`function`)c.cleanups.add(()=>{Promise.resolve(e()).catch(e=>{c.error=String(e)})});else if(e!==void 0)throw e&&typeof e==`object`&&`then`in e&&Promise.resolve(e).catch(()=>{}),Error(`GUI setup must be synchronous and return only cleanup`);return null}}),e=>this.fail(c,e)),c.controller.signal.aborted||a(c.owner,()=>t(()=>{if(c.iconChanges[0](),!c.controller.signal.aborted)try{let e=[...c.contributions].filter(e=>e.registry===ce).map(e=>e.read()).filter(e=>e!==void 0);this.fileIcons.replace(c.id,e),c.iconError!==void 0&&r(()=>{c.iconError=void 0,this.publish()})}catch(e){r(()=>{this.fileIcons.remove(c.id),c.iconError=e instanceof Error?e.message:String(e),this.publish()})}})),c.controller.signal.aborted||a(c.owner,()=>t(()=>{if(c.appearanceChanges[0](),!c.controller.signal.aborted)try{let e=e=>[...c.contributions].filter(t=>t.registry===e).map(e=>e.read()).filter(e=>e!==void 0);this.appearanceCatalog.replace(c.id,e(fe),e(ue),c.native?.activation.capabilities?.dockIcon===!0)}catch(e){r(()=>this.fail(c,e))}})),c.controller.signal.aborted||a(c.owner,()=>t(()=>{if(c.workStatusChanges[0](),!c.controller.signal.aborted)try{let e=[...c.contributions].filter(e=>e.registry===Re).map(e=>e.read()).filter(e=>e!==void 0);this.workStatus.replace(c.id,c.revision,e)}catch(e){r(()=>this.fail(c,e))}})),c.controller.signal.aborted||a(c.owner,()=>t(()=>{this.changes[0](),this.session[0](),this.appearance[0]();try{this.derive(c)}catch(e){r(()=>this.fail(c,e))}r(()=>this.publish())}))})}catch(e){this.fail(c,e)}this.changed(!0)}release(e){e.controller.abort(),e.native?.dispose();for(let t of[...e.cleanups])try{t()}catch(t){e.error??=String(t)}e.cleanups.clear(),$(e.root,t=>{e.error??=String(t)});try{e.dispose?.()}catch(t){e.error??=String(t)}e.contributions.clear(),e.commands=[],e.titlebarItems=[],e.panels=[],e.pages=[],e.settings=[],e.menus=[],this.fileIcons.remove(e.id),this.appearanceCatalog.remove(e.id),this.workStatus.remove(e.id);for(let t of this.contracts.values())t.provider===e&&(t.provider=void 0,t.live[1]({status:`inactive`,reason:e.status===`failed`?`failed`:`disabled`}))}fail(e,t){e.status!==`failed`&&this.instances.get(e.id)===e&&(e.status=`failed`,e.error=t instanceof Error?t.message:String(t),t instanceof E&&(e.errorCode=t.code),this.release(e),this.publish())}uninstall(e){let t=this.instances.get(e);if(t){this.instances.delete(e),this.release(t);for(let t of this.layouts.values())t.open=t.open.filter(t=>!t.startsWith(`${e}:`)),t.active?.startsWith(`${e}:`)&&(t.active=null);this.changed(!0)}}dispose(){this.ended||(this.ended=!0,u(()=>{for(let e of[...this.instances.keys()])this.uninstall(e)}),this.viewExports.dispose(),this.files?.dispose(),this.fileIcons.dispose(),this.appearanceCatalog.dispose(),this.workStatus.dispose(),this.storage.dispose(),this.layouts.clear(),this.fileViews.clear(),this.contracts.clear(),this.listeners.clear())}async setDockIcon(e,t){let n=this.instances.get(e),r=n?.native;if(!r?.active||!r.activation.capabilities?.dockIcon)return X(`Dock icon`);try{await r.setDockIcon(t)}catch(e){throw t!==null&&n&&this.fail(n,e),e}}own(e,t){let n=!0,r=()=>{n&&(n=!1,e.cleanups.delete(r),t())};return e.controller.signal.aborted||i(F)?.ended?(r(),r):(e.cleanups.add(r),o()&&m(r),r)}list(e){this.changes[0]();let t=[];for(let n of this.instances.values())if(n.status===`active`){for(let r of n.contributions)if(r.registry===e.id){let e=r.read();e!==void 0&&t.push(e)}}return t}context(e,n,a){let s=this.storage.forPlugin(e.id,e.controller.signal),l=Object.fromEntries(Object.entries(n.stores??{}).map(([e,t])=>[e,t.scope===`global`?s.store(e,{...t,scope:`global`}):n=>s.store(e,{...t,scope:{session:n}})])),u=(e,t)=>{let r=this.appearance[0]().locale;return(n.i18n?.[r]?.[e]??n.i18n?.[r.split(`-`)[0]]?.[e]??n.i18n?.en?.[e]??e).replace(/\{\{(\w+)\}\}/g,(e,n)=>String(t?.[n]??e))},d=Z(`layout`,{narrow:()=>this.appearance[0]().narrow,ready:()=>!!this.session[0](),open:(t,n,r)=>{e.controller.signal.aborted||this.openPanel(t,n,r)},close:(t,n)=>{e.controller.signal.aborted||this.closeFor(t,n)},toggle:(e,t)=>d.state(e,t)===`visible`?d.close(e,t):d.open(e,t),hide:(t,n)=>{if(e.controller.signal.aborted)return;let r=this.layout(n);r.active===t&&r.shown&&(r.shown=!1,this.changed())},state:(e,t)=>{this.changes[0]();let n=this.layout(t);return n.active===e?n.shown?`visible`:`active`:n.open.includes(e)?`open`:`closed`},stored:t=>(this.changes[0](),this.layout(t).open.filter(t=>t.startsWith(`${e.id}:`)).map(t=>t.slice(e.id.length+1))),side:{opened:e=>(this.changes[0](),this.layout(e).shown),toggle:t=>{if(e.controller.signal.aborted)return;let n=this.layout(t);n.shown=!n.shown,this.changed()},menu:()=>this.list(N).filter(e=>e.menu===`session.panel`).sort((e,t)=>(e.order??0)-(t.order??0))},scroll:{get:(e,t)=>(this.changes[0](),this.layout(e).scroll.get(t)),set:(t,n,r)=>{if(e.controller.signal.aborted)return;let i=this.layout(t).scroll;if(!i.has(n)&&i.size>=128)throw Error(`GUI layout scroll limit exceeded`);i.set(n,{...r}),this.changed()}}}),f=Ie(e.controller.signal),p=A(()=>e.controller.signal.aborted?{status:`inactive`,reason:`disabled`}:{status:`active`,generation:1,value:f}),h={open:t=>e.controller.signal.aborted||this.appearance[0]().narrow&&!this.mobilePageNetworkReady[0]()||!e.pages.some(e=>e.id===t)?!1:this.options.openPage?.(O(e.id,t))??!1,current:()=>{let t=this.currentPage[0]();return e.pages.find(n=>O(e.id,n.id)===t)?.id}},g=A(()=>e.controller.signal.aborted||!this.options.openPage||this.appearance[0]().narrow&&!this.mobilePageNetworkReady[0]()?{status:`inactive`,reason:`disabled`}:{status:`active`,generation:1,value:h});return Z(`ctx`,{id:e.id,options:a,signal:e.controller.signal,client:this.options.client,storage:s,stores:l,toast:Ne(e.controller.signal,this.options.toast),app:{name:`yuri`,version:e.native?.activation.app.version??``,channel:e.native?.activation.app.packaged?`prod`:`local`,platform:e.native?`desktop`:`web`,packaged:e.native?.activation.app.packaged??!1},desktop:e.native?Z(`desktop`,{os:e.native.activation.os}):void 0,t:u,plural:(e,t,n)=>{let r=`${e}.${new Intl.PluralRules(this.appearance[0]().locale).select(t)}`;return u(r,{...n,count:t})===r?u(`${e}.other`,{...n,count:t}):u(r,{...n,count:t})},add:(n,a)=>{if(e.controller.signal.aborted||i(F)?.ended)return()=>{};if([`server`,`composer-pill`,`slot`,`file.viewer`,`menubar-item`].includes(n.id)&&X(`registry.${n.id}`),e.contributions.size>=256)throw Error(`GUI contribution limit exceeded`);let s=()=>{},l,u=x(r=>{s=r,l=o();let i=()=>typeof a==`function`?a():a,u;if(n.id===`yuri.file-icon`){let e=c(()=>{try{return{ok:!0,value:i()}}catch(e){return{ok:!1,error:e}}});u=()=>{let t=e();if(!t.ok)throw t.error;return t.value}}else u=c(i);if(n.id===`style`){let n=document.createElement(`style`);n.dataset.yuriPluginStyle=e.id,document.head.append(n),m(()=>n.remove()),t(()=>{let e=u();n.textContent=e===void 0?``:String(e)})}return{registry:n.id,read:u}},o()??e.owner);e.contributions.add(u);let d=()=>{n.id===`yuri.file-icon`&&e.iconChanges[1](e=>e+1)},f=()=>{(n.id===`yuri.theme`||n.id===`yuri.branding`)&&e.appearanceChanges[1](e=>e+1)},p=()=>{n.id===`yuri.work-status`&&e.workStatusChanges[1](e=>e+1)};return r(d),r(f),r(p),r(()=>this.changed()),this.own(e,()=>{$(l,t=>{e.error??=String(t)}),s(),e.contributions.delete(u),r(d),r(f),r(p),r(()=>this.changed())})},list:e=>this.list(e),provide:(t,n)=>{if(e.controller.signal.aborted||i(F)?.ended)return()=>{};if(K(t.id)||t.id===`yuri.previewActions`||t.id===`yuri.pages`)throw Error(`Preview/export/page contracts are provided only by the Yuri host`);if(t.kind!==`contract`||!(t.id===e.id||t.id.startsWith(`${e.id}.`)))throw Error(`Contract must belong to the providing plugin`);let r=this.contract(t.id);if(r.provider)throw Error(`Contract already provided: ${t.id}`);return r.provider=e,r.live[1]({status:`active`,value:n,generation:++r.generation}),this.own(e,()=>{r.provider===e&&(r.provider=void 0,r.live[1]({status:`inactive`,reason:e.status===`failed`?`failed`:`disabled`}))})},use:t=>t.id===`yuri.pages`?t.kind===`contract`?g:X(`pages token must be a Contract`):t.id===`yuri.previewActions`?t.kind===`contract`?p:X(`preview actions token must be a Contract`):K(t.id)?t.kind===`contract`?this.viewExports.use(t.id,e.controller.signal):X(`export token must be a Contract`):t.kind===`ipc`&&e.native?e.native.token(t).live:this.contract(t.id,t.kind===`ipc`).live[0],main:t=>{if(!(t.id===e.id||t.id.startsWith(`${e.id}.`)))throw new E(`GUI_PLUGIN_FORBIDDEN`,`IPC must belong to the plugin`);return e.native?e.native.token(t).value:new Proxy({state:()=>void 0},{get:(e,t)=>t===`state`?e.state:t===`on`?()=>{throw new E(`GUI_PLUGIN_UNSUPPORTED`)}:()=>Promise.reject(new E(`GUI_PLUGIN_UNSUPPORTED`))})},sessions:{current:this.session[0],list:()=>{let e=this.session[0]();return e?[e]:[]}},screen:{current:()=>this.session[0]()?this.#e:void 0},layout:d,appearance:{mode:()=>this.appearance[0]().mode,font:()=>getComputedStyle(document.documentElement).getPropertyValue(`--font-mono`).trim()||`monospace`},locale:{locale:()=>this.appearance[0]().locale,direction:()=>/^(ar|fa|he|ur)(-|$)/i.test(this.appearance[0]().locale)?`rtl`:`ltr`},system:{copy:e=>navigator.clipboard.writeText(e),openExternal:e=>{let t=new URL(e);[`https:`,`http:`,`mailto:`].includes(t.protocol)||X(`system.openExternal protocol`),window.open(e,`_blank`,`noopener,noreferrer`)},save:Fe},commands:{run:t=>e.controller.signal.aborted||!this.command(t)?!1:(this.runCommand(t),!0)},links:{open:t=>!e.controller.signal.aborted&&this.navigateLink(e,t),exists:t=>r(()=>{if(e.controller.signal.aborted)return!1;let n=this.linkHandler(t);try{return Promise.resolve(n?.value.exists?.(t)??!1).catch(()=>!1)}catch{return!1}})}})}contract(e,t=!1){let n=this.contracts.get(e);if(!n){if(this.contracts.size>=256)throw Error(`GUI contract limit exceeded`);let t=l({status:`inactive`,reason:`disabled`});n={live:[A(t[0]),t[1]],generation:0},this.contracts.set(e,n)}return t&&n.provider&&X(`IPC contract collision`),n}derive(e){if(e.status!==`active`)return;let t=[],n=[],i=[],a=[],o=[],s=[],c=this.session[0]();for(let r of e.contributions){if([`yuri.file-icon`,`yuri.theme`,`yuri.branding`,`yuri.work-status`].includes(r.registry))continue;let l=r.read();if(l!==void 0){if(r.registry===`yuri.page`){let e=he(l);if(s.some(t=>t.id===e.id))throw Error(`Duplicate yuri.page id`);s.push(e)}else if(r.registry===we.id){let n=l,{priority:r=0,bind:i,scope:a}=n;if(typeof r!=`number`||!Number.isFinite(r))throw Error(`Invalid GUI command priority`);if(i!==void 0&&typeof i!=`string`)throw Error(`Invalid GUI command binding`);if(a!==void 0){if(typeof a!=`string`)throw Error(`Invalid GUI command scope`);document.documentElement.matches(a)}n.enabled!==!1&&t.push({key:`${e.id}.${n.id}`,pluginId:e.id,commandId:n.id,title:n.title,description:n.description,bind:i,hidden:n.hidden,priority:r,scope:a,editable:n.editable,run:()=>this.invoke(e,()=>n.run())})}else if(r.registry===k.id){let t=l;o.push({key:JSON.stringify([e.id,t.id]),pluginId:e.id,label:t.label,title:t.title,icon:je(t.icon),busy:t.busy,pressed:t.pressed,actionable:!!t.run,run:t.run})}else if(r.registry===Ee.id&&c){let t=l,r=`${e.id}:`,i=this.layout(c).open.filter(e=>e.startsWith(r)).map(e=>e.slice(r.length));for(let r of t.list({session:c,screen:this.#e,open:i}))n.push({plugin:e,panel:t,tab:r})}else if(r.registry===be.id){let e=l;(e.page||e.section)&&X(`SettingsPage host sections`),e.title,i.push(e)}else if(r.registry===N.id){let e=l;e.menu===`session.panel`?(e.title,a.push(e)):X(`MenuItem.${e.menu}`)}}}for(let e of n)e.tab.title;e.commands=t,e.titlebarItems=o,e.panels=n,e.pages=s,e.settings=i,e.menus=a,r(()=>this.views[1](e=>e+1))}publish(){let e=r(this.session[0]),t=e?this.layouts.get(e.key):void 0,n=[...this.instances.values()],i=n.filter(e=>e.status===`active`),a=i.flatMap(e=>e.commands.map(t=>({id:Le(e.id,t.commandId),pluginId:e.id,commandId:t.commandId,label:t.title,description:t.description,defaultCombo:t.bind??``,priority:t.priority??0,customizable:!0,scope:t.scope,editable:t.editable})));(a.length!==this.commandShortcuts.length||a.some((e,t)=>{let n=this.commandShortcuts[t];return!n||e.id!==n.id||e.label!==n.label||e.description!==n.description||e.defaultCombo!==n.defaultCombo||e.priority!==n.priority||e.scope!==n.scope||e.editable!==n.editable}))&&(this.commandShortcuts=Q(a));let o=i.flatMap(e=>e.panels.map(({tab:n})=>{let r=n.file?this.filePath(n.file):void 0;return{key:`${e.id}:${n.id}`,pluginId:e.id,title:n.title,file:r,inline:!!(r&&this.fileViews.has(r)),active:t?.shown===!0&&t.active===`${e.id}:${n.id}`}}));this.snapshot=Object.freeze({plugins:Q(n.map(({id:e,revision:t,status:n,error:r,errorCode:i,iconError:a})=>({id:e,revision:t,status:n,error:r??a,...i?{errorCode:i}:{}}))),commands:Q(i.flatMap(e=>e.commands.filter(e=>!e.hidden))),panels:Q(o),titlebarItems:Q(i.flatMap(e=>e.titlebarItems.map(({run:e,...t})=>t))),pages:Q(i.flatMap(e=>e.pages.map(t=>({key:O(e.id,t.id),pluginId:e.id,title:t.title,icon:t.icon})))),settings:Q(i.flatMap(e=>e.settings.map(t=>({key:`${e.id}:${t.id}`,pluginId:e.id,title:t.title})))),menuItems:Q(i.flatMap(e=>e.menus.map(t=>({key:`${e.id}:${t.id}`,pluginId:e.id,title:t.title,description:t.description,run:()=>{this.invoke(e,()=>t.run())}})))),activePanel:t?.shown&&o.some(e=>e.key===t.active)?t.active:null,sessionKey:e?.key});for(let e of this.listeners)e()}invoke(e,t){if(!e.controller.signal.aborted)try{let n=a(e.owner??null,t);return n instanceof Promise?n.catch(t=>this.fail(e,t)):n}catch(t){this.fail(e,t)}}command(e){return[...this.instances.values()].flatMap(e=>e.commands).find(t=>t.key===e)}getCommandShortcuts(){return this.commandShortcuts}runShortcutCommand(e,t){let n=this.instances.get(e);if(!n||n.status!==`active`||n.controller.signal.aborted)return!1;let r=n.commands.find(e=>e.commandId===t);return r?r.run()!==!1:!1}runCommand(e){let t=this.command(e)?.run();if(t!==!1)return t}runTitlebarItem(e){for(let t of this.instances.values()){let n=t.titlebarItems.find(t=>t.key===e);if(n?.run&&!n.busy)return this.invoke(t,n.run)}}linkHandler(e){let t=[];for(let e of this.instances.values())for(let n of e.contributions)if(n.registry===ye.id){let r=n.read();r&&t.push({instance:e,value:r})}for(let n of t.sort((e,t)=>(t.value.priority??0)-(e.value.priority??0)))try{if(n.value.match(e))return n}catch(e){this.fail(n.instance,e)}}navigateLink(e,t){if(this.ended)return!1;let n=me(t.href);if(!n||!pe(n.path))return this.openLink(t);let r=this.session[0]();if(!r||t.session&&(t.session.key!==r.key||t.session.server.id!==r.server.id))return!1;if(!this.options.focusFile)return this.openLink(t);let i=ie(t.base??r.directory,n.path),a=n.line===void 0?``:`:${n.line}${n.column===void 0?``:`:${n.column}`}`;return this.invoke(e,()=>this.options.focusFile(i+a,r.directory)),!0}openLink(e){if(this.ended)return!1;let t={...e,session:e.session??this.session[0]()},n=this.linkHandler(t);return n?(this.invoke(n.instance,()=>n.value.open(t)),!0):!1}filePath(e,t=this.session[0]()?.directory){let n=R(e);return/^(?:\/|[a-z]:\/)/i.test(n)||!t?n:R(`${t}/${n}`)}registerFileView(e,t){if(this.ended)return()=>{};let n=this.filePath(e,t),r=this.fileViews.get(n)??0;this.fileViews.set(n,r+1),r===0&&this.changed(!0);let i=!1;return()=>{if(i||this.ended)return;i=!0;let e=(this.fileViews.get(n)??1)-1;if(e){this.fileViews.set(n,e);return}{let e=this.session[0](),t=e&&this.layouts.get(e.key);t?.active&&this.snapshot.panels.some(e=>e.key===t.active&&e.file===n)&&(t.shown=!1),this.fileViews.delete(n)}this.changed(!0)}}filePanel(e,t){let n=this.filePath(e,t);return this.snapshot.panels.find(e=>e.file===n&&e.inline)}panelVisible(e){let t=this.session[0]();if(!t)return!1;let n=this.panel(e)?.tab.file;if(n&&this.fileViews.has(this.filePath(n)))return!0;let r=this.layouts.get(t.key);return!!(r?.shown&&r.active===e)}layout(e){let t=this.layouts.get(e.key);if(!t){if(this.layouts.size>=128)throw Error(`GUI session layout limit exceeded`);t={open:[],active:null,shown:!1,scroll:new Map},this.layouts.set(e.key,t)}return t}openPanel(e,t,n){if(this.ended)return;let r=this.layout(t),i=r.active,a=r.shown,o=r.open.length;if(!r.open.includes(e)){if(r.open.length>=64)throw Error(`GUI panel tab limit exceeded`);r.open=[...r.open,e]}n?.tab!==`append`&&(r.active=e,r.shown=!(this.appearance[0]().narrow&&n?.background)),(i!==r.active||a!==r.shown||o!==r.open.length)&&this.changed(!0);let s=this.panel(e);t.key===this.session[0]()?.key&&s&&n?.tab!==`append`&&this.invoke(s.plugin,()=>s.panel.focus?.({...this.props(e),restored:!1}))}selectPanel(e){let t=this.session[0]();t&&this.openPanel(e,t)}closeFor(e,t){let n=this.layout(t),r=t.key===this.session[0]()?.key?this.panel(e):void 0;if(!n.open.includes(e)||r?.tab.pinned||r?.tab.closable===!1)return;let i=this.session[0](),a=r&&i?{tab:r.tab,session:i,screen:this.#e}:void 0;n.open=n.open.filter(t=>t!==e),n.active===e&&(n.active=n.open.at(-1)??null),this.changed(!0),r&&a&&this.invoke(r.plugin,()=>r.panel.close?.(a))}closePanel(e){let t=this.session[0]();t&&this.closeFor(e,t)}hidePanel(){let e=this.session[0]();if(!e)return;let t=this.layout(e);t.shown&&(t.shown=!1,this.changed(!0))}panel(e){return[...this.instances.values()].flatMap(e=>e.panels).find(t=>`${t.plugin.id}:${t.tab.id}`===e)}props(e,t=!1){let n=this.panel(e)?.tab,r=()=>(this.views[0](),this.panel(e)?.tab??n??X(`panel no longer listed`)),i=t?c(()=>{let e=r();return{tab:e,fields:Object.getPrototypeOf(e)===Object.prototype?Object.getOwnPropertyDescriptors(e):void 0}},void 0,{equals:Ve}):void 0,a=i?()=>i().tab:r,o=()=>this.session[0]()??X(`panel without session`);return{get tab(){return a()},get session(){return o()},screen:this.#e}}mountPanel(e,n,i){let a=this.panel(e);if(!a)return()=>{};let o=new AbortController,s=()=>{let s=c(()=>{this.session[0](),this.changes[0](),this.views[0]();let t=this.panel(e)?.tab.file;return t&&this.files&&this.panelVisible(e)?{model:this.files,file:t}:void 0},void 0,{equals:(e,t)=>e?.model===t?.model&&e?.file===t?.file});t(()=>{let e=s();e&&(m(e.model.watch(e.file)),e.model.sync(e.file).catch(()=>{}))});let l=()=>r(()=>a.panel.render(this.props(e,!0)));return S(q.Provider,{value:i?{plugin:a.plugin.controller.signal,signal:o.signal,content:n,target:i}:void 0,get children(){return l()}})},l=this.mount(a.plugin,n,()=>S(xe.Provider,{value:{visible:()=>(this.changes[0](),this.panelVisible(e)),present:()=>(this.changes[0](),this.panelVisible(e)),placement:()=>this.appearance[0]().narrow?`mobile`:`side`,reserve:()=>!1,animate:()=>!1,sidebar:Z(`panel.sidebar`,{}),open:()=>{let e=this.session[0]();return e?a.plugin.context.layout.stored(e):[]}},get children(){return s()}})),u=()=>{this.panelMounts.delete(u),o.abort(),l()};return this.panelMounts.add(u),this.own(a.plugin,u)}mountSettings(e,t){for(let n of this.instances.values()){let r=n.settings.find(t=>`${n.id}:${t.id}`===e);if(r)return this.mount(n,t,()=>r.render({}))}return()=>{}}mountPage(e,t){if(this.appearance[0]().narrow&&!this.mobilePageNetworkReady[0]())throw new E(`GUI_PLUGIN_UNAVAILABLE`,`Mobile page Relay is not ready`);for(let n of this.instances.values()){let r=n.pages.find(t=>O(n.id,t.id)===e);if(r)return this.mount(n,t,()=>r.render())}return()=>{}}mountWorkStatus(e,t,n){let r=this.instances.get(e.pluginId);if(!r||!this.workStatus.contains(e)||this.ended)return{update(){},dispose(){}};let i=ze(n,n.sessionId&&n.directory?this.sessionReference({id:n.sessionId,directory:n.directory},n.scope):void 0,n.scope?JSON.stringify(n.scope.queryScope):this.options.transport),a=()=>{},o=()=>{},s=this.own(r,()=>{i.dispose(),o(),a()});return o=this.workStatus.subscribe(()=>{this.workStatus.contains(e)||s()}),a=this.mount(r,t,()=>e.render(i.props)),i.props.signal.aborted&&(o(),a()),{update:e=>{if(!i.matches(e)){s();return}i.update(e)},dispose:s}}mount(e,t,n){if(e.controller.signal.aborted)return()=>{};let i=()=>{},a,s=t=>{queueMicrotask(()=>this.fail(e,t))};try{i=_e(()=>S(j.Provider,{value:e.context,get children(){return a=o(),b(()=>r(n),s)}}),t)}catch(t){this.fail(e,t)}return this.own(e,()=>{$(a,t=>{e.error??=String(t)}),i(),t.replaceChildren()})}};export{He as GuiPluginHost};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{O as t,P as n,k as r}from"./platform-z1TeG-ky.js";import{ot as i,st as a}from"./vendor-base-ui-wXsskyKm.js";import{n as o}from"./vendor-react-BkccXcWz.js";import{n as s,t as c}from"./runtime-ead7P81A.js";import"./bootstrap-eLlfzqAI.js";import{i as l,t as u}from"./store-BRt8bo0A.js";var d=e(a(),1),f=o(),p=async(e,n)=>{if(!t())throw Error(`Desktop runtime is not available`);return r(e,n)},m=async()=>{if(n())try{await p(`desktop_start_window_drag`)}catch{}},h=async e=>{if(n())try{await p(`desktop_set_window_title`,{title:e})}catch{}},g=async(e,t)=>{if(n())try{await p(`desktop_set_window_theme`,{themeMode:e,themeVariant:t})}catch{}},_=async e=>{if(n())try{await p(`desktop_set_menu_locale`,{locale:e})}catch{}},v=async()=>{if(!n())return null;try{let e=await p(`desktop_get_app_version`);return typeof e==`string`&&e.trim().length>0?e:null}catch{return null}},y=d.createContext(null),b=i(),x=e=>{let t=(0,f.c)(19),{children:n}=e,r=l(S),i=l(C),a=l(w),o=l(T),p,m;t[0]===r?(p=t[1],m=t[2]):(p=()=>{typeof document>`u`||(document.documentElement.lang=r)},m=[r],t[0]=r,t[1]=p,t[2]=m),d.useEffect(p,m);let h,g;t[3]!==a||t[4]!==r?(h=()=>{a===null&&_(r)},g=[r,a],t[3]=a,t[4]=r,t[5]=h,t[6]=g):(h=t[5],g=t[6]),d.useEffect(h,g);let v;t[7]===i?v=t[8]:(v=(e,t)=>u(i,e,t),t[7]=i,t[8]=v);let x=v,E;t[9]===x?E=t[10]:(E=e=>x(s[e]),t[9]=x,t[10]=E);let D;t[11]!==r||t[12]!==o||t[13]!==x||t[14]!==E?(D={locale:r,locales:c,setLocale:o,label:E,t:x},t[11]=r,t[12]=o,t[13]=x,t[14]=E,t[15]=D):D=t[15];let O=D,k;return t[16]!==n||t[17]!==O?(k=(0,b.jsx)(y.Provider,{value:O,children:n}),t[16]=n,t[17]=O,t[18]=k):k=t[18],k};function S(e){return e.locale}function C(e){return e.dictionary}function w(e){return e.loadingLocale}function T(e){return e.setLocale}var E={en:`en-US`,fr:`fr-FR`,"zh-CN":`zh-CN`,"zh-TW":`zh-TW`,uk:`uk-UA`,es:`es-ES`,"pt-BR":`pt-BR`,ko:`ko-KR`,pl:`pl-PL`,ja:`ja-JP`},D=e=>E[e]??`en-US`,O=()=>D(l.getState().locale);function k(){let e=d.useContext(y);if(!e)throw Error(`useI18n must be used within I18nProvider`);return e}export{p as a,m as c,v as i,O as n,g as o,x as r,h as s,k as t};
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{A as t,I as n,j as r}from"./platform-B2ylz14u.js";import{ot as i,st as a}from"./vendor-base-ui-wXsskyKm.js";import{n as o}from"./vendor-react-BkccXcWz.js";import{n as s,t as c}from"./runtime-ead7P81A.js";import"./bootstrap-eLlfzqAI.js";import{i as l,t as u}from"./store-BgsgBTwJ.js";var d=e(a(),1),f=o(),p=async(e,n)=>{if(!t())throw Error(`Desktop runtime is not available`);return r(e,n)},m=async()=>{if(n())try{await p(`desktop_start_window_drag`)}catch{}},h=async e=>{if(n())try{await p(`desktop_set_window_title`,{title:e})}catch{}},g=async(e,t)=>{if(n())try{await p(`desktop_set_window_theme`,{themeMode:e,themeVariant:t})}catch{}},_=async e=>{if(n())try{await p(`desktop_set_menu_locale`,{locale:e})}catch{}},v=async()=>{if(!n())return null;try{let e=await p(`desktop_get_app_version`);return typeof e==`string`&&e.trim().length>0?e:null}catch{return null}},y=d.createContext(null),b=i(),x=e=>{let t=(0,f.c)(19),{children:n}=e,r=l(S),i=l(C),a=l(w),o=l(T),p,m;t[0]===r?(p=t[1],m=t[2]):(p=()=>{typeof document>`u`||(document.documentElement.lang=r)},m=[r],t[0]=r,t[1]=p,t[2]=m),d.useEffect(p,m);let h,g;t[3]!==a||t[4]!==r?(h=()=>{a===null&&_(r)},g=[r,a],t[3]=a,t[4]=r,t[5]=h,t[6]=g):(h=t[5],g=t[6]),d.useEffect(h,g);let v;t[7]===i?v=t[8]:(v=(e,t)=>u(i,e,t),t[7]=i,t[8]=v);let x=v,E;t[9]===x?E=t[10]:(E=e=>x(s[e]),t[9]=x,t[10]=E);let D;t[11]!==r||t[12]!==o||t[13]!==x||t[14]!==E?(D={locale:r,locales:c,setLocale:o,label:E,t:x},t[11]=r,t[12]=o,t[13]=x,t[14]=E,t[15]=D):D=t[15];let O=D,k;return t[16]!==n||t[17]!==O?(k=(0,b.jsx)(y.Provider,{value:O,children:n}),t[16]=n,t[17]=O,t[18]=k):k=t[18],k};function S(e){return e.locale}function C(e){return e.dictionary}function w(e){return e.loadingLocale}function T(e){return e.setLocale}var E={en:`en-US`,fr:`fr-FR`,"zh-CN":`zh-CN`,"zh-TW":`zh-TW`,uk:`uk-UA`,es:`es-ES`,"pt-BR":`pt-BR`,ko:`ko-KR`,pl:`pl-PL`,ja:`ja-JP`},D=e=>E[e]??`en-US`,O=()=>D(l.getState().locale);function k(){let e=d.useContext(y);if(!e)throw Error(`useI18n must be used within I18nProvider`);return e}export{p as a,m as c,v as i,O as n,g as o,x as r,h as s,k as t};
@@ -1 +1 @@
1
- import{r as e}from"./Icon-C1m8PihJ.js";var t=(e,t)=>{if(!t||t.length<2)return e;let n=t.map(e=>e.name).filter(Boolean).sort((e,t)=>t.length-e.length);return e.map(([e,t])=>{let r=n.find(t=>e.startsWith(`${t} · `));return r?[e,{...t,accountName:r}]:[e,t]})},n=(e,t)=>{let n=e[t]?.accountName;return!n||t>0&&e[t-1].accountName===n?null:new Set(e.map(e=>e.accountName).filter(Boolean)).size>1?n:null},r=(e,t)=>n(e.map(([,e])=>e),t),i={globe:`global`,server:`server`,"circle-check":`checkbox-circle`,"circle-x":`close-circle`,"window-analytics":`bar-chart-box`};function a(t){return t?Object.hasOwn(i,t)?i[t]:Object.hasOwn(e,t)?t:void 0:void 0}export{t as i,r as n,n as r,a as t};
1
+ import{r as e}from"./Icon-C1rjS64C.js";var t=(e,t)=>{if(!t||t.length<2)return e;let n=t.map(e=>e.name).filter(Boolean).sort((e,t)=>t.length-e.length);return e.map(([e,t])=>{let r=n.find(t=>e.startsWith(`${t} · `));return r?[e,{...t,accountName:r}]:[e,t]})},n=(e,t)=>{let n=e[t]?.accountName;return!n||t>0&&e[t-1].accountName===n?null:new Set(e.map(e=>e.accountName).filter(Boolean)).size>1?n:null},r=(e,t)=>n(e.map(([,e])=>e),t),i={globe:`global`,server:`server`,"circle-check":`checkbox-circle`,"circle-x":`close-circle`,"window-analytics":`bar-chart-box`};function a(t){return t?Object.hasOwn(i,t)?i[t]:Object.hasOwn(e,t)?t:void 0:void 0}export{t as i,r as n,n as r,a as t};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{_ as t,s as n}from"./runtime-auth-DA-qfGHk.js";import{c as r,i}from"./runtime-switch-DEPKHgdL.js";import{st as a}from"./vendor-base-ui-wXsskyKm.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{n as o}from"./vendor-react-BkccXcWz.js";import{E as s,t as c}from"./runtime-file-resource-COtIWnSi.js";import{a as l,o as u,r as d}from"./path-utils-jGozTg9d.js";var f=e(a(),1),p=o(),m=[0,250,750],h=e=>{try{return decodeURIComponent(e)}catch{return e}},g=e=>{try{let t=new URL(e),n=h(t.hostname),r=h(t.pathname);return/^[A-Za-z]$/.test(n)?r=`${n.toUpperCase()}:${r}`:n&&n.toLowerCase()!==`localhost`&&(r=`//${n}${r}`),/^\/[A-Za-z]:[\\/]/.test(r)&&(r=r.slice(1)),l(r)}catch{let t=h(e.replace(/^file:\/\//i,``));return/^\/[A-Za-z]:[\\/]/.test(t)&&(t=t.slice(1)),l(t)}},_=(e,t)=>{let n=e.trim();if(!n||/^https?:/i.test(n)||/^(?:data|blob):/i.test(n)||/^\/api(?=\/|[?#]|$)/.test(n))return{kind:`direct`,source:n};if(/^file:\/\//i.test(n))return{kind:`runtime-file`,source:n,path:g(n)};if(/^[a-z][a-z\d+.-]*:/i.test(n)&&!/^[A-Za-z]:[\\/]/.test(n))return{kind:`direct`,source:n};let r=h(n);return{kind:`runtime-file`,source:n,path:d(r)?l(r):u(t,r)}},v=(e,t,n)=>y(()=>c(e,t,void 0,n),t),y=async(e,t)=>{let r=i(),a=n(),o;for(let s of m){t.throwIfAborted(),s>0&&await new Promise((e,n)=>{let r=window.setTimeout(()=>{t.removeEventListener(`abort`,i),e()},s),i=()=>{window.clearTimeout(r),n(t.reason)};t.addEventListener(`abort`,i,{once:!0})});try{if(t.throwIfAborted(),r!==i()||a!==n())throw new DOMException(`Image request superseded`,`AbortError`);return await e()}catch(e){if(t.aborted||r!==i()||a!==n())throw e;o=e}}throw o instanceof Error?o:Error(`Image source request failed`)},b=()=>!1,x=e=>e.startsWith(`relay:`)||b(),S=(e,t)=>typeof t==`number`&&Number.isFinite(t)&&t>1048576&&x(e),C=()=>f.useSyncExternalStore(T,i,i),w=e=>e.kind===`runtime-file`&&!!e.path,T=e=>r(()=>e()),E=e=>t(()=>e()),D=(e,t,r)=>{let a=(0,p.c)(22),o=r===void 0?`inline`:r,l=s(),u=l?.entry.location.hostId?l.entry:void 0,d=f.useSyncExternalStore(E,n,n),m=f.useSyncExternalStore(T,i,i),h;a[0]!==t||a[1]!==e?(h=_(e,t),a[0]=t,a[1]=e,a[2]=h):h=a[2];let g=h,v;a[3]===g?v=a[4]:(v=w(g),a[3]=g,a[4]=v);let y=v,b=`${m}\n${u?.key??``}\n${u?.connectionGeneration??``}\n${d}\n${t}\n${e}\n${o}`,x=y?``:g.source,S=y,C;a[5]!==S||a[6]!==x||a[7]!==b?(C={key:b,source:x,loading:S,error:null},a[5]=S,a[6]=x,a[7]=b,a[8]=C):C=a[8];let[D,O]=f.useState(C),k,A;a[9]!==o||a[10]!==b||a[11]!==g||a[12]!==u||a[13]!==m||a[14]!==y?(k=()=>{if(!y||!w(g)){O({key:b,source:g.source,loading:!1,error:null});return}O({key:b,source:``,loading:!0,error:null});let e=new AbortController,t;return c(g.path,e.signal,o,u).then(n=>{if(e.signal.aborted||i()!==m){n.release();return}t=n.release,O({key:b,source:n.url,loading:!1,error:null})}).catch(t=>{e.signal.aborted||O({key:b,source:``,loading:!1,error:t instanceof Error?t.message:`Image source request failed`})}),()=>{e.abort(),t?.()}},A=[b,g,m,y,o,u],a[9]=o,a[10]=b,a[11]=g,a[12]=u,a[13]=m,a[14]=y,a[15]=k,a[16]=A):(k=a[15],A=a[16]),f.useEffect(k,A);let j;return a[17]!==D||a[18]!==S||a[19]!==x||a[20]!==b?(j=D.key===b?D:{key:b,source:x,loading:S,error:null},a[17]=D,a[18]=S,a[19]=x,a[20]=b,a[21]=j):j=a[21],j},O=(e,t,n)=>D(e,t,n===void 0?`inline`:n).source;export{_ as a,C as c,w as i,S as n,D as o,x as r,O as s,v as t};
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{_ as t,s as n}from"./runtime-auth-DA-qfGHk.js";import{c as r,i}from"./runtime-switch-DEPKHgdL.js";import{st as a}from"./vendor-base-ui-wXsskyKm.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{n as o}from"./vendor-react-BkccXcWz.js";import{E as s,t as c}from"./runtime-file-resource-BGZ4tGr5.js";import{a as l,o as u,r as d}from"./path-utils-jGozTg9d.js";var f=e(a(),1),p=o(),m=[0,250,750],h=e=>{try{return decodeURIComponent(e)}catch{return e}},g=e=>{try{let t=new URL(e),n=h(t.hostname),r=h(t.pathname);return/^[A-Za-z]$/.test(n)?r=`${n.toUpperCase()}:${r}`:n&&n.toLowerCase()!==`localhost`&&(r=`//${n}${r}`),/^\/[A-Za-z]:[\\/]/.test(r)&&(r=r.slice(1)),l(r)}catch{let t=h(e.replace(/^file:\/\//i,``));return/^\/[A-Za-z]:[\\/]/.test(t)&&(t=t.slice(1)),l(t)}},_=(e,t)=>{let n=e.trim();if(!n||/^https?:/i.test(n)||/^(?:data|blob):/i.test(n)||/^\/api(?=\/|[?#]|$)/.test(n))return{kind:`direct`,source:n};if(/^file:\/\//i.test(n))return{kind:`runtime-file`,source:n,path:g(n)};if(/^[a-z][a-z\d+.-]*:/i.test(n)&&!/^[A-Za-z]:[\\/]/.test(n))return{kind:`direct`,source:n};let r=h(n);return{kind:`runtime-file`,source:n,path:d(r)?l(r):u(t,r)}},v=(e,t,n)=>y(()=>c(e,t,void 0,n),t),y=async(e,t)=>{let r=i(),a=n(),o;for(let s of m){t.throwIfAborted(),s>0&&await new Promise((e,n)=>{let r=window.setTimeout(()=>{t.removeEventListener(`abort`,i),e()},s),i=()=>{window.clearTimeout(r),n(t.reason)};t.addEventListener(`abort`,i,{once:!0})});try{if(t.throwIfAborted(),r!==i()||a!==n())throw new DOMException(`Image request superseded`,`AbortError`);return await e()}catch(e){if(t.aborted||r!==i()||a!==n())throw e;o=e}}throw o instanceof Error?o:Error(`Image source request failed`)},b=()=>!1,x=e=>e.startsWith(`relay:`)||b(),S=(e,t)=>typeof t==`number`&&Number.isFinite(t)&&t>1048576&&x(e),C=()=>f.useSyncExternalStore(T,i,i),w=e=>e.kind===`runtime-file`&&!!e.path,T=e=>r(()=>e()),E=e=>t(()=>e()),D=(e,t,r)=>{let a=(0,p.c)(22),o=r===void 0?`inline`:r,l=s(),u=l?.entry.location.hostId?l.entry:void 0,d=f.useSyncExternalStore(E,n,n),m=f.useSyncExternalStore(T,i,i),h;a[0]!==t||a[1]!==e?(h=_(e,t),a[0]=t,a[1]=e,a[2]=h):h=a[2];let g=h,v;a[3]===g?v=a[4]:(v=w(g),a[3]=g,a[4]=v);let y=v,b=`${m}\n${u?.key??``}\n${u?.connectionGeneration??``}\n${d}\n${t}\n${e}\n${o}`,x=y?``:g.source,S=y,C;a[5]!==S||a[6]!==x||a[7]!==b?(C={key:b,source:x,loading:S,error:null},a[5]=S,a[6]=x,a[7]=b,a[8]=C):C=a[8];let[D,O]=f.useState(C),k,A;a[9]!==o||a[10]!==b||a[11]!==g||a[12]!==u||a[13]!==m||a[14]!==y?(k=()=>{if(!y||!w(g)){O({key:b,source:g.source,loading:!1,error:null});return}O({key:b,source:``,loading:!0,error:null});let e=new AbortController,t;return c(g.path,e.signal,o,u).then(n=>{if(e.signal.aborted||i()!==m){n.release();return}t=n.release,O({key:b,source:n.url,loading:!1,error:null})}).catch(t=>{e.signal.aborted||O({key:b,source:``,loading:!1,error:t instanceof Error?t.message:`Image source request failed`})}),()=>{e.abort(),t?.()}},A=[b,g,m,y,o,u],a[9]=o,a[10]=b,a[11]=g,a[12]=u,a[13]=m,a[14]=y,a[15]=k,a[16]=A):(k=a[15],A=a[16]),f.useEffect(k,A);let j;return a[17]!==D||a[18]!==S||a[19]!==x||a[20]!==b?(j=D.key===b?D:{key:b,source:x,loading:S,error:null},a[17]=D,a[18]=S,a[19]=x,a[20]=b,a[21]=j):j=a[21],j},O=(e,t,n)=>D(e,t,n===void 0?`inline`:n).source;export{_ as a,C as c,w as i,S as n,D as o,x as r,O as s,v as t};
@@ -1 +1 @@
1
- import"./rolldown-runtime-hePW80VL.js";import{ot as e,st as t}from"./vendor-base-ui-wXsskyKm.js";import{n}from"./vendor-react-BkccXcWz.js";import{no as r}from"./ui-DeV7Us1B.js";var i=n();t();var a=e();function o(e){let t=(0,i.c)(23),n,o,s,c,l,u;t[0]===e?(n=t[1],o=t[2],s=t[3],c=t[4],l=t[5],u=t[6]):({className:o,type:u,bordered:n,placeholder:c,endAdornment:s,...l}=e,t[0]=e,t[1]=n,t[2]=o,t[3]=s,t[4]=c,t[5]=l,t[6]=u);let d=c||` `,f=n!==void 0&&`border border-transparent ring-0 focus:ring-0 aria-invalid:ring-1 aria-invalid:focus:ring-1`,p=n&&`border-[var(--form-surface-border)]`,m=s&&`pe-11`,h;t[7]!==o||t[8]!==f||t[9]!==p||t[10]!==m?(h=r(`text-foreground file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-[var(--surface-elevated)] appearance-none flex h-9 w-full min-w-0 rounded-lg px-3 py-1 typography-markdown outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label`,`ring-1 ring-inset ring-border/60 transition duration-200 ease-out`,`hover:[&:not(:focus)]:bg-[var(--surface-subtle)] hover:[&:not(:focus)]:ring-transparent`,`focus:ring-2 focus:ring-[var(--interactive-focus-ring)] focus-visible:outline-none`,`aria-invalid:ring-[var(--status-error)] aria-invalid:focus:ring-[var(--status-error)]`,f,p,o,m),t[7]=o,t[8]=f,t[9]=p,t[10]=m,t[11]=h):h=t[11];let g;t[12]!==n||t[13]!==l||t[14]!==d||t[15]!==h||t[16]!==u?(g=(0,a.jsx)(`input`,{type:u,"data-slot":`input`,"data-bordered":n,placeholder:d,className:h,spellCheck:!1,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`,...l}),t[12]=n,t[13]=l,t[14]=d,t[15]=h,t[16]=u,t[17]=g):g=t[17];let _=g;if(!s)return _;let v;t[18]===s?v=t[19]:(v=(0,a.jsx)(`div`,{"data-slot":`input-end-adornment`,className:`absolute inset-y-0 end-0 flex items-center`,children:s}),t[18]=s,t[19]=v);let y;return t[20]!==_||t[21]!==v?(y=(0,a.jsxs)(`div`,{"data-slot":`input-wrapper`,className:`relative min-w-0 w-full flex-1`,children:[_,v]}),t[20]=_,t[21]=v,t[22]=y):y=t[22],y}export{o as t};
1
+ import"./rolldown-runtime-hePW80VL.js";import{ot as e,st as t}from"./vendor-base-ui-wXsskyKm.js";import{n}from"./vendor-react-BkccXcWz.js";import{io as r}from"./ui-BCYkB585.js";var i=n();t();var a=e();function o(e){let t=(0,i.c)(23),n,o,s,c,l,u;t[0]===e?(n=t[1],o=t[2],s=t[3],c=t[4],l=t[5],u=t[6]):({className:o,type:u,bordered:n,placeholder:c,endAdornment:s,...l}=e,t[0]=e,t[1]=n,t[2]=o,t[3]=s,t[4]=c,t[5]=l,t[6]=u);let d=c||` `,f=n!==void 0&&`border border-transparent ring-0 focus:ring-0 aria-invalid:ring-1 aria-invalid:focus:ring-1`,p=n&&`border-[var(--form-surface-border)]`,m=s&&`pe-11`,h;t[7]!==o||t[8]!==f||t[9]!==p||t[10]!==m?(h=r(`text-foreground file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-[var(--surface-elevated)] appearance-none flex h-9 w-full min-w-0 rounded-lg px-3 py-1 typography-markdown outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label`,`ring-1 ring-inset ring-border/60 transition duration-200 ease-out`,`hover:[&:not(:focus)]:bg-[var(--surface-subtle)] hover:[&:not(:focus)]:ring-transparent`,`focus:ring-2 focus:ring-[var(--interactive-focus-ring)] focus-visible:outline-none`,`aria-invalid:ring-[var(--status-error)] aria-invalid:focus:ring-[var(--status-error)]`,f,p,o,m),t[7]=o,t[8]=f,t[9]=p,t[10]=m,t[11]=h):h=t[11];let g;t[12]!==n||t[13]!==l||t[14]!==d||t[15]!==h||t[16]!==u?(g=(0,a.jsx)(`input`,{type:u,"data-slot":`input`,"data-bordered":n,placeholder:d,className:h,spellCheck:!1,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`,...l}),t[12]=n,t[13]=l,t[14]=d,t[15]=h,t[16]=u,t[17]=g):g=t[17];let _=g;if(!s)return _;let v;t[18]===s?v=t[19]:(v=(0,a.jsx)(`div`,{"data-slot":`input-end-adornment`,className:`absolute inset-y-0 end-0 flex items-center`,children:s}),t[18]=s,t[19]=v);let y;return t[20]!==_||t[21]!==v?(y=(0,a.jsxs)(`div`,{"data-slot":`input-wrapper`,className:`relative min-w-0 w-full flex-1`,children:[_,v]}),t[20]=_,t[21]=v,t[22]=y):y=t[22],y}export{o as t};
@@ -1 +1 @@
1
- import{i as e,n as t}from"./runtime-switch-DEPKHgdL.js";import{a as n}from"./vendor-zustand-CTekDqaS.js";import{t as r}from"./brand-storage-migration-Bhz6UOBJ.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{D as i,E as a,F as o,O as s,R as c,S as l,k as u,o as d,s as f,w as p,x as m}from"./prompt-attachment-upload-BG4nBKxi.js";import{t as h}from"./uuid-D-SDZijH.js";var g=`yuri_input_draft_metadata_v1`,_=`yuri_input_draft_metadata_migration_v1`,v=`yuri_chat_input_draft_`,y=`yuri_chat_confirmed_mentions_`,b=()=>({ok:!1,error:{code:`unavailable`}}),x=()=>({ok:!1,error:{code:`cancelled`}}),S=e=>({ok:!1,error:{code:e instanceof DOMException&&e.name===`QuotaExceededError`?`quota`:`unavailable`}}),C=e=>typeof e==`object`&&!!e&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),w=(e,t)=>Object.keys(e).every(e=>t.includes(e)),T=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0,E=e=>typeof e==`string`&&e.length>0,D=e=>({read:async t=>{if(!e)return b();try{return{ok:!0,value:e.getItem(t)}}catch(e){return S(e)}},write:async(t,n)=>{if(!e)return b();try{return e.setItem(t,n),{ok:!0,value:void 0}}catch(e){return S(e)}},remove:async t=>{if(!e)return b();try{return e.removeItem(t),{ok:!0,value:void 0}}catch(e){return S(e)}},keys:async()=>{if(!e)return b();try{let t=[];for(let n=0;n<e.length;n+=1){let r=e.key(n);r!==null&&t.push(r)}return{ok:!0,value:t}}catch(e){return S(e)}}}),O=()=>{try{return D(typeof window>`u`?null:window.localStorage)}catch{return D(null)}},k=(e,t,n,r)=>{let i=[];try{let e=n===null?[]:JSON.parse(n);Array.isArray(e)&&(i=e.filter(e=>typeof e==`string`))}catch{}return{suffix:e,text:t??``,mentions:i,keys:r}},ee=async e=>{let t=await e.keys();if(!t.ok)return t;let n=new Set;for(let e of t.value)e.startsWith(v)&&n.add(e.slice(22)),e.startsWith(y)&&n.add(e.slice(29));let r=[];for(let i of n){let n=`${v}${i}`,a=`${y}${i}`,[o,s]=await Promise.all([e.read(n),e.read(a)]);if(!o.ok)return o;if(!s.ok)return s;r.push(k(i,o.value,s.value,[n,a].filter(e=>t.value.includes(e))))}return{ok:!0,value:r}},te=e=>{if(!(!C(e)||!w(e,[`suffix`,`text`,`mentions`,`keys`])||typeof e.suffix!=`string`||typeof e.text!=`string`||!Array.isArray(e.mentions)||!e.mentions.every(e=>typeof e==`string`)||!Array.isArray(e.keys)||!e.keys.every(e=>typeof e==`string`)))return{suffix:e.suffix,text:e.text,mentions:[...e.mentions],keys:[...e.keys]}},ne=e=>{try{let t=JSON.parse(e);return Array.isArray(t)&&t.length===3&&E(t[0])&&(t[1]===`session`||t[1]===`draft`)&&E(t[2])&&e===JSON.stringify(t)}catch{return!1}},A=e=>{if(!C(e)||!w(e,[`complete`,`claimedTransportIdentity`,`captured`,`markerCommitted`,`cleanupComplete`])||typeof e.complete!=`boolean`||typeof e.claimedTransportIdentity!=`string`||e.captured!==void 0&&typeof e.captured!=`boolean`||e.markerCommitted!==void 0&&typeof e.markerCommitted!=`boolean`||e.cleanupComplete!==void 0&&typeof e.cleanupComplete!=`boolean`)return;let t=e.cleanupComplete??e.complete,n=e.captured??e.complete,r=e.markerCommitted??e.complete;if(!((n||r||t)&&!E(e.claimedTransportIdentity))&&!(r&&!n)&&!(t&&(!n||!r)))return{complete:t,claimedTransportIdentity:e.claimedTransportIdentity,captured:n,markerCommitted:r,cleanupComplete:t}},j=e=>{if(!C(e)||!w(e,[`version`,`drafts`,`tombstones`,`migration`,`legacy`])||e.version!==1||!C(e.drafts)||!C(e.tombstones)||!C(e.legacy)||!w(e.legacy,[`new`,`entries`])||!C(e.legacy.entries))return;let t=A(e.migration);if(!t)return;let n={};for(let[t,r]of Object.entries(e.drafts)){let e=c(r);if(!e||t!==a(e.key))return;n[t]=e}let r={};for(let[t,n]of Object.entries(e.tombstones)){if(!ne(t)||!T(n))return;r[t]=n}let i={};for(let[t,n]of Object.entries(e.legacy.entries)){let e=te(n);if(!e||t!==e.suffix||t===`new`)return;i[t]=e}let o=e.legacy.new===void 0?void 0:te(e.legacy.new);if(!(e.legacy.new!==void 0&&(!o||o.suffix!==`new`)))return{version:1,drafts:n,tombstones:r,migration:t,legacy:{...o?{new:o}:{},entries:i}}},M=(e=``)=>({version:1,drafts:{},tombstones:{},migration:{complete:!1,claimedTransportIdentity:e,captured:!1,markerCommitted:!1,cleanupComplete:!1},legacy:{entries:{}}}),N=e=>{try{return{ok:!0,value:JSON.stringify(e)}}catch{return{ok:!1,error:{code:`serialization`}}}},P=async e=>{let t=await e.read(g);if(!t.ok)return t;if(t.value===null)return{ok:!0,value:null};try{let e=j(JSON.parse(t.value));return e?{ok:!0,value:e}:{ok:!1,error:{code:`corrupt`}}}catch{return{ok:!1,error:{code:`corrupt`}}}},F=async(e,t)=>{let n=j(t);if(!n)return{ok:!1,error:{code:`corrupt`}};let r=N(n);return r.ok?e.write(g,r.value):r},I=e=>C(e)&&w(e,[`version`,`claimedTransportIdentity`])&&e.version===1&&E(e.claimedTransportIdentity)?{version:1,claimedTransportIdentity:e.claimedTransportIdentity}:void 0,re=e=>N({version:1,claimedTransportIdentity:e}),ie=(e,t,n)=>{let r={},i;for(let e of t)e.suffix===`new`?i=e:r[e.suffix]=e;return{...e,migration:{complete:!1,claimedTransportIdentity:n,captured:!0,markerCommitted:!1,cleanupComplete:!1},legacy:{...i?{new:i}:{},entries:r}}},L=e=>[...new Set([e.legacy.new,...Object.values(e.legacy.entries)].flatMap(e=>e?.keys??[]))],ae=new WeakMap,R=e=>{let t=ae.get(e);if(t)return t;let n=Promise.resolve(),r,i=!0,a=e=>{let t=n.then(e,e);return n=t.then(()=>void 0,()=>void 0),t},o={persist:t=>{let n=j(t);return n?i?a(async()=>i?F(e,n):b()):Promise.resolve(b()):Promise.resolve({ok:!1,error:{code:`corrupt`}})},migrate:(t,n={})=>{if(r)return r;let o=a(async()=>{let r=await P(e);if(!r.ok)return r;let a=r.value??M(),o=i&&(n.persistenceEnabled??!0);if(!a.migration.captured){let n=await ee(e);if(!n.ok)return n;if(!o)return{ok:!0,value:ie(a,n.value,``)};if(a=ie(a,n.value,t),!i)return{ok:!0,value:a};let r=await F(e,a);if(!r.ok)return r}if(!i||!(n.persistenceEnabled??!0)){let t=await ee(e);return t.ok?{ok:!0,value:a}:t}let s=await e.read(_);if(!s.ok)return s;if(s.value!==null)try{let t=I(JSON.parse(s.value));if(!t)return{ok:!1,error:{code:`corrupt`}};if(t.claimedTransportIdentity!==a.migration.claimedTransportIdentity){let t=re(a.migration.claimedTransportIdentity);if(!t.ok)return t;if(!i)return{ok:!0,value:a};let n=await e.write(_,t.value);if(!n.ok)return n}}catch{return{ok:!1,error:{code:`corrupt`}}}else{let t=re(a.migration.claimedTransportIdentity);if(!t.ok)return t;if(!i)return{ok:!0,value:a};let n=await e.write(_,t.value);if(!n.ok)return n}if(a.migration.cleanupComplete)return{ok:!0,value:a};for(let t of L(a)){if(!i)return{ok:!0,value:a};let n=await e.remove(t);if(!n.ok)return n}if(a={...a,migration:{complete:!0,claimedTransportIdentity:a.migration.claimedTransportIdentity,captured:!0,markerCommitted:!0,cleanupComplete:!0}},!i)return{ok:!0,value:a};let c=await F(e,a);return c.ok?{ok:!0,value:a}:c}).finally(()=>{r=void 0});return r=o,o},flush:()=>n,setEnabled:async e=>{i=e,i||await n}};return ae.set(e,o),o},z=e=>{let t=R(e),n=!0,r=!1,i=[],a=[],o=()=>{if(r||i.length>0)return;let e=a;a=[],e.forEach(e=>e())},s=()=>{if(r)return;let e=i.shift();if(!e){o();return}r=!0,t.persist(e.snapshot).then(e.resolve).finally(()=>{r=!1,s()})};return{persist:e=>{let t=j(e);return t?n?new Promise(e=>{i.push({snapshot:t,resolve:e}),s()}):Promise.resolve(b()):Promise.resolve({ok:!1,error:{code:`corrupt`}})},cancelPending:()=>{let e=i;i=[],e.forEach(({resolve:e})=>e(x())),o()},flush:()=>r||i.length>0?new Promise(e=>a.push(e)):Promise.resolve(),setEnabled:async e=>{if(n=e,!n){let e=i;i=[],e.forEach(({resolve:e})=>e(x()))}await(r||i.length>0?new Promise(e=>a.push(e)):Promise.resolve()),await t.setEnabled(e),await t.flush()}}},oe=`yuri-input-drafts`,se=1,ce=`blobs`,le=`blobRefs`,B=class extends Error{code;constructor(e){super(e),this.code=e}},V=e=>({ok:!1,error:{code:e instanceof B?e.code:e instanceof DOMException&&e.name===`QuotaExceededError`?`quota-exceeded`:e instanceof DOMException&&e.name===`AbortError`?`transaction-aborted`:`transaction-failed`}}),H=e=>{if(!(e instanceof Blob)&&!u(e))throw new B(`invalid-value`)},U=e=>{if(!e)throw new B(`invalid-value`)},W=(e,t)=>({id:p(e),blobID:t,transportIdentity:e.transportIdentity,ownerKind:e.owner.kind,ownerID:e.owner.ownerID}),G=async e=>{if(typeof e==`string`)return`url:${e}`;let t=await crypto.subtle.digest(`SHA-256`,await e.arrayBuffer()),n=[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,`0`)).join(``);return`blob:${e.type}:${e.size}:${n}`},K=async(e,t)=>(e.fingerprint??await G(e.value))===t,q=async(e,t=!1)=>{let n=await e.getAllBlobRefs(),r=await e.getAllBlobs(),i=new Map;for(let t of n)await e.getBlob(t.blobID)?i.set(t.blobID,(i.get(t.blobID)??0)+1):await e.deleteBlobRef(t.id);for(let n of r){let r=i.get(n.id)??0;r||!t?await e.putBlob({...n,refCount:r}):await e.deleteBlob(n.id)}},ue=e=>{try{let t=JSON.parse(e);return!Array.isArray(t)||t.length!==4||typeof t[0]!=`string`||typeof t[2]!=`string`||t[1]!==`session`&&t[1]!==`draft`&&t[1]!==`surface`&&t[1]!==`queue`&&t[1]!==`send`?void 0:{transportIdentity:t[0],ownerKind:t[1],ownerID:t[2]}}catch{return}},J=(e,t)=>{let n=ue(e.id),r=e.ownerKind??n?.ownerKind,i=e.transportIdentity??n?.transportIdentity;return r!==void 0&&t.ownerKinds.includes(r)&&(t.transportIdentities===void 0||i!==void 0&&t.transportIdentities.includes(i))},Y=(e=de())=>{let t=async(t,n)=>{try{return{ok:!0,value:await e.transaction(async e=>{let r=await e.getBlobRef(p(t));return!r||n!==void 0&&r.blobID!==n?!1:(await e.deleteBlobRef(r.id),await q(e),(await e.getAllBlobRefs()).some(e=>e.blobID===r.blobID)||await e.deleteBlob(r.blobID),!0)})}}catch(e){return V(e)}};return{put:async(t,n)=>{try{U(t),H(n);let r=await G(n);return await e.transaction(async e=>{let i=await e.getBlob(t);if(i&&!await K(i,r))throw new B(`blob-id-conflict`);i||await e.putBlob({id:t,value:n,refCount:0,fingerprint:r})}),{ok:!0,value:void 0}}catch(e){return V(e)}},putAndRetain:async(t,n,r)=>{try{U(n),H(r);let i=await G(r);return await e.transaction(async e=>{let a=p(t),o=await e.getBlobRef(a);if(o&&o.blobID!==n)throw new B(`blob-id-conflict`);let s=await e.getBlob(n);if(s&&!await K(s,i))throw new B(`blob-id-conflict`);s||await e.putBlob({id:n,value:r,refCount:0,fingerprint:i}),o||await e.putBlobRef(W(t,n)),await q(e)}),{ok:!0,value:void 0}}catch(e){return V(e)}},read:async t=>{try{let n=await e.transaction(e=>e.getBlob(t));return n?{ok:!0,value:n.value}:{ok:!1,error:{code:`missing-blob`}}}catch(e){return V(e)}},readReference:async t=>{try{return{ok:!0,value:(await e.transaction(e=>e.getBlobRef(p(t))))?.blobID}}catch(e){return V(e)}},retain:async(t,n)=>{try{return U(n),await e.transaction(async e=>{let r=await e.getBlobRef(p(t));if(r&&r.blobID!==n)throw new B(`blob-id-conflict`);if(!await e.getBlob(n))throw new B(`missing-blob`);r||await e.putBlobRef(W(t,n)),await q(e)}),{ok:!0,value:void 0}}catch(e){return V(e)}},release:e=>t(e),releaseIfMatches:(e,n)=>t(e,n),reconcileReferences:async(t,n={ownerKinds:[`session`,`draft`]})=>{try{return{ok:!0,value:await e.transaction(async e=>{let r=[],i=[],a=[],o=new Map((await e.getAllBlobRefs()).map(e=>[e.id,e]));for(let[i,a]of o)J(a,n)&&t.get(i)!==a.blobID&&(await e.deleteBlobRef(i),r.push(i));for(let[r,s]of t){let t=ue(r);if(!t||!n.ownerKinds.includes(t.ownerKind)||n.transportIdentities!==void 0&&!n.transportIdentities.includes(t.transportIdentity)){a.push(r);continue}let c=o.get(r);if(!await e.getBlob(s)){a.push(r);continue}(!c||c.blobID!==s)&&(await e.putBlobRef({id:r,blobID:s,...t}),i.push(r))}return await q(e,!0),{released:r,repaired:i,missing:a}})}}catch(e){return V(e)}},reconcileOwnerReferences:async(t,n)=>{let r=new Map;for(let[e,i]of n)r.set(p({transportIdentity:t.transportIdentity,owner:t.owner,attachmentOccurrenceRefID:e}),i);try{return{ok:!0,value:await e.transaction(async e=>{let n=0,i=new Set;for(let a of await e.getAllBlobRefs())a.transportIdentity===t.transportIdentity&&a.ownerKind===t.owner.kind&&a.ownerID===t.owner.ownerID&&r.get(a.id)!==a.blobID&&(await e.deleteBlobRef(a.id),i.add(a.blobID),n++);await q(e);let a=await e.getAllBlobRefs();for(let t of i)a.some(e=>e.blobID===t)||await e.deleteBlob(t);return n})}}catch(e){return V(e)}},discardUnreferenced:async t=>{try{return{ok:!0,value:await e.transaction(async e=>!await e.getBlob(t)||(await e.getAllBlobRefs()).some(e=>e.blobID===t)?!1:(await e.deleteBlob(t),!0))}}catch(e){return V(e)}}}},de=(e=oe)=>({transaction:async t=>{let n=await X(e),r=n.transaction([ce,le],`readwrite`),i=r.objectStore(ce),a=r.objectStore(le),o=e=>new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error??r.error??Error(`IndexedDB request failed`))}),s=new Promise((e,t)=>{r.oncomplete=()=>e(),r.onabort=()=>t(r.error??new DOMException(`aborted`,`AbortError`)),r.onerror=()=>{console.error(`Input draft IndexedDB transaction error`,r.error)}}),c;try{let e=await t({getBlob:e=>o(i.get(e)),getAllBlobs:()=>o(i.getAll()),putBlob:async e=>{await o(i.put(e))},deleteBlob:async e=>{await o(i.delete(e))},getBlobRef:e=>o(a.get(e)),getAllBlobRefs:()=>o(a.getAll()),putBlobRef:async e=>{await o(a.put(e))},deleteBlobRef:async e=>{await o(a.delete(e))}});return await s,e}catch(e){c=e;try{r.abort()}catch{}try{await s}catch(e){c===void 0&&(c=e)}throw c}finally{n.close()}}}),X=e=>(e===oe?r(oe):Promise.resolve()).then(()=>new Promise((t,n)=>{if(!globalThis.indexedDB){n(new B(`database-unavailable`));return}let r=indexedDB.open(e,se),i=!1,a=()=>{i||(i=!0,n(new B(`database-unavailable`)))};r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(ce)||e.createObjectStore(ce,{keyPath:`id`}),e.objectStoreNames.contains(le)||e.createObjectStore(le,{keyPath:`id`})},r.onsuccess=()=>{let e=r.result;if(e.onversionchange=()=>e.close(),i){e.close();return}i=!0,t(e)},r.onerror=a,r.onblocked=a})),fe=()=>({drafts:{},tombstones:{},migration:{complete:!1,claimedTransportIdentity:``,captured:!1,markerCommitted:!1,cleanupComplete:!1},legacy:{entries:{}}}),pe=e=>({version:1,drafts:e.drafts,tombstones:e.tombstones,migration:e.migration,legacy:e.legacy}),me=e=>{let t=pe(e),n=he(JSON.parse(JSON.stringify(t)));return{drafts:n.drafts,tombstones:n.tombstones,migration:n.migration,legacy:n.legacy}},he=e=>{let t=j(e);if(!t)throw Error(`invalid draft snapshot`);return t},ge=e=>e instanceof Map?[...e.entries()]:Object.entries(e??{}),_e=e=>typeof e==`string`?e:a(e),ve=[`session`,`draft`,`surface`],Z=e=>({transportIdentity:e.transportIdentity,owner:{kind:e.owner.kind,ownerID:e.owner.ownerID},attachmentOccurrenceRefID:e.attachmentOccurrenceRefID}),ye=e=>JSON.parse(JSON.stringify(e)),be=e=>e.phase===`metadata`?{phase:`metadata`,error:{code:e.error.code}}:{phase:`blob`,error:{...e.error},...e.reference?{reference:Z(e.reference)}:{}},xe=e=>({status:e.status,keys:[...e.keys],errors:e.errors.map(be),cleanupErrors:e.cleanupErrors.map(be)}),Se=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0,Ce=e=>{try{let t=JSON.parse(e);return Array.isArray(t)&&t.length===3&&typeof t[0]==`string`&&ve.includes(t[1])&&typeof t[2]==`string`&&t[0].length>0&&t[2].length>0}catch{return!1}},we=e=>[...e.attachments,...e.syntheticParts.flatMap(e=>e.attachments)].flatMap(t=>t.locator.kind===`blob`?[{reference:{transportIdentity:e.key.transportIdentity,owner:{kind:e.key.owner.kind,ownerID:e.key.owner.ownerID},attachmentOccurrenceRefID:t.attachmentRefID},attachment:ye(t)}]:[]),Te=e=>{let t=new Map;for(let n of Object.values(e))for(let e of we(n))t.set(p(e.reference),e);return t},Q=(e,t)=>({phase:`blob`,error:{...e},...t?{reference:Z(t)}:{}}),$=(e,t=[])=>({status:e,keys:t,errors:[],cleanupErrors:[]}),Ee=e=>e?.attachment.locator.kind===`blob`?e.attachment.locator.blobID:``,De=(e,t,n={})=>{let r=fe(),i=n.enabled??!0,o=0,s=!1,l=Promise.resolve(),u=new Map,d=e=>{let t=l.then(e,e);return l=t.then(()=>void 0,()=>void 0),t.then(e=>e&&typeof e==`object`&&`status`in e&&`keys`in e&&`errors`in e&&`cleanupErrors`in e?xe(e):e)},f=async(t=r.drafts)=>{let n=[],i=new Map([...Te(t)].map(([e,t])=>[e,t.attachment.locator.kind===`blob`?t.attachment.locator.blobID:``]));for(let[t,r]of u){if(i.get(t)===r.expectedBlobID){u.delete(t);continue}let a=await e.releaseIfMatches(Z(r.reference),r.expectedBlobID);a.ok?u.delete(t):n.push(Q(a.error,r.reference))}return n},m=async(t,n,r,i)=>{let a=Z(t),s=await e.releaseIfMatches(a,n);s.ok||(u.set(p(a),{reference:Z(a),expectedBlobID:n,generation:o,reason:i}),r.push(Q(s.error,a)))},h=async(t,n)=>{let r=t.attachment.locator.kind===`blob`?t.attachment.locator.blobID:``,i=Z(t.reference),a=ye(t.attachment),o=await e.readReference(i);if(!o.ok)return{acquired:!1,error:Q(o.error,i)};if(o.value&&o.value!==r)return{acquired:!1,error:Q({code:`reference-conflict`},i)};if(o.value===r){let t=await e.read(r);if(t.ok)return{acquired:!1};if(t.error.code!==`missing-blob`)return{acquired:!1,error:Q(t.error,i)};let o=await n?.(Z(i),ye(a));if(o===void 0)return{acquired:!1,error:Q({code:`runtime-value-missing`},i)};let s=await e.putAndRetain(i,r,o);return s.ok?{acquired:!0}:{acquired:!1,error:Q(s.error,i)}}let s=await e.read(r);if(s.ok){let t=await e.retain(i,r);return t.ok?{acquired:!0}:{acquired:!1,error:Q(t.error,i)}}if(s.error.code!==`missing-blob`)return{acquired:!1,error:Q(s.error,i)};let c=await n?.(Z(i),ye(a));if(c===void 0)return{acquired:!1,error:Q({code:`runtime-value-missing`},i)};let l=await e.putAndRetain(i,r,c);return l.ok?{acquired:!0}:{acquired:!1,error:Q(l.error,i)}};return{seed:t=>d(async()=>{if(!i)return $(`disabled`);if(s)return{...$(`failed`),errors:[Q({code:`invalid-record`})]};let n;try{if(!t)n=fe();else{let e=he(JSON.parse(JSON.stringify(t)));n={drafts:e.drafts,tombstones:e.tombstones,migration:e.migration,legacy:e.legacy}}}catch{return{...$(`failed`),errors:[Q({code:`invalid-record`})]}}let a=Te(n.drafts),o=await e.reconcileReferences(new Map([...a].map(([e,t])=>[e,Ee(t)])),{ownerKinds:ve});return o.ok?(r=n,s=!0,{...$(`committed`),errors:o.value.missing.map(e=>Q({code:`missing-blob`},a.get(e)?.reference))}):{...$(`failed`),errors:[Q(o.error)]}}),commit:e=>{let n=[...ge(e.drafts).map(([e])=>e),...(e.delete??[]).map(_e)];return i?d(async()=>{if(!s)return $(`unseeded`,n);if(!i)return $(`disabled`,n);let l=o,u=[],d=me(r),g=ge(e.drafts),_=ge(e.tombstones),v=(e.delete??[]).map(_e);if(g.some(([e,t])=>!Ce(e)||!Se(t.revision))||_.some(([e,t])=>!Ce(e)||!Se(t))||v.some(e=>!Ce(e))||new Set(g.map(([e])=>e)).size!==g.length||_.some(([e])=>g.some(([t])=>t===e)))return{...$(`failed`,n),errors:[Q({code:`invalid-record`})]};try{for(let[e,t]of g){let n=c(t);if(!n||e!==a(n.key))throw Error(`invalid draft record`);d.drafts[e]=n,delete d.tombstones[e]}for(let e of v)delete d.drafts[e];for(let[e,t]of _)d.tombstones[e]=t;e.migration&&(d.migration=e.migration),e.legacy&&(d.legacy=e.legacy);let t=he(pe(d));d.drafts=t.drafts,d.tombstones=t.tombstones,d.migration=t.migration,d.legacy=t.legacy}catch{return{...$(`failed`,n),errors:[Q({code:`invalid-record`})],cleanupErrors:u}}if(!await e.isCurrent())return $(`stale`,n);let y=Te(r.drafts),b=Te(d.drafts);u=await f(d.drafts);let x=[];for(let[t,r]of b){let i=y.get(t);if((i?.attachment.locator.kind===`blob`?i.attachment.locator.blobID:void 0)===(r.attachment.locator.kind===`blob`?r.attachment.locator.blobID:void 0))continue;let a=await h(r,e.resolveBlobValue);if(a.error){for(let e of x.reverse())await m(e,Ee(b.get(p(e))),u,`acquire-failed`);return{...$(`failed`,n),errors:[a.error],cleanupErrors:u}}a.acquired&&x.push(r.reference)}if(!await e.isCurrent()){for(let e of x.reverse())await m(e,Ee(b.get(p(e))),u,`stale`);return{...$(`stale`,n),cleanupErrors:u}}if(!i||l!==o){for(let e of x.reverse())await m(e,Ee(b.get(p(e))),u,`disabled`);return{...$(`disabled`,n),cleanupErrors:u}}let S=await t.persist(pe(d));if(!S.ok){for(let e of x.reverse())await m(e,Ee(b.get(p(e))),u,`metadata-failed`);return{...$(`failed`,n),errors:[{phase:`metadata`,error:S.error}],cleanupErrors:u}}r=d;for(let[e,t]of y)b.has(e)||await m(t.reference,t.attachment.locator.kind===`blob`?t.attachment.locator.blobID:``,u,`metadata-committed`);return{...$(`committed`,n),cleanupErrors:u}}):Promise.resolve(xe($(`disabled`,n)))},reconcile:()=>d(async()=>{if(!s)return $(`unseeded`);if(!i)return $(`disabled`);let t=await f(),n=new Map([...Te(r.drafts)].map(([e,t])=>[e,t.attachment.locator.kind===`blob`?t.attachment.locator.blobID:``])),a=await e.reconcileReferences(n,{ownerKinds:ve}),o=a.ok?a.value.missing.map(e=>Q({code:`missing-blob`},Te(r.drafts).get(e)?.reference)):[Q(a.error)];return{status:a.ok?`committed`:`failed`,keys:[],errors:o,cleanupErrors:t}}),retryCleanup:()=>d(async()=>({...$(`committed`),cleanupErrors:await f()})),flush:()=>l,setEnabled:async e=>{if(!e){i=!1,o+=1,t.cancelPending?.(),await t.setEnabled?.(!1),await l,await t.flush?.();return}await t.setEnabled?.(!0),i=!0,o+=1}}},Oe=`yuri-composer-reference-draft`,ke=`yuri-pasted-text-draft`,Ae=e=>Array.from(e).length,je=e=>typeof e==`object`&&!!e&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),Me=(e,t)=>typeof e==`string`&&e.length>0&&e.length<=t,Ne=(e,t)=>{let n=[],r=[],i=0;for(let a=0;a<Math.min(t.length,m.referenceCount);a+=1){let o=t[a];if(!(!je(o)||!Me(o.id,m.idLength)||!Me(o.token,m.displayLength)||typeof o.text!=`string`||o.text.length>m.pastePayloadLength||typeof o.characterCount!=`number`||!Number.isSafeInteger(o.characterCount)||o.characterCount!==Ae(o.text)||typeof o.index!=`number`||!Number.isSafeInteger(o.index)||o.index<1))for(let t=e.indexOf(o.token);t>=0&&n.length<m.referenceCount;t=e.indexOf(o.token,t+o.token.length)){let e=t+o.token.length;if(r.some(n=>n.start<e&&n.end>t)||i+o.text.length>m.totalPastePayloadLength)continue;let a=n.filter(e=>e.id.startsWith(`${o.id}:`)).length;n.push({id:`${o.id}:${a}`,kind:`paste`,start:t,end:e,display:o.token,text:o.text,characterCount:o.characterCount,index:o.index}),r.push({start:t,end:e}),i+=o.text.length}}return n.sort((e,t)=>e.start-t.start)},Pe=e=>{try{let t=JSON.parse(e);if(!je(t)||typeof t.text!=`string`)return{text:e,references:[]};if(t.type===Oe||t.type===`openchamber-composer-reference-draft`)return(t.version===2?o(t.text,t.references):void 0)??{text:t.text,references:[]};if(t.type===ke||t.type===`openchamber-pasted-text-draft`){let e=t.version===1&&Array.isArray(t.references)?Ne(t.text,t.references):[];return o(t.text,e)??{text:t.text,references:[]}}}catch{}return{text:e,references:[]}},Fe=`file://`,Ie=e=>{let t=e.replace(/\\/g,`/`);return/^[A-Za-z]:/.test(t)&&(t=`/${t}`),t.split(`/`).map((e,t)=>t===1&&/^[A-Za-z]:$/.test(e)?e:encodeURIComponent(e)).join(`/`)},Le=e=>{let t=e.replace(/\\/g,`/`).trim();return t.toLowerCase().startsWith(Fe)?t:`${Fe}${Ie(t)}`},Re=(e,t)=>`${e}\u0000${t}`,ze=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error??Error(`Failed to read file`)),r.onabort=()=>n(Error(`File read aborted`)),r.readAsDataURL(e)}),Be=e=>{if(!e.startsWith(`data:`))return 0;let t=e.indexOf(`,`);if(t<0)return 0;let n=e.slice(0,t).toLowerCase(),r=e.slice(t+1);if(!n.endsWith(`;base64`))return 0;let i=0;return r.endsWith(`==`)?i=2:r.endsWith(`=`)&&(i=1),Math.max(0,Math.floor(r.length*3/4)-i)},Ve=(e,t)=>e===t?!0:!e||!t?!1:e.filePath===t.filePath&&e.fileName===t.fileName&&e.relativePath===t.relativePath&&e.fileSize===t.fileSize&&e.selection?.startLine===t.selection?.startLine&&e.selection?.endLine===t.selection?.endLine&&e.selection?.text===t.selection?.text,He=e=>({version:1,key:e,revision:1,text:``,attachments:[],syntheticParts:[],mentions:[]}),Ue=(e,t)=>t.flatMap(t=>{let n=`@${t}`,r=[],i=e.indexOf(n);for(;i>=0;)r.push({kind:`file`,value:t,path:t,label:t,range:{start:i,end:i+n.length}}),i=e.indexOf(n,i+n.length);return r}),We=(r={})=>{let o=r.sink??O(),p=r.repository??R(o),m=r.coordinator??z(o),g=r.blobStore??Y(),_=r.durability??De(g,m,{enabled:r.persistenceEnabled??!0}),v=new Map,y=new Map,b=new Map,x=new Map,S=new Map,C=new Set,w=new Set,T,E,D=0,k=0,ee=!1,te=!1,ne,A=new Set,j=new Map,M=new Set;return n()((n,o)=>{let m=e=>v.set(e,(v.get(e)??0)+1),O=(...e)=>{for(let t of e)b.set(t,(b.get(t)??0)+1),x.delete(t)},N=e=>c(e),P=()=>r.runtimeCapture?.()??{transportIdentity:e(),generation:t()},F=e=>{let t=P();return t.transportIdentity===e.transportIdentity&&t.generation===e.generation},I=e=>[...e.attachments,...e.syntheticParts.flatMap(e=>e.attachments)],re=e=>new Set(I(e).map(e=>e.attachmentRefID)),ie=(e,t,n)=>{let r=re(n);return{draftAttachmentViews:{...e.draftAttachmentViews,[t]:Object.fromEntries(Object.entries(e.draftAttachmentViews[t]??{}).filter(([e])=>r.has(e)))},draftMissingAttachmentRefIDs:{...e.draftMissingAttachmentRefIDs,[t]:(e.draftMissingAttachmentRefIDs[t]??[]).filter(e=>r.has(e))}}},L=()=>r.createID?.()??h(),ae=async(e,t)=>{let n=t instanceof File?t:new File([t],e.filename,{type:e.mimeType});return{id:e.attachmentID,file:n,dataUrl:typeof t==`string`?t:await ze(n),mimeType:e.mimeType,filename:e.filename,size:e.size,source:e.source,...e.serverPath?{serverPath:e.serverPath}:{},...e.vscodePath?{vscodePath:e.vscodePath}:{},...e.vscodeSource?{vscodeSource:e.vscodeSource}:{}}},R=e=>{let t=e.errors[0]??e.cleanupErrors[0];return t?.phase===`metadata`||t?.phase===`blob`&&[`blob-id-conflict`,`database-unavailable`,`invalid-value`,`missing-blob`,`quota-exceeded`,`transaction-aborted`,`transaction-failed`].includes(t.error.code)?t.error.code:`unavailable`},z=(e,t)=>{let r=o(),i=D,a=t??P(),s=[...new Set(e)];if(s.forEach(e=>w.delete(e)),T&&w.size===0&&(clearTimeout(T),T=void 0,E=void 0),!r.persistenceEnabled)return s.forEach(e=>A.add(e)),Promise.resolve({status:`disabled`,keys:s,errors:[],cleanupErrors:[]});let c=new Map(s.map(e=>[e,v.get(e)??0])),l=new Map(s.map(e=>[e,r.drafts[e]?.revision??r.tombstones[e]??0])),u=s.filter(e=>r.drafts[e]),d=Object.fromEntries(u.map(e=>[e,r.draftPersistence[e]?.status===`error`?r.draftPersistence[e]:{status:`saving`,revision:l.get(e)}])),f=Object.fromEntries(u.map(e=>[e,r.draftAttachmentPersistence[e]?.status===`error`?r.draftAttachmentPersistence[e]:{status:`saving`,revision:l.get(e)}]));n(e=>({draftPersistence:{...e.draftPersistence,...d},draftAttachmentPersistence:{...e.draftAttachmentPersistence,...f}})),te||s.forEach(e=>A.add(e));let p=(async()=>{let e=o(),t=await _.commit({drafts:Object.fromEntries(s.flatMap(t=>e.drafts[t]?[[t,e.drafts[t]]]:[])),tombstones:Object.fromEntries(s.flatMap(t=>e.tombstones[t]?[[t,e.tombstones[t]]]:[])),delete:s.filter(t=>!e.drafts[t]),migration:e.migration,legacy:{...e.legacyNewDraft?{new:e.legacyNewDraft}:{},entries:e.legacyDraftEntries},resolveBlobValue:t=>{for(let[n,r]of Object.entries(e.drafts))if(r.key.transportIdentity===t.transportIdentity&&r.key.owner.kind===t.owner.kind&&r.key.owner.ownerID===t.owner.ownerID)return e.draftAttachmentViews[n]?.[t.attachmentOccurrenceRefID]?.file},isCurrent:()=>D===i&&o().persistenceEnabled&&F(a)&&s.every(e=>(v.get(e)??0)===c.get(e)&&(o().drafts[e]?.revision??o().tombstones[e]??0)===l.get(e))}),r=D===i&&o().persistenceEnabled&&F(a);return(!r||t.status===`unseeded`||t.status===`stale`||t.status===`disabled`)&&s.forEach(e=>A.add(e)),r&&n(e=>{let n={...e.draftPersistence};for(let e of u){if((v.get(e)??0)!==c.get(e))continue;let r=l.get(e);if(t.status===`committed`)n[e]={status:`saved`,revision:r};else if(t.status===`unseeded`||t.status===`stale`||t.status===`disabled`)continue;else n[e]={status:`error`,revision:r,errorCode:R(t)}}let r={...e.draftAttachmentPersistence};for(let e of u){if((v.get(e)??0)!==c.get(e))continue;let n=l.get(e);r[e]=t.status===`committed`&&t.cleanupErrors.length===0?{status:`saved`,revision:n}:t.status===`failed`||t.cleanupErrors.length>0?{status:`error`,revision:n,errorCode:R(t)}:r[e]??{status:`idle`,revision:n}}return{draftPersistence:n,draftAttachmentPersistence:r}}),t})();return C.add(p),p.then(()=>C.delete(p),()=>C.delete(p)),p},oe=e=>{let t=o(),r=Object.fromEntries(e.flatMap(e=>{let n=t.drafts[e];return n?[[e,{status:`saving`,revision:n.revision}]]:[]}));Object.keys(r).length&&n(e=>({draftPersistence:{...e.draftPersistence,...r}}))},se=()=>{T&&clearTimeout(T),T=void 0;let e=[...w];w.clear();let t=E;return E=void 0,e.length?z(e,t).then(()=>void 0):Promise.resolve()},ce=e=>{if(!o().persistenceEnabled){A.add(e);return}w.add(e),oe([e]),!T&&(E=P(),T=setTimeout(()=>{se()},40))},le=e=>{let t=[...e];return t.forEach(e=>w.delete(e)),T&&w.size===0&&(clearTimeout(T),T=void 0,E=void 0),z(t)},B=(e,t,r,i=`immediate`)=>{let s=a(e),c=o().drafts[s];if(!c||r!==void 0&&c.revision!==r)return;let l=N(t(c));if(!(!l||a(l.key)!==s))return m(s),n(e=>({drafts:{...e.drafts,[s]:l},...ie(e,s,l)})),i===`deferred`?ce(s):le([s]),l},V=e=>e?l(e):void 0,H=(e=[])=>JSON.parse(JSON.stringify(e)),U=(e,t,n,r=!1,i=!1)=>({status:e,...V(n)?{record:V(n)}:{},errors:H(t?.errors),cleanupErrors:H(t?.cleanupErrors),current:r,durable:i}),W=(e,t,n,r,i=!1,a=!1)=>({status:e,errors:H(t?.errors),cleanupErrors:H(t?.cleanupErrors),current:i,durable:a,source:V(n),destination:V(r)}),G=e=>e.status,K=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0,q=(e,...t)=>{let n={...e};for(let e of t)delete n[e];return n},ue=async(e,t)=>{let n={},r=o().draftAttachmentViews[a(e.key)]??{};for(let i of I(e)){let e;if(i.locator.kind===`url`){let n=t?.get(i.attachmentRefID);e=n===void 0?i.locator.url:n}else e=t?.get(i.attachmentRefID)??r[i.attachmentRefID]?.file??(typeof r[i.attachmentRefID]?.dataUrl==`string`&&u(r[i.attachmentRefID].dataUrl)?r[i.attachmentRefID].dataUrl:void 0);if(i.locator.kind===`url`&&e!==void 0&&(e!==i.locator.url||!u(e))||i.locator.kind===`blob`&&e!==void 0&&!(e instanceof Blob)&&!(typeof e==`string`&&u(e)))return;e!==void 0&&(n[i.attachmentRefID]=await ae(i,e))}return n},J=e=>e?a(e):`legacy-unowned`,Y=e=>j.get(e)??0,de=e=>{j.set(e,Y(e)+1)},X=(e,t,r=!1)=>{r&&de(e),n(n=>{let r=t(n.attachmentBuckets[e]??[]);return{attachmentBuckets:{...n.attachmentBuckets,[e]:r},...J(n.activeAttachmentDraft)===e?{attachedFiles:r}:{}}})};return{drafts:{},tombstones:{},draftHydration:{},draftPersistence:{},draftAttachmentViews:{},draftMissingAttachmentRefIDs:{},draftAttachmentPersistence:{},persistenceEnabled:r.persistenceEnabled??!0,legacyDraftEntries:{},migration:{complete:!1,claimedTransportIdentity:``},captureDraftRuntime:()=>P(),commitDraftSnapshot:async e=>{let t=a(e.key),r=e.runtime;if(r.transportIdentity!==e.key.transportIdentity||!F(r))return U(`stale`,void 0);let i=o(),s=i.drafts[t],c=i.tombstones[t]??0;if(e.expectedRevision!==`absent`&&!K(e.expectedRevision)||!Number.isSafeInteger(c)||c<0)return U(`failed`,void 0);if(e.expectedRevision===`absent`?s:s?.revision!==e.expectedRevision)return U(`conflict`,void 0,s);let u=e.expectedRevision===`absent`?c+1:e.expectedRevision+1;if(!K(u))return U(`failed`,void 0);let d=N({version:1,key:e.key,revision:u,...e.snapshot});if(!d)return U(`failed`,void 0);let f=await ue(d,e.values);if(!f)return U(`failed`,void 0);let p=v.get(t)??0,h=s?.revision??c,g=await _.commit({drafts:{[t]:d},isCurrent:()=>F(r)&&(v.get(t)??0)===p&&(o().drafts[t]?.revision??o().tombstones[t]??0)===h,resolveBlobValue:t=>e.values?.get(t.attachmentOccurrenceRefID)});if(g.status!==`committed`)return U(G(g),g,s);let y=(v.get(t)??0)===p&&(o().drafts[t]?.revision??o().tombstones[t]??0)===h,b=F(r);if(!y)return b||n(e=>({draftAttachmentViews:q(e.draftAttachmentViews,t),draftMissingAttachmentRefIDs:q(e.draftMissingAttachmentRefIDs,t),draftHydration:q(e.draftHydration,t),draftPersistence:q(e.draftPersistence,t),draftAttachmentPersistence:q(e.draftAttachmentPersistence,t)})),U(`stale`,g,d,!1,!0);let x=l(d);return x?(m(t),O(t),n(e=>({drafts:{...e.drafts,[t]:x},tombstones:(()=>{let n={...e.tombstones};return delete n[t],n})(),draftAttachmentViews:b?{...e.draftAttachmentViews,[t]:f}:q(e.draftAttachmentViews,t),draftMissingAttachmentRefIDs:b?{...e.draftMissingAttachmentRefIDs,[t]:[]}:q(e.draftMissingAttachmentRefIDs,t),draftHydration:b?e.draftHydration:q(e.draftHydration,t),draftPersistence:b?{...e.draftPersistence,[t]:{status:`saved`,revision:x.revision}}:q(e.draftPersistence,t),draftAttachmentPersistence:b?{...e.draftAttachmentPersistence,[t]:g.cleanupErrors.length?{status:`error`,revision:x.revision,errorCode:R(g)}:{status:`saved`,revision:x.revision}}:q(e.draftAttachmentPersistence,t)})),U(b?`committed`:`stale`,g,x,b,!0)):U(`failed`,g)},deleteDraftSnapshot:async e=>{let t=a(e.key),r=e.runtime;if(r.transportIdentity!==e.key.transportIdentity||!F(r))return U(`stale`,void 0);let i=o(),s=i.drafts[t],c=i.tombstones[t]??0;if(!K(e.expectedRevision)||!Number.isSafeInteger(c)||c<0)return U(`failed`,void 0);if(!s||s.revision!==e.expectedRevision)return U(`conflict`,void 0);let l=e.expectedRevision+1;if(!K(l))return U(`failed`,void 0);let u=v.get(t)??0,d=s.revision,f=Math.max(c,l),p=await _.commit({tombstones:{[t]:f},delete:[t],isCurrent:()=>F(r)&&(v.get(t)??0)===u&&o().drafts[t]?.revision===d&&(o().tombstones[t]??0)===c});if(p.status!==`committed`)return U(G(p),p);let h=(v.get(t)??0)===u&&o().drafts[t]?.revision===d&&(o().tombstones[t]??0)===c,g=F(r);return h?(m(t),O(t),n(e=>{let n={...e.drafts};return delete n[t],{drafts:n,tombstones:{...e.tombstones,[t]:Math.max(e.tombstones[t]??0,f)},draftAttachmentViews:q(e.draftAttachmentViews,t),draftMissingAttachmentRefIDs:q(e.draftMissingAttachmentRefIDs,t),draftHydration:q(e.draftHydration,t),draftPersistence:q(e.draftPersistence,t),draftAttachmentPersistence:q(e.draftAttachmentPersistence,t)}}),U(g?`committed`:`stale`,p,void 0,g,!0)):(g||n(e=>({draftAttachmentViews:q(e.draftAttachmentViews,t),draftMissingAttachmentRefIDs:q(e.draftMissingAttachmentRefIDs,t),draftHydration:q(e.draftHydration,t),draftPersistence:q(e.draftPersistence,t),draftAttachmentPersistence:q(e.draftAttachmentPersistence,t)})),U(`stale`,p,void 0,!1,!0))},finalizeDraftOwnership:async e=>{let t=a(e.source),r=a(e.destination),i=e.runtime,s=o(),c=s.drafts[t],u=s.drafts[r];if(t===r||e.destination.owner.kind!==`session`||e.source.transportIdentity!==i.transportIdentity||e.destination.transportIdentity!==i.transportIdentity||!F(i))return W(`stale`,void 0,c,u);if(!K(e.expectedSourceRevision))return W(`failed`,void 0,c,u);if(!c||c.revision!==e.expectedSourceRevision||u)return W(`conflict`,void 0,c,u);let d=v.get(t)??0,f=v.get(r)??0,p=s.tombstones[t]??0,h=s.tombstones[r]??0;if(!Number.isSafeInteger(p)||p<0||!Number.isSafeInteger(h)||h<0)return W(`failed`,void 0,c,u);let g=Math.max(c.revision+1,h+1);if(!K(g))return W(`failed`,void 0,c,u);let y=N(e.disposition===`preserve`?{...c,key:e.destination,revision:g}:{...He(e.destination),revision:g});if(!y)return W(`failed`,void 0,c,u);let b=await _.commit({drafts:{[r]:y},tombstones:{[t]:Math.max(p,g)},delete:[t],isCurrent:()=>F(i)&&(v.get(t)??0)===d&&(v.get(r)??0)===f&&o().drafts[t]?.revision===c.revision&&!o().drafts[r]&&(o().tombstones[t]??0)===p&&(o().tombstones[r]??0)===h,resolveBlobValue:e=>s.draftAttachmentViews[t]?.[e.attachmentOccurrenceRefID]?.file});if(b.status!==`committed`)return W(G(b),b,c,u);let x=(v.get(t)??0)===d&&o().drafts[t]?.revision===c.revision&&(o().tombstones[t]??0)===p,S=(v.get(r)??0)===f&&!o().drafts[r]&&(o().tombstones[r]??0)===h,C=F(i),w=l(y);if(!w)return W(`failed`,b,c,u);if(C&&!x&&!S)return W(`stale`,b,c,y,!1,!0);x&&(m(t),O(t)),S&&(m(r),O(r)),n(n=>{let i=n.drafts,a=n.tombstones;(x||S)&&(i={...i}),(x||S)&&(a={...a}),x&&(delete i[t],a[t]=Math.max(a[t]??0,g)),S&&(i[r]=w,delete a[r]);let o=n.draftHydration,s=n.draftPersistence,c=n.draftAttachmentViews,l=n.draftMissingAttachmentRefIDs,u=n.draftAttachmentPersistence;return C?(x&&(o=q(o,t),s=q(s,t),c=q(c,t),l=q(l,t),u=q(u,t)),S&&(o=q(o,r),s={...q(s,r),[r]:{status:`saved`,revision:w.revision}},c=q(c,r),l=q(l,r),u={...q(u,r),[r]:b.cleanupErrors.length?{status:`error`,revision:w.revision,errorCode:R(b)}:{status:`saved`,revision:w.revision}},C&&x&&e.disposition===`preserve`&&(c={...c,[r]:n.draftAttachmentViews[t]??{}},l={...l,[r]:n.draftMissingAttachmentRefIDs[t]??[]}))):(o=q(o,t,r),s=q(s,t,r),c=q(c,t,r),l=q(l,t,r),u=q(u,t,r)),{drafts:i,tombstones:a,draftHydration:o,draftPersistence:s,draftAttachmentViews:c,draftMissingAttachmentRefIDs:l,draftAttachmentPersistence:u}});let T=x&&S&&C;return W(T?`committed`:`stale`,b,c,y,T,!0)},flushDraftPersistence:async()=>{for(await se();C.size;)await Promise.all([...C]);await _.flush()},ensureDraft:e=>{let t=a(e),r=o().drafts[t];if(r)return r;let i=N({...He(e),revision:(o().tombstones[t]??0)+1});if(!i)throw Error(`Invalid empty draft`);return m(t),n(e=>({drafts:{...e.drafts,[t]:i}})),le([t]),i},getDraft:e=>o().drafts[a(e)],setDraftText:(e,t)=>{let n=o().getDraft(e)??o().ensureDraft(e);return B(e,e=>({...e,revision:e.revision+1,text:t,mentions:e.mentions.filter(e=>e.range.end<=t.length&&t.slice(e.range.start,e.range.end)===`@${e.value}`),composerReferences:[]}),n.revision,`deferred`)??n},setDraftComposerDocument:(e,t)=>{let n=o().getDraft(e)??o().ensureDraft(e);return o().setDraftComposerState(e,{document:t,mentions:n.mentions})},setDraftComposerState:(e,t)=>{let n=o().getDraft(e)??o().ensureDraft(e);return B(e,e=>({...e,revision:e.revision+1,text:t.document.text,composerReferences:t.document.references,mentions:t.mentions}),n.revision,`deferred`)},replaceDraft:(e,t,n)=>B(e,e=>({version:1,key:e.key,revision:e.revision+1,text:n.text,attachments:n.attachments,syntheticParts:n.syntheticParts,mentions:n.mentions,...n.composerReferences===void 0?{}:{composerReferences:n.composerReferences}}),t),setDraftMentions:(e,t)=>B(e,e=>({...e,revision:e.revision+1,mentions:t})),addDraftMention:(e,t)=>B(e,e=>({...e,revision:e.revision+1,mentions:[...e.mentions,t]})),removeDraftMention:(e,t)=>B(e,e=>({...e,revision:e.revision+1,mentions:e.mentions.filter(e=>e.value!==t)})),setDraftSyntheticParts:(e,t)=>B(e,e=>({...e,revision:e.revision+1,syntheticParts:t})),consumeDraftSyntheticParts:(e,t)=>{let n=o().getDraft(e);if(!n)return null;let r=n.syntheticParts.filter(e=>!t?.(e)),i=n.syntheticParts.filter(e=>t?.(e));return B(e,e=>({...e,revision:e.revision+1,syntheticParts:i}),n.revision)?r:null},setDraftAttachments:(e,t)=>B(e,e=>({...e,revision:e.revision+1,attachments:t})),addDraftLocalAttachment:async(e,t,r={})=>{let c=o().getDraft(e);if(r.partID&&!c?.syntheticParts.some(e=>e.partID===r.partID))return;let l=a(e),u=v.get(l)??0,d=o().tombstones[l]??0,f=P(),p=t instanceof File?t:new File([t],r.filename??`attachment`,{type:t.type}),h;try{h=await ze(p)}catch{let e=o().drafts[l];if(F(f)&&(o().tombstones[l]??0)===d&&(e?a(e.key)===l:(v.get(l)??0)===u)&&(!r.partID||e?.syntheticParts.some(e=>e.partID===r.partID))){let t=e?.revision??o().tombstones[l]??0;n(e=>({draftAttachmentPersistence:{...e.draftAttachmentPersistence,[l]:{status:`error`,revision:t,errorCode:`transaction-failed`}}}))}return}if(!F(f)||(o().tombstones[l]??0)!==d)return;let g=o().drafts[l];if(!g&&(v.get(l)??0)!==u)return;let _=g??o().ensureDraft(e);if(a(_.key)!==l||r.partID&&!_.syntheticParts.some(e=>e.partID===r.partID))return;let y=r.attachmentID??L(),b=r.partID?s(r.partID,y):i(y),x=L(),S={attachmentID:y,attachmentRefID:b,filename:r.filename??(t instanceof File?t.name:`attachment`),mimeType:t.type,size:t.size,locator:{kind:`blob`,blobID:x},source:r.source??`local`,...r.vscodePath?{vscodePath:r.vscodePath}:{},...r.vscodeSource?{vscodeSource:r.vscodeSource}:{}},C=r.partID?{..._,revision:_.revision+1,syntheticParts:_.syntheticParts.map(e=>e.partID===r.partID?{...e,attachments:[...e.attachments,S]}:e)}:{..._,revision:_.revision+1,attachments:[..._.attachments,S]},w=N(C);if(!w)return;m(l);let T={id:y,file:p,dataUrl:h,mimeType:S.mimeType,filename:S.filename,size:S.size,source:S.source,...r.vscodePath?{vscodePath:r.vscodePath}:{},...r.vscodeSource?{vscodeSource:r.vscodeSource}:{}};return n(e=>({drafts:{...e.drafts,[l]:w},draftAttachmentViews:{...e.draftAttachmentViews,[l]:{...e.draftAttachmentViews[l],[b]:T}}})),await z([l]),S},addDraftDurableAttachment:(e,t)=>{let r=o().getDraft(e)??o().ensureDraft(e);if(t.partID&&!r.syntheticParts.some(e=>e.partID===t.partID))return;let c=t.attachmentID??L(),l=t.partID?s(t.partID,c):i(c),u={attachmentID:c,attachmentRefID:l,filename:t.filename,mimeType:t.mimeType,size:t.size,source:t.source,locator:{kind:`url`,url:t.url},...t.serverPath?{serverPath:t.serverPath}:{},...t.vscodePath?{vscodePath:t.vscodePath}:{},...t.vscodeSource?{vscodeSource:t.vscodeSource}:{}},d=t.partID?{...r,revision:r.revision+1,syntheticParts:r.syntheticParts.map(e=>e.partID===t.partID?{...e,attachments:[...e.attachments,u]}:e)}:{...r,revision:r.revision+1,attachments:[...r.attachments,u]},f=N(d);if(!f)return;let p=a(e);m(p);let h={id:c,file:new File([],u.filename,{type:u.mimeType}),dataUrl:t.url,mimeType:u.mimeType,filename:u.filename,size:u.size,source:u.source,...u.serverPath?{serverPath:u.serverPath}:{},...u.vscodePath?{vscodePath:u.vscodePath}:{},...u.vscodeSource?{vscodeSource:u.vscodeSource}:{}};return n(e=>({drafts:{...e.drafts,[p]:f},draftAttachmentViews:{...e.draftAttachmentViews,[p]:{...e.draftAttachmentViews[p],[l]:h}}})),z([p]),u},getDraftAttachmentViews:e=>{let t=a(e),n=o().drafts[t],r=o().draftAttachmentViews[t]??{};return n?I(n).flatMap(e=>r[e.attachmentRefID]?[r[e.attachmentRefID]]:[]):[]},retryDraftAttachmentPersistence:async e=>{let t=a(e);if(!o().persistenceEnabled||!o().drafts[t]&&!o().tombstones[t])return;let r=await _.retryCleanup();r.cleanupErrors.length&&n(e=>({draftAttachmentPersistence:{...e.draftAttachmentPersistence,[t]:{status:`error`,revision:e.drafts[t]?.revision??e.tombstones[t],errorCode:R(r)}}})),await z([t])},hydrateDraftAttachments:async e=>{let t=a(e),r=x.get(t);if(r)return r;let i=o().drafts[t];if(!i)return;let s=(b.get(t)??0)+1;b.set(t,s);let c=P(),l=D,u=(async()=>{n(e=>({draftHydration:{...e.draftHydration,[t]:`loading`}}));let e=()=>{if(b.get(t)!==s)return;let e=o(),r=e.draftAttachmentViews[t],i=e.draftMissingAttachmentRefIDs[t]??[];n(e=>({draftHydration:{...e.draftHydration,[t]:i.length?`degraded`:Object.keys(r??{}).length?`ready`:`idle`}}))},r={},a=[];for(let u of I(i)){let d=u.locator.kind===`url`?{ok:!0,value:u.locator.url}:await g.read(u.locator.blobID);if(!d.ok){if(d.error.code===`missing-blob`)a.push(u.attachmentRefID);else{b.get(t)===s&&D===l&&F(c)&&o().drafts[t]===i?n(e=>({draftHydration:{...e.draftHydration,[t]:`error`}})):e();return}continue}try{r[u.attachmentRefID]=await ae(u,d.value)}catch{b.get(t)===s&&D===l&&F(c)&&o().drafts[t]===i?n(e=>({draftHydration:{...e.draftHydration,[t]:`error`}})):e();return}}let u=o(),d=u.drafts[t],f=b.get(t);if(f===s&&D===l&&F(c)&&d===i)n(e=>({draftAttachmentViews:{...e.draftAttachmentViews,[t]:r},draftMissingAttachmentRefIDs:{...e.draftMissingAttachmentRefIDs,[t]:a},draftHydration:{...e.draftHydration,[t]:a.length?`degraded`:`ready`}}));else if(f===s){let e=u.draftAttachmentViews[t],r=u.draftMissingAttachmentRefIDs[t]??[];n(n=>({draftHydration:{...n.draftHydration,[t]:r.length?`degraded`:Object.keys(e??{}).length?`ready`:`idle`}}))}})();x.set(t,u);try{await u}finally{x.get(t)===u&&x.delete(t)}},removeDraftAttachment:async(e,t)=>{let r=a(e),i=o().drafts[r],s=i&&I(i).find(e=>e.attachmentRefID===t);if(!i||!s)return!1;let c=d(s)?f(i.text,[s.filename],i.mentions,i.composerReferences):void 0,l=N({...i,revision:i.revision+1,...c?.changed?{text:c.text,mentions:c.mentions,...c.composerReferences===void 0?{}:{composerReferences:c.composerReferences}}:{},attachments:i.attachments.filter(e=>e.attachmentRefID!==t),syntheticParts:i.syntheticParts.map(e=>({...e,attachments:e.attachments.filter(e=>e.attachmentRefID!==t)}))});return l?(m(r),n(e=>{let n={...e.draftAttachmentViews[r]};return delete n[t],{drafts:{...e.drafts,[r]:l},draftAttachmentViews:{...e.draftAttachmentViews,[r]:n},draftMissingAttachmentRefIDs:{...e.draftMissingAttachmentRefIDs,[r]:(e.draftMissingAttachmentRefIDs[r]??[]).filter(e=>e!==t)}}}),(await z([r])).status===`committed`):!1},replaceDraftAttachment:async(e,t,r,c)=>{let l=a(e),u=o().drafts[l],d=u&&I(u).find(e=>e.attachmentRefID===t);if(!u||!d)return;let f=P(),p=o().tombstones[l]??0,h=r instanceof File?r:new File([r],c?.filename??`attachment`,{type:r.type}),g;try{g=await ze(h)}catch{let e=o().drafts[l],r=e&&I(e).find(e=>e.attachmentRefID===t);F(f)&&(o().tombstones[l]??0)===p&&e&&r?.attachmentID===d.attachmentID&&r.attachmentRefID===d.attachmentRefID&&a(e.key)===l&&n(t=>({draftAttachmentPersistence:{...t.draftAttachmentPersistence,[l]:{status:`error`,revision:e.revision,errorCode:`transaction-failed`}}}));return}let _=o().drafts[l],v=_&&I(_).find(e=>e.attachmentRefID===t);if(!F(f)||(o().tombstones[l]??0)!==p||!_||v?.attachmentID!==d.attachmentID||v.attachmentRefID!==d.attachmentRefID||a(_.key)!==l)return;let y=_.syntheticParts.find(e=>e.attachments.some(e=>e.attachmentRefID===t)),b=L(),x={attachmentID:b,attachmentRefID:y?s(y.partID,b):i(b),filename:c?.filename??h.name,mimeType:h.type,size:h.size,locator:{kind:`blob`,blobID:L()},source:c?.source??`local`,...c?.vscodePath?{vscodePath:c.vscodePath}:{},...c?.vscodeSource?{vscodeSource:c.vscodeSource}:{}},S=N({..._,revision:_.revision+1,attachments:y?_.attachments:_.attachments.map(e=>e.attachmentRefID===t?x:e),syntheticParts:_.syntheticParts.map(e=>e.partID===y?.partID?{...e,attachments:e.attachments.map(e=>e.attachmentRefID===t?x:e)}:e)});if(!S)return;m(l);let C={id:b,file:h,dataUrl:g,mimeType:x.mimeType,filename:x.filename,size:x.size,source:x.source,...x.vscodePath?{vscodePath:x.vscodePath}:{},...x.vscodeSource?{vscodeSource:x.vscodeSource}:{}};return n(e=>{let n={...e.draftAttachmentViews[l]};return delete n[t],{drafts:{...e.drafts,[l]:S},draftAttachmentViews:{...e.draftAttachmentViews,[l]:{...n,[x.attachmentRefID]:C}},draftMissingAttachmentRefIDs:{...e.draftMissingAttachmentRefIDs,[l]:(e.draftMissingAttachmentRefIDs[l]??[]).filter(e=>e!==t)}}}),(await z([l])).status===`committed`?x:void 0},replaceDraftRootAttachments:async(e,t)=>{let n=a(e),r=P();if(r.transportIdentity!==e.transportIdentity||!F(r))return U(`stale`,void 0);let s=o().drafts[n],c=s?s.revision:`absent`,l=[],d=new Map;for(let e of t){let t=e.id,n=i(t);if(e.source===`server`&&e.dataUrl&&u(e.dataUrl))l.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:`server`,locator:{kind:`url`,url:e.dataUrl},...e.serverPath?{serverPath:e.serverPath}:{}}),d.set(n,e.dataUrl);else if(e.source===`vscode`&&e.vscodeSource===`file`&&e.dataUrl&&u(e.dataUrl))l.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:`vscode`,locator:{kind:`url`,url:e.dataUrl},...e.vscodePath?{vscodePath:e.vscodePath}:{},vscodeSource:`file`}),d.set(n,e.dataUrl);else{let r=e.file instanceof File?e.file:new File([e.file],e.filename,{type:e.mimeType}),i=L();l.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:e.source===`vscode`?`vscode`:`local`,locator:{kind:`blob`,blobID:i},...e.vscodePath?{vscodePath:e.vscodePath}:{},...e.vscodeSource===`selection`?{vscodeSource:`selection`}:{}}),d.set(n,r)}}let f=s?.syntheticParts??[];for(let e of f)for(let t of e.attachments)t.locator.kind===`url`&&!d.has(t.attachmentRefID)&&d.set(t.attachmentRefID,t.locator.url);let p={text:s?.text??``,attachments:l,syntheticParts:f,mentions:s?.mentions??[],...s?.composerReferences===void 0?{}:{composerReferences:s.composerReferences}};return o().commitDraftSnapshot({key:e,expectedRevision:c,snapshot:p,values:d,runtime:r})},restoreDraftRootAttachments:async(e,t)=>{let n=a(e),r=P();if(r.transportIdentity!==e.transportIdentity||!F(r))return U(`stale`,void 0);let s=o().drafts[n],c=s?s.revision:`absent`,l=new Set(t.map(e=>e.id)),d=[],f=new Map;for(let e of t){let t=e.id,n=i(t);if(e.source===`server`&&e.dataUrl&&u(e.dataUrl))d.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:`server`,locator:{kind:`url`,url:e.dataUrl},...e.serverPath?{serverPath:e.serverPath}:{}}),f.set(n,e.dataUrl);else if(e.source===`vscode`&&e.vscodeSource===`file`&&e.dataUrl&&u(e.dataUrl))d.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:`vscode`,locator:{kind:`url`,url:e.dataUrl},...e.vscodePath?{vscodePath:e.vscodePath}:{},vscodeSource:`file`}),f.set(n,e.dataUrl);else{let r=e.file instanceof File?e.file:new File([e.file],e.filename,{type:e.mimeType}),i=L();d.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:e.source===`vscode`?`vscode`:`local`,locator:{kind:`blob`,blobID:i},...e.vscodePath?{vscodePath:e.vscodePath}:{},...e.vscodeSource===`selection`?{vscodeSource:`selection`}:{}}),f.set(n,r)}}let p=o().draftAttachmentViews[n]??{};for(let e of s?.attachments??[])if(!l.has(e.attachmentID))if(d.push(JSON.parse(JSON.stringify(e))),e.locator.kind===`url`)f.set(e.attachmentRefID,e.locator.url);else{let t=p[e.attachmentRefID];t?.file instanceof Blob?f.set(e.attachmentRefID,t.file):typeof t?.dataUrl==`string`&&u(t.dataUrl)&&f.set(e.attachmentRefID,t.dataUrl)}let m=s?.syntheticParts??[];for(let e of m)for(let t of e.attachments)t.locator.kind===`url`&&!f.has(t.attachmentRefID)&&f.set(t.attachmentRefID,t.locator.url);let h={text:s?.text??``,attachments:d,syntheticParts:m,mentions:s?.mentions??[],...s?.composerReferences===void 0?{}:{composerReferences:s.composerReferences}};return o().commitDraftSnapshot({key:e,expectedRevision:c,snapshot:h,values:f,runtime:r})},deleteDraft:(e,t)=>{let r=a(e),i=o().drafts[r];if(!i||t!==void 0&&i.revision!==t)return!1;let s=i.revision+1;return K(s)?(m(r),O(r),n(e=>{let t={...e.drafts};delete t[r];let n={...e.draftHydration},i={...e.draftPersistence},a={...e.draftAttachmentViews},o={...e.draftMissingAttachmentRefIDs},c={...e.draftAttachmentPersistence};return delete n[r],delete i[r],delete a[r],delete o[r],delete c[r],{drafts:t,tombstones:{...e.tombstones,[r]:Math.max(e.tombstones[r]??0,s)},draftHydration:n,draftPersistence:i,draftAttachmentViews:a,draftMissingAttachmentRefIDs:o,draftAttachmentPersistence:c}}),z([r]),!0):!1},moveDraft:(e,t,r)=>{let i=a(e),s=a(t),c=o().drafts[i];if(!c||i===s||r!==void 0&&c.revision!==r||o().drafts[s]||(o().tombstones[s]??0)>=c.revision+1||[...c.attachments,...c.syntheticParts.flatMap(e=>e.attachments)].some(e=>e.locator.kind===`blob`))return;let l=N({...c,key:t,revision:c.revision+1});if(l)return m(i),m(s),O(i,s),n(e=>{let t={...e.drafts};delete t[i];let n={...e.tombstones,[i]:Math.max(e.tombstones[i]??0,l.revision)};(n[s]??0)<l.revision&&delete n[s];let r=e=>{let t={...e},n=t[i];return delete t[i],delete t[s],n===void 0?t:{...t,[s]:n}};return{drafts:{...t,[s]:l},tombstones:n,draftHydration:r(e.draftHydration),draftPersistence:r(e.draftPersistence),draftAttachmentViews:r(e.draftAttachmentViews),draftMissingAttachmentRefIDs:r(e.draftMissingAttachmentRefIDs),draftAttachmentPersistence:r(e.draftAttachmentPersistence)}}),z([i,s]),l},moveDraftWithAttachments:async(e,t,r)=>{let i=a(e),s=a(t),c=o().drafts[i];if(!c||i===s||r!==void 0&&c.revision!==r||o().drafts[s]||(o().tombstones[s]??0)>=c.revision+1)return;let l=N({...c,key:t,revision:c.revision+1});if(l)return m(i),m(s),O(i,s),n(e=>{let t={...e.drafts};delete t[i];let n={...e.tombstones,[i]:Math.max(e.tombstones[i]??0,l.revision)};(n[s]??0)<l.revision&&delete n[s];let r=e=>{let t={...e},n=t[i];return delete t[i],delete t[s],n===void 0?t:{...t,[s]:n}};return{drafts:{...t,[s]:l},tombstones:n,draftHydration:r(e.draftHydration),draftPersistence:r(e.draftPersistence),draftAttachmentViews:r(e.draftAttachmentViews),draftMissingAttachmentRefIDs:r(e.draftMissingAttachmentRefIDs),draftAttachmentPersistence:r(e.draftAttachmentPersistence)}}),(await z([i,s])).status===`committed`?l:void 0},setDraftPersistenceEnabled:async e=>{if(D+=1,!e){T&&clearTimeout(T),T=void 0,w.clear(),E=void 0,n({persistenceEnabled:!1,draftPersistence:{}}),await _.setEnabled(!1),await _.flush();return}n({persistenceEnabled:!0}),await _.setEnabled(!0);let t=P();te||await o().hydrateDraftMetadata(t.transportIdentity);let r=new Set([...Object.keys(o().drafts),...Object.keys(o().tombstones),...A]);A.clear(),await z(r),await _.flush()},hydrateDraftMetadata:e=>{let t=S.get(e);if(t)return t;let r=(async()=>{let t=(y.get(e)??0)+1;y.set(e,t);let r=P();if(r.transportIdentity!==e)return!1;let i=D,s=new Map(v),c=k,l=Object.entries(o().drafts).filter(([,t])=>t.key.transportIdentity===e).map(([e])=>e);n(e=>({draftHydration:{...e.draftHydration,...Object.fromEntries(l.map(e=>[e,`loading`]))}}));let u=o().persistenceEnabled,d;try{d=await p.migrate(e,{persistenceEnabled:u})}catch{return!1}if(y.get(e)!==t||D!==i||!F(r))return!1;if(!d.ok)return n(e=>({draftHydration:{...e.draftHydration,...Object.fromEntries(l.map(t=>[t,e.drafts[t]?`degraded`:`error`]))}})),!1;let f=d.value;if(!te){ne??=_.seed(f).finally(()=>{ne=void 0});let a;try{a=await ne}catch{return!1}if(y.get(e)!==t||D!==i||!F(r))return!1;if(a.status!==`committed`&&a.status!==`disabled`)return n(e=>({draftHydration:{...e.draftHydration,...Object.fromEntries(l.map(e=>[e,`degraded`]))}})),!1;a.status===`committed`&&(te=!0)}let m=o(),h={...m.drafts},g={...m.tombstones},b=new Set;for(let[e,t]of Object.entries(f.tombstones))(v.get(e)??0)===(s.get(e)??0)&&(t>=(g[e]??0)&&(g[e]=t,(h[e]?.revision??0)<=t&&delete h[e]),b.add(e));for(let[t,n]of Object.entries(f.drafts)){if(n.key.transportIdentity!==e||(v.get(t)??0)!==(s.get(t)??0))continue;let r=h[t],i=N(n);i&&(!r||r.revision<i.revision)&&(g[t]??0)<i.revision&&(h[t]=i),b.add(t)}let x=k===c?{...f.legacy.entries}:{...m.legacyDraftEntries};if(f.migration.claimedTransportIdentity===e&&k===c)for(let[t,n]of Object.entries(x)){let r={transportIdentity:e,owner:{kind:`session`,ownerID:t}},i=a(r),o=Pe(n.text),c=N({...He(r),text:o.text,composerReferences:o.references,mentions:Ue(o.text,n.mentions)});c&&!h[i]&&!g[i]&&(v.get(i)??0)===(s.get(i)??0)&&(h[i]=c),delete x[t],b.add(i)}n(e=>({drafts:h,tombstones:g,legacyNewDraft:k===c&&!ee?f.legacy.new:e.legacyNewDraft,legacyDraftEntries:x,migration:k===c?f.migration:e.migration,draftHydration:{...e.draftHydration,...Object.fromEntries([...b].map(e=>[e,`ready`]))}}));let S=[...A];for(let e of S)b.add(e);A.clear();try{await z(b),await _.flush()}catch{return!1}return y.get(e)===t&&D===i&&F(r)})();return S.set(e,r),r.finally(()=>{S.get(e)===r&&S.delete(e)}).catch(()=>void 0),r},claimLegacyNewDraft:async e=>{let t=o().legacyNewDraft;if(!t)return o().getDraft(e);let r=a(e),i=o().drafts[r];if(k+=1,ee=!0,i||o().tombstones[r])return n({legacyNewDraft:void 0}),z([r]),i;let s=Pe(t.text),c=N({...He(e),text:s.text,composerReferences:s.references,mentions:Ue(s.text,t.mentions)});if(c)return m(r),n(e=>({drafts:{...e.drafts,[r]:c},legacyNewDraft:void 0})),z([r]),c},pendingInputText:null,pendingInputMode:`replace`,pendingSyntheticParts:null,pendingPresetSubmit:null,attachedFiles:[],attachmentBuckets:{"legacy-unowned":[]},activeAttachmentDraft:null,activeEditorFile:null,setPendingInputText:(e,t=`replace`)=>n({pendingInputText:e,pendingInputMode:t}),consumePendingInputText:()=>{let{pendingInputText:e,pendingInputMode:t}=o();return e===null?null:(n({pendingInputText:null,pendingInputMode:`replace`}),{text:e,mode:t})},requestPresetSubmit:e=>n({pendingPresetSubmit:e}),consumePendingPresetSubmit:()=>{let{pendingPresetSubmit:e}=o();return e===null?null:(n({pendingPresetSubmit:null}),e)},setPendingSyntheticParts:e=>n({pendingSyntheticParts:e}),consumePendingSyntheticParts:()=>{let{pendingSyntheticParts:e}=o();return e!==null&&n({pendingSyntheticParts:null}),e},setActiveAttachmentDraft:e=>{let t=J(e);n(n=>({activeAttachmentDraft:e,attachedFiles:n.attachmentBuckets[t]??[],attachmentBuckets:n.attachmentBuckets[t]?n.attachmentBuckets:{...n.attachmentBuckets,[t]:[]}}))},addAttachedFile:async e=>{let t=o().activeAttachmentDraft;if(t){let n=J(t),r=Y(n),i=await o().addDraftLocalAttachment(t,e);r!==Y(n)&&i&&o().removeDraftAttachment(t,i.attachmentRefID);return}let n=`${Date.now()}-${Math.random().toString(36).slice(2)}`,r=J(null),i=Y(r),a;try{a=await ze(e)}catch{return}if(i!==Y(r))return;let s={id:n,file:e,dataUrl:a,mimeType:e.type,filename:e.name,size:e.size,source:`local`};X(r,e=>[...e,s])},removeAttachedFile:e=>{let t=o().activeAttachmentDraft;if(t){let n=o().getDraft(t),r=n?[...n.attachments,...n.syntheticParts.flatMap(e=>e.attachments)].find(t=>t.attachmentID===e):void 0;r&&o().removeDraftAttachment(t,r.attachmentRefID);return}X(J(null),t=>t.filter(t=>t.id!==e))},setAttachedFiles:e=>{X(J(o().activeAttachmentDraft),()=>e,!0)},clearAttachedFiles:()=>{let e=o().activeAttachmentDraft;if(e){de(J(e)),o().getDraft(e)||o().ensureDraft(e),o().setDraftAttachments(e,[]);return}X(J(null),()=>[],!0)},addDraftVSCodeFileAttachment:(e,t,n,r)=>{if(o().getDraftAttachmentViews(e).some(e=>e.source===`vscode`&&e.vscodeSource===`file`&&(e.vscodePath||``)===t)||(o().getDraft(e)?.attachments.some(e=>e.source===`vscode`&&e.vscodeSource===`file`&&(e.vscodePath||``)===t)??!1))return;let i=Le(t);o().addDraftDurableAttachment(e,{filename:n,mimeType:`text/plain`,size:r||0,source:`vscode`,vscodePath:t,vscodeSource:`file`,url:i})},addDraftVSCodeSelectionAttachment:async(e,t,n)=>{let r=a(e),i=Y(r),s=`${r}\u0000${Re(t,n.name)}`;if(!(o().getDraftAttachmentViews(e).some(e=>e.source===`vscode`&&e.vscodeSource===`selection`&&e.filename===n.name&&e.vscodePath===t)||(o().getDraft(e)?.attachments.some(e=>e.source===`vscode`&&e.vscodeSource===`selection`&&e.filename===n.name&&e.vscodePath===t)??!1)||M.has(s))){M.add(s);try{let a=await o().addDraftLocalAttachment(e,n,{source:`vscode`,vscodePath:t,vscodeSource:`selection`});i!==Y(r)&&a&&o().removeDraftAttachment(e,a.attachmentRefID)}finally{M.delete(s)}}},addVSCodeFileAttachment:(e,t,n)=>{let r=o().activeAttachmentDraft;if(r){o().addDraftVSCodeFileAttachment(r,e,t,n);return}let i=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=J(null);if((o().attachmentBuckets[a]??[]).some(t=>t.source===`vscode`&&t.vscodeSource===`file`&&(t.vscodePath||``)===e))return;let s=Le(e),c={id:i,file:new File([],t,{type:`text/plain`}),dataUrl:s,mimeType:`text/plain`,filename:t,size:n||0,source:`vscode`,vscodePath:e,vscodeSource:`file`};X(a,e=>[...e,c])},addVSCodeSelectionAttachment:async(e,t)=>{let n=o().activeAttachmentDraft;if(n){await o().addDraftVSCodeSelectionAttachment(n,e,t);return}let r=`${Date.now()}-${Math.random().toString(36).slice(2)}`,i=J(null),a=Y(i),s=`${i}\u0000${Re(e,t.name)}`;if((o().attachmentBuckets[i]??[]).some(n=>n.source===`vscode`&&n.vscodeSource===`selection`&&n.filename===t.name&&n.vscodePath===e)||M.has(s))return;M.add(s);let c;try{c=await ze(t)}catch{return}finally{M.delete(s)}if(a!==Y(i))return;let l={id:r,file:t,dataUrl:c,mimeType:t.type,filename:t.name,size:t.size,source:`vscode`,vscodePath:e,vscodeSource:`selection`};X(i,e=>[...e,l])},addCodeSelectionAttachment:async(e,t,n)=>{let r=new File([n],t,{type:`text/plain`});await o().addVSCodeSelectionAttachment(e,r)},setActiveEditorFile:e=>{Ve(o().activeEditorFile,e)||n({activeEditorFile:e})},addRestoredAttachment:({url:e,mimeType:t,filename:n})=>{let r=o().activeAttachmentDraft;if(r){if(e.startsWith(`data:`)){let i=a(r);(async()=>{try{let s=await(await fetch(e)).blob(),c=new File([s],n,{type:t||s.type||`application/octet-stream`}),l=o().activeAttachmentDraft;if(!l||a(l)!==i)return;await o().addDraftLocalAttachment(r,c)}catch{}})();return}if(!u(e))return;o().addDraftDurableAttachment(r,{filename:n,mimeType:t,size:Be(e),source:`local`,serverPath:e,url:e});return}let i={id:`restored-${Date.now()}-${Math.random().toString(36).slice(2)}`,file:new File([],n,{type:t}),dataUrl:e,mimeType:t,filename:n,size:Be(e),source:`local`,serverPath:e};X(J(null),e=>[...e,i])}}})},Ge=We();export{O as a,Y as i,Ge as n,de as r,We as t};
1
+ import{i as e,n as t}from"./runtime-switch-DEPKHgdL.js";import{a as n}from"./vendor-zustand-CTekDqaS.js";import{t as r}from"./brand-storage-migration-Bhz6UOBJ.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{D as i,E as a,F as o,O as s,R as c,S as l,k as u,o as d,s as f,w as p,x as m}from"./prompt-attachment-upload-BzYqZdzd.js";import{t as h}from"./uuid-D-SDZijH.js";var g=`yuri_input_draft_metadata_v1`,_=`yuri_input_draft_metadata_migration_v1`,v=`yuri_chat_input_draft_`,y=`yuri_chat_confirmed_mentions_`,b=()=>({ok:!1,error:{code:`unavailable`}}),x=()=>({ok:!1,error:{code:`cancelled`}}),S=e=>({ok:!1,error:{code:e instanceof DOMException&&e.name===`QuotaExceededError`?`quota`:`unavailable`}}),C=e=>typeof e==`object`&&!!e&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),w=(e,t)=>Object.keys(e).every(e=>t.includes(e)),T=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0,E=e=>typeof e==`string`&&e.length>0,D=e=>({read:async t=>{if(!e)return b();try{return{ok:!0,value:e.getItem(t)}}catch(e){return S(e)}},write:async(t,n)=>{if(!e)return b();try{return e.setItem(t,n),{ok:!0,value:void 0}}catch(e){return S(e)}},remove:async t=>{if(!e)return b();try{return e.removeItem(t),{ok:!0,value:void 0}}catch(e){return S(e)}},keys:async()=>{if(!e)return b();try{let t=[];for(let n=0;n<e.length;n+=1){let r=e.key(n);r!==null&&t.push(r)}return{ok:!0,value:t}}catch(e){return S(e)}}}),O=()=>{try{return D(typeof window>`u`?null:window.localStorage)}catch{return D(null)}},k=(e,t,n,r)=>{let i=[];try{let e=n===null?[]:JSON.parse(n);Array.isArray(e)&&(i=e.filter(e=>typeof e==`string`))}catch{}return{suffix:e,text:t??``,mentions:i,keys:r}},ee=async e=>{let t=await e.keys();if(!t.ok)return t;let n=new Set;for(let e of t.value)e.startsWith(v)&&n.add(e.slice(22)),e.startsWith(y)&&n.add(e.slice(29));let r=[];for(let i of n){let n=`${v}${i}`,a=`${y}${i}`,[o,s]=await Promise.all([e.read(n),e.read(a)]);if(!o.ok)return o;if(!s.ok)return s;r.push(k(i,o.value,s.value,[n,a].filter(e=>t.value.includes(e))))}return{ok:!0,value:r}},te=e=>{if(!(!C(e)||!w(e,[`suffix`,`text`,`mentions`,`keys`])||typeof e.suffix!=`string`||typeof e.text!=`string`||!Array.isArray(e.mentions)||!e.mentions.every(e=>typeof e==`string`)||!Array.isArray(e.keys)||!e.keys.every(e=>typeof e==`string`)))return{suffix:e.suffix,text:e.text,mentions:[...e.mentions],keys:[...e.keys]}},ne=e=>{try{let t=JSON.parse(e);return Array.isArray(t)&&t.length===3&&E(t[0])&&(t[1]===`session`||t[1]===`draft`)&&E(t[2])&&e===JSON.stringify(t)}catch{return!1}},A=e=>{if(!C(e)||!w(e,[`complete`,`claimedTransportIdentity`,`captured`,`markerCommitted`,`cleanupComplete`])||typeof e.complete!=`boolean`||typeof e.claimedTransportIdentity!=`string`||e.captured!==void 0&&typeof e.captured!=`boolean`||e.markerCommitted!==void 0&&typeof e.markerCommitted!=`boolean`||e.cleanupComplete!==void 0&&typeof e.cleanupComplete!=`boolean`)return;let t=e.cleanupComplete??e.complete,n=e.captured??e.complete,r=e.markerCommitted??e.complete;if(!((n||r||t)&&!E(e.claimedTransportIdentity))&&!(r&&!n)&&!(t&&(!n||!r)))return{complete:t,claimedTransportIdentity:e.claimedTransportIdentity,captured:n,markerCommitted:r,cleanupComplete:t}},j=e=>{if(!C(e)||!w(e,[`version`,`drafts`,`tombstones`,`migration`,`legacy`])||e.version!==1||!C(e.drafts)||!C(e.tombstones)||!C(e.legacy)||!w(e.legacy,[`new`,`entries`])||!C(e.legacy.entries))return;let t=A(e.migration);if(!t)return;let n={};for(let[t,r]of Object.entries(e.drafts)){let e=c(r);if(!e||t!==a(e.key))return;n[t]=e}let r={};for(let[t,n]of Object.entries(e.tombstones)){if(!ne(t)||!T(n))return;r[t]=n}let i={};for(let[t,n]of Object.entries(e.legacy.entries)){let e=te(n);if(!e||t!==e.suffix||t===`new`)return;i[t]=e}let o=e.legacy.new===void 0?void 0:te(e.legacy.new);if(!(e.legacy.new!==void 0&&(!o||o.suffix!==`new`)))return{version:1,drafts:n,tombstones:r,migration:t,legacy:{...o?{new:o}:{},entries:i}}},M=(e=``)=>({version:1,drafts:{},tombstones:{},migration:{complete:!1,claimedTransportIdentity:e,captured:!1,markerCommitted:!1,cleanupComplete:!1},legacy:{entries:{}}}),N=e=>{try{return{ok:!0,value:JSON.stringify(e)}}catch{return{ok:!1,error:{code:`serialization`}}}},P=async e=>{let t=await e.read(g);if(!t.ok)return t;if(t.value===null)return{ok:!0,value:null};try{let e=j(JSON.parse(t.value));return e?{ok:!0,value:e}:{ok:!1,error:{code:`corrupt`}}}catch{return{ok:!1,error:{code:`corrupt`}}}},F=async(e,t)=>{let n=j(t);if(!n)return{ok:!1,error:{code:`corrupt`}};let r=N(n);return r.ok?e.write(g,r.value):r},I=e=>C(e)&&w(e,[`version`,`claimedTransportIdentity`])&&e.version===1&&E(e.claimedTransportIdentity)?{version:1,claimedTransportIdentity:e.claimedTransportIdentity}:void 0,re=e=>N({version:1,claimedTransportIdentity:e}),ie=(e,t,n)=>{let r={},i;for(let e of t)e.suffix===`new`?i=e:r[e.suffix]=e;return{...e,migration:{complete:!1,claimedTransportIdentity:n,captured:!0,markerCommitted:!1,cleanupComplete:!1},legacy:{...i?{new:i}:{},entries:r}}},L=e=>[...new Set([e.legacy.new,...Object.values(e.legacy.entries)].flatMap(e=>e?.keys??[]))],ae=new WeakMap,R=e=>{let t=ae.get(e);if(t)return t;let n=Promise.resolve(),r,i=!0,a=e=>{let t=n.then(e,e);return n=t.then(()=>void 0,()=>void 0),t},o={persist:t=>{let n=j(t);return n?i?a(async()=>i?F(e,n):b()):Promise.resolve(b()):Promise.resolve({ok:!1,error:{code:`corrupt`}})},migrate:(t,n={})=>{if(r)return r;let o=a(async()=>{let r=await P(e);if(!r.ok)return r;let a=r.value??M(),o=i&&(n.persistenceEnabled??!0);if(!a.migration.captured){let n=await ee(e);if(!n.ok)return n;if(!o)return{ok:!0,value:ie(a,n.value,``)};if(a=ie(a,n.value,t),!i)return{ok:!0,value:a};let r=await F(e,a);if(!r.ok)return r}if(!i||!(n.persistenceEnabled??!0)){let t=await ee(e);return t.ok?{ok:!0,value:a}:t}let s=await e.read(_);if(!s.ok)return s;if(s.value!==null)try{let t=I(JSON.parse(s.value));if(!t)return{ok:!1,error:{code:`corrupt`}};if(t.claimedTransportIdentity!==a.migration.claimedTransportIdentity){let t=re(a.migration.claimedTransportIdentity);if(!t.ok)return t;if(!i)return{ok:!0,value:a};let n=await e.write(_,t.value);if(!n.ok)return n}}catch{return{ok:!1,error:{code:`corrupt`}}}else{let t=re(a.migration.claimedTransportIdentity);if(!t.ok)return t;if(!i)return{ok:!0,value:a};let n=await e.write(_,t.value);if(!n.ok)return n}if(a.migration.cleanupComplete)return{ok:!0,value:a};for(let t of L(a)){if(!i)return{ok:!0,value:a};let n=await e.remove(t);if(!n.ok)return n}if(a={...a,migration:{complete:!0,claimedTransportIdentity:a.migration.claimedTransportIdentity,captured:!0,markerCommitted:!0,cleanupComplete:!0}},!i)return{ok:!0,value:a};let c=await F(e,a);return c.ok?{ok:!0,value:a}:c}).finally(()=>{r=void 0});return r=o,o},flush:()=>n,setEnabled:async e=>{i=e,i||await n}};return ae.set(e,o),o},z=e=>{let t=R(e),n=!0,r=!1,i=[],a=[],o=()=>{if(r||i.length>0)return;let e=a;a=[],e.forEach(e=>e())},s=()=>{if(r)return;let e=i.shift();if(!e){o();return}r=!0,t.persist(e.snapshot).then(e.resolve).finally(()=>{r=!1,s()})};return{persist:e=>{let t=j(e);return t?n?new Promise(e=>{i.push({snapshot:t,resolve:e}),s()}):Promise.resolve(b()):Promise.resolve({ok:!1,error:{code:`corrupt`}})},cancelPending:()=>{let e=i;i=[],e.forEach(({resolve:e})=>e(x())),o()},flush:()=>r||i.length>0?new Promise(e=>a.push(e)):Promise.resolve(),setEnabled:async e=>{if(n=e,!n){let e=i;i=[],e.forEach(({resolve:e})=>e(x()))}await(r||i.length>0?new Promise(e=>a.push(e)):Promise.resolve()),await t.setEnabled(e),await t.flush()}}},oe=`yuri-input-drafts`,se=1,ce=`blobs`,le=`blobRefs`,B=class extends Error{code;constructor(e){super(e),this.code=e}},V=e=>({ok:!1,error:{code:e instanceof B?e.code:e instanceof DOMException&&e.name===`QuotaExceededError`?`quota-exceeded`:e instanceof DOMException&&e.name===`AbortError`?`transaction-aborted`:`transaction-failed`}}),H=e=>{if(!(e instanceof Blob)&&!u(e))throw new B(`invalid-value`)},U=e=>{if(!e)throw new B(`invalid-value`)},W=(e,t)=>({id:p(e),blobID:t,transportIdentity:e.transportIdentity,ownerKind:e.owner.kind,ownerID:e.owner.ownerID}),G=async e=>{if(typeof e==`string`)return`url:${e}`;let t=await crypto.subtle.digest(`SHA-256`,await e.arrayBuffer()),n=[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,`0`)).join(``);return`blob:${e.type}:${e.size}:${n}`},K=async(e,t)=>(e.fingerprint??await G(e.value))===t,q=async(e,t=!1)=>{let n=await e.getAllBlobRefs(),r=await e.getAllBlobs(),i=new Map;for(let t of n)await e.getBlob(t.blobID)?i.set(t.blobID,(i.get(t.blobID)??0)+1):await e.deleteBlobRef(t.id);for(let n of r){let r=i.get(n.id)??0;r||!t?await e.putBlob({...n,refCount:r}):await e.deleteBlob(n.id)}},ue=e=>{try{let t=JSON.parse(e);return!Array.isArray(t)||t.length!==4||typeof t[0]!=`string`||typeof t[2]!=`string`||t[1]!==`session`&&t[1]!==`draft`&&t[1]!==`surface`&&t[1]!==`queue`&&t[1]!==`send`?void 0:{transportIdentity:t[0],ownerKind:t[1],ownerID:t[2]}}catch{return}},J=(e,t)=>{let n=ue(e.id),r=e.ownerKind??n?.ownerKind,i=e.transportIdentity??n?.transportIdentity;return r!==void 0&&t.ownerKinds.includes(r)&&(t.transportIdentities===void 0||i!==void 0&&t.transportIdentities.includes(i))},Y=(e=de())=>{let t=async(t,n)=>{try{return{ok:!0,value:await e.transaction(async e=>{let r=await e.getBlobRef(p(t));return!r||n!==void 0&&r.blobID!==n?!1:(await e.deleteBlobRef(r.id),await q(e),(await e.getAllBlobRefs()).some(e=>e.blobID===r.blobID)||await e.deleteBlob(r.blobID),!0)})}}catch(e){return V(e)}};return{put:async(t,n)=>{try{U(t),H(n);let r=await G(n);return await e.transaction(async e=>{let i=await e.getBlob(t);if(i&&!await K(i,r))throw new B(`blob-id-conflict`);i||await e.putBlob({id:t,value:n,refCount:0,fingerprint:r})}),{ok:!0,value:void 0}}catch(e){return V(e)}},putAndRetain:async(t,n,r)=>{try{U(n),H(r);let i=await G(r);return await e.transaction(async e=>{let a=p(t),o=await e.getBlobRef(a);if(o&&o.blobID!==n)throw new B(`blob-id-conflict`);let s=await e.getBlob(n);if(s&&!await K(s,i))throw new B(`blob-id-conflict`);s||await e.putBlob({id:n,value:r,refCount:0,fingerprint:i}),o||await e.putBlobRef(W(t,n)),await q(e)}),{ok:!0,value:void 0}}catch(e){return V(e)}},read:async t=>{try{let n=await e.transaction(e=>e.getBlob(t));return n?{ok:!0,value:n.value}:{ok:!1,error:{code:`missing-blob`}}}catch(e){return V(e)}},readReference:async t=>{try{return{ok:!0,value:(await e.transaction(e=>e.getBlobRef(p(t))))?.blobID}}catch(e){return V(e)}},retain:async(t,n)=>{try{return U(n),await e.transaction(async e=>{let r=await e.getBlobRef(p(t));if(r&&r.blobID!==n)throw new B(`blob-id-conflict`);if(!await e.getBlob(n))throw new B(`missing-blob`);r||await e.putBlobRef(W(t,n)),await q(e)}),{ok:!0,value:void 0}}catch(e){return V(e)}},release:e=>t(e),releaseIfMatches:(e,n)=>t(e,n),reconcileReferences:async(t,n={ownerKinds:[`session`,`draft`]})=>{try{return{ok:!0,value:await e.transaction(async e=>{let r=[],i=[],a=[],o=new Map((await e.getAllBlobRefs()).map(e=>[e.id,e]));for(let[i,a]of o)J(a,n)&&t.get(i)!==a.blobID&&(await e.deleteBlobRef(i),r.push(i));for(let[r,s]of t){let t=ue(r);if(!t||!n.ownerKinds.includes(t.ownerKind)||n.transportIdentities!==void 0&&!n.transportIdentities.includes(t.transportIdentity)){a.push(r);continue}let c=o.get(r);if(!await e.getBlob(s)){a.push(r);continue}(!c||c.blobID!==s)&&(await e.putBlobRef({id:r,blobID:s,...t}),i.push(r))}return await q(e,!0),{released:r,repaired:i,missing:a}})}}catch(e){return V(e)}},reconcileOwnerReferences:async(t,n)=>{let r=new Map;for(let[e,i]of n)r.set(p({transportIdentity:t.transportIdentity,owner:t.owner,attachmentOccurrenceRefID:e}),i);try{return{ok:!0,value:await e.transaction(async e=>{let n=0,i=new Set;for(let a of await e.getAllBlobRefs())a.transportIdentity===t.transportIdentity&&a.ownerKind===t.owner.kind&&a.ownerID===t.owner.ownerID&&r.get(a.id)!==a.blobID&&(await e.deleteBlobRef(a.id),i.add(a.blobID),n++);await q(e);let a=await e.getAllBlobRefs();for(let t of i)a.some(e=>e.blobID===t)||await e.deleteBlob(t);return n})}}catch(e){return V(e)}},discardUnreferenced:async t=>{try{return{ok:!0,value:await e.transaction(async e=>!await e.getBlob(t)||(await e.getAllBlobRefs()).some(e=>e.blobID===t)?!1:(await e.deleteBlob(t),!0))}}catch(e){return V(e)}}}},de=(e=oe)=>({transaction:async t=>{let n=await X(e),r=n.transaction([ce,le],`readwrite`),i=r.objectStore(ce),a=r.objectStore(le),o=e=>new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error??r.error??Error(`IndexedDB request failed`))}),s=new Promise((e,t)=>{r.oncomplete=()=>e(),r.onabort=()=>t(r.error??new DOMException(`aborted`,`AbortError`)),r.onerror=()=>{console.error(`Input draft IndexedDB transaction error`,r.error)}}),c;try{let e=await t({getBlob:e=>o(i.get(e)),getAllBlobs:()=>o(i.getAll()),putBlob:async e=>{await o(i.put(e))},deleteBlob:async e=>{await o(i.delete(e))},getBlobRef:e=>o(a.get(e)),getAllBlobRefs:()=>o(a.getAll()),putBlobRef:async e=>{await o(a.put(e))},deleteBlobRef:async e=>{await o(a.delete(e))}});return await s,e}catch(e){c=e;try{r.abort()}catch{}try{await s}catch(e){c===void 0&&(c=e)}throw c}finally{n.close()}}}),X=e=>(e===oe?r(oe):Promise.resolve()).then(()=>new Promise((t,n)=>{if(!globalThis.indexedDB){n(new B(`database-unavailable`));return}let r=indexedDB.open(e,se),i=!1,a=()=>{i||(i=!0,n(new B(`database-unavailable`)))};r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(ce)||e.createObjectStore(ce,{keyPath:`id`}),e.objectStoreNames.contains(le)||e.createObjectStore(le,{keyPath:`id`})},r.onsuccess=()=>{let e=r.result;if(e.onversionchange=()=>e.close(),i){e.close();return}i=!0,t(e)},r.onerror=a,r.onblocked=a})),fe=()=>({drafts:{},tombstones:{},migration:{complete:!1,claimedTransportIdentity:``,captured:!1,markerCommitted:!1,cleanupComplete:!1},legacy:{entries:{}}}),pe=e=>({version:1,drafts:e.drafts,tombstones:e.tombstones,migration:e.migration,legacy:e.legacy}),me=e=>{let t=pe(e),n=he(JSON.parse(JSON.stringify(t)));return{drafts:n.drafts,tombstones:n.tombstones,migration:n.migration,legacy:n.legacy}},he=e=>{let t=j(e);if(!t)throw Error(`invalid draft snapshot`);return t},ge=e=>e instanceof Map?[...e.entries()]:Object.entries(e??{}),_e=e=>typeof e==`string`?e:a(e),ve=[`session`,`draft`,`surface`],Z=e=>({transportIdentity:e.transportIdentity,owner:{kind:e.owner.kind,ownerID:e.owner.ownerID},attachmentOccurrenceRefID:e.attachmentOccurrenceRefID}),ye=e=>JSON.parse(JSON.stringify(e)),be=e=>e.phase===`metadata`?{phase:`metadata`,error:{code:e.error.code}}:{phase:`blob`,error:{...e.error},...e.reference?{reference:Z(e.reference)}:{}},xe=e=>({status:e.status,keys:[...e.keys],errors:e.errors.map(be),cleanupErrors:e.cleanupErrors.map(be)}),Se=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0,Ce=e=>{try{let t=JSON.parse(e);return Array.isArray(t)&&t.length===3&&typeof t[0]==`string`&&ve.includes(t[1])&&typeof t[2]==`string`&&t[0].length>0&&t[2].length>0}catch{return!1}},we=e=>[...e.attachments,...e.syntheticParts.flatMap(e=>e.attachments)].flatMap(t=>t.locator.kind===`blob`?[{reference:{transportIdentity:e.key.transportIdentity,owner:{kind:e.key.owner.kind,ownerID:e.key.owner.ownerID},attachmentOccurrenceRefID:t.attachmentRefID},attachment:ye(t)}]:[]),Te=e=>{let t=new Map;for(let n of Object.values(e))for(let e of we(n))t.set(p(e.reference),e);return t},Q=(e,t)=>({phase:`blob`,error:{...e},...t?{reference:Z(t)}:{}}),$=(e,t=[])=>({status:e,keys:t,errors:[],cleanupErrors:[]}),Ee=e=>e?.attachment.locator.kind===`blob`?e.attachment.locator.blobID:``,De=(e,t,n={})=>{let r=fe(),i=n.enabled??!0,o=0,s=!1,l=Promise.resolve(),u=new Map,d=e=>{let t=l.then(e,e);return l=t.then(()=>void 0,()=>void 0),t.then(e=>e&&typeof e==`object`&&`status`in e&&`keys`in e&&`errors`in e&&`cleanupErrors`in e?xe(e):e)},f=async(t=r.drafts)=>{let n=[],i=new Map([...Te(t)].map(([e,t])=>[e,t.attachment.locator.kind===`blob`?t.attachment.locator.blobID:``]));for(let[t,r]of u){if(i.get(t)===r.expectedBlobID){u.delete(t);continue}let a=await e.releaseIfMatches(Z(r.reference),r.expectedBlobID);a.ok?u.delete(t):n.push(Q(a.error,r.reference))}return n},m=async(t,n,r,i)=>{let a=Z(t),s=await e.releaseIfMatches(a,n);s.ok||(u.set(p(a),{reference:Z(a),expectedBlobID:n,generation:o,reason:i}),r.push(Q(s.error,a)))},h=async(t,n)=>{let r=t.attachment.locator.kind===`blob`?t.attachment.locator.blobID:``,i=Z(t.reference),a=ye(t.attachment),o=await e.readReference(i);if(!o.ok)return{acquired:!1,error:Q(o.error,i)};if(o.value&&o.value!==r)return{acquired:!1,error:Q({code:`reference-conflict`},i)};if(o.value===r){let t=await e.read(r);if(t.ok)return{acquired:!1};if(t.error.code!==`missing-blob`)return{acquired:!1,error:Q(t.error,i)};let o=await n?.(Z(i),ye(a));if(o===void 0)return{acquired:!1,error:Q({code:`runtime-value-missing`},i)};let s=await e.putAndRetain(i,r,o);return s.ok?{acquired:!0}:{acquired:!1,error:Q(s.error,i)}}let s=await e.read(r);if(s.ok){let t=await e.retain(i,r);return t.ok?{acquired:!0}:{acquired:!1,error:Q(t.error,i)}}if(s.error.code!==`missing-blob`)return{acquired:!1,error:Q(s.error,i)};let c=await n?.(Z(i),ye(a));if(c===void 0)return{acquired:!1,error:Q({code:`runtime-value-missing`},i)};let l=await e.putAndRetain(i,r,c);return l.ok?{acquired:!0}:{acquired:!1,error:Q(l.error,i)}};return{seed:t=>d(async()=>{if(!i)return $(`disabled`);if(s)return{...$(`failed`),errors:[Q({code:`invalid-record`})]};let n;try{if(!t)n=fe();else{let e=he(JSON.parse(JSON.stringify(t)));n={drafts:e.drafts,tombstones:e.tombstones,migration:e.migration,legacy:e.legacy}}}catch{return{...$(`failed`),errors:[Q({code:`invalid-record`})]}}let a=Te(n.drafts),o=await e.reconcileReferences(new Map([...a].map(([e,t])=>[e,Ee(t)])),{ownerKinds:ve});return o.ok?(r=n,s=!0,{...$(`committed`),errors:o.value.missing.map(e=>Q({code:`missing-blob`},a.get(e)?.reference))}):{...$(`failed`),errors:[Q(o.error)]}}),commit:e=>{let n=[...ge(e.drafts).map(([e])=>e),...(e.delete??[]).map(_e)];return i?d(async()=>{if(!s)return $(`unseeded`,n);if(!i)return $(`disabled`,n);let l=o,u=[],d=me(r),g=ge(e.drafts),_=ge(e.tombstones),v=(e.delete??[]).map(_e);if(g.some(([e,t])=>!Ce(e)||!Se(t.revision))||_.some(([e,t])=>!Ce(e)||!Se(t))||v.some(e=>!Ce(e))||new Set(g.map(([e])=>e)).size!==g.length||_.some(([e])=>g.some(([t])=>t===e)))return{...$(`failed`,n),errors:[Q({code:`invalid-record`})]};try{for(let[e,t]of g){let n=c(t);if(!n||e!==a(n.key))throw Error(`invalid draft record`);d.drafts[e]=n,delete d.tombstones[e]}for(let e of v)delete d.drafts[e];for(let[e,t]of _)d.tombstones[e]=t;e.migration&&(d.migration=e.migration),e.legacy&&(d.legacy=e.legacy);let t=he(pe(d));d.drafts=t.drafts,d.tombstones=t.tombstones,d.migration=t.migration,d.legacy=t.legacy}catch{return{...$(`failed`,n),errors:[Q({code:`invalid-record`})],cleanupErrors:u}}if(!await e.isCurrent())return $(`stale`,n);let y=Te(r.drafts),b=Te(d.drafts);u=await f(d.drafts);let x=[];for(let[t,r]of b){let i=y.get(t);if((i?.attachment.locator.kind===`blob`?i.attachment.locator.blobID:void 0)===(r.attachment.locator.kind===`blob`?r.attachment.locator.blobID:void 0))continue;let a=await h(r,e.resolveBlobValue);if(a.error){for(let e of x.reverse())await m(e,Ee(b.get(p(e))),u,`acquire-failed`);return{...$(`failed`,n),errors:[a.error],cleanupErrors:u}}a.acquired&&x.push(r.reference)}if(!await e.isCurrent()){for(let e of x.reverse())await m(e,Ee(b.get(p(e))),u,`stale`);return{...$(`stale`,n),cleanupErrors:u}}if(!i||l!==o){for(let e of x.reverse())await m(e,Ee(b.get(p(e))),u,`disabled`);return{...$(`disabled`,n),cleanupErrors:u}}let S=await t.persist(pe(d));if(!S.ok){for(let e of x.reverse())await m(e,Ee(b.get(p(e))),u,`metadata-failed`);return{...$(`failed`,n),errors:[{phase:`metadata`,error:S.error}],cleanupErrors:u}}r=d;for(let[e,t]of y)b.has(e)||await m(t.reference,t.attachment.locator.kind===`blob`?t.attachment.locator.blobID:``,u,`metadata-committed`);return{...$(`committed`,n),cleanupErrors:u}}):Promise.resolve(xe($(`disabled`,n)))},reconcile:()=>d(async()=>{if(!s)return $(`unseeded`);if(!i)return $(`disabled`);let t=await f(),n=new Map([...Te(r.drafts)].map(([e,t])=>[e,t.attachment.locator.kind===`blob`?t.attachment.locator.blobID:``])),a=await e.reconcileReferences(n,{ownerKinds:ve}),o=a.ok?a.value.missing.map(e=>Q({code:`missing-blob`},Te(r.drafts).get(e)?.reference)):[Q(a.error)];return{status:a.ok?`committed`:`failed`,keys:[],errors:o,cleanupErrors:t}}),retryCleanup:()=>d(async()=>({...$(`committed`),cleanupErrors:await f()})),flush:()=>l,setEnabled:async e=>{if(!e){i=!1,o+=1,t.cancelPending?.(),await t.setEnabled?.(!1),await l,await t.flush?.();return}await t.setEnabled?.(!0),i=!0,o+=1}}},Oe=`yuri-composer-reference-draft`,ke=`yuri-pasted-text-draft`,Ae=e=>Array.from(e).length,je=e=>typeof e==`object`&&!!e&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),Me=(e,t)=>typeof e==`string`&&e.length>0&&e.length<=t,Ne=(e,t)=>{let n=[],r=[],i=0;for(let a=0;a<Math.min(t.length,m.referenceCount);a+=1){let o=t[a];if(!(!je(o)||!Me(o.id,m.idLength)||!Me(o.token,m.displayLength)||typeof o.text!=`string`||o.text.length>m.pastePayloadLength||typeof o.characterCount!=`number`||!Number.isSafeInteger(o.characterCount)||o.characterCount!==Ae(o.text)||typeof o.index!=`number`||!Number.isSafeInteger(o.index)||o.index<1))for(let t=e.indexOf(o.token);t>=0&&n.length<m.referenceCount;t=e.indexOf(o.token,t+o.token.length)){let e=t+o.token.length;if(r.some(n=>n.start<e&&n.end>t)||i+o.text.length>m.totalPastePayloadLength)continue;let a=n.filter(e=>e.id.startsWith(`${o.id}:`)).length;n.push({id:`${o.id}:${a}`,kind:`paste`,start:t,end:e,display:o.token,text:o.text,characterCount:o.characterCount,index:o.index}),r.push({start:t,end:e}),i+=o.text.length}}return n.sort((e,t)=>e.start-t.start)},Pe=e=>{try{let t=JSON.parse(e);if(!je(t)||typeof t.text!=`string`)return{text:e,references:[]};if(t.type===Oe||t.type===`openchamber-composer-reference-draft`)return(t.version===2?o(t.text,t.references):void 0)??{text:t.text,references:[]};if(t.type===ke||t.type===`openchamber-pasted-text-draft`){let e=t.version===1&&Array.isArray(t.references)?Ne(t.text,t.references):[];return o(t.text,e)??{text:t.text,references:[]}}}catch{}return{text:e,references:[]}},Fe=`file://`,Ie=e=>{let t=e.replace(/\\/g,`/`);return/^[A-Za-z]:/.test(t)&&(t=`/${t}`),t.split(`/`).map((e,t)=>t===1&&/^[A-Za-z]:$/.test(e)?e:encodeURIComponent(e)).join(`/`)},Le=e=>{let t=e.replace(/\\/g,`/`).trim();return t.toLowerCase().startsWith(Fe)?t:`${Fe}${Ie(t)}`},Re=(e,t)=>`${e}\u0000${t}`,ze=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error??Error(`Failed to read file`)),r.onabort=()=>n(Error(`File read aborted`)),r.readAsDataURL(e)}),Be=e=>{if(!e.startsWith(`data:`))return 0;let t=e.indexOf(`,`);if(t<0)return 0;let n=e.slice(0,t).toLowerCase(),r=e.slice(t+1);if(!n.endsWith(`;base64`))return 0;let i=0;return r.endsWith(`==`)?i=2:r.endsWith(`=`)&&(i=1),Math.max(0,Math.floor(r.length*3/4)-i)},Ve=(e,t)=>e===t?!0:!e||!t?!1:e.filePath===t.filePath&&e.fileName===t.fileName&&e.relativePath===t.relativePath&&e.fileSize===t.fileSize&&e.selection?.startLine===t.selection?.startLine&&e.selection?.endLine===t.selection?.endLine&&e.selection?.text===t.selection?.text,He=e=>({version:1,key:e,revision:1,text:``,attachments:[],syntheticParts:[],mentions:[]}),Ue=(e,t)=>t.flatMap(t=>{let n=`@${t}`,r=[],i=e.indexOf(n);for(;i>=0;)r.push({kind:`file`,value:t,path:t,label:t,range:{start:i,end:i+n.length}}),i=e.indexOf(n,i+n.length);return r}),We=(r={})=>{let o=r.sink??O(),p=r.repository??R(o),m=r.coordinator??z(o),g=r.blobStore??Y(),_=r.durability??De(g,m,{enabled:r.persistenceEnabled??!0}),v=new Map,y=new Map,b=new Map,x=new Map,S=new Map,C=new Set,w=new Set,T,E,D=0,k=0,ee=!1,te=!1,ne,A=new Set,j=new Map,M=new Set;return n()((n,o)=>{let m=e=>v.set(e,(v.get(e)??0)+1),O=(...e)=>{for(let t of e)b.set(t,(b.get(t)??0)+1),x.delete(t)},N=e=>c(e),P=()=>r.runtimeCapture?.()??{transportIdentity:e(),generation:t()},F=e=>{let t=P();return t.transportIdentity===e.transportIdentity&&t.generation===e.generation},I=e=>[...e.attachments,...e.syntheticParts.flatMap(e=>e.attachments)],re=e=>new Set(I(e).map(e=>e.attachmentRefID)),ie=(e,t,n)=>{let r=re(n);return{draftAttachmentViews:{...e.draftAttachmentViews,[t]:Object.fromEntries(Object.entries(e.draftAttachmentViews[t]??{}).filter(([e])=>r.has(e)))},draftMissingAttachmentRefIDs:{...e.draftMissingAttachmentRefIDs,[t]:(e.draftMissingAttachmentRefIDs[t]??[]).filter(e=>r.has(e))}}},L=()=>r.createID?.()??h(),ae=async(e,t)=>{let n=t instanceof File?t:new File([t],e.filename,{type:e.mimeType});return{id:e.attachmentID,file:n,dataUrl:typeof t==`string`?t:await ze(n),mimeType:e.mimeType,filename:e.filename,size:e.size,source:e.source,...e.serverPath?{serverPath:e.serverPath}:{},...e.vscodePath?{vscodePath:e.vscodePath}:{},...e.vscodeSource?{vscodeSource:e.vscodeSource}:{}}},R=e=>{let t=e.errors[0]??e.cleanupErrors[0];return t?.phase===`metadata`||t?.phase===`blob`&&[`blob-id-conflict`,`database-unavailable`,`invalid-value`,`missing-blob`,`quota-exceeded`,`transaction-aborted`,`transaction-failed`].includes(t.error.code)?t.error.code:`unavailable`},z=(e,t)=>{let r=o(),i=D,a=t??P(),s=[...new Set(e)];if(s.forEach(e=>w.delete(e)),T&&w.size===0&&(clearTimeout(T),T=void 0,E=void 0),!r.persistenceEnabled)return s.forEach(e=>A.add(e)),Promise.resolve({status:`disabled`,keys:s,errors:[],cleanupErrors:[]});let c=new Map(s.map(e=>[e,v.get(e)??0])),l=new Map(s.map(e=>[e,r.drafts[e]?.revision??r.tombstones[e]??0])),u=s.filter(e=>r.drafts[e]),d=Object.fromEntries(u.map(e=>[e,r.draftPersistence[e]?.status===`error`?r.draftPersistence[e]:{status:`saving`,revision:l.get(e)}])),f=Object.fromEntries(u.map(e=>[e,r.draftAttachmentPersistence[e]?.status===`error`?r.draftAttachmentPersistence[e]:{status:`saving`,revision:l.get(e)}]));n(e=>({draftPersistence:{...e.draftPersistence,...d},draftAttachmentPersistence:{...e.draftAttachmentPersistence,...f}})),te||s.forEach(e=>A.add(e));let p=(async()=>{let e=o(),t=await _.commit({drafts:Object.fromEntries(s.flatMap(t=>e.drafts[t]?[[t,e.drafts[t]]]:[])),tombstones:Object.fromEntries(s.flatMap(t=>e.tombstones[t]?[[t,e.tombstones[t]]]:[])),delete:s.filter(t=>!e.drafts[t]),migration:e.migration,legacy:{...e.legacyNewDraft?{new:e.legacyNewDraft}:{},entries:e.legacyDraftEntries},resolveBlobValue:t=>{for(let[n,r]of Object.entries(e.drafts))if(r.key.transportIdentity===t.transportIdentity&&r.key.owner.kind===t.owner.kind&&r.key.owner.ownerID===t.owner.ownerID)return e.draftAttachmentViews[n]?.[t.attachmentOccurrenceRefID]?.file},isCurrent:()=>D===i&&o().persistenceEnabled&&F(a)&&s.every(e=>(v.get(e)??0)===c.get(e)&&(o().drafts[e]?.revision??o().tombstones[e]??0)===l.get(e))}),r=D===i&&o().persistenceEnabled&&F(a);return(!r||t.status===`unseeded`||t.status===`stale`||t.status===`disabled`)&&s.forEach(e=>A.add(e)),r&&n(e=>{let n={...e.draftPersistence};for(let e of u){if((v.get(e)??0)!==c.get(e))continue;let r=l.get(e);if(t.status===`committed`)n[e]={status:`saved`,revision:r};else if(t.status===`unseeded`||t.status===`stale`||t.status===`disabled`)continue;else n[e]={status:`error`,revision:r,errorCode:R(t)}}let r={...e.draftAttachmentPersistence};for(let e of u){if((v.get(e)??0)!==c.get(e))continue;let n=l.get(e);r[e]=t.status===`committed`&&t.cleanupErrors.length===0?{status:`saved`,revision:n}:t.status===`failed`||t.cleanupErrors.length>0?{status:`error`,revision:n,errorCode:R(t)}:r[e]??{status:`idle`,revision:n}}return{draftPersistence:n,draftAttachmentPersistence:r}}),t})();return C.add(p),p.then(()=>C.delete(p),()=>C.delete(p)),p},oe=e=>{let t=o(),r=Object.fromEntries(e.flatMap(e=>{let n=t.drafts[e];return n?[[e,{status:`saving`,revision:n.revision}]]:[]}));Object.keys(r).length&&n(e=>({draftPersistence:{...e.draftPersistence,...r}}))},se=()=>{T&&clearTimeout(T),T=void 0;let e=[...w];w.clear();let t=E;return E=void 0,e.length?z(e,t).then(()=>void 0):Promise.resolve()},ce=e=>{if(!o().persistenceEnabled){A.add(e);return}w.add(e),oe([e]),!T&&(E=P(),T=setTimeout(()=>{se()},40))},le=e=>{let t=[...e];return t.forEach(e=>w.delete(e)),T&&w.size===0&&(clearTimeout(T),T=void 0,E=void 0),z(t)},B=(e,t,r,i=`immediate`)=>{let s=a(e),c=o().drafts[s];if(!c||r!==void 0&&c.revision!==r)return;let l=N(t(c));if(!(!l||a(l.key)!==s))return m(s),n(e=>({drafts:{...e.drafts,[s]:l},...ie(e,s,l)})),i===`deferred`?ce(s):le([s]),l},V=e=>e?l(e):void 0,H=(e=[])=>JSON.parse(JSON.stringify(e)),U=(e,t,n,r=!1,i=!1)=>({status:e,...V(n)?{record:V(n)}:{},errors:H(t?.errors),cleanupErrors:H(t?.cleanupErrors),current:r,durable:i}),W=(e,t,n,r,i=!1,a=!1)=>({status:e,errors:H(t?.errors),cleanupErrors:H(t?.cleanupErrors),current:i,durable:a,source:V(n),destination:V(r)}),G=e=>e.status,K=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0,q=(e,...t)=>{let n={...e};for(let e of t)delete n[e];return n},ue=async(e,t)=>{let n={},r=o().draftAttachmentViews[a(e.key)]??{};for(let i of I(e)){let e;if(i.locator.kind===`url`){let n=t?.get(i.attachmentRefID);e=n===void 0?i.locator.url:n}else e=t?.get(i.attachmentRefID)??r[i.attachmentRefID]?.file??(typeof r[i.attachmentRefID]?.dataUrl==`string`&&u(r[i.attachmentRefID].dataUrl)?r[i.attachmentRefID].dataUrl:void 0);if(i.locator.kind===`url`&&e!==void 0&&(e!==i.locator.url||!u(e))||i.locator.kind===`blob`&&e!==void 0&&!(e instanceof Blob)&&!(typeof e==`string`&&u(e)))return;e!==void 0&&(n[i.attachmentRefID]=await ae(i,e))}return n},J=e=>e?a(e):`legacy-unowned`,Y=e=>j.get(e)??0,de=e=>{j.set(e,Y(e)+1)},X=(e,t,r=!1)=>{r&&de(e),n(n=>{let r=t(n.attachmentBuckets[e]??[]);return{attachmentBuckets:{...n.attachmentBuckets,[e]:r},...J(n.activeAttachmentDraft)===e?{attachedFiles:r}:{}}})};return{drafts:{},tombstones:{},draftHydration:{},draftPersistence:{},draftAttachmentViews:{},draftMissingAttachmentRefIDs:{},draftAttachmentPersistence:{},persistenceEnabled:r.persistenceEnabled??!0,legacyDraftEntries:{},migration:{complete:!1,claimedTransportIdentity:``},captureDraftRuntime:()=>P(),commitDraftSnapshot:async e=>{let t=a(e.key),r=e.runtime;if(r.transportIdentity!==e.key.transportIdentity||!F(r))return U(`stale`,void 0);let i=o(),s=i.drafts[t],c=i.tombstones[t]??0;if(e.expectedRevision!==`absent`&&!K(e.expectedRevision)||!Number.isSafeInteger(c)||c<0)return U(`failed`,void 0);if(e.expectedRevision===`absent`?s:s?.revision!==e.expectedRevision)return U(`conflict`,void 0,s);let u=e.expectedRevision===`absent`?c+1:e.expectedRevision+1;if(!K(u))return U(`failed`,void 0);let d=N({version:1,key:e.key,revision:u,...e.snapshot});if(!d)return U(`failed`,void 0);let f=await ue(d,e.values);if(!f)return U(`failed`,void 0);let p=v.get(t)??0,h=s?.revision??c,g=await _.commit({drafts:{[t]:d},isCurrent:()=>F(r)&&(v.get(t)??0)===p&&(o().drafts[t]?.revision??o().tombstones[t]??0)===h,resolveBlobValue:t=>e.values?.get(t.attachmentOccurrenceRefID)});if(g.status!==`committed`)return U(G(g),g,s);let y=(v.get(t)??0)===p&&(o().drafts[t]?.revision??o().tombstones[t]??0)===h,b=F(r);if(!y)return b||n(e=>({draftAttachmentViews:q(e.draftAttachmentViews,t),draftMissingAttachmentRefIDs:q(e.draftMissingAttachmentRefIDs,t),draftHydration:q(e.draftHydration,t),draftPersistence:q(e.draftPersistence,t),draftAttachmentPersistence:q(e.draftAttachmentPersistence,t)})),U(`stale`,g,d,!1,!0);let x=l(d);return x?(m(t),O(t),n(e=>({drafts:{...e.drafts,[t]:x},tombstones:(()=>{let n={...e.tombstones};return delete n[t],n})(),draftAttachmentViews:b?{...e.draftAttachmentViews,[t]:f}:q(e.draftAttachmentViews,t),draftMissingAttachmentRefIDs:b?{...e.draftMissingAttachmentRefIDs,[t]:[]}:q(e.draftMissingAttachmentRefIDs,t),draftHydration:b?e.draftHydration:q(e.draftHydration,t),draftPersistence:b?{...e.draftPersistence,[t]:{status:`saved`,revision:x.revision}}:q(e.draftPersistence,t),draftAttachmentPersistence:b?{...e.draftAttachmentPersistence,[t]:g.cleanupErrors.length?{status:`error`,revision:x.revision,errorCode:R(g)}:{status:`saved`,revision:x.revision}}:q(e.draftAttachmentPersistence,t)})),U(b?`committed`:`stale`,g,x,b,!0)):U(`failed`,g)},deleteDraftSnapshot:async e=>{let t=a(e.key),r=e.runtime;if(r.transportIdentity!==e.key.transportIdentity||!F(r))return U(`stale`,void 0);let i=o(),s=i.drafts[t],c=i.tombstones[t]??0;if(!K(e.expectedRevision)||!Number.isSafeInteger(c)||c<0)return U(`failed`,void 0);if(!s||s.revision!==e.expectedRevision)return U(`conflict`,void 0);let l=e.expectedRevision+1;if(!K(l))return U(`failed`,void 0);let u=v.get(t)??0,d=s.revision,f=Math.max(c,l),p=await _.commit({tombstones:{[t]:f},delete:[t],isCurrent:()=>F(r)&&(v.get(t)??0)===u&&o().drafts[t]?.revision===d&&(o().tombstones[t]??0)===c});if(p.status!==`committed`)return U(G(p),p);let h=(v.get(t)??0)===u&&o().drafts[t]?.revision===d&&(o().tombstones[t]??0)===c,g=F(r);return h?(m(t),O(t),n(e=>{let n={...e.drafts};return delete n[t],{drafts:n,tombstones:{...e.tombstones,[t]:Math.max(e.tombstones[t]??0,f)},draftAttachmentViews:q(e.draftAttachmentViews,t),draftMissingAttachmentRefIDs:q(e.draftMissingAttachmentRefIDs,t),draftHydration:q(e.draftHydration,t),draftPersistence:q(e.draftPersistence,t),draftAttachmentPersistence:q(e.draftAttachmentPersistence,t)}}),U(g?`committed`:`stale`,p,void 0,g,!0)):(g||n(e=>({draftAttachmentViews:q(e.draftAttachmentViews,t),draftMissingAttachmentRefIDs:q(e.draftMissingAttachmentRefIDs,t),draftHydration:q(e.draftHydration,t),draftPersistence:q(e.draftPersistence,t),draftAttachmentPersistence:q(e.draftAttachmentPersistence,t)})),U(`stale`,p,void 0,!1,!0))},finalizeDraftOwnership:async e=>{let t=a(e.source),r=a(e.destination),i=e.runtime,s=o(),c=s.drafts[t],u=s.drafts[r];if(t===r||e.destination.owner.kind!==`session`||e.source.transportIdentity!==i.transportIdentity||e.destination.transportIdentity!==i.transportIdentity||!F(i))return W(`stale`,void 0,c,u);if(!K(e.expectedSourceRevision))return W(`failed`,void 0,c,u);if(!c||c.revision!==e.expectedSourceRevision||u)return W(`conflict`,void 0,c,u);let d=v.get(t)??0,f=v.get(r)??0,p=s.tombstones[t]??0,h=s.tombstones[r]??0;if(!Number.isSafeInteger(p)||p<0||!Number.isSafeInteger(h)||h<0)return W(`failed`,void 0,c,u);let g=Math.max(c.revision+1,h+1);if(!K(g))return W(`failed`,void 0,c,u);let y=N(e.disposition===`preserve`?{...c,key:e.destination,revision:g}:{...He(e.destination),revision:g});if(!y)return W(`failed`,void 0,c,u);let b=await _.commit({drafts:{[r]:y},tombstones:{[t]:Math.max(p,g)},delete:[t],isCurrent:()=>F(i)&&(v.get(t)??0)===d&&(v.get(r)??0)===f&&o().drafts[t]?.revision===c.revision&&!o().drafts[r]&&(o().tombstones[t]??0)===p&&(o().tombstones[r]??0)===h,resolveBlobValue:e=>s.draftAttachmentViews[t]?.[e.attachmentOccurrenceRefID]?.file});if(b.status!==`committed`)return W(G(b),b,c,u);let x=(v.get(t)??0)===d&&o().drafts[t]?.revision===c.revision&&(o().tombstones[t]??0)===p,S=(v.get(r)??0)===f&&!o().drafts[r]&&(o().tombstones[r]??0)===h,C=F(i),w=l(y);if(!w)return W(`failed`,b,c,u);if(C&&!x&&!S)return W(`stale`,b,c,y,!1,!0);x&&(m(t),O(t)),S&&(m(r),O(r)),n(n=>{let i=n.drafts,a=n.tombstones;(x||S)&&(i={...i}),(x||S)&&(a={...a}),x&&(delete i[t],a[t]=Math.max(a[t]??0,g)),S&&(i[r]=w,delete a[r]);let o=n.draftHydration,s=n.draftPersistence,c=n.draftAttachmentViews,l=n.draftMissingAttachmentRefIDs,u=n.draftAttachmentPersistence;return C?(x&&(o=q(o,t),s=q(s,t),c=q(c,t),l=q(l,t),u=q(u,t)),S&&(o=q(o,r),s={...q(s,r),[r]:{status:`saved`,revision:w.revision}},c=q(c,r),l=q(l,r),u={...q(u,r),[r]:b.cleanupErrors.length?{status:`error`,revision:w.revision,errorCode:R(b)}:{status:`saved`,revision:w.revision}},C&&x&&e.disposition===`preserve`&&(c={...c,[r]:n.draftAttachmentViews[t]??{}},l={...l,[r]:n.draftMissingAttachmentRefIDs[t]??[]}))):(o=q(o,t,r),s=q(s,t,r),c=q(c,t,r),l=q(l,t,r),u=q(u,t,r)),{drafts:i,tombstones:a,draftHydration:o,draftPersistence:s,draftAttachmentViews:c,draftMissingAttachmentRefIDs:l,draftAttachmentPersistence:u}});let T=x&&S&&C;return W(T?`committed`:`stale`,b,c,y,T,!0)},flushDraftPersistence:async()=>{for(await se();C.size;)await Promise.all([...C]);await _.flush()},ensureDraft:e=>{let t=a(e),r=o().drafts[t];if(r)return r;let i=N({...He(e),revision:(o().tombstones[t]??0)+1});if(!i)throw Error(`Invalid empty draft`);return m(t),n(e=>({drafts:{...e.drafts,[t]:i}})),le([t]),i},getDraft:e=>o().drafts[a(e)],setDraftText:(e,t)=>{let n=o().getDraft(e)??o().ensureDraft(e);return B(e,e=>({...e,revision:e.revision+1,text:t,mentions:e.mentions.filter(e=>e.range.end<=t.length&&t.slice(e.range.start,e.range.end)===`@${e.value}`),composerReferences:[]}),n.revision,`deferred`)??n},setDraftComposerDocument:(e,t)=>{let n=o().getDraft(e)??o().ensureDraft(e);return o().setDraftComposerState(e,{document:t,mentions:n.mentions})},setDraftComposerState:(e,t)=>{let n=o().getDraft(e)??o().ensureDraft(e);return B(e,e=>({...e,revision:e.revision+1,text:t.document.text,composerReferences:t.document.references,mentions:t.mentions}),n.revision,`deferred`)},replaceDraft:(e,t,n)=>B(e,e=>({version:1,key:e.key,revision:e.revision+1,text:n.text,attachments:n.attachments,syntheticParts:n.syntheticParts,mentions:n.mentions,...n.composerReferences===void 0?{}:{composerReferences:n.composerReferences}}),t),setDraftMentions:(e,t)=>B(e,e=>({...e,revision:e.revision+1,mentions:t})),addDraftMention:(e,t)=>B(e,e=>({...e,revision:e.revision+1,mentions:[...e.mentions,t]})),removeDraftMention:(e,t)=>B(e,e=>({...e,revision:e.revision+1,mentions:e.mentions.filter(e=>e.value!==t)})),setDraftSyntheticParts:(e,t)=>B(e,e=>({...e,revision:e.revision+1,syntheticParts:t})),consumeDraftSyntheticParts:(e,t)=>{let n=o().getDraft(e);if(!n)return null;let r=n.syntheticParts.filter(e=>!t?.(e)),i=n.syntheticParts.filter(e=>t?.(e));return B(e,e=>({...e,revision:e.revision+1,syntheticParts:i}),n.revision)?r:null},setDraftAttachments:(e,t)=>B(e,e=>({...e,revision:e.revision+1,attachments:t})),addDraftLocalAttachment:async(e,t,r={})=>{let c=o().getDraft(e);if(r.partID&&!c?.syntheticParts.some(e=>e.partID===r.partID))return;let l=a(e),u=v.get(l)??0,d=o().tombstones[l]??0,f=P(),p=t instanceof File?t:new File([t],r.filename??`attachment`,{type:t.type}),h;try{h=await ze(p)}catch{let e=o().drafts[l];if(F(f)&&(o().tombstones[l]??0)===d&&(e?a(e.key)===l:(v.get(l)??0)===u)&&(!r.partID||e?.syntheticParts.some(e=>e.partID===r.partID))){let t=e?.revision??o().tombstones[l]??0;n(e=>({draftAttachmentPersistence:{...e.draftAttachmentPersistence,[l]:{status:`error`,revision:t,errorCode:`transaction-failed`}}}))}return}if(!F(f)||(o().tombstones[l]??0)!==d)return;let g=o().drafts[l];if(!g&&(v.get(l)??0)!==u)return;let _=g??o().ensureDraft(e);if(a(_.key)!==l||r.partID&&!_.syntheticParts.some(e=>e.partID===r.partID))return;let y=r.attachmentID??L(),b=r.partID?s(r.partID,y):i(y),x=L(),S={attachmentID:y,attachmentRefID:b,filename:r.filename??(t instanceof File?t.name:`attachment`),mimeType:t.type,size:t.size,locator:{kind:`blob`,blobID:x},source:r.source??`local`,...r.vscodePath?{vscodePath:r.vscodePath}:{},...r.vscodeSource?{vscodeSource:r.vscodeSource}:{}},C=r.partID?{..._,revision:_.revision+1,syntheticParts:_.syntheticParts.map(e=>e.partID===r.partID?{...e,attachments:[...e.attachments,S]}:e)}:{..._,revision:_.revision+1,attachments:[..._.attachments,S]},w=N(C);if(!w)return;m(l);let T={id:y,file:p,dataUrl:h,mimeType:S.mimeType,filename:S.filename,size:S.size,source:S.source,...r.vscodePath?{vscodePath:r.vscodePath}:{},...r.vscodeSource?{vscodeSource:r.vscodeSource}:{}};return n(e=>({drafts:{...e.drafts,[l]:w},draftAttachmentViews:{...e.draftAttachmentViews,[l]:{...e.draftAttachmentViews[l],[b]:T}}})),await z([l]),S},addDraftDurableAttachment:(e,t)=>{let r=o().getDraft(e)??o().ensureDraft(e);if(t.partID&&!r.syntheticParts.some(e=>e.partID===t.partID))return;let c=t.attachmentID??L(),l=t.partID?s(t.partID,c):i(c),u={attachmentID:c,attachmentRefID:l,filename:t.filename,mimeType:t.mimeType,size:t.size,source:t.source,locator:{kind:`url`,url:t.url},...t.serverPath?{serverPath:t.serverPath}:{},...t.vscodePath?{vscodePath:t.vscodePath}:{},...t.vscodeSource?{vscodeSource:t.vscodeSource}:{}},d=t.partID?{...r,revision:r.revision+1,syntheticParts:r.syntheticParts.map(e=>e.partID===t.partID?{...e,attachments:[...e.attachments,u]}:e)}:{...r,revision:r.revision+1,attachments:[...r.attachments,u]},f=N(d);if(!f)return;let p=a(e);m(p);let h={id:c,file:new File([],u.filename,{type:u.mimeType}),dataUrl:t.url,mimeType:u.mimeType,filename:u.filename,size:u.size,source:u.source,...u.serverPath?{serverPath:u.serverPath}:{},...u.vscodePath?{vscodePath:u.vscodePath}:{},...u.vscodeSource?{vscodeSource:u.vscodeSource}:{}};return n(e=>({drafts:{...e.drafts,[p]:f},draftAttachmentViews:{...e.draftAttachmentViews,[p]:{...e.draftAttachmentViews[p],[l]:h}}})),z([p]),u},getDraftAttachmentViews:e=>{let t=a(e),n=o().drafts[t],r=o().draftAttachmentViews[t]??{};return n?I(n).flatMap(e=>r[e.attachmentRefID]?[r[e.attachmentRefID]]:[]):[]},retryDraftAttachmentPersistence:async e=>{let t=a(e);if(!o().persistenceEnabled||!o().drafts[t]&&!o().tombstones[t])return;let r=await _.retryCleanup();r.cleanupErrors.length&&n(e=>({draftAttachmentPersistence:{...e.draftAttachmentPersistence,[t]:{status:`error`,revision:e.drafts[t]?.revision??e.tombstones[t],errorCode:R(r)}}})),await z([t])},hydrateDraftAttachments:async e=>{let t=a(e),r=x.get(t);if(r)return r;let i=o().drafts[t];if(!i)return;let s=(b.get(t)??0)+1;b.set(t,s);let c=P(),l=D,u=(async()=>{n(e=>({draftHydration:{...e.draftHydration,[t]:`loading`}}));let e=()=>{if(b.get(t)!==s)return;let e=o(),r=e.draftAttachmentViews[t],i=e.draftMissingAttachmentRefIDs[t]??[];n(e=>({draftHydration:{...e.draftHydration,[t]:i.length?`degraded`:Object.keys(r??{}).length?`ready`:`idle`}}))},r={},a=[];for(let u of I(i)){let d=u.locator.kind===`url`?{ok:!0,value:u.locator.url}:await g.read(u.locator.blobID);if(!d.ok){if(d.error.code===`missing-blob`)a.push(u.attachmentRefID);else{b.get(t)===s&&D===l&&F(c)&&o().drafts[t]===i?n(e=>({draftHydration:{...e.draftHydration,[t]:`error`}})):e();return}continue}try{r[u.attachmentRefID]=await ae(u,d.value)}catch{b.get(t)===s&&D===l&&F(c)&&o().drafts[t]===i?n(e=>({draftHydration:{...e.draftHydration,[t]:`error`}})):e();return}}let u=o(),d=u.drafts[t],f=b.get(t);if(f===s&&D===l&&F(c)&&d===i)n(e=>({draftAttachmentViews:{...e.draftAttachmentViews,[t]:r},draftMissingAttachmentRefIDs:{...e.draftMissingAttachmentRefIDs,[t]:a},draftHydration:{...e.draftHydration,[t]:a.length?`degraded`:`ready`}}));else if(f===s){let e=u.draftAttachmentViews[t],r=u.draftMissingAttachmentRefIDs[t]??[];n(n=>({draftHydration:{...n.draftHydration,[t]:r.length?`degraded`:Object.keys(e??{}).length?`ready`:`idle`}}))}})();x.set(t,u);try{await u}finally{x.get(t)===u&&x.delete(t)}},removeDraftAttachment:async(e,t)=>{let r=a(e),i=o().drafts[r],s=i&&I(i).find(e=>e.attachmentRefID===t);if(!i||!s)return!1;let c=d(s)?f(i.text,[s.filename],i.mentions,i.composerReferences):void 0,l=N({...i,revision:i.revision+1,...c?.changed?{text:c.text,mentions:c.mentions,...c.composerReferences===void 0?{}:{composerReferences:c.composerReferences}}:{},attachments:i.attachments.filter(e=>e.attachmentRefID!==t),syntheticParts:i.syntheticParts.map(e=>({...e,attachments:e.attachments.filter(e=>e.attachmentRefID!==t)}))});return l?(m(r),n(e=>{let n={...e.draftAttachmentViews[r]};return delete n[t],{drafts:{...e.drafts,[r]:l},draftAttachmentViews:{...e.draftAttachmentViews,[r]:n},draftMissingAttachmentRefIDs:{...e.draftMissingAttachmentRefIDs,[r]:(e.draftMissingAttachmentRefIDs[r]??[]).filter(e=>e!==t)}}}),(await z([r])).status===`committed`):!1},replaceDraftAttachment:async(e,t,r,c)=>{let l=a(e),u=o().drafts[l],d=u&&I(u).find(e=>e.attachmentRefID===t);if(!u||!d)return;let f=P(),p=o().tombstones[l]??0,h=r instanceof File?r:new File([r],c?.filename??`attachment`,{type:r.type}),g;try{g=await ze(h)}catch{let e=o().drafts[l],r=e&&I(e).find(e=>e.attachmentRefID===t);F(f)&&(o().tombstones[l]??0)===p&&e&&r?.attachmentID===d.attachmentID&&r.attachmentRefID===d.attachmentRefID&&a(e.key)===l&&n(t=>({draftAttachmentPersistence:{...t.draftAttachmentPersistence,[l]:{status:`error`,revision:e.revision,errorCode:`transaction-failed`}}}));return}let _=o().drafts[l],v=_&&I(_).find(e=>e.attachmentRefID===t);if(!F(f)||(o().tombstones[l]??0)!==p||!_||v?.attachmentID!==d.attachmentID||v.attachmentRefID!==d.attachmentRefID||a(_.key)!==l)return;let y=_.syntheticParts.find(e=>e.attachments.some(e=>e.attachmentRefID===t)),b=L(),x={attachmentID:b,attachmentRefID:y?s(y.partID,b):i(b),filename:c?.filename??h.name,mimeType:h.type,size:h.size,locator:{kind:`blob`,blobID:L()},source:c?.source??`local`,...c?.vscodePath?{vscodePath:c.vscodePath}:{},...c?.vscodeSource?{vscodeSource:c.vscodeSource}:{}},S=N({..._,revision:_.revision+1,attachments:y?_.attachments:_.attachments.map(e=>e.attachmentRefID===t?x:e),syntheticParts:_.syntheticParts.map(e=>e.partID===y?.partID?{...e,attachments:e.attachments.map(e=>e.attachmentRefID===t?x:e)}:e)});if(!S)return;m(l);let C={id:b,file:h,dataUrl:g,mimeType:x.mimeType,filename:x.filename,size:x.size,source:x.source,...x.vscodePath?{vscodePath:x.vscodePath}:{},...x.vscodeSource?{vscodeSource:x.vscodeSource}:{}};return n(e=>{let n={...e.draftAttachmentViews[l]};return delete n[t],{drafts:{...e.drafts,[l]:S},draftAttachmentViews:{...e.draftAttachmentViews,[l]:{...n,[x.attachmentRefID]:C}},draftMissingAttachmentRefIDs:{...e.draftMissingAttachmentRefIDs,[l]:(e.draftMissingAttachmentRefIDs[l]??[]).filter(e=>e!==t)}}}),(await z([l])).status===`committed`?x:void 0},replaceDraftRootAttachments:async(e,t)=>{let n=a(e),r=P();if(r.transportIdentity!==e.transportIdentity||!F(r))return U(`stale`,void 0);let s=o().drafts[n],c=s?s.revision:`absent`,l=[],d=new Map;for(let e of t){let t=e.id,n=i(t);if(e.source===`server`&&e.dataUrl&&u(e.dataUrl))l.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:`server`,locator:{kind:`url`,url:e.dataUrl},...e.serverPath?{serverPath:e.serverPath}:{}}),d.set(n,e.dataUrl);else if(e.source===`vscode`&&e.vscodeSource===`file`&&e.dataUrl&&u(e.dataUrl))l.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:`vscode`,locator:{kind:`url`,url:e.dataUrl},...e.vscodePath?{vscodePath:e.vscodePath}:{},vscodeSource:`file`}),d.set(n,e.dataUrl);else{let r=e.file instanceof File?e.file:new File([e.file],e.filename,{type:e.mimeType}),i=L();l.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:e.source===`vscode`?`vscode`:`local`,locator:{kind:`blob`,blobID:i},...e.vscodePath?{vscodePath:e.vscodePath}:{},...e.vscodeSource===`selection`?{vscodeSource:`selection`}:{}}),d.set(n,r)}}let f=s?.syntheticParts??[];for(let e of f)for(let t of e.attachments)t.locator.kind===`url`&&!d.has(t.attachmentRefID)&&d.set(t.attachmentRefID,t.locator.url);let p={text:s?.text??``,attachments:l,syntheticParts:f,mentions:s?.mentions??[],...s?.composerReferences===void 0?{}:{composerReferences:s.composerReferences}};return o().commitDraftSnapshot({key:e,expectedRevision:c,snapshot:p,values:d,runtime:r})},restoreDraftRootAttachments:async(e,t)=>{let n=a(e),r=P();if(r.transportIdentity!==e.transportIdentity||!F(r))return U(`stale`,void 0);let s=o().drafts[n],c=s?s.revision:`absent`,l=new Set(t.map(e=>e.id)),d=[],f=new Map;for(let e of t){let t=e.id,n=i(t);if(e.source===`server`&&e.dataUrl&&u(e.dataUrl))d.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:`server`,locator:{kind:`url`,url:e.dataUrl},...e.serverPath?{serverPath:e.serverPath}:{}}),f.set(n,e.dataUrl);else if(e.source===`vscode`&&e.vscodeSource===`file`&&e.dataUrl&&u(e.dataUrl))d.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:`vscode`,locator:{kind:`url`,url:e.dataUrl},...e.vscodePath?{vscodePath:e.vscodePath}:{},vscodeSource:`file`}),f.set(n,e.dataUrl);else{let r=e.file instanceof File?e.file:new File([e.file],e.filename,{type:e.mimeType}),i=L();d.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:e.source===`vscode`?`vscode`:`local`,locator:{kind:`blob`,blobID:i},...e.vscodePath?{vscodePath:e.vscodePath}:{},...e.vscodeSource===`selection`?{vscodeSource:`selection`}:{}}),f.set(n,r)}}let p=o().draftAttachmentViews[n]??{};for(let e of s?.attachments??[])if(!l.has(e.attachmentID))if(d.push(JSON.parse(JSON.stringify(e))),e.locator.kind===`url`)f.set(e.attachmentRefID,e.locator.url);else{let t=p[e.attachmentRefID];t?.file instanceof Blob?f.set(e.attachmentRefID,t.file):typeof t?.dataUrl==`string`&&u(t.dataUrl)&&f.set(e.attachmentRefID,t.dataUrl)}let m=s?.syntheticParts??[];for(let e of m)for(let t of e.attachments)t.locator.kind===`url`&&!f.has(t.attachmentRefID)&&f.set(t.attachmentRefID,t.locator.url);let h={text:s?.text??``,attachments:d,syntheticParts:m,mentions:s?.mentions??[],...s?.composerReferences===void 0?{}:{composerReferences:s.composerReferences}};return o().commitDraftSnapshot({key:e,expectedRevision:c,snapshot:h,values:f,runtime:r})},deleteDraft:(e,t)=>{let r=a(e),i=o().drafts[r];if(!i||t!==void 0&&i.revision!==t)return!1;let s=i.revision+1;return K(s)?(m(r),O(r),n(e=>{let t={...e.drafts};delete t[r];let n={...e.draftHydration},i={...e.draftPersistence},a={...e.draftAttachmentViews},o={...e.draftMissingAttachmentRefIDs},c={...e.draftAttachmentPersistence};return delete n[r],delete i[r],delete a[r],delete o[r],delete c[r],{drafts:t,tombstones:{...e.tombstones,[r]:Math.max(e.tombstones[r]??0,s)},draftHydration:n,draftPersistence:i,draftAttachmentViews:a,draftMissingAttachmentRefIDs:o,draftAttachmentPersistence:c}}),z([r]),!0):!1},moveDraft:(e,t,r)=>{let i=a(e),s=a(t),c=o().drafts[i];if(!c||i===s||r!==void 0&&c.revision!==r||o().drafts[s]||(o().tombstones[s]??0)>=c.revision+1||[...c.attachments,...c.syntheticParts.flatMap(e=>e.attachments)].some(e=>e.locator.kind===`blob`))return;let l=N({...c,key:t,revision:c.revision+1});if(l)return m(i),m(s),O(i,s),n(e=>{let t={...e.drafts};delete t[i];let n={...e.tombstones,[i]:Math.max(e.tombstones[i]??0,l.revision)};(n[s]??0)<l.revision&&delete n[s];let r=e=>{let t={...e},n=t[i];return delete t[i],delete t[s],n===void 0?t:{...t,[s]:n}};return{drafts:{...t,[s]:l},tombstones:n,draftHydration:r(e.draftHydration),draftPersistence:r(e.draftPersistence),draftAttachmentViews:r(e.draftAttachmentViews),draftMissingAttachmentRefIDs:r(e.draftMissingAttachmentRefIDs),draftAttachmentPersistence:r(e.draftAttachmentPersistence)}}),z([i,s]),l},moveDraftWithAttachments:async(e,t,r)=>{let i=a(e),s=a(t),c=o().drafts[i];if(!c||i===s||r!==void 0&&c.revision!==r||o().drafts[s]||(o().tombstones[s]??0)>=c.revision+1)return;let l=N({...c,key:t,revision:c.revision+1});if(l)return m(i),m(s),O(i,s),n(e=>{let t={...e.drafts};delete t[i];let n={...e.tombstones,[i]:Math.max(e.tombstones[i]??0,l.revision)};(n[s]??0)<l.revision&&delete n[s];let r=e=>{let t={...e},n=t[i];return delete t[i],delete t[s],n===void 0?t:{...t,[s]:n}};return{drafts:{...t,[s]:l},tombstones:n,draftHydration:r(e.draftHydration),draftPersistence:r(e.draftPersistence),draftAttachmentViews:r(e.draftAttachmentViews),draftMissingAttachmentRefIDs:r(e.draftMissingAttachmentRefIDs),draftAttachmentPersistence:r(e.draftAttachmentPersistence)}}),(await z([i,s])).status===`committed`?l:void 0},setDraftPersistenceEnabled:async e=>{if(D+=1,!e){T&&clearTimeout(T),T=void 0,w.clear(),E=void 0,n({persistenceEnabled:!1,draftPersistence:{}}),await _.setEnabled(!1),await _.flush();return}n({persistenceEnabled:!0}),await _.setEnabled(!0);let t=P();te||await o().hydrateDraftMetadata(t.transportIdentity);let r=new Set([...Object.keys(o().drafts),...Object.keys(o().tombstones),...A]);A.clear(),await z(r),await _.flush()},hydrateDraftMetadata:e=>{let t=S.get(e);if(t)return t;let r=(async()=>{let t=(y.get(e)??0)+1;y.set(e,t);let r=P();if(r.transportIdentity!==e)return!1;let i=D,s=new Map(v),c=k,l=Object.entries(o().drafts).filter(([,t])=>t.key.transportIdentity===e).map(([e])=>e);n(e=>({draftHydration:{...e.draftHydration,...Object.fromEntries(l.map(e=>[e,`loading`]))}}));let u=o().persistenceEnabled,d;try{d=await p.migrate(e,{persistenceEnabled:u})}catch{return!1}if(y.get(e)!==t||D!==i||!F(r))return!1;if(!d.ok)return n(e=>({draftHydration:{...e.draftHydration,...Object.fromEntries(l.map(t=>[t,e.drafts[t]?`degraded`:`error`]))}})),!1;let f=d.value;if(!te){ne??=_.seed(f).finally(()=>{ne=void 0});let a;try{a=await ne}catch{return!1}if(y.get(e)!==t||D!==i||!F(r))return!1;if(a.status!==`committed`&&a.status!==`disabled`)return n(e=>({draftHydration:{...e.draftHydration,...Object.fromEntries(l.map(e=>[e,`degraded`]))}})),!1;a.status===`committed`&&(te=!0)}let m=o(),h={...m.drafts},g={...m.tombstones},b=new Set;for(let[e,t]of Object.entries(f.tombstones))(v.get(e)??0)===(s.get(e)??0)&&(t>=(g[e]??0)&&(g[e]=t,(h[e]?.revision??0)<=t&&delete h[e]),b.add(e));for(let[t,n]of Object.entries(f.drafts)){if(n.key.transportIdentity!==e||(v.get(t)??0)!==(s.get(t)??0))continue;let r=h[t],i=N(n);i&&(!r||r.revision<i.revision)&&(g[t]??0)<i.revision&&(h[t]=i),b.add(t)}let x=k===c?{...f.legacy.entries}:{...m.legacyDraftEntries};if(f.migration.claimedTransportIdentity===e&&k===c)for(let[t,n]of Object.entries(x)){let r={transportIdentity:e,owner:{kind:`session`,ownerID:t}},i=a(r),o=Pe(n.text),c=N({...He(r),text:o.text,composerReferences:o.references,mentions:Ue(o.text,n.mentions)});c&&!h[i]&&!g[i]&&(v.get(i)??0)===(s.get(i)??0)&&(h[i]=c),delete x[t],b.add(i)}n(e=>({drafts:h,tombstones:g,legacyNewDraft:k===c&&!ee?f.legacy.new:e.legacyNewDraft,legacyDraftEntries:x,migration:k===c?f.migration:e.migration,draftHydration:{...e.draftHydration,...Object.fromEntries([...b].map(e=>[e,`ready`]))}}));let S=[...A];for(let e of S)b.add(e);A.clear();try{await z(b),await _.flush()}catch{return!1}return y.get(e)===t&&D===i&&F(r)})();return S.set(e,r),r.finally(()=>{S.get(e)===r&&S.delete(e)}).catch(()=>void 0),r},claimLegacyNewDraft:async e=>{let t=o().legacyNewDraft;if(!t)return o().getDraft(e);let r=a(e),i=o().drafts[r];if(k+=1,ee=!0,i||o().tombstones[r])return n({legacyNewDraft:void 0}),z([r]),i;let s=Pe(t.text),c=N({...He(e),text:s.text,composerReferences:s.references,mentions:Ue(s.text,t.mentions)});if(c)return m(r),n(e=>({drafts:{...e.drafts,[r]:c},legacyNewDraft:void 0})),z([r]),c},pendingInputText:null,pendingInputMode:`replace`,pendingSyntheticParts:null,pendingPresetSubmit:null,attachedFiles:[],attachmentBuckets:{"legacy-unowned":[]},activeAttachmentDraft:null,activeEditorFile:null,setPendingInputText:(e,t=`replace`)=>n({pendingInputText:e,pendingInputMode:t}),consumePendingInputText:()=>{let{pendingInputText:e,pendingInputMode:t}=o();return e===null?null:(n({pendingInputText:null,pendingInputMode:`replace`}),{text:e,mode:t})},requestPresetSubmit:e=>n({pendingPresetSubmit:e}),consumePendingPresetSubmit:()=>{let{pendingPresetSubmit:e}=o();return e===null?null:(n({pendingPresetSubmit:null}),e)},setPendingSyntheticParts:e=>n({pendingSyntheticParts:e}),consumePendingSyntheticParts:()=>{let{pendingSyntheticParts:e}=o();return e!==null&&n({pendingSyntheticParts:null}),e},setActiveAttachmentDraft:e=>{let t=J(e);n(n=>({activeAttachmentDraft:e,attachedFiles:n.attachmentBuckets[t]??[],attachmentBuckets:n.attachmentBuckets[t]?n.attachmentBuckets:{...n.attachmentBuckets,[t]:[]}}))},addAttachedFile:async e=>{let t=o().activeAttachmentDraft;if(t){let n=J(t),r=Y(n),i=await o().addDraftLocalAttachment(t,e);r!==Y(n)&&i&&o().removeDraftAttachment(t,i.attachmentRefID);return}let n=`${Date.now()}-${Math.random().toString(36).slice(2)}`,r=J(null),i=Y(r),a;try{a=await ze(e)}catch{return}if(i!==Y(r))return;let s={id:n,file:e,dataUrl:a,mimeType:e.type,filename:e.name,size:e.size,source:`local`};X(r,e=>[...e,s])},removeAttachedFile:e=>{let t=o().activeAttachmentDraft;if(t){let n=o().getDraft(t),r=n?[...n.attachments,...n.syntheticParts.flatMap(e=>e.attachments)].find(t=>t.attachmentID===e):void 0;r&&o().removeDraftAttachment(t,r.attachmentRefID);return}X(J(null),t=>t.filter(t=>t.id!==e))},setAttachedFiles:e=>{X(J(o().activeAttachmentDraft),()=>e,!0)},clearAttachedFiles:()=>{let e=o().activeAttachmentDraft;if(e){de(J(e)),o().getDraft(e)||o().ensureDraft(e),o().setDraftAttachments(e,[]);return}X(J(null),()=>[],!0)},addDraftVSCodeFileAttachment:(e,t,n,r)=>{if(o().getDraftAttachmentViews(e).some(e=>e.source===`vscode`&&e.vscodeSource===`file`&&(e.vscodePath||``)===t)||(o().getDraft(e)?.attachments.some(e=>e.source===`vscode`&&e.vscodeSource===`file`&&(e.vscodePath||``)===t)??!1))return;let i=Le(t);o().addDraftDurableAttachment(e,{filename:n,mimeType:`text/plain`,size:r||0,source:`vscode`,vscodePath:t,vscodeSource:`file`,url:i})},addDraftVSCodeSelectionAttachment:async(e,t,n)=>{let r=a(e),i=Y(r),s=`${r}\u0000${Re(t,n.name)}`;if(!(o().getDraftAttachmentViews(e).some(e=>e.source===`vscode`&&e.vscodeSource===`selection`&&e.filename===n.name&&e.vscodePath===t)||(o().getDraft(e)?.attachments.some(e=>e.source===`vscode`&&e.vscodeSource===`selection`&&e.filename===n.name&&e.vscodePath===t)??!1)||M.has(s))){M.add(s);try{let a=await o().addDraftLocalAttachment(e,n,{source:`vscode`,vscodePath:t,vscodeSource:`selection`});i!==Y(r)&&a&&o().removeDraftAttachment(e,a.attachmentRefID)}finally{M.delete(s)}}},addVSCodeFileAttachment:(e,t,n)=>{let r=o().activeAttachmentDraft;if(r){o().addDraftVSCodeFileAttachment(r,e,t,n);return}let i=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=J(null);if((o().attachmentBuckets[a]??[]).some(t=>t.source===`vscode`&&t.vscodeSource===`file`&&(t.vscodePath||``)===e))return;let s=Le(e),c={id:i,file:new File([],t,{type:`text/plain`}),dataUrl:s,mimeType:`text/plain`,filename:t,size:n||0,source:`vscode`,vscodePath:e,vscodeSource:`file`};X(a,e=>[...e,c])},addVSCodeSelectionAttachment:async(e,t)=>{let n=o().activeAttachmentDraft;if(n){await o().addDraftVSCodeSelectionAttachment(n,e,t);return}let r=`${Date.now()}-${Math.random().toString(36).slice(2)}`,i=J(null),a=Y(i),s=`${i}\u0000${Re(e,t.name)}`;if((o().attachmentBuckets[i]??[]).some(n=>n.source===`vscode`&&n.vscodeSource===`selection`&&n.filename===t.name&&n.vscodePath===e)||M.has(s))return;M.add(s);let c;try{c=await ze(t)}catch{return}finally{M.delete(s)}if(a!==Y(i))return;let l={id:r,file:t,dataUrl:c,mimeType:t.type,filename:t.name,size:t.size,source:`vscode`,vscodePath:e,vscodeSource:`selection`};X(i,e=>[...e,l])},addCodeSelectionAttachment:async(e,t,n)=>{let r=new File([n],t,{type:`text/plain`});await o().addVSCodeSelectionAttachment(e,r)},setActiveEditorFile:e=>{Ve(o().activeEditorFile,e)||n({activeEditorFile:e})},addRestoredAttachment:({url:e,mimeType:t,filename:n})=>{let r=o().activeAttachmentDraft;if(r){if(e.startsWith(`data:`)){let i=a(r);(async()=>{try{let s=await(await fetch(e)).blob(),c=new File([s],n,{type:t||s.type||`application/octet-stream`}),l=o().activeAttachmentDraft;if(!l||a(l)!==i)return;await o().addDraftLocalAttachment(r,c)}catch{}})();return}if(!u(e))return;o().addDraftDurableAttachment(r,{filename:n,mimeType:t,size:Be(e),source:`local`,serverPath:e,url:e});return}let i={id:`restored-${Date.now()}-${Math.random().toString(36).slice(2)}`,file:new File([],n,{type:t}),dataUrl:e,mimeType:t,filename:n,size:Be(e),source:`local`,serverPath:e};X(J(null),e=>[...e,i])}}})},Ge=We();export{O as a,Y as i,Ge as n,de as r,We as t};
@@ -0,0 +1 @@
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{l as t,u as n,z as r}from"./platform-B2ylz14u.js";import{a as i,i as a,r as o}from"./vendor-zustand-CTekDqaS.js";import{ot as s,st as c}from"./vendor-base-ui-wXsskyKm.js";import{St as l,an as u,jt as d,on as f}from"./gitApiHttp-ZjM4HkSo.js";import{t as p}from"./safeStorage-DTOhKN0V.js";import{i as m,t as h}from"./vendor-pathe-vBmvQE8f.js";import{n as g}from"./vendor-react-BkccXcWz.js";import{s as _,u as v}from"./vendor-tanstack-react-query-DIb_ItL-.js";import{E as y}from"./runtime-file-resource-BGZ4tGr5.js";import{o as b}from"./path-utils-jGozTg9d.js";import{r as x}from"./vendor-reactuses-core-DjKFMfz7.js";import{r as S}from"./useUIStore-68ZPpgYA.js";import{o as C,s as w}from"./spacedFileMention-Ds4GtgiF.js";import{Ca as T,Ha as E,Ia as D,Ii as O,R as k,Va as ee,Zi as A,_ as j,b as M,do as te,dt as N,f as P,fa as ne,io as F,ki as I,xt as L}from"./ui-BCYkB585.js";import{n as R}from"./Icon-C1rjS64C.js";import{s as re}from"./remoteProjectQueries-BQzoY_Y9.js";import{t as ie}from"./i18n-iu4pzqPi.js";import{t as ae}from"./ScrollableOverlay-CEglrXfm.js";import{t as oe}from"./useDebouncedValue-BHlMPqY8.js";import{t as se}from"./AgentAvatar-BOvjZ-DI.js";import{c as ce,d as le,l as ue,n as de,r as fe,t as pe}from"./fileMentionTouchSelection-pXNTKHAc.js";import{a as me,o as he,s as ge}from"./fileMentionAutocompleteState-B9411b4o.js";var _e=(e,t)=>{let n=t.trim();if(!n)return[...e].sort((e,t)=>e.isBuiltIn===t.isBuiltIn?e.name.localeCompare(t.name):e.isBuiltIn?-1:1);let r=w([...e],n,e=>[e.name,e.description??``]);return r.sort((e,t)=>e.score===t.score?e.item.isBuiltIn===t.item.isBuiltIn?e.item.name.localeCompare(t.item.name):e.item.isBuiltIn?-1:1:e.score-t.score),r.map(e=>e.item)},ve=(e,t)=>e===t||e.length===t.length&&e.every((e,n)=>{let r=t[n];return r!=null&&e.id===r.id&&e.title===r.title&&(e.subtitle??``)===(r.subtitle??``)&&(e.badge??``)===(r.badge??``)&&e.iconName===r.iconName&&e.agentName===r.agentName}),ye=(e,t)=>e.highlightedIndex===t.highlightedIndex&&ve(e.rows,t.rows),be=(e,t)=>ve(e,t)?e:t.slice(),xe=(e,t,n)=>{e&&(t.current&&ye(t.current,n)||(t.current=n,e(n)))},Se=(e,t)=>{t.current=null,e?.({rows:[],highlightedIndex:0})},z=e(c(),1),B=g(),Ce=e=>e.directories.flatMap(e=>e.sessions),V=(e,t)=>({...re(e,t.location.hostId),select:Ce}),we=async(e,t,n)=>{n.sdk();let r=await e.fetchQuery(V(t,n));return n.sdk(),Ce(r)},H=(e,t,n,r)=>{n.sdk();let i=e.getQueryData(V(t,n).queryKey);for(let e of i?.directories??[]){let t=e.sessions.find(e=>e.id===r);if(t)return t.title||r}return r},U=(e,t,n,r={})=>({queryKey:[...e.queryScope,`composer-files`,t,n,r],staleTime:3e4,gcTime:3e4,queryFn:async({signal:i})=>{let a=await e.sdk().file.find({query:t,location:{directory:e.location.directory},limit:n,type:r.type},{signal:i});if(e.sdk(),i.throwIfAborted(),!Array.isArray(a.data))throw Error(`File search returned no data`);return a.data.map(t=>{let n=m(t.path),r=h(n);return{name:r,path:b(e.location.directory,n),relativePath:n,extension:r.includes(`.`)?r.split(`.`).pop()?.toLowerCase():void 0,isDirectory:t.type===`directory`}})}}),W=e=>{if(!e)return``;let t=e.replace(/\\/g,`/`),n=t.startsWith(`//`),r=t.replace(/\/+/g,`/`);n&&!r.startsWith(`//`)&&(r=`/${r}`);let i=r===`/`,a=/^[A-Za-z]:\/$/.test(r);return!i&&!a&&(r=r.replace(/\/+$/,``)),r},G=e=>/^[A-Za-z]:\//.test(e)?e.toLowerCase():e,K=e=>e.startsWith(`yuri-remote-location:`)?t(e):W(e),q=(e,t)=>{let r=W(n(t,`local`).directory),i=W(e);if(!r||!i)return!1;let a=G(r),o=G(i);return o===a||o.startsWith(a.endsWith(`/`)?a:`${a}/`)},J=e=>{if(!e||typeof e!=`object`)return{};let t=e,n={};for(let[e,r]of Object.entries(t)){let t;try{t=K(e)}catch{continue}if(!t||!r||typeof r!=`object`)continue;let i=r,a=Array.isArray(i.openPaths)?Array.from(new Set(i.openPaths.filter(e=>typeof e==`string`).map(e=>W(e)).filter(e=>q(e,t)))):[],o=Array.isArray(i.expandedPaths)?Array.from(new Set(i.expandedPaths.filter(e=>typeof e==`string`).map(e=>W(e)).filter(e=>q(e,t)))):[],s=typeof i.selectedPath==`string`?W(i.selectedPath):null,c=s&&q(s,t)?s:a[0]??null,l=typeof i.touchedAt==`number`&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now(),u=n[t];if(u){let e=Array.from(new Set([...u.openPaths,...a])),r=Array.from(new Set([...u.expandedPaths,...o])),i=u.selectedPath??c??e[0]??null;n[t]={openPaths:e,selectedPath:i,expandedPaths:r,touchedAt:Math.max(u.touchedAt,l)};continue}n[t]={openPaths:a,selectedPath:c,expandedPaths:o,touchedAt:l}}return n},Y=(e,t)=>{let n=Object.entries(e);if(n.length<=t)return e;n.sort((e,t)=>(t[1]?.touchedAt??0)-(e[1]?.touchedAt??0));let r={};for(let[e,i]of n.slice(0,t))r[e]=i;return r},X=e=>e?{...e,touchedAt:Date.now()}:{openPaths:[],selectedPath:null,expandedPaths:[],touchedAt:Date.now()},Z=i()(o(a((e,t)=>({byRoot:{},addOpenPath:(t,n,r)=>{let i=K((t||``).trim()),a=W((n||``).trim());!i||!a||!r?.allowOutsideRoot&&!q(a,i)||e(e=>{let t=e.byRoot[i],n=X(t),r=n.openPaths.includes(a),o=r?n.openPaths:[...n.openPaths,a],s=n.selectedPath??a;return t&&r&&t.selectedPath===s?e:{byRoot:Y({...e.byRoot,[i]:{...n,openPaths:o,selectedPath:s}},20)}})},removeOpenPath:(t,n)=>{let r=K((t||``).trim()),i=W((n||``).trim());!r||!i||e(e=>{let t=e.byRoot[r];if(!t)return e;let n=G(i),a=e=>G(e)===n,o=t.selectedPath?a(t.selectedPath):!1;if(!t.openPaths.some(a)&&!o)return e;let s=t.openPaths.filter(e=>!a(e)),c=o?s[0]??null:t.selectedPath;return{byRoot:Y({...e.byRoot,[r]:{...t,openPaths:s,selectedPath:c,touchedAt:Date.now()}},20)}})},removeOpenPathsByPrefix:(t,n)=>{let r=K((t||``).trim()),i=W((n||``).trim());!r||!i||e(e=>{let t=e.byRoot[r];if(!t)return e;let n=G(i),a=n.endsWith(`/`)?n:`${n}/`,o=e=>{let t=G(e);return t===n||t.startsWith(a)},s=t.openPaths.filter(e=>!o(e));if(s.length===t.openPaths.length)return e;let c=t.selectedPath&&o(t.selectedPath)?s[0]??null:t.selectedPath;return{byRoot:Y({...e.byRoot,[r]:{...t,openPaths:s,selectedPath:c,touchedAt:Date.now()}},20)}})},removeExpandedPathsByPrefix:(t,n)=>{let r=K((t||``).trim()),i=W((n||``).trim());!r||!i||e(e=>{let t=e.byRoot[r];if(!t)return e;let n=G(i),a=n.endsWith(`/`)?n:`${n}/`,o=t.expandedPaths.filter(e=>{let t=G(e);return t!==n&&!t.startsWith(a)});return o.length===t.expandedPaths.length?e:{byRoot:Y({...e.byRoot,[r]:{...t,expandedPaths:o,touchedAt:Date.now()}},20)}})},setSelectedPath:(t,n,r)=>{let i=K((t||``).trim()),a=n?W(n.trim()):null;!i||a&&!r?.allowOutsideRoot&&!q(a,i)||e(e=>{let t=e.byRoot[i],n=X(t),r=a&&!n.openPaths.includes(a)?[...n.openPaths,a]:n.openPaths;return t&&t.selectedPath===a&&r===t.openPaths?e:{byRoot:Y({...e.byRoot,[i]:{...n,openPaths:r,selectedPath:a}},20)}})},ensureSelectedPath:e=>{let n=K((e||``).trim());if(!n)return;let r=t().byRoot[n];if(!r||r.selectedPath)return;let i=r.openPaths[0]??null;i&&t().setSelectedPath(n,i)},toggleExpandedPath:(t,n)=>{let r=K((t||``).trim()),i=W((n||``).trim());!r||!i||!q(i,r)||e(e=>{let t=e.byRoot[r],n=X(t),a=n.expandedPaths.includes(i)?n.expandedPaths.filter(e=>e!==i):[...n.expandedPaths,i];return t&&t.expandedPaths===a&&t.selectedPath===n.selectedPath&&t.openPaths===n.openPaths?e:{byRoot:Y({...e.byRoot,[r]:{...n,expandedPaths:a}},20)}})},expandPath:(t,n)=>{let r=K((t||``).trim()),i=W((n||``).trim());!r||!i||!q(i,r)||e(e=>{let t=e.byRoot[r],n=X(t);return n.expandedPaths.includes(i)&&t?e:{byRoot:Y({...e.byRoot,[r]:{...n,expandedPaths:[...n.expandedPaths,i]}},20)}})},expandPaths:(t,n)=>{let r=K((t||``).trim());if(!r||!n||n.length===0)return;let i=n.map(e=>W((e||``).trim())).filter(e=>e&&q(e,r));i.length!==0&&e(e=>{let t=e.byRoot[r],n=X(t),a=new Set(n.expandedPaths),o=i.filter(e=>!a.has(e));return o.length===0?e:{byRoot:Y({...e.byRoot,[r]:{...n,expandedPaths:[...n.expandedPaths,...o]}},20)}})}}),{name:`files-view-tabs-store`,version:2,storage:p(),migrate:e=>{if(!e||typeof e!=`object`)return{byRoot:{}};let t=e.byRoot;return{byRoot:J(t)}},merge:(e,t)=>({...t,byRoot:J(e&&typeof e==`object`?e.byRoot:void 0)}),partialize:e=>({byRoot:J(e.byRoot)})}),{name:`files-view-tabs-store`})),Q=()=>{let e=(0,B.c)(17),t=P(Te),n=L(),r;e[0]===t?r=e[1]:(r=e=>t?e.getAttachment(t):void 0,e[0]=t,e[1]=r);let i=M(r),a=P(Ee),o=P(De),s=E(Oe),c=E(ke),u=l(Ae);if(t){let r;e[2]===i?r=e[3]:(r=j(i),e[2]=i,e[3]=r);let o=r;if(o)return o;let s;e[4]!==t||e[5]!==a?(s=a.get(t),e[4]=t,e[5]=a,e[6]=s):s=e[6];let c=s;if(c?.path)return c.path;let l;if(e[7]!==t||e[8]!==n){let r;e[10]===t?r=e[11]:(r=e=>e.id===t,e[10]=t,e[11]=r),l=n.find(r),e[7]=t,e[8]=n,e[9]=l}else l=e[9];let u=l;if(u?.directory)return u.directory}if(o?.open&&(o.bootstrapPendingDirectory||o.directoryOverride))return(o.bootstrapPendingDirectory||o.directoryOverride)??void 0;if(s){let t;if(e[12]!==s||e[13]!==c){let n;e[15]===s?n=e[16]:(n=e=>e.id===s,e[15]=s,e[16]=n),t=c.find(n),e[12]=s,e[13]=c,e[14]=t}else t=e[14];let n=t;if(n?.path)return n.path}return u??void 0};function Te(e){return e.currentSessionId}function Ee(e){return e.worktreeMetadata}function De(e){return e.newSessionDraft}function Oe(e){return e.activeProjectId}function ke(e){return e.projects}function Ae(e){return e.currentDirectory}var $=s(),je=`bg-transparent font-[inherit] text-[var(--primary-base)]`,Me=(e,t)=>{let n=t.trim().toLowerCase();if(!n)return e;let r=e.toLowerCase();if(!r.includes(n))return e;let i=[],a=0,o=r.indexOf(n);for(;o!==-1;)o>a&&i.push(e.slice(a,o)),i.push((0,$.jsx)(`mark`,{className:je,children:e.slice(o,o+n.length)},`${o}-${n}`)),a=o+n.length,o=r.indexOf(n,a);return a<e.length&&i.push(e.slice(a)),i},Ne=z.forwardRef((e,t)=>{let n=(0,B.c)(4),r=y(),i;return n[0]!==r||n[1]!==e||n[2]!==t?(i=r?.entry.location.hostId?(0,$.jsx)(Le,{...e,ref:t,entry:r.entry,registry:r.registry},JSON.stringify(r.entry.queryScope)):(0,$.jsx)(Pe,{...e,ref:t}),n[0]=r,n[1]=e,n[2]=t,n[3]=i):i=n[3],i}),Pe=z.forwardRef((e,t)=>{let n=(0,B.c)(22),r=Q()??``,i=P(ze),a=O(Be),o=!!e.onSessionSelect,s;n[0]===o?s=n[1]:(s={enabled:o},n[0]=o,n[1]=s);let c=k(s),l=E(Ve),u=E(He),f;if(n[2]!==l||n[3]!==r||n[4]!==u){let e=u.find(e=>e.id===l)?.path||r;f=e?e.replace(/\\/g,`/`).replace(/\/+$/,``):null,n[2]=l,n[3]=r,n[4]=u,n[5]=f}else f=n[5];let p=f,m;n[6]===p?m=n[7]:(m=e=>p?e.byRoot[p]:void 0,n[6]=p,n[7]=m);let h=Z(m),g=A(Ue),_=d(We),v;n[8]!==a||n[9]!==c||n[10]!==e.onSessionSelect?(v=e.onSessionSelect?I(a,c):[],n[8]=a,n[9]=c,n[10]=e.onSessionSelect,n[11]=v):v=n[11];let y=v,b=e.currentSessionId??i,x;return n[12]!==g||n[13]!==r||n[14]!==p||n[15]!==h||n[16]!==e||n[17]!==t||n[18]!==_||n[19]!==y||n[20]!==b?(x=(0,$.jsx)(Re,{...e,ref:t,currentDirectory:r,currentSessionId:b,projectRoot:p,projectTabs:h,agentCatalog:g,sessions:y,searchFiles:_}),n[12]=g,n[13]=r,n[14]=p,n[15]=h,n[16]=e,n[17]=t,n[18]=_,n[19]=y,n[20]=b,n[21]=x):x=n[21],x}),Fe=[],Ie=[],Le=z.forwardRef((e,t)=>{let n=(0,B.c)(32),{entry:r,registry:i}=e,a=v(),o;n[0]===r?o=n[1]:(o=D(r.location.directory,void 0,r),n[0]=r,n[1]=o);let s=!!e.onAgentSelect,c;n[2]!==o||n[3]!==s?(c={...o,enabled:s},n[2]=o,n[3]=s,n[4]=c):c=n[4];let l=_(c),u;n[5]!==r||n[6]!==i?(u=V(i,r),n[5]=r,n[6]=i,n[7]=u):u=n[7];let d=!!e.onSessionSelect,f;n[8]!==u||n[9]!==d?(f={...u,enabled:d},n[8]=u,n[9]=d,n[10]=f):f=n[10];let p=_(f),m;n[11]===r.key?m=n[12]:(m=e=>e.byRoot[r.key],n[11]=r.key,n[12]=m);let h=Z(m),g;n[13]!==a||n[14]!==r?(g=(e,t,n,i)=>{let o=n===void 0?60:n;return a.fetchQuery(U(r,t,o,i))},n[13]=a,n[14]=r,n[15]=g):g=n[15];let y=x(g),b=r.location.directory,S;if(n[16]!==r.location.directory){let e;n[18]===Symbol.for(`react.memo_cache_sentinel`)?(e=/\/+$/,n[18]=e):e=n[18],S=r.location.directory.replace(/\\/g,`/`).replace(e,``),n[16]=r.location.directory,n[17]=S}else S=n[17];let C=l.data??Ie,w=p.data??Fe,T=l.error??p.error,E;n[19]===r?E=n[20]:(E=()=>{r.sdk()},n[19]=r,n[20]=E);let O;return n[21]!==r.location.directory||n[22]!==h||n[23]!==e||n[24]!==t||n[25]!==y||n[26]!==C||n[27]!==w||n[28]!==T||n[29]!==E||n[30]!==S?(O=(0,$.jsx)(Re,{...e,ref:t,currentDirectory:b,projectRoot:S,projectTabs:h,agentCatalog:C,sessions:w,searchFiles:y,catalogError:T,assertCurrent:E}),n[21]=r.location.directory,n[22]=h,n[23]=e,n[24]=t,n[25]=y,n[26]=C,n[27]=w,n[28]=T,n[29]=E,n[30]=S,n[31]=O):O=n[31],O}),Re=z.forwardRef(({searchQuery:e,onFileSelect:t,onAgentSelect:n,onSkillSelect:r,onSessionSelect:i,onClose:a,style:o,onRowsChange:s,currentDirectory:c,currentSessionId:l,projectRoot:d,projectTabs:p,agentCatalog:m,sessions:h,searchFiles:g,catalogError:_,assertCurrent:v},y)=>{let{t:b}=ie(),w=oe(e,180),E=f(),D=u(),[O,k]=z.useState([]),[ee,A]=z.useState(!1),[j,M]=z.useState(null),[N,P]=z.useState(0),I=z.useRef(0),L=z.useRef({query:e,directory:c,ids:[]}),[re,le]=z.useState(360),[ue,_e]=z.useState({}),[ve,ye]=z.useState({}),be=z.useRef([]),B=z.useRef([]),Ce=z.useRef([]),V=z.useRef(null),we=z.useRef(null),H=z.useRef(null);H.current||=pe();let U=S(e=>e.isMobile),W=(e??``).trim(),G=T({directory:c||null}),K=z.useMemo(()=>r?G.data??[]:[],[r,G.data]),q=z.useMemo(()=>{if(!d||!p)return[];let e=[p.selectedPath,...p.openPaths.slice().reverse()].filter(e=>typeof e==`string`&&e.length>0),t=new Set,n=[];for(let r of e){if(t.has(r))continue;t.add(r);let e=r.replace(/\\/g,`/`),i=e.split(`/`).filter(Boolean).pop()||e,a=e.startsWith(`${d}/`)?e.slice(d.length+1):e;n.push({name:i,path:e,relativePath:a,extension:i.includes(`.`)?i.split(`.`).pop()?.toLowerCase():void 0})}return ge(n,W,{limit:6})},[W,d,p]),J=z.useMemo(()=>n?ne(m).filter(e=>e.mode!==`primary`):[],[m,n]),Y=z.useMemo(()=>i?me({sessions:h,currentSessionId:l??null,searchQuery:W}):[],[h,l,W,i]),X=q,Z=O,Q=z.useMemo(()=>ce({skills:K,agents:J,sessions:Y,recentFiles:X,pathHits:Z,searchQuery:W,untitledSession:b(`chat.fileMentionAutocomplete.untitledSession`),sessionBadge:b(`chat.fileMentionAutocomplete.sessionType`),skillBadge:b(`chat.commandAutocomplete.badge.skill`)}),[K,J,Y,X,Z,W,b]);z.useEffect(()=>{let e=e=>{let t=e.target;!t||!V.current||V.current.contains(t)||a()};return document.addEventListener(`pointerdown`,e,!0),()=>{document.removeEventListener(`pointerdown`,e,!0)}},[a]),z.useEffect(()=>{if(!c){k([]),A(!1),M(null);return}let e=(w??``).trim(),t=C(e);if(!t){k([]),A(!1),M(null);return}let n=!1;A(!0),M(null);let r={includeHidden:E,respectGitignore:!D};return Promise.all([g(c,t,80,{...r,type:`file`}),g(c,t,40,{...r,type:`directory`})]).then(([t,r])=>{if(n)return;let i=new Set(q.map(e=>e.path));k(he({files:t,directories:r,query:e,excludePaths:i,limit:20}))}).catch(e=>{n||M(e instanceof Error?e:Error(String(e)))}).finally(()=>{n||A(!1)}),()=>{n=!0}},[c,w,q,g,E,D]),z.useLayoutEffect(()=>{let t=L.current,n=t.ids[I.current],r=t.query===e&&t.directory===c?Math.max(0,Q.findIndex(e=>e.id===n)):0;L.current={query:e,directory:c,ids:Q.map(e=>e.id)},I.current=r,P(r)},[Q,e,c]),z.useEffect(()=>{_e({}),ye({})},[Q]),z.useEffect(()=>{be.current[N]?.scrollIntoView({block:`nearest`})},[N]),z.useEffect(()=>{let e=null,t=()=>{e!==null&&cancelAnimationFrame(e),e=requestAnimationFrame(()=>{let e={},t={};B.current.forEach((n,r)=>{if(!n)return;let i=Ce.current[r]?.offsetWidth??n.scrollWidth,a=Math.max(0,i-n.clientWidth),o=a>8;if(e[r]=o,o){let e=Math.max(.6,a/110);t[r]=e}}),_e(e),ye(t)})};return t(),window.addEventListener(`resize`,t),()=>{e!==null&&cancelAnimationFrame(e),window.removeEventListener(`resize`,t)}},[Q]),z.useEffect(()=>{let e=B.current[N];if(!e)return;let t=()=>{let t=e.clientWidth;t>0&&le(t)};if(t(),typeof ResizeObserver>`u`)return;let n=new ResizeObserver(t);return n.observe(e),()=>{n.disconnect()}},[N]);let Te=x(e=>{t(e)}),Ee=x(e=>{n?.(e)}),De=x(e=>{i?.(e)}),Oe=x(e=>{r?.(e)}),ke=(e,t)=>({onMouseDown:e=>e.preventDefault(),onPointerDown:e=>{e.pointerType===`touch`&&H.current?.pointerDown(e.clientX,e.clientY)},onPointerMove:e=>{e.pointerType===`touch`&&H.current?.pointerMove(e.clientX,e.clientY)},onPointerUp:e=>{e.pointerType===`touch`&&(H.current?.pointerUp(t)??!1)&&(e.preventDefault(),e.stopPropagation())},onPointerCancel:()=>H.current?.pointerCancel(),onClick:()=>{H.current?.click(t)},onMouseMove:()=>{I.current=e,P(e)}}),Ae=e=>{try{v?.()}catch(e){M(e instanceof Error?e:Error(String(e)));return}let t=Q.length;if(t===0)return;let n=(e%t+t)%t,r=Q[n];if(r.agentName!==void 0){Ee(r.agentName);return}if(r.id.startsWith(`skill:`)){let e=K.find(e=>r.id===`skill:${e.name}-${e.scope}`);e&&Oe(e);return}if(r.id.startsWith(`session:`)){let e=Y.find(e=>r.id===`session:${e.id}`);e&&De(e);return}let i=r.id.startsWith(`recent:`)?X.find(e=>r.id===`recent:${e.path}`):Z.find(e=>r.id===`file:${e.path}`);i&&Te(i)};z.useEffect(()=>{xe(s,we,{rows:Q,highlightedIndex:N})},[s,N,Q]);let je=z.useRef(s);return je.current=s,z.useEffect(()=>()=>{Se(je.current,we)},[]),z.useImperativeHandle(y,()=>({acceptIndex:e=>{Ae(e)},handleKeyDown:e=>{if(e===`Escape`){a();return}let t=Q.length;if(t!==0){if(e===`ArrowDown`){I.current=(I.current+1)%t,P(I.current);return}if(e===`ArrowUp`){I.current=(I.current-1+t)%t,P(I.current);return}(e===`Enter`||e===`Tab`)&&Ae(I.current)}}})),(0,$.jsxs)(de,{ref:V,isMobile:U,className:`max-w-[640px] max-h-64`,style:o,children:[(0,$.jsx)(ae,{preventOverscroll:!0,outerClassName:`flex-1 min-h-0`,className:`px-0`,children:(0,$.jsxs)(`div`,{className:`py-1`,children:[_||G.error||j?(0,$.jsx)(`div`,{role:`alert`,className:`px-3 py-2 typography-ui-label text-muted-foreground`,children:(_??G.error??j)?.message}):null,Q.map((e,t)=>{let n=e.id.startsWith(`file:`)||e.id.startsWith(`recent:`),r=n?te(e.title,{maxLength:60}):e.title,i=N===t,a=ue[t]??!1,o=ve[t]??2.6;return(0,$.jsxs)(`div`,{"data-mention-id":e.id,ref:e=>{be.current[t]=e},className:F(`flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg`,U&&`min-h-11`,fe(U,i),!U&&i&&`text-interactive-selection-foreground`),...ke(t,()=>Ae(t)),children:[(0,$.jsx)(`span`,{className:`flex size-5 shrink-0 items-center justify-center`,children:e.agentName===void 0?(0,$.jsx)(R,{name:e.iconName,className:`size-3.5 text-current`}):(0,$.jsx)(se,{name:e.agentName,size:20})}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-baseline gap-2`,children:[(0,$.jsxs)(`span`,{ref:e=>{B.current[t]=e},className:F(`relative block min-w-0 overflow-hidden`,n&&a&&i&&`file-mention-marquee-container`),style:i?{"--file-mention-marquee-width":`${re}px`,"--file-mention-marquee-duration":`${o}s`}:void 0,title:e.title,children:[(0,$.jsx)(`span`,{ref:e=>{Ce.current[t]=e},className:`absolute invisible whitespace-nowrap pointer-events-none`,"aria-hidden":!0,children:e.title}),n&&a&&i?(0,$.jsx)(`span`,{className:`inline-block whitespace-nowrap file-mention-marquee`,children:Me(e.title,W)}):(0,$.jsx)(`span`,{className:`block truncate`,children:Me(r,W)})]}),e.trailingLabel?(0,$.jsx)(`span`,{className:F(`max-w-[40%] shrink-0 truncate text-muted-foreground`,U?`typography-micro`:`typography-meta`),children:e.trailingLabel}):null]}),e.subtitle?(0,$.jsx)(`div`,{className:F(`truncate text-muted-foreground`,U?`typography-micro`:`typography-meta`),children:Me(e.subtitle,W)}):null]})]},e.id)}),ee&&Z.length===0?(0,$.jsx)(`div`,{className:`flex items-center justify-center py-3`,children:(0,$.jsx)(R,{name:`refresh`,className:`h-4 w-4 animate-spin text-muted-foreground`})}):null,!ee&&Q.length===0&&(0,$.jsx)(`div`,{className:`px-3 py-2 typography-ui-label text-muted-foreground`,children:b(`chat.fileMentionAutocomplete.empty`)})]})}),!U&&(0,$.jsx)(`div`,{className:`px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground`,children:b(`chat.autocomplete.keyboardHint`)})]})});function ze(e){return e.currentSessionId}function Be(e){return e.activeSessions}function Ve(e){return e.activeProjectId}function He(e){return e.projects}function Ue(e){return e.agents}function We(e){return e.searchFiles}var Ge=new Set([`new`,`fork`,`compact`,`reload`,`undo`,`redo`,`model`,`btw`]),Ke=(e,t)=>{if(!t||e.isSkill)return!1;let n=e.name?.trim().toLowerCase();return!!(n&&Ge.has(n))},qe=(e,t)=>!e||t({name:e}),Je=` `,Ye=(e,t)=>{let n=Math.max(0,Math.min(t,e.length)),r=n;for(;r>0&&!/\s/.test(e[r-1]);)--r;return r>=2&&e[r-1]===Je&&e[r-2]===`/`&&(r-=2),e[r]===`/`?{start:r,end:n}:null},Xe=`text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0`,Ze=F(Xe,`bg-[color-mix(in_srgb,var(--primary-base)_12%,transparent)] text-[color-mix(in_srgb,var(--primary-base)_70%,transparent)] border-[color-mix(in_srgb,var(--primary-base)_24%,transparent)]`),Qe=F(Xe,`bg-[color-mix(in_srgb,var(--status-success)_12%,transparent)] text-[color-mix(in_srgb,var(--status-success)_70%,transparent)] border-[color-mix(in_srgb,var(--status-success)_24%,transparent)]`),$e=F(Xe,`bg-[color-mix(in_srgb,var(--status-info)_12%,transparent)] text-[color-mix(in_srgb,var(--status-info)_70%,transparent)] border-[color-mix(in_srgb,var(--status-info)_24%,transparent)]`),et=F(Xe,`bg-[var(--surface-muted)] text-muted-foreground border-[var(--interactive-border)]/60`),tt=(e,t)=>e.length===t.length&&e.every((e,n)=>e.id===t[n]?.id&&e.description===t[n]?.description),nt=e=>{let t=!!e.sessionID;return{hasSession:t,canStartSessionCommand:t||e.hasNewDraft}},rt=z.forwardRef(({searchQuery:e,onCommandSelect:t,onClose:n,directory:i,style:a,commandPolicy:o,commandContext:s,onRowsChange:c},l)=>{let{t:u}=ie(),d=S(e=>e.isMobile),f=P(e=>e.currentSessionId),p=P(e=>!!e.newSessionDraft?.open),m=P(z.useCallback(e=>f?e.getDirectoryForSession(f):void 0,[f])),h=N(f??``,m??void 0),g=z.useMemo(()=>s??{sessionID:f??null,hasMessages:h.length>0,hasNewDraft:p},[s,f,h.length,p]),{hasSession:_,canStartSessionCommand:v}=z.useMemo(()=>nt(g),[g]),y=g.hasMessages,[b,x]=z.useState([]),[C,w]=z.useState(!1),T=ee({directory:i}),E=z.useMemo(()=>T.data??[],[T.data]),D=T.isFetching,[O,k]=z.useState(0),A=z.useRef(0),j=z.useRef(!1),M=z.useRef([]),te=z.useRef(null),ne=z.useRef(!1),I=z.useRef(null),L=z.useRef(!1),re=z.useRef(null);z.useEffect(()=>{let e=e=>{let t=e.target;!t||!te.current||te.current.contains(t)||n()};return document.addEventListener(`pointerdown`,e,!0),()=>{document.removeEventListener(`pointerdown`,e,!0)}},[n]),z.useEffect(()=>{(async()=>{w(D);try{let t=E.flatMap((e,t)=>e.source===`skill`?[]:[{id:`opencode:${e.scope??`global`}:${e.name}:${e.agent??``}:${e.model??``}:${t}`,name:e.name,source:`opencode`,description:e.description,agent:e.agent??void 0,model:e.model??void 0,isBuiltIn:e.isBuiltIn,scope:e.scope,reference:e.reference}]),n=[{id:`yuri:new`,name:`new`,source:`yuri`,description:u(`chat.commandAutocomplete.command.newDescription`),isBuiltIn:!0},..._&&!y?[{id:`yuri:init`,name:`init`,source:`yuri`,description:u(`chat.commandAutocomplete.command.initDescription`),isBuiltIn:!0}]:[],..._?[{id:`yuri:btw`,name:`btw`,source:`yuri`,description:u(`chat.btw.description`),isBuiltIn:!0},{id:`yuri:undo`,name:`undo`,source:`yuri`,description:u(`chat.commandAutocomplete.command.undoDescription`),isBuiltIn:!0},{id:`yuri:redo`,name:`redo`,source:`yuri`,description:u(`chat.commandAutocomplete.command.redoDescription`),isBuiltIn:!0},{id:`yuri:fork`,name:`fork`,source:`yuri`,description:u(`chat.commandAutocomplete.command.forkDescription`),isBuiltIn:!0},{id:`yuri:timeline`,name:`timeline`,source:`yuri`,description:u(`chat.commandAutocomplete.command.timelineDescription`),isBuiltIn:!0}]:[],{id:`yuri:model`,name:`model`,source:`yuri`,description:u(`chat.commandAutocomplete.command.modelDescription`),isBuiltIn:!0},{id:`yuri:compact`,name:`compact`,source:`yuri`,description:u(`chat.commandAutocomplete.command.compactDescription`),isBuiltIn:!0},...r()?[{id:`yuri:reload`,name:`reload`,source:`yuri`,description:u(`chat.commandAutocomplete.command.reloadDescription`),isBuiltIn:!0}]:[],..._?[{id:`yuri:summary`,name:`summary`,source:`yuri`,description:u(`chat.commandAutocomplete.command.summaryDescription`),isYuri:!0}]:[],...v?[{id:`yuri:workspace-review`,name:`workspace-review`,source:`yuri`,description:u(`chat.commandAutocomplete.command.workspaceReviewDescription`),isYuri:!0}]:[],...v?[{id:`yuri:craft-goal`,name:`craft-goal`,source:`yuri`,description:u(`chat.commandAutocomplete.command.craftGoalDescription`),isYuri:!0}]:[],...v?[{id:`yuri:catch-up`,name:`catch-up`,source:`yuri`,description:u(`chat.commandAutocomplete.command.catchUpDescription`),isYuri:!0}]:[],...v?[{id:`yuri:debug`,name:`debug`,source:`yuri`,description:u(`chat.commandAutocomplete.command.debugDescription`),isYuri:!0}]:[],...v?[{id:`yuri:weigh`,name:`weigh`,source:`yuri`,description:u(`chat.commandAutocomplete.command.weighDescription`),isYuri:!0}]:[],...v?[{id:`yuri:explore`,name:`explore`,source:`yuri`,description:u(`chat.commandAutocomplete.command.exploreDescription`),isYuri:!0}]:[],...t],i=!y,a=_e(n.filter(e=>(i||e.name!==`init`)&&(o?.(e)??!0)),e);x(e=>tt(e,a)?e:a)}catch{let t=!y,n=_e([{id:`yuri:new`,name:`new`,source:`yuri`,description:u(`chat.commandAutocomplete.command.newDescription`),isBuiltIn:!0},..._&&!y?[{id:`yuri:init`,name:`init`,source:`yuri`,description:u(`chat.commandAutocomplete.command.initDescription`),isBuiltIn:!0}]:[],..._?[{id:`yuri:btw`,name:`btw`,source:`yuri`,description:u(`chat.btw.description`),isBuiltIn:!0},{id:`yuri:undo`,name:`undo`,source:`yuri`,description:u(`chat.commandAutocomplete.command.undoDescription`),isBuiltIn:!0},{id:`yuri:redo`,name:`redo`,source:`yuri`,description:u(`chat.commandAutocomplete.command.redoDescription`),isBuiltIn:!0},{id:`yuri:fork`,name:`fork`,source:`yuri`,description:u(`chat.commandAutocomplete.command.forkDescription`),isBuiltIn:!0},{id:`yuri:timeline`,name:`timeline`,source:`yuri`,description:u(`chat.commandAutocomplete.command.timelineDescription`),isBuiltIn:!0}]:[],{id:`yuri:model`,name:`model`,source:`yuri`,description:u(`chat.commandAutocomplete.command.modelDescription`),isBuiltIn:!0},{id:`yuri:compact`,name:`compact`,source:`yuri`,description:u(`chat.commandAutocomplete.command.compactDescription`),isBuiltIn:!0},...r()?[{id:`yuri:reload`,name:`reload`,source:`yuri`,description:u(`chat.commandAutocomplete.command.reloadDescription`),isBuiltIn:!0}]:[],..._?[{id:`yuri:summary`,name:`summary`,source:`yuri`,description:u(`chat.commandAutocomplete.command.summaryDescription`),isYuri:!0}]:[],...v?[{id:`yuri:workspace-review`,name:`workspace-review`,source:`yuri`,description:u(`chat.commandAutocomplete.command.workspaceReviewDescription`),isYuri:!0}]:[],...v?[{id:`yuri:craft-goal`,name:`craft-goal`,source:`yuri`,description:u(`chat.commandAutocomplete.command.craftGoalDescription`),isYuri:!0}]:[],...v?[{id:`yuri:catch-up`,name:`catch-up`,source:`yuri`,description:u(`chat.commandAutocomplete.command.catchUpDescription`),isYuri:!0}]:[],...v?[{id:`yuri:debug`,name:`debug`,source:`yuri`,description:u(`chat.commandAutocomplete.command.debugDescription`),isYuri:!0}]:[],...v?[{id:`yuri:weigh`,name:`weigh`,source:`yuri`,description:u(`chat.commandAutocomplete.command.weighDescription`),isYuri:!0}]:[],...v?[{id:`yuri:explore`,name:`explore`,source:`yuri`,description:u(`chat.commandAutocomplete.command.exploreDescription`),isYuri:!0}]:[]].filter(e=>(t||e.name!==`init`)&&(o?.(e)??!0)),e);x(e=>tt(e,n)?e:n)}finally{w(!1)}})()},[e,y,_,v,E,D,u,o]),z.useEffect(()=>{k(0)},[b]),z.useEffect(()=>{A.current=O},[O]),z.useEffect(()=>{M.current[O]?.scrollIntoView({block:`nearest`})},[O]),z.useEffect(()=>{xe(c,re,{rows:ue(b,{skill:u(`chat.commandAutocomplete.badge.skill`),command:u(`chat.commandAutocomplete.badge.command`),system:u(`chat.commandAutocomplete.badge.system`)}),highlightedIndex:O})},[b,c,O,u]);let oe=z.useRef(c);oe.current=c,z.useEffect(()=>()=>{Se(oe.current,re)},[]),z.useImperativeHandle(l,()=>({acceptIndex:(e,n=!0)=>{let r=b[e];r&&t(r,Ke(r,n))},handleKeyDown:e=>{let r=b.length;if(e===`Escape`){n();return}if(r!==0){if(e===`ArrowDown`){j.current=!0,k(e=>(e+1)%r);return}if(e===`ArrowUp`){j.current=!0,k(e=>(e-1+r)%r);return}if(e===`Enter`||e===`Tab`){let n=(A.current%r+r)%r,i=b[n];i&&t(i,Ke(i,e===`Enter`))}}}}),[b,n,t]);let se=e=>{let t=le(e);switch(e.name){case`new`:return(0,$.jsx)(R,{name:t,className:`h-3.5 w-3.5`});case`init`:return(0,$.jsx)(R,{name:t,className:`h-3.5 w-3.5 text-green-500`});case`undo`:return(0,$.jsx)(R,{name:t,className:`h-3.5 w-3.5 text-orange-500`});case`redo`:return(0,$.jsx)(R,{name:t,className:`h-3.5 w-3.5 text-orange-500`});case`timeline`:case`reload`:return(0,$.jsx)(R,{name:t,className:`h-3.5 w-3.5`});case`compact`:return(0,$.jsx)(R,{name:t,className:`h-3.5 w-3.5 text-purple-500`});case`goal`:return(0,$.jsx)(R,{name:t,className:`h-3.5 w-3.5`});case`review`:return(0,$.jsx)(R,{name:t,className:`h-3.5 w-3.5 text-blue-500`});case`test`:case`build`:case`run`:return(0,$.jsx)(R,{name:t,className:`h-3.5 w-3.5 text-cyan-500`});default:return e.isBuiltIn?(0,$.jsx)(R,{name:t,className:`h-3.5 w-3.5 text-yellow-500`}):(0,$.jsx)(R,{name:t,className:`h-3.5 w-3.5 text-muted-foreground`})}};return(0,$.jsxs)(de,{ref:te,isMobile:d,className:`max-w-[450px] max-h-64`,style:a,children:[(0,$.jsx)(ae,{preventOverscroll:!0,outerClassName:`flex-1 min-h-0`,className:`px-0 py-1.5`,children:C?(0,$.jsx)(`div`,{className:`flex items-center justify-center py-4`,children:(0,$.jsx)(R,{name:`refresh`,className:`h-4 w-4 animate-spin text-muted-foreground`})}):(0,$.jsxs)(`div`,{children:[b.map((n,r)=>{let i=n.isBuiltIn,a=n.isYuri;return(0,$.jsxs)(`div`,{ref:e=>{M.current[r]=e},className:F(`flex gap-2 px-2 py-2 cursor-pointer rounded-lg`,d?`items-center`:`items-start`,fe(d,r===O),!d&&r===O&&`bg-interactive-selection/35`),onMouseDown:e=>e.preventDefault(),onPointerDown:e=>{e.pointerType===`touch`&&(I.current={x:e.clientX,y:e.clientY},L.current=!1)},onPointerMove:e=>{if(e.pointerType!==`touch`||!I.current)return;let t=e.clientX-I.current.x,n=e.clientY-I.current.y;Math.hypot(t,n)>6&&(L.current=!0)},onPointerUp:e=>{if(e.pointerType!==`touch`)return;let r=L.current;I.current=null,L.current=!1,!r&&(e.preventDefault(),e.stopPropagation(),ne.current=!0,t(n,Ke(n,d)))},onPointerCancel:()=>{I.current=null,L.current=!1},onClick:()=>{if(ne.current){ne.current=!1;return}t(n,Ke(n,d))},onMouseMove:()=>{j.current=!1,k(r)},children:[(0,$.jsx)(`div`,{className:F(!d&&`mt-0.5`),children:se(n)}),(0,$.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsxs)(`span`,{className:`typography-ui-label font-medium`,children:[`/`,Me(n.name,e)]}),n.isSkill?(0,$.jsx)(`span`,{className:Ze,children:u(`chat.commandAutocomplete.badge.skill`)}):(0,$.jsx)(`span`,{className:Ze,children:u(`chat.commandAutocomplete.badge.command`)}),a?(0,$.jsx)(`span`,{className:et,children:`Yuri`}):i?(0,$.jsx)(`span`,{className:et,children:u(`chat.commandAutocomplete.badge.system`)}):n.scope?(0,$.jsx)(`span`,{className:n.scope===`project`?$e:Qe,children:n.scope}):null,n.agent&&(0,$.jsx)(`span`,{className:et,children:n.agent})]}),n.description&&!d&&(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground mt-0.5 truncate`,children:Me(n.description,e)})]})]},n.id)}),b.length===0&&(0,$.jsx)(`div`,{className:`px-3 py-2 typography-ui-label text-muted-foreground`,children:u(`chat.commandAutocomplete.empty`)})]})}),!d&&(0,$.jsx)(`div`,{className:`px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground`,children:u(`chat.autocomplete.keyboardHint`)})]})});rt.displayName=`CommandAutocomplete`;var it=(e,t,n)=>{if(!e)return e;let r=t.length>0&&!/\s$/.test(t)&&!/^\s/.test(e)&&!/[([{]$/.test(t),i=n.length>0&&!/\s$/.test(e)&&!/^\s/.test(n)&&!/^[\])}.,;:!?]/.test(n);return`${r?` `:``}${e}${i?` `:``}`},at=(e,t,n)=>{let r=it(e,t,n);return`${t.length===0&&!/^\s/.test(r)?` `:``}${r}${n.length===0&&!/\s$/.test(r)?` `:``}`},ot=(e,t,n,r)=>{let i=e.slice(0,t),a=e.slice(n),o=at(r,i,a),s=Math.max(0,o.indexOf(r)),c=i.length+s;return{text:`${i}${o}${a}`,caret:i.length+o.length,start:c,end:c+r.length}},st=(e,t)=>{let n=e=>`${e.kind}:${e.value}:${e.range.start}:${e.range.end}`;return new Set(e.map(n)).has(n(t))||e.some(e=>e.range.start<t.range.end&&t.range.start<e.range.end)?[...e]:[...e,t]},ct=(e,t)=>t<e.length&&e[t]===` `?t+1:t;export{rt as a,Ne as c,we as d,H as f,at as i,Q as l,st as n,Ye as o,be as p,ot as r,qe as s,ct as t,Z as u};