@pi-chamber/web 1.0.4-rc.1 → 1.0.4-rc.4

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 (168) hide show
  1. package/dist/assets/DiagramView--BGR3PRZ.js +1 -0
  2. package/dist/assets/{DiffView-BjWUdbL5.js → DiffView-hz90_htv.js} +5 -5
  3. package/dist/assets/FileSaveConflictDialog-CcrWHRvd.js +3 -0
  4. package/dist/assets/{FilesView-qP1ypN9J.js → FilesView-DaqkPMqx.js} +4 -4
  5. package/dist/assets/{GitHubDetailScaffold-zCKCy5OJ.js → GitHubDetailScaffold-BZhP67Va.js} +2 -2
  6. package/dist/assets/GitHubLinkPicker-CJZmDljp.js +1 -0
  7. package/dist/assets/{GitHubListPrimitives-Ck3zllel.js → GitHubListPrimitives-DhF42guB.js} +1 -1
  8. package/dist/assets/{GitView-y2k2i4gR.js → GitView-JK-QCK9R.js} +4 -4
  9. package/dist/assets/{IssuesSurface-HWgR87N3.js → IssuesSurface-CAqQzrsv.js} +3 -3
  10. package/dist/assets/{JsonTreeView-DSuC4naV.js → JsonTreeView-CKTqB1CD.js} +1 -1
  11. package/dist/assets/MarkdownRendererImpl-B5kJy9Nt.js +12 -0
  12. package/dist/assets/{PatchDiff-DArTeWeK.js → PatchDiff-BQnRFN30.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-DQKujzLb.js → PierreDiffViewer-BeGpdI0x.js} +2 -2
  14. package/dist/assets/PullRequestsSurface-D9beq2x9.js +2 -0
  15. package/dist/assets/SessionSwitcherContent-DElQ_cjm.js +1 -0
  16. package/dist/assets/SessionSwitcherDropdown-JaIDcDIj.js +2 -0
  17. package/dist/assets/SessionUnreadDot-Czfvjbdi.js +1 -0
  18. package/dist/assets/SettingsView-C_GC1Mx3.js +6 -0
  19. package/dist/assets/SettingsWindow-CAxKgYOu.js +1 -0
  20. package/dist/assets/ToolOutputDialog-lz5exVQ4.js +8 -0
  21. package/dist/assets/ToolPartDiffPreview-nIUiNLpP.js +1 -0
  22. package/dist/assets/{VirtualizedFileDiff-D6KbvKc6.js → VirtualizedFileDiff-IWqCJNXu.js} +1 -1
  23. package/dist/assets/{Virtualizer-wpC51ZBQ.js → Virtualizer-Cp_cJWbI.js} +1 -1
  24. package/dist/assets/{collapsible-DhV9d4dT.js → collapsible-C7oyikVm.js} +1 -1
  25. package/dist/assets/{computeVirtualFileMetrics-CeMpF2xC.js → computeVirtualFileMetrics-CyhUKEfv.js} +1 -1
  26. package/dist/assets/{contextFileOpenGuard-Ck5u_kAP.js → contextFileOpenGuard-DkjmJ-NU.js} +1 -1
  27. package/dist/assets/{gitStatusPredicates-DEBSqUNE.js → gitStatusPredicates-DBmUY3kA.js} +1 -1
  28. package/dist/assets/{githubLink-DT7i2NlH.js → githubLink-BdbPMMAK.js} +5 -5
  29. package/dist/assets/index-BnZVqcki.js +11 -0
  30. package/dist/assets/index-BnieExes.css +1 -0
  31. package/dist/assets/index-CKgYIOis.js +1 -0
  32. package/dist/assets/{main-BczEScAA.js → main-6YKi4QM2.js} +2 -2
  33. package/dist/assets/{main-CHLNMYeJ.js → main-CWdWdhdL.js} +8 -8
  34. package/dist/assets/{markdownCore-C4Gk5Zht.js → markdownCore-D7V46WY9.js} +1 -1
  35. package/dist/assets/miniChat-PanPmbEK.js +2 -0
  36. package/dist/assets/mobile-0LY-2fxw.js +2 -0
  37. package/dist/assets/nativeFileSave-BzhtrDoD.js +1 -0
  38. package/dist/assets/{pi-session-focus-preference-LDVCJ_YR.js → pi-session-focus-preference-BC-ze1oC.js} +4 -4
  39. package/dist/assets/{renderDiffWithHighlighter-CDsgOnkH.js → renderDiffWithHighlighter-ByZtK9za.js} +1 -1
  40. package/dist/assets/renderElectronMiniChatApp-DETQLjFi.js +2 -0
  41. package/dist/assets/{renderFileWithHighlighter-TpKRyfCY.js → renderFileWithHighlighter-CnN0Tv_8.js} +1 -1
  42. package/dist/assets/renderMobileApp-DS0FDQLg.js +11 -0
  43. package/dist/assets/runtimeEndpointReset-BqqXMwE9.js +62 -0
  44. package/dist/assets/{runtimeSurface-DW_Ia4q3.js → runtimeSurface-DBiUWYK2.js} +1 -1
  45. package/dist/assets/useAppFontEffects-BisjofNZ.js +212 -0
  46. package/dist/assets/{useFilesViewSearch-C_LzYIgD.js → useFilesViewSearch-BWABG6pS.js} +3 -3
  47. package/dist/assets/{useGitHubRemoteSearch-DsxWOzKZ.js → useGitHubRemoteSearch-Bsf2YeQP.js} +1 -1
  48. package/dist/assets/{useSwitcherItems-BmoCnS9W.js → useSwitcherItems-BSTSev5C.js} +1 -1
  49. package/dist/assets/vendor-aparajita-capacitor-secure-storage-BYohCVY0.js +1 -0
  50. package/dist/assets/{vendor-base-ui-DIkTOIJS.js → vendor-base-ui-BscvGUFt.js} +1 -1
  51. package/dist/assets/vendor-boot-Dgb9NVFe.js +69 -0
  52. package/dist/assets/vendor-capacitor-app-BjdQVib9.js +1 -0
  53. package/dist/assets/vendor-capacitor-keyboard-eTtI5go3.js +1 -0
  54. package/dist/assets/vendor-capacitor-push-notifications-CBKq2Arn.js +1 -0
  55. package/dist/assets/vendor-capacitor-status-bar-9rNIGxlO.js +1 -0
  56. package/dist/assets/{vendor-codemirror-autocomplete-DsFn4GLp.js → vendor-codemirror-autocomplete-DxS3jwvE.js} +1 -1
  57. package/dist/assets/{vendor-codemirror-lang-angular-B_NMmBbS.js → vendor-codemirror-lang-angular-DdjXl9e2.js} +1 -1
  58. package/dist/assets/vendor-codemirror-lang-cpp--aMr7NVt.js +1 -0
  59. package/dist/assets/vendor-codemirror-lang-css-CZ_qxZY9.js +1 -0
  60. package/dist/assets/{vendor-codemirror-lang-go-C2KHbcll.js → vendor-codemirror-lang-go-Ca-y2Alu.js} +2 -2
  61. package/dist/assets/vendor-codemirror-lang-html-COZ0L5wT.js +1 -0
  62. package/dist/assets/vendor-codemirror-lang-java-D3Rf3QNJ.js +1 -0
  63. package/dist/assets/{vendor-codemirror-lang-javascript-DpTUrvx8.js → vendor-codemirror-lang-javascript-DwJ-IvCs.js} +2 -2
  64. package/dist/assets/vendor-codemirror-lang-jinja-D_5lod6k.js +1 -0
  65. package/dist/assets/vendor-codemirror-lang-json-BG8C7OpC.js +1 -0
  66. package/dist/assets/vendor-codemirror-lang-less-CVEkoaTw.js +1 -0
  67. package/dist/assets/vendor-codemirror-lang-liquid-U9vj0m8w.js +1 -0
  68. package/dist/assets/vendor-codemirror-lang-markdown-DqlYH9gY.js +1 -0
  69. package/dist/assets/vendor-codemirror-lang-php-BFEiEVA1.js +1 -0
  70. package/dist/assets/vendor-codemirror-lang-python-Cz1dQXQd.js +3 -0
  71. package/dist/assets/vendor-codemirror-lang-rust-C_CoD9mj.js +1 -0
  72. package/dist/assets/vendor-codemirror-lang-sass-BuR0aKh5.js +1 -0
  73. package/dist/assets/{vendor-codemirror-lang-sql-C_RazIaB.js → vendor-codemirror-lang-sql-DggNUjdM.js} +2 -2
  74. package/dist/assets/{vendor-codemirror-lang-vue-BYL0r7KR.js → vendor-codemirror-lang-vue-DFZHi2J3.js} +1 -1
  75. package/dist/assets/vendor-codemirror-lang-wast-zuTN3SHT.js +1 -0
  76. package/dist/assets/vendor-codemirror-lang-xml-CrcvhI-k.js +1 -0
  77. package/dist/assets/vendor-codemirror-lang-yaml-DcVWsakb.js +1 -0
  78. package/dist/assets/{vendor-codemirror-language-data-DglcKYWT.js → vendor-codemirror-language-data-CCLITgCF.js} +2 -2
  79. package/dist/assets/{vendor-codemirror-search-DaE6R5gH.js → vendor-codemirror-search-H7NOEdbX.js} +2 -2
  80. package/dist/assets/{vendor-lezer-cpp-Dt99h3WT.js → vendor-lezer-cpp-C8aD2KAr.js} +1 -1
  81. package/dist/assets/{vendor-lezer-css-DNU_fzPI.js → vendor-lezer-css-2lbTJF-Y.js} +1 -1
  82. package/dist/assets/{vendor-lezer-go-BEFtcNyS.js → vendor-lezer-go-Bw6LFTrZ.js} +1 -1
  83. package/dist/assets/{vendor-lezer-html-DDGRhRUz.js → vendor-lezer-html-D7ym2z7S.js} +1 -1
  84. package/dist/assets/{vendor-lezer-java-DmfZtW09.js → vendor-lezer-java-CZhK7w21.js} +1 -1
  85. package/dist/assets/{vendor-lezer-javascript-oje4tdp_.js → vendor-lezer-javascript-rpKeTHZp.js} +1 -1
  86. package/dist/assets/{vendor-lezer-json-BRXb_bDX.js → vendor-lezer-json-C7jwsd2G.js} +1 -1
  87. package/dist/assets/{vendor-lezer-lr-BU2qmu_5.js → vendor-lezer-lr-DR-ylqNN.js} +1 -1
  88. package/dist/assets/{vendor-lezer-markdown-CicYv7V9.js → vendor-lezer-markdown-Bir0m5nB.js} +1 -1
  89. package/dist/assets/{vendor-lezer-php-COORrTpE.js → vendor-lezer-php-y0hIEfo1.js} +1 -1
  90. package/dist/assets/{vendor-lezer-python-Cuvm9X9Y.js → vendor-lezer-python-D64A9lNV.js} +1 -1
  91. package/dist/assets/{vendor-lezer-rust-C_zOfHbX.js → vendor-lezer-rust-E3ZA9T2L.js} +1 -1
  92. package/dist/assets/{vendor-lezer-sass-DWP4w7O1.js → vendor-lezer-sass-C5UFI9SP.js} +1 -1
  93. package/dist/assets/{vendor-lezer-xml-Br6nOYeG.js → vendor-lezer-xml-DOy7FzCR.js} +1 -1
  94. package/dist/assets/{vendor-lezer-yaml-CYQmm6Sb.js → vendor-lezer-yaml-kEjaSCvZ.js} +1 -1
  95. package/dist/assets/{vendor-replit-codemirror-vim-CZy3BUVv.js → vendor-replit-codemirror-vim-BLfh0LPy.js} +1 -1
  96. package/dist/assets/{web-components-CH3-XV-n.js → web-components-CdMfsnXE.js} +1 -1
  97. package/dist/index.html +4 -4
  98. package/dist/mini-chat.html +3 -3
  99. package/dist/mobile.html +3 -3
  100. package/package.json +2 -2
  101. package/server/lib/pi/routes.js +1 -0
  102. package/server/lib/pi/session-daemon/DOCUMENTATION.md +22 -9
  103. package/server/lib/pi/session-daemon/builtin-extensions.js +37 -0
  104. package/server/lib/pi/session-daemon/daemon-process.js +6 -0
  105. package/server/lib/pi/session-daemon/extension-theme.js +75 -0
  106. package/server/lib/pi/session-daemon/extension-theme.test.js +47 -0
  107. package/server/lib/pi/session-daemon/prompt-operations.test.js +3 -3
  108. package/server/lib/pi/session-daemon/prompt-preflight.test.js +12 -14
  109. package/server/lib/pi/session-daemon/sdk-upgrade.test.js +118 -2
  110. package/server/lib/pi/session-daemon/send-operation-dedup.test.js +1 -1
  111. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +1 -1
  112. package/server/lib/pi/session-daemon/session-daemon-mcp.e2e.test.js +638 -0
  113. package/server/lib/pi/session-daemon/session-daemon-turn.e2e.test.js +437 -0
  114. package/server/lib/pi/session-daemon/session-daemon.js +61 -42
  115. package/server/lib/pi/session-daemon/session-daemon.test.js +53 -5
  116. package/server/lib/pi/session-daemon/session-idle-residency.test.js +1 -1
  117. package/server/lib/pi/session-daemon/session-replay.test.js +1 -1
  118. package/server/lib/pi/session-daemon/supervisor.js +13 -1
  119. package/server/lib/pi/session-daemon/supervisor.test.js +92 -0
  120. package/server/lib/pi/session-persistence-gap.test.js +2 -3
  121. package/server/lib/pi/ui-settings-store.js +1 -0
  122. package/server/lib/pi/ui-settings-store.test.js +27 -0
  123. package/server/lib/relay/DOCUMENTATION.md +4 -0
  124. package/server/lib/terminal/DOCUMENTATION.md +1 -0
  125. package/dist/assets/DiagramView-DfZMQkXY.js +0 -1
  126. package/dist/assets/FileSaveConflictDialog-u5L4k_5k.js +0 -3
  127. package/dist/assets/GitHubLinkPicker-CwxKY3lN.js +0 -1
  128. package/dist/assets/MarkdownRendererImpl-CT5ln9em.js +0 -12
  129. package/dist/assets/PullRequestsSurface-Cfb1wSvC.js +0 -2
  130. package/dist/assets/SessionSwitcherContent-DEGJyZBl.js +0 -1
  131. package/dist/assets/SessionSwitcherDropdown-cC9wVBH7.js +0 -2
  132. package/dist/assets/SessionUnreadDot-CELKNVIM.js +0 -1
  133. package/dist/assets/SettingsView-CZvRRgJe.js +0 -6
  134. package/dist/assets/SettingsWindow-CZM1dmVb.js +0 -1
  135. package/dist/assets/ToolOutputDialog-DClOSbJc.js +0 -8
  136. package/dist/assets/ToolPartDiffPreview-BaFiGUDE.js +0 -1
  137. package/dist/assets/index-6IO1AcJI.js +0 -10
  138. package/dist/assets/index-BAmzAlNx.css +0 -1
  139. package/dist/assets/index-eDf4LKLY.js +0 -1
  140. package/dist/assets/miniChat-Do3hE87Z.js +0 -2
  141. package/dist/assets/mobile-CTnihwfa.js +0 -2
  142. package/dist/assets/renderElectronMiniChatApp-DSa3gYqR.js +0 -2
  143. package/dist/assets/renderMobileApp-CPE-3uMl.js +0 -11
  144. package/dist/assets/runtimeEndpointReset-CzJfovWI.js +0 -62
  145. package/dist/assets/useAppFontEffects-CG3_yteE.js +0 -212
  146. package/dist/assets/vendor-aparajita-capacitor-secure-storage-5IShChL0.js +0 -1
  147. package/dist/assets/vendor-boot-DyL2td56.js +0 -69
  148. package/dist/assets/vendor-capacitor-app-BrDJj9I_.js +0 -1
  149. package/dist/assets/vendor-capacitor-core-B4EWRrHz.js +0 -1
  150. package/dist/assets/vendor-capacitor-keyboard-CYccoJjr.js +0 -1
  151. package/dist/assets/vendor-capacitor-push-notifications-KNe1zSBF.js +0 -1
  152. package/dist/assets/vendor-capacitor-status-bar-B-N0EOVk.js +0 -1
  153. package/dist/assets/vendor-codemirror-lang-cpp-GOE7Gjd0.js +0 -1
  154. package/dist/assets/vendor-codemirror-lang-css-Dwf2XpnZ.js +0 -1
  155. package/dist/assets/vendor-codemirror-lang-html-DcKqyeGk.js +0 -1
  156. package/dist/assets/vendor-codemirror-lang-java-6eGbyB2k.js +0 -1
  157. package/dist/assets/vendor-codemirror-lang-jinja-xSUJjXhr.js +0 -1
  158. package/dist/assets/vendor-codemirror-lang-json-CLGxdOCz.js +0 -1
  159. package/dist/assets/vendor-codemirror-lang-less-6nXi1rS9.js +0 -1
  160. package/dist/assets/vendor-codemirror-lang-liquid-B9hmb9P8.js +0 -1
  161. package/dist/assets/vendor-codemirror-lang-markdown-DmFP9s6x.js +0 -1
  162. package/dist/assets/vendor-codemirror-lang-php-DC6To8iX.js +0 -1
  163. package/dist/assets/vendor-codemirror-lang-python-yuxIkjit.js +0 -3
  164. package/dist/assets/vendor-codemirror-lang-rust-di1Sjz-0.js +0 -1
  165. package/dist/assets/vendor-codemirror-lang-sass-BWpV9NPV.js +0 -1
  166. package/dist/assets/vendor-codemirror-lang-wast-BiVarhcz.js +0 -1
  167. package/dist/assets/vendor-codemirror-lang-xml-Cn1lY1ts.js +0 -1
  168. package/dist/assets/vendor-codemirror-lang-yaml-BZ6mZw9L.js +0 -1
