@openchamber/web 1.21.0 → 1.21.1

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 (135) hide show
  1. package/bin/cli.test.js +35 -0
  2. package/bin/lib/DOCUMENTATION.md +12 -0
  3. package/bin/lib/cli-settings-accessors.js +111 -0
  4. package/bin/lib/cli-settings-accessors.test.js +189 -0
  5. package/bin/lib/cli-startup.js +29 -9
  6. package/bin/lib/commands-connect-url.js +12 -14
  7. package/dist/assets/{CodeMirrorCommentWidgets-C2BopIs3.js → CodeMirrorCommentWidgets-BGj8TJxW.js} +1 -1
  8. package/dist/assets/CommitSection-DwGiXyjf.js +1 -0
  9. package/dist/assets/{DiffView-D5cvbEPb.js → DiffView-Db6bjVv1.js} +3 -3
  10. package/dist/assets/FilesView-DQOa7Lgz.js +17 -0
  11. package/dist/assets/GitView-CHzJxTi0.js +6 -0
  12. package/dist/assets/{JsonTreeView-osju7J70.js → JsonTreeView-CggOsLot.js} +1 -1
  13. package/dist/assets/MarkdownImageGallery-DoZpaHev.js +1 -0
  14. package/dist/assets/MarkdownRendererImpl-B5Y5xCOz.js +12 -0
  15. package/dist/assets/{OnboardingScreen-w2VG4fWY.js → OnboardingScreen-C98d69Fp.js} +1 -1
  16. package/dist/assets/{PatchDiff-Dan3mADn.js → PatchDiff-DJYMUiXA.js} +1 -1
  17. package/dist/assets/{PierreDiffViewer-CGoI2v0q.js → PierreDiffViewer-CY2bx_SB.js} +3 -3
  18. package/dist/assets/PlanView-PkiOY_9H.js +5 -0
  19. package/dist/assets/SettingsView-D-K3ELCM.js +28 -0
  20. package/dist/assets/{SettingsWindow-DXF-MTHG.js → SettingsWindow-oyOm2fHR.js} +1 -1
  21. package/dist/assets/{ToolOutputDialog-DrCa1JRk.js → ToolOutputDialog-lKyeQTPL.js} +6 -6
  22. package/dist/assets/{ToolPartDiffPreview-B_tfvlNF.js → ToolPartDiffPreview-C7kBQNAA.js} +2 -2
  23. package/dist/assets/{VirtualizedFileDiff-CN_BctrR.js → VirtualizedFileDiff-BP7ebDFF.js} +1 -1
  24. package/dist/assets/{WalkthroughView-D9Q4lr5x.js → WalkthroughView-MuJodAHD.js} +2 -2
  25. package/dist/assets/{computeVirtualFileMetrics-Gi1d5eU1.js → computeVirtualFileMetrics-CZ0xPeaT.js} +1 -1
  26. package/dist/assets/{contextPanelEmbeddedChat-CpzVNWAv.js → contextPanelEmbeddedChat-C9abMBTb.js} +1 -1
  27. package/dist/assets/de-CEoCz3j6.js +9 -0
  28. package/dist/assets/es-DwyXCqaL.js +15 -0
  29. package/dist/assets/{fr-5qJM0nFS.js → fr-CS7Csln9.js} +5 -5
  30. package/dist/assets/index-CUKcHnUA.css +1 -0
  31. package/dist/assets/{index-Brm3X9rs.js → index-CaPAjwXQ.js} +1 -1
  32. package/dist/assets/index-DIvDEKE-.js +7 -0
  33. package/dist/assets/{isDiffPlainText-pH9kAJQH.js → isDiffPlainText-ZBvDxhVB.js} +1 -1
  34. package/dist/assets/{isFilePlainText-CVKy_dgB.js → isFilePlainText-DiLRrkJr.js} +1 -1
  35. package/dist/assets/ja-vnwqLcx6.js +15 -0
  36. package/dist/assets/ko-CXuSfZv5.js +15 -0
  37. package/dist/assets/{main-vUCh0VB0.js → main-D5RWr6sJ.js} +2 -2
  38. package/dist/assets/main-DLlfDjQ_.js +926 -0
  39. package/dist/assets/{markdown-shiki.worker-CKGJ1J33.js → markdown-shiki.worker-D5fBU-lw.js} +5 -5
  40. package/dist/assets/markdownCore-CcTcLsQF.js +3 -0
  41. package/dist/assets/{miniChat-BlzGEYgE.js → miniChat-CqR3icsk.js} +2 -2
  42. package/dist/assets/{mobile-CkX6H-IT.js → mobile-RN_UTTlB.js} +2 -2
  43. package/dist/assets/{patchFileDiff-BCTsE43U.js → patchFileDiff-CjRR5ESs.js} +3 -3
  44. package/dist/assets/pl-BJxry0Mi.js +15 -0
  45. package/dist/assets/pt-BR-DxLmkhdv.js +15 -0
  46. package/dist/assets/{renderElectronMiniChatApp-CJYe_KOL.js → renderElectronMiniChatApp-1wC94fQK.js} +2 -2
  47. package/dist/assets/renderMobileApp-ltva2Plg.js +25 -0
  48. package/dist/assets/runtimeEndpointReset-D6SmNZaP.js +15 -0
  49. package/dist/assets/{scheduledTasksApi-CAGPh_gZ.js → scheduledTasksApi-mjMDet_H.js} +1 -1
  50. package/dist/assets/{shikiHighlight-BgTPSITe.js → shikiHighlight-fGmFkxAM.js} +1 -1
  51. package/dist/assets/tr-5Mk_hQ2Q.js +6 -0
  52. package/dist/assets/uk-ClgQjmlw.js +15 -0
  53. package/dist/assets/{useAppFontEffects-Cll4gnsh.js → useAppFontEffects-KP8_yiGW.js} +143 -141
  54. package/dist/assets/{useInlineCommentController-DFFv0hae.js → useInlineCommentController-HIjtuhxD.js} +2 -2
  55. package/dist/assets/useRootScrollLock-BSiQ5F75.js +1 -0
  56. package/dist/assets/{vendor-base-ui-_6j2xOWl.js → vendor-base-ui-BeMD8X_w.js} +1 -1
  57. package/dist/assets/{vendor-codemirror-language-data-DkQX2EBa.js → vendor-codemirror-language-data-DrTPkHl4.js} +2 -2
  58. package/dist/assets/{vendor-floating-ui-core-CXmKXOXc.js → vendor-floating-ui-core-PuGzNPnN.js} +1 -1
  59. package/dist/assets/{vendor-floating-ui-dom-WyXykhNi.js → vendor-floating-ui-dom-BTvzWks8.js} +1 -1
  60. package/dist/assets/{vendor-floating-ui-react-dom-DKpLs02S.js → vendor-floating-ui-react-dom-DxYCWdHj.js} +1 -1
  61. package/dist/assets/{vendor-floating-ui-utils-BzXdqYpP.js → vendor-floating-ui-utils-D6FqdtJt.js} +1 -1
  62. package/dist/assets/vendor-linkify-it-DZCzzDkK.js +1 -0
  63. package/dist/assets/vendor-marked-linkify-it-CXI_LHIE.js +1 -0
  64. package/dist/assets/vendor-uc.micro-BAd0H0z4.js +1 -0
  65. package/dist/assets/{web-components-DLnGY4fs.js → web-components-DOXvU-tB.js} +1 -1
  66. package/dist/assets/zh-CN-Ba6y8H-i.js +15 -0
  67. package/dist/assets/zh-TW-Dv8yyhN1.js +15 -0
  68. package/dist/index.html +5 -5
  69. package/dist/mini-chat.html +3 -3
  70. package/dist/mobile.html +3 -3
  71. package/dist/site.webmanifest +1 -1
  72. package/dist/sw.js +1 -1
  73. package/package.json +2 -2
  74. package/public/site.webmanifest +1 -1
  75. package/server/index.js +2 -2
  76. package/server/lib/cloudflare-tunnel.js +1 -1
  77. package/server/lib/fs/DOCUMENTATION.md +1 -0
  78. package/server/lib/fs/routes.js +21 -0
  79. package/server/lib/fs/routes.test.js +89 -3
  80. package/server/lib/git/DOCUMENTATION.md +4 -3
  81. package/server/lib/git/service.js +128 -6
  82. package/server/lib/git/service.test.js +191 -1
  83. package/server/lib/markdown-image-grants/DOCUMENTATION.md +4 -0
  84. package/server/lib/markdown-image-grants/routes.js +3 -1
  85. package/server/lib/markdown-image-grants/routes.test.js +14 -0
  86. package/server/lib/openchamber-sessions/routes.js +4 -1
  87. package/server/lib/openchamber-sessions/routes.test.js +23 -0
  88. package/server/lib/opencode/env-runtime.js +17 -1
  89. package/server/lib/opencode/env-runtime.test.js +56 -0
  90. package/server/lib/opencode/lifecycle.js +48 -9
  91. package/server/lib/opencode/lifecycle.test.js +125 -1
  92. package/server/lib/opencode/managed-process-registry.d.ts +13 -0
  93. package/server/lib/opencode/managed-process-registry.js +213 -163
  94. package/server/lib/opencode/managed-process-registry.test.mjs +285 -0
  95. package/server/lib/opencode/project-directory-runtime.js +16 -11
  96. package/server/lib/opencode/project-directory-runtime.test.js +32 -12
  97. package/server/lib/opencode/pwa-manifest-routes.js +1 -1
  98. package/server/lib/opencode/routes-upgrade.test.js +96 -12
  99. package/server/lib/opencode/routes.js +53 -5
  100. package/server/lib/opencode/settings-helpers.js +3 -0
  101. package/server/lib/opencode/settings-helpers.test.js +10 -0
  102. package/server/lib/opencode/theme-runtime.js +1 -1
  103. package/server/lib/opencode/theme-runtime.test.js +129 -0
  104. package/server/lib/quota/DOCUMENTATION.md +19 -0
  105. package/server/lib/quota/providers/copilot.js +26 -10
  106. package/server/lib/quota/providers/copilot.test.js +78 -0
  107. package/server/lib/small-model/DOCUMENTATION.md +11 -5
  108. package/server/lib/small-model/call.js +64 -20
  109. package/server/lib/small-model/call.test.js +184 -2
  110. package/server/lib/tunnels/install-help.js +2 -2
  111. package/server/lib/tunnels/install-help.test.js +9 -0
  112. package/server/lib/walkthrough/languages.js +1 -0
  113. package/dist/assets/CommitSection-HJeMUAWb.js +0 -1
  114. package/dist/assets/FilesView-DPU8aNPL.js +0 -17
  115. package/dist/assets/GitView-Ct6xWrVH.js +0 -6
  116. package/dist/assets/MarkdownImageGallery-EujHSZ2M.js +0 -1
  117. package/dist/assets/MarkdownRendererImpl-CPzu4kIr.js +0 -12
  118. package/dist/assets/PlanView-Dgg-WTEc.js +0 -4
  119. package/dist/assets/SessionSwitcherDropdown-CJTrc8K7.js +0 -1
  120. package/dist/assets/SettingsView-D9yRuFZw.js +0 -28
  121. package/dist/assets/de-B_LdJwEM.js +0 -9
  122. package/dist/assets/es-CubfsAYV.js +0 -15
  123. package/dist/assets/index-BW82eK5v.css +0 -1
  124. package/dist/assets/index-rlLjZUM5.js +0 -7
  125. package/dist/assets/ja-DJYIBUlH.js +0 -15
  126. package/dist/assets/ko-DcUBkB7y.js +0 -15
  127. package/dist/assets/main-DLBxKIoX.js +0 -926
  128. package/dist/assets/markdownCore-DG6GHLF4.js +0 -3
  129. package/dist/assets/pl-rB6BLcio.js +0 -15
  130. package/dist/assets/pt-BR-DcwtlO-o.js +0 -15
  131. package/dist/assets/renderMobileApp-hQJTnr8B.js +0 -25
  132. package/dist/assets/runtimeEndpointReset-BDh7r8BL.js +0 -15
  133. package/dist/assets/uk-INZlFD9A.js +0 -15
  134. package/dist/assets/zh-CN-Dzda8xa1.js +0 -15
  135. package/dist/assets/zh-TW-Cwn3rNYZ.js +0 -15