@@ -1,7 +1,7 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-6IO1AcJI.js","assets/vendor-zustand-CUi8eEds.js","assets/vendor-react-DASdDPIk.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-BAmzAlNx.css"])))=>i.map(i=>d[i]);
2
- import{j as t}from"./vendor-boot-DyL2td56.js";import{R as u}from"./vendor-react-DASdDPIk.js";import{i as Pe,j as ot,p as lt,l as it,m as ct,r as ut,b as dt,c as mt,G as ht,h as Ne,u as ft,n as bt,o as gt}from"./useGitHubRemoteSearch-DsxWOzKZ.js";import{a4 as pt,B as j,I as R,ak as xt,al as yt,am as vt,an as Ct,ao as jt,ap as wt,p as $e,f as kt,t as P,cH as St,o as ye,ai as Oe,a8 as Re,ab as Le,ad as Ee,cu as Nt,cv as Rt,af as pe,ag as Lt,n as Et}from"./useAppFontEffects-CG3_yteE.js";import{ad as It,ae as Ie,af as xe,ag as Ae,ah as ce,ai as At,aj as ue,R as Dt,Z as _e,a3 as Gt,a0 as Tt,ak as Ht}from"./runtimeEndpointReset-CzJfovWI.js";import{_ as Bt}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as Ft,d as Mt}from"./vendor-zustand-CUi8eEds.js";import{v as Ue,A as zt}from"./index-6IO1AcJI.js";import{a as Ke,u as Pt,p as $t,r as Ot,t as De,x as _t,z as Ut,A as Kt,w as ie,y as Wt,B as oe,C as We,D as qt,R as Vt,E as Ge,G as Qt,H as Jt,I as Zt,J as Yt,K as Te}from"./GitHubDetailScaffold-zCKCy5OJ.js";import{I as He,a as Xt,b as es,i as qe,c as ts,d as ss,s as as,g as le,e as ns,f as rs,h as Be,j as Fe,C as os,k as ls,v as is}from"./githubLink-DT7i2NlH.js";import{a as cs,b as us}from"./GitHubListPrimitives-Ck3zllel.js";import"./vendor-clsx-B-dksMZM.js";import"./runtimeSurface-DW_Ia4q3.js";import"./SessionUnreadDot-CELKNVIM.js";/* empty css */import"./permissionStore-B9Hkrqny.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-dompurify-r8glNMJW.js";const ve={state:"open",involvement:"all",labels:"",search:"",sort:"updated"},ds=3e4,ms=100,hs=50,Ve=(e,s)=>ue([e,"issues-collection",s]),Qe=(e,s)=>ue([e,"issues-remote",s.state,s.involvement,s.labels.trim(),s.q.trim()]),Ce=(e,s)=>ue([e,"issue-detail",s]),je=(e,s)=>ue([e,"issue-comments",s]),fs=e=>({state:e,perPage:ms}),bs=(e,s)=>({state:e.state,filter:e.involvement,q:e.q.trim()?e.q.trim():void 0,labels:e.labels.trim()?e.labels.trim():void 0,perPage:hs,...s?{cursor:s}:{}}),gs={set:e=>{typeof e=="function"?C.setState(s=>{const n={filtersByScope:s.filtersByScope,selectionByDirectory:s.selectionByDirectory};return e(n)}):C.setState(e)},get:()=>{const e=C.getState();return{filtersByScope:e.filtersByScope,selectionByDirectory:e.selectionByDirectory}}},g=At({openCollection:"open",closedCollection:"closed",defaultFilters:ve,freshWindowMs:ds,serverKind:"issues",errorFallback:"Issue request failed",collectionKeyFor:Ve,remoteKeyFor:Qe,detailKeyFor:Ce,commentsKeyFor:je,buildCollectionQuery:e=>({...fs(e)}),buildRemoteQuery:(e,s)=>({...bs(e,s)}),fetchList:async(e,s,n,r)=>{const l=await e.issuesList(s,n,r);return{items:l.items,nextCursor:l.nextCursor,fetchedAt:l.fetchedAt}},fetchDetail:async(e,s,n,r)=>e.issueGet(s,n,r),fetchComments:async(e,s,n,r,l)=>{const a=await e.issueComments(s,n,r,l);return{comments:a.comments,nextCursor:a.nextCursor,fetchedAt:a.fetchedAt}}},gs),C=Ft()(Mt((e,s)=>({...g.initialState,actionErrorByDetail:{},actingActions:{},setFilters:g.setFilters,resetFilters:g.resetFilters,selectIssue:g.select,ensureCollection:g.ensureCollection,ensureCollectionsFresh:g.ensureCollectionsFresh,prefetchClosedCollection:g.prefetchClosedCollection,loadMoreCollection:g.loadMoreCollection,refreshCollections:g.refreshCollections,searchRemote:g.searchRemote,loadMoreRemote:g.loadMoreRemote,dropRemoteForRepo:g.dropRemoteForRepo,refreshAllForScope:g.refreshAllForScope,ensureDetail:g.ensureDetail,refreshDetail:g.refreshDetail,ensureComments:g.ensureComments,loadMoreComments:g.loadMoreComments,refreshComments:g.refreshComments,updateIssue:async(n,r,l,a,d)=>{const b=Ae(r,l),o=Ce(r,l);if(s().actingActions[b])return{ok:!1,error:{kind:"failed",message:"An update is already in progress"}};e(p=>({actingActions:{...p.actingActions,[b]:!0},actionErrorByDetail:{...p.actionErrorByDetail,[b]:null}}));const c=g.resources.details.getEntry(o)?.data?.detail??null,y=c?.issue??null,w=y?{...y,title:a.title??y.title,body:a.body??y.body,state:a.state??y.state,stateReason:a.state!==void 0?a.stateReason??null:y.stateReason,labels:a.labels!==void 0?a.labels.map(p=>({name:p})):y.labels,assignees:a.assignees!==void 0?a.assignees.map(p=>({login:p})):y.assignees}:null;w&&c&&await g.resources.details.refresh(o,async()=>({detail:{...c,issue:w}})).catch(()=>null);try{return await d.issueUpdate(n,r,l,a),await xe(d,{directory:n,repo:r,kind:"issues",number:l}),s().dropRemoteForRepo(r),await s().refreshCollections(n,r,"both",d).catch(()=>null),await s().refreshDetail(n,r,l,d).catch(()=>null),e(p=>({actingActions:{...p.actingActions,[b]:!1}})),{ok:!0}}catch(p){const S=g.toStoreError(p);return c&&await g.resources.details.refresh(o,async()=>({detail:c})).catch(()=>null),e(f=>({actingActions:{...f.actingActions,[b]:!1},actionErrorByDetail:{...f.actionErrorByDetail,[b]:S}})),{ok:!1,error:S}}},addComment:async(n,r,l,a,d)=>{const b=Ae(r,l),o=je(r,l),c=a.trim(),y={id:-Date.now(),url:"",body:c,author:null,createdAt:new Date().toISOString(),updatedAt:null},w=g.resources.comments.getEntry(o)?.data??null;if(w){const p={comments:[...w.comments,y],nextCursor:w.nextCursor,fetchedAt:w.fetchedAt};await g.resources.comments.refresh(o,async()=>p).catch(()=>null)}try{return await d.issueComment(n,r,l,c),await xe(d,{directory:n,repo:r,kind:"issues",number:l}),await s().refreshComments(n,r,l,d).catch(()=>null),await s().refreshDetail(n,r,l,d).catch(()=>null),{ok:!0}}catch(p){const S=g.toStoreError(p);return w?await g.resources.comments.refresh(o,async()=>w).catch(()=>null):g.resources.comments.remove(o),e(f=>({actionErrorByDetail:{...f.actionErrorByDetail,[b]:S}})),{ok:!1,error:S}}},createIssue:async(n,r)=>{try{const l=await r.issueCreate(n.directory,n.repo,{title:n.title,body:n.body,labels:n.labels,assignees:n.assignees});return await xe(r,{directory:n.directory,repo:n.repo,kind:"issues"}),s().dropRemoteForRepo(n.repo),await s().refreshCollections(n.directory,n.repo,"both",r).catch(()=>null),{ok:!0,number:l.issue.number}}catch(l){return{ok:!1,error:g.toStoreError(l)}}},notifyAgentTurnComplete:n=>{const r=Ue((n||"").trim());if(!r)return;const l=s().selectionByDirectory[r];!l?.repo||typeof l.number!="number"||(g.markCollectionsStale(l.repo),Bt(async()=>{const{getRegisteredRuntimeAPIs:a}=await import("./index-6IO1AcJI.js").then(d=>d.cv);return{getRegisteredRuntimeAPIs:a}},__vite__mapDeps([0,1,2,3,4,5,6])).then(({getRegisteredRuntimeAPIs:a})=>{const d=a()?.github??null;if(d)return s().refreshDetail(r,l.repo,l.number,d)}).catch(()=>{}))},resetForRuntimeSwitch:()=>{g.resetCore(),e({actionErrorByDetail:{},actingActions:{}})}}),{name:"github-issues-store"}));typeof window<"u"&&zt(()=>{C.getState().resetForRuntimeSwitch()});const ps=e=>g.getLocalIndex(e),xs=(e,s)=>g.getLocalIndex(e).find(n=>n.number===s)??null,Me=(e,s)=>ce(g.resources.collections,e?Ve(e,s):null),ys=(e,s)=>ce(g.resources.remote,e?Qe(e,s):null),vs=(e,s)=>ce(g.resources.details,e!=null&&s!=null?Ce(e,s):null),Cs=(e,s)=>ce(g.resources.comments,e!=null&&s!=null?je(e,s):null),js=(e,s)=>C(n=>!e||!s?ve:n.filtersByScope[It(e,s)]??ve),ws=e=>C(s=>e?s.selectionByDirectory[Ue(e)]??Ie:Ie),ks=e=>typeof e!="number"||e===0?null:t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-0.5 typography-micro tabular-nums text-muted-foreground",title:`${e} comments`,"aria-label":`${e} comments`,children:[t.jsx(R,{name:"chat-1",className:"size-3.5"}),e]}),Ss=({items:e,hasMore:s,isLoadingMore:n,isLoading:r,isRefreshing:l,stale:a,error:d,filters:b,countComplete:o=!0,incompleteNotice:c=null,remote:y=null,numberJump:w=null,onFiltersChange:p,onClearFilters:S,onLoadMore:f,onRetry:x,onOpen:N,onNewIssue:k,headerActionsSlot:T=null,headerActionsPresentation:H="drawer"})=>{const z=b.state==="open"&&b.involvement==="all"&&!b.search.trim()&&!b.labels.trim(),{isMobile:D,isTablet:I}=pt(),B=D||I,G=T!=null,A=H??"drawer",$=G?A==="desktop"?t.jsxs(j,{type:"button",variant:"ghost",size:"sm",onClick:k,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-4"}),"New issue"]}):t.jsxs(j,{type:"button",variant:"ghost",size:"default",onClick:k,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-4"}),"New issue"]}):t.jsxs(j,{type:"button",variant:"ghost",size:B?"sm":"xs",onClick:k,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-3.5"}),"New issue"]}),O=u.useCallback(h=>t.jsx("li",{role:"listitem",children:t.jsx(Pe,{glyph:t.jsx(Ke,{kind:"issue",state:h.state}),number:`#${h.number}`,title:h.title,signals:ks(h.comments),meta:t.jsxs(t.Fragment,{children:[t.jsx(ot,{login:h.author?.login,avatarUrl:h.author?.avatarUrl}),t.jsx(lt,{labels:h.labels??[]})]}),updatedAt:h.updatedAt,onOpen:()=>N(h.number),ariaLabel:`Open issue #${h.number} ${h.title}`})},h.number),[N]);return t.jsx(it,{items:e,renderRow:O,hasMore:s,isLoadingMore:n,isLoading:r,isRefreshing:l,stale:a,error:d,searchValue:b.search,onSearchChange:h=>p({search:h}),searchPlaceholder:"Search issues, or label:bug",searchAriaLabel:"Search issues",toolbarControls:t.jsx(ct,{stateValue:b.state,stateOptions:He.map(h=>({id:h.id,label:h.label})),onStateChange:h=>p({state:h}),involvementValue:b.involvement,involvementOptions:es.map(h=>({id:h.id,label:h.label})),onInvolvementChange:h=>p({involvement:h}),labelsValue:b.labels,onLabelsChange:h=>p({labels:h}),sortValue:b.sort,sortOptions:Xt.map(h=>({id:h.id,label:h.label})),onSortChange:h=>p({sort:h}),sortAriaLabel:"Sort issues"}),primaryAction:$,headerActionsSlot:T,headerActionsPresentation:A,isDefaultFilters:z,stateLabel:He.find(h=>h.id===b.state)?.label??b.state,kindSingular:"issue",kindPlural:"issues",noItemsTitle:b.state==="open"?"No open issues":"No issues yet",noItemsBody:"Issues for this repository appear here.",noItemsIcon:"inbox-archive",noItemsAction:t.jsxs(j,{type:"button",variant:"outline",size:"sm",onClick:k,children:[t.jsx(R,{name:"add",className:"size-3.5"}),"New issue"]}),listAriaLabel:"Issues",skeletonLabel:"Loading issues",updatedAtOf:h=>h.updatedAt,countComplete:o,incompleteNotice:c,remote:y,numberJump:w,numberJumpKind:"issue",onClearFilters:S,onLoadMore:f,onRetry:x,onOpen:N})},Je=(e,s,n)=>{const[r,l]=u.useState([]),[a,d]=u.useState([]),[b,o]=u.useState(!1);return u.useEffect(()=>{if(!n)return;let c=!1;return o(!0),n.repoMeta(e,s).then(y=>{c||(l(y.labels??[]),d(y.assignees??[]))}).catch(()=>{c||(l([]),d([]))}).finally(()=>{c||o(!1)}),()=>{c=!0}},[n,e,s]),{labels:r,assignees:a,loading:b}},Ze=(e,s)=>e.includes(s)?e.filter(n=>n!==s):[...e,s],Ye=({candidates:e,loading:s,selected:n,onChange:r})=>s?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"Loading labels…"}):e.length===0?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"No labels in this repository."}):t.jsx("div",{className:"flex flex-wrap gap-1",children:e.map(l=>{const a=n.includes(l.name);return t.jsx(j,{type:"button",variant:"chip",size:"xs","aria-pressed":a,onClick:()=>r(Ze(n,l.name)),children:l.name},l.name)})}),Xe=({candidates:e,loading:s,selected:n,onChange:r})=>s?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"Loading assignees…"}):e.length===0?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"No assignable users found."}):t.jsx("div",{className:"flex flex-wrap gap-1",children:e.map(l=>{const a=l.login,d=a?n.includes(a):!1;return t.jsx(j,{type:"button",variant:"chip",size:"xs","aria-pressed":d,onClick:()=>{a&&r(Ze(n,a))},children:a},a)})}),Ns=({open:e,onOpenChange:s,issueNumber:n,issueTitle:r,busy:l,onChoose:a})=>{const[d,b]=u.useState("worktree"),o=qe(n,r);return t.jsx(xt,{open:e,onOpenChange:s,children:t.jsxs(yt,{className:"max-w-md w-[calc(100vw-2rem)]",children:[t.jsxs(vt,{children:[t.jsxs(Ct,{children:["Start session from issue #",n]}),t.jsx(jt,{children:"Choose where the new session works. The composer is pre-filled — nothing is sent automatically."})]}),t.jsxs("div",{className:"flex flex-col gap-1",role:"radiogroup","aria-label":"Session location",children:[t.jsxs("button",{type:"button",role:"radio","aria-checked":d==="current",onClick:()=>b("current"),className:"flex items-start gap-2 rounded-md border border-border px-3 py-2 text-left hover:bg-interactive-hover",children:[t.jsx(R,{name:d==="current"?"record-circle":"checkbox-blank-circle-fill",className:"mt-0.5 size-4 shrink-0 text-muted-foreground"}),t.jsxs("span",{className:"min-w-0",children:[t.jsx("span",{className:"block typography-ui-label text-foreground",children:"Current checkout"}),t.jsx("span",{className:"block typography-micro text-muted-foreground",children:"Work directly where you are now."})]})]}),t.jsxs("button",{type:"button",role:"radio","aria-checked":d==="worktree",onClick:()=>b("worktree"),className:"flex items-start gap-2 rounded-md border border-border px-3 py-2 text-left hover:bg-interactive-hover",children:[t.jsx(R,{name:d==="worktree"?"record-circle":"checkbox-blank-circle-fill",className:"mt-0.5 size-4 shrink-0 text-muted-foreground"}),t.jsxs("span",{className:"min-w-0",children:[t.jsx("span",{className:"block typography-ui-label text-foreground",children:"New worktree"}),t.jsxs("span",{className:"block truncate font-mono typography-micro text-muted-foreground",title:o,children:["Branch ",o]})]})]})]}),t.jsxs(wt,{children:[t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:()=>s(!1),disabled:l,children:"Cancel"}),t.jsx(j,{type:"button",variant:"default",size:"sm",onClick:()=>a(d),disabled:l,"aria-label":d==="worktree"?"Create worktree and open session draft":"Open session draft in current checkout",children:l?"Working…":d==="worktree"?"Create worktree":"Open draft"})]})]})})},ze=e=>{const s=as(e.title);return e.kind==="pr"?`pr-${e.number}-${s}`:qe(e.number,e.title)},Rs=async(e,s)=>{const{github:n,git:r,openDraft:l,refreshWorktrees:a}=s;if(!l)return{ok:!1,error:"Sessions are not available in this runtime"};let d;try{d=(await n.agentContext(e.directory,e.repo,e.kind==="pr"?"pr":"issue",e.number)).text}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Failed to load issue context"}}const o=`${e.kind==="pr"?"PR":"Issue"} #${e.number}: ${e.title.trim()||"(untitled)"}`,c=e.kind==="pr"?`Work on this GitHub pull request. Read the quoted context below, then propose a plan and wait for confirmation before changing code.
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BnZVqcki.js","assets/vendor-zustand-CUi8eEds.js","assets/vendor-react-DASdDPIk.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-BnieExes.css"])))=>i.map(i=>d[i]);
2
+ import{k as t}from"./vendor-boot-Dgb9NVFe.js";import{R as u}from"./vendor-react-DASdDPIk.js";import{i as Pe,j as ot,p as lt,l as it,m as ct,r as ut,b as dt,c as mt,G as ht,h as Ne,u as ft,n as bt,o as gt}from"./useGitHubRemoteSearch-Bsf2YeQP.js";import{a4 as pt,B as j,I as R,ak as xt,al as yt,am as vt,an as Ct,ao as jt,ap as wt,q as $e,h as kt,t as P,cH as St,o as ye,ai as Oe,a8 as Re,ab as Le,ad as Ee,cu as Nt,cv as Rt,af as pe,ag as Lt,p as Et}from"./useAppFontEffects-BisjofNZ.js";import{ae as It,af as Ie,ag as xe,ah as Ae,ai as ce,aj as At,ak as ue,U as Dt,_ as _e,a4 as Gt,a1 as Tt,al as Ht}from"./runtimeEndpointReset-BqqXMwE9.js";import{_ as Bt}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as Ft,d as Mt}from"./vendor-zustand-CUi8eEds.js";import{v as Ue,A as zt}from"./index-BnZVqcki.js";import{a as Ke,u as Pt,p as $t,r as Ot,t as De,x as _t,z as Ut,A as Kt,w as ie,y as Wt,B as oe,C as We,D as qt,R as Vt,E as Ge,G as Qt,H as Jt,I as Yt,J as Zt,K as Te}from"./GitHubDetailScaffold-BZhP67Va.js";import{I as He,a as Xt,b as es,i as qe,c as ts,d as ss,s as as,g as le,e as ns,f as rs,h as Be,j as Fe,C as os,k as ls,v as is}from"./githubLink-BdbPMMAK.js";import{a as cs,b as us}from"./GitHubListPrimitives-DhF42guB.js";import"./vendor-clsx-B-dksMZM.js";import"./runtimeSurface-DBiUWYK2.js";import"./nativeFileSave-BzhtrDoD.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./SessionUnreadDot-Czfvjbdi.js";/* empty css */import"./permissionStore-B9Hkrqny.js";import"./vendor-dompurify-r8glNMJW.js";const ve={state:"open",involvement:"all",labels:"",search:"",sort:"updated"},ds=3e4,ms=100,hs=50,Ve=(e,s)=>ue([e,"issues-collection",s]),Qe=(e,s)=>ue([e,"issues-remote",s.state,s.involvement,s.labels.trim(),s.q.trim()]),Ce=(e,s)=>ue([e,"issue-detail",s]),je=(e,s)=>ue([e,"issue-comments",s]),fs=e=>({state:e,perPage:ms}),bs=(e,s)=>({state:e.state,filter:e.involvement,q:e.q.trim()?e.q.trim():void 0,labels:e.labels.trim()?e.labels.trim():void 0,perPage:hs,...s?{cursor:s}:{}}),gs={set:e=>{typeof e=="function"?C.setState(s=>{const n={filtersByScope:s.filtersByScope,selectionByDirectory:s.selectionByDirectory};return e(n)}):C.setState(e)},get:()=>{const e=C.getState();return{filtersByScope:e.filtersByScope,selectionByDirectory:e.selectionByDirectory}}},g=At({openCollection:"open",closedCollection:"closed",defaultFilters:ve,freshWindowMs:ds,serverKind:"issues",errorFallback:"Issue request failed",collectionKeyFor:Ve,remoteKeyFor:Qe,detailKeyFor:Ce,commentsKeyFor:je,buildCollectionQuery:e=>({...fs(e)}),buildRemoteQuery:(e,s)=>({...bs(e,s)}),fetchList:async(e,s,n,r)=>{const l=await e.issuesList(s,n,r);return{items:l.items,nextCursor:l.nextCursor,fetchedAt:l.fetchedAt}},fetchDetail:async(e,s,n,r)=>e.issueGet(s,n,r),fetchComments:async(e,s,n,r,l)=>{const a=await e.issueComments(s,n,r,l);return{comments:a.comments,nextCursor:a.nextCursor,fetchedAt:a.fetchedAt}}},gs),C=Ft()(Mt((e,s)=>({...g.initialState,actionErrorByDetail:{},actingActions:{},setFilters:g.setFilters,resetFilters:g.resetFilters,selectIssue:g.select,ensureCollection:g.ensureCollection,ensureCollectionsFresh:g.ensureCollectionsFresh,prefetchClosedCollection:g.prefetchClosedCollection,loadMoreCollection:g.loadMoreCollection,refreshCollections:g.refreshCollections,searchRemote:g.searchRemote,loadMoreRemote:g.loadMoreRemote,dropRemoteForRepo:g.dropRemoteForRepo,refreshAllForScope:g.refreshAllForScope,ensureDetail:g.ensureDetail,refreshDetail:g.refreshDetail,ensureComments:g.ensureComments,loadMoreComments:g.loadMoreComments,refreshComments:g.refreshComments,updateIssue:async(n,r,l,a,d)=>{const b=Ae(r,l),o=Ce(r,l);if(s().actingActions[b])return{ok:!1,error:{kind:"failed",message:"An update is already in progress"}};e(p=>({actingActions:{...p.actingActions,[b]:!0},actionErrorByDetail:{...p.actionErrorByDetail,[b]:null}}));const c=g.resources.details.getEntry(o)?.data?.detail??null,y=c?.issue??null,w=y?{...y,title:a.title??y.title,body:a.body??y.body,state:a.state??y.state,stateReason:a.state!==void 0?a.stateReason??null:y.stateReason,labels:a.labels!==void 0?a.labels.map(p=>({name:p})):y.labels,assignees:a.assignees!==void 0?a.assignees.map(p=>({login:p})):y.assignees}:null;w&&c&&await g.resources.details.refresh(o,async()=>({detail:{...c,issue:w}})).catch(()=>null);try{return await d.issueUpdate(n,r,l,a),await xe(d,{directory:n,repo:r,kind:"issues",number:l}),s().dropRemoteForRepo(r),await s().refreshCollections(n,r,"both",d).catch(()=>null),await s().refreshDetail(n,r,l,d).catch(()=>null),e(p=>({actingActions:{...p.actingActions,[b]:!1}})),{ok:!0}}catch(p){const S=g.toStoreError(p);return c&&await g.resources.details.refresh(o,async()=>({detail:c})).catch(()=>null),e(f=>({actingActions:{...f.actingActions,[b]:!1},actionErrorByDetail:{...f.actionErrorByDetail,[b]:S}})),{ok:!1,error:S}}},addComment:async(n,r,l,a,d)=>{const b=Ae(r,l),o=je(r,l),c=a.trim(),y={id:-Date.now(),url:"",body:c,author:null,createdAt:new Date().toISOString(),updatedAt:null},w=g.resources.comments.getEntry(o)?.data??null;if(w){const p={comments:[...w.comments,y],nextCursor:w.nextCursor,fetchedAt:w.fetchedAt};await g.resources.comments.refresh(o,async()=>p).catch(()=>null)}try{return await d.issueComment(n,r,l,c),await xe(d,{directory:n,repo:r,kind:"issues",number:l}),await s().refreshComments(n,r,l,d).catch(()=>null),await s().refreshDetail(n,r,l,d).catch(()=>null),{ok:!0}}catch(p){const S=g.toStoreError(p);return w?await g.resources.comments.refresh(o,async()=>w).catch(()=>null):g.resources.comments.remove(o),e(f=>({actionErrorByDetail:{...f.actionErrorByDetail,[b]:S}})),{ok:!1,error:S}}},createIssue:async(n,r)=>{try{const l=await r.issueCreate(n.directory,n.repo,{title:n.title,body:n.body,labels:n.labels,assignees:n.assignees});return await xe(r,{directory:n.directory,repo:n.repo,kind:"issues"}),s().dropRemoteForRepo(n.repo),await s().refreshCollections(n.directory,n.repo,"both",r).catch(()=>null),{ok:!0,number:l.issue.number}}catch(l){return{ok:!1,error:g.toStoreError(l)}}},notifyAgentTurnComplete:n=>{const r=Ue((n||"").trim());if(!r)return;const l=s().selectionByDirectory[r];!l?.repo||typeof l.number!="number"||(g.markCollectionsStale(l.repo),Bt(async()=>{const{getRegisteredRuntimeAPIs:a}=await import("./index-BnZVqcki.js").then(d=>d.cy);return{getRegisteredRuntimeAPIs:a}},__vite__mapDeps([0,1,2,3,4,5,6,7])).then(({getRegisteredRuntimeAPIs:a})=>{const d=a()?.github??null;if(d)return s().refreshDetail(r,l.repo,l.number,d)}).catch(()=>{}))},resetForRuntimeSwitch:()=>{g.resetCore(),e({actionErrorByDetail:{},actingActions:{}})}}),{name:"github-issues-store"}));typeof window<"u"&&zt(()=>{C.getState().resetForRuntimeSwitch()});const ps=e=>g.getLocalIndex(e),xs=(e,s)=>g.getLocalIndex(e).find(n=>n.number===s)??null,Me=(e,s)=>ce(g.resources.collections,e?Ve(e,s):null),ys=(e,s)=>ce(g.resources.remote,e?Qe(e,s):null),vs=(e,s)=>ce(g.resources.details,e!=null&&s!=null?Ce(e,s):null),Cs=(e,s)=>ce(g.resources.comments,e!=null&&s!=null?je(e,s):null),js=(e,s)=>C(n=>!e||!s?ve:n.filtersByScope[It(e,s)]??ve),ws=e=>C(s=>e?s.selectionByDirectory[Ue(e)]??Ie:Ie),ks=e=>typeof e!="number"||e===0?null:t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-0.5 typography-micro tabular-nums text-muted-foreground",title:`${e} comments`,"aria-label":`${e} comments`,children:[t.jsx(R,{name:"chat-1",className:"size-3.5"}),e]}),Ss=({items:e,hasMore:s,isLoadingMore:n,isLoading:r,isRefreshing:l,stale:a,error:d,filters:b,countComplete:o=!0,incompleteNotice:c=null,remote:y=null,numberJump:w=null,onFiltersChange:p,onClearFilters:S,onLoadMore:f,onRetry:x,onOpen:N,onNewIssue:k,headerActionsSlot:T=null,headerActionsPresentation:H="drawer"})=>{const z=b.state==="open"&&b.involvement==="all"&&!b.search.trim()&&!b.labels.trim(),{isMobile:D,isTablet:I}=pt(),B=D||I,G=T!=null,A=H??"drawer",$=G?A==="desktop"?t.jsxs(j,{type:"button",variant:"ghost",size:"sm",onClick:k,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-4"}),"New issue"]}):t.jsxs(j,{type:"button",variant:"ghost",size:"default",onClick:k,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-4"}),"New issue"]}):t.jsxs(j,{type:"button",variant:"ghost",size:B?"sm":"xs",onClick:k,"aria-label":"New issue",title:"New issue",children:[t.jsx(R,{name:"add",className:"size-3.5"}),"New issue"]}),O=u.useCallback(h=>t.jsx("li",{role:"listitem",children:t.jsx(Pe,{glyph:t.jsx(Ke,{kind:"issue",state:h.state}),number:`#${h.number}`,title:h.title,signals:ks(h.comments),meta:t.jsxs(t.Fragment,{children:[t.jsx(ot,{login:h.author?.login,avatarUrl:h.author?.avatarUrl}),t.jsx(lt,{labels:h.labels??[]})]}),updatedAt:h.updatedAt,onOpen:()=>N(h.number),ariaLabel:`Open issue #${h.number} ${h.title}`})},h.number),[N]);return t.jsx(it,{items:e,renderRow:O,hasMore:s,isLoadingMore:n,isLoading:r,isRefreshing:l,stale:a,error:d,searchValue:b.search,onSearchChange:h=>p({search:h}),searchPlaceholder:"Search issues, or label:bug",searchAriaLabel:"Search issues",toolbarControls:t.jsx(ct,{stateValue:b.state,stateOptions:He.map(h=>({id:h.id,label:h.label})),onStateChange:h=>p({state:h}),involvementValue:b.involvement,involvementOptions:es.map(h=>({id:h.id,label:h.label})),onInvolvementChange:h=>p({involvement:h}),labelsValue:b.labels,onLabelsChange:h=>p({labels:h}),sortValue:b.sort,sortOptions:Xt.map(h=>({id:h.id,label:h.label})),onSortChange:h=>p({sort:h}),sortAriaLabel:"Sort issues"}),primaryAction:$,headerActionsSlot:T,headerActionsPresentation:A,isDefaultFilters:z,stateLabel:He.find(h=>h.id===b.state)?.label??b.state,kindSingular:"issue",kindPlural:"issues",noItemsTitle:b.state==="open"?"No open issues":"No issues yet",noItemsBody:"Issues for this repository appear here.",noItemsIcon:"inbox-archive",noItemsAction:t.jsxs(j,{type:"button",variant:"outline",size:"sm",onClick:k,children:[t.jsx(R,{name:"add",className:"size-3.5"}),"New issue"]}),listAriaLabel:"Issues",skeletonLabel:"Loading issues",updatedAtOf:h=>h.updatedAt,countComplete:o,incompleteNotice:c,remote:y,numberJump:w,numberJumpKind:"issue",onClearFilters:S,onLoadMore:f,onRetry:x,onOpen:N})},Je=(e,s,n)=>{const[r,l]=u.useState([]),[a,d]=u.useState([]),[b,o]=u.useState(!1);return u.useEffect(()=>{if(!n)return;let c=!1;return o(!0),n.repoMeta(e,s).then(y=>{c||(l(y.labels??[]),d(y.assignees??[]))}).catch(()=>{c||(l([]),d([]))}).finally(()=>{c||o(!1)}),()=>{c=!0}},[n,e,s]),{labels:r,assignees:a,loading:b}},Ye=(e,s)=>e.includes(s)?e.filter(n=>n!==s):[...e,s],Ze=({candidates:e,loading:s,selected:n,onChange:r})=>s?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"Loading labels…"}):e.length===0?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"No labels in this repository."}):t.jsx("div",{className:"flex flex-wrap gap-1",children:e.map(l=>{const a=n.includes(l.name);return t.jsx(j,{type:"button",variant:"chip",size:"xs","aria-pressed":a,onClick:()=>r(Ye(n,l.name)),children:l.name},l.name)})}),Xe=({candidates:e,loading:s,selected:n,onChange:r})=>s?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"Loading assignees…"}):e.length===0?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"No assignable users found."}):t.jsx("div",{className:"flex flex-wrap gap-1",children:e.map(l=>{const a=l.login,d=a?n.includes(a):!1;return t.jsx(j,{type:"button",variant:"chip",size:"xs","aria-pressed":d,onClick:()=>{a&&r(Ye(n,a))},children:a},a)})}),Ns=({open:e,onOpenChange:s,issueNumber:n,issueTitle:r,busy:l,onChoose:a})=>{const[d,b]=u.useState("worktree"),o=qe(n,r);return t.jsx(xt,{open:e,onOpenChange:s,children:t.jsxs(yt,{className:"max-w-md w-[calc(100vw-2rem)]",children:[t.jsxs(vt,{children:[t.jsxs(Ct,{children:["Start session from issue #",n]}),t.jsx(jt,{children:"Choose where the new session works. The composer is pre-filled — nothing is sent automatically."})]}),t.jsxs("div",{className:"flex flex-col gap-1",role:"radiogroup","aria-label":"Session location",children:[t.jsxs("button",{type:"button",role:"radio","aria-checked":d==="current",onClick:()=>b("current"),className:"flex items-start gap-2 rounded-md border border-border px-3 py-2 text-left hover:bg-interactive-hover",children:[t.jsx(R,{name:d==="current"?"record-circle":"checkbox-blank-circle-fill",className:"mt-0.5 size-4 shrink-0 text-muted-foreground"}),t.jsxs("span",{className:"min-w-0",children:[t.jsx("span",{className:"block typography-ui-label text-foreground",children:"Current checkout"}),t.jsx("span",{className:"block typography-micro text-muted-foreground",children:"Work directly where you are now."})]})]}),t.jsxs("button",{type:"button",role:"radio","aria-checked":d==="worktree",onClick:()=>b("worktree"),className:"flex items-start gap-2 rounded-md border border-border px-3 py-2 text-left hover:bg-interactive-hover",children:[t.jsx(R,{name:d==="worktree"?"record-circle":"checkbox-blank-circle-fill",className:"mt-0.5 size-4 shrink-0 text-muted-foreground"}),t.jsxs("span",{className:"min-w-0",children:[t.jsx("span",{className:"block typography-ui-label text-foreground",children:"New worktree"}),t.jsxs("span",{className:"block truncate font-mono typography-micro text-muted-foreground",title:o,children:["Branch ",o]})]})]})]}),t.jsxs(wt,{children:[t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:()=>s(!1),disabled:l,children:"Cancel"}),t.jsx(j,{type:"button",variant:"default",size:"sm",onClick:()=>a(d),disabled:l,"aria-label":d==="worktree"?"Create worktree and open session draft":"Open session draft in current checkout",children:l?"Working…":d==="worktree"?"Create worktree":"Open draft"})]})]})})},ze=e=>{const s=as(e.title);return e.kind==="pr"?`pr-${e.number}-${s}`:qe(e.number,e.title)},Rs=async(e,s)=>{const{github:n,git:r,openDraft:l,refreshWorktrees:a}=s;if(!l)return{ok:!1,error:"Sessions are not available in this runtime"};let d;try{d=(await n.agentContext(e.directory,e.repo,e.kind==="pr"?"pr":"issue",e.number)).text}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Failed to load issue context"}}const o=`${e.kind==="pr"?"PR":"Issue"} #${e.number}: ${e.title.trim()||"(untitled)"}`,c=e.kind==="pr"?`Work on this GitHub pull request. Read the quoted context below, then propose a plan and wait for confirmation before changing code.
3
3
 
4
4
  PR #${e.number}: ${e.title}
5
5
  ${e.url}
6
6
 
7
- ${d}`:ts({repo:e.repo,number:e.number,title:e.title,url:e.url,contextText:d}),y=[{text:ss({kind:e.kind,number:e.number,title:e.title,url:e.url}),synthetic:!0},{text:d,synthetic:!0}];if(e.target==="current")return l({directoryOverride:e.directory,title:o,initialPrompt:c,syntheticParts:y}),{ok:!0,directory:e.directory};if(!r?.getGitBranches||!r?.createGitWorktree)return{ok:!1,error:"Worktree creation is not available in this runtime"};let w,p=!1;try{const x=await r.getGitBranches(e.directory);if(w=x.current?.trim()??"",!w)throw new Error("no current branch");p=Array.isArray(x.all)&&x.all.includes(ze(e))}catch{return{ok:!1,error:"Could not determine the current branch to start the worktree from"}}const S=ze(e);let f;try{if(p){let x=null;if(r.listGitWorktrees)try{const N=await r.listGitWorktrees(e.directory);x=Array.isArray(N)?N.find(k=>!k?.prunable&&k?.branch===S)?.path??null:null}catch{x=null}if(x)f=x;else if(f=(await r.createGitWorktree(e.directory,{mode:"existing",existingBranch:S})).path,!f)throw new Error("worktree path missing")}else if(f=(await r.createGitWorktree(e.directory,{mode:"new",startRef:w,branchName:S})).path,!f)throw new Error("worktree path missing")}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Worktree creation failed"}}return await a?.(e.directory),l({directoryOverride:f,title:o,initialPrompt:c,syntheticParts:y}),{ok:!0,directory:f}},Ls=()=>{const e=$e(),s=kt(a=>a.openNewSessionDraft),[n,r]=u.useState(null);return{start:u.useCallback(async a=>{const d=e.github;if(!d)return P.error("GitHub is not available in this runtime"),!1;const b=`${a.repo}#${a.number}:${a.target}`;r(b);try{const o=await Rs(a,{github:d,git:e.git??null,refreshWorktrees:c=>ut(c,e.git),openDraft:c=>s(c)});return o.ok?(P.success(a.target==="worktree"?"Worktree ready — session draft opened":"Session draft opened"),!0):(P.error(o.error),!1)}finally{r(null)}},[e.github,e.git,s]),startingKey:n}},Es=({issue:e})=>t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(We,{login:e.author?.login,avatarUrl:e.author?.avatarUrl,size:"xs"}),e.author?.login??"ghost"]}),e.createdAt?` · opened ${Te(e.createdAt)}`:"",e.updatedAt&&e.updatedAt!==e.createdAt?` · updated ${Te(e.updatedAt)}`:""]}),Is=({number:e,closed:s,closeReason:n,onCloseReasonChange:r,closeAllowed:l,closeReasonText:a,reopenAllowed:d,reopenReasonText:b,acting:o,onStateAction:c,askSending:y,onAskAgent:w,onEditTitle:p,editAllowed:S,editReasonText:f,onCopyLink:x,url:N})=>t.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 px-3 pt-1 pb-2","aria-label":"Issue actions",children:[s?t.jsx(Ne,{copy:Fe("reopen",e),busy:o,variant:"outline",disabled:!d,disabledReason:b??"Reopen issue",label:"Reopen issue",icon:t.jsx(R,{name:"history",className:"size-3.5","aria-hidden":"true"}),onConfirm:()=>{c("reopen")}}):t.jsxs("span",{role:"group","aria-label":"Close issue",className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(Ne,{copy:Fe(n==="not_planned"?"close-not-planned":"close-completed",e),busy:o,destructive:!0,variant:"outline",disabled:!l,disabledReason:a??"Close issue",label:"Close issue",icon:t.jsx(R,{name:"close",className:"size-3.5","aria-hidden":"true"}),onConfirm:()=>{c(n==="not_planned"?"close-not-planned":"close-completed")}}),t.jsxs(Re,{modal:!1,children:[t.jsx(Le,{asChild:!0,children:t.jsx(j,{type:"button",variant:"outline",size:"xs",className:"shrink-0 px-1.5",title:"Close options","aria-label":"Close options",disabled:!l||o,children:t.jsx(R,{name:"arrow-down-s",className:"size-3.5"})})}),t.jsx(Ee,{align:"start",className:"w-60",children:t.jsx(Nt,{value:n,onValueChange:k=>r(k),children:os.map(k=>t.jsx(Rt,{value:k.id,children:k.id==="completed"?"Close as completed":"Close as not planned"},k.id))})})]})]}),t.jsxs(j,{type:"button",variant:"outline",size:"xs",className:"shrink-0",onClick:w,disabled:y,title:"Send issue context to the agent composer","aria-label":"Ask agent about this issue",children:[t.jsx(R,{name:"send-plane-2",className:"size-3.5","aria-hidden":"true"}),y?"Asking…":"Ask agent"]}),t.jsxs(j,{type:"button",variant:"ghost",size:"xs",className:"shrink-0",onClick:()=>{ye(N)},title:"Open on GitHub","aria-label":"Open on GitHub",children:[t.jsx(R,{name:"external-link",className:"size-3.5","aria-hidden":"true"}),"Open on GitHub"]}),t.jsxs(Re,{modal:!1,children:[t.jsx(Le,{asChild:!0,children:t.jsx(j,{type:"button",variant:"ghost",size:"xs",className:"shrink-0 px-1.5","aria-label":"More issue actions",title:"More issue actions",children:t.jsx(R,{name:"more-2",className:"size-4"})})}),t.jsxs(Ee,{align:"end",className:"w-60",children:[t.jsxs(pe,{onClick:p,disabled:!S,title:f??"Edit title",children:[t.jsx(R,{name:"pencil",className:"size-3.5"}),"Edit title"]}),t.jsx(Lt,{}),t.jsxs(pe,{onClick:()=>{ye(N)},children:[t.jsx(R,{name:"external-link",className:"size-3.5"}),"Open on GitHub"]}),t.jsxs(pe,{onClick:x,children:[t.jsx(R,{name:"file-copy",className:"size-3.5"}),"Copy link"]})]})]})]}),As=e=>{const{directory:s,repo:n,number:r,github:l,issue:a}=e,d=C(i=>i.updateIssue),b=C(i=>i.addComment),o=C(i=>i.actionErrorByDetail[`${n}#${r}`]??null),c=C(i=>i.actingActions[`${n}#${r}`]??!1),{start:y,startingKey:w}=Ls(),p=Pt(s,n),[S,f]=u.useState("completed"),[x,N]=u.useState(!1),[k,T]=u.useState(""),[H,z]=u.useState(!1),[D,I]=u.useState(""),[B,G]=u.useState(!1),[A,$]=u.useState([]),[O,h]=u.useState([]),{draft:v,onDraftChange:L,flushDraft:_}=dt(n,r),{busy:W,error:de,submit:X}=mt({postComment:i=>b(s,n,r,i,l),runFollowUp:i=>d(s,n,r,Be(i==="reopen"?"reopen":S==="not_planned"?"close-not-planned":"close-completed"),l),verbs:{close:"close",reopen:"reopen"},doneLabels:{close:"Closed with comment",reopen:"Reopened with comment"},afterPost:()=>{L(""),ft.getState().clearCommentDraft(n,r)}}),[Q,me]=u.useState("newest"),[he,J]=u.useState(!1),[Z,ee]=u.useState(!1),U=u.useMemo(()=>({capabilities:e.capabilities??null,isAuthor:$t(a?.author?.login,e.viewerLogin),permissionFallback:e.viewerPermission?.fallback===!0}),[e.capabilities,e.viewerLogin,e.viewerPermission?.fallback,a?.author?.login]),F=le(a?.state==="closed"?"reopen":"close",a,U),M=le("edit",a,U),te=le("labels",a,U),se=le("comment",a,U),ae=St(s),Y=u.useMemo(()=>{const i=new Set;for(const E of ae.scope?.repositories??[])E.host&&E.owner&&E.repo&&i.add(`${E.host}/${E.owner}/${E.repo}`.toLowerCase());return i.add(n.toLowerCase()),i},[ae.scope,n]),m=u.useCallback(i=>{Y.has(i.repoRef.toLowerCase())?Dt(s,i.repoRef,i.number):ye(i.url)},[s,Y]),{labels:q,assignees:et,loading:we}=Je(s,n,l),ne=i=>{a&&(i==="title"?(T(a.title),N(!0)):i==="body"?(I(a.body??""),z(!0)):($((a.labels??[]).map(E=>E.name)),h((a.assignees??[]).map(E=>E.login).filter(Boolean)),G(!0)))},fe=u.useCallback(async i=>{const E=await d(s,n,r,i,l);return E.ok?(N(!1),z(!1),G(!1),!0):(P.error(E.error?.kind==="failed"?E.error.message:"Update failed"),!1)},[d,s,n,r,l]),tt=u.useCallback(async i=>{const E=Be(i),ge=await d(s,n,r,E,l);return ge.ok?!0:(P.error(ge.error?.kind==="failed"?ge.error.message:"State change failed"),!1)},[d,s,n,r,l]),st=Ot(a?.url),at=u.useCallback(async()=>{if(!(!a||Z)){ee(!0);try{const i=await l.agentContext(s,n,"issue",r);ns({kind:"issue",number:r,title:a.title,url:a.url,contextText:i.text},rs()),P.success("Added to composer")}catch(i){P.error(i instanceof Error?i.message:"Failed to fetch GitHub context")}finally{ee(!1)}}},[a,Z,l,s,n,r]),K=u.useMemo(()=>{const i=[...e.comments];return Q==="newest"&&i.reverse(),i},[e.comments,Q]),nt=u.useMemo(()=>K.filter(i=>!De(i.author?.login)),[K]),rt=u.useMemo(()=>K.filter(i=>De(i.author?.login)),[K]),ke=a?.state==="closed",Se=w!==null,V=a??(e.seed&&e.seed.number===r?e.seed:null),be=t.jsxs(t.Fragment,{children:[t.jsx(_t,{onBack:e.onBack,backLabel:"Back to issues",repoName:p,number:r,url:V?.url,numberTintClass:Kt("issue",V?.state??"open",!1,a?.stateReason),statePill:V?t.jsx(Ut,{kind:"issue",state:V.state,stateReason:a?.stateReason}):void 0,openLabel:`Open issue #${r} on GitHub`,title:V?.title??null,onEditTitle:a?()=>ne("title"):void 0,editTitleLabel:"Edit issue title",editTitleDisabledReason:M.allowed?null:M.reason,meta:V?t.jsx(Es,{issue:V}):void 0,primary:a?t.jsxs(j,{type:"button",variant:"default",size:"xs",onClick:()=>J(!0),disabled:Se,"aria-label":"Start session from issue",children:[t.jsx(R,{name:"add-circle",className:"size-3.5"}),"Start session"]}):void 0}),a?t.jsx(Is,{number:r,closed:ke,closeReason:S,onCloseReasonChange:f,closeAllowed:a.state!=="closed"?F.allowed:!1,closeReasonText:a.state!=="closed"?F.reason:"Already closed",reopenAllowed:a.state==="closed"?F.allowed:!1,reopenReasonText:a.state==="closed"?F.reason:"Already open",acting:c,onStateAction:i=>tt(i),askSending:Z,onAskAgent:()=>{at()},onEditTitle:()=>ne("title"),editAllowed:M.allowed,editReasonText:M.reason,onCopyLink:st,url:a.url}):null]});if(!a&&e.detailError)return t.jsx(ie,{header:be,tabs:[],activeTab:"",onTabChange:()=>{},children:t.jsx(cs,{icon:"error-warning",title:"Could not load this issue",action:t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:e.onRetryDetail,disabled:e.detailLoading,children:"Retry"})})});if(!a)return t.jsx(ie,{header:be,tabs:[],activeTab:"",onTabChange:()=>{},children:t.jsx(Wt,{label:"Loading issue"})});const re=ke?"reopen":"close";return t.jsxs(ie,{header:be,tabs:[],activeTab:"",onTabChange:()=>{},children:[t.jsxs("div",{className:"flex flex-col gap-1 px-3 py-2",children:[e.detailStale?t.jsxs("p",{className:"typography-micro text-muted-foreground",role:"note",children:["Showing saved issue — last refresh failed."," ",t.jsx("button",{type:"button",className:"underline",onClick:e.onRetryDetail,children:"Retry"})]}):null,o?t.jsxs("p",{className:"flex items-start gap-2 rounded-md border border-[var(--status-error-border)] bg-[var(--status-error-background)] px-3 py-2 typography-micro text-foreground",role:"alert",children:[t.jsx(R,{name:"error-warning",className:"size-4 shrink-0 text-[var(--status-error)]","aria-hidden":"true"}),t.jsx("span",{className:"min-w-0",children:o.kind==="failed"?o.message:"Action failed"})]}):null,U.permissionFallback?t.jsx("p",{className:"typography-micro text-muted-foreground",role:"note",children:"Permissions could not be loaded — actions stay enabled and any failure will be shown after you act."}):null,x?t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1 py-1",children:[t.jsx(Oe,{value:k,onChange:i=>T(i.target.value),"aria-label":"Issue title",className:"h-7"}),t.jsx(j,{type:"button",variant:"default",size:"xs",onClick:()=>{fe({title:k})},disabled:c||!k.trim(),children:"Save"}),t.jsx(j,{type:"button",variant:"ghost",size:"xs",onClick:()=>N(!1),disabled:c,children:"Cancel"})]}):null,t.jsxs("div",{className:"flex flex-col gap-1.5 py-1",children:[t.jsx(oe,{icon:"user",label:"Assignees",children:t.jsx("span",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:(a.assignees??[]).length===0?t.jsx("span",{className:"typography-micro text-muted-foreground",children:"Unassigned"}):(a.assignees??[]).map(i=>t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1 typography-micro text-muted-foreground",children:[t.jsx(We,{login:i.login,avatarUrl:i.avatarUrl,size:"xs"}),t.jsx("span",{className:"truncate",children:i.login})]},i.login))})}),t.jsx(oe,{icon:"list-unordered",label:"Labels",children:t.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-1",children:[(a.labels??[]).length===0?t.jsx("span",{className:"typography-micro text-muted-foreground",children:"None"}):(a.labels??[]).map(i=>t.jsx(qt,{name:i.name,color:i.color},i.name)),t.jsx(j,{type:"button",variant:"ghost",size:"xs",onClick:()=>ne("meta"),"aria-label":"Edit labels and assignees",title:te.reason??"Edit labels and assignees",disabled:!te.allowed,children:"Edit"})]})}),a.milestone?t.jsx(oe,{icon:"time",label:"Milestone",children:t.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:a.milestone.title})}):null,t.jsx(oe,{icon:"git-pull-request",label:"Linked PRs",children:t.jsx("span",{className:"min-w-0 flex-1",children:e.linkedPullRequestsError?t.jsxs("span",{className:"flex items-center gap-2 typography-micro text-[var(--status-error)]",role:"alert",children:[t.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Linked pull requests failed to load"}),t.jsx(j,{type:"button",variant:"outline",size:"xs",onClick:e.onRetryDetail,children:"Retry"})]}):(e.linkedPullRequests??[]).length===0?t.jsx("span",{className:"typography-micro text-muted-foreground",children:"None"}):t.jsx("ul",{className:"flex min-w-0 flex-col",children:(e.linkedPullRequests??[]).map(i=>{const E=Y.has(i.repoRef.toLowerCase());return t.jsx("li",{children:t.jsx(Pe,{glyph:t.jsx(Ke,{kind:"pr",state:i.state,draft:i.draft}),number:`#${i.number}`,title:i.title||"(no title)",meta:t.jsxs("span",{className:"truncate",children:[Vt(i.repoRef),E?"":" · GitHub"]}),onOpen:()=>m(i),ariaLabel:`Open linked pull request #${i.number}: ${i.title}`})},`${i.repoRef}#${i.number}`)})})})}),B?t.jsxs("div",{className:"flex flex-col gap-2 py-1",children:[t.jsx("p",{className:"typography-micro font-medium text-muted-foreground",children:"Labels"}),t.jsx(Ye,{candidates:q,loading:we,selected:A,onChange:$}),t.jsx("p",{className:"typography-micro font-medium text-muted-foreground",children:"Assignees"}),t.jsx(Xe,{candidates:et,loading:we,selected:O,onChange:h}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(j,{type:"button",size:"sm",onClick:()=>{fe({labels:A,assignees:O})},disabled:c,children:"Save"}),t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:()=>G(!1),disabled:c,children:"Cancel"})]})]}):null]}),t.jsx(Ge,{id:`issue-${r}-description`,title:"Description",action:H?void 0:t.jsx(j,{type:"button",variant:"ghost",size:"xs",onClick:()=>ne("body"),"aria-label":"Edit issue body",title:M.reason??"Edit issue body",disabled:!M.allowed,children:"Edit"}),children:H?t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(_e,{value:D,onChange:i=>I(i.target.value),"aria-label":"Issue body",rows:6}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(j,{type:"button",size:"sm",onClick:()=>{fe({body:D})},disabled:c,children:"Save"}),t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:()=>z(!1),disabled:c,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(Qt,{markdown:a.body??"",html:a.bodyHtml??null,fallbackUrl:a.url}),a.body?.trim()?null:t.jsx("p",{className:"typography-micro text-muted-foreground",children:"No description."})]})}),t.jsx(Ge,{id:`issue-${r}-comments`,title:`Comments${K.length?` (${K.length})`:""}`,action:t.jsx(Yt,{order:Q,onToggle:()=>me(i=>i==="newest"?"oldest":"newest")}),children:t.jsxs("div",{className:"flex flex-col gap-2",children:[K.length===0&&!e.commentsLoading?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"No comments yet."}):nt.map(i=>t.jsx(Jt,{comment:i},i.id)),t.jsx(Zt,{comments:rt}),e.commentsLoading&&K.length===0?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"Loading comments…"}):null,t.jsx(us,{hasMore:e.commentsHasMore,isLoading:e.commentsLoading,onLoadMore:e.onLoadMoreComments,label:"Load older comments"}),se.allowed?t.jsx(ht,{draft:v,onDraftChange:L,onDraftBlur:_,ariaLabel:`Leave a comment on issue #${r}`,busy:W,error:de,disabledReason:se.reason,followUp:{id:re,label:re==="close"?"Close with comment":"Reopen with comment",busyLabel:re==="close"?"Closing…":"Reopening…",onRun:()=>{X(re,v)},allowed:F.allowed,reason:F.reason},onSubmitComment:()=>{X("comment",v)}}):null]})})]}),a?t.jsx(Ns,{open:he,onOpenChange:J,issueNumber:r,issueTitle:a.title,busy:Se,onChoose:i=>{J(!1),y({directory:s,repo:n,number:r,kind:"issue",title:a.title,url:a.url,target:i})}}):null]})},Ds=({directory:e,repo:s,github:n,onCreated:r,onCancel:l})=>{const a=C(v=>v.createIssue),[d,b]=u.useState(""),[o,c]=u.useState(""),[y,w]=u.useState([]),[p,S]=u.useState([]),[f,x]=u.useState(""),[N,k]=u.useState([]),[T,H]=u.useState(null),{labels:z,assignees:D,loading:I}=Je(e,s,n),[B,G]=u.useState(!1),[A,$]=u.useState({});u.useEffect(()=>{let v=!1;return n.issueTemplates(e,s).then(L=>{v||(k(L.templates),H(L.templates.length===0?"No markdown templates in this repository. YAML issue forms are not supported.":null))}).catch(()=>{v||H("Issue templates are unavailable.")}),()=>{v=!0}},[n,e,s]);const O=v=>{if(x(v),!v)return;const L=N.find(_=>_.filename===v);L&&c(_=>ls(_,L.body))},h=async()=>{const v=is({title:d,body:o});if($(v.errors),!!v.ok){G(!0);try{const L=await a({directory:e,repo:s,title:d.trim(),body:o.trim()?o:void 0,labels:y.length>0?y:void 0,assignees:p.length>0?p:void 0},n);if(!L.ok||typeof L.number!="number"){P.error(L.error?.kind==="failed"?L.error.message:"Could not create the issue");return}P.success(`Issue #${L.number} created`),r(L.number)}finally{G(!1)}}};return t.jsx(ie,{header:t.jsxs("div",{className:"flex h-7 min-w-0 items-center gap-1 px-2 pt-1",children:[t.jsx(j,{type:"button",variant:"ghost",size:"icon",onClick:l,title:"Back to issues","aria-label":"Back to issues",className:"size-6 shrink-0",children:t.jsx(R,{name:"arrow-left",className:"size-4"})}),t.jsx("h1",{className:"min-w-0 flex-1 truncate text-base font-semibold text-foreground",children:"New issue"})]}),tabs:[],activeTab:"",onTabChange:()=>{},children:t.jsxs("div",{className:"flex flex-col gap-3 px-4 py-3",children:[t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("label",{htmlFor:"new-issue-title",className:"typography-micro font-medium text-muted-foreground",children:"Title"}),t.jsx(Oe,{id:"new-issue-title",value:d,onChange:v=>b(v.target.value),placeholder:"Short summary","aria-label":"Issue title",className:"h-8",maxLength:300}),A.title?t.jsx("p",{className:"typography-micro text-[var(--status-error)]",role:"alert",children:A.title}):null]}),t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("label",{htmlFor:"new-issue-template",className:"typography-micro font-medium text-muted-foreground",children:"Template"}),t.jsxs("select",{id:"new-issue-template","aria-label":"Issue template",value:f,onChange:v=>O(v.target.value),className:"h-8 rounded-md border border-border bg-[var(--surface-elevated)] px-2 typography-micro text-foreground",children:[t.jsx("option",{value:"",children:"No template"}),N.map(v=>t.jsx("option",{value:v.filename,children:v.name},v.filename))]}),T?t.jsx("p",{className:"typography-micro text-muted-foreground",children:T}):null]}),t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("label",{htmlFor:"new-issue-body",className:"typography-micro font-medium text-muted-foreground",children:"Body"}),t.jsx(_e,{id:"new-issue-body",value:o,onChange:v=>c(v.target.value),placeholder:"Describe the issue","aria-label":"Issue body",rows:8}),A.body?t.jsx("p",{className:"typography-micro text-[var(--status-error)]",role:"alert",children:A.body}):null]}),t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("span",{className:"typography-micro font-medium text-muted-foreground",children:"Labels"}),t.jsx(Ye,{candidates:z,loading:I,selected:y,onChange:w})]}),t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("span",{className:"typography-micro font-medium text-muted-foreground",children:"Assignees"}),t.jsx(Xe,{candidates:D,loading:I,selected:p,onChange:S})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(j,{type:"button",size:"sm",onClick:h,disabled:B||!d.trim(),"aria-label":"Create issue",children:B?"Creating…":"Create issue"}),t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:l,disabled:B,children:"Cancel"})]})]})})},Gs=({directory:e,repo:s,isRefreshing:n,registerRefresh:r,onRefreshChange:l,headerActionsSlot:a=null,headerActionsPresentation:d="drawer"})=>{const o=$e().github??null,c=js(e,s),y=ws(e),w=Gt(),[p,S]=u.useState(!1),f=y.repo===s&&typeof y.number=="number"?y.number:null,x=c.state==="open"?"open":c.state==="all"?"both":"closed",N=u.useCallback(()=>{o&&(l(!0),C.getState().refreshAllForScope(e,s,o).catch(()=>null).finally(()=>l(!1)))},[o,e,s,l]);u.useEffect(()=>(r(N),()=>r(null)),[r,N]),u.useEffect(()=>{o&&(l(!0),C.getState().ensureCollectionsFresh(e,s,x,o).catch(()=>null).finally(()=>l(!1)))},[o,e,s,x]),u.useEffect(()=>{if(!o||f===null)return;const m=C.getState();m.ensureDetail(e,s,f,o),m.ensureComments(e,s,f,o)},[o,e,s,f]),u.useEffect(()=>{if(!o)return;const m=()=>{typeof document<"u"&&document.hidden||C.getState().ensureCollectionsFresh(e,s,x,o).catch(()=>{})};return window.addEventListener("focus",m),document.addEventListener("visibilitychange",m),()=>{window.removeEventListener("focus",m),document.removeEventListener("visibilitychange",m)}},[o,e,s,x]),u.useEffect(()=>Tt(m=>{C.getState().notifyAgentTurnComplete(m)}),[]);const k=Me(s,"open"),T=Me(s,"closed"),H=u.useMemo(()=>ps(s),[s,k?.data,T?.data]),z=u.useMemo(()=>new Set(H.map(m=>m.number)),[H]),D=u.useMemo(()=>Ht(H,{state:c.state,involvement:c.involvement,labels:c.labels,search:c.search,sort:c.sort,viewerLogin:w}),[H,c.state,c.involvement,c.labels,c.search,c.sort,w]),I=x==="both"?[k,T]:[x==="open"?k:T],B=I.some(m=>m?.data!=null),G=B&&I.every(m=>m?.data?.nextCursor==null),A=I.reduce((m,q)=>m+(q?.data?.items.length??0),0),$=I.find(m=>m?.error)?.error??null,O=I.some(m=>m?.stale),h=c.search.trim(),v=c.labels.trim(),L=c.involvement!=="all"&&!w||c.involvement==="mentioned",_=h.length>0||v.length>0||c.involvement!=="all",W=u.useMemo(()=>({state:c.state,involvement:c.involvement,labels:v,q:h}),[c.state,c.involvement,v,h]),de=`${W.state}|${W.involvement}|${W.labels}|${W.q}`,X=!G&&B&&(D.length===0||L)&&(h.length>0||v.length>0||L),Q=u.useCallback(m=>o?C.getState().searchRemote(e,s,m,o):Promise.resolve(null),[e,s,o]),me=u.useCallback(m=>o?C.getState().loadMoreRemote(e,s,m,o):Promise.resolve(null),[e,s,o]),{remoteView:he,numberJump:J,remotePending:Z,handleSearchAll:ee}=gt({repo:s,query:W,queryKey:de,autoRemote:X,indexNumbers:z,visibleItems:D,searchText:h,useRemoteEntry:ys,runSearch:Q,runLoadMore:me}),U=u.useMemo(()=>{if(G||!B||!_)return null;const m=D.length===1?"1 match":`${D.length} matches`,q=A===1?"1 most recent loaded issue":`${A} most recent loaded issues`;return`Showing ${m} from the ${q}`},[G,B,_,D.length,A]),F=vs(s,f),M=Cs(s,f),te=u.useCallback(()=>{!o||f===null||C.getState().loadMoreComments(e,s,f,o)},[o,e,s,f]),se=u.useCallback(()=>{C.getState().selectIssue(e,null,null)},[e]),ae=u.useCallback(()=>{!o||f===null||C.getState().refreshDetail(e,s,f,o)},[o,e,s,f]),Y=u.useCallback(()=>{!o||f===null||C.getState().refreshComments(e,s,f,o)},[o,e,s,f]);if(!o)return null;if(p)return t.jsx(Ds,{directory:e,repo:s,github:o,onCancel:()=>S(!1),onCreated:m=>{S(!1),C.getState().selectIssue(e,s,m)}});if(f!==null){const m=F?.data?.detail??null;return t.jsx(As,{directory:e,repo:s,number:f,github:o,seed:xs(s,f),issue:m?.issue??null,linkedPullRequests:m?.linkedPullRequests??[],linkedPullRequestsError:m?.sectionErrors?.linkedPullRequests??null,capabilities:m?.capabilities??null,viewerLogin:m?.viewerLogin??null,viewerPermission:m?.viewerPermission??null,detailError:F?.error??null,detailStale:F?.stale??!1,detailLoading:F?.isLoading??!1,comments:M?.data?.comments??[],commentsHasMore:!!M?.data?.nextCursor,commentsLoading:M?.isLoading??!1,onLoadMoreComments:te,onBack:se,onRetryDetail:ae,onRetryComments:Y})}return t.jsx(Ss,{items:D,headerActionsSlot:a,headerActionsPresentation:d,hasMore:I.some(m=>m?.data?.nextCursor!=null),isLoadingMore:I.some(m=>m?.isLoading),isLoading:I.some(m=>m?.isLoading),isRefreshing:n,stale:O,error:$,filters:c,countComplete:G,incompleteNotice:U?{summary:U,searching:Z,onSearchAll:ee}:null,remote:he,numberJump:J,onFiltersChange:m=>C.getState().setFilters(e,s,m),onClearFilters:()=>C.getState().resetFilters(e,s),onLoadMore:()=>{const m=x==="both"?["open","closed"]:[x];Promise.all(m.map(q=>C.getState().loadMoreCollection(e,s,q,o)))},onRetry:()=>N(),onOpen:m=>C.getState().selectIssue(e,s,m),onNewIssue:()=>S(!0)})},Xs=({headerActionsSlot:e=null,headerActionsPresentation:s="drawer"})=>{const n=Et()??"",[r,l]=u.useState(!1),a=u.useRef(null),d=u.useCallback(o=>{a.current=o},[]),b=u.useCallback(o=>l(o),[]);return n?t.jsx(bt,{directory:n,isRefreshing:r,onRefresh:()=>a.current?.(),children:({repo:o,directory:c})=>t.jsx(Gs,{directory:c,repo:o,isRefreshing:r,registerRefresh:d,onRefreshChange:b,headerActionsSlot:e,headerActionsPresentation:s})}):t.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center",children:t.jsx("p",{className:"typography-ui text-muted-foreground",children:"Open a project to browse issues."})})};export{Xs as IssuesSurface};
7
+ ${d}`:ts({repo:e.repo,number:e.number,title:e.title,url:e.url,contextText:d}),y=[{text:ss({kind:e.kind,number:e.number,title:e.title,url:e.url}),synthetic:!0},{text:d,synthetic:!0}];if(e.target==="current")return l({directoryOverride:e.directory,title:o,initialPrompt:c,syntheticParts:y}),{ok:!0,directory:e.directory};if(!r?.getGitBranches||!r?.createGitWorktree)return{ok:!1,error:"Worktree creation is not available in this runtime"};let w,p=!1;try{const x=await r.getGitBranches(e.directory);if(w=x.current?.trim()??"",!w)throw new Error("no current branch");p=Array.isArray(x.all)&&x.all.includes(ze(e))}catch{return{ok:!1,error:"Could not determine the current branch to start the worktree from"}}const S=ze(e);let f;try{if(p){let x=null;if(r.listGitWorktrees)try{const N=await r.listGitWorktrees(e.directory);x=Array.isArray(N)?N.find(k=>!k?.prunable&&k?.branch===S)?.path??null:null}catch{x=null}if(x)f=x;else if(f=(await r.createGitWorktree(e.directory,{mode:"existing",existingBranch:S})).path,!f)throw new Error("worktree path missing")}else if(f=(await r.createGitWorktree(e.directory,{mode:"new",startRef:w,branchName:S})).path,!f)throw new Error("worktree path missing")}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Worktree creation failed"}}return await a?.(e.directory),l({directoryOverride:f,title:o,initialPrompt:c,syntheticParts:y}),{ok:!0,directory:f}},Ls=()=>{const e=$e(),s=kt(a=>a.openNewSessionDraft),[n,r]=u.useState(null);return{start:u.useCallback(async a=>{const d=e.github;if(!d)return P.error("GitHub is not available in this runtime"),!1;const b=`${a.repo}#${a.number}:${a.target}`;r(b);try{const o=await Rs(a,{github:d,git:e.git??null,refreshWorktrees:c=>ut(c,e.git),openDraft:c=>s(c)});return o.ok?(P.success(a.target==="worktree"?"Worktree ready — session draft opened":"Session draft opened"),!0):(P.error(o.error),!1)}finally{r(null)}},[e.github,e.git,s]),startingKey:n}},Es=({issue:e})=>t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(We,{login:e.author?.login,avatarUrl:e.author?.avatarUrl,size:"xs"}),e.author?.login??"ghost"]}),e.createdAt?` · opened ${Te(e.createdAt)}`:"",e.updatedAt&&e.updatedAt!==e.createdAt?` · updated ${Te(e.updatedAt)}`:""]}),Is=({number:e,closed:s,closeReason:n,onCloseReasonChange:r,closeAllowed:l,closeReasonText:a,reopenAllowed:d,reopenReasonText:b,acting:o,onStateAction:c,askSending:y,onAskAgent:w,onEditTitle:p,editAllowed:S,editReasonText:f,onCopyLink:x,url:N})=>t.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 px-3 pt-1 pb-2","aria-label":"Issue actions",children:[s?t.jsx(Ne,{copy:Fe("reopen",e),busy:o,variant:"outline",disabled:!d,disabledReason:b??"Reopen issue",label:"Reopen issue",icon:t.jsx(R,{name:"history",className:"size-3.5","aria-hidden":"true"}),onConfirm:()=>{c("reopen")}}):t.jsxs("span",{role:"group","aria-label":"Close issue",className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(Ne,{copy:Fe(n==="not_planned"?"close-not-planned":"close-completed",e),busy:o,destructive:!0,variant:"outline",disabled:!l,disabledReason:a??"Close issue",label:"Close issue",icon:t.jsx(R,{name:"close",className:"size-3.5","aria-hidden":"true"}),onConfirm:()=>{c(n==="not_planned"?"close-not-planned":"close-completed")}}),t.jsxs(Re,{modal:!1,children:[t.jsx(Le,{asChild:!0,children:t.jsx(j,{type:"button",variant:"outline",size:"xs",className:"shrink-0 px-1.5",title:"Close options","aria-label":"Close options",disabled:!l||o,children:t.jsx(R,{name:"arrow-down-s",className:"size-3.5"})})}),t.jsx(Ee,{align:"start",className:"w-60",children:t.jsx(Nt,{value:n,onValueChange:k=>r(k),children:os.map(k=>t.jsx(Rt,{value:k.id,children:k.id==="completed"?"Close as completed":"Close as not planned"},k.id))})})]})]}),t.jsxs(j,{type:"button",variant:"outline",size:"xs",className:"shrink-0",onClick:w,disabled:y,title:"Send issue context to the agent composer","aria-label":"Ask agent about this issue",children:[t.jsx(R,{name:"send-plane-2",className:"size-3.5","aria-hidden":"true"}),y?"Asking…":"Ask agent"]}),t.jsxs(j,{type:"button",variant:"ghost",size:"xs",className:"shrink-0",onClick:()=>{ye(N)},title:"Open on GitHub","aria-label":"Open on GitHub",children:[t.jsx(R,{name:"external-link",className:"size-3.5","aria-hidden":"true"}),"Open on GitHub"]}),t.jsxs(Re,{modal:!1,children:[t.jsx(Le,{asChild:!0,children:t.jsx(j,{type:"button",variant:"ghost",size:"xs",className:"shrink-0 px-1.5","aria-label":"More issue actions",title:"More issue actions",children:t.jsx(R,{name:"more-2",className:"size-4"})})}),t.jsxs(Ee,{align:"end",className:"w-60",children:[t.jsxs(pe,{onClick:p,disabled:!S,title:f??"Edit title",children:[t.jsx(R,{name:"pencil",className:"size-3.5"}),"Edit title"]}),t.jsx(Lt,{}),t.jsxs(pe,{onClick:()=>{ye(N)},children:[t.jsx(R,{name:"external-link",className:"size-3.5"}),"Open on GitHub"]}),t.jsxs(pe,{onClick:x,children:[t.jsx(R,{name:"file-copy",className:"size-3.5"}),"Copy link"]})]})]})]}),As=e=>{const{directory:s,repo:n,number:r,github:l,issue:a}=e,d=C(i=>i.updateIssue),b=C(i=>i.addComment),o=C(i=>i.actionErrorByDetail[`${n}#${r}`]??null),c=C(i=>i.actingActions[`${n}#${r}`]??!1),{start:y,startingKey:w}=Ls(),p=Pt(s,n),[S,f]=u.useState("completed"),[x,N]=u.useState(!1),[k,T]=u.useState(""),[H,z]=u.useState(!1),[D,I]=u.useState(""),[B,G]=u.useState(!1),[A,$]=u.useState([]),[O,h]=u.useState([]),{draft:v,onDraftChange:L,flushDraft:_}=dt(n,r),{busy:W,error:de,submit:X}=mt({postComment:i=>b(s,n,r,i,l),runFollowUp:i=>d(s,n,r,Be(i==="reopen"?"reopen":S==="not_planned"?"close-not-planned":"close-completed"),l),verbs:{close:"close",reopen:"reopen"},doneLabels:{close:"Closed with comment",reopen:"Reopened with comment"},afterPost:()=>{L(""),ft.getState().clearCommentDraft(n,r)}}),[Q,me]=u.useState("newest"),[he,J]=u.useState(!1),[Y,ee]=u.useState(!1),U=u.useMemo(()=>({capabilities:e.capabilities??null,isAuthor:$t(a?.author?.login,e.viewerLogin),permissionFallback:e.viewerPermission?.fallback===!0}),[e.capabilities,e.viewerLogin,e.viewerPermission?.fallback,a?.author?.login]),F=le(a?.state==="closed"?"reopen":"close",a,U),M=le("edit",a,U),te=le("labels",a,U),se=le("comment",a,U),ae=St(s),Z=u.useMemo(()=>{const i=new Set;for(const E of ae.scope?.repositories??[])E.host&&E.owner&&E.repo&&i.add(`${E.host}/${E.owner}/${E.repo}`.toLowerCase());return i.add(n.toLowerCase()),i},[ae.scope,n]),m=u.useCallback(i=>{Z.has(i.repoRef.toLowerCase())?Dt(s,i.repoRef,i.number):ye(i.url)},[s,Z]),{labels:q,assignees:et,loading:we}=Je(s,n,l),ne=i=>{a&&(i==="title"?(T(a.title),N(!0)):i==="body"?(I(a.body??""),z(!0)):($((a.labels??[]).map(E=>E.name)),h((a.assignees??[]).map(E=>E.login).filter(Boolean)),G(!0)))},fe=u.useCallback(async i=>{const E=await d(s,n,r,i,l);return E.ok?(N(!1),z(!1),G(!1),!0):(P.error(E.error?.kind==="failed"?E.error.message:"Update failed"),!1)},[d,s,n,r,l]),tt=u.useCallback(async i=>{const E=Be(i),ge=await d(s,n,r,E,l);return ge.ok?!0:(P.error(ge.error?.kind==="failed"?ge.error.message:"State change failed"),!1)},[d,s,n,r,l]),st=Ot(a?.url),at=u.useCallback(async()=>{if(!(!a||Y)){ee(!0);try{const i=await l.agentContext(s,n,"issue",r);ns({kind:"issue",number:r,title:a.title,url:a.url,contextText:i.text},rs()),P.success("Added to composer")}catch(i){P.error(i instanceof Error?i.message:"Failed to fetch GitHub context")}finally{ee(!1)}}},[a,Y,l,s,n,r]),K=u.useMemo(()=>{const i=[...e.comments];return Q==="newest"&&i.reverse(),i},[e.comments,Q]),nt=u.useMemo(()=>K.filter(i=>!De(i.author?.login)),[K]),rt=u.useMemo(()=>K.filter(i=>De(i.author?.login)),[K]),ke=a?.state==="closed",Se=w!==null,V=a??(e.seed&&e.seed.number===r?e.seed:null),be=t.jsxs(t.Fragment,{children:[t.jsx(_t,{onBack:e.onBack,backLabel:"Back to issues",repoName:p,number:r,url:V?.url,numberTintClass:Kt("issue",V?.state??"open",!1,a?.stateReason),statePill:V?t.jsx(Ut,{kind:"issue",state:V.state,stateReason:a?.stateReason}):void 0,openLabel:`Open issue #${r} on GitHub`,title:V?.title??null,onEditTitle:a?()=>ne("title"):void 0,editTitleLabel:"Edit issue title",editTitleDisabledReason:M.allowed?null:M.reason,meta:V?t.jsx(Es,{issue:V}):void 0,primary:a?t.jsxs(j,{type:"button",variant:"default",size:"xs",onClick:()=>J(!0),disabled:Se,"aria-label":"Start session from issue",children:[t.jsx(R,{name:"add-circle",className:"size-3.5"}),"Start session"]}):void 0}),a?t.jsx(Is,{number:r,closed:ke,closeReason:S,onCloseReasonChange:f,closeAllowed:a.state!=="closed"?F.allowed:!1,closeReasonText:a.state!=="closed"?F.reason:"Already closed",reopenAllowed:a.state==="closed"?F.allowed:!1,reopenReasonText:a.state==="closed"?F.reason:"Already open",acting:c,onStateAction:i=>tt(i),askSending:Y,onAskAgent:()=>{at()},onEditTitle:()=>ne("title"),editAllowed:M.allowed,editReasonText:M.reason,onCopyLink:st,url:a.url}):null]});if(!a&&e.detailError)return t.jsx(ie,{header:be,tabs:[],activeTab:"",onTabChange:()=>{},children:t.jsx(cs,{icon:"error-warning",title:"Could not load this issue",action:t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:e.onRetryDetail,disabled:e.detailLoading,children:"Retry"})})});if(!a)return t.jsx(ie,{header:be,tabs:[],activeTab:"",onTabChange:()=>{},children:t.jsx(Wt,{label:"Loading issue"})});const re=ke?"reopen":"close";return t.jsxs(ie,{header:be,tabs:[],activeTab:"",onTabChange:()=>{},children:[t.jsxs("div",{className:"flex flex-col gap-1 px-3 py-2",children:[e.detailStale?t.jsxs("p",{className:"typography-micro text-muted-foreground",role:"note",children:["Showing saved issue — last refresh failed."," ",t.jsx("button",{type:"button",className:"underline",onClick:e.onRetryDetail,children:"Retry"})]}):null,o?t.jsxs("p",{className:"flex items-start gap-2 rounded-md border border-[var(--status-error-border)] bg-[var(--status-error-background)] px-3 py-2 typography-micro text-foreground",role:"alert",children:[t.jsx(R,{name:"error-warning",className:"size-4 shrink-0 text-[var(--status-error)]","aria-hidden":"true"}),t.jsx("span",{className:"min-w-0",children:o.kind==="failed"?o.message:"Action failed"})]}):null,U.permissionFallback?t.jsx("p",{className:"typography-micro text-muted-foreground",role:"note",children:"Permissions could not be loaded — actions stay enabled and any failure will be shown after you act."}):null,x?t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1 py-1",children:[t.jsx(Oe,{value:k,onChange:i=>T(i.target.value),"aria-label":"Issue title",className:"h-7"}),t.jsx(j,{type:"button",variant:"default",size:"xs",onClick:()=>{fe({title:k})},disabled:c||!k.trim(),children:"Save"}),t.jsx(j,{type:"button",variant:"ghost",size:"xs",onClick:()=>N(!1),disabled:c,children:"Cancel"})]}):null,t.jsxs("div",{className:"flex flex-col gap-1.5 py-1",children:[t.jsx(oe,{icon:"user",label:"Assignees",children:t.jsx("span",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:(a.assignees??[]).length===0?t.jsx("span",{className:"typography-micro text-muted-foreground",children:"Unassigned"}):(a.assignees??[]).map(i=>t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1 typography-micro text-muted-foreground",children:[t.jsx(We,{login:i.login,avatarUrl:i.avatarUrl,size:"xs"}),t.jsx("span",{className:"truncate",children:i.login})]},i.login))})}),t.jsx(oe,{icon:"list-unordered",label:"Labels",children:t.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-1",children:[(a.labels??[]).length===0?t.jsx("span",{className:"typography-micro text-muted-foreground",children:"None"}):(a.labels??[]).map(i=>t.jsx(qt,{name:i.name,color:i.color},i.name)),t.jsx(j,{type:"button",variant:"ghost",size:"xs",onClick:()=>ne("meta"),"aria-label":"Edit labels and assignees",title:te.reason??"Edit labels and assignees",disabled:!te.allowed,children:"Edit"})]})}),a.milestone?t.jsx(oe,{icon:"time",label:"Milestone",children:t.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:a.milestone.title})}):null,t.jsx(oe,{icon:"git-pull-request",label:"Linked PRs",children:t.jsx("span",{className:"min-w-0 flex-1",children:e.linkedPullRequestsError?t.jsxs("span",{className:"flex items-center gap-2 typography-micro text-[var(--status-error)]",role:"alert",children:[t.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Linked pull requests failed to load"}),t.jsx(j,{type:"button",variant:"outline",size:"xs",onClick:e.onRetryDetail,children:"Retry"})]}):(e.linkedPullRequests??[]).length===0?t.jsx("span",{className:"typography-micro text-muted-foreground",children:"None"}):t.jsx("ul",{className:"flex min-w-0 flex-col",children:(e.linkedPullRequests??[]).map(i=>{const E=Z.has(i.repoRef.toLowerCase());return t.jsx("li",{children:t.jsx(Pe,{glyph:t.jsx(Ke,{kind:"pr",state:i.state,draft:i.draft}),number:`#${i.number}`,title:i.title||"(no title)",meta:t.jsxs("span",{className:"truncate",children:[Vt(i.repoRef),E?"":" · GitHub"]}),onOpen:()=>m(i),ariaLabel:`Open linked pull request #${i.number}: ${i.title}`})},`${i.repoRef}#${i.number}`)})})})}),B?t.jsxs("div",{className:"flex flex-col gap-2 py-1",children:[t.jsx("p",{className:"typography-micro font-medium text-muted-foreground",children:"Labels"}),t.jsx(Ze,{candidates:q,loading:we,selected:A,onChange:$}),t.jsx("p",{className:"typography-micro font-medium text-muted-foreground",children:"Assignees"}),t.jsx(Xe,{candidates:et,loading:we,selected:O,onChange:h}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(j,{type:"button",size:"sm",onClick:()=>{fe({labels:A,assignees:O})},disabled:c,children:"Save"}),t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:()=>G(!1),disabled:c,children:"Cancel"})]})]}):null]}),t.jsx(Ge,{id:`issue-${r}-description`,title:"Description",action:H?void 0:t.jsx(j,{type:"button",variant:"ghost",size:"xs",onClick:()=>ne("body"),"aria-label":"Edit issue body",title:M.reason??"Edit issue body",disabled:!M.allowed,children:"Edit"}),children:H?t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(_e,{value:D,onChange:i=>I(i.target.value),"aria-label":"Issue body",rows:6}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(j,{type:"button",size:"sm",onClick:()=>{fe({body:D})},disabled:c,children:"Save"}),t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:()=>z(!1),disabled:c,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(Qt,{markdown:a.body??"",html:a.bodyHtml??null,fallbackUrl:a.url}),a.body?.trim()?null:t.jsx("p",{className:"typography-micro text-muted-foreground",children:"No description."})]})}),t.jsx(Ge,{id:`issue-${r}-comments`,title:`Comments${K.length?` (${K.length})`:""}`,action:t.jsx(Zt,{order:Q,onToggle:()=>me(i=>i==="newest"?"oldest":"newest")}),children:t.jsxs("div",{className:"flex flex-col gap-2",children:[K.length===0&&!e.commentsLoading?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"No comments yet."}):nt.map(i=>t.jsx(Jt,{comment:i},i.id)),t.jsx(Yt,{comments:rt}),e.commentsLoading&&K.length===0?t.jsx("p",{className:"typography-micro text-muted-foreground",children:"Loading comments…"}):null,t.jsx(us,{hasMore:e.commentsHasMore,isLoading:e.commentsLoading,onLoadMore:e.onLoadMoreComments,label:"Load older comments"}),se.allowed?t.jsx(ht,{draft:v,onDraftChange:L,onDraftBlur:_,ariaLabel:`Leave a comment on issue #${r}`,busy:W,error:de,disabledReason:se.reason,followUp:{id:re,label:re==="close"?"Close with comment":"Reopen with comment",busyLabel:re==="close"?"Closing…":"Reopening…",onRun:()=>{X(re,v)},allowed:F.allowed,reason:F.reason},onSubmitComment:()=>{X("comment",v)}}):null]})})]}),a?t.jsx(Ns,{open:he,onOpenChange:J,issueNumber:r,issueTitle:a.title,busy:Se,onChoose:i=>{J(!1),y({directory:s,repo:n,number:r,kind:"issue",title:a.title,url:a.url,target:i})}}):null]})},Ds=({directory:e,repo:s,github:n,onCreated:r,onCancel:l})=>{const a=C(v=>v.createIssue),[d,b]=u.useState(""),[o,c]=u.useState(""),[y,w]=u.useState([]),[p,S]=u.useState([]),[f,x]=u.useState(""),[N,k]=u.useState([]),[T,H]=u.useState(null),{labels:z,assignees:D,loading:I}=Je(e,s,n),[B,G]=u.useState(!1),[A,$]=u.useState({});u.useEffect(()=>{let v=!1;return n.issueTemplates(e,s).then(L=>{v||(k(L.templates),H(L.templates.length===0?"No markdown templates in this repository. YAML issue forms are not supported.":null))}).catch(()=>{v||H("Issue templates are unavailable.")}),()=>{v=!0}},[n,e,s]);const O=v=>{if(x(v),!v)return;const L=N.find(_=>_.filename===v);L&&c(_=>ls(_,L.body))},h=async()=>{const v=is({title:d,body:o});if($(v.errors),!!v.ok){G(!0);try{const L=await a({directory:e,repo:s,title:d.trim(),body:o.trim()?o:void 0,labels:y.length>0?y:void 0,assignees:p.length>0?p:void 0},n);if(!L.ok||typeof L.number!="number"){P.error(L.error?.kind==="failed"?L.error.message:"Could not create the issue");return}P.success(`Issue #${L.number} created`),r(L.number)}finally{G(!1)}}};return t.jsx(ie,{header:t.jsxs("div",{className:"flex h-7 min-w-0 items-center gap-1 px-2 pt-1",children:[t.jsx(j,{type:"button",variant:"ghost",size:"icon",onClick:l,title:"Back to issues","aria-label":"Back to issues",className:"size-6 shrink-0",children:t.jsx(R,{name:"arrow-left",className:"size-4"})}),t.jsx("h1",{className:"min-w-0 flex-1 truncate text-base font-semibold text-foreground",children:"New issue"})]}),tabs:[],activeTab:"",onTabChange:()=>{},children:t.jsxs("div",{className:"flex flex-col gap-3 px-4 py-3",children:[t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("label",{htmlFor:"new-issue-title",className:"typography-micro font-medium text-muted-foreground",children:"Title"}),t.jsx(Oe,{id:"new-issue-title",value:d,onChange:v=>b(v.target.value),placeholder:"Short summary","aria-label":"Issue title",className:"h-8",maxLength:300}),A.title?t.jsx("p",{className:"typography-micro text-[var(--status-error)]",role:"alert",children:A.title}):null]}),t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("label",{htmlFor:"new-issue-template",className:"typography-micro font-medium text-muted-foreground",children:"Template"}),t.jsxs("select",{id:"new-issue-template","aria-label":"Issue template",value:f,onChange:v=>O(v.target.value),className:"h-8 rounded-md border border-border bg-[var(--surface-elevated)] px-2 typography-micro text-foreground",children:[t.jsx("option",{value:"",children:"No template"}),N.map(v=>t.jsx("option",{value:v.filename,children:v.name},v.filename))]}),T?t.jsx("p",{className:"typography-micro text-muted-foreground",children:T}):null]}),t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("label",{htmlFor:"new-issue-body",className:"typography-micro font-medium text-muted-foreground",children:"Body"}),t.jsx(_e,{id:"new-issue-body",value:o,onChange:v=>c(v.target.value),placeholder:"Describe the issue","aria-label":"Issue body",rows:8}),A.body?t.jsx("p",{className:"typography-micro text-[var(--status-error)]",role:"alert",children:A.body}):null]}),t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("span",{className:"typography-micro font-medium text-muted-foreground",children:"Labels"}),t.jsx(Ze,{candidates:z,loading:I,selected:y,onChange:w})]}),t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("span",{className:"typography-micro font-medium text-muted-foreground",children:"Assignees"}),t.jsx(Xe,{candidates:D,loading:I,selected:p,onChange:S})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(j,{type:"button",size:"sm",onClick:h,disabled:B||!d.trim(),"aria-label":"Create issue",children:B?"Creating…":"Create issue"}),t.jsx(j,{type:"button",variant:"outline",size:"sm",onClick:l,disabled:B,children:"Cancel"})]})]})})},Gs=({directory:e,repo:s,isRefreshing:n,registerRefresh:r,onRefreshChange:l,headerActionsSlot:a=null,headerActionsPresentation:d="drawer"})=>{const o=$e().github??null,c=js(e,s),y=ws(e),w=Gt(),[p,S]=u.useState(!1),f=y.repo===s&&typeof y.number=="number"?y.number:null,x=c.state==="open"?"open":c.state==="all"?"both":"closed",N=u.useCallback(()=>{o&&(l(!0),C.getState().refreshAllForScope(e,s,o).catch(()=>null).finally(()=>l(!1)))},[o,e,s,l]);u.useEffect(()=>(r(N),()=>r(null)),[r,N]),u.useEffect(()=>{o&&(l(!0),C.getState().ensureCollectionsFresh(e,s,x,o).catch(()=>null).finally(()=>l(!1)))},[o,e,s,x]),u.useEffect(()=>{if(!o||f===null)return;const m=C.getState();m.ensureDetail(e,s,f,o),m.ensureComments(e,s,f,o)},[o,e,s,f]),u.useEffect(()=>{if(!o)return;const m=()=>{typeof document<"u"&&document.hidden||C.getState().ensureCollectionsFresh(e,s,x,o).catch(()=>{})};return window.addEventListener("focus",m),document.addEventListener("visibilitychange",m),()=>{window.removeEventListener("focus",m),document.removeEventListener("visibilitychange",m)}},[o,e,s,x]),u.useEffect(()=>Tt(m=>{C.getState().notifyAgentTurnComplete(m)}),[]);const k=Me(s,"open"),T=Me(s,"closed"),H=u.useMemo(()=>ps(s),[s,k?.data,T?.data]),z=u.useMemo(()=>new Set(H.map(m=>m.number)),[H]),D=u.useMemo(()=>Ht(H,{state:c.state,involvement:c.involvement,labels:c.labels,search:c.search,sort:c.sort,viewerLogin:w}),[H,c.state,c.involvement,c.labels,c.search,c.sort,w]),I=x==="both"?[k,T]:[x==="open"?k:T],B=I.some(m=>m?.data!=null),G=B&&I.every(m=>m?.data?.nextCursor==null),A=I.reduce((m,q)=>m+(q?.data?.items.length??0),0),$=I.find(m=>m?.error)?.error??null,O=I.some(m=>m?.stale),h=c.search.trim(),v=c.labels.trim(),L=c.involvement!=="all"&&!w||c.involvement==="mentioned",_=h.length>0||v.length>0||c.involvement!=="all",W=u.useMemo(()=>({state:c.state,involvement:c.involvement,labels:v,q:h}),[c.state,c.involvement,v,h]),de=`${W.state}|${W.involvement}|${W.labels}|${W.q}`,X=!G&&B&&(D.length===0||L)&&(h.length>0||v.length>0||L),Q=u.useCallback(m=>o?C.getState().searchRemote(e,s,m,o):Promise.resolve(null),[e,s,o]),me=u.useCallback(m=>o?C.getState().loadMoreRemote(e,s,m,o):Promise.resolve(null),[e,s,o]),{remoteView:he,numberJump:J,remotePending:Y,handleSearchAll:ee}=gt({repo:s,query:W,queryKey:de,autoRemote:X,indexNumbers:z,visibleItems:D,searchText:h,useRemoteEntry:ys,runSearch:Q,runLoadMore:me}),U=u.useMemo(()=>{if(G||!B||!_)return null;const m=D.length===1?"1 match":`${D.length} matches`,q=A===1?"1 most recent loaded issue":`${A} most recent loaded issues`;return`Showing ${m} from the ${q}`},[G,B,_,D.length,A]),F=vs(s,f),M=Cs(s,f),te=u.useCallback(()=>{!o||f===null||C.getState().loadMoreComments(e,s,f,o)},[o,e,s,f]),se=u.useCallback(()=>{C.getState().selectIssue(e,null,null)},[e]),ae=u.useCallback(()=>{!o||f===null||C.getState().refreshDetail(e,s,f,o)},[o,e,s,f]),Z=u.useCallback(()=>{!o||f===null||C.getState().refreshComments(e,s,f,o)},[o,e,s,f]);if(!o)return null;if(p)return t.jsx(Ds,{directory:e,repo:s,github:o,onCancel:()=>S(!1),onCreated:m=>{S(!1),C.getState().selectIssue(e,s,m)}});if(f!==null){const m=F?.data?.detail??null;return t.jsx(As,{directory:e,repo:s,number:f,github:o,seed:xs(s,f),issue:m?.issue??null,linkedPullRequests:m?.linkedPullRequests??[],linkedPullRequestsError:m?.sectionErrors?.linkedPullRequests??null,capabilities:m?.capabilities??null,viewerLogin:m?.viewerLogin??null,viewerPermission:m?.viewerPermission??null,detailError:F?.error??null,detailStale:F?.stale??!1,detailLoading:F?.isLoading??!1,comments:M?.data?.comments??[],commentsHasMore:!!M?.data?.nextCursor,commentsLoading:M?.isLoading??!1,onLoadMoreComments:te,onBack:se,onRetryDetail:ae,onRetryComments:Z})}return t.jsx(Ss,{items:D,headerActionsSlot:a,headerActionsPresentation:d,hasMore:I.some(m=>m?.data?.nextCursor!=null),isLoadingMore:I.some(m=>m?.isLoading),isLoading:I.some(m=>m?.isLoading),isRefreshing:n,stale:O,error:$,filters:c,countComplete:G,incompleteNotice:U?{summary:U,searching:Y,onSearchAll:ee}:null,remote:he,numberJump:J,onFiltersChange:m=>C.getState().setFilters(e,s,m),onClearFilters:()=>C.getState().resetFilters(e,s),onLoadMore:()=>{const m=x==="both"?["open","closed"]:[x];Promise.all(m.map(q=>C.getState().loadMoreCollection(e,s,q,o)))},onRetry:()=>N(),onOpen:m=>C.getState().selectIssue(e,s,m),onNewIssue:()=>S(!0)})},ea=({headerActionsSlot:e=null,headerActionsPresentation:s="drawer"})=>{const n=Et()??"",[r,l]=u.useState(!1),a=u.useRef(null),d=u.useCallback(o=>{a.current=o},[]),b=u.useCallback(o=>l(o),[]);return n?t.jsx(bt,{directory:n,isRefreshing:r,onRefresh:()=>a.current?.(),children:({repo:o,directory:c})=>t.jsx(Gs,{directory:c,repo:o,isRefreshing:r,registerRefresh:d,onRefreshChange:b,headerActionsSlot:e,headerActionsPresentation:s})}):t.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center",children:t.jsx("p",{className:"typography-ui text-muted-foreground",children:"Open a project to browse issues."})})};export{ea as IssuesSurface};
@@ -1 +1 @@
1
- import{c5 as M,di as Z,dj as Fe,dk as Ce,dl as ke,dm as Ie,dn as ze,dd as Ne,dp as Oe,B as ee,I as te,dq as Ve}from"./useAppFontEffects-CG3_yteE.js";import{a as ie,s as Pe,b as Se,c as ne,d as ve,g as Be,e as re,f as I,h as De,i as Ue,j as _e,k as We,R as Ge,I as je,p as se,l as $e,m as qe,n as Ke,o as Je,w as Ye,q as ae,u as Xe,r as Qe,t as Ze,v as et,x as oe,S as tt,y as it,z as nt,A as rt,B as ye,C as he,F as st}from"./web-components-CH3-XV-n.js";import{G as at,u as ot,W as ht,a as lt,b as dt,n as le,t as ct}from"./Virtualizer-wpC51ZBQ.js";import{j as C}from"./vendor-boot-DyL2td56.js";import{o as ut,i as j,f as A,a as ft,q as de,s as pt,t as ce,d as gt,u as ue,b as mt,w as B,x as fe}from"./computeVirtualFileMetrics-CeMpF2xC.js";import{a as F,i as K,l as pe,h as Ct,r as St}from"./renderFileWithHighlighter-TpKRyfCY.js";import{t as H}from"./vendor-hast-util-to-html-BKBhbTDb.js";import{a as k,R as L}from"./vendor-react-DASdDPIk.js";let vt=-1;var yt=class{options;onRenderUpdate;workerManager;__id=`file-renderer:${++vt}`;highlighter;renderCache;computedLang="text";lineAnnotations={};lineCache;textDoucmentCache=new WeakMap;constructor(i={theme:M},e,t){this.options=i,this.onRenderUpdate=e,this.workerManager=t,t?.isWorkingPool()!==!0&&(this.highlighter=ie(i.theme??M)?ut():void 0)}setOptions(i){this.options=i}mergeOptions(i){this.options={...this.options,...i}}setLineAnnotations(i){this.lineAnnotations={};for(const e of i){const t=this.lineAnnotations[e.lineNumber]??[];this.lineAnnotations[e.lineNumber]=t,t.push(e)}}cleanUp(){this.recycle(),this.workerManager=void 0,this.onRenderUpdate=void 0}recycle(){this.clearRenderCache(),this.highlighter=void 0,this.workerManager?.cleanUpTasks(this),this.lineCache=void 0}clearRenderCache(){const i=this.renderCache;this.renderCache=void 0,i!=null&&i.isDirty===!0&&i.file.cacheKey!=null&&this.workerManager?.evictFileFromCache(i.file.cacheKey)}hydrate(i){const{options:e}=this.getRenderOptions(i),t=$(this.getOrCreateLineCache(i).length,this.getTokenizeMaxLength());let n=this.workerManager?.getFileResultCache(i);n!=null&&!F(e,n.options)&&(n=void 0),this.renderCache??={file:i,options:e,highlighted:!t&&!K(i),result:t?void 0:n?.result,renderRange:void 0},this.workerManager?.isWorkingPool()===!0?this.renderCache.result==null&&!t&&this.workerManager.highlightFileAST(this,i):this.highlighter==null&&(this.computedLang=i.lang??j(i.name),this.initializeHighlighter())}getRenderOptions(i){const e=(()=>{if(this.workerManager?.isWorkingPool()===!0)return this.workerManager.getFileRenderOptions();const{theme:n=M,tokenizeMaxLineLength:r=1e3}=this.options;return{theme:n,useTokenTransformer:Pe(this.options),tokenizeMaxLineLength:r}})(),{renderCache:t}=this;return t?.result==null?{options:e,forceHighlight:!0}:!A(i,t.file)||!F(e,t.options)?{options:e,forceHighlight:!0}:{options:e,forceHighlight:!1}}getOrCreateLineCache(i){if(i.cacheKey==null)return this.lineCache=void 0,pe(i.contents);let{lineCache:e}=this;return(e==null||e.cacheKey!==i.cacheKey)&&(e={cacheKey:i.cacheKey,lines:pe(i.contents)}),this.lineCache=e,e.lines}getLineCount(i){return this.textDoucmentCache.get(i)?.lineCount??this.getOrCreateLineCache(i).length}updateRenderCache(i,e){if(this.renderCache==null)return;const{result:t}=this.renderCache;if(t!=null){for(const[n,r]of i)t.code[n]={type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:r.map(([s,a,o])=>s===0&&a===""?o===""?{type:"element",tagName:"br",properties:{},children:[]}:{type:"text",value:o}:{type:"element",tagName:"span",properties:{"data-char":s,style:`--diffs-token-${e}:${a};`},children:[{type:"text",value:o}]})};t.baseThemeType=e,this.renderCache.isDirty=!0}}applyDocumentChange(i){if(this.renderCache==null)return;const{file:e,result:t}=this.renderCache;if(t!=null&&t.code.length!==i.lineCount){t.code.length=Math.min(t.code.length,i.lineCount);for(let n=t.code.length;n<i.lineCount;n++)t.code.push({type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:[{type:"element",tagName:"span",properties:{"data-char":0},children:[{type:"text",value:i.getLineText(n)}]}]});this.renderCache.isDirty=!0}this.textDoucmentCache.set(e,i)}renderFile(i=this.renderCache?.file,e=Z){if(i==null)return;let{options:t,forceHighlight:n}=this.getRenderOptions(i);const r=this.getMatchingWorkerResultCache(i,t);r!=null&&!this.hasHighlightedRenderCache(i,t)&&(this.renderCache={file:i,highlighted:!0,renderRange:void 0,...r},n=!1),this.renderCache??={file:i,highlighted:!1,options:t,result:void 0,renderRange:void 0};const s=this.getOrCreateLineCache(i),a=i.contents.length>0,o=!a||K(i)||$(s.length,this.getTokenizeMaxLength()),h=!A(i,this.renderCache.file),d=!Se(this.renderCache.renderRange,e);if(this.workerManager?.isWorkingPool()===!0)(o||this.renderCache.result==null||!this.renderCache.highlighted&&(h||d))&&(this.renderCache.file=i,this.renderCache.options=t,this.renderCache.highlighted=!1,(this.renderCache.result==null||h||d||n)&&(this.renderCache.result=this.workerManager.getPlainFileAST(i,e.startingLine,e.totalLines,s)),this.renderCache.renderRange=e),!o&&a&&(!this.renderCache.highlighted||n)&&this.workerManager.highlightFileAST(this,i);else{this.computedLang=i.lang??j(i.name);const l=this.highlighter!=null&&ie(t.theme),c=this.highlighter!=null&&ne(this.computedLang),u=!o&&c;if(this.highlighter!=null&&l&&(n||o||!this.renderCache.highlighted&&u||this.renderCache.result==null)){const{result:p,options:f}=this.renderFileWithHighlighter(i,this.highlighter,o||!c);this.renderCache={file:i,options:f,highlighted:u,result:p,renderRange:void 0}}(!l||!o&&!c)&&this.asyncHighlight(i).then(({result:p,options:f})=>{this.renderCache!=null&&(this.renderCache.highlighted=!1),this.onHighlightSuccess(i,p,f,!o)})}return this.renderCache.result!=null?this.processFileResult(this.renderCache.file,e,this.renderCache.result):void 0}async asyncRender(i,e=Z){const{result:t}=await this.asyncHighlight(i);return this.processFileResult(i,e,t)}async asyncHighlight(i){const e=$(this.getOrCreateLineCache(i).length,this.getTokenizeMaxLength());this.computedLang=e?"text":i.lang??j(i.name);const t=this.highlighter!=null&&Ct(ft(this.options.theme)),n=e||this.highlighter!=null&&ne(this.computedLang);return(this.highlighter==null||!t||!n)&&(this.highlighter=await this.initializeHighlighter()),this.renderFileWithHighlighter(i,this.highlighter,e)}renderFileWithHighlighter(i,e,t=!1){const{options:n}=this.getRenderOptions(i);return{result:St(i,e,n,{forcePlainText:t}),options:n}}processFileResult(i,e,{code:t,themeStyles:n,baseThemeType:r}){const s=this.getLineCount(i),{disableFileHeader:a=!1}=this.options,o=[],h=ue(),d=Math.min(e.startingLine+e.totalLines,s);let l=0;const c=ve(e)?Be(this.lineAnnotations):void 0;c!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:-1,lineIndex:-1,annotations:c.map(u=>I(u))})),l++);for(let u=e.startingLine;u<d;u++){const p=u+1,f=t[u];if(f==null){const g="FileRenderer.processFileResult: Line doesnt exist";throw console.error(g,{name:i.name,lineIndex:u,lineNumber:p}),new Error(g)}h.children.push(pt("context",p,`${u}`)),o.push(f),l++;const S=this.lineAnnotations[p];S!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:0,lineIndex:p,annotations:S.map(g=>I(g))})),l++)}return h.properties.style=`grid-row: span ${l}`,{gutterAST:h.children??[],contentAST:o,preAST:this.createPreElement(s),headerAST:a?void 0:this.renderHeader(i),totalLines:s,rowCount:l,themeStyles:n,baseThemeType:r,bufferBefore:e.bufferBefore,bufferAfter:e.bufferAfter,css:""}}renderHeader(i){const{headerRenderMode:e="default",stickyHeader:t=!1}=this.options;return De({fileOrDiff:i,mode:e,stickyHeader:t})}renderFullHTML(i){return H(this.renderFullAST(i))}renderFullAST(i,e=[]){return e.push(ce({tagName:"code",children:this.renderCodeAST(i),properties:{"data-code":""}})),{...i.preAST,children:e}}renderCodeAST(i){const e=ue();return e.children=i.gutterAST,e.properties.style=`grid-row: span ${i.rowCount}`,[e,Ue(i.contentAST,i.rowCount)]}renderPartialHTML(i,e=!1){return e?H(ce({tagName:"code",children:i,properties:{"data-code":""}})):H(i)}async initializeHighlighter(){return this.highlighter=await gt(_e(this.computedLang,this.options)),this.highlighter}onHighlightSuccess(i,e,t,n=!0){if(this.renderCache==null)return;const r=!A(i,this.renderCache.file)||!this.renderCache.highlighted||!F(t,this.renderCache.options);this.renderCache={file:i,options:t,highlighted:n,result:e,renderRange:void 0},r&&this.onRenderUpdate?.()}getMatchingWorkerResultCache(i,e){const t=this.workerManager?.getFileResultCache(i);if(!(t==null||!F(e,t.options)))return t}hasHighlightedRenderCache(i,e){const{renderCache:t}=this;return t?.result!=null&&t.highlighted&&A(i,t.file)&&F(e,t.options)}onHighlightError(i){console.error(i)}getTokenizeMaxLength(){return this.options.tokenizeMaxLength??1e5}createPreElement(i){const{disableLineNumbers:e=!1,overflow:t="scroll"}=this.options;return We({type:"file",diffIndicators:"none",disableBackground:!0,disableLineNumbers:e,overflow:t,split:!1,totalLines:i})}};function $(i,e){return i>e}function Tt(i,e){return i.lineNumber===e.lineNumber&&i.metadata===e.metadata}function ge(i){return{theme:i?.theme,disableLineNumbers:i?.disableLineNumbers,overflow:i?.overflow,themeType:i?.themeType,collapsed:i?.collapsed,disableFileHeader:i?.disableFileHeader,disableVirtualizationBuffers:i?.disableVirtualizationBuffers,stickyHeader:i?.stickyHeader,preferredHighlighter:i?.preferredHighlighter,useCSSClasses:i?.useCSSClasses,useTokenTransformer:i?.useTokenTransformer,tokenizeMaxLineLength:i?.tokenizeMaxLineLength,tokenizeMaxLength:i?.tokenizeMaxLength,unsafeCSS:i?.unsafeCSS,headerRenderMode:i?.renderCustomHeader!=null?"custom":"default"}}const bt=[""];let Rt=-1;var Te=class{options;workerManager;isContainerManaged;static LoadedCustomComponent=!0;__id=`file:${++Rt}`;type="file";fileContainer;spriteSVG;pre;code;bufferBefore;bufferAfter;themeCSSStyle;appliedThemeCSS;hasAdoptedThemeCSS=!1;unsafeCSSStyle;appliedUnsafeCSS;gutterUtilityContent;errorWrapper;placeHolder;lastRenderedHeaderHTML;cachedHeaderHTML;appliedPreAttributes;lastRowCount;mounted=!1;headerElement;headerCustom;headerPrefix;headerFilenameSuffix;headerMetadata;fileRenderer;resizeManager;interactionManager;annotationCache=new Map;lineAnnotations=[];managersDirty=!1;file;renderRange;enabled=!0;editor;constructor(e={theme:M},t,n=!1){this.options=e,this.workerManager=t,this.isContainerManaged=n,this.fileRenderer=new yt(e,this.handleHighlightRender,this.workerManager),this.resizeManager=new Ge,this.interactionManager=new je("file",se(e)),this.workerManager?.subscribeToThemeChanges(this)}handleHighlightRender=()=>{this.rerender()};rerender(){!this.enabled||this.file==null||this.render({file:this.file,forceRender:!0,renderRange:this.renderRange})}onThemeChange(){this.fileRenderer.clearRenderCache(),this.rerender()}setOptions(e){e!=null&&(this.options=e,this.cachedHeaderHTML=void 0,this.syncInteractionOptions())}syncInteractionOptions(){this.interactionManager.setOptions(se(this.options))}mergeOptions(e){this.options={...this.options,...e}}setThemeType(e){(this.options.themeType??"system")!==e&&(this.mergeOptions({themeType:e}),this.applyCachedThemeState(e))}applyCachedThemeState(e){if(typeof this.options.theme=="string"||this.fileContainer==null||this.appliedThemeCSS==null)return!1;const t=this.appliedThemeCSS.baseThemeType??e;return this.appliedThemeCSS.themeType===t?!1:(this.applyThemeState(this.fileContainer,this.appliedThemeCSS.themeStyles,e,this.appliedThemeCSS.baseThemeType),!0)}hasThemeChanged(){return this.appliedThemeCSS!=null&&!mt(this.appliedThemeCSS.theme,this.options.theme??M)}getHoveredLine=()=>this.interactionManager.getHoveredLine();setLineAnnotations(e){this.lineAnnotations=e}setSelectedLines(e,t){this.interactionManager.setSelection(e,t)}flushManagers(){if(!this.managersDirty||this.pre==null){this.managersDirty=!1;return}const{overflow:e="scroll"}=this.options;this.interactionManager.setup(this.pre),this.resizeManager.setup(this.pre,e==="wrap"),this.managersDirty=!1}cleanUp(e=!1){this.emitPostRender(!0),this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.managersDirty=!1,this.workerManager?.unsubscribeToThemeChanges(this),this.renderRange=void 0,this.isContainerManaged||this.fileContainer?.remove(),this.fileContainer=void 0,this.mounted=!1,e||(this.lineAnnotations=[]),this.annotationCache.clear(),this.pre=void 0,this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.lastRenderedHeaderHTML=void 0,e||(this.cachedHeaderHTML=void 0),this.errorWrapper=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.placeHolder=void 0,this.unsafeCSSStyle=void 0,e?this.fileRenderer.recycle():(this.fileRenderer.cleanUp(),this.workerManager=void 0,this.file=void 0),this.enabled=!1,this.editor?.cleanUp(),this.editor=void 0}virtualizedSetup(){this.enabled=!0,this.workerManager?.subscribeToThemeChanges(this)}hydrate(e){const{fileContainer:t,prerenderedHTML:n,preventEmit:r=!1,file:s,lineAnnotations:a}=e;this.hydrateElements(t,n),Lt(this.pre,s,this.options.collapsed)||At(this.headerElement,s,this.options.disableFileHeader)?this.render({...e,preventEmit:!0}):this.hydrationSetup({file:s,lineAnnotations:a}),r||this.emitPostRender()}hydrateElements(e,t){this.fileContainer!==e&&this.emitPostRender(!0),$e(e,t);for(const n of Array.from(e.shadowRoot?.children??[])){if(n instanceof SVGElement){this.spriteSVG=n;continue}if(n instanceof HTMLElement){if(n instanceof HTMLPreElement){this.pre=n,this.appliedPreAttributes=void 0;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-theme-css")){this.themeCSSStyle=n;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-unsafe-css")){this.unsafeCSSStyle=n,this.appliedUnsafeCSS=n.textContent;continue}if("diffsHeader"in n.dataset){this.headerElement=n,this.lastRenderedHeaderHTML=void 0;continue}}}this.pre!=null&&(this.syncCodeNodeFromPre(this.pre),this.pre.removeAttribute("data-dehydrated")),this.fileContainer=e,this.hydrateMeasuredScrollbar()}hydrationSetup({file:e,lineAnnotations:t}){this.lineAnnotations=t??this.lineAnnotations,this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),this.pre!=null&&(this.fileRenderer.hydrate(e),this.renderAnnotations(),this.renderGutterUtility(),this.injectUnsafeCSS(),this.managersDirty=!0,this.flushManagers())}getOrCreateLineCache(e=this.file){return e!=null?this.fileRenderer.getOrCreateLineCache(e):bt}updateBuffers(e){this.pre!=null&&this.applyBuffers(this.pre,e)}syncRenderViewToEditor(){const e=this.editor,t=this.fileContainer,n=this.file;e!=null&&t!=null&&n!=null&&this.fileRenderer.initializeHighlighter().then(r=>{e.__syncRenderView(r,t,n,this.lineAnnotations,this.renderRange)})}attachEditor(e){return this.editor?.cleanUp(),this.editor=e,this.interactionManager.setEditorAttached(!0),this.syncRenderViewToEditor(),()=>{this.editor=void 0,this.interactionManager.setEditorAttached(!1)}}applyDocumentChange(e,t){this.fileRenderer.applyDocumentChange(e),t!=null&&t!==this.lineAnnotations&&this.file!=null&&(this.setLineAnnotations(t),this.fileRenderer.setLineAnnotations(this.lineAnnotations),this.renderAnnotations())}updateRenderCache(e,t){this.fileRenderer.updateRenderCache(e,t)}render({file:e,fileContainer:t,forceRender:n=!1,preventEmit:r=!1,containerWrapper:s,deferManagers:a=!1,lineAnnotations:o,renderRange:h}){if(!this.enabled)throw new Error("File.render: attempting to call render after cleaned up");this.editor?.__postponeBackgroundTokenizeToNextFrame();const{collapsed:d=!1,themeType:l="system"}=this.options,c=d?void 0:h,u=this.renderRange,p=this.hasThemeChanged(),f=o!=null&&(o.length>0||this.lineAnnotations.length>0)?o!==this.lineAnnotations:!1,S=!A(this.file,e);if(!d&&!n&&Se(c,this.renderRange)&&!S&&!f&&!p)return this.applyCachedThemeState(l);this.renderRange=c,S&&(this.cachedHeaderHTML=void 0),this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),o!=null&&this.setLineAnnotations(o),this.fileRenderer.setLineAnnotations(this.lineAnnotations);const{disableErrorHandling:g=!1,disableFileHeader:y=!1}=this.options;if(y&&(this.headerElement!=null&&(this.headerElement.remove(),this.headerElement=void 0,this.lastRenderedHeaderHTML=void 0),this.clearHeaderSlots()),t=this.getOrCreateFileContainerNode(t,s),this.applyCachedThemeState(l),d){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{const m=this.fileRenderer.renderFile(e,Fe);m!=null&&this.applyThemeState(t,m.themeStyles,l,m.baseThemeType),m?.headerAST!=null&&this.applyHeaderToDOM(m.headerAST,t),this.injectUnsafeCSS()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}try{const m=this.getOrCreatePreNode(t);if(!this.canPartiallyRender(n,f,S||p)||!this.applyPartialRender(u,c)){const v=this.fileRenderer.renderFile(e,c);if(v==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.initialize().then(()=>this.rerender()),!1;this.applyThemeState(t,v.themeStyles,l,v.baseThemeType),v.headerAST!=null&&this.applyHeaderToDOM(v.headerAST,t),this.applyFullRender(v,m)}this.applyBuffers(m,c),this.injectUnsafeCSS(),this.managersDirty=!0,a||this.flushManagers(),this.renderAnnotations(),this.renderGutterUtility(),this.editor!=null&&this.syncRenderViewToEditor()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}emitPostRender(e=!1){const{fileContainer:t,options:{onPostRender:n}}=this;if(e){if(!this.mounted||(this.mounted=!1,t==null))return;n?.(t,this,"unmount");return}if(t==null)return;const r=this.mounted?"update":"mount";this.mounted=!0,n?.(t,this,r)}removeRenderedCode(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.code?.remove(),this.code=void 0,this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0}clearAuxiliaryNodes(){for(const{element:e}of this.annotationCache.values())e.remove();this.annotationCache.clear(),this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0}canPartiallyRender(e,t,n){return!(e||t||n)}renderPlaceholder(e){if(this.fileContainer==null)return!1;if(this.emitPostRender(!0),this.cleanChildNodes(),this.placeHolder==null){const t=this.fileContainer.shadowRoot??this.fileContainer.attachShadow({mode:"open"});this.placeHolder=document.createElement("div"),this.placeHolder.dataset.placeholder="",t.appendChild(this.placeHolder)}return this.placeHolder.style.setProperty("height",`${e}px`),!0}primeHighlightCache(){const{file:e,workerManager:t}=this;e==null||e.cacheKey==null||t==null||K(e)||this.fileRenderer.getOrCreateLineCache(e).length>(this.options.tokenizeMaxLength??1e5)||t.primeFileHighlightCache(e)}cleanChildNodes(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferAfter?.remove(),this.bufferBefore?.remove(),this.code?.remove(),this.errorWrapper?.remove(),this.headerElement?.remove(),this.gutterUtilityContent?.remove(),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.pre?.remove(),this.spriteSVG?.remove(),this.themeCSSStyle?.remove(),this.unsafeCSSStyle?.remove(),this.bufferAfter=void 0,this.bufferBefore=void 0,this.code=void 0,this.errorWrapper=void 0,this.headerElement=void 0,this.gutterUtilityContent=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.pre=void 0,this.spriteSVG=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.lastRenderedHeaderHTML=void 0,this.lastRowCount=void 0,this.mounted=!1}renderAnnotations(){if(this.isContainerManaged||this.fileContainer==null){for(const{element:n}of this.annotationCache.values())n.remove();this.annotationCache.clear();return}const e=new Map(this.annotationCache),{renderAnnotation:t}=this.options;if(t!=null&&this.lineAnnotations.length>0)for(const[n,r]of this.lineAnnotations.entries()){const s=`${n}-${I(r)}`;let a=this.annotationCache.get(s);if(a==null||!Tt(r,a.annotation)){a?.element.remove();const o=t(r);if(o==null)continue;a={element:qe(I(r)),annotation:r},a.element.appendChild(o),this.fileContainer.appendChild(a.element),this.annotationCache.set(s,a)}e.delete(s)}for(const[n,{element:r}]of e.entries())this.annotationCache.delete(n),r.remove()}renderGutterUtility(){const{renderGutterUtility:e}=this.options;if(this.fileContainer==null||e==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const t=e(this.interactionManager.getHoveredLine);if(t!=null&&this.gutterUtilityContent!=null)return;if(t==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const n=Ke();n.appendChild(t),this.fileContainer.appendChild(n),this.gutterUtilityContent=n}injectUnsafeCSS(){const{unsafeCSS:e}=this.options,t=this.fileContainer?.shadowRoot;if(t!=null){if(e==null||e===""){this.unsafeCSSStyle!=null&&(this.unsafeCSSStyle.remove(),this.unsafeCSSStyle=void 0),this.appliedUnsafeCSS=void 0;return}this.unsafeCSSStyle?.parentNode===t&&this.appliedUnsafeCSS===e||(this.unsafeCSSStyle??=Je(),this.unsafeCSSStyle.parentNode!==t&&t.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=Ye(e),this.appliedUnsafeCSS=e)}}applyThemeState(e,t,n,r){const s=e.shadowRoot??e.attachShadow({mode:"open"}),a=r??n,o=this.options.theme??M,h=typeof o=="string"?o:{...o},d=ae(s);if(this.themeCSSStyle?.parentNode===s&&this.appliedThemeCSS?.themeStyles===t&&this.appliedThemeCSS.themeType===a&&this.appliedThemeCSS.scrollbarGutter===d){this.appliedThemeCSS.theme=h;return}if(this.hasAdoptedThemeCSS&&this.themeCSSStyle?.parentNode===s){this.hasAdoptedThemeCSS=!1,this.appliedThemeCSS={theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:d};return}this.themeCSSStyle=Xe({shadowRoot:s,currentNode:this.themeCSSStyle,themeCSS:Qe(t,a,d)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:d}:void 0}hydrateMeasuredScrollbar(){const e=this.fileContainer?.shadowRoot;e==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=Ze(this.themeCSSStyle.textContent??"",ae(e)))}applyFullRender(e,t){this.cleanupErrorWrapper(),this.applyPreNodeAttributes(t,e),this.code=et({code:this.code});const n=this.fileRenderer.renderCodeAST(e);if(this.code.childElementCount>=2)for(let r=0;r<2;r++){const s=this.code.children[r],a=n[r];s.innerHTML=H(a.children),s.style.cssText=a.properties.style}else this.code.innerHTML=H(n);t.contains(this.code)||t.replaceChildren(this.code),this.lastRowCount=e.rowCount}applyPartialRender(e,t){if(e==null||t==null)return!1;const{file:n,code:r}=this,s=r!=null?this.getColumns(r):void 0;if(n==null||r==null||s==null)return!1;const a=e.startingLine,o=t.startingLine,h=e.totalLines===1/0?Number.POSITIVE_INFINITY:a+e.totalLines,d=t.totalLines===1/0?Number.POSITIVE_INFINITY:o+t.totalLines,l=Math.max(a,o),c=Math.min(h,d);if(c<=l||!this.trimDOMToOverlap(s.gutter,l,c)||!this.trimDOMToOverlap(s.content,l,c))return!1;let{length:u}=s.content.children;const p=(y,m)=>{if(!(m<=0))return this.fileRenderer.renderFile(n,{startingLine:y,totalLines:m,bufferBefore:0,bufferAfter:0})},f=o<l?p(o,l-o):void 0;if(f===void 0&&o<l)return!1;const S=d===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:Math.max(0,d-c),g=d>c?p(c,S):void 0;return g===void 0&&d>c?!1:(this.cleanupErrorWrapper(),f!=null&&(s.gutter.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.gutterAST)),s.content.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.contentAST)),u+=f.rowCount),g!=null&&(s.gutter.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.gutterAST)),s.content.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.contentAST)),u+=g.rowCount),this.lastRowCount!==u&&(s.gutter.style.setProperty("grid-row",`span ${u}`),s.content.style.setProperty("grid-row",`span ${u}`),this.lastRowCount=u),!0)}getColumns(e){const t=e.children[0],n=e.children[1];if(!(!(t instanceof HTMLElement)||!(n instanceof HTMLElement)||t.dataset.gutter==null||n.dataset.content==null))return{gutter:t,content:n}}trimDOMToOverlap(e,t,n){const r=this.getDOMBoundaryIndices(e,[t,n]),s=r.get(t)??e.children.length,a=r.get(n)??e.children.length;if(s>a)return!1;for(let o=e.children.length-1;o>=a;o-=1)e.children[o]?.remove();for(let o=s-1;o>=0;o-=1)e.children[o]?.remove();return!0}getDOMBoundaryIndices(e,t){const n=[...new Set(t)].sort((h,d)=>h-d),r=new Map;if(n.length===0)return r;let s=0,a=n[s];const{children:o}=e;a===0&&(r.set(0,0),s+=1,a=n[s]);for(let h=0;h<o.length;h+=1){const d=o[h];if(!(d instanceof HTMLElement))continue;const l=this.getLineIndexFromDOMNode(d);if(l!=null){for(;a!=null&&l>=a;)r.set(a,h),s+=1,a=n[s];if(s>=n.length)break}}for(const h of n)r.has(h)||r.set(h,o.length);return r}getLineIndexFromDOMNode(e){const t=e.dataset.lineIndex;if(t==null)return;const n=Number(t);return Number.isNaN(n)?void 0:n}applyBuffers(e,t){if(t==null||this.shouldDisableVirtualizationBuffers()){this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0);return}t.bufferBefore>0?(this.bufferBefore==null&&(this.bufferBefore=document.createElement("div"),this.bufferBefore.dataset.virtualizerBuffer="before",e.before(this.bufferBefore)),this.bufferBefore.style.setProperty("height",`${t.bufferBefore}px`),this.bufferBefore.style.setProperty("contain","strict")):this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),t.bufferAfter>0?(this.bufferAfter==null&&(this.bufferAfter=document.createElement("div"),this.bufferAfter.dataset.virtualizerBuffer="after",e.after(this.bufferAfter)),this.bufferAfter.style.setProperty("height",`${t.bufferAfter}px`),this.bufferAfter.style.setProperty("contain","strict")):this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0)}shouldDisableVirtualizationBuffers(){return this.options.disableVirtualizationBuffers??!1}applyHeaderToDOM(e,t){const{file:n}=this;if(n==null)return;this.cleanupErrorWrapper(),this.placeHolder?.remove(),this.placeHolder=void 0;const r=this.cachedHeaderHTML??H(e);if(this.cachedHeaderHTML=r,r!==this.lastRenderedHeaderHTML){const d=document.createElement("div");d.innerHTML=r;const l=d.firstElementChild;if(!(l instanceof HTMLElement))return;this.headerElement!=null?t.shadowRoot?.replaceChild(l,this.headerElement):t.shadowRoot?.prepend(l),this.headerElement=l,this.lastRenderedHeaderHTML=r}if(this.isContainerManaged)return;const{renderHeaderPrefix:s,renderHeaderFilenameSuffix:a,renderCustomHeader:o,renderHeaderMetadata:h}=this.options;if(o!=null){const d=o(n)??void 0;this.headerCustom=this.upsertHeaderSlotElement(t,this.headerCustom,Ce,d),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0}else{const d=s?.(n)??void 0,l=a?.(n)??void 0,c=h?.(n)??void 0;this.headerPrefix=this.upsertHeaderSlotElement(t,this.headerPrefix,ke,d),this.headerFilenameSuffix=this.upsertHeaderSlotElement(t,this.headerFilenameSuffix,Ie,l),this.headerMetadata=this.upsertHeaderSlotElement(t,this.headerMetadata,ze,c),this.headerCustom?.remove(),this.headerCustom=void 0}}clearHeaderSlots(){this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0}upsertHeaderSlotElement(e,t,n,r){if(r==null){t?.remove();return}const s=t??this.createHeaderSlotElement(n);return t==null&&e.appendChild(s),this.replaceHeaderSlotContent(s,r),s}replaceHeaderSlotContent(e,t){e.replaceChildren(),t instanceof Element?e.appendChild(t):e.innerText=`${t}`}createHeaderSlotElement(e){const t=document.createElement("div");return t.slot=e,t}getOrCreateFileContainerNode(e,t){const{fileContainer:n}=this,r=e??n??document.createElement("diffs-container"),s=n!==r;return s&&this.emitPostRender(!0),this.fileContainer=r,n!=null&&s&&(this.lastRenderedHeaderHTML=void 0,this.headerElement=void 0),t!=null&&this.fileContainer.parentNode!==t&&t.appendChild(this.fileContainer),s&&this.adoptReusableShellElements(this.fileContainer),this.ensureSpriteSVG(this.fileContainer),this.fileContainer}adoptReusableShellElements(e){const{shadowRoot:t}=e;if(t!=null)for(const n of t.children)n instanceof SVGElement?this.spriteSVG??=n:oe(n)&&n.hasAttribute("data-theme-css")?(this.themeCSSStyle??=n,this.hasAdoptedThemeCSS=!0):oe(n)&&n.hasAttribute("data-unsafe-css")&&(this.unsafeCSSStyle??=n,this.appliedUnsafeCSS??=this.options.unsafeCSS??void 0)}ensureSpriteSVG(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});if(this.spriteSVG==null){const n=document.createElement("div");n.innerHTML=tt;const r=n.firstChild;r instanceof SVGElement&&(this.spriteSVG=r)}this.spriteSVG!=null&&this.spriteSVG.parentNode!==t&&t.appendChild(this.spriteSVG)}getOrCreatePreNode(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});return this.pre==null?(this.pre=document.createElement("pre"),this.appliedPreAttributes=void 0,this.code=void 0,t.appendChild(this.pre)):this.pre.parentNode!==t&&(e.shadowRoot?.appendChild(this.pre),this.appliedPreAttributes=void 0),this.placeHolder?.remove(),this.placeHolder=void 0,this.pre}syncCodeNodeFromPre(e){this.code=void 0;for(const t of Array.from(e.children))if(t instanceof HTMLElement&&t.hasAttribute("data-code")){this.code=t;return}}applyPreNodeAttributes(e,{totalLines:t}){const{overflow:n="scroll",disableLineNumbers:r=!1}=this.options,s={type:"file",split:!1,overflow:n,disableLineNumbers:r,diffIndicators:"none",disableBackground:!0,totalLines:t};it(s,this.appliedPreAttributes)||(nt(e,s),this.appliedPreAttributes=s)}applyErrorToDOM(e,t){this.cleanupErrorWrapper(),this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0;const n=t.shadowRoot??t.attachShadow({mode:"open"});this.errorWrapper??=document.createElement("div"),this.errorWrapper.dataset.errorWrapper="",this.errorWrapper.textContent="",n.appendChild(this.errorWrapper);const r=document.createElement("div");r.dataset.errorMessage="",r.innerText=e.message,this.errorWrapper.appendChild(r);const s=document.createElement("pre");s.dataset.errorStack="",s.innerText=e.stack??"No Error Stack",this.errorWrapper.appendChild(s)}cleanupErrorWrapper(){this.errorWrapper?.remove(),this.errorWrapper=void 0}};function Lt(i,e,t=!1){return!t&&i==null&&e!=null}function At(i,e,t=!1){return i==null&&e!=null&&!t}const Mt=5e3;let Ht=-1;function xt(i,e){return(i.overflow??"scroll")!==(e.overflow??"scroll")||(i.collapsed??!1)!==(e.collapsed??!1)||(i.disableLineNumbers??!1)!==(e.disableLineNumbers??!1)||(i.disableFileHeader??!1)!==(e.disableFileHeader??!1)||i.unsafeCSS!==e.unsafeCSS}var wt=class extends Te{virtualizer;metrics;__id=`virtualized-file:${++Ht}`;top;height=0;cache={heights:new Map,checkpoints:[],fileAnnotationHeight:0};isVisible=!1;isSetup=!1;layoutDirty=!0;forceRenderOverride;currentCollapsed;constructor(i,e,t=Ne,n,r=!1){super(i,n,r),this.virtualizer=e,this.metrics=t}setMetrics(i,e=!1){!e&&rt(this.metrics,i)||(this.metrics=i,this.resetLayoutCache())}setLineAnnotations(i){this.syncLineAnnotations(i)&&this.resetLayoutCache()}syncLineAnnotations(i){return i==null||i===this.lineAnnotations||i.length===0&&this.lineAnnotations.length===0?!1:(super.setLineAnnotations(i),!0)}hasLineAnnotations(){return this.lineAnnotations.some(i=>i.lineNumber>0)}getLineHeight(i,e=!1){const t=this.cache.heights.get(i);if(t!=null)return t;const n=e?2:1;return this.metrics.lineHeight*n}setOptions(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setOptions cannot be used inside CodeView. Update CodeView options instead.");if(i==null)return;const{options:e}=this,t=!ye(e,i),n=xt(e,i);super.setOptions(i),n&&this.resetLayoutCache(!0),t&&(this.forceRenderOverride=!0),t&&this.virtualizer.instanceChanged(this,n)}setThemeType(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setThemeType cannot be used inside CodeView. Update CodeView options instead.");super.setThemeType(i)}resetLayoutCache(i=!1){this.layoutDirty=!0,this.cache.fileAnnotationHeight=0,this.cache.heights.size>0&&this.cache.heights.clear(),this.cache.checkpoints.length>0&&(this.cache.checkpoints.length=0),this.renderRange!=null&&(this.renderRange=void 0),i&&this.isSimpleMode()&&this.computeApproximateSize()}reconcileHeights(){let i=!1;if(this.fileContainer==null||this.file==null)return this.height!==0&&(i=!0),this.height=0,i;const{overflow:e="scroll"}=this.options;if(this.top=this.getVirtualizedTop(),e==="scroll"&&this.lineAnnotations.length===0&&!this.isResizeDebuggingEnabled()||this.code==null)return i;const t=this.code.children[1];if(!(t instanceof HTMLElement))return i;const n=he(this.lineAnnotations);if(this.renderRange!=null&&n&&ve(this.renderRange)){const r=Et(t)??0;r!==this.cache.fileAnnotationHeight&&(this.cache.fileAnnotationHeight=r,i=!0)}else!n&&this.cache.fileAnnotationHeight!==0&&(this.cache.fileAnnotationHeight=0,i=!0);for(const r of t.children){if(!(r instanceof HTMLElement))continue;const s=r.dataset.lineIndex;if(s==null)continue;const a=Number(s);let o=r.getBoundingClientRect().height,h=!1;r.nextElementSibling instanceof HTMLElement&&("lineAnnotation"in r.nextElementSibling.dataset||"noNewline"in r.nextElementSibling.dataset)&&("noNewline"in r.nextElementSibling.dataset&&(h=!0),o+=r.nextElementSibling.getBoundingClientRect().height);const d=this.getLineHeight(a,h);o!==d&&(i=!0,o===this.metrics.lineHeight*(h?2:1)?this.cache.heights.delete(a):this.cache.heights.set(a,o))}return(i||this.isResizeDebuggingEnabled())&&this.computeApproximateSize(!0),i}onRender=i=>this.fileContainer==null||this.file==null?!1:(i&&(this.top=this.getVirtualizedTop()),this.render({file:this.file}));prepareCodeViewItem(i,e,t,n){const r=this.syncLineAnnotations(n);let s=t?.resetFileLayoutCache===!0||r;t?.metrics!=null&&(this.metrics=t.metrics,s=!0);const{collapsed:a=!1}=this.options;return this.currentCollapsed!==a&&(this.currentCollapsed=a,s=!0),s&&this.resetLayoutCache(),this.file!==i&&(this.layoutDirty=!0),this.file=i,this.top=e,this.computeApproximateSize(),this.height}getLinePosition(i){if(this.file==null||i<1)return;const{disableFileHeader:e=!1,collapsed:t=!1}=this.options,n=this.fileRenderer.getLineCount(this.file)-1;let r=B(this.metrics,e);if(t||n<0)return{top:r,height:0};const s=Math.min(Math.max(i-1,0),n),{overflow:a="scroll"}=this.options,{lineHeight:o}=this.metrics;if(r+=this.cache.fileAnnotationHeight,a==="scroll"&&!this.hasLineAnnotations())return{top:r+s*o,height:o};const h=this.getLayoutCheckpointBeforeLineIndex(s);r=h?.top??r;for(let d=h?.lineIndex??0;d<s;d++)r+=this.getLineHeight(d,!1);return{top:r,height:this.getLineHeight(s,!1)}}getNumericScrollAnchor(i){if(this.file==null||this.renderRange==null)return;const{disableFileHeader:e=!1,collapsed:t=!1,overflow:n="scroll"}=this.options;if(t||this.renderRange.totalLines<=0)return;const r=this.fileRenderer.getLineCount(this.file)-1;if(r<0)return;const s=B(this.metrics,e),a=Math.min(this.renderRange.startingLine,r),o=Math.min(a+this.renderRange.totalLines-1,r);if(o<a)return;const{fileAnnotationHeight:h}=this.cache;if(n==="scroll"&&!this.hasLineAnnotations()){const{lineHeight:l}=this.metrics,c=s+(a===0?h:this.renderRange.bufferBefore),u=a+Math.max(Math.ceil((i-c)/l),0);return u>o?void 0:{lineNumber:u+1,top:s+h+u*l}}let d=s+(a===0?h:this.renderRange.bufferBefore);for(let l=a;l<=o;l++){if(d>=i)return{lineNumber:l+1,top:d};d+=this.getLineHeight(l)}}getVirtualizedHeight(){return this.height}getAdvancedStickySpecs(i){if(this.top==null||this.file==null)return;if(this.options.collapsed===!0)return{topOffset:this.top,height:this.height};const e=i!=null?this.computeRenderRangeFromWindow(this.file,this.top,i):this.renderRange;if(e==null)return;const{bufferBefore:t,bufferAfter:n,totalLines:r}=e;let s=0;if(r===0){const a=i??this.virtualizer.getWindowSpecs();this.top<a.top&&(s=n)}return{topOffset:this.top+t+s,height:this.height-(t+n)}}cleanUp(i=!1){this.fileContainer!=null&&this.isSimpleMode()&&this.getSimpleVirtualizer()?.disconnect(this.fileContainer),i||this.resetLayoutCache(),this.isSetup=!1,super.cleanUp(i)}computeApproximateSize(i=!1){const e=this.isResizeDebuggingEnabled();if(!i&&!this.layoutDirty&&!e)return;const t=this.height===0;if(this.height=0,this.cache.checkpoints=[],this.file==null){this.layoutDirty=!1;return}const{disableFileHeader:n=!1,collapsed:r=!1,overflow:s="scroll"}=this.options,{lineHeight:a}=this.metrics,o=this.fileRenderer.getLineCount(this.file),h=B(this.metrics,n),d=fe(this.metrics);if(this.height+=h,r){this.layoutDirty=!1;return}if(this.height+=this.cache.fileAnnotationHeight,s==="scroll"&&!this.hasLineAnnotations())this.height+=o*a;else for(let l=0;l<o;l++)this.addLayoutCheckpoint(l,this.height),this.height+=this.getLineHeight(l,!1);if(o>0&&(this.height+=d),this.fileContainer!=null&&e&&!t){const l=this.fileContainer.getBoundingClientRect();l.height!==this.height?console.log("VirtualizedFile.computeApproximateSize: computed height doesnt match",{name:this.file.name,elementHeight:l.height,computedHeight:this.height}):console.log("VirtualizedFile.computeApproximateSize: computed height IS CORRECT")}this.layoutDirty=!1}setVisibility(i){this.isAdvancedMode()||this.fileContainer==null||(i&&!this.isVisible?(this.top=this.getVirtualizedTop(),this.isVisible=!0):!i&&this.isVisible&&(this.isVisible=!1,this.rerender()))}rerender(){!this.enabled||this.file==null||(this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!1))}applyDocumentChange(i,e,t=!1){const{heights:n,checkpoints:r}=this.cache,s=this.renderRange;if(super.applyDocumentChange(i,e),this.getSimpleVirtualizer()?.markDOMDirty(),this.layoutDirty=!0,n.size>0&&n.clear(),r.length>0&&(r.length=0),this.isSimpleMode()&&this.computeApproximateSize(),t&&s!==void 0&&this.file!==void 0){const a=this.virtualizer.getWindowSpecs(),o=this.computeRenderRangeFromWindow(this.file,this.top??0,a);o.bufferAfter!==s.bufferAfter&&this.updateBuffers(o)}}render({fileContainer:i,file:e,forceRender:t=!1,lineAnnotations:n,...r}){const s=this.file==null||!A(this.file,e),{forceRenderOverride:a,isSetup:o}=this;this.forceRenderOverride=void 0;const h=this.syncLineAnnotations(n);if(h&&this.resetLayoutCache(),this.file=e,i=this.getOrCreateFileContainerNode(i),this.file==null)return console.error("VirtualizedFile.render: attempting to virtually render when we dont have file"),!1;if(o)this.top??=this.getVirtualizedTop(),s&&this.isSimpleMode()&&(this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache(!0));else{this.computeApproximateSize();const u=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(u==null)throw new Error("VirtualizedFile.render: simple virtualizer is not available");u.connect(i,this),this.isVisible=u.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode())return this.renderPlaceholder(this.height);const d=this.virtualizer.getWindowSpecs(),l=this.top??0,c=this.computeRenderRangeFromWindow(this.file,l,d);return super.render({file:this.file,fileContainer:i,renderRange:c,lineAnnotations:n,forceRender:(a??t)||h,...r})}syncVirtualizedTop(){this.top=this.getVirtualizedTop()}shouldDisableVirtualizationBuffers(){return this.isAdvancedMode()||super.shouldDisableVirtualizationBuffers()}isSimpleMode(){return this.virtualizer.type==="simple"}isAdvancedMode(){return this.virtualizer.type==="advanced"}addLayoutCheckpoint(i,e){i%Mt===0&&this.cache.checkpoints.push({lineIndex:i,top:e})}getLayoutCheckpointBeforeLineIndex(i){if(i<=0||this.cache.checkpoints.length===0)return;let e=0,t=this.cache.checkpoints.length-1,n;for(;e<=t;){const r=e+t>>1,s=this.cache.checkpoints[r];if(s==null)throw new Error("VirtualizedFile: invalid checkpoint index");s.lineIndex<=i?(n=s,e=r+1):t=r-1}return n}getLayoutCheckpointBeforeTop(i,e){let t=0,n=this.cache.checkpoints.length-1,r=-1;for(;t<=n;){const s=t+n>>1,a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");a.top<=i?(r=s,t=s+1):n=s-1}if(e==null)return r>=0?this.cache.checkpoints[r]:void 0;for(let s=r;s>=0;s--){const a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");if(a.lineIndex%e===0)return a}}getVirtualizedTop(){return this.virtualizer.type==="advanced"?this.virtualizer.getLocalTopForInstance(this):this.fileContainer!=null?this.virtualizer.getOffsetInScrollContainer(this.fileContainer):0}getSimpleVirtualizer(){return this.virtualizer.type==="simple"?this.virtualizer:void 0}isResizeDebuggingEnabled(){return this.getSimpleVirtualizer()?.config.resizeDebugging??!1}computeRenderRangeFromWindow(i,e,{top:t,bottom:n}){const{disableFileHeader:r=!1,overflow:s="scroll"}=this.options,{hunkLineCount:a,lineHeight:o}=this.metrics,h=this.fileRenderer.getLineCount(i),d=this.height,l=B(this.metrics,r),c=h>0?fe(this.metrics):0,{fileAnnotationHeight:u}=this.cache,p=l+u,f=Math.max(0,d-l-u-c),S=he(this.lineAnnotations),g=e+l,y=u>0&&S&&g<n&&g+u>t;if(e<t-d||e>n)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};if(h<=a)return{startingLine:0,totalLines:a,bufferBefore:0,bufferAfter:0};const m=Math.ceil(Math.max(n-t,0)/o),v=Math.ceil(m/a)*a+a*2,z=v/a,D=(t+n)/2;if(s==="scroll"&&!this.hasLineAnnotations()){const R=e+p,P=R+f;if(!y&&!(R<n&&P>t))return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};const w=Math.floor(y&&D<e+p?0:(D-(e+p))/o),b=Math.floor(w/a)-Math.floor(z/2),xe=Math.ceil(h/a),E=Math.max(0,Math.min(b,xe))*a,Q=b<0?v+b*a:v,we=E===0?0:u+E*o,Ee=Math.min(Q,h-E);return{startingLine:E,totalLines:Q,bufferBefore:we,bufferAfter:Math.max(0,(h-E-Ee)*o)}}const be=z,N=[],U=this.getLayoutCheckpointBeforeTop(Math.max(0,t-e-v*o*2),a);let T=e+(U?.top??p),_=U?.lineIndex??0,O,V,x;const Re=U?.lineIndex??0;for(let R=Re;R<h;R++){const P=_%a===0,w=Math.floor(_/a);if(P&&(N[w]=T-(e+p),x!=null)){if(x<=0)break;x--}const b=this.getLineHeight(R,!1);T>t-b&&T<n&&(O??=w),T+b>D&&(V??=w),x==null&&T>=n&&P&&(x=be),_++,T+=b}if(O==null)if(y)O=0,V=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};V??=O;const W=Math.round(V-z/2),Le=Math.max(0,Math.ceil(h/a)-z),G=Math.max(0,Math.min(W,Le)),J=G*a,Y=W<0?v+W*a:v,Ae=N[G]??0,Me=J===0?0:u+Ae,X=G+Y/a,He=X<N.length?f-N[X]:f-(T-e-p);return{startingLine:J,totalLines:Y,bufferBefore:Me,bufferAfter:Math.max(0,He)}}};function Et(i){let e;for(const t of i.children)t instanceof HTMLElement&&t.dataset.lineAnnotation===st&&(e=Math.max(e??0,t.getBoundingClientRect().height));return e}function Ft({file:i,renderCustomHeader:e,renderHeaderPrefix:t,renderHeaderFilenameSuffix:n,renderHeaderMetadata:r,renderAnnotation:s,lineAnnotations:a,renderGutterUtility:o,getHoveredLine:h}){const d=e?.(i),l=t?.(i),c=n?.(i),u=r?.(i);return C.jsxs(C.Fragment,{children:[d!=null?C.jsx("div",{slot:Ce,children:d}):C.jsxs(C.Fragment,{children:[l!=null&&C.jsx("div",{slot:"header-prefix",children:l}),c!=null&&C.jsx("div",{slot:"header-filename-suffix",children:c}),u!=null&&C.jsx("div",{slot:"header-metadata",children:u})]}),s!=null&&a?.map((p,f)=>C.jsx("div",{slot:I(p),children:s(p)},f)),o!=null&&C.jsx("div",{slot:"gutter-utility-slot",style:at,children:o(h)})]})}const me=typeof window>"u"?k.useEffect:k.useLayoutEffect;function kt({file:i,options:e,lineAnnotations:t,selectedLines:n,prerenderedHTML:r,metrics:s,hasGutterRenderUtility:a,hasCustomHeader:o,disableWorkerPool:h,contentEditable:d}){const l=ot(),c=n!==void 0,u=k.useContext(ht),p=lt(),f=k.useRef(null),S=dt(g=>{if(g!=null){if(f.current!=null)throw new Error("File: An instance should not already exist when a node is created");l!=null?f.current=new wt(q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),l,s,h?void 0:u,!0):f.current=new Te(q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),h?void 0:u,!0),f.current.hydrate({file:i,fileContainer:g,lineAnnotations:t,prerenderedHTML:r})}else{if(f.current==null)throw new Error("File: A File instance should exist when unmounting");f.current.cleanUp(),f.current=null}});return me(()=>{if(f.current==null)return;const g=q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),y=!ye(f.current.options,g);f.current.setOptions(g),f.current.render({file:i,lineAnnotations:t,forceRender:y}),n!==void 0&&f.current.setSelectedLines(n)}),me(()=>{if(d&&f.current!=null){if(p===void 0)throw new Error("File: Editor is not attached");return p.edit(f.current)}},[d,p]),{ref:S,getHoveredLine:k.useCallback(()=>f.current?.getHoveredLine(),[])}}function q({options:i,controlledSelection:e,contentEditable:t,hasCustomHeader:n,hasEditor:r,hasGutterRenderUtility:s}){const a=t&&r,o=e||s||n;if(!o&&!a)return i;let h={...i};return o&&(h={...h,controlledSelection:e,renderCustomHeader:n?le:i?.renderCustomHeader,renderGutterUtility:s?le:i?.renderGutterUtility}),a&&(h={...h,useTokenTransformer:!0,enableGutterUtility:!1,enableLineSelection:!1,lineHoverHighlight:"disabled"}),h}function _t({file:i,lineAnnotations:e,selectedLines:t,options:n,metrics:r,className:s,style:a,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:d,renderHeaderFilenameSuffix:l,renderHeaderMetadata:c,prerenderedHTML:u,renderGutterUtility:p,disableWorkerPool:f=!1,contentEditable:S=!1}){const{ref:g,getHoveredLine:y}=kt({file:i,options:n,metrics:r,lineAnnotations:e,selectedLines:t,prerenderedHTML:u,hasGutterRenderUtility:p!=null,hasCustomHeader:h!=null,disableWorkerPool:f,contentEditable:S});return C.jsx(Oe,{ref:g,className:s,style:a,children:ct(Ft({file:i,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:d,renderHeaderFilenameSuffix:l,renderHeaderMetadata:c,renderGutterUtility:p,lineAnnotations:e,getHoveredLine:y}),u)})}const Wt=L.memo(function({jsonString:e,className:t,maxHeight:n="100%",initiallyExpandedDepth:r=2}){const s=L.useRef(null),[a,o]=L.useState(null),h=L.useMemo(()=>{try{const c=e.trim();if(!c)return o("Empty JSON content"),null;const u=JSON.parse(c);return o(null),u}catch(c){return o(c instanceof Error?c.message:"Invalid JSON"),null}},[e]),d=L.useCallback(()=>{s.current?.expandAll()},[]),l=L.useCallback(()=>{s.current?.collapseAll()},[]);return a?C.jsx("div",{className:t,children:C.jsxs("div",{className:"rounded-md border border-[var(--interactive-border)] bg-[var(--syntax-base-background)] p-4",children:[C.jsx("div",{className:"mb-1 font-medium text-[var(--surface-foreground)]",children:"Invalid JSON"}),C.jsx("div",{className:"font-mono text-xs text-[var(--surface-mutedForeground)]",children:a})]})}):h===null?null:C.jsxs("div",{className:t,children:[C.jsxs("div",{className:"flex items-center gap-1 border-b border-[var(--interactive-border)] px-2 py-1",children:[C.jsxs(ee,{variant:"ghost",size:"xs",onClick:d,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-down-s",className:"h-3 w-3"}),"Expand All"]}),C.jsxs(ee,{variant:"ghost",size:"xs",onClick:l,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-up-s",className:"h-3 w-3"}),"Collapse All"]})]}),C.jsx("div",{className:"bg-[var(--syntax-base-background)] py-1",style:{maxHeight:n,overflow:"auto"},children:C.jsx(Ve,{ref:s,data:h,maxHeight:n,initiallyExpandedDepth:r})})]})});export{_t as F,Wt as J};
1
+ import{c5 as M,di as Z,dj as Fe,dk as Ce,dl as ke,dm as Ie,dn as ze,dd as Ne,dp as Oe,B as ee,I as te,dq as Ve}from"./useAppFontEffects-BisjofNZ.js";import{a as ie,s as Pe,b as Se,c as ne,d as ve,g as Be,e as re,f as I,h as De,i as Ue,j as _e,k as We,R as Ge,I as je,p as se,l as $e,m as qe,n as Ke,o as Je,w as Ye,q as ae,u as Xe,r as Qe,t as Ze,v as et,x as oe,S as tt,y as it,z as nt,A as rt,B as ye,C as he,F as st}from"./web-components-CdMfsnXE.js";import{G as at,u as ot,W as ht,a as lt,b as dt,n as le,t as ct}from"./Virtualizer-Cp_cJWbI.js";import{k as C}from"./vendor-boot-Dgb9NVFe.js";import{o as ut,i as j,f as A,a as ft,q as de,s as pt,t as ce,d as gt,u as ue,b as mt,w as B,x as fe}from"./computeVirtualFileMetrics-CyhUKEfv.js";import{a as F,i as K,l as pe,h as Ct,r as St}from"./renderFileWithHighlighter-CnN0Tv_8.js";import{t as H}from"./vendor-hast-util-to-html-BKBhbTDb.js";import{a as k,R as L}from"./vendor-react-DASdDPIk.js";let vt=-1;var yt=class{options;onRenderUpdate;workerManager;__id=`file-renderer:${++vt}`;highlighter;renderCache;computedLang="text";lineAnnotations={};lineCache;textDoucmentCache=new WeakMap;constructor(i={theme:M},e,t){this.options=i,this.onRenderUpdate=e,this.workerManager=t,t?.isWorkingPool()!==!0&&(this.highlighter=ie(i.theme??M)?ut():void 0)}setOptions(i){this.options=i}mergeOptions(i){this.options={...this.options,...i}}setLineAnnotations(i){this.lineAnnotations={};for(const e of i){const t=this.lineAnnotations[e.lineNumber]??[];this.lineAnnotations[e.lineNumber]=t,t.push(e)}}cleanUp(){this.recycle(),this.workerManager=void 0,this.onRenderUpdate=void 0}recycle(){this.clearRenderCache(),this.highlighter=void 0,this.workerManager?.cleanUpTasks(this),this.lineCache=void 0}clearRenderCache(){const i=this.renderCache;this.renderCache=void 0,i!=null&&i.isDirty===!0&&i.file.cacheKey!=null&&this.workerManager?.evictFileFromCache(i.file.cacheKey)}hydrate(i){const{options:e}=this.getRenderOptions(i),t=$(this.getOrCreateLineCache(i).length,this.getTokenizeMaxLength());let n=this.workerManager?.getFileResultCache(i);n!=null&&!F(e,n.options)&&(n=void 0),this.renderCache??={file:i,options:e,highlighted:!t&&!K(i),result:t?void 0:n?.result,renderRange:void 0},this.workerManager?.isWorkingPool()===!0?this.renderCache.result==null&&!t&&this.workerManager.highlightFileAST(this,i):this.highlighter==null&&(this.computedLang=i.lang??j(i.name),this.initializeHighlighter())}getRenderOptions(i){const e=(()=>{if(this.workerManager?.isWorkingPool()===!0)return this.workerManager.getFileRenderOptions();const{theme:n=M,tokenizeMaxLineLength:r=1e3}=this.options;return{theme:n,useTokenTransformer:Pe(this.options),tokenizeMaxLineLength:r}})(),{renderCache:t}=this;return t?.result==null?{options:e,forceHighlight:!0}:!A(i,t.file)||!F(e,t.options)?{options:e,forceHighlight:!0}:{options:e,forceHighlight:!1}}getOrCreateLineCache(i){if(i.cacheKey==null)return this.lineCache=void 0,pe(i.contents);let{lineCache:e}=this;return(e==null||e.cacheKey!==i.cacheKey)&&(e={cacheKey:i.cacheKey,lines:pe(i.contents)}),this.lineCache=e,e.lines}getLineCount(i){return this.textDoucmentCache.get(i)?.lineCount??this.getOrCreateLineCache(i).length}updateRenderCache(i,e){if(this.renderCache==null)return;const{result:t}=this.renderCache;if(t!=null){for(const[n,r]of i)t.code[n]={type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:r.map(([s,a,o])=>s===0&&a===""?o===""?{type:"element",tagName:"br",properties:{},children:[]}:{type:"text",value:o}:{type:"element",tagName:"span",properties:{"data-char":s,style:`--diffs-token-${e}:${a};`},children:[{type:"text",value:o}]})};t.baseThemeType=e,this.renderCache.isDirty=!0}}applyDocumentChange(i){if(this.renderCache==null)return;const{file:e,result:t}=this.renderCache;if(t!=null&&t.code.length!==i.lineCount){t.code.length=Math.min(t.code.length,i.lineCount);for(let n=t.code.length;n<i.lineCount;n++)t.code.push({type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:[{type:"element",tagName:"span",properties:{"data-char":0},children:[{type:"text",value:i.getLineText(n)}]}]});this.renderCache.isDirty=!0}this.textDoucmentCache.set(e,i)}renderFile(i=this.renderCache?.file,e=Z){if(i==null)return;let{options:t,forceHighlight:n}=this.getRenderOptions(i);const r=this.getMatchingWorkerResultCache(i,t);r!=null&&!this.hasHighlightedRenderCache(i,t)&&(this.renderCache={file:i,highlighted:!0,renderRange:void 0,...r},n=!1),this.renderCache??={file:i,highlighted:!1,options:t,result:void 0,renderRange:void 0};const s=this.getOrCreateLineCache(i),a=i.contents.length>0,o=!a||K(i)||$(s.length,this.getTokenizeMaxLength()),h=!A(i,this.renderCache.file),d=!Se(this.renderCache.renderRange,e);if(this.workerManager?.isWorkingPool()===!0)(o||this.renderCache.result==null||!this.renderCache.highlighted&&(h||d))&&(this.renderCache.file=i,this.renderCache.options=t,this.renderCache.highlighted=!1,(this.renderCache.result==null||h||d||n)&&(this.renderCache.result=this.workerManager.getPlainFileAST(i,e.startingLine,e.totalLines,s)),this.renderCache.renderRange=e),!o&&a&&(!this.renderCache.highlighted||n)&&this.workerManager.highlightFileAST(this,i);else{this.computedLang=i.lang??j(i.name);const l=this.highlighter!=null&&ie(t.theme),c=this.highlighter!=null&&ne(this.computedLang),u=!o&&c;if(this.highlighter!=null&&l&&(n||o||!this.renderCache.highlighted&&u||this.renderCache.result==null)){const{result:p,options:f}=this.renderFileWithHighlighter(i,this.highlighter,o||!c);this.renderCache={file:i,options:f,highlighted:u,result:p,renderRange:void 0}}(!l||!o&&!c)&&this.asyncHighlight(i).then(({result:p,options:f})=>{this.renderCache!=null&&(this.renderCache.highlighted=!1),this.onHighlightSuccess(i,p,f,!o)})}return this.renderCache.result!=null?this.processFileResult(this.renderCache.file,e,this.renderCache.result):void 0}async asyncRender(i,e=Z){const{result:t}=await this.asyncHighlight(i);return this.processFileResult(i,e,t)}async asyncHighlight(i){const e=$(this.getOrCreateLineCache(i).length,this.getTokenizeMaxLength());this.computedLang=e?"text":i.lang??j(i.name);const t=this.highlighter!=null&&Ct(ft(this.options.theme)),n=e||this.highlighter!=null&&ne(this.computedLang);return(this.highlighter==null||!t||!n)&&(this.highlighter=await this.initializeHighlighter()),this.renderFileWithHighlighter(i,this.highlighter,e)}renderFileWithHighlighter(i,e,t=!1){const{options:n}=this.getRenderOptions(i);return{result:St(i,e,n,{forcePlainText:t}),options:n}}processFileResult(i,e,{code:t,themeStyles:n,baseThemeType:r}){const s=this.getLineCount(i),{disableFileHeader:a=!1}=this.options,o=[],h=ue(),d=Math.min(e.startingLine+e.totalLines,s);let l=0;const c=ve(e)?Be(this.lineAnnotations):void 0;c!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:-1,lineIndex:-1,annotations:c.map(u=>I(u))})),l++);for(let u=e.startingLine;u<d;u++){const p=u+1,f=t[u];if(f==null){const g="FileRenderer.processFileResult: Line doesnt exist";throw console.error(g,{name:i.name,lineIndex:u,lineNumber:p}),new Error(g)}h.children.push(pt("context",p,`${u}`)),o.push(f),l++;const S=this.lineAnnotations[p];S!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:0,lineIndex:p,annotations:S.map(g=>I(g))})),l++)}return h.properties.style=`grid-row: span ${l}`,{gutterAST:h.children??[],contentAST:o,preAST:this.createPreElement(s),headerAST:a?void 0:this.renderHeader(i),totalLines:s,rowCount:l,themeStyles:n,baseThemeType:r,bufferBefore:e.bufferBefore,bufferAfter:e.bufferAfter,css:""}}renderHeader(i){const{headerRenderMode:e="default",stickyHeader:t=!1}=this.options;return De({fileOrDiff:i,mode:e,stickyHeader:t})}renderFullHTML(i){return H(this.renderFullAST(i))}renderFullAST(i,e=[]){return e.push(ce({tagName:"code",children:this.renderCodeAST(i),properties:{"data-code":""}})),{...i.preAST,children:e}}renderCodeAST(i){const e=ue();return e.children=i.gutterAST,e.properties.style=`grid-row: span ${i.rowCount}`,[e,Ue(i.contentAST,i.rowCount)]}renderPartialHTML(i,e=!1){return e?H(ce({tagName:"code",children:i,properties:{"data-code":""}})):H(i)}async initializeHighlighter(){return this.highlighter=await gt(_e(this.computedLang,this.options)),this.highlighter}onHighlightSuccess(i,e,t,n=!0){if(this.renderCache==null)return;const r=!A(i,this.renderCache.file)||!this.renderCache.highlighted||!F(t,this.renderCache.options);this.renderCache={file:i,options:t,highlighted:n,result:e,renderRange:void 0},r&&this.onRenderUpdate?.()}getMatchingWorkerResultCache(i,e){const t=this.workerManager?.getFileResultCache(i);if(!(t==null||!F(e,t.options)))return t}hasHighlightedRenderCache(i,e){const{renderCache:t}=this;return t?.result!=null&&t.highlighted&&A(i,t.file)&&F(e,t.options)}onHighlightError(i){console.error(i)}getTokenizeMaxLength(){return this.options.tokenizeMaxLength??1e5}createPreElement(i){const{disableLineNumbers:e=!1,overflow:t="scroll"}=this.options;return We({type:"file",diffIndicators:"none",disableBackground:!0,disableLineNumbers:e,overflow:t,split:!1,totalLines:i})}};function $(i,e){return i>e}function Tt(i,e){return i.lineNumber===e.lineNumber&&i.metadata===e.metadata}function ge(i){return{theme:i?.theme,disableLineNumbers:i?.disableLineNumbers,overflow:i?.overflow,themeType:i?.themeType,collapsed:i?.collapsed,disableFileHeader:i?.disableFileHeader,disableVirtualizationBuffers:i?.disableVirtualizationBuffers,stickyHeader:i?.stickyHeader,preferredHighlighter:i?.preferredHighlighter,useCSSClasses:i?.useCSSClasses,useTokenTransformer:i?.useTokenTransformer,tokenizeMaxLineLength:i?.tokenizeMaxLineLength,tokenizeMaxLength:i?.tokenizeMaxLength,unsafeCSS:i?.unsafeCSS,headerRenderMode:i?.renderCustomHeader!=null?"custom":"default"}}const bt=[""];let Rt=-1;var Te=class{options;workerManager;isContainerManaged;static LoadedCustomComponent=!0;__id=`file:${++Rt}`;type="file";fileContainer;spriteSVG;pre;code;bufferBefore;bufferAfter;themeCSSStyle;appliedThemeCSS;hasAdoptedThemeCSS=!1;unsafeCSSStyle;appliedUnsafeCSS;gutterUtilityContent;errorWrapper;placeHolder;lastRenderedHeaderHTML;cachedHeaderHTML;appliedPreAttributes;lastRowCount;mounted=!1;headerElement;headerCustom;headerPrefix;headerFilenameSuffix;headerMetadata;fileRenderer;resizeManager;interactionManager;annotationCache=new Map;lineAnnotations=[];managersDirty=!1;file;renderRange;enabled=!0;editor;constructor(e={theme:M},t,n=!1){this.options=e,this.workerManager=t,this.isContainerManaged=n,this.fileRenderer=new yt(e,this.handleHighlightRender,this.workerManager),this.resizeManager=new Ge,this.interactionManager=new je("file",se(e)),this.workerManager?.subscribeToThemeChanges(this)}handleHighlightRender=()=>{this.rerender()};rerender(){!this.enabled||this.file==null||this.render({file:this.file,forceRender:!0,renderRange:this.renderRange})}onThemeChange(){this.fileRenderer.clearRenderCache(),this.rerender()}setOptions(e){e!=null&&(this.options=e,this.cachedHeaderHTML=void 0,this.syncInteractionOptions())}syncInteractionOptions(){this.interactionManager.setOptions(se(this.options))}mergeOptions(e){this.options={...this.options,...e}}setThemeType(e){(this.options.themeType??"system")!==e&&(this.mergeOptions({themeType:e}),this.applyCachedThemeState(e))}applyCachedThemeState(e){if(typeof this.options.theme=="string"||this.fileContainer==null||this.appliedThemeCSS==null)return!1;const t=this.appliedThemeCSS.baseThemeType??e;return this.appliedThemeCSS.themeType===t?!1:(this.applyThemeState(this.fileContainer,this.appliedThemeCSS.themeStyles,e,this.appliedThemeCSS.baseThemeType),!0)}hasThemeChanged(){return this.appliedThemeCSS!=null&&!mt(this.appliedThemeCSS.theme,this.options.theme??M)}getHoveredLine=()=>this.interactionManager.getHoveredLine();setLineAnnotations(e){this.lineAnnotations=e}setSelectedLines(e,t){this.interactionManager.setSelection(e,t)}flushManagers(){if(!this.managersDirty||this.pre==null){this.managersDirty=!1;return}const{overflow:e="scroll"}=this.options;this.interactionManager.setup(this.pre),this.resizeManager.setup(this.pre,e==="wrap"),this.managersDirty=!1}cleanUp(e=!1){this.emitPostRender(!0),this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.managersDirty=!1,this.workerManager?.unsubscribeToThemeChanges(this),this.renderRange=void 0,this.isContainerManaged||this.fileContainer?.remove(),this.fileContainer=void 0,this.mounted=!1,e||(this.lineAnnotations=[]),this.annotationCache.clear(),this.pre=void 0,this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.lastRenderedHeaderHTML=void 0,e||(this.cachedHeaderHTML=void 0),this.errorWrapper=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.placeHolder=void 0,this.unsafeCSSStyle=void 0,e?this.fileRenderer.recycle():(this.fileRenderer.cleanUp(),this.workerManager=void 0,this.file=void 0),this.enabled=!1,this.editor?.cleanUp(),this.editor=void 0}virtualizedSetup(){this.enabled=!0,this.workerManager?.subscribeToThemeChanges(this)}hydrate(e){const{fileContainer:t,prerenderedHTML:n,preventEmit:r=!1,file:s,lineAnnotations:a}=e;this.hydrateElements(t,n),Lt(this.pre,s,this.options.collapsed)||At(this.headerElement,s,this.options.disableFileHeader)?this.render({...e,preventEmit:!0}):this.hydrationSetup({file:s,lineAnnotations:a}),r||this.emitPostRender()}hydrateElements(e,t){this.fileContainer!==e&&this.emitPostRender(!0),$e(e,t);for(const n of Array.from(e.shadowRoot?.children??[])){if(n instanceof SVGElement){this.spriteSVG=n;continue}if(n instanceof HTMLElement){if(n instanceof HTMLPreElement){this.pre=n,this.appliedPreAttributes=void 0;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-theme-css")){this.themeCSSStyle=n;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-unsafe-css")){this.unsafeCSSStyle=n,this.appliedUnsafeCSS=n.textContent;continue}if("diffsHeader"in n.dataset){this.headerElement=n,this.lastRenderedHeaderHTML=void 0;continue}}}this.pre!=null&&(this.syncCodeNodeFromPre(this.pre),this.pre.removeAttribute("data-dehydrated")),this.fileContainer=e,this.hydrateMeasuredScrollbar()}hydrationSetup({file:e,lineAnnotations:t}){this.lineAnnotations=t??this.lineAnnotations,this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),this.pre!=null&&(this.fileRenderer.hydrate(e),this.renderAnnotations(),this.renderGutterUtility(),this.injectUnsafeCSS(),this.managersDirty=!0,this.flushManagers())}getOrCreateLineCache(e=this.file){return e!=null?this.fileRenderer.getOrCreateLineCache(e):bt}updateBuffers(e){this.pre!=null&&this.applyBuffers(this.pre,e)}syncRenderViewToEditor(){const e=this.editor,t=this.fileContainer,n=this.file;e!=null&&t!=null&&n!=null&&this.fileRenderer.initializeHighlighter().then(r=>{e.__syncRenderView(r,t,n,this.lineAnnotations,this.renderRange)})}attachEditor(e){return this.editor?.cleanUp(),this.editor=e,this.interactionManager.setEditorAttached(!0),this.syncRenderViewToEditor(),()=>{this.editor=void 0,this.interactionManager.setEditorAttached(!1)}}applyDocumentChange(e,t){this.fileRenderer.applyDocumentChange(e),t!=null&&t!==this.lineAnnotations&&this.file!=null&&(this.setLineAnnotations(t),this.fileRenderer.setLineAnnotations(this.lineAnnotations),this.renderAnnotations())}updateRenderCache(e,t){this.fileRenderer.updateRenderCache(e,t)}render({file:e,fileContainer:t,forceRender:n=!1,preventEmit:r=!1,containerWrapper:s,deferManagers:a=!1,lineAnnotations:o,renderRange:h}){if(!this.enabled)throw new Error("File.render: attempting to call render after cleaned up");this.editor?.__postponeBackgroundTokenizeToNextFrame();const{collapsed:d=!1,themeType:l="system"}=this.options,c=d?void 0:h,u=this.renderRange,p=this.hasThemeChanged(),f=o!=null&&(o.length>0||this.lineAnnotations.length>0)?o!==this.lineAnnotations:!1,S=!A(this.file,e);if(!d&&!n&&Se(c,this.renderRange)&&!S&&!f&&!p)return this.applyCachedThemeState(l);this.renderRange=c,S&&(this.cachedHeaderHTML=void 0),this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),o!=null&&this.setLineAnnotations(o),this.fileRenderer.setLineAnnotations(this.lineAnnotations);const{disableErrorHandling:g=!1,disableFileHeader:y=!1}=this.options;if(y&&(this.headerElement!=null&&(this.headerElement.remove(),this.headerElement=void 0,this.lastRenderedHeaderHTML=void 0),this.clearHeaderSlots()),t=this.getOrCreateFileContainerNode(t,s),this.applyCachedThemeState(l),d){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{const m=this.fileRenderer.renderFile(e,Fe);m!=null&&this.applyThemeState(t,m.themeStyles,l,m.baseThemeType),m?.headerAST!=null&&this.applyHeaderToDOM(m.headerAST,t),this.injectUnsafeCSS()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}try{const m=this.getOrCreatePreNode(t);if(!this.canPartiallyRender(n,f,S||p)||!this.applyPartialRender(u,c)){const v=this.fileRenderer.renderFile(e,c);if(v==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.initialize().then(()=>this.rerender()),!1;this.applyThemeState(t,v.themeStyles,l,v.baseThemeType),v.headerAST!=null&&this.applyHeaderToDOM(v.headerAST,t),this.applyFullRender(v,m)}this.applyBuffers(m,c),this.injectUnsafeCSS(),this.managersDirty=!0,a||this.flushManagers(),this.renderAnnotations(),this.renderGutterUtility(),this.editor!=null&&this.syncRenderViewToEditor()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}emitPostRender(e=!1){const{fileContainer:t,options:{onPostRender:n}}=this;if(e){if(!this.mounted||(this.mounted=!1,t==null))return;n?.(t,this,"unmount");return}if(t==null)return;const r=this.mounted?"update":"mount";this.mounted=!0,n?.(t,this,r)}removeRenderedCode(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.code?.remove(),this.code=void 0,this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0}clearAuxiliaryNodes(){for(const{element:e}of this.annotationCache.values())e.remove();this.annotationCache.clear(),this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0}canPartiallyRender(e,t,n){return!(e||t||n)}renderPlaceholder(e){if(this.fileContainer==null)return!1;if(this.emitPostRender(!0),this.cleanChildNodes(),this.placeHolder==null){const t=this.fileContainer.shadowRoot??this.fileContainer.attachShadow({mode:"open"});this.placeHolder=document.createElement("div"),this.placeHolder.dataset.placeholder="",t.appendChild(this.placeHolder)}return this.placeHolder.style.setProperty("height",`${e}px`),!0}primeHighlightCache(){const{file:e,workerManager:t}=this;e==null||e.cacheKey==null||t==null||K(e)||this.fileRenderer.getOrCreateLineCache(e).length>(this.options.tokenizeMaxLength??1e5)||t.primeFileHighlightCache(e)}cleanChildNodes(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferAfter?.remove(),this.bufferBefore?.remove(),this.code?.remove(),this.errorWrapper?.remove(),this.headerElement?.remove(),this.gutterUtilityContent?.remove(),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.pre?.remove(),this.spriteSVG?.remove(),this.themeCSSStyle?.remove(),this.unsafeCSSStyle?.remove(),this.bufferAfter=void 0,this.bufferBefore=void 0,this.code=void 0,this.errorWrapper=void 0,this.headerElement=void 0,this.gutterUtilityContent=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.pre=void 0,this.spriteSVG=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.lastRenderedHeaderHTML=void 0,this.lastRowCount=void 0,this.mounted=!1}renderAnnotations(){if(this.isContainerManaged||this.fileContainer==null){for(const{element:n}of this.annotationCache.values())n.remove();this.annotationCache.clear();return}const e=new Map(this.annotationCache),{renderAnnotation:t}=this.options;if(t!=null&&this.lineAnnotations.length>0)for(const[n,r]of this.lineAnnotations.entries()){const s=`${n}-${I(r)}`;let a=this.annotationCache.get(s);if(a==null||!Tt(r,a.annotation)){a?.element.remove();const o=t(r);if(o==null)continue;a={element:qe(I(r)),annotation:r},a.element.appendChild(o),this.fileContainer.appendChild(a.element),this.annotationCache.set(s,a)}e.delete(s)}for(const[n,{element:r}]of e.entries())this.annotationCache.delete(n),r.remove()}renderGutterUtility(){const{renderGutterUtility:e}=this.options;if(this.fileContainer==null||e==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const t=e(this.interactionManager.getHoveredLine);if(t!=null&&this.gutterUtilityContent!=null)return;if(t==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const n=Ke();n.appendChild(t),this.fileContainer.appendChild(n),this.gutterUtilityContent=n}injectUnsafeCSS(){const{unsafeCSS:e}=this.options,t=this.fileContainer?.shadowRoot;if(t!=null){if(e==null||e===""){this.unsafeCSSStyle!=null&&(this.unsafeCSSStyle.remove(),this.unsafeCSSStyle=void 0),this.appliedUnsafeCSS=void 0;return}this.unsafeCSSStyle?.parentNode===t&&this.appliedUnsafeCSS===e||(this.unsafeCSSStyle??=Je(),this.unsafeCSSStyle.parentNode!==t&&t.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=Ye(e),this.appliedUnsafeCSS=e)}}applyThemeState(e,t,n,r){const s=e.shadowRoot??e.attachShadow({mode:"open"}),a=r??n,o=this.options.theme??M,h=typeof o=="string"?o:{...o},d=ae(s);if(this.themeCSSStyle?.parentNode===s&&this.appliedThemeCSS?.themeStyles===t&&this.appliedThemeCSS.themeType===a&&this.appliedThemeCSS.scrollbarGutter===d){this.appliedThemeCSS.theme=h;return}if(this.hasAdoptedThemeCSS&&this.themeCSSStyle?.parentNode===s){this.hasAdoptedThemeCSS=!1,this.appliedThemeCSS={theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:d};return}this.themeCSSStyle=Xe({shadowRoot:s,currentNode:this.themeCSSStyle,themeCSS:Qe(t,a,d)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:d}:void 0}hydrateMeasuredScrollbar(){const e=this.fileContainer?.shadowRoot;e==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=Ze(this.themeCSSStyle.textContent??"",ae(e)))}applyFullRender(e,t){this.cleanupErrorWrapper(),this.applyPreNodeAttributes(t,e),this.code=et({code:this.code});const n=this.fileRenderer.renderCodeAST(e);if(this.code.childElementCount>=2)for(let r=0;r<2;r++){const s=this.code.children[r],a=n[r];s.innerHTML=H(a.children),s.style.cssText=a.properties.style}else this.code.innerHTML=H(n);t.contains(this.code)||t.replaceChildren(this.code),this.lastRowCount=e.rowCount}applyPartialRender(e,t){if(e==null||t==null)return!1;const{file:n,code:r}=this,s=r!=null?this.getColumns(r):void 0;if(n==null||r==null||s==null)return!1;const a=e.startingLine,o=t.startingLine,h=e.totalLines===1/0?Number.POSITIVE_INFINITY:a+e.totalLines,d=t.totalLines===1/0?Number.POSITIVE_INFINITY:o+t.totalLines,l=Math.max(a,o),c=Math.min(h,d);if(c<=l||!this.trimDOMToOverlap(s.gutter,l,c)||!this.trimDOMToOverlap(s.content,l,c))return!1;let{length:u}=s.content.children;const p=(y,m)=>{if(!(m<=0))return this.fileRenderer.renderFile(n,{startingLine:y,totalLines:m,bufferBefore:0,bufferAfter:0})},f=o<l?p(o,l-o):void 0;if(f===void 0&&o<l)return!1;const S=d===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:Math.max(0,d-c),g=d>c?p(c,S):void 0;return g===void 0&&d>c?!1:(this.cleanupErrorWrapper(),f!=null&&(s.gutter.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.gutterAST)),s.content.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.contentAST)),u+=f.rowCount),g!=null&&(s.gutter.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.gutterAST)),s.content.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.contentAST)),u+=g.rowCount),this.lastRowCount!==u&&(s.gutter.style.setProperty("grid-row",`span ${u}`),s.content.style.setProperty("grid-row",`span ${u}`),this.lastRowCount=u),!0)}getColumns(e){const t=e.children[0],n=e.children[1];if(!(!(t instanceof HTMLElement)||!(n instanceof HTMLElement)||t.dataset.gutter==null||n.dataset.content==null))return{gutter:t,content:n}}trimDOMToOverlap(e,t,n){const r=this.getDOMBoundaryIndices(e,[t,n]),s=r.get(t)??e.children.length,a=r.get(n)??e.children.length;if(s>a)return!1;for(let o=e.children.length-1;o>=a;o-=1)e.children[o]?.remove();for(let o=s-1;o>=0;o-=1)e.children[o]?.remove();return!0}getDOMBoundaryIndices(e,t){const n=[...new Set(t)].sort((h,d)=>h-d),r=new Map;if(n.length===0)return r;let s=0,a=n[s];const{children:o}=e;a===0&&(r.set(0,0),s+=1,a=n[s]);for(let h=0;h<o.length;h+=1){const d=o[h];if(!(d instanceof HTMLElement))continue;const l=this.getLineIndexFromDOMNode(d);if(l!=null){for(;a!=null&&l>=a;)r.set(a,h),s+=1,a=n[s];if(s>=n.length)break}}for(const h of n)r.has(h)||r.set(h,o.length);return r}getLineIndexFromDOMNode(e){const t=e.dataset.lineIndex;if(t==null)return;const n=Number(t);return Number.isNaN(n)?void 0:n}applyBuffers(e,t){if(t==null||this.shouldDisableVirtualizationBuffers()){this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0);return}t.bufferBefore>0?(this.bufferBefore==null&&(this.bufferBefore=document.createElement("div"),this.bufferBefore.dataset.virtualizerBuffer="before",e.before(this.bufferBefore)),this.bufferBefore.style.setProperty("height",`${t.bufferBefore}px`),this.bufferBefore.style.setProperty("contain","strict")):this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),t.bufferAfter>0?(this.bufferAfter==null&&(this.bufferAfter=document.createElement("div"),this.bufferAfter.dataset.virtualizerBuffer="after",e.after(this.bufferAfter)),this.bufferAfter.style.setProperty("height",`${t.bufferAfter}px`),this.bufferAfter.style.setProperty("contain","strict")):this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0)}shouldDisableVirtualizationBuffers(){return this.options.disableVirtualizationBuffers??!1}applyHeaderToDOM(e,t){const{file:n}=this;if(n==null)return;this.cleanupErrorWrapper(),this.placeHolder?.remove(),this.placeHolder=void 0;const r=this.cachedHeaderHTML??H(e);if(this.cachedHeaderHTML=r,r!==this.lastRenderedHeaderHTML){const d=document.createElement("div");d.innerHTML=r;const l=d.firstElementChild;if(!(l instanceof HTMLElement))return;this.headerElement!=null?t.shadowRoot?.replaceChild(l,this.headerElement):t.shadowRoot?.prepend(l),this.headerElement=l,this.lastRenderedHeaderHTML=r}if(this.isContainerManaged)return;const{renderHeaderPrefix:s,renderHeaderFilenameSuffix:a,renderCustomHeader:o,renderHeaderMetadata:h}=this.options;if(o!=null){const d=o(n)??void 0;this.headerCustom=this.upsertHeaderSlotElement(t,this.headerCustom,Ce,d),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0}else{const d=s?.(n)??void 0,l=a?.(n)??void 0,c=h?.(n)??void 0;this.headerPrefix=this.upsertHeaderSlotElement(t,this.headerPrefix,ke,d),this.headerFilenameSuffix=this.upsertHeaderSlotElement(t,this.headerFilenameSuffix,Ie,l),this.headerMetadata=this.upsertHeaderSlotElement(t,this.headerMetadata,ze,c),this.headerCustom?.remove(),this.headerCustom=void 0}}clearHeaderSlots(){this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0}upsertHeaderSlotElement(e,t,n,r){if(r==null){t?.remove();return}const s=t??this.createHeaderSlotElement(n);return t==null&&e.appendChild(s),this.replaceHeaderSlotContent(s,r),s}replaceHeaderSlotContent(e,t){e.replaceChildren(),t instanceof Element?e.appendChild(t):e.innerText=`${t}`}createHeaderSlotElement(e){const t=document.createElement("div");return t.slot=e,t}getOrCreateFileContainerNode(e,t){const{fileContainer:n}=this,r=e??n??document.createElement("diffs-container"),s=n!==r;return s&&this.emitPostRender(!0),this.fileContainer=r,n!=null&&s&&(this.lastRenderedHeaderHTML=void 0,this.headerElement=void 0),t!=null&&this.fileContainer.parentNode!==t&&t.appendChild(this.fileContainer),s&&this.adoptReusableShellElements(this.fileContainer),this.ensureSpriteSVG(this.fileContainer),this.fileContainer}adoptReusableShellElements(e){const{shadowRoot:t}=e;if(t!=null)for(const n of t.children)n instanceof SVGElement?this.spriteSVG??=n:oe(n)&&n.hasAttribute("data-theme-css")?(this.themeCSSStyle??=n,this.hasAdoptedThemeCSS=!0):oe(n)&&n.hasAttribute("data-unsafe-css")&&(this.unsafeCSSStyle??=n,this.appliedUnsafeCSS??=this.options.unsafeCSS??void 0)}ensureSpriteSVG(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});if(this.spriteSVG==null){const n=document.createElement("div");n.innerHTML=tt;const r=n.firstChild;r instanceof SVGElement&&(this.spriteSVG=r)}this.spriteSVG!=null&&this.spriteSVG.parentNode!==t&&t.appendChild(this.spriteSVG)}getOrCreatePreNode(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});return this.pre==null?(this.pre=document.createElement("pre"),this.appliedPreAttributes=void 0,this.code=void 0,t.appendChild(this.pre)):this.pre.parentNode!==t&&(e.shadowRoot?.appendChild(this.pre),this.appliedPreAttributes=void 0),this.placeHolder?.remove(),this.placeHolder=void 0,this.pre}syncCodeNodeFromPre(e){this.code=void 0;for(const t of Array.from(e.children))if(t instanceof HTMLElement&&t.hasAttribute("data-code")){this.code=t;return}}applyPreNodeAttributes(e,{totalLines:t}){const{overflow:n="scroll",disableLineNumbers:r=!1}=this.options,s={type:"file",split:!1,overflow:n,disableLineNumbers:r,diffIndicators:"none",disableBackground:!0,totalLines:t};it(s,this.appliedPreAttributes)||(nt(e,s),this.appliedPreAttributes=s)}applyErrorToDOM(e,t){this.cleanupErrorWrapper(),this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0;const n=t.shadowRoot??t.attachShadow({mode:"open"});this.errorWrapper??=document.createElement("div"),this.errorWrapper.dataset.errorWrapper="",this.errorWrapper.textContent="",n.appendChild(this.errorWrapper);const r=document.createElement("div");r.dataset.errorMessage="",r.innerText=e.message,this.errorWrapper.appendChild(r);const s=document.createElement("pre");s.dataset.errorStack="",s.innerText=e.stack??"No Error Stack",this.errorWrapper.appendChild(s)}cleanupErrorWrapper(){this.errorWrapper?.remove(),this.errorWrapper=void 0}};function Lt(i,e,t=!1){return!t&&i==null&&e!=null}function At(i,e,t=!1){return i==null&&e!=null&&!t}const Mt=5e3;let Ht=-1;function xt(i,e){return(i.overflow??"scroll")!==(e.overflow??"scroll")||(i.collapsed??!1)!==(e.collapsed??!1)||(i.disableLineNumbers??!1)!==(e.disableLineNumbers??!1)||(i.disableFileHeader??!1)!==(e.disableFileHeader??!1)||i.unsafeCSS!==e.unsafeCSS}var wt=class extends Te{virtualizer;metrics;__id=`virtualized-file:${++Ht}`;top;height=0;cache={heights:new Map,checkpoints:[],fileAnnotationHeight:0};isVisible=!1;isSetup=!1;layoutDirty=!0;forceRenderOverride;currentCollapsed;constructor(i,e,t=Ne,n,r=!1){super(i,n,r),this.virtualizer=e,this.metrics=t}setMetrics(i,e=!1){!e&&rt(this.metrics,i)||(this.metrics=i,this.resetLayoutCache())}setLineAnnotations(i){this.syncLineAnnotations(i)&&this.resetLayoutCache()}syncLineAnnotations(i){return i==null||i===this.lineAnnotations||i.length===0&&this.lineAnnotations.length===0?!1:(super.setLineAnnotations(i),!0)}hasLineAnnotations(){return this.lineAnnotations.some(i=>i.lineNumber>0)}getLineHeight(i,e=!1){const t=this.cache.heights.get(i);if(t!=null)return t;const n=e?2:1;return this.metrics.lineHeight*n}setOptions(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setOptions cannot be used inside CodeView. Update CodeView options instead.");if(i==null)return;const{options:e}=this,t=!ye(e,i),n=xt(e,i);super.setOptions(i),n&&this.resetLayoutCache(!0),t&&(this.forceRenderOverride=!0),t&&this.virtualizer.instanceChanged(this,n)}setThemeType(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setThemeType cannot be used inside CodeView. Update CodeView options instead.");super.setThemeType(i)}resetLayoutCache(i=!1){this.layoutDirty=!0,this.cache.fileAnnotationHeight=0,this.cache.heights.size>0&&this.cache.heights.clear(),this.cache.checkpoints.length>0&&(this.cache.checkpoints.length=0),this.renderRange!=null&&(this.renderRange=void 0),i&&this.isSimpleMode()&&this.computeApproximateSize()}reconcileHeights(){let i=!1;if(this.fileContainer==null||this.file==null)return this.height!==0&&(i=!0),this.height=0,i;const{overflow:e="scroll"}=this.options;if(this.top=this.getVirtualizedTop(),e==="scroll"&&this.lineAnnotations.length===0&&!this.isResizeDebuggingEnabled()||this.code==null)return i;const t=this.code.children[1];if(!(t instanceof HTMLElement))return i;const n=he(this.lineAnnotations);if(this.renderRange!=null&&n&&ve(this.renderRange)){const r=Et(t)??0;r!==this.cache.fileAnnotationHeight&&(this.cache.fileAnnotationHeight=r,i=!0)}else!n&&this.cache.fileAnnotationHeight!==0&&(this.cache.fileAnnotationHeight=0,i=!0);for(const r of t.children){if(!(r instanceof HTMLElement))continue;const s=r.dataset.lineIndex;if(s==null)continue;const a=Number(s);let o=r.getBoundingClientRect().height,h=!1;r.nextElementSibling instanceof HTMLElement&&("lineAnnotation"in r.nextElementSibling.dataset||"noNewline"in r.nextElementSibling.dataset)&&("noNewline"in r.nextElementSibling.dataset&&(h=!0),o+=r.nextElementSibling.getBoundingClientRect().height);const d=this.getLineHeight(a,h);o!==d&&(i=!0,o===this.metrics.lineHeight*(h?2:1)?this.cache.heights.delete(a):this.cache.heights.set(a,o))}return(i||this.isResizeDebuggingEnabled())&&this.computeApproximateSize(!0),i}onRender=i=>this.fileContainer==null||this.file==null?!1:(i&&(this.top=this.getVirtualizedTop()),this.render({file:this.file}));prepareCodeViewItem(i,e,t,n){const r=this.syncLineAnnotations(n);let s=t?.resetFileLayoutCache===!0||r;t?.metrics!=null&&(this.metrics=t.metrics,s=!0);const{collapsed:a=!1}=this.options;return this.currentCollapsed!==a&&(this.currentCollapsed=a,s=!0),s&&this.resetLayoutCache(),this.file!==i&&(this.layoutDirty=!0),this.file=i,this.top=e,this.computeApproximateSize(),this.height}getLinePosition(i){if(this.file==null||i<1)return;const{disableFileHeader:e=!1,collapsed:t=!1}=this.options,n=this.fileRenderer.getLineCount(this.file)-1;let r=B(this.metrics,e);if(t||n<0)return{top:r,height:0};const s=Math.min(Math.max(i-1,0),n),{overflow:a="scroll"}=this.options,{lineHeight:o}=this.metrics;if(r+=this.cache.fileAnnotationHeight,a==="scroll"&&!this.hasLineAnnotations())return{top:r+s*o,height:o};const h=this.getLayoutCheckpointBeforeLineIndex(s);r=h?.top??r;for(let d=h?.lineIndex??0;d<s;d++)r+=this.getLineHeight(d,!1);return{top:r,height:this.getLineHeight(s,!1)}}getNumericScrollAnchor(i){if(this.file==null||this.renderRange==null)return;const{disableFileHeader:e=!1,collapsed:t=!1,overflow:n="scroll"}=this.options;if(t||this.renderRange.totalLines<=0)return;const r=this.fileRenderer.getLineCount(this.file)-1;if(r<0)return;const s=B(this.metrics,e),a=Math.min(this.renderRange.startingLine,r),o=Math.min(a+this.renderRange.totalLines-1,r);if(o<a)return;const{fileAnnotationHeight:h}=this.cache;if(n==="scroll"&&!this.hasLineAnnotations()){const{lineHeight:l}=this.metrics,c=s+(a===0?h:this.renderRange.bufferBefore),u=a+Math.max(Math.ceil((i-c)/l),0);return u>o?void 0:{lineNumber:u+1,top:s+h+u*l}}let d=s+(a===0?h:this.renderRange.bufferBefore);for(let l=a;l<=o;l++){if(d>=i)return{lineNumber:l+1,top:d};d+=this.getLineHeight(l)}}getVirtualizedHeight(){return this.height}getAdvancedStickySpecs(i){if(this.top==null||this.file==null)return;if(this.options.collapsed===!0)return{topOffset:this.top,height:this.height};const e=i!=null?this.computeRenderRangeFromWindow(this.file,this.top,i):this.renderRange;if(e==null)return;const{bufferBefore:t,bufferAfter:n,totalLines:r}=e;let s=0;if(r===0){const a=i??this.virtualizer.getWindowSpecs();this.top<a.top&&(s=n)}return{topOffset:this.top+t+s,height:this.height-(t+n)}}cleanUp(i=!1){this.fileContainer!=null&&this.isSimpleMode()&&this.getSimpleVirtualizer()?.disconnect(this.fileContainer),i||this.resetLayoutCache(),this.isSetup=!1,super.cleanUp(i)}computeApproximateSize(i=!1){const e=this.isResizeDebuggingEnabled();if(!i&&!this.layoutDirty&&!e)return;const t=this.height===0;if(this.height=0,this.cache.checkpoints=[],this.file==null){this.layoutDirty=!1;return}const{disableFileHeader:n=!1,collapsed:r=!1,overflow:s="scroll"}=this.options,{lineHeight:a}=this.metrics,o=this.fileRenderer.getLineCount(this.file),h=B(this.metrics,n),d=fe(this.metrics);if(this.height+=h,r){this.layoutDirty=!1;return}if(this.height+=this.cache.fileAnnotationHeight,s==="scroll"&&!this.hasLineAnnotations())this.height+=o*a;else for(let l=0;l<o;l++)this.addLayoutCheckpoint(l,this.height),this.height+=this.getLineHeight(l,!1);if(o>0&&(this.height+=d),this.fileContainer!=null&&e&&!t){const l=this.fileContainer.getBoundingClientRect();l.height!==this.height?console.log("VirtualizedFile.computeApproximateSize: computed height doesnt match",{name:this.file.name,elementHeight:l.height,computedHeight:this.height}):console.log("VirtualizedFile.computeApproximateSize: computed height IS CORRECT")}this.layoutDirty=!1}setVisibility(i){this.isAdvancedMode()||this.fileContainer==null||(i&&!this.isVisible?(this.top=this.getVirtualizedTop(),this.isVisible=!0):!i&&this.isVisible&&(this.isVisible=!1,this.rerender()))}rerender(){!this.enabled||this.file==null||(this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!1))}applyDocumentChange(i,e,t=!1){const{heights:n,checkpoints:r}=this.cache,s=this.renderRange;if(super.applyDocumentChange(i,e),this.getSimpleVirtualizer()?.markDOMDirty(),this.layoutDirty=!0,n.size>0&&n.clear(),r.length>0&&(r.length=0),this.isSimpleMode()&&this.computeApproximateSize(),t&&s!==void 0&&this.file!==void 0){const a=this.virtualizer.getWindowSpecs(),o=this.computeRenderRangeFromWindow(this.file,this.top??0,a);o.bufferAfter!==s.bufferAfter&&this.updateBuffers(o)}}render({fileContainer:i,file:e,forceRender:t=!1,lineAnnotations:n,...r}){const s=this.file==null||!A(this.file,e),{forceRenderOverride:a,isSetup:o}=this;this.forceRenderOverride=void 0;const h=this.syncLineAnnotations(n);if(h&&this.resetLayoutCache(),this.file=e,i=this.getOrCreateFileContainerNode(i),this.file==null)return console.error("VirtualizedFile.render: attempting to virtually render when we dont have file"),!1;if(o)this.top??=this.getVirtualizedTop(),s&&this.isSimpleMode()&&(this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache(!0));else{this.computeApproximateSize();const u=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(u==null)throw new Error("VirtualizedFile.render: simple virtualizer is not available");u.connect(i,this),this.isVisible=u.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode())return this.renderPlaceholder(this.height);const d=this.virtualizer.getWindowSpecs(),l=this.top??0,c=this.computeRenderRangeFromWindow(this.file,l,d);return super.render({file:this.file,fileContainer:i,renderRange:c,lineAnnotations:n,forceRender:(a??t)||h,...r})}syncVirtualizedTop(){this.top=this.getVirtualizedTop()}shouldDisableVirtualizationBuffers(){return this.isAdvancedMode()||super.shouldDisableVirtualizationBuffers()}isSimpleMode(){return this.virtualizer.type==="simple"}isAdvancedMode(){return this.virtualizer.type==="advanced"}addLayoutCheckpoint(i,e){i%Mt===0&&this.cache.checkpoints.push({lineIndex:i,top:e})}getLayoutCheckpointBeforeLineIndex(i){if(i<=0||this.cache.checkpoints.length===0)return;let e=0,t=this.cache.checkpoints.length-1,n;for(;e<=t;){const r=e+t>>1,s=this.cache.checkpoints[r];if(s==null)throw new Error("VirtualizedFile: invalid checkpoint index");s.lineIndex<=i?(n=s,e=r+1):t=r-1}return n}getLayoutCheckpointBeforeTop(i,e){let t=0,n=this.cache.checkpoints.length-1,r=-1;for(;t<=n;){const s=t+n>>1,a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");a.top<=i?(r=s,t=s+1):n=s-1}if(e==null)return r>=0?this.cache.checkpoints[r]:void 0;for(let s=r;s>=0;s--){const a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");if(a.lineIndex%e===0)return a}}getVirtualizedTop(){return this.virtualizer.type==="advanced"?this.virtualizer.getLocalTopForInstance(this):this.fileContainer!=null?this.virtualizer.getOffsetInScrollContainer(this.fileContainer):0}getSimpleVirtualizer(){return this.virtualizer.type==="simple"?this.virtualizer:void 0}isResizeDebuggingEnabled(){return this.getSimpleVirtualizer()?.config.resizeDebugging??!1}computeRenderRangeFromWindow(i,e,{top:t,bottom:n}){const{disableFileHeader:r=!1,overflow:s="scroll"}=this.options,{hunkLineCount:a,lineHeight:o}=this.metrics,h=this.fileRenderer.getLineCount(i),d=this.height,l=B(this.metrics,r),c=h>0?fe(this.metrics):0,{fileAnnotationHeight:u}=this.cache,p=l+u,f=Math.max(0,d-l-u-c),S=he(this.lineAnnotations),g=e+l,y=u>0&&S&&g<n&&g+u>t;if(e<t-d||e>n)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};if(h<=a)return{startingLine:0,totalLines:a,bufferBefore:0,bufferAfter:0};const m=Math.ceil(Math.max(n-t,0)/o),v=Math.ceil(m/a)*a+a*2,z=v/a,D=(t+n)/2;if(s==="scroll"&&!this.hasLineAnnotations()){const R=e+p,P=R+f;if(!y&&!(R<n&&P>t))return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};const w=Math.floor(y&&D<e+p?0:(D-(e+p))/o),b=Math.floor(w/a)-Math.floor(z/2),xe=Math.ceil(h/a),E=Math.max(0,Math.min(b,xe))*a,Q=b<0?v+b*a:v,we=E===0?0:u+E*o,Ee=Math.min(Q,h-E);return{startingLine:E,totalLines:Q,bufferBefore:we,bufferAfter:Math.max(0,(h-E-Ee)*o)}}const be=z,N=[],U=this.getLayoutCheckpointBeforeTop(Math.max(0,t-e-v*o*2),a);let T=e+(U?.top??p),_=U?.lineIndex??0,O,V,x;const Re=U?.lineIndex??0;for(let R=Re;R<h;R++){const P=_%a===0,w=Math.floor(_/a);if(P&&(N[w]=T-(e+p),x!=null)){if(x<=0)break;x--}const b=this.getLineHeight(R,!1);T>t-b&&T<n&&(O??=w),T+b>D&&(V??=w),x==null&&T>=n&&P&&(x=be),_++,T+=b}if(O==null)if(y)O=0,V=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};V??=O;const W=Math.round(V-z/2),Le=Math.max(0,Math.ceil(h/a)-z),G=Math.max(0,Math.min(W,Le)),J=G*a,Y=W<0?v+W*a:v,Ae=N[G]??0,Me=J===0?0:u+Ae,X=G+Y/a,He=X<N.length?f-N[X]:f-(T-e-p);return{startingLine:J,totalLines:Y,bufferBefore:Me,bufferAfter:Math.max(0,He)}}};function Et(i){let e;for(const t of i.children)t instanceof HTMLElement&&t.dataset.lineAnnotation===st&&(e=Math.max(e??0,t.getBoundingClientRect().height));return e}function Ft({file:i,renderCustomHeader:e,renderHeaderPrefix:t,renderHeaderFilenameSuffix:n,renderHeaderMetadata:r,renderAnnotation:s,lineAnnotations:a,renderGutterUtility:o,getHoveredLine:h}){const d=e?.(i),l=t?.(i),c=n?.(i),u=r?.(i);return C.jsxs(C.Fragment,{children:[d!=null?C.jsx("div",{slot:Ce,children:d}):C.jsxs(C.Fragment,{children:[l!=null&&C.jsx("div",{slot:"header-prefix",children:l}),c!=null&&C.jsx("div",{slot:"header-filename-suffix",children:c}),u!=null&&C.jsx("div",{slot:"header-metadata",children:u})]}),s!=null&&a?.map((p,f)=>C.jsx("div",{slot:I(p),children:s(p)},f)),o!=null&&C.jsx("div",{slot:"gutter-utility-slot",style:at,children:o(h)})]})}const me=typeof window>"u"?k.useEffect:k.useLayoutEffect;function kt({file:i,options:e,lineAnnotations:t,selectedLines:n,prerenderedHTML:r,metrics:s,hasGutterRenderUtility:a,hasCustomHeader:o,disableWorkerPool:h,contentEditable:d}){const l=ot(),c=n!==void 0,u=k.useContext(ht),p=lt(),f=k.useRef(null),S=dt(g=>{if(g!=null){if(f.current!=null)throw new Error("File: An instance should not already exist when a node is created");l!=null?f.current=new wt(q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),l,s,h?void 0:u,!0):f.current=new Te(q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),h?void 0:u,!0),f.current.hydrate({file:i,fileContainer:g,lineAnnotations:t,prerenderedHTML:r})}else{if(f.current==null)throw new Error("File: A File instance should exist when unmounting");f.current.cleanUp(),f.current=null}});return me(()=>{if(f.current==null)return;const g=q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),y=!ye(f.current.options,g);f.current.setOptions(g),f.current.render({file:i,lineAnnotations:t,forceRender:y}),n!==void 0&&f.current.setSelectedLines(n)}),me(()=>{if(d&&f.current!=null){if(p===void 0)throw new Error("File: Editor is not attached");return p.edit(f.current)}},[d,p]),{ref:S,getHoveredLine:k.useCallback(()=>f.current?.getHoveredLine(),[])}}function q({options:i,controlledSelection:e,contentEditable:t,hasCustomHeader:n,hasEditor:r,hasGutterRenderUtility:s}){const a=t&&r,o=e||s||n;if(!o&&!a)return i;let h={...i};return o&&(h={...h,controlledSelection:e,renderCustomHeader:n?le:i?.renderCustomHeader,renderGutterUtility:s?le:i?.renderGutterUtility}),a&&(h={...h,useTokenTransformer:!0,enableGutterUtility:!1,enableLineSelection:!1,lineHoverHighlight:"disabled"}),h}function _t({file:i,lineAnnotations:e,selectedLines:t,options:n,metrics:r,className:s,style:a,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:d,renderHeaderFilenameSuffix:l,renderHeaderMetadata:c,prerenderedHTML:u,renderGutterUtility:p,disableWorkerPool:f=!1,contentEditable:S=!1}){const{ref:g,getHoveredLine:y}=kt({file:i,options:n,metrics:r,lineAnnotations:e,selectedLines:t,prerenderedHTML:u,hasGutterRenderUtility:p!=null,hasCustomHeader:h!=null,disableWorkerPool:f,contentEditable:S});return C.jsx(Oe,{ref:g,className:s,style:a,children:ct(Ft({file:i,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:d,renderHeaderFilenameSuffix:l,renderHeaderMetadata:c,renderGutterUtility:p,lineAnnotations:e,getHoveredLine:y}),u)})}const Wt=L.memo(function({jsonString:e,className:t,maxHeight:n="100%",initiallyExpandedDepth:r=2}){const s=L.useRef(null),[a,o]=L.useState(null),h=L.useMemo(()=>{try{const c=e.trim();if(!c)return o("Empty JSON content"),null;const u=JSON.parse(c);return o(null),u}catch(c){return o(c instanceof Error?c.message:"Invalid JSON"),null}},[e]),d=L.useCallback(()=>{s.current?.expandAll()},[]),l=L.useCallback(()=>{s.current?.collapseAll()},[]);return a?C.jsx("div",{className:t,children:C.jsxs("div",{className:"rounded-md border border-[var(--interactive-border)] bg-[var(--syntax-base-background)] p-4",children:[C.jsx("div",{className:"mb-1 font-medium text-[var(--surface-foreground)]",children:"Invalid JSON"}),C.jsx("div",{className:"font-mono text-xs text-[var(--surface-mutedForeground)]",children:a})]})}):h===null?null:C.jsxs("div",{className:t,children:[C.jsxs("div",{className:"flex items-center gap-1 border-b border-[var(--interactive-border)] px-2 py-1",children:[C.jsxs(ee,{variant:"ghost",size:"xs",onClick:d,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-down-s",className:"h-3 w-3"}),"Expand All"]}),C.jsxs(ee,{variant:"ghost",size:"xs",onClick:l,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-up-s",className:"h-3 w-3"}),"Collapse All"]})]}),C.jsx("div",{className:"bg-[var(--syntax-base-background)] py-1",style:{maxHeight:n,overflow:"auto"},children:C.jsx(Ve,{ref:s,data:h,maxHeight:n,initiallyExpandedDepth:r})})]})});export{_t as F,Wt as J};
@@ -0,0 +1,12 @@
1
+ import{k as _}from"./vendor-boot-Dgb9NVFe.js";import{R as y}from"./vendor-react-DASdDPIk.js";import{m as je}from"./vendor-morphdom-B7dS_VPB.js";import{r as Ue}from"./vendor-beautiful-mermaid-DApbjBp2.js";import{S as Ze,an as Xe,t as ve,m as Ge,a8 as ee,bO as Ye,o as Z,_ as te}from"./index-BnZVqcki.js";import{c6 as Ae,c7 as Je,c8 as Qe,ae as W,br as et,bs as tt,c9 as rt,ca as nt,o as ot,cb as re,cc as at,cd as it,ce as st,q as ke,p as Ee,cf as Ce,cg as lt,aX as ct}from"./useAppFontEffects-BisjofNZ.js";import{r as dt,s as ut,i as mt,a as ft,b as pt}from"./markdownCore-D7V46WY9.js";import{r as ht}from"./registerCustomTheme-DmolaWWZ.js";import{saveOrShareFile as gt}from"./nativeFileSave-BzhtrDoD.js";import{i as bt}from"./runtimeSurface-DBiUWYK2.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-elkjs-D27273Ms.js";import"./vendor-entities-C3BA0AJP.js";import"./vendor-zustand-CUi8eEds.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-marked-CX41MkDF.js";import"./vendor-dompurify-r8glNMJW.js";import"./vendor-remend-BWYYytN3.js";import"./themeResolver-yJ9XpNMI.js";import"./vendor-pierre-theming-Dgp7B_O4.js";import"./vendor-shikijs-core-CGM_jqPK.js";import"./vendor-shikijs-types-CPSbSeK6.js";import"./vendor-shikijs-vscode-textmate-BgLrS_2D.js";import"./vendor-hast-util-to-html-BKBhbTDb.js";import"./vendor-html-void-elements-CkdplsNl.js";import"./vendor-property-information-rJCbAzvX.js";import"./vendor-zwitch-C2o2j-tx.js";import"./vendor-stringify-entities-CsH1VEn9.js";import"./vendor-character-entities-legacy-BpoLgcEt.js";import"./vendor-character-entities-html4-D7taRCQ7.js";import"./vendor-ccount-c2V3InAJ.js";import"./vendor-comma-separated-tokens-D8TqSuIK.js";import"./vendor-space-separated-tokens-DD3iYX1K.js";import"./vendor-hast-util-whitespace-D4Wp6AEg.js";const Se="pichamber-md",wt={name:Se,colors:{"editor.background":"transparent","editor.foreground":"var(--md-syntax-foreground)"},tokenColors:[{scope:["comment","punctuation.definition.comment","string.comment"],settings:{foreground:"var(--md-syntax-comment)",fontStyle:"italic"}},{scope:["string","punctuation.definition.string","string.template"],settings:{foreground:"var(--md-syntax-string)"}},{scope:["constant.numeric","constant.language","constant.character","constant"],settings:{foreground:"var(--md-syntax-number)"}},{scope:["keyword","storage","storage.type","storage.modifier","keyword.control"],settings:{foreground:"var(--md-syntax-keyword)"}},{scope:["keyword.operator","punctuation.separator","punctuation.terminator"],settings:{foreground:"var(--md-syntax-operator)"}},{scope:["entity.name.function","support.function","meta.function-call"],settings:{foreground:"var(--md-syntax-function)"}},{scope:["entity.name.type","entity.name.class","support.type","support.class","entity.other.inherited-class"],settings:{foreground:"var(--md-syntax-type)"}},{scope:["variable","variable.other","variable.parameter","meta.definition.variable"],settings:{foreground:"var(--md-syntax-variable)"}},{scope:["variable.other.property","meta.property-name","support.type.property-name"],settings:{foreground:"var(--md-syntax-property)"}},{scope:["entity.name.tag","punctuation.definition.tag"],settings:{foreground:"var(--md-syntax-keyword)"}},{scope:["entity.other.attribute-name"],settings:{foreground:"var(--md-syntax-property)"}},{scope:["markup.bold","punctuation.definition.bold"],settings:{fontStyle:"bold"}},{scope:["markup.italic","punctuation.definition.italic"],settings:{fontStyle:"italic"}},{scope:["markup.heading","markup.heading entity.name"],settings:{foreground:"var(--md-syntax-keyword)",fontStyle:"bold"}},{scope:["markup.inserted","punctuation.definition.inserted"],settings:{foreground:"var(--md-syntax-inserted)"}},{scope:["markup.deleted","punctuation.definition.deleted"],settings:{foreground:"var(--md-syntax-deleted)"}},{scope:["invalid","invalid.illegal"],settings:{foreground:"var(--md-syntax-deleted)"}}]};let ne=!1;const yt=()=>{ne||(ne=!0,ht(Se,()=>Promise.resolve(wt)))},k=e=>Number.isFinite(e)&&e>0,oe=e=>{if(typeof e=="number")return k(e)?e:null;if(typeof e!="string")return null;const t=e.trim().match(/^([+-]?(?:(?:\d+\.?\d*)|(?:\.\d+))(?:[eE][+-]?\d+)?)(?:px)?$/);if(!t)return null;const n=Number(t[1]);return k(n)?n:null},B=(e,t,n)=>Math.min(n,Math.max(t,e)),vt=6,ae=1.25,At=1.0015,kt=.5,Et=12,ie=3,Ct=400,I='[data-markdown="mermaid-block"]',M=e=>e.querySelector(I)!==null,St=e=>[e.x,e.y,e.width,e.height].map(t=>{const n=Number(t.toFixed(vt));return Object.is(n,-0)?"0":String(n)}).join(" "),Mt=e=>{const t=e.viewBox?.trim().split(/[\s,]+/).map(s=>Number.parseFloat(s));if(t?.length===4){const[s,o,a,i]=t;if(Number.isFinite(s)&&Number.isFinite(o)&&k(a)&&k(i))return{x:s,y:o,width:a,height:i}}const n=oe(e.width),r=oe(e.height);return n===null||r===null?null:{x:0,y:0,width:n,height:r}},Lt=e=>{let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)},Nt=e=>{const t=e.renderMode||"unknown",n=e.svgMarkup??"";if(!n){const r=[e.viewBox??"",e.width??"",e.height??""];return r.some(s=>s!=="")?`${t}:bounds:${r.join(":")}`:`${t}:no-svg`}return[t,Lt(n)].join(":")},Me=(e,t)=>{if(!k(t.width)||!k(t.height))return e;const n=e.width/e.height,r=t.width/t.height;if(n>r){const o=e.width/r;return{x:e.x,y:e.y-(o-e.height)/2,width:e.width,height:o}}const s=e.height*r;return{x:e.x-(s-e.width)/2,y:e.y,width:s,height:e.height}},xt=({currentBox:e,viewport:t,delta:n})=>!k(t.width)||!k(t.height)||!k(e.width)||!k(e.height)?e:{x:e.x-n.x/t.width*e.width,y:e.y-n.y/t.height*e.height,width:e.width,height:e.height},Tt=(e,t)=>{const n=t.x-e.x,r=t.y-e.y;return n*n+r*r>ie*ie},Pt=({currentBox:e,contentBox:t,viewport:n,pointer:r,zoomFactor:s,minScale:o,maxScale:a})=>{if(!k(n.width)||!k(n.height)||!k(s)||!k(e.width)||!k(e.height)||!k(t.width)||!k(t.height)||!k(o)||!k(a))return e;const i=Math.min(o,a),l=Math.max(o,a),d=Me(t,n),c=d.width/e.width,m=B(c*s,i,l),f=d.width/m,p=f/(e.width/e.height),h=B(r.x/n.width,0,1),v=B(r.y/n.height,0,1),A=e.x+h*e.width,w=e.y+v*e.height;return{x:A-h*f,y:w-v*p,width:f,height:p}},X=new WeakMap,Rt=e=>e instanceof HTMLElement?X.get(e)??null:null,_t=e=>e.querySelector('[data-markdown="mermaid-viewport"]')??e.querySelector('[data-markdown="mermaid"]'),se=e=>{const t=e.querySelector('[data-markdown="mermaid"] svg'),n=e.querySelector('[data-markdown="mermaid"]');return Nt({renderMode:e.getAttribute("data-mermaid-render"),svgMarkup:n?.getAttribute("data-md-original-svg")??t?.outerHTML??null,viewBox:t?.getAttribute("viewBox"),width:t?.getAttribute("width"),height:t?.getAttribute("height")})},R=e=>{const t=e.getBoundingClientRect();return{width:t.width,height:t.height}},It=(e,t)=>{const n=t.getBoundingClientRect();return{x:e.clientX-n.left,y:e.clientY-n.top}},Ft=e=>e instanceof Element&&!!e.closest('button, a, [role="button"]'),Ot=e=>{const t=_t(e),n=e.querySelector('[data-markdown="mermaid"] svg');if(!t||!n)return null;const r=Mt({viewBox:n.getAttribute("viewBox"),width:n.getAttribute("width"),height:n.getAttribute("height")});if(!r)return null;let s=r,o=null,a=null,i=null,l=null;const d=u=>{s=u,n.setAttribute("viewBox",St(u)),n.removeAttribute("width"),n.removeAttribute("height")},c=()=>{d(Me(r,R(t)))},m=(u,E)=>{d(Pt({currentBox:s,contentBox:r,viewport:R(t),pointer:u,zoomFactor:E,minScale:kt,maxScale:Et}))},f=()=>{const u=R(t);m({x:u.width/2,y:u.height/2},ae)},p=()=>{const u=R(t);m({x:u.width/2,y:u.height/2},1/ae)},h=u=>{!u.ctrlKey&&!u.metaKey||(u.preventDefault(),u.stopPropagation(),m(It(u,t),Math.pow(At,-u.deltaY)))},v=u=>{u.button!==0||Ft(u.target)||(o=u.pointerId,a={x:u.clientX,y:u.clientY},i=a,l!==null&&(window.clearTimeout(l),l=null),e.removeAttribute("data-mermaid-suppress-click"),t.setPointerCapture?.(u.pointerId),e.setAttribute("data-mermaid-panning","true"),u.preventDefault())},A=u=>{if(o!==u.pointerId||!i)return;const E={x:u.clientX,y:u.clientY};d(xt({currentBox:s,viewport:R(t),delta:{x:E.x-i.x,y:E.y-i.y}})),i=E,a&&Tt(a,E)&&e.setAttribute("data-mermaid-suppress-click","true"),u.preventDefault()},w=u=>{o===u.pointerId&&(t.releasePointerCapture?.(u.pointerId),o=null,a=null,i=null,e.removeAttribute("data-mermaid-panning"),e.hasAttribute("data-mermaid-suppress-click")&&(l=window.setTimeout(()=>{e.removeAttribute("data-mermaid-suppress-click"),l=null},Ct)))},g=()=>{c()};t.addEventListener("wheel",h,{passive:!1}),t.addEventListener("pointerdown",v),t.addEventListener("pointermove",A),t.addEventListener("pointerup",w),t.addEventListener("pointercancel",w),window.addEventListener("resize",g);const b=typeof ResizeObserver>"u"?null:new ResizeObserver(g);return b?.observe(t),c(),{zoomIn:f,zoomOut:p,fit:c,cleanup:()=>{t.removeEventListener("wheel",h),t.removeEventListener("pointerdown",v),t.removeEventListener("pointermove",A),t.removeEventListener("pointerup",w),t.removeEventListener("pointercancel",w),window.removeEventListener("resize",g),b?.disconnect(),l!==null&&window.clearTimeout(l),e.removeAttribute("data-mermaid-panning"),e.removeAttribute("data-mermaid-suppress-click"),X.delete(e)}}},Dt=e=>{const t=new Map,n=new Map,r=()=>{for(const[o,a]of Array.from(t.entries())){const i=se(o);(!e.contains(o)||i!==n.get(o))&&(a.cleanup(),t.delete(o),n.delete(o))}for(const o of Array.from(e.querySelectorAll(I))){if(t.has(o)||o.querySelector('[data-markdown="mermaid"] svg')===null)continue;const a=Ot(o);a&&(t.set(o,a),n.set(o,se(o)),X.set(o,a))}},s=()=>{for(const o of t.values())o.cleanup();t.clear(),n.clear()};return r(),{refresh:r,cleanup:s}},x=e=>`<svg class="remixicon size-3.5" viewBox="0 0 24 24" aria-hidden="true"><use href="#oc-${e}"></use></svg>`,q={copy:x("file-copy"),check:x("check"),download:x("download"),zoomIn:x("add"),zoomOut:x("subtract"),fit:x("refresh")},Le="p-1 rounded hover:bg-interactive-hover/60 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--interactive-focus-ring)]",$=(e,t)=>{e.innerHTML=t},S=(e,t,n)=>{const r=document.createElement("button");return r.type="button",r.className=Le,r.setAttribute("data-md-action",n),r.setAttribute("title",t),r.setAttribute("aria-label",t),$(r,q[e]),r},Ne=e=>{const t=e.querySelector("[data-md-code-body]"),n=e.querySelector("pre"),r=e.querySelector("pre code"),s=e.querySelectorAll("[data-md-code-line-content]");e.setAttribute("data-code-wrap","true"),t?.classList.remove("overflow-x-auto"),t?.classList.add("overflow-x-hidden"),n?.classList.add("whitespace-pre-wrap","break-words"),r?.classList.add("whitespace-pre-wrap","break-words"),n&&(n.style.whiteSpace="pre-wrap",n.style.overflowWrap="anywhere"),r&&(r.style.whiteSpace="pre-wrap",r.style.overflowWrap="anywhere");for(const o of Array.from(s))o.style.whiteSpace="pre-wrap",o.style.overflowWrap="anywhere"},xe=e=>{const t=e.querySelector(":scope > code");if(!t||t.hasAttribute("data-md-code-lines"))return;const n=t.textContent??"",r=n.endsWith(`
2
+ `),s=r?n.slice(0,-1).split(`
3
+ `):n.split(`
4
+ `),o=s.length>0?s:[""],a=Array.from(t.children).filter(d=>d.classList.contains("line"));r&&a.length===o.length+1&&a.at(-1)?.textContent===""&&a.pop();const i=a.length===o.length,l=document.createDocumentFragment();o.forEach((d,c)=>{const m=document.createElement("span");m.setAttribute("data-md-code-line","");const f=document.createElement("span");f.setAttribute("data-md-code-line-number",""),f.setAttribute("aria-hidden","true"),f.textContent=String(c+1);const p=document.createElement("span");if(p.setAttribute("data-md-code-line-content",""),i){const h=a[c];h&&p.append(...Array.from(h.childNodes))}else p.textContent=d;if(m.append(f,p),l.appendChild(m),c<o.length-1||r){const h=document.createElement("span");h.setAttribute("data-md-code-line-break",""),h.textContent=`
5
+ `,l.appendChild(h)}}),t.replaceChildren(l),t.setAttribute("data-md-code-lines",""),t.toggleAttribute("data-md-code-trailing-newline",r)},Te=e=>{const t=Array.from(e.querySelectorAll("[data-md-code-line-content]"));if(t.length===0)return e.textContent??"";const n=t.map(r=>r.textContent??"").join(`
6
+ `);return e.hasAttribute("data-md-code-trailing-newline")?`${n}
7
+ `:n},qt=e=>{const t=e.querySelectorAll('[data-component="markdown-code"]');for(const n of Array.from(t)){const r=n.querySelector("pre");r&&xe(r),Ne(n)}},le=(e,t,n,r)=>{$(e,q.check),e.setAttribute("title",t),e.setAttribute("aria-label",t),window.setTimeout(()=>{$(e,q[n]),e.setAttribute("title",r),e.setAttribute("aria-label",r)},2e3)},$t=e=>{const t=e.querySelectorAll(":not(pre) > code");for(const n of Array.from(t))n.getAttribute("data-markdown")!=="inline-code"&&n.setAttribute("data-markdown","inline-code")},zt=(e,t)=>{const n=e.querySelectorAll("pre");for(const r of Array.from(n)){if(r.querySelector("code.language-mermaid"))continue;const s=r.parentElement;if(!s||s.closest('[data-component="markdown-code"]'))continue;const o=r.querySelector("code")?.className.match(/language-([\w+#.-]+)/)?.[1],a=r.getAttribute("data-md-lang")??o??"text",i=document.createElement("div");i.setAttribute("data-component","markdown-code"),i.className="my-4 group overflow-hidden rounded-2xl border border-border/80 bg-[var(--surface-elevated)]";const l=document.createElement("div");l.className="flex items-center justify-between border-b border-border/70 px-3 py-1.5";const d=document.createElement("span");d.className="font-mono text-[13px] text-muted-foreground",d.textContent=a;const c=S("copy",t.labels.copy,"copy-code");l.appendChild(d);const m=document.createElement("div");m.className="flex items-center gap-1",m.setAttribute("data-md-code-actions",""),m.appendChild(c),l.appendChild(m);const f=document.createElement("div");f.setAttribute("data-md-code-body",""),f.className="px-3 py-2.5 overflow-x-auto",s.replaceChild(i,r),r.style.margin="0",r.style.background="transparent",r.classList.add("min-w-0","w-full","flex-1"),t.deferCodeLineNumberSync||xe(r),f.appendChild(r),i.appendChild(l),i.appendChild(f),Ne(i)}},ce=e=>{const t=[],n=[],r=e.querySelectorAll("thead th");for(const o of Array.from(r))t.push((o.textContent??"").trim());const s=e.querySelectorAll("tbody tr");for(const o of Array.from(s)){const a=Array.from(o.querySelectorAll("td")).map(i=>(i.textContent??"").trim());a.length>0&&n.push(a)}return{headers:t,rows:n}},Ht=e=>/[",\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e,de=({headers:e,rows:t})=>[e,...t].map(n=>n.map(Ht).join(",")).join(`
8
+ `),Wt=({headers:e,rows:t})=>[e,...t].map(n=>n.join(" ")).join(`
9
+ `),ue=({headers:e,rows:t})=>{const n=`| ${e.join(" | ")} |`,r=`| ${e.map(()=>"---").join(" | ")} |`,s=t.map(o=>`| ${o.join(" | ")} |`).join(`
10
+ `);return`${n}
11
+ ${r}
12
+ ${s}`},me=(e,t)=>{const n=document.createElement("div");n.className=`absolute top-full right-0 mt-1 hidden ${et}`,n.style.backgroundColor="var(--surface-elevated)",n.style.color="var(--surface-elevated-foreground)",n.setAttribute("data-md-menu",e);for(const r of t){const s=document.createElement("button");s.type="button",s.className=`w-full text-left ${tt}`,s.setAttribute("data-md-action",`${e}-${r.key}`),s.textContent=r.label,n.appendChild(s)}return n},Bt=(e,t)=>{const n=e.querySelectorAll("table");for(const r of Array.from(n)){if(r.closest('[data-markdown="table-wrapper"]'))continue;const o=document.createElement("div");o.className="group my-4 flex flex-col space-y-2",o.setAttribute("data-markdown","table-wrapper");const a=document.createElement("div");a.className="flex items-center justify-end gap-1";const i=document.createElement("div");i.className="relative",i.appendChild(S("copy",t.copyTable,"table-copy-toggle")),i.appendChild(me("table-copy",[{key:"csv",label:"CSV"},{key:"tsv",label:"TSV"},{key:"markdown",label:"Markdown"}]));const l=document.createElement("div");l.className="relative",l.appendChild(S("download",t.downloadTable,"table-download-toggle")),l.appendChild(me("table-download",[{key:"csv",label:"CSV"},{key:"markdown",label:"Markdown"}])),a.appendChild(i),a.appendChild(l);const d=document.createElement("div");d.className="overflow-x-auto rounded-lg border border-border/80 bg-[var(--surface-elevated)]";const c=r.parentElement;if(!c)continue;c.replaceChild(o,r),r.setAttribute("data-markdown","table"),r.classList.add("w-full","border-collapse","text-sm");for(const f of Array.from(r.querySelectorAll("tr")))f.classList.add("border-b","border-border/60");const m=r.querySelector("tbody tr:last-child");m?.classList.remove("border-b"),m?.classList.add("border-0");for(const f of Array.from(r.querySelectorAll("th")))f.classList.add("border-r","border-border/60","px-4","py-2.5","text-left","align-middle","font-semibold","text-foreground","last:border-r-0");for(const f of Array.from(r.querySelectorAll("td")))f.classList.add("border-r","border-border/60","px-4","py-2.5","align-middle","text-foreground/90","last:border-r-0");d.appendChild(r),o.appendChild(a),o.appendChild(d)}},Vt=(e,t)=>{const n=e.querySelectorAll("pre > code.language-mermaid");for(const r of Array.from(n)){const s=r.parentElement;if(!s)continue;const o=(r.textContent??"").replace(/\s+$/,""),a=t.renderMermaid(o),i=document.createElement("div");i.setAttribute("data-markdown","mermaid-block"),i.setAttribute("data-md-source",o),i.className="group relative";const l=document.createElement("div");l.setAttribute("data-markdown","mermaid-scroll");const d=document.createElement("div");if(d.setAttribute("data-markdown","mermaid-toolbar"),d.className="absolute top-1 right-2 flex items-center gap-1 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity",a.svg){i.setAttribute("data-mermaid-render","svg");const m=document.createElement("div");m.setAttribute("data-markdown","mermaid-viewport");const f=document.createElement("div");if(f.setAttribute("data-markdown","mermaid"),f.setAttribute("data-md-original-svg",a.svg),f.innerHTML=a.svg,m.appendChild(f),l.appendChild(m),t.mermaidControls.showPanZoomControls&&(d.appendChild(S("zoomIn",t.labels.zoomInDiagram,"mermaid-zoom-in")),d.appendChild(S("zoomOut",t.labels.zoomOutDiagram,"mermaid-zoom-out")),d.appendChild(S("fit",t.labels.resetDiagramView,"mermaid-fit"))),t.mermaidControls.copy){const p=S("copy",t.labels.copyDiagram,"mermaid-copy");p.setAttribute("data-md-source",o),d.appendChild(p)}if(t.mermaidControls.download){const p=S("download",t.labels.downloadDiagram,"mermaid-download");p.setAttribute("data-md-svg","1"),d.appendChild(p)}}else{i.setAttribute("data-mermaid-render","svg");const m=document.createElement("pre");if(m.setAttribute("data-markdown","mermaid-ascii"),m.textContent=o,l.appendChild(m),t.mermaidControls.copy){const f=S("copy",t.labels.copyDiagram,"mermaid-copy");f.setAttribute("data-md-source",o),d.appendChild(f)}}i.appendChild(l),i.appendChild(d);const c=s.parentElement;c&&c.replaceChild(i,s)}},Kt=(e,t)=>{const n=e.querySelectorAll("a[href]");for(const r of Array.from(n)){if(r.getAttribute("data-md-link-decorated")==="true"||r.getAttribute("data-pichamber-file-link")==="true")continue;const s=r.getAttribute("href")??"";if(!Ae(s))continue;r.setAttribute("data-md-link-decorated","true");const o=Je(s);if(o){const a=document.createElement("span");a.className="mr-1 inline-flex size-[18px] items-center justify-center rounded border border-[var(--border)] bg-[var(--interactive-hover)] align-middle";const i=document.createElement("img");i.src=o,i.alt="",i.setAttribute("aria-hidden","true"),i.loading="lazy",i.decoding="async",i.className="size-3.5 rounded-sm",i.addEventListener("error",()=>a.remove(),{once:!0}),a.appendChild(i),r.parentNode?.insertBefore(a,r)}if(t.onPreviewLoopback&&Qe(s)){const a=document.createElement("button");a.type="button",a.className=`ml-1 align-middle ${Le}`,a.setAttribute("data-md-action","preview-loopback"),a.setAttribute("data-md-url",s),a.setAttribute("title",t.labels.previewTitle),a.setAttribute("aria-label",t.labels.previewLabel),$(a,q.download),r.parentNode?.insertBefore(a,r.nextSibling)}}},fe=(e,t)=>{$t(e),Vt(e,t),zt(e,t),Bt(e,t.labels),Kt(e,t)},pe=(e,t,n)=>{gt({filename:e,mimeType:n,data:t}).catch(r=>console.warn("[markdown] Download failed",r))},F=e=>{for(const t of Array.from(e.querySelectorAll("[data-md-menu]")))t.classList.add("hidden")},jt=(e,t)=>{const n=r=>{const s=r.target;if(!(s instanceof Element))return;const o=s.closest("[data-md-action]");if(!o){F(e);return}const a=o.getAttribute("data-md-action")??"";if(a==="copy-code"){const i=o.closest('[data-component="markdown-code"]')?.querySelector("code"),l=i?Te(i):"";l&&W(l).then(()=>le(o,t.labels.copied,"copy",t.labels.copy));return}if(a==="table-copy-toggle"||a==="table-download-toggle"){r.preventDefault();const i=o.parentElement?.querySelector("[data-md-menu]")??null,l=i?.classList.contains("hidden")??!1;F(e),i&&l&&i.classList.remove("hidden");return}if(a.startsWith("table-copy-")){const i=a.replace("table-copy-",""),l=o.closest('[data-markdown="table-wrapper"]')?.querySelector("table");if(l instanceof HTMLTableElement){const d=ce(l),c=i==="csv"?de(d):i==="tsv"?Wt(d):ue(d);W(c)}F(e);return}if(a.startsWith("table-download-")){const i=a.replace("table-download-",""),l=o.closest('[data-markdown="table-wrapper"]')?.querySelector("table");if(l instanceof HTMLTableElement){const d=ce(l),c=i==="csv"?de(d):ue(d);pe(i==="csv"?"table.csv":"table.md",c,i==="csv"?"text/csv":"text/markdown")}F(e);return}if(a==="mermaid-copy"){const i=o.getAttribute("data-md-source")??"";i&&W(i).then(()=>le(o,t.labels.copied,"copy",t.labels.copyDiagram));return}if(a==="mermaid-zoom-in"||a==="mermaid-zoom-out"||a==="mermaid-fit"){r.preventDefault();const i=o.closest('[data-markdown="mermaid-block"]'),l=Rt(i);a==="mermaid-zoom-in"?l?.zoomIn():a==="mermaid-zoom-out"?l?.zoomOut():l?.fit();return}if(a==="mermaid-download"){const i=o.closest('[data-markdown="mermaid-block"]')?.querySelector('[data-markdown="mermaid"]'),l=i?.getAttribute("data-md-original-svg")??i?.innerHTML??"";l&&pe("diagram.svg",l,"image/svg+xml;charset=utf-8");return}if(a==="preview-loopback"){r.preventDefault();const i=o.getAttribute("data-md-url")??"";i&&t.onPreviewLoopback?.(i);return}};return e.addEventListener("click",n),()=>e.removeEventListener("click",n)},he=(e,t,n)=>{let r=0;for(const o of e){const a=r+o.data.length;if(t<a||t===a&&n==="left")return{node:o,offset:Math.max(0,t-r)};r=a}const s=e.at(-1);return s?{node:s,offset:s.data.length}:null},Ut=new Set(["dockerfile","makefile","readme","license",".env",".gitignore",".npmrc"]),ge=Array.from(Ut).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),Zt=e=>nt(e),Xt=e=>rt(e),z=e=>{let t=(e||"").trim();return t?((t.startsWith("`")&&t.endsWith("`")||t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1).trim()),t=t.replace(/[.,;!?]+$/g,""),t.endsWith(")")&&!t.includes("(")&&(t=t.slice(0,-1)),t.endsWith("]")&&!t.includes("[")&&(t=t.slice(0,-1)),t):""},O=e=>{let t=z(e);if(!t)return"";const n=t.indexOf(";");n>=0&&(t=t.slice(0,n)),t=t.replace(/#.*$/,"");const r=t.match(/^(.*\.[A-Za-z0-9_-]{1,16}):.*$/);r&&(t=r[1]??t);const s=ge.length>0?t.match(new RegExp(`^(.*(?:/|^)(${ge})):.*$`,"i")):null;return s&&(t=s[1]??t),z(t)},Pe=e=>{const t=z(e);if(!t)return null;const n=t.indexOf(";"),r=n>=0?z(t.slice(0,n)):t;if(!r)return null;const s=r.match(/^(.*?):(\d+)-(\d+)$/);if(s){const l=O(s[1]??""),d=Number.parseInt(s[2]??"",10),c=Number.parseInt(s[3]??"",10);return!l||!Number.isFinite(d)||!Number.isFinite(c)||c<d?null:{path:l,line:d,endLine:c}}const o=r.match(/^(.*)#L(\d+)(?:C(\d+))?$/i);if(o){const l=O(o[1]??""),d=Number.parseInt(o[2]??"",10),c=o[3]?Number.parseInt(o[3],10):void 0;return!l||!Number.isFinite(d)?null:{path:l,line:d,column:Number.isFinite(c??Number.NaN)?c:void 0}}const a=r.match(/^(.*?):(\d+)(?::(\d+))?$/);if(a){const l=O(a[1]??""),d=Number.parseInt(a[2]??"",10),c=a[3]?Number.parseInt(a[3],10):void 0;return!l||!Number.isFinite(d)?null:{path:l,line:d,column:Number.isFinite(c??Number.NaN)?c:void 0}}const i=O(r);return i?{path:i}:null},V=/(?:[A-Za-z]:[\\/])?[\w.\-/@+]*[\w\-/@+]\.[A-Za-z0-9]{1,8}(?::\d+(?:-\d+)?(?::\d+)?)?/g,Re=({containerRef:e,enabled:t})=>{y.useEffect(()=>{if(t===!1)return;const n=e.current;if(!n)return;const r=s=>{if(s.defaultPrevented||s.button!==0||s.metaKey||s.ctrlKey||s.altKey||s.shiftKey)return;const o=s.target;if(!(o instanceof Element))return;const a=o.closest("a[href]");if(!(a instanceof HTMLAnchorElement)||a.getAttribute("data-pichamber-file-link")==="true")return;const i=a.getAttribute("href")??"";Ae(i)&&(s.preventDefault(),s.stopPropagation(),ot(i))};return n.addEventListener("click",r),()=>{n.removeEventListener("click",r)}},[e,t])},be='[data-pichamber-file-link="true"]',_e="data-pichamber-block-path-token",Ie=`[${_e}]`,T="data-pichamber-block-paths-scanned",Gt=2e5,Yt=4,Jt=1e3,Qt=80,we=160,L=new Map;let D=0;const ye=[],er=()=>Jt,tr=()=>Qt,rr=new Set(["dockerfile","makefile","readme","license",".env",".gitignore",".npmrc"]),G=e=>Zt(e),nr=e=>Xt(e),or=(e,t)=>st(e,t),ar=e=>{const t=e.split("/").filter(Boolean).pop()??"";return!t||t.endsWith(".")?!1:/\.[A-Za-z0-9_-]{1,16}$/.test(t)},Fe=e=>{if(!e||e.startsWith("--")||e.includes("://")||/[<>]/.test(e)||/\s{2,}/.test(e))return!1;const t=G(e),n=t.split("/").filter(Boolean).pop()??t;if(!n||n==="."||n==="..")return!1;const r=n.toLowerCase();return rr.has(r)||r.startsWith(".")&&r.length>1?!0:ar(t)},Oe=e=>{const t=Pe(e);return t?Fe(t.path):!1},ir=e=>{const t=e.querySelectorAll(Ie);for(const r of Array.from(t))r.replaceWith(e.ownerDocument.createTextNode(r.textContent??""));const n=e.querySelectorAll(`code[${T}]`);for(const r of Array.from(n))r.removeAttribute(T),r.normalize()},K=e=>{if(e.tagName.toLowerCase()==="a"){const t=e.getAttribute("href")?.trim();if(t&&Oe(t))return t}return(e.textContent||"").trim()},sr=e=>{const t=e.querySelectorAll("pre code");if(t.length===0)return;const n=e.ownerDocument;if(n)for(const r of Array.from(t)){if(r.getAttribute(T)==="true")continue;if((r.textContent??"").length>Gt){r.setAttribute(T,"true");continue}const s=n.createTreeWalker(r,NodeFilter.SHOW_TEXT),o=[];let a=s.nextNode();for(;a;){const c=a;c.parentElement?.closest("[data-md-code-line-number]")||o.push(c),a=s.nextNode()}const i=Te(r);if(!i.includes(".")){r.setAttribute(T,"true");continue}V.lastIndex=0;const l=[];let d=V.exec(i);for(;d;){const c=d[0];c&&Oe(c)&&l.push({start:d.index,end:d.index+c.length,raw:c}),d=V.exec(i)}for(const{start:c,end:m,raw:f}of l.reverse()){const p=he(o,c,"right"),h=he(o,m,"left");if(!p||!h)continue;const v=n.createRange();v.setStart(p.node,p.offset),v.setEnd(h.node,h.offset);const A=n.createElement("span");A.setAttribute(_e,"true"),A.textContent=f,v.deleteContents(),v.insertNode(A)}r.setAttribute(T,"true")}},j=(e,t)=>{const n=Pe(e);if(!n||!Fe(n.path))return null;const r=nr(n.path)?G(n.path):or(t,n.path);return r?{...n,resolvedPath:r}:null},lr=e=>{const t=G(e);if(!t)return Promise.resolve(!1);const n=L.get(t);if(n)return L.delete(t),L.set(t,n),n;const r=new Promise(o=>{const a=()=>{D+=1,Ge(`/api/fs/stat?path=${encodeURIComponent(t)}&optional=true`,{method:"GET",cache:"no-store"}).then(async i=>{if(!i.ok){o(!1);return}const l=await i.json().catch(()=>null);o(l?.exists!==!1)}).catch(()=>o(!1)).finally(()=>{D=Math.max(0,D-1),ye.shift()?.()})};if(D<Yt){a();return}ye.push(a)}),s=er();for(;L.size>=s;){const o=L.keys().next().value;if(typeof o!="string")break;L.delete(o)}return L.set(t,r),r},cr=(e,t)=>e||it(e,t),De=({containerRef:e,effectiveDirectory:t,editor:n,preferRuntimeEditor:r,enabled:s})=>{const o=y.useRef(null);y.useEffect(()=>{const a=e.current;if(!a)return;let i=!1;const l=tr(),d=s&&!bt(),c=g=>{g.removeAttribute("data-pichamber-file-link"),g.removeAttribute("data-pichamber-file-ref"),g.removeAttribute("data-pichamber-file-path"),g.getAttribute("title")==="Open file"&&g.removeAttribute("title"),g.tagName.toLowerCase()!=="a"&&(g.removeAttribute("role"),g.removeAttribute("tabindex"))},m=()=>{const g=a.querySelectorAll(be);for(const b of Array.from(g))c(b);ir(a)};if(!d){m();return}const f=(g=0)=>{if(o.current!==null&&typeof window<"u"&&window.clearTimeout(o.current),typeof window>"u"){p();return}o.current=window.setTimeout(()=>{o.current=null,window.requestAnimationFrame(()=>{i||p()})},g)},p=()=>{d&&sr(a);const g=a.querySelectorAll(`[data-markdown="inline-code"], a, ${Ie}`);let b=0;for(const u of Array.from(g)){const E=K(u),C=j(E,t);if(c(u),!C||b>=l)continue;b+=1,(Ze()&&Xe()&&!re(C.resolvedPath,t)?Promise.resolve(!0):lr(C.resolvedPath)).then(Ke=>{if(i||!Ke||!a.contains(u))return;const Q=K(u),H=j(Q,t);!H||H.resolvedPath!==C.resolvedPath||(u.setAttribute("data-pichamber-file-link","true"),u.setAttribute("data-pichamber-file-ref",Q),u.setAttribute("data-pichamber-file-path",H.resolvedPath),u.setAttribute("title","Open file"),u.tagName.toLowerCase()!=="a"&&(u.setAttribute("role","button"),u.setAttribute("tabindex","0")))})}},h=async g=>{const b=g.getAttribute("data-pichamber-file-ref")||K(g),u=j(b,t);if(!u)return;const E=cr(t,u.resolvedPath);re(u.resolvedPath,t)||await at(u.resolvedPath,t);const C=ve.getState();Number.isFinite(u.line??Number.NaN)?C.openContextFileAtLine(E,u.resolvedPath,Math.max(1,Math.trunc(u.line)),Number.isFinite(u.column??Number.NaN)?Math.max(1,Math.trunc(u.column)):1):C.openContextFile(E,u.resolvedPath)},v=g=>{const b=g.target;if(!(b instanceof Element))return;const u=b.closest(be);u instanceof HTMLElement&&(g.preventDefault(),g.stopPropagation(),h(u))},A=g=>{if(g.key!=="Enter"&&g.key!==" ")return;const b=g.target;!(b instanceof HTMLElement)||b.getAttribute("data-pichamber-file-link")!=="true"||(g.preventDefault(),g.stopPropagation(),h(b))};f(we);const w=new MutationObserver(()=>{f(we)});return w.observe(a,{childList:!0,subtree:!0}),a.addEventListener("click",v),a.addEventListener("keydown",A),()=>{i=!0,o.current!==null&&typeof window<"u"&&window.clearTimeout(o.current),o.current=null,w.disconnect(),a.removeEventListener("click",v),a.removeEventListener("keydown",A)}},[e,n,t,r,s])},P={download:!0,copy:!0,showPanZoomControls:!0},qe=!0,$e=({containerRef:e,onShowPopup:t,enableFullscreen:n,enablePanZoom:r,allowMermaidWheelEvents:s})=>{y.useEffect(()=>{const o=e.current;if(!o)return;const a=l=>{if(!t)return;const d=l.target;if(!(d instanceof Element)||d.closest('button, a, [role="button"]'))return;const c=d.closest(I);if(!c)return;if(c instanceof HTMLElement&&c.hasAttribute("data-mermaid-suppress-click")){c.removeAttribute("data-mermaid-suppress-click");return}const f=Array.from(o.querySelectorAll(I)).indexOf(c);if(f<0)return;const p=c instanceof HTMLElement?c.getAttribute("data-md-source"):null;if(!p||p.trim().length===0)return;const h=`Diagram ${f+1}`;t({open:!0,title:h,content:"",metadata:{tool:"mermaid-preview",filename:h},mermaid:{url:`data:text/plain;charset=utf-8,${encodeURIComponent(p)}`,source:p,filename:h}})},i=l=>{if(s||(l.ctrlKey||l.metaKey)&&r)return;const d=l.target;!(d instanceof Element)||!d.closest(I)||l.stopPropagation()};return o.addEventListener("click",a),o.addEventListener("wheel",i,{capture:!0,passive:!0}),()=>{o.removeEventListener("click",a),o.removeEventListener("wheel",i,!0)}},[s,e,n,r,t])},N=new Map,dr=100,ur=(e,t)=>{const n=N.get(e);if(n)return N.delete(e),N.set(e,n),n;const r=t();if(N.set(e,r),N.size>dr){const s=N.keys().next().value;s&&N.delete(s)}return r},mr=e=>({bg:e.colors.surface.elevated,fg:e.colors.surface.foreground,line:e.colors.interactive.border,accent:e.colors.primary.base,muted:e.colors.surface.mutedForeground,surface:e.colors.surface.muted,border:e.colors.interactive.border,transparent:!0,font:"system-ui, sans-serif"}),ze=()=>{const e=ct(),t=te(!1),n=te(!0);return e?.currentTheme??(typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?n:t)},fr=e=>{const t=e.match(/^(?:\uFEFF)?(---|\+\+\+)[^\S\r\n]*\r?\n[\s\S]*?\r?\n\1[^\S\r\n]*(?:\r?\n|$)/);return t?e.slice(t[0].length):e},He=(e,t,n,r=P)=>{const s=y.useMemo(()=>({copy:"Copy code",copied:"Copied",copyTable:"Copy table",downloadTable:"Download table",copyDiagram:"Copy source",downloadDiagram:"Download SVG",zoomInDiagram:"Zoom in",zoomOutDiagram:"Zoom out",resetDiagramView:"Reset view",previewLabel:"Preview",previewTitle:"Open preview pane"}),[]);return y.useMemo(()=>{const o=mr(e),a=e.metadata?.id??"theme";return{labels:s,mermaidControls:r,deferCodeLineNumberSync:t,renderMermaid:l=>ur(`${a}:svg:${l}`,()=>{try{return{svg:Ue(l,o)}}catch{return{}}}),onPreviewLoopback:n}},[e,s,r,t,n])},We=e=>{e.style.display="contents",e.style.width="",e.style.minWidth="",e.style.maxWidth=""},U=(e,t)=>{We(e);const n=pt(t);let r=e.querySelector(":scope > [data-md-live]");const s=r?.hasAttribute("data-md-live-pre")===!0;(!r||s!==n)&&(e.replaceChildren(),r=document.createElement(n?"div":"p"),r.setAttribute("data-md-live",""),n&&r.setAttribute("data-md-live-pre",""),r.className=n?"w-full min-w-0 whitespace-pre-wrap break-words":"w-full min-w-0 break-words",r.appendChild(document.createTextNode("")),e.appendChild(r));const o=r.firstChild;if(!(o instanceof globalThis.Text)){r.replaceChildren(document.createTextNode(t));return}if(t.startsWith(o.data)){const a=t.slice(o.data.length);a.length>0&&o.appendData(a);return}o.data=t},Be=({containerRef:e,text:t,streaming:n,cacheKey:r,syntaxVars:s,ctx:o})=>{y.useEffect(()=>{yt()},[]);const a=y.useRef(null),i=y.useRef(null),l=y.useRef(r);l.current!==r&&(l.current=r,i.current=null);const d=y.useCallback(()=>{const c=e.current;if(c){if(!a.current){if(!M(c))return;a.current=Dt(c);return}a.current.refresh()}},[e]);y.useLayoutEffect(()=>{const c=e.current,m=c?.querySelector("[data-markdown-content]")??c;if(m&&t&&m.childNodes.length===0){const f=document.createElement("div");if(f.setAttribute("data-md-block",""),f.style.display="contents",n){U(f,t),m.appendChild(f);return}f.innerHTML=dt(t),fe(f,o),m.appendChild(f),M(f)&&d()}},[e,t,n,o,d]),y.useEffect(()=>()=>{a.current?.cleanup(),a.current=null},[]),y.useEffect(()=>{const c=e.current;if(!c)return;const m=c.querySelector("[data-markdown-content]")??c;let f=!0;if(n&&i.current){const p=ut(r).update(t);if(mt(i.current,p)){const h=p[p.length-1],v=m.querySelectorAll(":scope > [data-md-block]")[p.length-1];if(h&&v){U(v,h.raw),v.setAttribute("data-md-id",`live:${p.length-1}`),i.current=i.current.map((A,w)=>w===p.length-1?{...A,raw:h.raw,id:`live:${w}`,mode:"live"}:A);return}}}return ft(t,n,r).then(p=>{if(!f)return;const h=Array.from(m.querySelectorAll(":scope > [data-md-block]"));p.forEach((w,g)=>{let b=h[g];if(b||(b=document.createElement("div"),b.setAttribute("data-md-block",""),b.style.display="contents",m.appendChild(b)),w.mode==="live"){U(b,w.raw),b.setAttribute("data-md-id",w.id);return}if(We(b),b.getAttribute("data-md-id")===w.id)return;const u=document.createElement("div");u.innerHTML=w.html,fe(u,o);const E=M(b),C=M(u);je(b,u,{childrenOnly:!0,onBeforeElUpdated:(Y,J)=>!Y.isEqualNode(J)}),b.setAttribute("data-md-id",w.id),(E||C||M(b))&&d()});const v=M(m);let A=!1;for(let w=h.length-1;w>=p.length;w-=1){const g=h[w];g&&M(g)&&(A=!0),g?.remove()}(A||h.length>p.length&&v)&&d(),i.current=p}),()=>{f=!1}},[e,t,n,r,o,d]),y.useEffect(()=>{const c=e.current;if(c)return jt(c,o)},[e,o]),y.useEffect(()=>{const c=e.current,m=c?.querySelector("[data-markdown-content]")??c;if(m)for(const[f,p]of Object.entries(s))m.style.setProperty(f,p)},[e,s]),y.useEffect(()=>{const c=e.current,m=c?.querySelector("[data-markdown-content]")??c;m&&(o.deferCodeLineNumberSync||qt(m))},[e,o.deferCodeLineNumberSync])},Ve=(e,t)=>Z("w-full min-w-0",e==="tool"?"markdown-content markdown-tool":e==="reasoning"?"markdown-content markdown-reasoning":"markdown-content leading-relaxed",t&&"markdown-streaming"),pr=({content:e,part:t,messageId:n,isAnimated:r=!0,skipFadeIn:s=!1,className:o,isStreaming:a=!1,disableStreamAnimation:i=!1,variant:l="assistant",onShowPopup:d,enableFileReferences:c=!0})=>{ee("ui.markdown_renderer.render"),a&&ee("ui.markdown_renderer.render.streaming"),Ye("ui.markdown_renderer.content_len",e.length);const m=ze(),{editor:f}=ke(),p=y.useRef(null),h=Ee()??"",v=ve(C=>C.openContextPreview),A=y.useCallback(C=>{h&&v(h,C)},[h,v]),w=a&&!i;$e({containerRef:p,onShowPopup:d,enableFullscreen:qe,enablePanZoom:P.showPanZoomControls}),De({containerRef:p,effectiveDirectory:h,editor:f,preferRuntimeEditor:!1,enabled:c&&!a}),Re({containerRef:p});const g=y.useMemo(()=>Ce(m),[m]),b=He(m,w,h?A:void 0,P),u=`markdown-${t?.id?`part-${t.id}`:`message-${n}`}`;Be({containerRef:p,text:e,streaming:w,cacheKey:u,syntaxVars:g,ctx:b});const E=_.jsx("div",{className:Z("break-words w-full min-w-0",o),ref:p,children:_.jsx("div",{className:Ve(l,w),"data-markdown-content":!0})});return r?_.jsx(lt,{skipAnimation:s,children:E},u):E},Jr=y.memo(pr,(e,t)=>e.content===t.content&&e.isStreaming===t.isStreaming&&e.disableStreamAnimation===t.disableStreamAnimation&&e.variant===t.variant&&e.isAnimated===t.isAnimated&&e.skipFadeIn===t.skipFadeIn&&e.className===t.className&&e.messageId===t.messageId&&e.onShowPopup===t.onShowPopup&&e.enableFileReferences===t.enableFileReferences&&e.part?.id===t.part?.id),hr=({content:e,className:t,variant:n="assistant",disableLinkSafety:r,stripFrontmatter:s=!1,onShowPopup:o,mermaidControls:a=P,allowMermaidWheelEvents:i=!1,enableFileReferences:l=!0})=>{const{editor:d}=ke(),c=ze(),m=y.useRef(null),f=Ee()??"",p=y.useMemo(()=>s?fr(e):e,[e,s]);$e({containerRef:m,onShowPopup:o,enableFullscreen:qe,enablePanZoom:a.showPanZoomControls,allowMermaidWheelEvents:i}),De({containerRef:m,effectiveDirectory:f,editor:d,preferRuntimeEditor:!1,enabled:l}),Re({containerRef:m,enabled:!r});const h=y.useMemo(()=>Ce(c),[c]),v=He(c,!1,void 0,a);return Be({containerRef:m,text:p,streaming:!1,cacheKey:`simple:${n}`,syntaxVars:h,ctx:v}),_.jsx("div",{className:Z("break-words w-full min-w-0",t),ref:m,children:_.jsx("div",{className:Ve(n),"data-markdown-content":!0})})},Qr=y.memo(hr,(e,t)=>{const n=e.mermaidControls??P,r=t.mermaidControls??P;return e.content===t.content&&e.variant===t.variant&&e.className===t.className&&e.disableLinkSafety===t.disableLinkSafety&&e.stripFrontmatter===t.stripFrontmatter&&e.onShowPopup===t.onShowPopup&&n.download===r.download&&n.copy===r.copy&&n.showPanZoomControls===r.showPanZoomControls&&e.allowMermaidWheelEvents===t.allowMermaidWheelEvents&&e.enableFileReferences===t.enableFileReferences});export{Jr as MarkdownRenderer,Qr as SimpleMarkdownRenderer};