@@ -0,0 +1,6 @@
1
+ import{R as l,r as be,j as t,f as Ct}from"./vendor-react-BUCujlKS.js";import{f as et,y as Xe,a0 as Rt,hK as Pn,cS as Jt,cd as Kt,t as b,I as T,b2 as Ps,a$ as Fs,cQ as br,b1 as Rs,cw as Bs,cx as Ds,cy as Ms,cz as Ts,cr as qt,cs as Yt,B as W,hL as Fn,hM as Rn,bE as ht,bF as gt,bG as ft,bH as pt,bI as yt,S as ir,a6 as Qt,a7 as Zt,a8 as Xt,hN as Bn,h as Ve,hO as Dn,hP as Mn,hQ as Tn,hR as En,a_ as Ln,al as An,bP as On,hS as zn,hT as Gn,hU as _n,hV as $n,hW as Hn,hX as Wn,hY as Un,c0 as vr,bS as Jn,bT as Kn,bU as qn,bV as Yn,bW as Qn,hZ as Zn,bZ as Xn,bJ as Is,eJ as ea,V as ta,ab as sa,ad as ra,ac as na,bu as aa,h_ as ia,b_ as oa,h$ as la,i0 as ca,ae as da,i1 as ua,af as ma,bN as ha,hD as ga,l as fa,b$ as pa,g as xa,cB as wa,ak as ya,a1 as ba,i2 as va,i3 as Ss}from"./useAppFontEffects-KP8_yiGW.js";import{a as ja,b as Ca,d as Na}from"./main-DLlfDjQ_.js";import{v as Sa,s as ka,q as Va,R as Ia,_ as Pa}from"./runtimeEndpointReset-D6SmNZaP.js";import{u as or}from"./vendor-zustand-BAGL70zf.js";import{r as Fa,u as Pt}from"./index-DIvDEKE-.js";import{C as Ra,a as Ba}from"./CommitSection-DwGiXyjf.js";import{P as Da}from"./PierreDiffViewer-CY2bx_SB.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-base-ui-BeMD8X_w.js";import"./vendor-floating-ui-utils-D6FqdtJt.js";import"./vendor-floating-ui-react-dom-DxYCWdHj.js";import"./vendor-floating-ui-dom-BTvzWks8.js";import"./vendor-floating-ui-core-PuGzNPnN.js";import"./vendor-use-sync-external-store-D6wYuSt-.js";import"./contextPanelEmbeddedChat-C9abMBTb.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-dnd-kit-core-BZknOX2w.js";import"./vendor-dnd-kit-utilities-B_MdXhJC.js";import"./vendor-dnd-kit-accessibility-BHxJPORy.js";import"./vendor-dnd-kit-sortable-CsEagZ81.js";import"./vendor-framer-motion-livSKyyV.js";import"./vendor-motion-dom-D_o3BTI3.js";import"./vendor-motion-utils-BGh8QBgx.js";import"./vendor-tanstack-react-virtual-g05Cx3z9.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-sonner-DFyL3AvE.js";import"./vendor-cmdk-DgLInKvT.js";import"./vendor-radix-ui-react-dialog-B94Bt2qq.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-DcAh5WdT.js";import"./vendor-radix-ui-react-context-Czxm7Z62.js";import"./vendor-radix-ui-react-id-f5BLKEVw.js";import"./vendor-radix-ui-react-use-layout-effect-D_3IhJdJ.js";import"./vendor-radix-ui-react-use-controllable-state-BFT5YmkA.js";import"./vendor-radix-ui-react-dismissable-layer-D7kXcwgJ.js";import"./vendor-radix-ui-react-primitive-DhVoX9SD.js";import"./vendor-radix-ui-react-slot-BQgQOasS.js";import"./vendor-radix-ui-react-use-callback-ref-BZPnuXAC.js";import"./vendor-radix-ui-react-use-escape-keydown-oph88g-F.js";import"./vendor-radix-ui-react-focus-scope-CiaxW4dD.js";import"./vendor-radix-ui-react-portal-BMJYHWck.js";import"./vendor-radix-ui-react-presence-CNxf-uq4.js";import"./vendor-radix-ui-react-focus-guards-B6qJXYua.js";import"./vendor-react-remove-scroll-DO7dCTnK.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-BcFYyj3E.js";import"./vendor-react-style-singleton-q6EMHnwf.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-zDC0RhA3.js";import"./vendor-use-callback-ref-D3RC8gqK.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BgPj_McA.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-codemirror-state-C9awkmn-.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-codemirror-view-CiLROUVV.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-Cc2ZYbgX.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-DzPz9Wgq.js";import"./vendor-codemirror-lang-json-CMBS2tG9.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-O0cZX78y.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-CfgK872x.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-BPGOH9ye.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-DrTPkHl4.js";import"./vendor-codemirror-lang-python-HahnQaAS.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-B7H_j0iU.js";import"./vendor-legendapp-list-gg7YLRW7.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-zod-BLfBSgBh.js";import"./useRootScrollLock-BSiQ5F75.js";import"./scheduledTasksApi-mjMDet_H.js";import"./vendor-cron-parser-CUcP7OfX.js";import"./vendor-luxon-BZ0puJYg.js";import"./vendor-opencode-sdk-BJ73u-bH.js";import"./web-components-DOXvU-tB.js";import"./computeVirtualFileMetrics-CZ0xPeaT.js";import"./vendor-shiki-Bbf2GEcE.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";import"./vendor-shikijs-engine-oniguruma-DPWuIF1G.js";import"./themeResolver-BmJyTmjJ.js";import"./vendor-pierre-theming-C6Z4M5_u.js";import"./vendor-shikijs-engine-javascript-Cme4830A.js";import"./vendor-oniguruma-to-es-DLBnFDCE.js";import"./vendor-oniguruma-parser-C0D4_9rT.js";import"./vendor-regex-BBWcyTkg.js";import"./vendor-regex-utilities-2BQyy0xI.js";import"./vendor-regex-recursion-JU4mF-dD.js";import"./vendor-shikijs-transformers-CZWsLLKm.js";import"./VirtualizedFileDiff-BP7ebDFF.js";import"./isDiffPlainText-ZBvDxhVB.js";import"./vendor-diff-C3JhlQdm.js";import"./Virtualizer-D_a8gKmg.js";import"./useInlineCommentController-HIjtuhxD.js";import"./appThemeRegistry-BK0dHKa6.js";import"./registerCustomTheme-BBXUCRnG.js";const jr="gitmojiCache",Ma=1e3*60*60*24*7,Cr="1",Ta="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",Nr=i=>{if(!i||typeof i!="object")return!1;const e=i;return typeof e.emoji=="string"&&typeof e.code=="string"&&typeof e.description=="string"},ks=()=>{if(typeof window>"u")return null;try{const i=window.localStorage.getItem(jr);if(!i)return null;const e=JSON.parse(i);return!e||e.version!==Cr||typeof e.fetchedAt!="number"||!Array.isArray(e.gitmojis)?null:{gitmojis:e.gitmojis.filter(Nr),fetchedAt:e.fetchedAt,version:e.version}}catch{return null}},Ea=i=>{if(!(typeof window>"u"))try{const e={gitmojis:i,fetchedAt:Date.now(),version:Cr};window.localStorage.setItem(jr,JSON.stringify(e))}catch{return}},lr=i=>Date.now()-i.fetchedAt<Ma;let Wt=null;const Ft=new Set,cr=async()=>{if(Wt)return Wt;const i=(async()=>{try{const e=await fetch(Ta);if(!e.ok)throw new Error(`Failed to load gitmojis: ${e.statusText}`);const n=await e.json(),r=Array.isArray(n.gitmojis)?n.gitmojis.filter(Nr):[];return Ea(r),Ft.forEach(v=>v(r)),r}catch(e){console.warn("Failed to load gitmoji list:",e);const n=[];return Ft.forEach(r=>r(n)),n}finally{Wt=null}})();return Wt=i,i},La=i=>{const[e,n]=l.useState(()=>i?ks()?.gitmojis??[]:[]),[r,v]=l.useState(!1),h=l.useRef(i);h.current=i,l.useEffect(()=>{if(!i){Ft.delete(n),n([]),v(!1);return}const f=ks();if(f&&(n(f.gitmojis),lr(f)))return;Ft.add(n),v(!0);let m=!1;return cr().finally(()=>{!m&&h.current&&v(!1)}),()=>{m=!0,Ft.delete(n)}},[i]);const p=l.useCallback(async()=>{if(!h.current)return[];if(e.length>0)return e;const f=ks();return f&&lr(f)?f.gitmojis:cr()},[e]);return{gitmojis:e,isLoading:r,ensureLoaded:p}},Nt=async(i,e)=>{const n=await Fa(`/api/git/integrate/${i}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok){const r=await n.json().catch(()=>null);throw new Error(r?.error||`Git integrate request failed: ${n.statusText}`)}return n.json()};async function It(i){return Nt("plan",i)}async function Aa(i){return Nt("conflict-details",{tempWorktreePath:i})}async function Oa(i){return(await Nt("cherry-pick-status",{tempWorktreePath:i})).inProgress}async function za(i){return Nt("run",{plan:i})}async function Ga(i){await Nt("abort",{state:i})}async function _a(i){return Nt("continue",{state:i})}const $a=({repoRoot:i,sourceBranch:e,worktreeMetadata:n,localBranches:r,defaultTargetBranch:v,refreshKey:h,onRefresh:p,showHeader:f=!0})=>{const{t:m}=et(),x=Xe(u=>u.currentSessionId),[M,y]=be.useState(!1),[k,L]=be.useState(""),N=be.useRef(null),O=be.useMemo(()=>Rt(r,k,u=>[u]),[r,k]),[j,w]=be.useState(v);be.useEffect(()=>{w(v)},[v]),be.useEffect(()=>{if(M){const u=setTimeout(()=>{N.current?.focus()},0);return()=>clearTimeout(u)}},[M]);const B=!!(i&&e&&j&&j!=="HEAD"&&e!==j),[S,R]=be.useState({kind:"idle"}),[I,P]=be.useState(!1),[g,H]=be.useState([]),E=be.useMemo(()=>x?`openchamber.integrate.conflict:${x}`:null,[x]);be.useEffect(()=>{if(!E||typeof window>"u")return;const u=window.localStorage.getItem(E);if(!u)return;let d=!1;try{const F=JSON.parse(u);if(!F?.tempWorktreePath||F.repoRoot!==i){window.localStorage.removeItem(E);return}(async()=>{const A=await Oa(F.tempWorktreePath).catch(()=>!1);if(d)return;if(!A){window.localStorage.removeItem(E);return}const q=await Aa(F.tempWorktreePath).catch(()=>null);d||q&&R({kind:"conflict",state:F,details:q})})()}catch{window.localStorage.removeItem(E)}return()=>{d=!0}},[E,i]),be.useEffect(()=>{if(!B){R({kind:"idle"});return}let u=!1;return R({kind:"loading"}),(async()=>{try{const d=await It({repoRoot:i,sourceBranch:e,targetBranch:j});if(u)return;if(R({kind:"ready",plan:d}),d.commits.length>0){const A=d.commits.slice(-50).reverse(),q=await Pn(i,A);u||(H(q),P(!1))}else u||(H([]),P(!1))}catch{u||R({kind:"idle"})}})(),()=>{u=!0}},[B,i,e,j,h]);const V=be.useCallback(u=>{x&&Xe.getState().setWorktreeMetadata(x,{...n,createdFromBranch:u})},[x,n]),D=Xe(u=>u.openNewSessionDraft),U=be.useCallback(async u=>{const d=await Jt("git.integrate.cherrypick.resolve.visible",{current_commit:u.state.currentCommit,target_branch:u.state.targetBranch}),F=await Jt("git.integrate.cherrypick.resolve.instructions",{repo_root:u.state.repoRoot,temp_worktree_path:u.state.tempWorktreePath,source_branch:u.state.sourceBranch,target_branch:u.state.targetBranch,current_commit:u.state.currentCommit}),A=`Cherry-pick conflict context (JSON)
2
+ ${JSON.stringify({repoRoot:u.state.repoRoot,tempWorktreePath:u.state.tempWorktreePath,sourceBranch:u.state.sourceBranch,targetBranch:u.state.targetBranch,currentCommit:u.state.currentCommit,remainingCommits:u.state.remainingCommits,statusPorcelain:u.details.statusPorcelain,unmergedFiles:u.details.unmergedFiles,currentPatchMeta:u.details.currentPatchMeta,currentPatch:u.details.currentPatch,diff:u.details.diff},null,2)}`;return{visibleText:d,instructionsText:F,payloadText:A}},[]),$=Kt(u=>u.setPendingInputText),_=Kt(u=>u.setPendingSyntheticParts),Y=be.useCallback(async(u,d)=>{const F=await U(u);if(d){D({directoryOverride:u.state.tempWorktreePath,initialPrompt:F.visibleText,syntheticParts:[{text:F.instructionsText,synthetic:!0},{text:F.payloadText,synthetic:!0}]});return}if(!x){b.error(m("gitView.integrate.noActiveSession"),{description:m("gitView.integrate.noActiveSessionDescription")});return}$(F.visibleText,"replace"),_([{text:F.instructionsText,synthetic:!0},{text:F.payloadText,synthetic:!0}])},[x,U,D,$,_,m]),ee=be.useCallback(async()=>{if(S.kind==="ready"){if(S.plan.commits.length===0){b.message(m("gitView.integrate.noCommitsToMoveToast"));return}R({kind:"running",plan:S.plan});try{const u=await za(S.plan);if(u.kind==="success"){b.success(m("gitView.integrate.commitsMovedToast"),{description:u.moved===1?m("gitView.integrate.commitsMovedDescriptionSingle",{count:u.moved,branch:S.plan.targetBranch}):m("gitView.integrate.commitsMovedDescriptionPlural",{count:u.moved,branch:S.plan.targetBranch})});const d=await It(S.plan);R({kind:"ready",plan:d}),p?.();return}u.kind==="conflict"&&(b.error(m("gitView.integrate.cherryPickConflictToast"),{description:m("gitView.integrate.cherryPickConflictDescription")}),R({kind:"conflict",state:u.state,details:u.details}),E&&typeof window<"u"&&window.localStorage.setItem(E,JSON.stringify(u.state)))}catch(u){const d=u instanceof Error?u.message:String(u);b.error(m("gitView.integrate.failedToMoveToast"),{description:d});const F=await It({repoRoot:i,sourceBranch:e,targetBranch:j}).catch(()=>null);R(F?{kind:"ready",plan:F}:{kind:"idle"})}}},[S,p,i,e,j,E,m]),X=be.useCallback(async()=>{if(S.kind==="conflict")try{await Ga(S.state),b.message(m("gitView.integrate.cherryPickAbortedToast")),E&&typeof window<"u"&&window.localStorage.removeItem(E)}finally{const u=await It({repoRoot:i,sourceBranch:e,targetBranch:j}).catch(()=>null);R(u?{kind:"ready",plan:u}:{kind:"idle"})}},[S,i,e,j,E,m]),oe=be.useCallback(async()=>{if(S.kind==="conflict")try{const u=await _a(S.state);if(u.kind==="success"){b.success(m("gitView.integrate.cherryPickFinishedToast"));const d=await It({repoRoot:i,sourceBranch:e,targetBranch:j}).catch(()=>null);R(d?{kind:"ready",plan:d}:{kind:"idle"}),E&&typeof window<"u"&&window.localStorage.removeItem(E),p?.();return}u.kind==="conflict"&&(R({kind:"conflict",state:u.state,details:u.details}),E&&typeof window<"u"&&window.localStorage.setItem(E,JSON.stringify(u.state)))}catch(u){const d=u instanceof Error?u.message:String(u);b.error(m("gitView.integrate.cherryPickContinueFailedToast"),{description:d})}},[S,i,e,j,p,E,m]);return!i||!e?null:t.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[f?t.jsxs("div",{className:"px-0 py-3 border-b border-border/40 flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx(T,{name:"split-cells-horizontal",className:"size-4 text-muted-foreground"}),t.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:m("gitView.integrate.title")}),S.kind==="ready"&&S.plan.commits.length>0?t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:m("gitView.integrate.toMoveCount",{count:S.plan.commits.length})}):null]}),t.jsx("div",{className:"flex items-center gap-2",children:S.kind==="loading"||S.kind==="running"?t.jsx(T,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}):null})]}):null,t.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"typography-ui-label text-foreground",children:m("gitView.integrate.moveCommits")}),t.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[e," → ",j]})]}),t.jsx("div",{className:"flex-1"}),t.jsxs(Ps,{open:M,onOpenChange:y,children:[t.jsx(Fs,{asChild:!0,children:t.jsxs("button",{type:"button",className:br({size:"default"}),children:[m("gitView.integrate.target"),t.jsx("span",{className:"max-w-[160px] truncate font-mono text-xs text-muted-foreground",children:j}),t.jsx(T,{name:"arrow-down-s",className:"size-4 opacity-60"})]})}),t.jsx(Rs,{align:"end",className:"w-72 p-0 max-h-[var(--available-height)] flex flex-col overflow-hidden",children:t.jsxs(Bs,{className:"h-full min-h-0",shouldFilter:!1,children:[t.jsx(Ds,{ref:N,placeholder:m("gitView.branch.searchPlaceholder"),value:k,onValueChange:L,onKeyDown:u=>u.stopPropagation()}),t.jsxs(Ms,{className:"h-full min-h-0",scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[t.jsx(Ts,{children:m("gitView.branch.empty")}),t.jsx(qt,{heading:m("gitView.branch.localBranches"),children:O.map(u=>t.jsx(Yt,{value:u,onSelect:()=>{w(u),V(u),y(!1),L("")},children:u},u))})]})]})})]}),S.kind==="ready"?t.jsx(W,{size:"sm",onClick:()=>{ee()},disabled:!B||S.plan.commits.length===0,children:m("gitView.integrate.move")}):S.kind==="loading"?t.jsx(W,{size:"sm",variant:"outline",disabled:!0,children:m("gitView.integrate.checking")}):S.kind==="running"?t.jsx(W,{size:"sm",variant:"outline",disabled:!0,children:m("gitView.integrate.moving")}):null]}),S.kind==="ready"&&S.plan.commits.length===0&&t.jsx("div",{className:"typography-meta text-muted-foreground",children:m("gitView.integrate.noCommitsToMove")}),S.kind==="ready"&&S.plan.commits.length>0&&t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"typography-meta text-foreground",children:[m("gitView.integrate.commitsToMove"),t.jsxs("span",{className:"text-muted-foreground",children:[" (",S.plan.commits.length,")"]})]}),g.length>0&&S.plan.commits.length>5&&t.jsx("button",{type:"button",onClick:()=>P(u=>!u),className:"typography-micro text-muted-foreground hover:text-foreground",children:m(I?"gitView.integrate.showLess":"gitView.integrate.showAll")})]}),t.jsxs("div",{className:"space-y-1",children:[(I?g:g.slice(0,5)).map(u=>t.jsxs("div",{className:"flex items-baseline gap-2 min-w-0",children:[t.jsx("span",{className:"font-mono text-xs text-muted-foreground flex-shrink-0",children:u.short}),t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:u.subject||u.sha})]},u.sha)),g.length===0&&t.jsx("div",{className:"typography-meta text-muted-foreground",children:m("gitView.integrate.previewUnavailable")}),S.plan.commits.length>g.length&&t.jsx("div",{className:"typography-micro text-muted-foreground/70",children:m("gitView.integrate.showingFirstCommits",{count:g.length})})]})]}),S.kind==="conflict"&&t.jsxs("div",{className:"rounded-md border border-border/60 bg-background/60 p-3 space-y-2",children:[t.jsx("div",{className:"typography-meta text-foreground",children:m("gitView.integrate.conflictsInFiles",{count:S.details.unmergedFiles.length})}),t.jsxs("div",{className:"typography-micro text-muted-foreground/80",children:[m("gitView.integrate.currentCommit"),": ",t.jsx("span",{className:"font-mono",children:S.state.currentCommit.slice(0,7)})]}),t.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[S.details.unmergedFiles.slice(0,6).map(u=>t.jsx("span",{className:"font-mono text-xs px-2 py-0.5 rounded bg-muted/40 text-muted-foreground",children:u},u)),S.details.unmergedFiles.length>6&&t.jsx("span",{className:"text-xs text-muted-foreground",children:m("gitView.integrate.moreFiles",{count:S.details.unmergedFiles.length-6})})]}),t.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[t.jsx(W,{size:"sm",variant:"ghost",className:"typography-meta",onClick:()=>{X()},children:m("gitView.operation.abort")}),t.jsxs(W,{size:"sm",variant:"secondary",className:"typography-meta gap-1",disabled:!x,onClick:()=>{Y({state:S.state,details:S.details},!1)},children:[t.jsx(T,{name:"sparkling",className:"size-3.5"}),m("gitView.integrate.currentSession")]}),t.jsxs(W,{size:"sm",variant:"secondary",className:"typography-meta gap-1",onClick:()=>{Y({state:S.state,details:S.details},!0)},children:[t.jsx(T,{name:"sparkling",className:"size-3.5"}),m("gitView.integrate.newSession")]}),t.jsx(W,{size:"sm",className:"typography-meta",onClick:()=>{oe()},children:m("gitView.operation.continue")})]})]})]})]})},Ha=({open:i,onOpenChange:e,directory:n,hasUncommittedChanges:r,hasStagedChanges:v=!1,uncommittedFileCount:h,onChanged:p})=>{const{t:f}=et(),[m,x]=l.useState([]),[M,y]=l.useState(!1),[k,L]=l.useState(""),[N,O]=l.useState(""),[j,w]=l.useState(null),[B,S]=l.useState({}),R=l.useCallback(async()=>{if(n){y(!0);try{const V=await Fn(n);x(V.stashes),S({})}catch(V){b.error(V instanceof Error?V.message:f("gitView.stashes.toast.loadFailed"))}finally{y(!1)}}},[n,f]);l.useEffect(()=>{i&&R()},[R,i]),l.useEffect(()=>{if(!i||!n||m.length===0)return;let V=!1;const D=m.map(U=>U.ref);return Rn(n,D).then(U=>{V||S(U.counts)}).catch(()=>{}),()=>{V=!0}},[n,i,m]);const I=l.useMemo(()=>Rt(m,k,V=>[V.message,V.ref,V.relativeTime]),[k,m]),P=l.useCallback(async V=>{await R(),await p?.(V)},[R,p]),g=async()=>{if(!(!n||j)){w("create");try{const V=await Bn(n,{message:N.trim()||void 0});V.created?(b.success(f("gitView.stashes.toast.created")),O("")):b.info(f("gitView.stashes.toast.noChanges")),await P({affectsIndex:!!(V.created&&v)})}catch(V){b.error(V instanceof Error?V.message:f("gitView.stashes.toast.createFailed"))}finally{w(null)}}},H=async(V,D)=>{if(!(!n||j)&&!(D==="drop"&&!window.confirm(f("gitView.stashes.confirm.drop",{ref:V.ref})))){w(`${D}:${V.ref}`);try{D==="apply"&&await Dn(n,{ref:V.ref}),D==="pop"&&await Mn(n,{ref:V.ref}),D==="drop"&&await Tn(n,{ref:V.ref});const U=D==="apply"?"gitView.stashes.toast.applySuccess":D==="pop"?"gitView.stashes.toast.popSuccess":"gitView.stashes.toast.dropSuccess";b.success(f(U)),await P({affectsIndex:D!=="drop"})}catch(U){const $=D==="apply"?"gitView.stashes.toast.applyFailed":D==="pop"?"gitView.stashes.toast.popFailed":"gitView.stashes.toast.dropFailed";b.error(U instanceof Error?U.message:f($)),await P({affectsIndex:D!=="drop"})}finally{w(null)}}},E=j!==null;return t.jsx(ht,{open:i,onOpenChange:e,children:t.jsxs(gt,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[t.jsxs(ft,{children:[t.jsxs(pt,{className:"flex items-center gap-2",children:[t.jsx(T,{name:"archive-stack",className:"h-5 w-5"}),f("gitView.stashes.title")]}),t.jsx(yt,{children:f("gitView.stashes.description")})]}),t.jsxs("div",{className:"mt-2 rounded-lg border border-border/60 bg-[var(--surface-elevated)] p-3",children:[t.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[t.jsx(ir,{value:N,onChange:V=>O(V.target.value),placeholder:f("gitView.stashes.messagePlaceholder"),disabled:E||!r,className:"flex-1"}),t.jsxs(W,{onClick:g,disabled:!r||E||!n,children:[j==="create"?t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(T,{name:"inbox-archive",className:"size-4"}),f("gitView.stashes.actions.stashCurrentWithCount",{count:h})]})]}),t.jsx("p",{className:"typography-meta mt-2 text-muted-foreground",children:f("gitView.stashes.includeUntrackedHint")})]}),t.jsxs("div",{className:"relative mt-2",children:[t.jsx(T,{name:"search",className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx(ir,{value:k,onChange:V=>L(V.target.value),placeholder:f("gitView.stashes.searchPlaceholder"),className:"pl-9"})]}),t.jsx("div",{className:"flex-1 overflow-y-auto",children:M?t.jsx("div",{className:"flex items-center justify-center py-10 text-muted-foreground",children:t.jsx(T,{name:"loader-4",className:"size-5 animate-spin"})}):I.length===0?t.jsx("div",{className:"py-8 text-center text-muted-foreground",children:f(k?"gitView.stashes.empty.search":"gitView.stashes.empty.list")}):I.map((V,D)=>t.jsxs("div",{className:"group flex items-center gap-2 rounded py-1.5 transition-colors hover:bg-interactive-hover/30",children:[t.jsxs("div",{className:"min-w-0 flex-1 pl-2",children:[t.jsx("p",{className:"typography-small truncate text-foreground",children:V.message||f("gitView.stashes.untitled")}),t.jsxs("p",{className:"typography-meta truncate text-muted-foreground",children:[t.jsxs(Qt,{children:[t.jsx(Zt,{asChild:!0,children:t.jsx("span",{children:D===0&&!k.trim()?f("gitView.stashes.latestLabel"):f("gitView.stashes.itemNumber",{number:D+1})})}),t.jsx(Xt,{sideOffset:6,children:V.ref})]})," · ",V.relativeTime," · ",typeof B[V.ref]=="number"?f("gitView.stashes.fileCount",{count:B[V.ref]}):f("gitView.stashes.fileCountLoading")]})]}),t.jsxs("div",{className:"mr-2 flex shrink-0 items-center gap-1 opacity-100 sm:opacity-0 sm:group-hover:opacity-100",children:[t.jsx(Vs,{label:f("gitView.stashes.actions.apply"),loading:j===`apply:${V.ref}`,onClick:()=>H(V,"apply"),disabled:E,children:t.jsx(T,{name:"inbox-unarchive",className:"size-4"})}),t.jsx(Vs,{label:f("gitView.stashes.actions.pop"),loading:j===`pop:${V.ref}`,onClick:()=>H(V,"pop"),disabled:E,children:t.jsx(T,{name:"inbox-unarchive-fill",className:"size-4"})}),t.jsx(Vs,{label:f("gitView.stashes.actions.drop"),loading:j===`drop:${V.ref}`,onClick:()=>H(V,"drop"),disabled:E,destructive:!0,children:t.jsx(T,{name:"delete-bin",className:"size-4"})})]})]},V.ref))})]})})},Vs=i=>{const e=Ct.c(17),{label:n,loading:r,disabled:v,destructive:h,onClick:p,children:f}=i,m=r||void 0,x=h?"text-[var(--status-error)] hover:text-[var(--status-error)]":"text-muted-foreground hover:text-foreground";let M;e[0]!==x?(M=Ve("flex h-6 w-6 items-center justify-center transition-colors disabled:opacity-50",x),e[0]=x,e[1]=M):M=e[1];let y;e[2]!==f||e[3]!==r?(y=r?t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):f,e[2]=f,e[3]=r,e[4]=y):y=e[4];let k;e[5]!==v||e[6]!==n||e[7]!==p||e[8]!==m||e[9]!==M||e[10]!==y?(k=t.jsx(Zt,{asChild:!0,children:t.jsx("button",{type:"button","aria-label":n,"aria-busy":m,className:M,onClick:p,disabled:v,children:y})}),e[5]=v,e[6]=n,e[7]=p,e[8]=m,e[9]=M,e[10]=y,e[11]=k):k=e[11];let L;e[12]!==n?(L=t.jsx(Xt,{sideOffset:6,children:n}),e[12]=n,e[13]=L):L=e[13];let N;return e[14]!==k||e[15]!==L?(N=t.jsxs(Qt,{children:[k,L]}),e[14]=k,e[15]=L,e[16]=N):N=e[16],N},Wa=i=>{const e=Ct.c(16),{onOpenStashes:n}=i,{t:r}=et();let v;e[0]===Symbol.for("react.memo_cache_sentinel")?(v=t.jsx(T,{name:"git-commit",className:"size-10 text-muted-foreground/70 mb-4"}),e[0]=v):v=e[0];let h;e[1]!==r?(h=r("gitView.empty.cleanTitle"),e[1]=r,e[2]=h):h=e[2];let p;e[3]!==h?(p=t.jsx("p",{className:"typography-ui-label font-semibold text-foreground mb-1",children:h}),e[3]=h,e[4]=p):p=e[4];let f;e[5]!==r?(f=r("gitView.empty.cleanDescription"),e[5]=r,e[6]=f):f=e[6];let m;e[7]!==f?(m=t.jsx("p",{className:"typography-meta text-muted-foreground mb-4",children:f}),e[7]=f,e[8]=m):m=e[8];let x;e[9]!==n||e[10]!==r?(x=n?t.jsxs(W,{type:"button",variant:"outline",size:"sm",onClick:n,className:"gap-1.5",children:[t.jsx(T,{name:"archive-stack",className:"size-4"}),r("gitView.stashes.title")]}):null,e[9]=n,e[10]=r,e[11]=x):x=e[11];let M;return e[12]!==p||e[13]!==m||e[14]!==x?(M=t.jsxs("div",{className:"flex flex-col items-center justify-center py-10 px-4 text-center",children:[v,p,m,x]}),e[12]=p,e[13]=m,e[14]=x,e[15]=M):M=e[15],M},mt=8,Ua=i=>{const e=Ct.c(18),{laned:n,totalLanes:r,isExpanded:v}=i,{lane:h,color:p,connectors:f}=n,x=Math.max(r,h+1)*mt+mt/2,M=l.useRef(null),y=l.useRef(null);let k;e[0]!==p||e[1]!==f||e[2]!==h||e[3]!==x?(k=()=>{const w=M.current,B=y.current;if(!w||!B)return;const S=w.offsetHeight;if(S===0)return;const R=window.devicePixelRatio||1;B.width=x*R,B.height=S*R;const I=B.getContext("2d");if(!I)return;I.scale(R,R),I.clearRect(0,0,x,S);const P=S/2,g=h*mt+mt/2,H=getComputedStyle(B),E=H.getPropertyValue("--surface-muted-foreground").trim()||H.color,V=$=>{if(!$.startsWith("var("))return $;const _=$.slice(4,-1).trim();return H.getPropertyValue(_).trim()||E},D=[...f].sort(Ka);for(const $ of D){const _=$.fromLane*mt+mt/2,Y=$.toLane*mt+mt/2,ee=$.type==="passing"?.72:$.type==="branch-out"||$.type==="merge-in"?.95:1;I.beginPath(),I.strokeStyle=V($.color),I.globalAlpha=ee,I.lineWidth=1.25,I.lineCap="round";e:switch($.type){case"passing":case"commit-lane":{I.moveTo(_,0),I.lineTo(_,S);break e}case"top-stub":{I.moveTo(_,0),I.lineTo(_,P);break e}case"bottom-stub":{I.moveTo(_,P),I.lineTo(_,S);break e}case"branch-out":{const X=(P+S)/2;I.moveTo(g,P),I.bezierCurveTo(g,X,Y,X,Y,S);break e}case"merge-in":{const X=P/2;I.moveTo(_,0),I.bezierCurveTo(_,X,g,X,g,P);break e}default:continue}I.stroke(),I.globalAlpha=1}const U=H.getPropertyValue("--background").trim()||H.getPropertyValue("--surface-background").trim();I.beginPath(),I.arc(g,P,4,0,Math.PI*2),I.fillStyle=V(p),I.fill(),I.beginPath(),I.arc(g,P,5,0,Math.PI*2),I.strokeStyle=U||E,I.lineWidth=2,I.stroke()},e[0]=p,e[1]=f,e[2]=h,e[3]=x,e[4]=k):k=e[4];let L;e[5]!==p||e[6]!==f||e[7]!==v||e[8]!==h||e[9]!==n||e[10]!==r||e[11]!==x?(L=[n,h,p,f,r,v,x],e[5]=p,e[6]=f,e[7]=v,e[8]=h,e[9]=n,e[10]=r,e[11]=x,e[12]=L):L=e[12],l.useLayoutEffect(k,L);let N;e[13]!==x?(N={width:x,height:"100%",position:"relative",flexShrink:0,overflow:"hidden"},e[13]=x,e[14]=N):N=e[14];let O;e[15]===Symbol.for("react.memo_cache_sentinel")?(O=t.jsx("canvas",{ref:y,style:{position:"absolute",inset:0,width:"100%",height:"100%",display:"block"}}),e[15]=O):O=e[15];let j;return e[16]!==N?(j=t.jsx("div",{ref:M,style:N,children:O}),e[16]=N,e[17]=j):j=e[17],j};function Ja(i){return i==="branch-out"||i==="merge-in"}function Ka(i,e){const n=Ja;return(n(i.type)?1:0)-(n(e.type)?1:0)}const dr=15e3,ur=500,mr=12,hr=8*1024*1024,gr=i=>typeof i=="string"?0:(i.original?.length??0)+(i.modified?.length??0),fr=i=>{if(i.size<=mr){let v=0;for(const h of i.values())v+=gr(h);if(v<=hr)return i}const e=Array.from(i.entries()).reverse(),n=new Map;let r=0;for(const[v,h]of e){if(n.size>=mr)continue;const p=gr(h);r+p>hr&&n.size>0||(n.set(v,h),r+=p)}return new Map(Array.from(n.entries()).reverse())};function pr(i,e){const n=new Date(i);return Number.isNaN(n.getTime())?i:On(n,e,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function qa(i){switch(i){case"A":return"text-[var(--status-success)]";case"D":return"text-[var(--status-error)]";case"M":return"text-[var(--status-warning)]";case"R":return"text-[var(--status-info)]";default:return"text-muted-foreground"}}function Ya(i){return i?i.split(",").map(e=>e.trim()).filter(Boolean).map(e=>{const n=e.startsWith("HEAD ->");return{label:n?e.replace("HEAD -> ",""):e.replace("tag: ",""),isHead:n,isTag:e.startsWith("tag: ")}}):[]}const Qa=l.memo(({entry:i,mode:e="history",laned:n,totalLanes:r,isExpanded:v,onToggle:h,files:p,isLoadingFiles:f,onCopyHash:m,directory:x,onConflict:M,onActionSuccess:y})=>{const{t:k}=et(),L=Pt(d=>d.timeFormatPreference),N=e==="graph",[O,j]=l.useState(null),[w,B]=l.useState(!1),[S,R]=l.useState(""),[I,P]=l.useState(null),[g,H]=l.useState(new Set),[E,V]=l.useState(new Map),[D,U]=l.useState(new Set),$=async()=>{if(x){j("checkout");try{await Un(x,i.hash),b.success(k("gitView.history.actions.detachedHead")),y?.()}catch(d){b.error(String(d.message))}finally{j(null)}}},_=async()=>{if(!(!x||!S.trim())){j("createBranch");try{await zn(x,S.trim(),i.hash),B(!1),R(""),y?.()}catch(d){b.error(String(d.message))}finally{j(null)}}},Y=async()=>{if(x){j("cherryPick");try{const d=await Wn(x,i.hash);d.conflict?M?.({conflict:!0,conflictFiles:d.conflictFiles,operation:"cherry-pick"}):y?.()}catch(d){b.error(String(d.message))}finally{j(null)}}},ee=async()=>{if(x){j("revert");try{const d=await Hn(x,i.hash);d.conflict?M?.({conflict:!0,conflictFiles:d.conflictFiles,operation:"revert"}):y?.()}catch(d){b.error(String(d.message))}finally{j(null)}}},X=async(d,F=!1)=>{if(!(!x||O!==null)){j("reset");try{await Gn(x,i.hash,d,F),y?.()}catch(A){b.error(String(A.message))}finally{j(null)}}},oe=async()=>{if(!I)return;const d=I;switch(P(null),d){case"checkout":return $();case"cherryPick":return Y();case"revert":return ee();case"merge":return de();case"rebase":return Q();case"resetSoft":return X("soft");case"resetMixed":return X("mixed");case"resetHard":return X("hard",!0)}},de=async()=>{if(x){j("merge");try{const d=await $n(x,{branch:i.hash});d.conflict?M?.({conflict:!0,conflictFiles:d.conflictFiles,operation:"merge"}):y?.()}catch(d){b.error(String(d.message))}finally{j(null)}}},Q=async()=>{if(x){j("rebase");try{const d=await _n(x,{onto:i.hash});d.conflict?M?.({conflict:!0,conflictFiles:d.conflictFiles,operation:"rebase"}):y?.()}catch(d){b.error(String(d.message))}finally{j(null)}}},te=l.useCallback(async d=>{const F=d.path;if(!x){V(A=>new Map(A).set(F,"error"));return}V(A=>fr(new Map(A).set(F,"loading")));try{const A=En(x,i.hash,d.path,!1),q=new Promise((se,G)=>{setTimeout(()=>G(new Error(`Timed out after ${dr}ms`)),dr)}),ie=await Promise.race([A,q]);V(se=>fr(new Map(se).set(F,ie)))}catch{V(A=>new Map(A).set(F,"error"))}},[x,i.hash]),u=l.useCallback(async d=>{const F=d.path;if(d.changeType==="R"||d.isBinary){H(se=>{const G=new Set(se);return G.has(F)?G.delete(F):G.add(F),G});return}const A=E.get(F);if(g.has(F)&&A&&A!=="error"){H(se=>{const G=new Set(se);return G.delete(F),G});return}H(se=>{const G=new Set(se);return G.add(F),G}),!(A&&A!=="error"||d.insertions+d.deletions>ur&&!D.has(F))&&await te(d)},[E,D,te,g]);return t.jsxs("li",{children:[t.jsxs("button",{type:"button",onClick:h,className:Ve("w-full flex items-start gap-3 px-3 py-2 text-left transition-colors",N?"hover:bg-[var(--interactive-hover)]/40":v?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[N&&n&&r!==void 0?t.jsx("div",{className:"-my-2 shrink-0 self-stretch",children:t.jsx(Ua,{laned:n,totalLanes:r,isExpanded:v})}):t.jsx("div",{className:"h-2 w-2 translate-y-2 rounded-full shrink-0",style:{backgroundColor:"var(--status-success)"},"aria-hidden":!0}),t.jsxs("div",{className:"min-w-0 flex-1",children:[N?(()=>{const d=Ya(i.refs);return d.length>0?t.jsx("div",{className:"flex flex-wrap gap-1 mb-0.5",children:d.map(F=>t.jsx("span",{className:Ve("inline-flex items-center px-1.5 py-0 typography-micro rounded font-medium",F.isHead?"bg-[var(--chart-1)] text-[var(--primary-foreground)]":F.isTag?"bg-[var(--chart-5)] text-[var(--primary-foreground)]":"bg-[var(--interactive-hover)] text-[var(--foreground)]"),children:F.label},F.label))}):null})():null,t.jsx("p",{className:"typography-ui-label font-medium text-foreground line-clamp-1",children:i.message}),t.jsxs("div",{className:"flex items-center gap-1 typography-meta text-muted-foreground",children:[t.jsxs("div",{className:"flex items-center gap-1 min-w-0 truncate",children:[t.jsx("span",{className:"truncate min-w-[3ch]",title:i.author_name,children:i.author_name}),t.jsx("span",{className:"shrink-0",children:"·"}),t.jsx("span",{className:"truncate min-w-0",title:pr(i.date,L),children:pr(i.date,L)})]}),t.jsx("span",{className:"shrink-0",children:"·"}),t.jsx("code",{className:"shrink-0 font-mono",children:i.hash.slice(0,8)}),t.jsxs(Qt,{children:[t.jsx(Zt,{asChild:!0,children:t.jsx(W,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:d=>{d.stopPropagation(),m(i.hash)},children:t.jsx(T,{name:"file-copy",className:"size-3"})})}),t.jsx(Xt,{sideOffset:8,children:k("gitView.history.copySha")})]})]})]})]}),v&&t.jsxs("div",{className:"px-3 pb-2 pl-8 border-t border-border/40",children:[N&&I?t.jsxs("div",{className:"flex items-center gap-2 py-2 border-b border-border/30 mb-2",children:[t.jsx("span",{className:"typography-micro text-muted-foreground flex-1 min-w-0",children:k(`gitView.history.actions.${I}Confirm`)}),t.jsxs(W,{variant:"destructive",size:"xs",className:"h-6 shrink-0",disabled:O!==null,onClick:d=>{d.stopPropagation(),oe()},children:[O!==null?t.jsx(T,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,k("gitView.history.actions.confirmButton")]}),t.jsx(W,{variant:"ghost",size:"xs",className:"h-6 shrink-0",disabled:O!==null,onClick:d=>{d.stopPropagation(),P(null)},children:k("gitView.history.actions.cancelButton")})]}):N?t.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 py-2 border-b border-border/30 mb-2",children:[t.jsx(W,{variant:"outline",size:"xs",className:"h-6",disabled:O!==null,onClick:d=>{d.stopPropagation(),P("checkout")},children:k("gitView.history.actions.checkout")}),w?t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx("input",{autoFocus:!0,value:S,onChange:d=>R(d.target.value),onKeyDown:d=>{d.key==="Enter"&&_(),d.key==="Escape"&&(B(!1),R(""))},placeholder:k("gitView.history.actions.createBranchPlaceholder"),className:"h-6 text-xs px-2 rounded border border-border/60 bg-background min-w-0 w-32"}),t.jsxs(W,{variant:"outline",size:"xs",className:"h-6",disabled:!S.trim()||O!==null,onClick:d=>{d.stopPropagation(),_()},children:[O==="createBranch"?t.jsx(T,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,k("gitView.history.actions.createBranchConfirm")]})]}):t.jsx(W,{variant:"outline",size:"xs",className:"h-6",onClick:d=>{d.stopPropagation(),B(!0)},children:k("gitView.history.actions.createBranch")}),t.jsx(W,{variant:"outline",size:"xs",className:"h-6",disabled:O!==null,onClick:d=>{d.stopPropagation(),P("cherryPick")},children:k("gitView.history.actions.cherryPick")}),t.jsx(W,{variant:"outline",size:"xs",className:"h-6",disabled:O!==null,onClick:d=>{d.stopPropagation(),P("revert")},children:k("gitView.history.actions.revert")}),t.jsxs(Ps,{children:[t.jsx(Fs,{asChild:!0,children:t.jsxs(W,{variant:"outline",size:"xs",className:"h-6",disabled:O!==null,onClick:d=>d.stopPropagation(),children:[O==="reset"?t.jsx(T,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,k("gitView.history.actions.reset")]})}),t.jsx(Rs,{align:"start",className:"min-w-max",children:["soft","mixed","hard"].map(d=>t.jsx(Ln,{disabled:O!==null,onSelect:F=>{F.stopPropagation(),P(`reset${d.charAt(0).toUpperCase()+d.slice(1)}`)},children:k(`gitView.history.actions.reset${d.charAt(0).toUpperCase()+d.slice(1)}`)},d))})]}),t.jsx(W,{variant:"outline",size:"xs",className:"h-6",disabled:O!==null,onClick:d=>{d.stopPropagation(),P("merge")},children:k("gitView.history.actions.merge")}),t.jsx(W,{variant:"outline",size:"xs",className:"h-6",disabled:O!==null,onClick:d=>{d.stopPropagation(),P("rebase")},children:k("gitView.history.actions.rebase")})]}):null,f?t.jsxs("div",{className:"flex items-center gap-2 py-2",children:[t.jsx(T,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}),t.jsx("span",{className:"typography-micro text-muted-foreground",children:k("gitView.history.loadingFiles")})]}):p.length===0?t.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:k("gitView.history.noFiles")}):t.jsx("ul",{className:"space-y-0.5 py-2",children:p.map(d=>t.jsxs("li",{children:[t.jsxs("button",{type:"button",onClick:()=>u(d),className:Ve("w-full flex items-center gap-2 typography-micro text-left cursor-pointer transition-colors rounded px-1",g.has(d.path)?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[t.jsx("span",{className:Ve("font-semibold w-3 text-center shrink-0",qa(d.changeType)),children:d.changeType}),t.jsx("span",{className:"truncate text-foreground min-w-0",title:d.path,children:d.path}),!d.isBinary&&t.jsxs("span",{className:"shrink-0",children:[t.jsxs("span",{style:{color:"var(--status-success)"},children:["+",d.insertions]}),t.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),t.jsxs("span",{style:{color:"var(--status-error)"},children:["-",d.deletions]})]}),d.isBinary&&t.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:k("gitView.history.binary")}),t.jsx(T,{name:g.has(d.path)?"arrow-down-s":"arrow-right-s",className:"size-3 shrink-0 text-muted-foreground"})]}),g.has(d.path)&&t.jsx("div",{className:"max-h-[400px] overflow-y-auto rounded border border-border/40 mx-2 mb-1","data-diff-virtual-root":!0,"data-diff-virtual-content":!0,children:d.changeType==="R"?t.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:k("gitView.history.renamedNoDiff")}):d.isBinary?t.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:k("gitView.history.binaryNoDiff")}):(()=>{const F=d.insertions+d.deletions;if(!D.has(d.path)&&F>ur)return t.jsxs("div",{className:"flex flex-col items-start gap-1 px-3 py-2 text-sm text-muted-foreground",children:[t.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:k("gitView.history.largeDiffTitle",{count:F})}),t.jsx("div",{className:"typography-meta text-muted-foreground",children:k("gitView.history.largeDiffDescription")}),t.jsx(W,{type:"button",variant:"ghost",size:"xs",className:"h-6 px-0 text-primary hover:bg-transparent hover:underline",onClick:()=>{U(q=>new Set(q).add(d.path)),te(d)},children:k("gitView.history.renderDiffAnyway")})]});const A=E.get(d.path);return A==="loading"||A===void 0?t.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:k("gitView.history.loadingDiff")}):A==="error"?t.jsx("button",{type:"button",onClick:()=>u(d),className:"w-full text-left px-3 py-2 text-sm text-muted-foreground hover:bg-[var(--interactive-hover)] transition-colors",children:k("gitView.history.diffError")}):t.jsx(Da,{original:A.original,modified:A.modified,language:An(d.path)||"",fileName:d.path,renderSideBySide:!1,layout:"inline",enableComments:!1})})()})]},d.path))})]})]})}),xr=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)","var(--syntax-keyword)","var(--syntax-string)","var(--status-info)"];function Ut(i){return xr[i%xr.length]}function Za(i){if(i.length===0)return[];const e=[],n=[];for(let r=0;r<i.length;r++){const v=i[r],h=[];for(let N=0;N<e.length;N++)e[N]===v.hash&&h.push(N);let p=h.length>0?h[0]:-1;if(p===-1){const N=e.indexOf(null);N!==-1?p=N:(p=e.length,e.push(null))}const f=h.slice(1),m=Ut(p),x=e[p]===v.hash,M=v.parents.length>0;M?e[p]=v.parents[0]:e[p]=null;const y=[],k=new Set;for(let N=1;N<v.parents.length;N++){const O=v.parents[N],j=e.indexOf(O);if(j!==-1)y.push(j);else{const w=e.indexOf(null);if(w!==-1)e[w]=O,y.push(w),k.add(w);else{const B=e.length;e.push(O),y.push(B),k.add(B)}}}const L=[];x&&M?L.push({fromLane:p,toLane:p,color:m,type:"commit-lane"}):x&&!M?L.push({fromLane:p,toLane:p,color:m,type:"top-stub"}):!x&&M&&L.push({fromLane:p,toLane:p,color:m,type:"bottom-stub"});for(const N of f)L.push({fromLane:N,toLane:p,color:Ut(N),type:"merge-in"}),e[N]=null;for(const N of y)L.push({fromLane:p,toLane:N,color:Ut(N),type:"branch-out"});for(let N=0;N<e.length;N++)e[N]!==null&&N!==p&&(k.has(N)||L.push({fromLane:N,toLane:N,color:Ut(N),type:"passing"}));n.push({commit:v,lane:p,color:m,connectors:L})}return n}const Xa=[{labelKey:"gitView.history.logSize25",value:25},{labelKey:"gitView.history.logSize50",value:50},{labelKey:"gitView.history.logSize100",value:100}],ei=i=>{const e=Ct.c(84),{mode:n,log:r,isLogLoading:v,logMaxCount:h,onLogMaxCountChange:p,expandedCommitHashes:f,onToggleCommit:m,commitFilesMap:x,loadingCommitHashes:M,onCopyHash:y,directory:k,showHeader:L,contentMaxHeightClassName:N,branchDivider:O,onConflict:j,onActionSuccess:w}=i,B=n===void 0?"history":n,S=L===void 0?!0:L,R=N===void 0?"max-h-[50vh]":N,I=O===void 0?null:O,{t:P}=et(),[g,H]=l.useState(!0),E=B==="graph";let V;e[0]!==E||e[1]!==r?(V=E&&r?Za(r.all):[],e[0]=E,e[1]=r,e[2]=V):V=e[2];const D=V;let U;e[3]!==D?(U=Math.max(1,...D.map(ti)),e[3]=D,e[4]=U):U=e[4];const $=U;let _;e[5]!==D?(_=new Map(D.map(si)),e[5]=D,e[6]=_):_=e[6];const Y=_;if(!r)return null;const ee=I!==null&&I.insertBeforeIndex>0&&I.insertBeforeIndex<r.all.length,X=I!==null&&I.insertBeforeIndex===r.all.length,oe=ee||X;let de;e[7]!==I||e[8]!==ee||e[9]!==X||e[10]!==r.all?(de=ee?r.all.slice(0,I.insertBeforeIndex):X?r.all:[],e[7]=I,e[8]=ee,e[9]=X,e[10]=r.all,e[11]=de):de=e[11];const Q=de;let te;if(e[12]!==I||e[13]!==x||e[14]!==R||e[15]!==k||e[16]!==f||e[17]!==ee||e[18]!==oe||e[19]!==E||e[20]!==v||e[21]!==Y||e[22]!==M||e[23]!==r.all||e[24]!==h||e[25]!==$||e[26]!==B||e[27]!==w||e[28]!==j||e[29]!==y||e[30]!==p||e[31]!==m||e[32]!==P||e[33]!==Q){const re=ee?r.all.slice(I.insertBeforeIndex):[];let le;e[35]!==I?.direction?(le=I?.direction==="down"?t.jsx(T,{name:"arrow-down-s",className:"size-3.5"}):t.jsx(T,{name:"arrow-up",className:"size-3.5"}),e[35]=I?.direction,e[36]=le):le=e[36];const ve=le;let pe;e[37]!==x||e[38]!==k||e[39]!==f||e[40]!==E||e[41]!==Y||e[42]!==M||e[43]!==$||e[44]!==B||e[45]!==w||e[46]!==j||e[47]!==y||e[48]!==m?(pe=ge=>t.jsx("ul",{className:"divide-y divide-border/60",children:ge.map(ce=>t.jsx(Qa,{entry:ce,mode:B,laned:E?Y.get(ce.hash):void 0,totalLanes:E?$:void 0,isExpanded:f.has(ce.hash),onToggle:()=>m(ce.hash),files:x.get(ce.hash)??[],isLoadingFiles:M.has(ce.hash),onCopyHash:y,directory:k,onConflict:j,onActionSuccess:w},ce.hash))}),e[37]=x,e[38]=k,e[39]=f,e[40]=E,e[41]=Y,e[42]=M,e[43]=$,e[44]=B,e[45]=w,e[46]=j,e[47]=y,e[48]=m,e[49]=pe):pe=e[49];const ue=pe;let me;e[50]!==v||e[51]!==r.all.length||e[52]!==h||e[53]!==p||e[54]!==P?(me=r.all.length>=h?t.jsx("div",{className:"flex justify-center py-2 border-t border-border/40",children:t.jsx(W,{type:"button",variant:"ghost",size:"xs",onClick:()=>p(h+25),disabled:v,className:"px-3 text-muted-foreground hover:text-foreground",children:v?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx(T,{name:"loader-4",className:"size-3 animate-spin"}),P("gitView.history.loadingMore")]}):P("gitView.history.loadMore")})}):null,e[50]=v,e[51]=r.all.length,e[52]=h,e[53]=p,e[54]=P,e[55]=me):me=e[55];const he=me;te=t.jsx(vr,{outerClassName:`min-h-0 ${R}`,className:"h-full w-full",children:r.all.length===0?t.jsx("div",{className:"flex h-full items-center justify-center p-4",children:t.jsx("p",{className:"typography-ui-label text-muted-foreground",children:P("gitView.history.noCommits")})}):oe&&I?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex flex-col gap-0",children:[Q.length>0?t.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:ue(Q)}):null,t.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5","aria-hidden":!0,children:[t.jsx("span",{className:"h-px flex-1 bg-border/60"}),t.jsxs("span",{className:"inline-flex max-w-[80%] items-center gap-1 typography-micro text-muted-foreground",children:[t.jsx("span",{className:"truncate",title:I.branchName,children:I.branchName}),ve]}),t.jsx("span",{className:"h-px flex-1 bg-border/60"})]}),re.length>0?t.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:ue(re)}):null]}),he]}):t.jsxs(t.Fragment,{children:[ue(r.all),he]})}),e[12]=I,e[13]=x,e[14]=R,e[15]=k,e[16]=f,e[17]=ee,e[18]=oe,e[19]=E,e[20]=v,e[21]=Y,e[22]=M,e[23]=r.all,e[24]=h,e[25]=$,e[26]=B,e[27]=w,e[28]=j,e[29]=y,e[30]=p,e[31]=m,e[32]=P,e[33]=Q,e[34]=te}else te=e[34];const u=te;if(!S){if(oe){let le;return e[56]!==u?(le=t.jsx("section",{className:"h-full min-h-0",children:u}),e[56]=u,e[57]=le):le=e[57],le}let re;return e[58]!==u?(re=t.jsx("section",{className:"h-full min-h-0 rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:u}),e[58]=u,e[59]=re):re=e[59],re}let d;e[60]!==P?(d=P("gitView.history.title"),e[60]=P,e[61]=d):d=e[61];let F;e[62]!==d?(F=t.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:d}),e[62]=d,e[63]=F):F=e[63];let A;e[64]!==v||e[65]!==g||e[66]!==h||e[67]!==p||e[68]!==P?(A=g&&t.jsx("div",{onClick:ri,onPointerDown:ni,children:t.jsxs(Jn,{value:String(h),onValueChange:re=>p(Number(re)),disabled:v,children:[t.jsx(Kn,{size:"sm",className:"w-auto",disabled:v,children:t.jsx(qn,{placeholder:P("gitView.history.commitsPlaceholder")})}),t.jsx(Yn,{children:Xa.map(re=>t.jsx(Qn,{value:String(re.value),children:P(re.labelKey)},re.value))})]})}),e[64]=v,e[65]=g,e[66]=h,e[67]=p,e[68]=P,e[69]=A):A=e[69];let q;e[70]!==g?(q=g?t.jsx(T,{name:"arrow-up-s",className:"size-4 text-muted-foreground"}):t.jsx(T,{name:"arrow-down-s",className:"size-4 text-muted-foreground"}),e[70]=g,e[71]=q):q=e[71];let ie;e[72]!==A||e[73]!==q?(ie=t.jsxs("div",{className:"flex items-center gap-2",children:[A,q]}),e[72]=A,e[73]=q,e[74]=ie):ie=e[74];let se;e[75]!==F||e[76]!==ie?(se=t.jsxs(Sa,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[F,ie]}),e[75]=F,e[76]=ie,e[77]=se):se=e[77];let G;e[78]!==u?(G=t.jsx(ka,{children:u}),e[78]=u,e[79]=G):G=e[79];let fe;return e[80]!==g||e[81]!==se||e[82]!==G?(fe=t.jsxs(Va,{open:g,onOpenChange:H,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[se,G]}),e[80]=g,e[81]=se,e[82]=G,e[83]=fe):fe=e[83],fe};function ti(i){return i.lane+1}function si(i){return[i.commit.hash,i]}function ri(i){return i.stopPropagation()}function ni(i){return i.stopPropagation()}const ai=i=>{const e=Ct.c(148),{open:n,onOpenChange:r,conflictFiles:v,directory:h,operation:p,onAbort:f,onClearState:m}=i;let x;e[0]!==v?(x=v===void 0?[]:v,e[0]=v,e[1]=x):x=e[1];const M=x,{t:y}=et(),k=Xe(ii),L=Xe(oi),N=Kt(li),O=Kt(ci),[j,w]=l.useState(!1),[B,S]=l.useState(null),[R,I]=l.useState(null);let P,g;e[2]!==h||e[3]!==n||e[4]!==y?(P=()=>{!n||!h||(w(!0),I(null),S(null),Zn(h).then(K=>{S(K)}).catch(K=>{const xe=K instanceof Error?K.message:y("gitView.conflict.loadFailed");I(xe)}).finally(()=>{w(!1)}))},g=[n,h,y],e[2]=h,e[3]=n,e[4]=y,e[5]=P,e[6]=g):(P=e[5],g=e[6]),l.useEffect(P,g);let H;e[7]!==B||e[8]!==h||e[9]!==p?(H=async()=>{if(!B)return null;const K=p==="merge"?"merge":"rebase",xe=B.headInfo||(p==="merge"?"MERGE_HEAD":"REBASE_HEAD"),Te=p==="merge"?"git commit --no-edit":"git rebase --continue",Ge=await Jt("git.conflict.resolve.visible",{operation_label:K,head_ref:xe}),Ie=await Jt("git.conflict.resolve.instructions",{operation_label:K,directory:h,operation:p,head_info:B.headInfo||"N/A",continue_cmd:Te}),Ne=`${K} conflict context (JSON)
3
+ ${JSON.stringify({directory:h,operation:B.operation,headInfo:B.headInfo,statusPorcelain:B.statusPorcelain,unmergedFiles:B.unmergedFiles,diff:B.diff},null,2)}`;return{visibleText:Ge,instructionsText:Ie,payloadText:Ne}},e[7]=B,e[8]=h,e[9]=p,e[10]=H):H=e[10];const E=H;let V;e[11]!==f||e[12]!==r?(V=()=>{f(),r(!1)},e[11]=f,e[12]=r,e[13]=V):V=e[13];const D=V;let U;e[14]!==m||e[15]!==r?(U=()=>{m?.(),r(!1)},e[14]=m,e[15]=r,e[16]=U):U=e[16];const $=U;let _;e[17]!==E||e[18]!==L||e[19]!==m||e[20]!==r||e[21]!==N||e[22]!==O||e[23]!==y?(_=async()=>{const K=await E();if(!K){b.error(y("gitView.conflict.noDetailsAvailable"));return}if(!L){b.error(y("gitView.conflict.noActiveSession"),{description:y("gitView.conflict.noActiveSessionDescription")});return}N(K.visibleText,"replace"),O([{text:K.instructionsText,synthetic:!0},{text:K.payloadText,synthetic:!0}]),m?.(),r(!1)},e[17]=E,e[18]=L,e[19]=m,e[20]=r,e[21]=N,e[22]=O,e[23]=y,e[24]=_):_=e[24];const Y=_;let ee;e[25]!==E||e[26]!==h||e[27]!==m||e[28]!==r||e[29]!==k||e[30]!==y?(ee=async()=>{const K=await E();if(!K){b.error(y("gitView.conflict.noDetailsAvailable"));return}k({directoryOverride:h,initialPrompt:K.visibleText,syntheticParts:[{text:K.instructionsText,synthetic:!0},{text:K.payloadText,synthetic:!0}]}),m?.(),r(!1)},e[25]=E,e[26]=h,e[27]=m,e[28]=r,e[29]=k,e[30]=y,e[31]=ee):ee=e[31];const X=ee;let oe,de,Q,te,u,d,F,A,q,ie,se,G,fe,re,le,ve,pe,ue,me,he,ge,ce;if(e[32]!==B||e[33]!==M||e[34]!==L||e[35]!==D||e[36]!==$||e[37]!==Y||e[38]!==X||e[39]!==j||e[40]!==R||e[41]!==r||e[42]!==n||e[43]!==p||e[44]!==y){const K=y(p==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),xe=B?.unmergedFiles||M;Q=ht,ge=n,ce=r,de=gt,he="max-w-md w-[calc(100vw-2rem)]",re="flex flex-col gap-4 overflow-hidden";let Te;e[67]===Symbol.for("react.memo_cache_sentinel")?(Te=t.jsx(T,{name:"alert",className:"size-5 shrink-0 text-[var(--status-warning)]"}),e[67]=Te):Te=e[67];const Ge=t.jsxs("div",{className:"flex items-center gap-2",children:[Te,t.jsx(pt,{children:y("gitView.conflict.detectedTitle",{operation:K})})]});let Ie;e[68]!==p||e[69]!==y?(Ie=y("gitView.conflict.detectedDescription",{operation:p}),e[68]=p,e[69]=y,e[70]=Ie):Ie=e[70];let Ne;e[71]!==Ie?(Ne=t.jsx(yt,{children:Ie}),e[71]=Ie,e[72]=Ne):Ne=e[72],e[73]!==Ge||e[74]!==Ne?(le=t.jsxs(ft,{children:[Ge,Ne]}),e[73]=Ge,e[74]=Ne,e[75]=le):le=e[75],e[76]!==j||e[77]!==y?(ve=j&&t.jsxs("div",{className:"flex items-center justify-center gap-2 py-4 text-muted-foreground",children:[t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}),t.jsx("span",{className:"typography-meta",children:y("gitView.conflict.loading")})]}),e[76]=j,e[77]=y,e[78]=ve):ve=e[78],e[79]!==R||e[80]!==y?(pe=R&&t.jsx("div",{className:"rounded-lg bg-[var(--status-error-bg)] p-3 text-[var(--status-error)] typography-meta break-words",children:y("gitView.conflict.errorLoadingDetails",{message:R})}),e[79]=R,e[80]=y,e[81]=pe):pe=e[81],e[82]!==xe||e[83]!==y?(ue=xe.length>0&&t.jsxs("div",{className:"space-y-2 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:y("gitView.conflict.conflictedFiles")}),t.jsx("span",{className:"typography-micro px-1.5 py-0.5 rounded bg-[var(--surface-elevated)] text-muted-foreground",children:xe.length})]}),t.jsx("div",{className:"bg-[var(--surface-elevated)] rounded-lg p-3 max-h-40 overflow-y-auto overflow-x-hidden",children:t.jsx("ul",{className:"space-y-1",children:xe.map(di)})})]}),e[82]=xe,e[83]=y,e[84]=ue):ue=e[84],e[85]!==B||e[86]!==y?(me=B?.headInfo&&t.jsxs("div",{className:"space-y-1 overflow-hidden",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:y("gitView.conflict.headInfo")}),t.jsx("div",{className:"typography-micro text-foreground font-mono bg-[var(--surface-elevated)] rounded-lg p-3 max-h-24 overflow-y-auto break-words whitespace-pre-wrap",children:B.headInfo})]}),e[85]=B,e[86]=y,e[87]=me):me=e[87],se="flex flex-col gap-2 pt-2";let Se;e[88]!==X?(Se=()=>{X()},e[88]=X,e[89]=Se):Se=e[89];const Be=j||!B;let Pe;e[90]!==j?(Pe=j?t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(T,{name:"add",className:"size-4"}),e[90]=j,e[91]=Pe):Pe=e[91];let ke;e[92]!==y?(ke=y("gitView.conflict.resolveNewSession"),e[92]=y,e[93]=ke):ke=e[93],e[94]!==Se||e[95]!==Be||e[96]!==Pe||e[97]!==ke?(G=t.jsxs(W,{variant:"default",onClick:Se,disabled:Be,className:"w-full gap-2",children:[Pe,ke]}),e[94]=Se,e[95]=Be,e[96]=Pe,e[97]=ke,e[98]=G):G=e[98];let we;e[99]!==Y?(we=()=>{Y()},e[99]=Y,e[100]=we):we=e[100];const De=j||!B||!L;let Le;e[101]!==j?(Le=j?t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(T,{name:"chat-1",className:"size-4"}),e[101]=j,e[102]=Le):Le=e[102];let Z;e[103]!==y?(Z=y("gitView.conflict.resolveCurrentSession"),e[103]=y,e[104]=Z):Z=e[104],e[105]!==we||e[106]!==De||e[107]!==Le||e[108]!==Z?(fe=t.jsxs(W,{variant:"outline",onClick:we,disabled:De,className:"w-full gap-2",children:[Le,Z]}),e[105]=we,e[106]=De,e[107]=Le,e[108]=Z,e[109]=fe):fe=e[109],q="flex gap-2 pt-1";let Fe;e[110]!==y?(Fe=y("gitView.conflict.continueLater"),e[110]=y,e[111]=Fe):Fe=e[111],e[112]!==$||e[113]!==Fe?(ie=t.jsx(W,{variant:"ghost",size:"sm",onClick:$,className:"flex-1",children:Fe}),e[112]=$,e[113]=Fe,e[114]=ie):ie=e[114],oe=W,te="destructive",u="sm",d=D,F="flex-1",A=y("gitView.conflict.abortOperation",{operation:K}),e[32]=B,e[33]=M,e[34]=L,e[35]=D,e[36]=$,e[37]=Y,e[38]=X,e[39]=j,e[40]=R,e[41]=r,e[42]=n,e[43]=p,e[44]=y,e[45]=oe,e[46]=de,e[47]=Q,e[48]=te,e[49]=u,e[50]=d,e[51]=F,e[52]=A,e[53]=q,e[54]=ie,e[55]=se,e[56]=G,e[57]=fe,e[58]=re,e[59]=le,e[60]=ve,e[61]=pe,e[62]=ue,e[63]=me,e[64]=he,e[65]=ge,e[66]=ce}else oe=e[45],de=e[46],Q=e[47],te=e[48],u=e[49],d=e[50],F=e[51],A=e[52],q=e[53],ie=e[54],se=e[55],G=e[56],fe=e[57],re=e[58],le=e[59],ve=e[60],pe=e[61],ue=e[62],me=e[63],he=e[64],ge=e[65],ce=e[66];let ze;e[115]!==oe||e[116]!==te||e[117]!==u||e[118]!==d||e[119]!==F||e[120]!==A?(ze=t.jsx(oe,{variant:te,size:u,onClick:d,className:F,children:A}),e[115]=oe,e[116]=te,e[117]=u,e[118]=d,e[119]=F,e[120]=A,e[121]=ze):ze=e[121];let $e;e[122]!==q||e[123]!==ie||e[124]!==ze?($e=t.jsxs("div",{className:q,children:[ie,ze]}),e[122]=q,e[123]=ie,e[124]=ze,e[125]=$e):$e=e[125];let je;e[126]!==se||e[127]!==G||e[128]!==fe||e[129]!==$e?(je=t.jsxs("div",{className:se,children:[G,fe,$e]}),e[126]=se,e[127]=G,e[128]=fe,e[129]=$e,e[130]=je):je=e[130];let Re;e[131]!==re||e[132]!==le||e[133]!==ve||e[134]!==pe||e[135]!==ue||e[136]!==me||e[137]!==je?(Re=t.jsxs("div",{className:re,children:[le,ve,pe,ue,me,je]}),e[131]=re,e[132]=le,e[133]=ve,e[134]=pe,e[135]=ue,e[136]=me,e[137]=je,e[138]=Re):Re=e[138];let Ce;e[139]!==de||e[140]!==he||e[141]!==Re?(Ce=t.jsx(de,{className:he,children:Re}),e[139]=de,e[140]=he,e[141]=Re,e[142]=Ce):Ce=e[142];let Ee;return e[143]!==Q||e[144]!==ge||e[145]!==ce||e[146]!==Ce?(Ee=t.jsx(Q,{open:ge,onOpenChange:ce,children:Ce}),e[143]=Q,e[144]=ge,e[145]=ce,e[146]=Ce,e[147]=Ee):Ee=e[147],Ee};function ii(i){return i.openNewSessionDraft}function oi(i){return i.currentSessionId}function li(i){return i.setPendingInputText}function ci(i){return i.setPendingSyntheticParts}function di(i){return t.jsx("li",{className:"typography-micro text-foreground font-mono truncate block",title:i,children:i},i)}const ui=({open:i,onOpenChange:e,operation:n,targetBranch:r,onConfirm:v})=>{const{t:h}=et(),[p,f]=l.useState(!0),[m,x]=l.useState(!1),M=h(n==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),y=async()=>{x(!0);try{await v(p),e(!1)}catch(L){const N=L instanceof Error?L.message:`Failed to ${n}`;b.error(N)}finally{x(!1)}},k=()=>{m||e(!1)};return t.jsx(ht,{open:i,onOpenChange:m?void 0:e,children:t.jsxs(gt,{className:"max-w-md",children:[t.jsxs(ft,{children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(T,{name:"alert",className:"size-5 text-[var(--status-warning)]"}),t.jsx(pt,{children:h("gitView.stash.title")})]}),t.jsx(yt,{children:h("gitView.stash.description",{operation:n})})]}),t.jsxs("div",{className:"py-2",children:[t.jsx("p",{className:"typography-meta text-muted-foreground mb-3",children:h("gitView.stash.thisWill")}),t.jsxs("ol",{className:"list-decimal list-inside space-y-1 typography-meta text-foreground",children:[t.jsx("li",{children:h("gitView.stash.stepStash")}),t.jsxs("li",{children:[h(n==="merge"?"gitView.operation.merge":"gitView.operation.rebase")," ",h(n==="merge"?"gitView.stash.mergeWith":"gitView.stash.rebaseOnto")," ",t.jsx("span",{className:"font-mono text-primary",children:r})]}),p&&t.jsx("li",{children:h("gitView.stash.stepRestore")})]})]}),t.jsxs("div",{className:"flex items-center gap-2 py-2",children:[t.jsx(Xn,{checked:p,onChange:f,disabled:m,ariaLabel:h("gitView.stash.restoreAria")}),t.jsx("span",{className:"typography-ui-label text-foreground cursor-pointer select-none",onClick:()=>!m&&f(!p),children:h("gitView.stash.restoreAfterOperation",{operation:n})})]}),t.jsxs(Is,{className:"gap-2",children:[t.jsx(W,{variant:"ghost",size:"sm",onClick:k,disabled:m,children:h("gitView.common.cancel")}),t.jsx(W,{variant:"default",size:"sm",onClick:y,disabled:m,className:"gap-1.5",children:m?t.jsxs(t.Fragment,{children:[t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}),h("gitView.common.processing")]}):h("gitView.stash.confirmButton",{operation:M})})]})]})})},mi=({mergeInProgress:i,rebaseInProgress:e,onContinue:n,onAbort:r,onResolveWithAI:v,conflictCount:h=0,isLoading:p=!1})=>{const{t:f}=et(),[m,x]=l.useState(null),M=i&&i.head,y=e&&(e.headName||e.onto),k=M?"merge":y?"rebase":null;if(!k)return null;const L=async()=>{x("continue");try{await n()}finally{x(null)}},N=async()=>{x("abort");try{await r()}finally{x(null)}},O=m!==null,j=h>0,w=f(k==="merge"?"gitView.operation.merge":"gitView.operation.rebase");let B="";i?B=i.message?f("gitView.operation.mergingMessage",{message:i.message}):f("gitView.operation.mergeInProgressWithHead",{head:i.head}):e&&(B=e.headName?f("gitView.operation.rebasingOnto",{headName:e.headName,onto:e.onto||""}):f("gitView.operation.rebaseInProgress"));const S=j?h===1?f("gitView.operation.inProgressTitleOneConflict",{operation:w,count:h}):f("gitView.operation.inProgressTitleManyConflicts",{operation:w,count:h}):f("gitView.operation.inProgressTitle",{operation:w}),R=f(j?"gitView.operation.resolveConflictsHint":"gitView.operation.readyToContinueHint");return t.jsx("div",{className:"mx-4 mt-3 overflow-hidden rounded-lg border border-[var(--status-warning-border)]",children:t.jsxs("div",{className:"flex flex-col gap-3 p-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("p",{className:"typography-label text-[var(--status-warning)]",children:S}),B&&t.jsx("p",{className:"typography-micro break-words text-muted-foreground",children:B})]}),t.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[t.jsx("p",{className:"typography-micro min-w-0 flex-1 text-muted-foreground",children:R}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[t.jsxs(W,{variant:"ghost",size:"sm",onClick:N,disabled:O||p,className:"gap-1.5",children:[m==="abort"?t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(T,{name:"close",className:"size-4"}),f("gitView.operation.abort")]}),j?v&&t.jsx(W,{variant:"default",size:"sm",onClick:v,disabled:O||p,children:f("gitView.operation.resolveWithAi")}):t.jsxs(W,{variant:"default",size:"sm",onClick:L,disabled:O||p,className:"gap-1.5",children:[m==="continue"?t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(T,{name:"check",className:"size-4"}),f("gitView.operation.continue")]})]})]})]})})},hi=i=>{const e=Ct.c(104),{currentBranch:n,localBranches:r,remoteBranches:v,onMerge:h,onRebase:p,disabled:f,isOperating:m,operationLogs:x,onOperationComplete:M,mode:y,defaultTargetBranch:k}=i,L=f===void 0?!1:f,N=m===void 0?!1:m,O=x===void 0?[]:x,j=y===void 0?"dialog":y,{t:w}=et(),[B,S]=l.useState(!1),[R,I]=l.useState("merge"),[P,g]=l.useState(null),[H,E]=l.useState(!1),[V,D]=l.useState(""),U=l.useRef(null),$=l.useRef(null),_=L||N,Y=n||w("gitView.branch.currentBranchFallback"),ee=O.length>0&&O.every(gi),X=O.some(fi);let oe;e[0]===Symbol.for("react.memo_cache_sentinel")?(oe=()=>{$.current&&($.current.scrollTop=$.current.scrollHeight)},e[0]=oe):oe=e[0],l.useEffect(oe,[O]);let de;e[1]!==v?(de=new Set(v.map(pi).filter(Boolean)),e[1]=v,e[2]=de):de=e[2];const Q=de;let te;if(e[3]!==V||e[4]!==n||e[5]!==r||e[6]!==Q){let Z;e[8]!==n||e[9]!==Q?(Z=_e=>_e!==n&&!Q.has(_e),e[8]=n,e[9]=Q,e[10]=Z):Z=e[10];const Fe=r.filter(Z);te=Rt(Fe,V,xi),e[3]=V,e[4]=n,e[5]=r,e[6]=Q,e[7]=te}else te=e[7];const u=te;let d;e[11]!==V||e[12]!==v?(d=Rt(v,V,wi),e[11]=V,e[12]=v,e[13]=d):d=e[13];const F=d;let A;e[14]!==k||e[15]!==r||e[16]!==v?(A=()=>k&&(v.includes(k)||r.includes(k))?k:null,e[14]=k,e[15]=r,e[16]=v,e[17]=A):A=e[17];const q=A;let ie;e[18]!==q||e[19]!==S?(ie=()=>{S(!0),g(q()),I("merge"),D("")},e[18]=q,e[19]=S,e[20]=ie):ie=e[20];const se=ie;let G;e[21]===Symbol.for("react.memo_cache_sentinel")?(G=Z=>{g(Z),E(!1),D("")},e[21]=G):G=e[21];const fe=G;let re;e[22]!==h||e[23]!==p||e[24]!==R||e[25]!==P?(re=()=>{P&&(R==="merge"?h(P):p(P))},e[22]=h,e[23]=p,e[24]=R,e[25]=P,e[26]=re):re=e[26];const le=re;let ve;e[27]!==N||e[28]!==S?(ve=()=>{N||(g(null),I("merge"),D(""),S(!1))},e[27]=N,e[28]=S,e[29]=ve):ve=e[29];const pe=ve,ue=()=>{N&&!ee||(ee&&M?.(),g(null),I("merge"),D(""),S(!1))};let me,he;e[30]!==H?(me=()=>{H||D("")},he=[H],e[30]=H,e[31]=me,e[32]=he):(me=e[31],he=e[32]),l.useEffect(me,he);let ge,ce;e[33]!==j||e[34]!==q||e[35]!==P?(ge=()=>{j==="dialog"||P||g(q())},ce=[j,q,P],e[33]=j,e[34]=q,e[35]=P,e[36]=ge,e[37]=ce):(ge=e[36],ce=e[37]),l.useEffect(ge,ce);const je=N?t.jsxs("div",{className:"space-y-3",children:[t.jsx("div",{ref:$,className:"rounded-lg border border-border bg-muted/30 p-3 max-h-48 overflow-y-auto",children:t.jsx("div",{className:"space-y-2",children:O.map(yi)})}),ee?j==="dialog"?t.jsx(Is,{children:t.jsx(W,{variant:"default",size:"sm",onClick:ue,children:w(X?"gitView.common.close":"gitView.common.done")})}):t.jsx("div",{className:"flex justify-end",children:t.jsx(W,{variant:"default",size:"sm",onClick:ue,children:w(X?"gitView.common.close":"gitView.common.done")})}):null]}):t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"space-y-3",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:w("gitView.branch.operation")}),t.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[t.jsxs("button",{type:"button",onClick:()=>I("merge"),className:Ve("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",R==="merge"?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(T,{name:"git-merge",className:Ve("size-4",R==="merge"?"text-primary":"text-muted-foreground")}),t.jsx("span",{className:Ve("typography-ui-label",R==="merge"?"text-foreground":"text-muted-foreground"),children:w("gitView.operation.merge")})]}),t.jsx("p",{className:"typography-micro text-muted-foreground",children:w("gitView.branch.mergeDescription")})]}),t.jsxs("button",{type:"button",onClick:()=>I("rebase"),className:Ve("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",R==="rebase"?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(T,{name:"git-branch",className:Ve("size-4",R==="rebase"?"text-primary":"text-muted-foreground")}),t.jsx("span",{className:Ve("typography-ui-label",R==="rebase"?"text-foreground":"text-muted-foreground"),children:w("gitView.operation.rebase")})]}),t.jsx("p",{className:"typography-micro text-muted-foreground",children:w("gitView.branch.rebaseDescription")})]})]})]}),t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:R==="merge"?w("gitView.branch.branchToMergeInto",{branch:Y}):w("gitView.branch.branchToRebaseOnto")}),t.jsxs(Ps,{open:H,onOpenChange:E,modal:!1,children:[t.jsx(Fs,{asChild:!0,children:t.jsxs("button",{type:"button",className:Ve(br({size:"default"}),"w-full"),children:[t.jsx("span",{className:Ve("truncate",!P&&"text-muted-foreground"),children:P||w("gitView.branch.selectBranch")}),t.jsx(T,{name:"arrow-down-s",className:"size-4 opacity-60 shrink-0"})]})}),t.jsx(Rs,{align:"start",sideOffset:6,className:"w-[var(--anchor-width)] p-0 max-h-[min(var(--available-height),24rem)] flex flex-col overflow-hidden",children:t.jsxs(Bs,{className:"h-full min-h-0",shouldFilter:!1,children:[t.jsx(Ds,{ref:U,placeholder:w("gitView.branch.searchPlaceholder"),value:V,onValueChange:D,onKeyDown:bi}),t.jsxs(Ms,{className:"h-full min-h-0",disableHorizontal:!0,children:[t.jsx(Ts,{children:w("gitView.branch.empty")}),u.length>0&&t.jsx(qt,{heading:w("gitView.branch.localBranches"),children:u.map(Z=>t.jsx(Yt,{onSelect:()=>fe(Z),children:t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Z})},`local-${Z}`))}),u.length>0&&F.length>0?t.jsx(ea,{}):null,F.length>0&&t.jsx(qt,{heading:w("gitView.branch.remoteBranches"),children:F.map(Z=>t.jsx(Yt,{onSelect:()=>fe(Z),children:t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Z})},`remote-${Z}`))})]})]})})]})]}),P?t.jsx("div",{className:"rounded-lg bg-muted/50 p-3",children:t.jsx("p",{className:"typography-meta text-muted-foreground",children:R==="merge"?t.jsxs(t.Fragment,{children:[w("gitView.branch.summaryMergePrefix")," ",t.jsx("span",{className:"font-mono text-foreground",children:P})," ",w("gitView.branch.summaryMergeInfix")," ",t.jsx("span",{className:"font-mono text-foreground",children:Y})]}):t.jsxs(t.Fragment,{children:[w("gitView.branch.summaryRebasePrefix")," ",t.jsx("span",{className:"font-mono text-foreground",children:Y})," ",w("gitView.branch.summaryRebaseInfix")," ",t.jsx("span",{className:"font-mono text-foreground",children:P})]})})}):null,j==="dialog"?t.jsxs(Is,{className:"gap-2 pt-1",children:[t.jsx(W,{variant:"ghost",size:"sm",onClick:pe,children:w("gitView.common.cancel")}),t.jsx(W,{variant:"default",size:"sm",onClick:le,disabled:!P,className:"gap-1.5",children:R==="merge"?t.jsxs(t.Fragment,{children:[t.jsx(T,{name:"git-merge",className:"size-4"}),w("gitView.operation.merge")]}):t.jsxs(t.Fragment,{children:[t.jsx(T,{name:"git-branch",className:"size-4"}),w("gitView.operation.rebase")]})})]}):t.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[t.jsx(W,{variant:"destructive",size:"sm",onClick:pe,disabled:_,children:w("gitView.common.reset")}),t.jsx("div",{className:"flex-1"}),t.jsx(W,{variant:"default",size:"sm",onClick:le,disabled:_||!P,children:w(R==="merge"?"gitView.operation.merge":"gitView.operation.rebase")})]})]});if(j==="bare")return je;if(j==="inline"){let Z;e[38]!==w?(Z=w("gitView.branch.updateTitle"),e[38]=w,e[39]=Z):Z=e[39];let Fe;e[40]!==Z?(Fe=t.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:Z}),e[40]=Z,e[41]=Fe):Fe=e[41];let _e;e[42]!==w?(_e=w("gitView.branch.updateDescriptionPrefix"),e[42]=w,e[43]=_e):_e=e[43];let tt;e[44]!==Y?(tt=t.jsx("span",{className:"font-mono text-foreground",children:Y}),e[44]=Y,e[45]=tt):tt=e[45];let st;e[46]!==_e||e[47]!==tt?(st=t.jsxs("div",{className:"typography-micro text-muted-foreground",children:[_e," ",tt,"."]}),e[46]=_e,e[47]=tt,e[48]=st):st=e[48];let Je;e[49]!==Fe||e[50]!==st?(Je=t.jsx("header",{className:"border-b border-border/40 px-0 py-3",children:t.jsxs("div",{className:"space-y-1",children:[Fe,st]})}),e[49]=Fe,e[50]=st,e[51]=Je):Je=e[51];let at;e[52]!==je?(at=t.jsx("div",{className:"pt-3",children:je}),e[52]=je,e[53]=at):at=e[53];let it;return e[54]!==Je||e[55]!==at?(it=t.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[Je,at]}),e[54]=Je,e[55]=at,e[56]=it):it=e[56],it}let Re;e[57]!==N?(Re=N?t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(T,{name:"git-merge",className:"size-4"}),e[57]=N,e[58]=Re):Re=e[58];let Ce;e[59]!==w?(Ce=w("gitView.branch.mergeRebase"),e[59]=w,e[60]=Ce):Ce=e[60];let Ee;e[61]!==Ce?(Ee=t.jsx("span",{children:Ce}),e[61]=Ce,e[62]=Ee):Ee=e[62];let K;e[63]!==se||e[64]!==_||e[65]!==Re||e[66]!==Ee?(K=t.jsx(Zt,{asChild:!0,children:t.jsxs(W,{variant:"outline",size:"sm",className:"gap-1.5",onClick:se,disabled:_,children:[Re,Ee]})}),e[63]=se,e[64]=_,e[65]=Re,e[66]=Ee,e[67]=K):K=e[67];let xe;e[68]!==w?(xe=w("gitView.branch.mergeRebaseTooltip"),e[68]=w,e[69]=xe):xe=e[69];let Te;e[70]!==xe?(Te=t.jsx(Xt,{sideOffset:8,children:xe}),e[70]=xe,e[71]=Te):Te=e[71];let Ge;e[72]!==K||e[73]!==Te?(Ge=t.jsxs(Qt,{children:[K,Te]}),e[72]=K,e[73]=Te,e[74]=Ge):Ge=e[74];let Ie;e[75]!==ue||e[76]!==S?(Ie=Z=>{Z?S(!0):ue()},e[75]=ue,e[76]=S,e[77]=Ie):Ie=e[77];let Ne;e[78]!==w?(Ne=w("gitView.branch.updateTitle"),e[78]=w,e[79]=Ne):Ne=e[79];let Se;e[80]!==Ne?(Se=t.jsx(pt,{children:Ne}),e[80]=Ne,e[81]=Se):Se=e[81];let Be;e[82]!==X||e[83]!==N||e[84]!==R||e[85]!==ee||e[86]!==w||e[87]!==Y?(Be=N?w(ee?X?"gitView.branch.operationFailed":"gitView.branch.operationCompleted":R==="merge"?"gitView.branch.mergingInProgress":"gitView.branch.rebasingInProgress"):t.jsxs(t.Fragment,{children:[w("gitView.branch.dialogDescriptionPrefix")," ",t.jsx("span",{className:"font-mono text-foreground",children:Y}),"."]}),e[82]=X,e[83]=N,e[84]=R,e[85]=ee,e[86]=w,e[87]=Y,e[88]=Be):Be=e[88];let Pe;e[89]!==Be?(Pe=t.jsx(yt,{children:Be}),e[89]=Be,e[90]=Pe):Pe=e[90];let ke;e[91]!==Se||e[92]!==Pe?(ke=t.jsxs(ft,{children:[Se,Pe]}),e[91]=Se,e[92]=Pe,e[93]=ke):ke=e[93];let we;e[94]!==je||e[95]!==ke?(we=t.jsxs(gt,{className:"max-w-md",children:[ke,je]}),e[94]=je,e[95]=ke,e[96]=we):we=e[96];let De;e[97]!==B||e[98]!==Ie||e[99]!==we?(De=t.jsx(ht,{open:B,onOpenChange:Ie,children:we}),e[97]=B,e[98]=Ie,e[99]=we,e[100]=De):De=e[100];let Le;return e[101]!==Ge||e[102]!==De?(Le=t.jsxs(t.Fragment,{children:[Ge,De]}),e[101]=Ge,e[102]=De,e[103]=Le):Le=e[103],Le};function gi(i){return i.status==="done"||i.status==="error"}function fi(i){return i.status==="error"}function pi(i){return i.slice(i.indexOf("/")+1)}function xi(i){return[i]}function wi(i){return[i]}function yi(i,e){return t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsxs("div",{className:"mt-0.5 shrink-0",children:[i.status==="running"&&t.jsx(T,{name:"loader-4",className:"size-3.5 animate-spin text-primary"}),i.status==="done"&&t.jsx(T,{name:"check",className:"size-3.5 text-success"}),i.status==="error"&&t.jsx(T,{name:"close",className:"size-3.5 text-destructive"}),i.status==="pending"&&t.jsx("div",{className:"size-3.5 rounded-full border border-muted-foreground/30"})]}),t.jsx("span",{className:Ve("typography-micro",i.status==="error"&&"text-destructive",i.status==="done"&&"text-muted-foreground",i.status==="running"&&"text-foreground",i.status==="pending"&&"text-muted-foreground/60"),children:i.message})]},e)}function bi(i){return i.stopPropagation()}const vi=({runMutation:i,onMutationComplete:e,onMutationError:n,onPathsComplete:r,scheduleFlush:v})=>{const h=[];let p=!1;return{enqueue:m=>{const x=h[h.length-1];if(x?.directory===m.directory&&x.direction===m.direction){m.paths.forEach(M=>x.paths.add(M));return}h.push(m)},flush:()=>{if(p)return;const m=h.shift();if(!m)return;p=!0;const x={directory:m.directory,direction:m.direction,paths:Array.from(m.paths),rollback:m.rollback};(async()=>{try{await i(x),e(x)}catch(M){n(x,M)}finally{r(x.paths),p=!1,h.length>0&&v()}})()},clear:()=>{h.length=0},size:()=>h.length,isRunning:()=>p}},ji=15e3,Ci=40,Ni=20,wr={feat:":sparkles:",feature:":sparkles:",fix:":bug:",bug:":bug:",hotfix:":ambulance:",docs:":memo:",documentation:":memo:",style:":lipstick:",refactor:":recycle:",perf:":zap:",performance:":zap:",test:":white_check_mark:",tests:":white_check_mark:",build:":construction_worker:",ci:":green_heart:",chore:":wrench:",revert:":rewind:",wip:":construction:",security:":lock:",release:":bookmark:",merge:":twisted_rightwards_arrows:",mv:":truck:",move:":truck:",rename:":truck:",remove:":fire:",delete:":fire:",add:":sparkles:",create:":sparkles:",implement:":sparkles:",update:":recycle:",improve:":zap:",optimize:":zap:",upgrade:":arrow_up:",downgrade:":arrow_down:",deploy:":rocket:",init:":tada:",initial:":tada:"},Si=(i,e)=>{const n=i.toLowerCase(),r=/^([a-z]+)(?:\(.*\))?!?:/,v=n.match(r);if(v){const f=v[1],m=wr[f];if(m)return e.find(x=>x.code===m)||null}const h=n.split(" ")[0],p=wr[h];return p&&e.find(f=>f.code===p)||null},ki=20,jt=new Map,Vi=(i,e)=>{if(jt.delete(i),jt.set(i,e),jt.size>ki){const n=jt.keys().next().value;n!==void 0&&jt.delete(n)}},nt=i=>(i||"").replace(/\\/g,"/").replace(/\/+$/,""),yr=i=>{const e=i.index?.trim();return!!(e&&e!=="?")},Ii=i=>{const e=i.working_dir?.trim(),n=i.index?.trim();return!!(e||n==="?")},Wl=({isActive:i})=>{const{t:e}=et(),{git:n}=ta(),r=sa(),[v,h]=l.useState(null),[p,f]=l.useState(!1),m=Xe(s=>s.currentSessionId),x=Xe(s=>s.newSessionDraft),M=Xe(s=>s.setDraftBootstrapPendingDirectory),y=Xe(s=>s.worktreeMetadata),k=Xe(s=>s.availableWorktrees),L=nt(r),N=l.useMemo(()=>{if(!L)return;const s=k.find(a=>nt(a.path)===L);if(s)return s;for(const a of y.values())if(nt(a.path)===L)return a},[k,L,y]),O=l.useMemo(()=>{if(m)return y.get(m)??N;if(x?.open)return N},[m,N,x?.open,y]),{profiles:j,globalIdentity:w,defaultGitIdentityId:B,loadProfiles:S,loadGlobalIdentity:R,loadDefaultGitIdentityId:I}=Ia(or(s=>({profiles:s.profiles,globalIdentity:s.globalIdentity,defaultGitIdentityId:s.defaultGitIdentityId,loadProfiles:s.loadProfiles,loadGlobalIdentity:s.loadGlobalIdentity,loadDefaultGitIdentityId:s.loadDefaultGitIdentityId}))),P=ra(r??null),g=na(r??null),H=aa(s=>m?s.getAttachment(m):void 0),E=H?ia(H):[],V=H&&!H.degraded&&!H.legacy?H.worktreeRoot??void 0:void 0,D=ja(r,O,g?.current??void 0),U=oa(r??null),$=la(r??null),_=ca(r??null),Y=da(r??null),ee=ua(r??null),{setActiveDirectory:X,fetchAll:oe,ensureAll:de,fetchStatus:Q,fetchBranches:te,fetchLog:u,setLogMaxCount:d,fetchIdentity:F,prefetchDiffs:A,clearDiffCache:q,moveStatusPathsOptimistically:ie,restoreStatus:se,bumpIndexRevision:G}=ma(or(s=>({setActiveDirectory:s.setActiveDirectory,fetchAll:s.fetchAll,ensureAll:s.ensureAll,fetchStatus:s.fetchStatus,fetchBranches:s.fetchBranches,fetchLog:s.fetchLog,setLogMaxCount:s.setLogMaxCount,fetchIdentity:s.fetchIdentity,prefetchDiffs:s.prefetchDiffs,clearDiffCache:s.clearDiffCache,moveStatusPathsOptimistically:s.moveStatusPathsOptimistically,restoreStatus:s.restoreStatus,bumpIndexRevision:s.bumpIndexRevision}))),fe=Pt(s=>s.isMobile),re=Pt(s=>s.openContextDiff),le=Pt(s=>s.openContextSurface),ve=g?.current??null,pe=ha(s=>!r||!ve?null:ga(s.entries,r,ve)),ue=Pt(s=>s.navigateToDiff),me=l.useRef(null),he=l.useRef(null),ge=l.useRef(null),ce=l.useRef(null),ze=l.useRef(!0);l.useEffect(()=>()=>{ze.current=!1},[]);const $e=l.useCallback(()=>{he.current!==null&&(window.clearTimeout(he.current),he.current=null)},[]),je=l.useCallback(s=>{$e(),he.current=window.setTimeout(()=>{he.current=null,nt(s)===nt(r)&&Q(s,n,{silent:!0})},ji)},[$e,r,Q,n]);l.useEffect(()=>$e,[$e]);const Re=l.useCallback(()=>{ge.current!==null&&(window.clearTimeout(ge.current),ge.current=null)},[]),Ce=l.useCallback(()=>{ge.current===null&&(ge.current=window.setTimeout(()=>{ge.current=null,ce.current?.()},0))},[]),Ee=l.useCallback(async(s,a,o)=>{if(a==="stage"){if(n.stageGitFiles){await n.stageGitFiles(s,o);return}await Promise.all(o.map(c=>n.stageGitFile(s,c)));return}if(n.unstageGitFiles){await n.unstageGitFiles(s,o);return}await Promise.all(o.map(c=>n.unstageGitFile(s,c)))},[n]),K=l.useMemo(()=>vi({runMutation:({directory:s,direction:a,paths:o})=>Ee(s,a,o),onMutationComplete:({directory:s})=>{G(s),je(s)},onMutationError:({directory:s,direction:a,rollback:o},c)=>{o?.(),G(s),je(s);const C=e(a==="stage"?"gitView.toast.stageFileFailed":"gitView.toast.unstageFileFailed");b.error(c instanceof Error?c.message:C)},onPathsComplete:s=>{zs(a=>{const o=new Set(a);return s.forEach(c=>o.delete(c)),o})},scheduleFlush:Ce}),[G,Ee,Ce,je,e]);l.useEffect(()=>(ce.current=K.flush,()=>{ce.current=null}),[K]),l.useEffect(()=>()=>K.clear(),[K]),l.useEffect(()=>Re,[Re]),l.useEffect(()=>{if(!i)return;if(!r){h(null),f(!1);return}let s=!1,a=null;const o=async()=>{try{const c=await va(r);if(s)return;h(c.status),c.status==="pending"&&(a=window.setTimeout(()=>{o()},500))}catch{s||h(null)}};return o(),()=>{s=!0,a!==null&&window.clearTimeout(a)}},[i,r]),l.useEffect(()=>{const s=me.current;me.current=v,!(!r||!n)&&(s==="pending"&&v==="ready"&&(f(!0),oe(r,n).finally(()=>{window.setTimeout(()=>{f(!1)},1200)})),v==="failed"&&(M(null),f(!1)))},[r,oe,n,M,v]);const xe=nt(x?.bootstrapPendingDirectory??null),Te=!!(r&&xe&&xe===nt(r)),Ie=!!(r&&(v==="pending"||Te))||p,Ne=l.useMemo(()=>r?jt.get(r)??null:null,[r]),Se=fa(s=>s.settingsGitmojiEnabled),[Be,Pe]=l.useState(null),{gitmojis:ke}=La(Se);l.useEffect(()=>{const s=V||D?.projectDirectory;if(!s){Pe(null);return}let a=!1;return pa(s).then(o=>{if(a)return;const c=o.trim();Pe(c&&c!=="HEAD"?c:null)}).catch(()=>{a||Pe(null)}),()=>{a=!0}},[V,D?.projectDirectory]);const[we,De]=l.useState(Ne?.commitMessage??""),[Le,Z]=l.useState([]),[Fe,_e]=l.useState(!1),tt=l.useRef(null),[st,Je]=l.useState(null),[at,it]=l.useState(!1),[Es,Ls]=l.useState(null),[Ke,Sr]=l.useState(25),[kr,As]=l.useState(!1),{triggerFireworks:Vr}=Ca(),Os=l.useRef(new Map),Bt=l.useRef(0),es=l.useCallback(()=>{Bt.current+=1,ze.current&&As(!0)},[]),ts=l.useCallback(()=>{Bt.current=Math.max(0,Bt.current-1),ze.current&&Bt.current===0&&As(!1)},[]),[ss,Dt]=l.useState(new Set),[Ir,zs]=l.useState(new Set),[rs,Gs]=l.useState(!1),[Pr,Fr]=l.useState(0),[Rr,_s]=l.useState(!1),[ns,$s]=l.useState(Ne?.generatedHighlights??[]),Br=Ir.size>0||K.size()>0||K.isRunning(),Hs=l.useCallback(()=>{const s=tt.current;s&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{s.scrollTo({top:s.scrollHeight,behavior:"smooth"})})})},[]),as=V||D?.projectDirectory||null,is=g?.current||null,Dr=l.useMemo(()=>{const s=g?.tracking;return s?s.startsWith("origin/"):!0},[g?.tracking]),Ws=l.useMemo(()=>{const s=D?.createdFromBranch,a=typeof s=="string"?s.trim():"",o=typeof g?.current=="string"?g.current.trim():"",c=typeof Be=="string"?Be.trim():"";return a?a===o&&a.startsWith("opencode/")&&c.length>0&&c!==a?c:a:c||o||"HEAD"},[D?.createdFromBranch,g,Be]),Mt=l.useCallback(()=>{$s([])},[]),[os,Mr]=l.useState(new Set),[Tt,Tr]=l.useState(new Map),[Et,ls]=l.useState(new Set),cs=l.useRef(Tt),St=l.useRef(Et),[Er,bt]=l.useState(null),[xt,ds]=l.useState(null),[Us,Js]=l.useState(""),[Me,Lt]=l.useState(null),[Lr,Ks]=l.useState(!1),[Ar,qs]=l.useState(!1),[us,ms]=l.useState([]),[Or,Ys]=l.useState(null),[Qs,hs]=l.useState(null),[zr,At]=l.useState([]),[Gr,qe]=l.useState(!1),[_r,Qe]=l.useState([]),[Ot,Ze]=l.useState("merge"),[$r,gs]=l.useState(null),[fs,Zs]=l.useState(!1),[ps,Hr]=l.useState(100),[Wr,Ur]=l.useState(0),Ye=l.useMemo(()=>m?`openchamber.conflict:${m}`:null,[m]),rt=l.useCallback((s,a,o)=>{if(!Ye||typeof window>"u")return;const c={directory:s,conflictFiles:a,operation:o};window.localStorage.setItem(Ye,JSON.stringify(c))},[Ye]),He=l.useCallback(()=>{!Ye||typeof window>"u"||window.localStorage.removeItem(Ye)},[Ye]);l.useEffect(()=>{if(!Ye||typeof window>"u"||!r)return;const s=window.localStorage.getItem(Ye);if(s)try{const a=JSON.parse(s);if(a.directory!==r){window.localStorage.removeItem(Ye);return}Qe(a.conflictFiles??[]),Ze(a.operation??"merge"),qe(!0)}catch{window.localStorage.removeItem(Ye)}},[Ye,r]);const[Jr,xs]=l.useState(!1),[ws,Xs]=l.useState("merge"),[ys,er]=l.useState(""),Kr=l.useCallback(s=>{xa(s).then(a=>{if(a.ok){b.success(e("gitView.toast.commitHashCopied"));return}b.error(e("gitView.toast.copyFailed"))})},[e]),qr=l.useCallback(s=>{Mr(a=>{const o=new Set(a);return o.has(s)?o.delete(s):o.add(s),o})},[]);l.useEffect(()=>{cs.current=Tt},[Tt]),l.useEffect(()=>{St.current=Et},[Et]),l.useEffect(()=>{if(!r||!n)return;const s=Array.from(os).filter(o=>!cs.current.has(o)&&!St.current.has(o));if(s.length===0)return;let a=!1;return ls(o=>{const c=new Set(o);for(const C of s)c.add(C);return St.current=c,c}),Promise.all(s.map(o=>n.getCommitFiles(r,o).then(c=>({hash:o,files:c.files})).catch(c=>(console.error("Failed to fetch commit files:",c),{hash:o,files:[]})))).then(o=>{a||(Tr(c=>{const C=new Map(c);for(const{hash:z,files:ae}of o)C.set(z,ae);return cs.current=C,C}),ls(c=>{const C=new Set(c);for(const{hash:z}of o)C.delete(z);return St.current=C,C}))}),()=>{a=!0,ls(o=>{let c=!1;const C=new Set(o);for(const z of s)C.delete(z)&&(c=!0);return c?(St.current=C,C):o})}},[os,r,n]),l.useEffect(()=>{r&&Vi(r,{directory:r,commitMessage:we,generatedHighlights:ns})},[we,r,ns]),l.useEffect(()=>{i&&(S(),R(),I())},[i,S,R,I]),l.useEffect(()=>{if(!i)return;if(!r||!n?.getRemoteUrl){ds(null);return}let s=!1;return n.getRemoteUrl(r).then(a=>{s||ds(a)}).catch(()=>{s||ds(null)}),()=>{s=!0}},[i,r,n]);const zt=l.useCallback(async()=>{if(!r||!n?.getRemotes){ms([]);return}try{const s=await n.getRemotes(r);ze.current&&ms(s)}catch{ze.current&&ms([])}},[r,n]);l.useEffect(()=>{i&&zt()},[i,zt]),l.useEffect(()=>{i&&r&&(X(r),de(r,n))},[i,r,X,de,n]),l.useEffect(()=>{if(i&&r)return wa.onGitRefreshHint(s=>{nt(s.directory)===nt(r)&&(s.paths?.length&&q(r,s.paths),Q(r,n,{silent:!0}))})},[i,q,r,Q,n]);const ne=l.useCallback(async(s=!0)=>{if(r)try{await Promise.all([Q(r,n),te(r,n)])}catch(a){if(s){const o=a instanceof Error?a.message:e("gitView.toast.refreshRepositoryFailed");b.error(o)}}},[r,n,Q,te,e]),ye=l.useCallback(async()=>{r&&await u(r,n,Ke)},[r,n,u,Ke]),bs=l.useCallback(async()=>{r&&await F(r,n)},[r,n,F]);l.useEffect(()=>{if(!i||!r||!n?.hasLocalIdentity||P!==!0)return;const s=typeof B=="string"?B.trim():"";if(!s||s==="global"||Os.current.get(r)===s)return;let o=!1;return(async()=>{try{const C=await n.hasLocalIdentity?.(r);if(o||C===!0)return;es(),await n.setGitIdentity(r,s),Os.current.set(r,s),await bs()}catch(C){console.warn("Failed to auto-apply default git identity:",C)}finally{o||ts()}})(),()=>{o=!0}},[i,es,r,B,ts,n,P,bs]);const ot=l.useMemo(()=>g?[...g.files??[]].sort((a,o)=>a.path.localeCompare(o.path)):[],[g]),We=l.useMemo(()=>ot.filter(yr),[ot]),vs=l.useMemo(()=>ot.filter(Ii),[ot]);l.useEffect(()=>{if(!r||ot.length===0)return;const s=[],a=new Set,o=C=>{!C||a.has(C)||(a.add(C),s.push(C))};if(We.forEach(C=>o(C.path)),Le.forEach(o),ot.slice(0,Ni).forEach(C=>o(C.path)),s.length===0)return;const c=window.setTimeout(()=>{A(r,n,s,{maxFiles:Ci})},120);return()=>{window.clearTimeout(c)}},[ot,r,n,A,We,Le]);const tr=s=>s?.pushed[0]?.remote||g?.tracking?.split("/")[0]||Ue.find(a=>a.name==="origin")?.name||Ue[0]?.name||"origin",sr=async(s,a)=>{if(r){Je(s);try{const o=c=>{const C=`${c.name}/`,z=g?.tracking?.startsWith(C)?g.tracking.slice(C.length):void 0;return{remote:c.name,branch:z,rebase:!0}};if(s==="fetch"){if(!a)throw new Error("No remote available for fetch");await n.gitFetch(r,{remote:a.name}),b.success(e("gitView.toast.fetchedFromRemote",{name:a.name}))}else if(s==="pull"){if(!a)throw new Error("No remote available for pull");const c=await n.gitPull(r,o(a));b.success(c.files.length===1?e("gitView.toast.pulledFilesSingle",{count:c.files.length,name:a.name}):e("gitView.toast.pulledFilesPlural",{count:c.files.length,name:a.name}))}else if(s==="push"){const c=await n.gitPush(r);b.success(e("gitView.toast.pushedToUpstream",{name:tr(c)}))}else if(s==="sync"){if(!a)throw new Error("No remote available for sync");let c=0,C=!1;await n.gitFetch(r,{remote:a.name});const z=await n.getGitStatus(r);if((z.behind??0)>0){if((z.files?.length??0)>0){b.error(e("gitView.toast.commitOrStashBeforeSync"));return}c=(await n.gitPull(r,o(a))).files.length}((await n.getGitStatus(r)).ahead??0)>0&&(await n.gitPush(r),C=!0),c>0&&C?b.success(c===1?e("gitView.toast.syncedPulledSingleAndPushed",{count:c,name:a.name}):e("gitView.toast.syncedPulledPluralAndPushed",{count:c,name:a.name})):c>0?b.success(c===1?e("gitView.toast.pulledFilesSingle",{count:c,name:a.name}):e("gitView.toast.pulledFilesPlural",{count:c,name:a.name})):C?b.success(e("gitView.toast.pushedToUpstream",{name:a.name})):b.success(e("gitView.toast.alreadyUpToDate"))}await ne(!1),await ye()}catch(o){const c=o instanceof Error?o.message:e("gitView.toast.syncActionFailed",{action:s==="sync"?e("gitView.sync.syncChanges"):s==="pull"?e("gitView.sync.pull"):s});b.error(c)}finally{Je(null)}}},Yr=l.useCallback(async s=>{if(!r)return;const a=s.name.trim();if(!a){b.error(e("gitView.toast.remoteNameRequired"));return}if(a==="origin"){b.error(e("gitView.toast.cannotRemoveOriginRemote"));return}Ys(a);try{await n.removeRemote(r,{remote:a}),b.success(e("gitView.toast.removedRemote",{name:a})),await Promise.all([ne(!1),zt()])}catch(o){const c=o instanceof Error?o.message:`Failed to remove ${a}`;b.error(c)}finally{Ys(null)}},[r,n,zt,ne,e]),rr=async(s={})=>{if(!r)return;if(!we.trim()){b.error(e("gitView.toast.enterCommitMessage"));return}const a=We.map(c=>c.path).sort();if(a.length===0){b.error(e("gitView.toast.stageFileToCommit"));return}const o=s.pushAfter?"commitAndPush":"commit";Ls(o);try{if(await n.createGitCommit(r,we.trim(),{files:a,stageFiles:[]}),G(r),b.success(e("gitView.toast.commitCreated")),De(""),Mt(),await ne(),s.pushAfter){const c=g?.tracking?.split("/")[0],C=Ue.find(In=>In.name===c)??Ue[0];if(!C)throw new Error(e("mobile.changes.noRemote"));Je("sync");const z=`${C.name}/`,ae=g?.tracking?.startsWith(z)?g.tracking.slice(z.length):void 0;await n.gitFetch(r,{remote:C.name});const J=await n.getGitStatus(r);if((J.behind??0)>0){if((J.files?.length??0)>0){b.error(e("gitView.toast.commitOrStashBeforeSync")),await ne(!1);return}await n.gitPull(r,{remote:C.name,branch:ae,rebase:!0})}const Oe=await n.getGitStatus(r);let vt;(Oe.ahead??0)>0&&(vt=await n.gitPush(r)),b.success(e("gitView.toast.pushedToUpstream",{name:tr(vt)})),Vr(),await ne(!1)}else await ne(!1);await ye(),Fr(c=>c+1)}catch(c){const C=c instanceof Error?c.message:e("gitView.toast.createCommitFailed");b.error(C)}finally{Ls(null),s.pushAfter&&Je(null)}},Qr=l.useCallback(async()=>{if(!r)return;const s=We.map(a=>a.path).sort();if(s.length===0){b.error(e("gitView.toast.stageFileToDescribe"));return}console.error("[git-generation][browser] generate button clicked",{directory:r,selectedFiles:s.length}),_s(!0);try{const{message:a}=await ya(r,s),o=a.subject?.trim()??"",c=Array.isArray(a.highlights)?a.highlights:[];if(o){let C=o;if(Se&&ke.length>0){const z=Si(o,ke);if(z){const{code:ae,emoji:J}=z;!o.startsWith(ae)&&!o.startsWith(J)&&(C=`${ae} ${o}`)}}De(C)}$s(c),Hs()}catch(a){console.error("[git-generation][browser] GitView generate handler failed",{message:a instanceof Error?a.message:String(a),error:a});const o=a instanceof Error?a.message:e("gitView.toast.generateCommitMessageFailed");b.error(o)}finally{_s(!1)}},[r,We,Se,ke,Hs,e]),js=s=>s.reason==="attention"?`${s.attentionReason} in progress`:s.reason==="missing"?"worktree is missing":"worktree is invalid",Zr=async(s,a)=>{if(!r||!g)return;const o=Ss(H);if(o.length>0){b.error(e("gitView.toast.cannotCreateBranch",{reason:js(o[0])}));return}const c=g.current??null,C=a?.name??"origin";try{await n.createBranch(r,s,c??"HEAD"),b.success(e("gitView.toast.createdBranch",{name:s})),await n.checkoutBranch(r,s);let z=!1;try{await n.gitPush(r,{remote:C,branch:s,options:["--set-upstream"]}),z=!0}catch(ae){const J=ae instanceof Error?ae.message:`Unable to push new branch to ${C}.`;b.warning(e("gitView.toast.branchCreatedLocally"),{description:t.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",J]})})}await ne(),await ye(),z&&b.success(e("gitView.toast.upstreamSet",{branch:s,remote:C}))}catch(z){const ae=z instanceof Error?z.message:e("gitView.toast.createBranchFailed");throw b.error(ae),z}},Xr=async(s,a)=>{if(!r)return;const o=Ss(H);if(o.length>0){b.error(e("gitView.toast.cannotRenameBranch",{reason:js(o[0])}));return}try{await n.renameBranch(r,s,a),b.success(e("gitView.toast.renamedBranch",{oldName:s,newName:a})),await ne(),await ye()}catch(c){const C=c instanceof Error?c.message:e("gitView.toast.renameBranchFailed",{oldName:s,newName:a});b.error(C)}},en=async s=>{if(!r)return;const a=Ss(H);if(a.length>0){b.error(e("gitView.toast.cannotCheckout",{reason:js(a[0])}));return}const o=s.replace(/^remotes\//,"");if(g?.current!==o)try{const c=await n.checkoutBranch(r,o);b.success(e("gitView.toast.checkedOut",{name:c?.branch||o})),await ne(),await ye()}catch(c){const C=c instanceof Error?c.message:e("gitView.toast.checkoutFailed",{name:o});b.error(C)}},tn=async s=>{if(r){es();try{await n.setGitIdentity(r,s.id),b.success(e("gitView.toast.appliedIdentity",{name:s.name})),await bs()}catch(a){const o=a instanceof Error?a.message:e("gitView.toast.applyIdentityFailed");b.error(o)}finally{ts()}}},kt=l.useMemo(()=>U?.all?U.all.filter(s=>!s.startsWith("remotes/")).sort():[],[U]),lt=l.useMemo(()=>U?.all?U.all.filter(s=>s.startsWith("remotes/")).map(s=>s.replace(/^remotes\//,"")).sort():[],[U]),Ue=l.useMemo(()=>{if(us.length>0)return us;const s=new Set,a=g?.tracking?.trim();a&&a.includes("/")&&s.add(a.split("/")[0]);for(const o of lt){const c=o.indexOf("/");c>0&&s.add(o.slice(0,c))}return s.size===0&&xt&&s.add("origin"),Array.from(s).map(o=>({name:o,fetchUrl:xt??"",pushUrl:xt??""}))},[us,lt,xt,g?.tracking]),ct=g?.current??null,nr=l.useMemo(()=>{const s=g?.tracking?.trim().split("/")[0];return(s&&U?.defaultBranches?.[s])??U?.defaultBranches?.origin},[U,g?.tracking]),wt=l.useMemo(()=>Na({remoteNames:new Set(Ue.map(s=>s.name)),localBranches:kt,worktreeCreatedFromBranch:D?.createdFromBranch,rootBranchHint:Be,defaultBranch:nr,headBranch:ct}),[ct,nr,Ue,kt,Be,D?.createdFromBranch]),sn=l.useMemo(()=>Ue.map(o=>o.name).map(o=>`${o}/${wt}`).find(o=>lt.includes(o))??wt,[wt,Ue,lt]),rn=l.useMemo(()=>{const s=new Map;w&&s.set(w.id,w);let a=null;if(xt)try{let o=xt.trim();o.startsWith("git@")&&(o=`https://${o.slice(4).replace(":","/")}`),o.endsWith(".git")&&(o=o.slice(0,-4));const c=new URL(o);a=c.hostname+c.pathname}catch{}for(const o of j){if(o.authType!=="token"){s.set(o.id,o);continue}const c=o.host;if(!c){s.set(o.id,o);continue}if(!c.includes("/")){s.set(o.id,o);continue}a&&a===c&&s.set(o.id,o)}return Array.from(s.values())},[j,w,xt]),nn=l.useMemo(()=>{if(_?.userName&&_?.userEmail){const s=j.find(a=>a.userName===_.userName&&a.userEmail===_.userEmail);return s||(w&&w.userName===_.userName&&w.userEmail===_.userEmail?w:{id:"local-config",name:_.userName,userName:_.userName,userEmail:_.userEmail,sshKey:_.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return w??null},[_,j,w]),an=We.length,on=Y||st!==null||Es!==null,ln=!!(D&&as&&is&&Dr),ar=!!ct,dt=ln&&as&&is&&D?{repoRoot:as,sourceBranch:is,worktreeMetadata:D}:null;l.useEffect(()=>{if(!r||!n||!$?.all?.length||!ct||!wt||ct===wt){bt(null);return}let s=!1;return(async()=>{try{const o=await n.getGitLog(r,{from:wt,to:"HEAD",maxCount:Ke});if(s)return;const c=new Set((o?.all??[]).map(z=>z.hash).filter(z=>typeof z=="string"&&z.length>0));if(c.size===0){bt(null);return}const C=$.all.findIndex(z=>!c.has(z.hash));if(C===0){bt(null);return}if(C===-1){bt({insertBeforeIndex:$.all.length,branchName:ct,direction:"up"});return}bt({insertBeforeIndex:C,branchName:ct,direction:"up"})}catch{s||bt(null)}})(),()=>{s=!0}},[wt,ct,r,n,$,Ke]),l.useEffect(()=>{gs(null)},[r]),l.useEffect(()=>{if(Me!=="graph"||!r){Me!=="graph"&&gs(null);return}let s=!1;return Zs(!0),n.getGitLog(r,{maxCount:ps,all:!0}).then(a=>{s||gs(a)}).catch(a=>{console.error("Failed to fetch graph log:",a)}).finally(()=>{s||Zs(!1)}),()=>{s=!0}},[Me,r,ps,Wr,n]);const Vt=l.useCallback((s,a)=>{if(!r||s.length===0)return;const o=Array.from(new Set(s));zs(C=>{const z=new Set(C);return o.forEach(ae=>z.add(ae)),z});const c=ie(r,o,a);K.enqueue({directory:r,direction:a,paths:new Set(o),rollback:()=>se(r,c)}),Ce()},[r,K,ie,se,Ce]),Cs=l.useCallback(async s=>{if(r){Dt(a=>{const o=new Set(a);return o.add(s),o});try{await n.revertGitFile(r,s,{scope:"working"}),b.success(e("gitView.toast.revertedFile",{path:s})),await ne(!1)}catch(a){const o=a instanceof Error?a.message:e("gitView.toast.revertFailed");b.error(o)}finally{Dt(a=>{const o=new Set(a);return o.delete(s),o})}}},[r,ne,n,e]),Gt=l.useCallback(async(s,a,o="all")=>{if(!r||s.length===0)return;const c=Array.from(new Set(s));if(rs||c.some(J=>ss.has(J)))return;const C=new Set(We.map(J=>J.path)),z=o==="all"&&c.some(J=>C.has(J));a&&Gs(!0),Dt(J=>{const Oe=new Set(J);return c.forEach(vt=>Oe.add(vt)),Oe});const ae=[];try{if(await Promise.all(c.map(async J=>{try{await n.revertGitFile(r,J,{scope:o})}catch(Oe){ae.push({path:J,message:Oe instanceof Error?Oe.message:e("gitView.toast.revertFailed")})}})),z&&ae.length<c.length&&G(r),await ne(!1),ae.length===0)b.success(c.length===1?e("gitView.toast.revertedFilesSingle",{count:c.length}):e("gitView.toast.revertedFilesPlural",{count:c.length}));else if(ae.length===c.length)b.error(ae[0]?.message||e("gitView.toast.revertFailed"));else{const J=c.length-ae.length;b.warning(J===1?e("gitView.toast.revertedSomeSingle",{success:J,failed:ae.length}):e("gitView.toast.revertedSomePlural",{success:J,failed:ae.length}))}}finally{Dt(J=>{const Oe=new Set(J);return c.forEach(vt=>Oe.delete(vt)),Oe}),a&&Gs(!1)}},[G,r,n,rs,ne,ss,We,e]),cn=l.useCallback(async s=>{await Gt(s,!0)},[Gt]),dn=l.useCallback(async s=>{await Gt(s,!1,"working")},[Gt]),Ns=l.useCallback((s,a)=>{if(r&&!fe){re(r,s,a);return}ue(s,a)},[r,fe,ue,re]),un=l.useCallback(()=>it(!0),[]),mn=l.useMemo(()=>{const s=[];return We.length>0&&s.push({id:"staged",title:e("gitView.changes.stagedTitle"),entries:We,actionSymbol:"-",actionAllLabel:e("gitView.changes.unstageAllAria"),getActionLabel:a=>e("gitView.changes.unstageFileAria",{path:a}),onActionFile:a=>{Vt([a],"unstage")},onActionAll:a=>{Vt(a,"unstage")},onViewDiff:a=>Ns(a,!0),onRevertFile:Cs,showRevertActions:!1,accent:!0}),vs.length>0&&s.push({id:"unstaged",title:e("gitView.changes.title"),entries:vs,actionSymbol:"+",actionAllLabel:e("gitView.changes.stageAllAria"),getActionLabel:a=>e("gitView.changes.stageFileAria",{path:a}),onActionFile:a=>{Vt([a],"stage")},onActionAll:a=>{Vt(a,"stage")},onViewDiff:a=>Ns(a,!1),onRevertFile:Cs}),s},[Cs,Ns,Vt,We,e,vs]),hn=l.useCallback(s=>{if(s.length===0)return;const a=s.map(o=>o.trim()).filter(Boolean);if(a.length===0){Mt();return}De(o=>{const c=o.trim(),C=c.length>0?`
4
+
5
+ `:"";return`${c}${C}${a.join(`
6
+ `)}`.trim()}),Mt()},[Mt]),gn=l.useCallback((s,a)=>{const o=a||s;De(c=>{const C=c.trimStart();return C.startsWith(s)||a&&C.startsWith(a)?c:`${o.endsWith(" ")?o:`${o} `}${c}`.trimStart()}),Js(""),_e(!1)},[]),_t=l.useCallback(s=>{const a=s instanceof Error?s.message.toLowerCase():"";return a.includes("uncommitted changes")||a.includes("local changes")||a.includes("your local changes would be overwritten")||a.includes("please commit your changes or stash them")||a.includes("cannot rebase: you have unstaged changes")||a.includes("error: cannot pull with rebase")},[]),ut=l.useCallback((s,a)=>{At(o=>[...o,{message:s,status:a,timestamp:Date.now()}])},[]),Ae=l.useCallback((s,a)=>{At(o=>{if(o.length===0)return o;const c=[...o];return c[c.length-1]={...c[c.length-1],status:s,...a?{message:a}:{}},c})},[]),$t=l.useCallback(()=>{At([])},[]),fn=l.useCallback(()=>{At([]),hs(null)},[]),Ht=l.useCallback(s=>{const a=s.trim(),o=new Set(Ue.map(C=>C.name)),c=a.indexOf("/");if(c>0){const C=a.slice(0,c),z=a.slice(c+1);if(o.has(C)&&z)return{branch:a,remote:C,remoteBranch:z}}for(const C of Ue){const z=`${C.name}/${a}`;if(lt.includes(z))return{branch:z,remote:C.name,remoteBranch:a}}return{branch:a,remote:null,remoteBranch:null}},[Ue,lt]),pn=l.useCallback(async s=>{if(!r)return;hs("merge"),$t();const a=g?.current,o=Ht(s);try{o.remote&&o.remoteBranch&&(ut(`Fetching ${o.remote}/${o.remoteBranch}...`,"running"),await n.gitFetch(r,{remote:o.remote,branch:o.remoteBranch}),Ae("done",`Fetched ${o.remote}/${o.remoteBranch}`)),ut(`Merging ${o.branch} into ${a}...`,"running");const c=await n.merge(r,{branch:o.branch});c.conflict?(Ae("error","Merge conflicts detected"),Qe(c.conflictFiles??[]),Ze("merge"),qe(!0),rt(r,c.conflictFiles??[],"merge")):(Ae("done",`Merged ${o.branch} into ${a}`),He(),ut("Refreshing repository status...","running"),await ne(),await ye(),Ae("done","Repository status updated"))}catch(c){if(_t(c))Ae("error","Uncommitted changes detected"),Xs("merge"),er(o.branch),xs(!0);else{const C=c instanceof Error?c.message:`Failed to merge ${o.branch}`;Ae("error",C)}}},[r,n,g,Ht,ne,ye,_t,rt,He,ut,Ae,$t]),xn=l.useCallback(async s=>{if(!r)return;hs("rebase"),$t();const a=g?.current,o=Ht(s);try{o.remote&&o.remoteBranch&&(ut(`Fetching ${o.remote}/${o.remoteBranch}...`,"running"),await n.gitFetch(r,{remote:o.remote,branch:o.remoteBranch}),Ae("done",`Fetched ${o.remote}/${o.remoteBranch}`)),ut(`Rebasing ${a} onto ${o.branch}...`,"running");const c=await n.rebase(r,{onto:o.branch});c.conflict?(Ae("error","Rebase conflicts detected"),Qe(c.conflictFiles??[]),Ze("rebase"),qe(!0),rt(r,c.conflictFiles??[],"rebase")):(Ae("done",`Rebased ${a} onto ${o.branch}`),He(),ut("Refreshing repository status...","running"),await ne(),await ye(),Ae("done","Repository status updated"))}catch(c){if(_t(c))Ae("error","Uncommitted changes detected"),Xs("rebase"),er(o.branch),xs(!0);else{const C=c instanceof Error?c.message:`Failed to rebase onto ${o.branch}`;Ae("error",C)}}},[r,n,g,Ht,ne,ye,_t,rt,He,ut,Ae,$t]),wn=l.useCallback(async()=>{if(r)try{Ot==="merge"?(await n.abortMerge(r),b.success(e("gitView.toast.mergeAborted"))):(await n.abortRebase(r),b.success(e("gitView.toast.rebaseAborted"))),He(),await ne(),await ye()}catch(s){const a=s instanceof Error?s.message:`Failed to abort ${Ot}`;b.error(a)}},[r,n,Ot,ne,ye,He,e]),yn=l.useMemo(()=>g?.files?g.files.filter(s=>s.index==="U"||s.working_dir==="U"||s.index==="A"&&s.working_dir==="A"||s.index==="D"&&s.working_dir==="D").length:0,[g?.files]),bn=l.useCallback(async()=>{if(r)try{const s=!!g?.mergeInProgress?.head,a=!!(g?.rebaseInProgress?.headName||g?.rebaseInProgress?.onto);if(s){const o=await n.continueMerge(r);o.conflict?(Qe(o.conflictFiles??[]),Ze("merge"),qe(!0),rt(r,o.conflictFiles??[],"merge"),b.error(e("gitView.toast.mergeConflictsDetected"))):(He(),b.success(e("gitView.toast.mergeCompleted")),await ne(),await ye())}else if(a){const o=await n.continueRebase(r);o.conflict?(Qe(o.conflictFiles??[]),Ze("rebase"),qe(!0),rt(r,o.conflictFiles??[],"rebase"),b.error(e("gitView.toast.rebaseConflictsDetected"))):(He(),b.success(e("gitView.toast.rebaseStepCompleted")),await ne(),await ye())}}catch(s){const a=s instanceof Error?s.message:e("gitView.toast.continueOperationFailed");b.error(a)}},[r,n,g,ne,ye,rt,He,e]),vn=l.useCallback(async()=>{if(r)try{!!g?.mergeInProgress?.head?(await n.abortMerge(r),b.success(e("gitView.toast.mergeAborted"))):(await n.abortRebase(r),b.success(e("gitView.toast.rebaseAborted"))),He(),await ne(),await ye()}catch(s){const a=s instanceof Error?s.message:e("gitView.toast.abortOperationFailed");b.error(a)}},[r,n,g,ne,ye,He,e]),jn=l.useCallback(()=>{if(!r)return;const a=!!g?.mergeInProgress?.head?"merge":"rebase",o=g?.files?.filter(c=>c.index==="U"||c.working_dir==="U").map(c=>c.path)??[];o.length>0&&Qe(o),Ze(a),qe(!0)},[r,g]),Cn=l.useCallback(async s=>{if(!r)return;const a=g?.current,o=ws,c=ys,C=(g?.files??[]).some(yr);try{await n.stash(r,{message:`Auto-stash before ${o} with ${c}`,includeUntracked:!0}),C&&G(r)}catch(J){const Oe=J instanceof Error?J.message:"Failed to stash changes";b.error(Oe);return}let z=!1,ae=!1;try{if(o==="merge"){const J=await n.merge(r,{branch:c});J.conflict?(ae=!0,Qe(J.conflictFiles??[]),Ze("merge"),qe(!0)):(z=!0,b.success(e("gitView.toast.mergedIntoBranch",{branch:c,currentBranch:a||""})))}else{const J=await n.rebase(r,{onto:c});J.conflict?(ae=!0,Qe(J.conflictFiles??[]),Ze("rebase"),qe(!0)):(z=!0,b.success(e("gitView.toast.rebasedOntoBranch",{currentBranch:a||"",branch:c})))}if(s&&z)try{await n.stashPop(r),G(r),b.success(e("gitView.toast.stashedRestored"))}catch(J){const Oe=J instanceof Error?J.message:e("gitView.toast.restoreStashFailed");b.error(Oe)}else s&&ae&&b.info(e("gitView.toast.restoreStashManually"));await ne(),await ye()}catch(J){if(s)try{await n.stashPop(r),G(r)}catch{}throw J}},[G,r,n,g,ws,ys,ne,ye,e]),Nn=l.useCallback(s=>{Sr(s),r&&(d(r,s),u(r,n,s))},[r,u,n,d]),Sn=l.useCallback(s=>{Hr(s)},[]),kn=l.useCallback(()=>{Lt(null),r&&(Q(r,n),te(r,n),u(r,n,Ke))},[r,Q,te,u,Ke,n]),Vn=l.useCallback(s=>{if(s.conflict){if(s.operation==="cherry-pick"||s.operation==="revert"){b.error(e("gitView.history.actions.conflictToastTitle"),{description:e("gitView.history.actions.conflictToastDescription",{files:s.conflictFiles?.join(", ")??"unknown files"})}),r&&(Q(r,n),te(r,n),u(r,n,Ke));return}Qe(s.conflictFiles??[]),Ze(s.operation),qe(!0),r&&rt(r,s.conflictFiles??[],s.operation)}},[e,Qe,Ze,qe,rt,r,Q,te,u,Ke,n]);return r?P===null||P===!0&&!g?t.jsx("div",{className:"flex h-full items-center justify-center",children:t.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}),t.jsx("span",{className:"typography-ui-label",children:e("gitView.loading.checkingRepository")})]})}):P===!1?Ie?t.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[t.jsx(T,{name:"loader-4",className:"mb-3 size-6 animate-spin text-muted-foreground"}),t.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:e("gitView.empty.worktreeSetupInProgress")}),t.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:e("gitView.empty.worktreeSetupDescription")})]}):t.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[t.jsx(T,{name:"git-branch",className:"mb-3 size-6 text-muted-foreground"}),t.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:e("gitView.empty.notGitRepository")}),t.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:e("gitView.empty.notGitRepositoryDescription")}),E.includes("open-without-worktree-features")?t.jsx("p",{className:"typography-meta mt-2 text-muted-foreground",children:e("gitView.empty.worktreeFeaturesUnavailable")}):null]}):t.jsxs("div",{className:Ve("flex h-full flex-col overflow-hidden"),children:[t.jsx(Pa,{status:g,localBranches:kt,remoteBranches:lt,branchInfo:U?.branches,syncAction:st,remotes:Ue,onFetch:s=>sr("fetch",s),onSync:s=>sr("sync",s),onRemoveRemote:Yr,removingRemoteName:Or,onCheckoutBranch:en,onCreateBranch:Zr,onRenameBranch:Xr,activeIdentityProfile:nn,availableIdentities:rn,onSelectIdentity:tn,isApplyingIdentity:kr,isWorktreeMode:!!D,onOpenHistory:()=>Lt("history"),onOpenGraph:()=>Lt("graph"),onOpenStashes:un,onOpenUpdateBranch:ar?()=>Ks(!0):void 0,onOpenReintegrateCommits:dt?()=>qs(!0):void 0,pullRequest:pe?.pr??null,prChecks:pe?.checks??null,onOpenPullRequest:r?()=>le(r,"pr"):void 0}),r&&(g?.mergeInProgress?.head||g?.rebaseInProgress?.headName||g?.rebaseInProgress?.onto)&&t.jsx(mi,{mergeInProgress:g?.mergeInProgress,rebaseInProgress:g?.rebaseInProgress,onContinue:bn,onAbort:vn,onResolveWithAI:jn,conflictCount:yn,isLoading:Y}),t.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:t.jsx("div",{className:"h-full min-h-0 flex flex-col",children:t.jsx("div",{className:Ve("min-w-0 min-h-0 h-full flex flex-col"),children:t.jsx(vr,{as:ba,ref:tt,outerClassName:"flex-1 min-h-0",className:Ve("px-4","pt-1 pb-4"),disableHorizontal:!0,preventOverscroll:!0,children:t.jsx("div",{className:"flex h-full min-h-0 flex-col gap-3",children:(ot?.length??0)>0?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:t.jsx(Ra,{groups:mn,diffStats:g?.diffStats,revertingPaths:ss,isRevertingAll:rs,onVisiblePathsChange:Z,onRevertAll:cn,onRevertDirectory:dn,headerBackgroundClassName:"bg-background"})}),t.jsx(Ba,{stagedCount:an,commitMessage:we,onCommitMessageChange:De,generatedHighlights:ns,onInsertHighlights:hn,onGenerateMessage:Qr,isGeneratingMessage:Rr,onCommit:()=>rr({pushAfter:!1}),onCommitAndPush:()=>rr({pushAfter:!0}),commitAction:Es,hasPendingIndexMutation:Br,gitmojiEnabled:Se,onOpenGitmojiPicker:()=>_e(!0)})]}):t.jsx(Wa,{onOpenStashes:()=>it(!0)})})})})})}),t.jsx(ht,{open:Lr,onOpenChange:s=>{!s&&Qs!==null||Ks(s)},children:t.jsxs(gt,{className:"max-w-2xl min-h-[26rem]",children:[t.jsxs(ft,{children:[t.jsx(pt,{children:e("gitView.branch.updateTitle")}),t.jsxs(yt,{children:[e("gitView.branch.updateDescriptionPrefix")," ",t.jsx("span",{className:"font-mono text-foreground",children:g?.current??""}),"."]})]}),ar?t.jsx(hi,{mode:"bare",currentBranch:g?.current,localBranches:kt,remoteBranches:lt,defaultTargetBranch:sn,onMerge:pn,onRebase:xn,disabled:on,isOperating:Qs!==null,operationLogs:zr,onOperationComplete:fn}):t.jsx("p",{className:"typography-meta text-muted-foreground",children:e("gitView.branch.actionsUnavailable")})]})}),t.jsx(ht,{open:Ar,onOpenChange:qs,children:t.jsxs(gt,{className:"max-w-2xl min-h-[26rem]",children:[t.jsxs(ft,{children:[t.jsx(pt,{children:e("gitView.integrate.title")}),t.jsx(yt,{children:dt?t.jsxs("span",{className:"font-mono text-foreground",children:[dt.sourceBranch," → ",Ws]}):null})]}),dt?t.jsx($a,{repoRoot:dt.repoRoot,sourceBranch:dt.sourceBranch,worktreeMetadata:dt.worktreeMetadata,localBranches:kt,defaultTargetBranch:Ws,refreshKey:Pr,showHeader:!1,onRefresh:()=>{r&&(Q(r,n),te(r,n),u(r,n,Ke))}},dt.worktreeMetadata.path):null]})}),t.jsx(ht,{open:Me!==null,onOpenChange:s=>{s||Lt(null)},children:t.jsxs(gt,{className:"max-w-5xl h-[90vh] max-h-[90vh] flex flex-col overflow-hidden",children:[t.jsxs(ft,{children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx(pt,{children:e(Me==="graph"?"gitView.graph.title":"gitView.history.title")}),t.jsxs(W,{type:"button",variant:"ghost",size:"sm",className:"mr-6 h-7 shrink-0 gap-1.5 px-2",onClick:()=>{if(Me==="graph"){Ur(s=>s+1);return}r&&u(r,n,Ke)},disabled:Me==="graph"?fs:ee,title:e("gitView.history.refresh"),"aria-label":e("gitView.history.refresh"),children:[t.jsx(T,{name:"refresh",className:Ve("size-4",(Me==="graph"?fs:ee)&&"animate-spin")}),e("gitView.history.refresh")]})]}),t.jsx(yt,{children:e("gitView.history.dialogDescription")})]}),t.jsx("div",{className:"flex-1 min-h-0",children:t.jsx(ei,{mode:Me==="graph"?"graph":"history",log:Me==="graph"?$r??$:$,isLogLoading:Me==="graph"&&fs||ee,logMaxCount:Me==="graph"?ps:Ke,onLogMaxCountChange:Me==="graph"?Sn:Nn,expandedCommitHashes:os,onToggleCommit:qr,commitFilesMap:Tt,loadingCommitHashes:Et,onCopyHash:Kr,directory:r??void 0,showHeader:!1,contentMaxHeightClassName:"h-full max-h-none",branchDivider:Me==="graph"?null:Er,onConflict:Me==="graph"?Vn:void 0,onActionSuccess:Me==="graph"?kn:void 0})})]})}),t.jsx(Ha,{open:at,onOpenChange:it,directory:r,hasUncommittedChanges:(g?.files?.length??0)>0,hasStagedChanges:We.length>0,uncommittedFileCount:g?.files?.length??0,onChanged:async s=>{r&&s?.affectsIndex&&G(r),await ne(!1),await ye()}}),t.jsx(ht,{open:Fe,onOpenChange:_e,children:t.jsxs(gt,{className:"max-w-md p-0 overflow-hidden",children:[t.jsx(ft,{className:"px-4 pt-4",children:t.jsx(pt,{children:e("gitView.gitmoji.title")})}),t.jsxs(Bs,{className:"h-[420px]",shouldFilter:!1,children:[t.jsx(Ds,{placeholder:e("gitView.gitmoji.searchPlaceholder"),value:Us,onValueChange:Js}),t.jsxs(Ms,{children:[t.jsx(Ts,{children:e("gitView.gitmoji.empty")}),t.jsx(qt,{children:Rt(ke,Us,s=>[s.code,s.description,s.emoji]).map(s=>t.jsxs(Yt,{onSelect:()=>gn(s.emoji,s.code),children:[t.jsx("span",{className:"text-lg",children:s.emoji}),t.jsx("span",{className:"typography-ui-label text-foreground",children:s.code}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:s.description})]},s.code))})]})]})]})}),r&&t.jsx(ai,{open:Gr,onOpenChange:qe,conflictFiles:_r,directory:r,operation:Ot,onAbort:wn,onClearState:He}),t.jsx(ui,{open:Jr,onOpenChange:xs,operation:ws,targetBranch:ys,onConfirm:Cn})]}):t.jsx("div",{className:"flex h-full items-center justify-center px-4 text-center",children:t.jsx("p",{className:"typography-ui-label text-muted-foreground",children:e("gitView.empty.selectSessionOrDirectory")})})};export{Wl as GitView};
@@ -1 +1 @@
1
- import{fd as M,h5 as Z,h6 as Fe,gS as Ce,gT as ke,gU as Ie,gV as ze,g$ as Ne,g_ as Ve,f as Oe,B as ee,I as te,hm as Pe}from"./useAppFontEffects-Cll4gnsh.js";import{b as ie,s as Be,d as Se,e as ne,i as ve,j as De,c as re,k as I,l as Ue,h as _e,g as We,f as je,R as Ge,I as $e,p as se,m as qe,n as Ke,o as Je,r as Ye,w as Xe,t as ae,u as Qe,A as Ze,v as et,x as tt,q as oe,S as it,y as nt,z as rt,B as st,a as ye,C as he,F as at}from"./web-components-DLnGY4fs.js";import{G as ot,u as ht,W as lt,a as dt,b as ct,n as le,t as ut}from"./Virtualizer-CZlLSacm.js";import{j as C,r as k,R as L}from"./vendor-react-BUCujlKS.js";import{n as ft,i as G,f as A,a as pt,o as de,s as gt,j as ce,d as mt,q as ue,b as Ct,t as B,u as fe}from"./computeVirtualFileMetrics-Gi1d5eU1.js";import{a as F,i as K,l as pe,h as St,r as vt}from"./isFilePlainText-CVKy_dgB.js";import{t as H}from"./vendor-hast-util-to-html-BKBhbTDb.js";let yt=-1;var Tt=class{options;onRenderUpdate;workerManager;__id=`file-renderer:${++yt}`;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)?ft():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??G(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:Be(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),l=!Se(this.renderCache.renderRange,e);if(this.workerManager?.isWorkingPool()===!0)(o||this.renderCache.result==null||!this.renderCache.highlighted&&(h||l))&&(this.renderCache.file=i,this.renderCache.options=t,this.renderCache.highlighted=!1,(this.renderCache.result==null||h||l||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??G(i.name);const d=this.highlighter!=null&&ie(t.theme),u=this.highlighter!=null&&ne(this.computedLang),c=!o&&u;if(this.highlighter!=null&&d&&(n||o||!this.renderCache.highlighted&&c||this.renderCache.result==null)){const{result:p,options:f}=this.renderFileWithHighlighter(i,this.highlighter,o||!u);this.renderCache={file:i,options:f,highlighted:c,result:p,renderRange:void 0}}(!d||!o&&!u)&&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??G(i.name);const t=this.highlighter!=null&&St(pt(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:vt(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(),l=Math.min(e.startingLine+e.totalLines,s);let d=0;const u=ve(e)?De(this.lineAnnotations):void 0;u!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:-1,lineIndex:-1,annotations:u.map(c=>I(c))})),d++);for(let c=e.startingLine;c<l;c++){const p=c+1,f=t[c];if(f==null){const g="FileRenderer.processFileResult: Line doesnt exist";throw console.error(g,{name:i.name,lineIndex:c,lineNumber:p}),new Error(g)}h.children.push(gt("context",p,`${c}`)),o.push(f),d++;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))})),d++)}return h.properties.style=`grid-row: span ${d}`,{gutterAST:h.children??[],contentAST:o,preAST:this.createPreElement(s),headerAST:a?void 0:this.renderHeader(i),totalLines:s,rowCount:d,themeStyles:n,baseThemeType:r,bufferBefore:e.bufferBefore,bufferAfter:e.bufferAfter,css:""}}renderHeader(i){const{headerRenderMode:e="default",stickyHeader:t=!1}=this.options;return Ue({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,_e(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 mt(We(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 je({type:"file",diffIndicators:"none",disableBackground:!0,disableLineNumbers:e,overflow:t,split:!1,totalLines:i})}};function $(i,e){return i>e}function bt(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 Rt=[""];let Lt=-1;var Te=class{options;workerManager;isContainerManaged;static LoadedCustomComponent=!0;__id=`file:${++Lt}`;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 Tt(e,this.handleHighlightRender,this.workerManager),this.resizeManager=new Ge,this.interactionManager=new $e("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&&!Ct(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),At(this.pre,s,this.options.collapsed)||Mt(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),qe(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):Rt}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:l=!1,themeType:d="system"}=this.options,u=l?void 0:h,c=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(!l&&!n&&Se(u,this.renderRange)&&!S&&!f&&!p)return this.applyCachedThemeState(d);this.renderRange=u,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(d),l){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{const m=this.fileRenderer.renderFile(e,Fe);m!=null&&this.applyThemeState(t,m.themeStyles,d,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(c,u)){const v=this.fileRenderer.renderFile(e,u);if(v==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.initialize().then(()=>this.rerender()),!1;this.applyThemeState(t,v.themeStyles,d,v.baseThemeType),v.headerAST!=null&&this.applyHeaderToDOM(v.headerAST,t),this.applyFullRender(v,m)}this.applyBuffers(m,u),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||!bt(r,a.annotation)){a?.element.remove();const o=t(r);if(o==null)continue;a={element:Ke(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=Je();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??=Ye(),this.unsafeCSSStyle.parentNode!==t&&t.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=Xe(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},l=ae(s);if(this.themeCSSStyle?.parentNode===s&&this.appliedThemeCSS?.themeStyles===t&&this.appliedThemeCSS.themeType===a&&this.appliedThemeCSS.scrollbarGutter===l){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:l};return}this.themeCSSStyle=Qe({shadowRoot:s,currentNode:this.themeCSSStyle,themeCSS:Ze(t,a,l)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:l}:void 0}hydrateMeasuredScrollbar(){const e=this.fileContainer?.shadowRoot;e==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=et(this.themeCSSStyle.textContent??"",ae(e)))}applyFullRender(e,t){this.cleanupErrorWrapper(),this.applyPreNodeAttributes(t,e),this.code=tt({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,l=t.totalLines===1/0?Number.POSITIVE_INFINITY:o+t.totalLines,d=Math.max(a,o),u=Math.min(h,l);if(u<=d||!this.trimDOMToOverlap(s.gutter,d,u)||!this.trimDOMToOverlap(s.content,d,u))return!1;let{length:c}=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<d?p(o,d-o):void 0;if(f===void 0&&o<d)return!1;const S=l===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:Math.max(0,l-u),g=l>u?p(u,S):void 0;return g===void 0&&l>u?!1:(this.cleanupErrorWrapper(),f!=null&&(s.gutter.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.gutterAST)),s.content.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.contentAST)),c+=f.rowCount),g!=null&&(s.gutter.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.gutterAST)),s.content.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.contentAST)),c+=g.rowCount),this.lastRowCount!==c&&(s.gutter.style.setProperty("grid-row",`span ${c}`),s.content.style.setProperty("grid-row",`span ${c}`),this.lastRowCount=c),!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,l)=>h-l),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 l=o[h];if(!(l instanceof HTMLElement))continue;const d=this.getLineIndexFromDOMNode(l);if(d!=null){for(;a!=null&&d>=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 l=document.createElement("div");l.innerHTML=r;const d=l.firstElementChild;if(!(d instanceof HTMLElement))return;this.headerElement!=null?t.shadowRoot?.replaceChild(d,this.headerElement):t.shadowRoot?.prepend(d),this.headerElement=d,this.lastRenderedHeaderHTML=r}if(this.isContainerManaged)return;const{renderHeaderPrefix:s,renderHeaderFilenameSuffix:a,renderCustomHeader:o,renderHeaderMetadata:h}=this.options;if(o!=null){const l=o(n)??void 0;this.headerCustom=this.upsertHeaderSlotElement(t,this.headerCustom,Ce,l),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0}else{const l=s?.(n)??void 0,d=a?.(n)??void 0,u=h?.(n)??void 0;this.headerPrefix=this.upsertHeaderSlotElement(t,this.headerPrefix,ke,l),this.headerFilenameSuffix=this.upsertHeaderSlotElement(t,this.headerFilenameSuffix,Ie,d),this.headerMetadata=this.upsertHeaderSlotElement(t,this.headerMetadata,ze,u),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=it;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};nt(s,this.appliedPreAttributes)||(rt(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 At(i,e,t=!1){return!t&&i==null&&e!=null}function Mt(i,e,t=!1){return i==null&&e!=null&&!t}const Ht=5e3;let xt=-1;function wt(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 Et=class extends Te{virtualizer;metrics;__id=`virtualized-file:${++xt}`;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&&st(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=wt(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=Ft(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 l=this.getLineHeight(a,h);o!==l&&(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 l=h?.lineIndex??0;l<s;l++)r+=this.getLineHeight(l,!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:d}=this.metrics,u=s+(a===0?h:this.renderRange.bufferBefore),c=a+Math.max(Math.ceil((i-u)/d),0);return c>o?void 0:{lineNumber:c+1,top:s+h+c*d}}let l=s+(a===0?h:this.renderRange.bufferBefore);for(let d=a;d<=o;d++){if(l>=i)return{lineNumber:d+1,top:l};l+=this.getLineHeight(d)}}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),l=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 d=0;d<o;d++)this.addLayoutCheckpoint(d,this.height),this.height+=this.getLineHeight(d,!1);if(o>0&&(this.height+=l),this.fileContainer!=null&&e&&!t){const d=this.fileContainer.getBoundingClientRect();d.height!==this.height?console.log("VirtualizedFile.computeApproximateSize: computed height doesnt match",{name:this.file.name,elementHeight:d.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 c=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(c==null)throw new Error("VirtualizedFile.render: simple virtualizer is not available");c.connect(i,this),this.isVisible=c.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode())return this.renderPlaceholder(this.height);const l=this.virtualizer.getWindowSpecs(),d=this.top??0,u=this.computeRenderRangeFromWindow(this.file,d,l);return super.render({file:this.file,fileContainer:i,renderRange:u,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%Ht===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),l=this.height,d=B(this.metrics,r),u=h>0?fe(this.metrics):0,{fileAnnotationHeight:c}=this.cache,p=d+c,f=Math.max(0,l-d-c-u),S=he(this.lineAnnotations),g=e+d,y=c>0&&S&&g<n&&g+c>t;if(e<t-l||e>n)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:l-d-u};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:l-d-u};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:c+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,V,O,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&&(V??=w),T+b>D&&(O??=w),x==null&&T>=n&&P&&(x=be),_++,T+=b}if(V==null)if(y)V=0,O=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:l-d-u};O??=V;const W=Math.round(O-z/2),Le=Math.max(0,Math.ceil(h/a)-z),j=Math.max(0,Math.min(W,Le)),J=j*a,Y=W<0?v+W*a:v,Ae=N[j]??0,Me=J===0?0:c+Ae,X=j+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 Ft(i){let e;for(const t of i.children)t instanceof HTMLElement&&t.dataset.lineAnnotation===at&&(e=Math.max(e??0,t.getBoundingClientRect().height));return e}function kt({file:i,renderCustomHeader:e,renderHeaderPrefix:t,renderHeaderFilenameSuffix:n,renderHeaderMetadata:r,renderAnnotation:s,lineAnnotations:a,renderGutterUtility:o,getHoveredLine:h}){const l=e?.(i),d=t?.(i),u=n?.(i),c=r?.(i);return C.jsxs(C.Fragment,{children:[l!=null?C.jsx("div",{slot:Ce,children:l}):C.jsxs(C.Fragment,{children:[d!=null&&C.jsx("div",{slot:"header-prefix",children:d}),u!=null&&C.jsx("div",{slot:"header-filename-suffix",children:u}),c!=null&&C.jsx("div",{slot:"header-metadata",children:c})]}),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:ot,children:o(h)})]})}const me=typeof window>"u"?k.useEffect:k.useLayoutEffect;function It({file:i,options:e,lineAnnotations:t,selectedLines:n,prerenderedHTML:r,metrics:s,hasGutterRenderUtility:a,hasCustomHeader:o,disableWorkerPool:h,contentEditable:l}){const d=ht(),u=n!==void 0,c=k.useContext(lt),p=dt(),f=k.useRef(null),S=ct(g=>{if(g!=null){if(f.current!=null)throw new Error("File: An instance should not already exist when a node is created");d!=null?f.current=new Et(q({controlledSelection:u,contentEditable:l,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),d,s,h?void 0:c,!0):f.current=new Te(q({controlledSelection:u,contentEditable:l,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),h?void 0:c,!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:u,contentEditable:l,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(l&&f.current!=null){if(p===void 0)throw new Error("File: Editor is not attached");return p.edit(f.current)}},[l,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:l,renderHeaderFilenameSuffix:d,renderHeaderMetadata:u,prerenderedHTML:c,renderGutterUtility:p,disableWorkerPool:f=!1,contentEditable:S=!1}){const{ref:g,getHoveredLine:y}=It({file:i,options:n,metrics:r,lineAnnotations:e,selectedLines:t,prerenderedHTML:c,hasGutterRenderUtility:p!=null,hasCustomHeader:h!=null,disableWorkerPool:f,contentEditable:S});return C.jsx(Ve,{ref:g,className:s,style:a,children:ut(kt({file:i,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:l,renderHeaderFilenameSuffix:d,renderHeaderMetadata:u,renderGutterUtility:p,lineAnnotations:e,getHoveredLine:y}),c)})}const Wt=L.memo(function({jsonString:e,className:t,maxHeight:n="100%",initiallyExpandedDepth:r=2}){const{t:s}=Oe(),a=L.useRef(null),[o,h]=L.useState(null),l=L.useMemo(()=>{try{const c=e.trim();if(!c)return h(s("jsonTreeView.error.emptyJson")),null;const p=JSON.parse(c);return h(null),p}catch(c){return h(c instanceof Error?c.message:s("jsonTreeView.error.invalidJson")),null}},[e,s]),d=L.useCallback(()=>{a.current?.expandAll()},[]),u=L.useCallback(()=>{a.current?.collapseAll()},[]);return o?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:s("jsonTreeView.error.invalidJsonTitle")}),C.jsx("div",{className:"font-mono text-xs text-[var(--surface-mutedForeground)]",children:o})]})}):l===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"}),s("jsonTreeView.actions.expandAll")]}),C.jsxs(ee,{variant:"ghost",size:"xs",onClick:u,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-up-s",className:"h-3 w-3"}),s("jsonTreeView.actions.collapseAll")]})]}),C.jsx("div",{className:"bg-[var(--syntax-base-background)] py-1",style:{maxHeight:n,overflow:"auto"},children:C.jsx(Pe,{ref:a,data:l,maxHeight:n,initiallyExpandedDepth:r})})]})});export{_t as F,Wt as J};
1
+ import{fg as M,h9 as Q,ha as Fe,gW as Ce,gX as ke,gY as Ie,gZ as ze,h3 as Ne,h2 as Ve,f as Oe,B as ee,I as te,hq as Pe}from"./useAppFontEffects-KP8_yiGW.js";import{b as ie,s as Be,d as Se,e as ne,i as ve,j as De,c as re,k as I,l as Ue,h as _e,g as We,f as je,R as Ge,I as $e,p as se,m as qe,n as Ke,o as Ye,r as Je,w as Xe,t as ae,u as Ze,A as Qe,v as et,x as tt,q as oe,S as it,y as nt,z as rt,B as st,a as ye,C as he,F as at}from"./web-components-DOXvU-tB.js";import{G as ot,u as ht,W as lt,a as dt,b as ct,n as le,t as ut}from"./Virtualizer-CZlLSacm.js";import{j as C,r as k,R as L}from"./vendor-react-BUCujlKS.js";import{n as ft,i as G,f as A,a as pt,o as de,s as gt,j as ce,d as mt,q as ue,b as Ct,t as B,u as fe}from"./computeVirtualFileMetrics-CZ0xPeaT.js";import{a as F,i as K,l as pe,h as St,r as vt}from"./isFilePlainText-DiLRrkJr.js";import{t as H}from"./vendor-hast-util-to-html-BKBhbTDb.js";let yt=-1;var Tt=class{options;onRenderUpdate;workerManager;__id=`file-renderer:${++yt}`;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)?ft():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??G(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:Be(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=Q){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),l=!Se(this.renderCache.renderRange,e);if(this.workerManager?.isWorkingPool()===!0)(o||this.renderCache.result==null||!this.renderCache.highlighted&&(h||l))&&(this.renderCache.file=i,this.renderCache.options=t,this.renderCache.highlighted=!1,(this.renderCache.result==null||h||l||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??G(i.name);const d=this.highlighter!=null&&ie(t.theme),u=this.highlighter!=null&&ne(this.computedLang),c=!o&&u;if(this.highlighter!=null&&d&&(n||o||!this.renderCache.highlighted&&c||this.renderCache.result==null)){const{result:p,options:f}=this.renderFileWithHighlighter(i,this.highlighter,o||!u);this.renderCache={file:i,options:f,highlighted:c,result:p,renderRange:void 0}}(!d||!o&&!u)&&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=Q){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??G(i.name);const t=this.highlighter!=null&&St(pt(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:vt(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(),l=Math.min(e.startingLine+e.totalLines,s);let d=0;const u=ve(e)?De(this.lineAnnotations):void 0;u!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:-1,lineIndex:-1,annotations:u.map(c=>I(c))})),d++);for(let c=e.startingLine;c<l;c++){const p=c+1,f=t[c];if(f==null){const g="FileRenderer.processFileResult: Line doesnt exist";throw console.error(g,{name:i.name,lineIndex:c,lineNumber:p}),new Error(g)}h.children.push(gt("context",p,`${c}`)),o.push(f),d++;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))})),d++)}return h.properties.style=`grid-row: span ${d}`,{gutterAST:h.children??[],contentAST:o,preAST:this.createPreElement(s),headerAST:a?void 0:this.renderHeader(i),totalLines:s,rowCount:d,themeStyles:n,baseThemeType:r,bufferBefore:e.bufferBefore,bufferAfter:e.bufferAfter,css:""}}renderHeader(i){const{headerRenderMode:e="default",stickyHeader:t=!1}=this.options;return Ue({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,_e(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 mt(We(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 je({type:"file",diffIndicators:"none",disableBackground:!0,disableLineNumbers:e,overflow:t,split:!1,totalLines:i})}};function $(i,e){return i>e}function bt(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 Rt=[""];let Lt=-1;var Te=class{options;workerManager;isContainerManaged;static LoadedCustomComponent=!0;__id=`file:${++Lt}`;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 Tt(e,this.handleHighlightRender,this.workerManager),this.resizeManager=new Ge,this.interactionManager=new $e("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&&!Ct(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),At(this.pre,s,this.options.collapsed)||Mt(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),qe(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):Rt}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:l=!1,themeType:d="system"}=this.options,u=l?void 0:h,c=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(!l&&!n&&Se(u,this.renderRange)&&!S&&!f&&!p)return this.applyCachedThemeState(d);this.renderRange=u,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(d),l){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{const m=this.fileRenderer.renderFile(e,Fe);m!=null&&this.applyThemeState(t,m.themeStyles,d,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(c,u)){const v=this.fileRenderer.renderFile(e,u);if(v==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.initialize().then(()=>this.rerender()),!1;this.applyThemeState(t,v.themeStyles,d,v.baseThemeType),v.headerAST!=null&&this.applyHeaderToDOM(v.headerAST,t),this.applyFullRender(v,m)}this.applyBuffers(m,u),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||!bt(r,a.annotation)){a?.element.remove();const o=t(r);if(o==null)continue;a={element:Ke(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=Ye();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=Xe(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},l=ae(s);if(this.themeCSSStyle?.parentNode===s&&this.appliedThemeCSS?.themeStyles===t&&this.appliedThemeCSS.themeType===a&&this.appliedThemeCSS.scrollbarGutter===l){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:l};return}this.themeCSSStyle=Ze({shadowRoot:s,currentNode:this.themeCSSStyle,themeCSS:Qe(t,a,l)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:l}:void 0}hydrateMeasuredScrollbar(){const e=this.fileContainer?.shadowRoot;e==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=et(this.themeCSSStyle.textContent??"",ae(e)))}applyFullRender(e,t){this.cleanupErrorWrapper(),this.applyPreNodeAttributes(t,e),this.code=tt({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,l=t.totalLines===1/0?Number.POSITIVE_INFINITY:o+t.totalLines,d=Math.max(a,o),u=Math.min(h,l);if(u<=d||!this.trimDOMToOverlap(s.gutter,d,u)||!this.trimDOMToOverlap(s.content,d,u))return!1;let{length:c}=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<d?p(o,d-o):void 0;if(f===void 0&&o<d)return!1;const S=l===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:Math.max(0,l-u),g=l>u?p(u,S):void 0;return g===void 0&&l>u?!1:(this.cleanupErrorWrapper(),f!=null&&(s.gutter.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.gutterAST)),s.content.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.contentAST)),c+=f.rowCount),g!=null&&(s.gutter.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.gutterAST)),s.content.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.contentAST)),c+=g.rowCount),this.lastRowCount!==c&&(s.gutter.style.setProperty("grid-row",`span ${c}`),s.content.style.setProperty("grid-row",`span ${c}`),this.lastRowCount=c),!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,l)=>h-l),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 l=o[h];if(!(l instanceof HTMLElement))continue;const d=this.getLineIndexFromDOMNode(l);if(d!=null){for(;a!=null&&d>=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 l=document.createElement("div");l.innerHTML=r;const d=l.firstElementChild;if(!(d instanceof HTMLElement))return;this.headerElement!=null?t.shadowRoot?.replaceChild(d,this.headerElement):t.shadowRoot?.prepend(d),this.headerElement=d,this.lastRenderedHeaderHTML=r}if(this.isContainerManaged)return;const{renderHeaderPrefix:s,renderHeaderFilenameSuffix:a,renderCustomHeader:o,renderHeaderMetadata:h}=this.options;if(o!=null){const l=o(n)??void 0;this.headerCustom=this.upsertHeaderSlotElement(t,this.headerCustom,Ce,l),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0}else{const l=s?.(n)??void 0,d=a?.(n)??void 0,u=h?.(n)??void 0;this.headerPrefix=this.upsertHeaderSlotElement(t,this.headerPrefix,ke,l),this.headerFilenameSuffix=this.upsertHeaderSlotElement(t,this.headerFilenameSuffix,Ie,d),this.headerMetadata=this.upsertHeaderSlotElement(t,this.headerMetadata,ze,u),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=it;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};nt(s,this.appliedPreAttributes)||(rt(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 At(i,e,t=!1){return!t&&i==null&&e!=null}function Mt(i,e,t=!1){return i==null&&e!=null&&!t}const Ht=5e3;let xt=-1;function wt(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 Et=class extends Te{virtualizer;metrics;__id=`virtualized-file:${++xt}`;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&&st(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=wt(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=Ft(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 l=this.getLineHeight(a,h);o!==l&&(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 l=h?.lineIndex??0;l<s;l++)r+=this.getLineHeight(l,!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:d}=this.metrics,u=s+(a===0?h:this.renderRange.bufferBefore),c=a+Math.max(Math.ceil((i-u)/d),0);return c>o?void 0:{lineNumber:c+1,top:s+h+c*d}}let l=s+(a===0?h:this.renderRange.bufferBefore);for(let d=a;d<=o;d++){if(l>=i)return{lineNumber:d+1,top:l};l+=this.getLineHeight(d)}}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),l=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 d=0;d<o;d++)this.addLayoutCheckpoint(d,this.height),this.height+=this.getLineHeight(d,!1);if(o>0&&(this.height+=l),this.fileContainer!=null&&e&&!t){const d=this.fileContainer.getBoundingClientRect();d.height!==this.height?console.log("VirtualizedFile.computeApproximateSize: computed height doesnt match",{name:this.file.name,elementHeight:d.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 c=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(c==null)throw new Error("VirtualizedFile.render: simple virtualizer is not available");c.connect(i,this),this.isVisible=c.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode())return this.renderPlaceholder(this.height);const l=this.virtualizer.getWindowSpecs(),d=this.top??0,u=this.computeRenderRangeFromWindow(this.file,d,l);return super.render({file:this.file,fileContainer:i,renderRange:u,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%Ht===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),l=this.height,d=B(this.metrics,r),u=h>0?fe(this.metrics):0,{fileAnnotationHeight:c}=this.cache,p=d+c,f=Math.max(0,l-d-c-u),S=he(this.lineAnnotations),g=e+d,y=c>0&&S&&g<n&&g+c>t;if(e<t-l||e>n)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:l-d-u};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:l-d-u};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,Z=b<0?v+b*a:v,we=E===0?0:c+E*o,Ee=Math.min(Z,h-E);return{startingLine:E,totalLines:Z,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,V,O,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&&(V??=w),T+b>D&&(O??=w),x==null&&T>=n&&P&&(x=be),_++,T+=b}if(V==null)if(y)V=0,O=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:l-d-u};O??=V;const W=Math.round(O-z/2),Le=Math.max(0,Math.ceil(h/a)-z),j=Math.max(0,Math.min(W,Le)),Y=j*a,J=W<0?v+W*a:v,Ae=N[j]??0,Me=Y===0?0:c+Ae,X=j+J/a,He=X<N.length?f-N[X]:f-(T-e-p);return{startingLine:Y,totalLines:J,bufferBefore:Me,bufferAfter:Math.max(0,He)}}};function Ft(i){let e;for(const t of i.children)t instanceof HTMLElement&&t.dataset.lineAnnotation===at&&(e=Math.max(e??0,t.getBoundingClientRect().height));return e}function kt({file:i,renderCustomHeader:e,renderHeaderPrefix:t,renderHeaderFilenameSuffix:n,renderHeaderMetadata:r,renderAnnotation:s,lineAnnotations:a,renderGutterUtility:o,getHoveredLine:h}){const l=e?.(i),d=t?.(i),u=n?.(i),c=r?.(i);return C.jsxs(C.Fragment,{children:[l!=null?C.jsx("div",{slot:Ce,children:l}):C.jsxs(C.Fragment,{children:[d!=null&&C.jsx("div",{slot:"header-prefix",children:d}),u!=null&&C.jsx("div",{slot:"header-filename-suffix",children:u}),c!=null&&C.jsx("div",{slot:"header-metadata",children:c})]}),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:ot,children:o(h)})]})}const me=typeof window>"u"?k.useEffect:k.useLayoutEffect;function It({file:i,options:e,lineAnnotations:t,selectedLines:n,prerenderedHTML:r,metrics:s,hasGutterRenderUtility:a,hasCustomHeader:o,disableWorkerPool:h,contentEditable:l}){const d=ht(),u=n!==void 0,c=k.useContext(lt),p=dt(),f=k.useRef(null),S=ct(g=>{if(g!=null){if(f.current!=null)throw new Error("File: An instance should not already exist when a node is created");d!=null?f.current=new Et(q({controlledSelection:u,contentEditable:l,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),d,s,h?void 0:c,!0):f.current=new Te(q({controlledSelection:u,contentEditable:l,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),h?void 0:c,!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:u,contentEditable:l,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(l&&f.current!=null){if(p===void 0)throw new Error("File: Editor is not attached");return p.edit(f.current)}},[l,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:l,renderHeaderFilenameSuffix:d,renderHeaderMetadata:u,prerenderedHTML:c,renderGutterUtility:p,disableWorkerPool:f=!1,contentEditable:S=!1}){const{ref:g,getHoveredLine:y}=It({file:i,options:n,metrics:r,lineAnnotations:e,selectedLines:t,prerenderedHTML:c,hasGutterRenderUtility:p!=null,hasCustomHeader:h!=null,disableWorkerPool:f,contentEditable:S});return C.jsx(Ve,{ref:g,className:s,style:a,children:ut(kt({file:i,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:l,renderHeaderFilenameSuffix:d,renderHeaderMetadata:u,renderGutterUtility:p,lineAnnotations:e,getHoveredLine:y}),c)})}const Wt=L.memo(function({jsonString:e,className:t,maxHeight:n="100%",initiallyExpandedDepth:r=2}){const{t:s}=Oe(),a=L.useRef(null),[o,h]=L.useState(null),l=L.useMemo(()=>{try{const c=e.trim();if(!c)return h(s("jsonTreeView.error.emptyJson")),null;const p=JSON.parse(c);return h(null),p}catch(c){return h(c instanceof Error?c.message:s("jsonTreeView.error.invalidJson")),null}},[e,s]),d=L.useCallback(()=>{a.current?.expandAll()},[]),u=L.useCallback(()=>{a.current?.collapseAll()},[]);return o?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:s("jsonTreeView.error.invalidJsonTitle")}),C.jsx("div",{className:"font-mono text-xs text-[var(--surface-mutedForeground)]",children:o})]})}):l===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"}),s("jsonTreeView.actions.expandAll")]}),C.jsxs(ee,{variant:"ghost",size:"xs",onClick:u,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-up-s",className:"h-3 w-3"}),s("jsonTreeView.actions.collapseAll")]})]}),C.jsx("div",{className:"bg-[var(--syntax-base-background)] py-1",style:{maxHeight:n,overflow:"auto"},children:C.jsx(Pe,{ref:a,data:l,maxHeight:n,initiallyExpandedDepth:r})})]})});export{_t as F,Wt as J};
@@ -0,0 +1 @@
1
+ import{f as B,R as h,j as P}from"./vendor-react-BUCujlKS.js";import{toast as H}from"./vendor-sonner-DFyL3AvE.js";import{fs as K,fp as J,ab as Z,f as Q,I as W}from"./useAppFontEffects-KP8_yiGW.js";import{r as G,V,F as ee,e as te,c$ as re,d0 as oe,aN as ae}from"./index-DIvDEKE-.js";import{extractMarkdownImageCandidates as se,MAX_MARKDOWN_IMAGE_COUNT as ne}from"./markdownCore-CcTcLsQF.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-zustand-BAGL70zf.js";import"./vendor-base-ui-BeMD8X_w.js";import"./vendor-floating-ui-utils-D6FqdtJt.js";import"./vendor-floating-ui-react-dom-DxYCWdHj.js";import"./vendor-floating-ui-dom-BTvzWks8.js";import"./vendor-floating-ui-core-PuGzNPnN.js";import"./vendor-use-sync-external-store-D6wYuSt-.js";import"./contextPanelEmbeddedChat-C9abMBTb.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-dnd-kit-core-BZknOX2w.js";import"./vendor-dnd-kit-utilities-B_MdXhJC.js";import"./vendor-dnd-kit-accessibility-BHxJPORy.js";import"./vendor-dnd-kit-sortable-CsEagZ81.js";import"./vendor-framer-motion-livSKyyV.js";import"./vendor-motion-dom-D_o3BTI3.js";import"./vendor-motion-utils-BGh8QBgx.js";import"./vendor-tanstack-react-virtual-g05Cx3z9.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-cmdk-DgLInKvT.js";import"./vendor-radix-ui-react-dialog-B94Bt2qq.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-DcAh5WdT.js";import"./vendor-radix-ui-react-context-Czxm7Z62.js";import"./vendor-radix-ui-react-id-f5BLKEVw.js";import"./vendor-radix-ui-react-use-layout-effect-D_3IhJdJ.js";import"./vendor-radix-ui-react-use-controllable-state-BFT5YmkA.js";import"./vendor-radix-ui-react-dismissable-layer-D7kXcwgJ.js";import"./vendor-radix-ui-react-primitive-DhVoX9SD.js";import"./vendor-radix-ui-react-slot-BQgQOasS.js";import"./vendor-radix-ui-react-use-callback-ref-BZPnuXAC.js";import"./vendor-radix-ui-react-use-escape-keydown-oph88g-F.js";import"./vendor-radix-ui-react-focus-scope-CiaxW4dD.js";import"./vendor-radix-ui-react-portal-BMJYHWck.js";import"./vendor-radix-ui-react-presence-CNxf-uq4.js";import"./vendor-radix-ui-react-focus-guards-B6qJXYua.js";import"./vendor-react-remove-scroll-DO7dCTnK.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-BcFYyj3E.js";import"./vendor-react-style-singleton-q6EMHnwf.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-zDC0RhA3.js";import"./vendor-use-callback-ref-D3RC8gqK.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BgPj_McA.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-codemirror-state-C9awkmn-.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-codemirror-view-CiLROUVV.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-Cc2ZYbgX.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-DzPz9Wgq.js";import"./vendor-codemirror-lang-json-CMBS2tG9.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-O0cZX78y.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-CfgK872x.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-BPGOH9ye.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-DrTPkHl4.js";import"./vendor-codemirror-lang-python-HahnQaAS.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-B7H_j0iU.js";import"./vendor-legendapp-list-gg7YLRW7.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-zod-BLfBSgBh.js";import"./vendor-opencode-sdk-BJ73u-bH.js";import"./vendor-marked-CX41MkDF.js";import"./vendor-marked-linkify-it-CXI_LHIE.js";import"./vendor-linkify-it-DZCzzDkK.js";import"./vendor-uc.micro-BAd0H0z4.js";import"./vendor-remend-BWYYytN3.js";import"./vendor-katex-k3Ppq1Ha.js";import"./vendor-dompurify-r8glNMJW.js";const $=10*1024*1024,ie=1024,le=3e4,ce=new Set(["image/png","image/jpeg","image/gif","image/webp"]),z=new WeakMap,L=r=>{if(r.aborted)throw new DOMException("Image load aborted","AbortError")},me=r=>{let e=r;if(/^file:\/\//i.test(e))try{const o=new URL(e);if(o.protocol!=="file:")return"";e=o.host&&o.host!=="localhost"?`//${o.host}${o.pathname}`:o.pathname,/^\/[A-Za-z]:\//.test(e)&&(e=e.slice(1))}catch{return""}const t=e.split(/[?#]/,1)[0]??"";try{return decodeURIComponent(t)}catch{return t}},ue=r=>new Promise((e,t)=>{const o=new FileReader;o.onload=()=>{typeof o.result=="string"?e(o.result):t(new Error("Unable to encode image"))},o.onerror=()=>t(o.error??new Error("Unable to encode image")),o.readAsDataURL(r)}),pe=async(r,e)=>{const t=new Uint8Array(await r.slice(0,12).arrayBuffer()),o=(n,u)=>String.fromCharCode(...t.slice(n,u));switch(e){case"image/png":return t[0]===137&&o(1,4)==="PNG"&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10;case"image/jpeg":return t[0]===255&&t[1]===216&&t[2]===255;case"image/gif":{const n=o(0,6);return n==="GIF87a"||n==="GIF89a"}case"image/webp":return o(0,4)==="RIFF"&&o(8,12)==="WEBP";default:return!1}},Y=async(r,e)=>{if(!ce.has(e))throw new Error("Unsupported image type");if(r.size>$)throw new Error("Image is too large");if(!await pe(r,e))throw new Error("Unsupported image data")},fe=async r=>{const e=/^data:(image\/(?:png|jpeg|gif|webp));base64,([\s\S]*)$/i.exec(r);if(!e?.[1]||e[2]===void 0)throw new Error("Invalid image data URL");if(e[2].length>Math.ceil($*4/3)+4)throw new Error("Image is too large");let t;try{t=atob(e[2])}catch{throw new Error("Invalid image data URL")}const o=Uint8Array.from(t,n=>n.charCodeAt(0));await Y(new Blob([o]),e[1].toLowerCase())},q=r=>!/^(?:https?:)?\/\//i.test(r)&&!/^data:image\/(?:png|jpeg|gif|webp);base64,/i.test(r),de=async({sources:r,directory:e,sessionId:t,messageId:o,signal:n})=>{const u=V();let s=z.get(u);s||(s=new Map,z.set(u,s));const c=`${t}\0${o}\0${e}\0${r.join("\0")}`,i=s.get(c);if(i&&i.expiresAt>Date.now())return s.delete(c),s.set(c,i),i.result;i&&s.delete(c);const p=await G(`/api/openchamber/sessions/${encodeURIComponent(t)}/markdown-image-grants`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({directory:e,messageId:o,sources:r}),signal:n});if(!p.ok)throw new Error(`Unable to prepare images (${p.status})`);const m=await p.json(),l=new Map;for(const a of m.results??[])a.source&&(a.status==="ready"&&a.path?l.set(a.source,{status:"ready",path:a.path,outsideFileGrant:a.outsideFileGrant,expiresAt:a.expiresAt}):a.status==="missing"?l.set(a.source,{status:"missing"}):l.set(a.source,{status:"error"}));for(const a of r)l.has(a)||l.set(a,{status:"error"});for(;s.size>=ie;)s.delete(s.keys().next().value);const w=[...l.values()].every(a=>a.status==="ready"),y=Math.min(...[...l.values()].filter(a=>a.status==="ready").map(a=>a.expiresAt??Number.POSITIVE_INFINITY));return s.set(c,{result:l,expiresAt:w?y:Date.now()+le}),l},ge=async(r,e)=>{if(L(e),/^(?:https?:)?\/\//i.test(r))return r;if(/^data:image\/(?:png|jpeg|gif|webp);base64,/i.test(r))return await fe(r),L(e),r;throw new Error("Local image has not been prepared")},he=async(r,e,t)=>{L(t);const o=me(r),n=K(e,o);if(!e||!o||!J(n,e))throw new Error("Image path is outside the active workspace");const u=await G("/api/fs/stat",{query:{path:n,directory:e,optional:"true"},signal:t});if(!u.ok)throw new Error(`Unable to inspect image (${u.status})`);const s=await u.json();if(!s.isFile)throw new Error("Image path is not a file");if(typeof s.size=="number"&&s.size>$)throw new Error("Image is too large");const c=await G("/api/fs/raw",{query:{path:n,directory:e},signal:t});if(!c.ok)throw new Error(`Unable to load image (${c.status})`);const i=(c.headers.get("content-type")??"").split(";",1)[0]?.toLowerCase()??"",p=Number(c.headers.get("content-length"));if(Number.isFinite(p)&&p>$)throw new Error("Image is too large");const m=await c.blob();return await Y(m,i),L(t),ue(m)},we=(r,e)=>V().authenticatedAsset("/api/fs/raw",{path:r.path,directory:e,allowOutsideWorkspace:r.outsideFileGrant?"true":void 0,outsideFileGrant:r.outsideFileGrant}),be=r=>{const e=B.c(7),[t,o]=h.useState(!1),[n,u]=h.useState(0);let s;e[0]===Symbol.for("react.memo_cache_sentinel")?(s=te(),e[0]=s):s=e[0];const c=s;let i,p;e[1]!==r?(i=()=>{if(!r){o(!1);return}let w=!1,y;const a=re(c),g=oe(()=>{w||u(Ie)}),I=()=>{ae(c).then(()=>{w||o(!0)}).catch(()=>{w||(y=setTimeout(I,1e3))})};return I(),()=>{w=!0,y&&clearTimeout(y),a(),g()}},p=[c,r],e[1]=r,e[2]=i,e[3]=p):(i=e[2],p=e[3]),h.useEffect(i,p);const m=!r||t;let l;return e[4]!==n||e[5]!==m?(l={ready:m,nonce:n},e[4]=n,e[5]=m,e[6]=l):l=e[6],l},ye=r=>{const e=B.c(46),{candidate:t,preparation:o,directory:n,assetAuthReady:u,assetAuthNonce:s,useWorkspaceFsBridge:c,onShowPopup:i}=r,{t:p}=Q(),m=h.useRef(null),[l,w]=h.useState(!1);let y;e[0]===Symbol.for("react.memo_cache_sentinel")?(y={url:"",status:"loading"},e[0]=y):y=e[0];const[a,g]=h.useState(y);let I;e[1]!==t.source?(I=q(t.source),e[1]=t.source,e[2]=I):I=e[2];const b=I;let x,f;e[3]!==l?(x=()=>{const N=m.current;if(!N||l)return;if(typeof IntersectionObserver>"u"){w(!0);return}const E=new IntersectionObserver(C=>{C.some(Ee)&&(w(!0),E.disconnect())},{rootMargin:"200px"});return E.observe(N),()=>E.disconnect()},f=[l],e[3]=l,e[4]=x,e[5]=f):(x=e[4],f=e[5]),h.useEffect(x,f);let v;e[6]!==u||e[7]!==t.source||e[8]!==n||e[9]!==b||e[10]!==o||e[11]!==l||e[12]!==c?(v=()=>{if(!l||b&&!c&&!o)return;if(b&&c){const E=new AbortController;return g({url:"",status:"loading"}),he(t.source,n,E.signal).then(C=>{E.signal.aborted||g({url:C,status:"loading"})}).catch(()=>{E.signal.aborted||g({url:"",status:"error"})}),()=>E.abort()}if(b){if(o?.status!=="ready"){g({url:"",status:"error"});return}if(!u)return;g({url:we(o,n),status:"loading"});return}const N=new AbortController;return g({url:"",status:"loading"}),ge(t.source,N.signal).then(E=>{N.signal.aborted||g({url:E,status:"loading"})}).catch(()=>{N.signal.aborted||g({url:"",status:"error"})}),()=>N.abort()},e[6]=u,e[7]=t.source,e[8]=n,e[9]=b,e[10]=o,e[11]=l,e[12]=c,e[13]=v):v=e[13];let k;e[14]!==s||e[15]!==u||e[16]!==t.source||e[17]!==n||e[18]!==b||e[19]!==o||e[20]!==l||e[21]!==c?(k=[s,u,t.source,n,b,o,l,c],e[14]=s,e[15]=u,e[16]=t.source,e[17]=n,e[18]=b,e[19]=o,e[20]=l,e[21]=c,e[22]=k):k=e[22],h.useEffect(v,k);let R;e[23]!==t.filename||e[24]!==a.status||e[25]!==a.url||e[26]!==i||e[27]!==p?(R=()=>{if(a.status==="error"){H.error(p("filesView.error.previewUnavailable"));return}a.status!=="ready"||!i||i({open:!0,title:t.filename,content:"",metadata:{tool:"markdown-image-preview",filename:t.filename},image:{url:a.url,filename:t.filename}})},e[23]=t.filename,e[24]=a.status,e[25]=a.url,e[26]=i,e[27]=p,e[28]=R):R=e[28];const U=R,j=a.status==="loading";let A;e[29]!==t.filename||e[30]!==a.status||e[31]!==a.url?(A=P.jsx("span",{className:"flex h-[72px] w-[100px] items-center justify-center overflow-hidden rounded-lg border border-border/40 bg-muted/10",children:a.url&&a.status!=="error"?P.jsx("img",{src:a.url,alt:t.filename,className:"h-full w-full object-contain",loading:"lazy",decoding:"async",referrerPolicy:"no-referrer",onLoad:()=>g(Ae),onError:()=>g({url:"",status:"error"}),"data-openchamber-markdown-image":"true","data-openchamber-markdown-image-thumbnail":"true","data-openchamber-markdown-image-state":a.status}):P.jsx(W,{name:"file-image",className:"h-5 w-5 text-muted-foreground"})}),e[29]=t.filename,e[30]=a.status,e[31]=a.url,e[32]=A):A=e[32];let _;e[33]===Symbol.for("react.memo_cache_sentinel")?(_=P.jsx(W,{name:"file-image",className:"h-3 w-3 shrink-0"}),e[33]=_):_=e[33];let S;e[34]!==t.filename?(S=P.jsx("span",{className:"min-w-0 truncate typography-meta",children:t.filename}),e[34]=t.filename,e[35]=S):S=e[35];let F;e[36]!==t.filename||e[37]!==S?(F=P.jsxs("span",{className:"mt-1 flex w-[100px] items-center justify-center gap-1 text-muted-foreground",title:t.filename,"data-openchamber-markdown-image-caption":"true",children:[_,S]}),e[36]=t.filename,e[37]=S,e[38]=F):F=e[38];let M;return e[39]!==t.filename||e[40]!==t.source||e[41]!==U||e[42]!==F||e[43]!==j||e[44]!==A?(M=P.jsxs("button",{ref:m,type:"button",className:"w-[100px] shrink-0 text-left outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":t.filename,disabled:j,onClick:U,"data-openchamber-markdown-image-action":"true","data-openchamber-markdown-image-source":t.source,"data-openchamber-markdown-image-filename":t.filename,children:[A,F]}),e[39]=t.filename,e[40]=t.source,e[41]=U,e[42]=F,e[43]=j,e[44]=A,e[45]=M):M=e[45],M},pr=r=>{const e=B.c(34),{sessionId:t,messageId:o,contents:n,onShowPopup:u}=r,s=Z()??"",c=h.useRef(null),[i,p]=h.useState(!1),[m,l]=h.useState(null),[w,y]=h.useState(0);let a;e[0]===Symbol.for("react.memo_cache_sentinel")?(a=ee(),e[0]=a):a=e[0];const g=a;let I;e[1]!==n?(I=se(n,ne),e[1]=n,e[2]=I):I=e[2];const b=I;let x;e[3]!==b?(x=g?[]:b.filter(xe).map(ve),e[3]=b,e[4]=x):x=e[4];const f=x;let v,k;e[5]!==f.length||e[6]!==i?(v=()=>{if(f.length===0||i)return;const d=c.current;if(!d||typeof IntersectionObserver>"u"){p(!0);return}const T=new IntersectionObserver(X=>{X.some(ke)&&(p(!0),T.disconnect())},{rootMargin:"200px"});return T.observe(d),()=>T.disconnect()},k=[f.length,i],e[5]=f.length,e[6]=i,e[7]=v,e[8]=k):(v=e[7],k=e[8]),h.useEffect(v,k);let R;e[9]!==s||e[10]!==o||e[11]!==f||e[12]!==t||e[13]!==i?(R=()=>{if(!i||!t||f.length===0)return;const d=new AbortController;return de({sources:f,directory:s,sessionId:t,messageId:o,signal:d.signal}).then(T=>{d.signal.aborted||l(T)}).catch(()=>{d.signal.aborted||l(new Map(f.map(Re)))}),()=>d.abort()},e[9]=s,e[10]=o,e[11]=f,e[12]=t,e[13]=i,e[14]=R):R=e[14];let U;e[15]!==s||e[16]!==o||e[17]!==w||e[18]!==f||e[19]!==t||e[20]!==i?(U=[s,o,w,f,t,i],e[15]=s,e[16]=o,e[17]=w,e[18]=f,e[19]=t,e[20]=i,e[21]=U):U=e[21],h.useEffect(R,U);let j,A;e[22]!==m?(j=()=>{const d=Math.min(...[...m?.values()??[]].filter(_e).map(Se));if(!Number.isFinite(d))return;const T=setTimeout(()=>y(Me),Math.max(0,d-Date.now()));return()=>clearTimeout(T)},A=[m],e[22]=m,e[23]=j,e[24]=A):(j=e[23],A=e[24]),h.useEffect(j,A);let _;e[25]!==m?(_=d=>m?.get(d.source)?.status!=="missing",e[25]=m,e[26]=_):_=e[26];const S=b.filter(_),F=[...m?.values()??[]].some(Ne),M=be(F);if(S.length===0)return null;const N="mt-3 flex max-w-full gap-2 overflow-x-auto pb-1",E="true";let C;e[27]!==M||e[28]!==s||e[29]!==u||e[30]!==m?(C=d=>P.jsx(ye,{candidate:d,preparation:m?.get(d.source),directory:s,assetAuthReady:M.ready,assetAuthNonce:M.nonce,useWorkspaceFsBridge:g,onShowPopup:u},d.source),e[27]=M,e[28]=s,e[29]=u,e[30]=m,e[31]=C):C=e[31];const D=S.map(C);let O;return e[32]!==D?(O=P.jsx("div",{ref:c,className:N,"data-openchamber-markdown-image-gallery":E,children:D}),e[32]=D,e[33]=O):O=e[33],O};function Ie(r){return r+1}function Ee(r){return r.isIntersecting}function Ae(r){return{...r,status:"ready"}}function xe(r){return q(r.source)}function ve(r){return r.source}function ke(r){return r.isIntersecting}function Re(r){return[r,{status:"error"}]}function _e(r){return r.status==="ready"}function Se(r){return r.expiresAt??Number.POSITIVE_INFINITY}function Me(r){return r+1}function Ne(r){return r.status==="ready"}export{pr as MarkdownImageGallery};