@pi-chamber/web 0.1.8 → 0.1.9

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 (51) hide show
  1. package/dist/assets/{CommitSection-DGGArAb2.js → CommitSection-DSFuOWuL.js} +1 -1
  2. package/dist/assets/{DiagramEditor-ig5nYV6t.js → DiagramEditor-D6W6zeV7.js} +1 -1
  3. package/dist/assets/{DiagramView-8Qr6pwwI.js → DiagramView-r89Qi5ON.js} +1 -1
  4. package/dist/assets/{DiffView-BHS4m_K7.js → DiffView-k3lX2PiV.js} +2 -2
  5. package/dist/assets/{FilesView-DmZcdwl-.js → FilesView-C39IOFfs.js} +3 -3
  6. package/dist/assets/GitView-CkztSaT7.js +6 -0
  7. package/dist/assets/{JsonTreeView-DbFqka3P.js → JsonTreeView-C6qt2uIj.js} +1 -1
  8. package/dist/assets/{MarkdownRendererImpl-B07lHhBl.js → MarkdownRendererImpl-CF12jEtB.js} +2 -2
  9. package/dist/assets/{PatchDiff-DD9pAs47.js → PatchDiff-D6In_lUU.js} +1 -1
  10. package/dist/assets/PierreDiffViewer-DSQwk05R.js +136 -0
  11. package/dist/assets/{SessionSwitcherDropdown-t7WZX24f.js → SessionSwitcherDropdown-CvE7hsxG.js} +1 -1
  12. package/dist/assets/{SettingsView-CtsS4oDI.js → SettingsView-Bf4vWwVK.js} +3 -3
  13. package/dist/assets/{SettingsWindow-DIRGn3eQ.js → SettingsWindow-B8IV35H4.js} +1 -1
  14. package/dist/assets/{ToolOutputDialog-iZG2ey4T.js → ToolOutputDialog-Brg2Humk.js} +6 -6
  15. package/dist/assets/{ToolPartDiffPreview-FTexlZSz.js → ToolPartDiffPreview-rlz2ipa2.js} +1 -1
  16. package/dist/assets/{VirtualizedFileDiff-DD5IznIe.js → VirtualizedFileDiff-BELx71mz.js} +4 -4
  17. package/dist/assets/{collapsible-ODWWxk4f.js → collapsible-QoPrpZP_.js} +1 -1
  18. package/dist/assets/{computeVirtualFileMetrics-DdXkLFAD.js → computeVirtualFileMetrics-CInbUZiB.js} +2 -2
  19. package/dist/assets/{contextFileOpenGuard-uC4OerzL.js → contextFileOpenGuard-BOtkNMZy.js} +1 -1
  20. package/dist/assets/{index-MSKFS67y.js → index-4sRd3SSM.js} +1 -1
  21. package/dist/assets/index-Dnby-sDS.js +8 -0
  22. package/dist/assets/{index-C_Mo87uS.css → index-NYG3k04a.css} +1 -1
  23. package/dist/assets/{isDiffPlainText-CeCQwHA2.js → isDiffPlainText-BquUayus.js} +1 -1
  24. package/dist/assets/{isFilePlainText-BcfhE9FH.js → isFilePlainText-D4iUTBdr.js} +1 -1
  25. package/dist/assets/{main-DZg4qzOe.js → main-Cp3YZZm1.js} +2 -2
  26. package/dist/assets/{main-CPygRDd9.js → main-CyshB9VI.js} +8 -8
  27. package/dist/assets/{markdownCore-BULtt6Xa.js → markdownCore-BK98alzY.js} +2 -2
  28. package/dist/assets/{miniChat-BFotDgpO.js → miniChat-C_A4lnrT.js} +2 -2
  29. package/dist/assets/{mobile-3LLzhN5Q.js → mobile-2dXx6cUI.js} +2 -2
  30. package/dist/assets/{renderElectronMiniChatApp-DGmmT9Wf.js → renderElectronMiniChatApp-HL15h5xo.js} +1 -1
  31. package/dist/assets/renderMobileApp-w6YFCJhq.js +23 -0
  32. package/dist/assets/runtimeEndpointReset-DiVqZFZB.js +46 -0
  33. package/dist/assets/runtimeSurface-DMXukysz.js +1 -0
  34. package/dist/assets/{useAppFontEffects-DXASDavv.js → useAppFontEffects-DqOhrZWx.js} +85 -85
  35. package/dist/assets/{useInlineCommentController-KJFe98HG.js → useInlineCommentController-ruw8wb2Y.js} +2 -2
  36. package/dist/assets/useOpenInAppsStore-DVr2oGEm.js +1 -0
  37. package/dist/assets/{useWindowTitle-BcwmWC0M.js → useWindowTitle-qt23iibv.js} +3 -3
  38. package/dist/assets/{vendor-codemirror-language-data-CFVH0pe8.js → vendor-codemirror-language-data-DVYP3hf_.js} +2 -2
  39. package/dist/assets/{web-components-CNPQSzpa.js → web-components-P2py0R8j.js} +1 -1
  40. package/dist/index.html +4 -4
  41. package/dist/mini-chat.html +3 -3
  42. package/dist/mobile.html +3 -3
  43. package/package.json +1 -1
  44. package/dist/assets/GitView-gfHxmc66.js +0 -6
  45. package/dist/assets/PierreDiffViewer-Bo0_BCT7.js +0 -136
  46. package/dist/assets/TerminalView-DUwO1CCY.js +0 -46
  47. package/dist/assets/index-CRB7i1S2.js +0 -8
  48. package/dist/assets/renderMobileApp-Dd8P9hvM.js +0 -23
  49. package/dist/assets/runtimeSurface-Cnqjhb6Y.js +0 -1
  50. package/dist/assets/useOpenInAppsStore-DHAeT9zx.js +0 -1
  51. /package/dist/assets/{TerminalView-BV3KOtdA.css → runtimeEndpointReset-BV3KOtdA.css} +0 -0
@@ -0,0 +1,6 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DiffView-k3lX2PiV.js","assets/vendor-react-DYyjh7Q0.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-Dnby-sDS.js","assets/vendor-zustand-CnsBKjP5.js","assets/index-NYG3k04a.css","assets/useAppFontEffects-DqOhrZWx.js","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-base-ui-DwfTg5wD.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-sVFnuruh.js","assets/vendor-floating-ui-dom-Bkw82kL9.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-B7OScDIw.js","assets/runtimeSurface-DMXukysz.js","assets/vendor-dnd-kit-core-GipZW2tY.js","assets/vendor-dnd-kit-utilities-CrOcp0Bp.js","assets/vendor-dnd-kit-accessibility-Cv52zwWT.js","assets/vendor-dnd-kit-sortable-Ct2QxIHb.js","assets/vendor-cmdk-BCEUzcHE.js","assets/vendor-radix-ui-react-dialog-jX3Dld8c.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-D1GnwnP9.js","assets/vendor-radix-ui-react-context-CM4yFQ2I.js","assets/vendor-radix-ui-react-id-BcxRjnbX.js","assets/vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js","assets/vendor-radix-ui-react-use-controllable-state-C_ecoh35.js","assets/vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js","assets/vendor-radix-ui-react-primitive-CfpW6_IT.js","assets/vendor-radix-ui-react-slot-BxUc3Pvz.js","assets/vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js","assets/vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js","assets/vendor-radix-ui-react-focus-scope-C2K7lNPv.js","assets/vendor-radix-ui-react-portal-xlJWBfDg.js","assets/vendor-radix-ui-react-presence-Btn-Dp7L.js","assets/vendor-radix-ui-react-focus-guards-D5MZ0nQs.js","assets/vendor-react-remove-scroll-CfeMe0DL.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-C9YRs2nU.js","assets/vendor-react-style-singleton-B1H4bWSG.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-C-AuTczP.js","assets/vendor-use-callback-ref-CJB0R85I.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-BuDklWi8.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-codemirror-state-Wdz6Qsow.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-codemirror-view-pXtfpqbT.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-CrbeaEAU.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-3xMyV7a2.js","assets/vendor-codemirror-lang-json-BTvAjwkJ.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-C4jEScp7.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-C1Svvdey.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-BloD9GN-.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-DVYP3hf_.js","assets/vendor-codemirror-lang-python-CR2g6ukK.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-Bzf12ODH.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tanstack-react-virtual-IrbCBGJ4.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-DJASDzNt.js","assets/vendor-motion-dom-DJLgZh4Q.js","assets/vendor-motion-utils-BGh8QBgx.js","assets/vendor-sonner-dWA7qvjr.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/PierreDiffViewer-DSQwk05R.js","assets/web-components-P2py0R8j.js","assets/computeVirtualFileMetrics-CInbUZiB.js","assets/vendor-shiki-Bbf2GEcE.js","assets/vendor-shikijs-core-CGM_jqPK.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js","assets/vendor-hast-util-to-html-BKBhbTDb.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-rJCbAzvX.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/themeResolver-BmJyTmjJ.js","assets/vendor-pierre-theming-C6Z4M5_u.js","assets/vendor-shikijs-engine-javascript-Cme4830A.js","assets/vendor-oniguruma-to-es-DLBnFDCE.js","assets/vendor-oniguruma-parser-C0D4_9rT.js","assets/vendor-regex-BBWcyTkg.js","assets/vendor-regex-utilities-2BQyy0xI.js","assets/vendor-regex-recursion-JU4mF-dD.js","assets/vendor-shikijs-transformers-CZWsLLKm.js","assets/VirtualizedFileDiff-BELx71mz.js","assets/isDiffPlainText-BquUayus.js","assets/vendor-diff-C3JhlQdm.js","assets/runtimeEndpointReset-DiVqZFZB.js","assets/permissionStore-BRcQ9Jgt.js","assets/runtimeEndpointReset-BV3KOtdA.css","assets/useInlineCommentController-ruw8wb2Y.js","assets/collapsible-QoPrpZP_.js","assets/appThemeRegistry-BK0dHKa6.js","assets/registerCustomTheme-BBXUCRnG.js","assets/contextFileOpenGuard-BOtkNMZy.js"])))=>i.map(i=>d[i]);
2
+ import{_ as Rr}from"./vendor-vite-runtime-DD1OZmLC.js";import{R as n,j as e}from"./vendor-react-DYyjh7Q0.js";import{eI as Ir,t as g,eJ as Er,D as ke,C as Re,E as Ie,G as Ee,I as R,H as $e,a1 as ss,B as D,T as st,y as rt,z as at,eK as Fr,f as ee,eL as Mr,eM as Pr,eN as Lr,eO as $r,aw as ys,ax as js,ay as ws,az as Br,_ as Ar,b1 as Dr,eP as zr,eQ as Gr,eR as Tr,eS as Or,eT as _r,eU as Hr,eV as Ur,aY as Wr,bP as Vr,bQ as Yr,bR as qr,bS as Jr,bT as Kr,m as kt,b9 as rs,eW as Qr,cS as as,bA as Xr,J as Rt,bX as Zr,bm as vs,bn as Cs,bo as Ns,bp as Ss,bq as It,br as Et,c9 as ea,K as ta,L as sa,N as ra,M as aa,eX as na,eY as oa,eZ as ia,Q as la,e_ as ca,R as da,h as ua,aB as ma,bj as ha,Y as fa,Z as ga}from"./useAppFontEffects-DqOhrZWx.js";import{a4 as pa,ai as xa,aj as ba}from"./runtimeEndpointReset-DiVqZFZB.js";import{u as ns}from"./vendor-zustand-CnsBKjP5.js";import{C as ya}from"./CommitSection-DSFuOWuL.js";import{C as ja,a as wa,b as va}from"./collapsible-QoPrpZP_.js";import{P as Ca}from"./PierreDiffViewer-DSQwk05R.js";import{u as ks}from"./index-Dnby-sDS.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-base-ui-DwfTg5wD.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-sVFnuruh.js";import"./vendor-floating-ui-dom-Bkw82kL9.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-B7OScDIw.js";import"./runtimeSurface-DMXukysz.js";import"./vendor-dnd-kit-core-GipZW2tY.js";import"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import"./vendor-dnd-kit-accessibility-Cv52zwWT.js";import"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import"./vendor-cmdk-BCEUzcHE.js";import"./vendor-radix-ui-react-dialog-jX3Dld8c.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-D1GnwnP9.js";import"./vendor-radix-ui-react-context-CM4yFQ2I.js";import"./vendor-radix-ui-react-id-BcxRjnbX.js";import"./vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js";import"./vendor-radix-ui-react-use-controllable-state-C_ecoh35.js";import"./vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js";import"./vendor-radix-ui-react-primitive-CfpW6_IT.js";import"./vendor-radix-ui-react-slot-BxUc3Pvz.js";import"./vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js";import"./vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js";import"./vendor-radix-ui-react-focus-scope-C2K7lNPv.js";import"./vendor-radix-ui-react-portal-xlJWBfDg.js";import"./vendor-radix-ui-react-presence-Btn-Dp7L.js";import"./vendor-radix-ui-react-focus-guards-D5MZ0nQs.js";import"./vendor-react-remove-scroll-CfeMe0DL.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-C9YRs2nU.js";import"./vendor-react-style-singleton-B1H4bWSG.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-C-AuTczP.js";import"./vendor-use-callback-ref-CJB0R85I.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BuDklWi8.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-codemirror-state-Wdz6Qsow.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-codemirror-view-pXtfpqbT.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-CrbeaEAU.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-3xMyV7a2.js";import"./vendor-codemirror-lang-json-BTvAjwkJ.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-C4jEScp7.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-C1Svvdey.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-BloD9GN-.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-DVYP3hf_.js";import"./vendor-codemirror-lang-python-CR2g6ukK.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-Bzf12ODH.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-framer-motion-DJASDzNt.js";import"./vendor-motion-dom-DJLgZh4Q.js";import"./vendor-motion-utils-BGh8QBgx.js";import"./vendor-sonner-dWA7qvjr.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./permissionStore-BRcQ9Jgt.js";import"./web-components-P2py0R8j.js";import"./computeVirtualFileMetrics-CInbUZiB.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-BELx71mz.js";import"./isDiffPlainText-BquUayus.js";import"./vendor-diff-C3JhlQdm.js";import"./useInlineCommentController-ruw8wb2Y.js";import"./appThemeRegistry-BK0dHKa6.js";import"./registerCustomTheme-BBXUCRnG.js";const Rs="gitmojiCache",Na=1e3*60*60*24*7,Is="1",Sa="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",Es=l=>{if(!l||typeof l!="object")return!1;const r=l;return typeof r.emoji=="string"&&typeof r.code=="string"&&typeof r.description=="string"},Nt=()=>{if(typeof window>"u")return null;try{const l=window.localStorage.getItem(Rs);if(!l)return null;const r=JSON.parse(l);return!r||r.version!==Is||typeof r.fetchedAt!="number"||!Array.isArray(r.gitmojis)?null:{gitmojis:r.gitmojis.filter(Es),fetchedAt:r.fetchedAt,version:r.version}}catch{return null}},ka=l=>{if(!(typeof window>"u"))try{const r={gitmojis:l,fetchedAt:Date.now(),version:Is};window.localStorage.setItem(Rs,JSON.stringify(r))}catch{return}},os=l=>Date.now()-l.fetchedAt<Na;let Ze=null;const ze=new Set,is=async()=>{if(Ze)return Ze;const l=(async()=>{try{const r=await fetch(Sa);if(!r.ok)throw new Error(`Failed to load gitmojis: ${r.statusText}`);const t=await r.json(),j=Array.isArray(t.gitmojis)?t.gitmojis.filter(Es):[];return ka(j),ze.forEach(b=>b(j)),j}catch(r){console.warn("Failed to load gitmoji list:",r);const t=[];return ze.forEach(j=>j(t)),t}finally{Ze=null}})();return Ze=l,l},Ra=l=>{const[r,t]=n.useState(()=>l?Nt()?.gitmojis??[]:[]),[j,b]=n.useState(!1),p=n.useRef(l);p.current=l,n.useEffect(()=>{if(!l){ze.delete(t),t([]),b(!1);return}const w=Nt();if(w&&(t(w.gitmojis),os(w)))return;ze.add(t),b(!0);let S=!1;return is().finally(()=>{!S&&p.current&&b(!1)}),()=>{S=!0,ze.delete(t)}},[l]);const x=n.useCallback(async()=>{if(!p.current)return[];if(r.length>0)return r;const w=Nt();return w&&os(w)?w.gitmojis:is()},[r]);return{gitmojis:r,isLoading:j,ensureLoaded:x}},Ia=({open:l,onOpenChange:r,directory:t,hasUncommittedChanges:j,hasStagedChanges:b=!1,uncommittedFileCount:p,onChanged:x})=>{const[w,S]=n.useState([]),[y,F]=n.useState(!1),[m,v]=n.useState(""),[h,d]=n.useState(""),[N,C]=n.useState(null),[k,Y]=n.useState({}),G=n.useCallback(async()=>{if(t){F(!0);try{const u=await Ir(t);S(u.stashes),Y({})}catch(u){g.error(u instanceof Error?u.message:"Failed to load stashes")}finally{F(!1)}}},[t]);n.useEffect(()=>{l&&G()},[G,l]),n.useEffect(()=>{if(!l||!t||w.length===0)return;let u=!1;const I=w.map(H=>H.ref);return Er(t,I).then(H=>{u||Y(H.counts)}).catch(()=>{}),()=>{u=!0}},[t,l,w]);const z=n.useMemo(()=>{const u=m.trim().toLowerCase();return u?w.filter(I=>`${I.ref} ${I.message} ${I.relativeTime}`.toLowerCase().includes(u)):w},[m,w]),W=n.useCallback(async u=>{await G(),await x?.(u)},[G,x]),M=async()=>{if(!(!t||N)){C("create");try{const u=await Fr(t,{message:h.trim()||void 0});u.created?(g.success("Changes stashed"),d("")):g.info("No local changes to stash"),await W({affectsIndex:!!(u.created&&b)})}catch(u){g.error(u instanceof Error?u.message:"Failed to stash changes")}finally{C(null)}}},L=async(u,I)=>{if(!(!t||N)&&!(I==="drop"&&!window.confirm(`Drop ${u.ref}?`))){C(`${I}:${u.ref}`);try{I==="apply"&&await Mr(t,{ref:u.ref}),I==="pop"&&await Pr(t,{ref:u.ref}),I==="drop"&&await Lr(t,{ref:u.ref});const H=I==="apply"?"Stash applied":I==="pop"?"Stash popped":"Stash dropped";g.success(H),await W({affectsIndex:I!=="drop"})}catch(H){const J=I==="apply"?"Failed to apply stash":I==="pop"?"Failed to pop stash":"Failed to drop stash";g.error(H instanceof Error?H.message:J),await W({affectsIndex:I!=="drop"})}finally{C(null)}}},A=N!==null;return e.jsx(ke,{open:l,onOpenChange:r,children:e.jsxs(Re,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(Ie,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(R,{name:"archive-stack",className:"h-5 w-5"}),"Stashes"]}),e.jsx($e,{children:"Save, restore, and clean up Git stashes for this repository."})]}),e.jsxs("div",{className:"mt-2 rounded-lg border border-border/60 bg-[var(--surface-elevated)] p-3",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsx(ss,{value:h,onChange:u=>d(u.target.value),placeholder:"Stash name",disabled:A||!j,className:"flex-1"}),e.jsxs(D,{onClick:M,disabled:!j||A||!t,children:[N==="create"?e.jsx(R,{name:"loader-4",className:"size-4 animate-spin"}):e.jsx(R,{name:"inbox-archive",className:"size-4"}),`Stash ${p} files`]})]}),e.jsx("p",{className:"typography-meta mt-2 text-muted-foreground",children:"Untracked files are included automatically."})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(R,{name:"search",className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(ss,{value:m,onChange:u=>v(u.target.value),placeholder:"Search stashes",className:"pl-9"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:y?e.jsx("div",{className:"flex items-center justify-center py-10 text-muted-foreground",children:e.jsx(R,{name:"loader-4",className:"size-5 animate-spin"})}):z.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:m?"No matching stashes.":"No stashes yet."}):z.map((u,I)=>e.jsxs("div",{className:"group flex items-center gap-2 rounded py-1.5 transition-colors hover:bg-interactive-hover/30",children:[e.jsxs("div",{className:"min-w-0 flex-1 pl-2",children:[e.jsx("p",{className:"typography-small truncate text-foreground",children:u.message||"Untitled stash"}),e.jsxs("p",{className:"typography-meta truncate text-muted-foreground",children:[e.jsxs(st,{children:[e.jsx(rt,{asChild:!0,children:e.jsx("span",{children:I===0&&!m.trim()?"Latest":`#${I+1}`})}),e.jsx(at,{sideOffset:6,children:u.ref})]})," · ",u.relativeTime," · ",typeof k[u.ref]=="number"?`${k[u.ref]} files`:"counting files..."]})]}),e.jsxs("div",{className:"mr-2 flex shrink-0 items-center gap-1 opacity-100 sm:opacity-0 sm:group-hover:opacity-100",children:[e.jsx(St,{label:"Apply",loading:N===`apply:${u.ref}`,onClick:()=>L(u,"apply"),disabled:A,children:e.jsx(R,{name:"inbox-unarchive",className:"size-4"})}),e.jsx(St,{label:"Pop",loading:N===`pop:${u.ref}`,onClick:()=>L(u,"pop"),disabled:A,children:e.jsx(R,{name:"inbox-unarchive-fill",className:"size-4"})}),e.jsx(St,{label:"Drop",loading:N===`drop:${u.ref}`,onClick:()=>L(u,"drop"),disabled:A,destructive:!0,children:e.jsx(R,{name:"delete-bin",className:"size-4"})})]})]},u.ref))})]})})},St=({label:l,loading:r,disabled:t,destructive:j,onClick:b,children:p})=>e.jsxs(st,{children:[e.jsx(rt,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":l,"aria-busy":r||void 0,className:ee("flex h-6 w-6 items-center justify-center transition-colors disabled:opacity-50",j?"text-[var(--status-error)] hover:text-[var(--status-error)]":"text-muted-foreground hover:text-foreground"),onClick:b,disabled:t,children:r?e.jsx(R,{name:"loader-4",className:"size-4 animate-spin"}):p})}),e.jsx(at,{sideOffset:6,children:l})]}),Ea=({onOpenStashes:l})=>e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 px-4 text-center",children:[e.jsx(R,{name:"git-commit",className:"size-10 text-muted-foreground/70 mb-4"}),e.jsx("p",{className:"typography-ui-label font-semibold text-foreground mb-1",children:"Working tree clean"}),e.jsx("p",{className:"typography-meta text-muted-foreground mb-4",children:"All changes have been committed"}),l?e.jsxs(D,{type:"button",variant:"outline",size:"sm",onClick:l,className:"gap-1.5",children:[e.jsx(R,{name:"archive-stack",className:"size-4"}),"Stashes"]}):null]}),Ne=8,Fa=({laned:l,totalLanes:r,isExpanded:t})=>{const{lane:j,color:b,connectors:p}=l,w=Math.max(r,j+1)*Ne+Ne/2,S=n.useRef(null),y=n.useRef(null);return n.useLayoutEffect(()=>{const F=S.current,m=y.current;if(!F||!m)return;const v=F.offsetHeight;if(v===0)return;const h=window.devicePixelRatio||1;m.width=w*h,m.height=v*h;const d=m.getContext("2d");if(!d)return;d.scale(h,h),d.clearRect(0,0,w,v);const N=v/2,C=j*Ne+Ne/2,k=getComputedStyle(m),Y=k.getPropertyValue("--surface-muted-foreground").trim()||k.color,G=M=>{if(!M.startsWith("var("))return M;const L=M.slice(4,-1).trim();return k.getPropertyValue(L).trim()||Y},z=[...p].sort((M,L)=>{const A=u=>u==="branch-out"||u==="merge-in";return(A(M.type)?1:0)-(A(L.type)?1:0)});for(const M of z){const L=M.fromLane*Ne+Ne/2,A=M.toLane*Ne+Ne/2,u=M.type==="passing"?.72:M.type==="branch-out"||M.type==="merge-in"?.95:1;switch(d.beginPath(),d.strokeStyle=G(M.color),d.globalAlpha=u,d.lineWidth=1.25,d.lineCap="round",M.type){case"passing":case"commit-lane":d.moveTo(L,0),d.lineTo(L,v);break;case"top-stub":d.moveTo(L,0),d.lineTo(L,N);break;case"bottom-stub":d.moveTo(L,N),d.lineTo(L,v);break;case"branch-out":{const I=(N+v)/2;d.moveTo(C,N),d.bezierCurveTo(C,I,A,I,A,v);break}case"merge-in":{const I=N/2;d.moveTo(L,0),d.bezierCurveTo(L,I,C,I,C,N);break}default:continue}d.stroke(),d.globalAlpha=1}const W=k.getPropertyValue("--background").trim()||k.getPropertyValue("--surface-background").trim();d.beginPath(),d.arc(C,N,4,0,Math.PI*2),d.fillStyle=G(b),d.fill(),d.beginPath(),d.arc(C,N,5,0,Math.PI*2),d.strokeStyle=W||Y,d.lineWidth=2,d.stroke()},[l,j,b,p,r,t,w]),e.jsx("div",{ref:S,style:{width:w,height:"100%",position:"relative",flexShrink:0,overflow:"hidden"},children:e.jsx("canvas",{ref:y,style:{position:"absolute",inset:0,width:"100%",height:"100%",display:"block"}})})},ls=15e3,cs=500,ds=12,us=8*1024*1024,ms=l=>typeof l=="string"?0:(l.original?.length??0)+(l.modified?.length??0),hs=l=>{if(l.size<=ds){let b=0;for(const p of l.values())b+=ms(p);if(b<=us)return l}const r=Array.from(l.entries()).reverse(),t=new Map;let j=0;for(const[b,p]of r){if(t.size>=ds)continue;const x=ms(p);j+x>us&&t.size>0||(t.set(b,p),j+=x)}return new Map(Array.from(t.entries()).reverse())};function fs(l,r){const t=new Date(l);return Number.isNaN(t.getTime())?l:Dr(t,r,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Ma(l){switch(l){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 Pa(l){return l?l.split(",").map(r=>r.trim()).filter(Boolean).map(r=>{const t=r.startsWith("HEAD ->");return{label:t?r.replace("HEAD -> ",""):r.replace("tag: ",""),isHead:t,isTag:r.startsWith("tag: ")}}):[]}const La=n.memo(({entry:l,mode:r="history",laned:t,totalLanes:j,isExpanded:b,onToggle:p,files:x,isLoadingFiles:w,onCopyHash:S,directory:y,onConflict:F,onActionSuccess:m})=>{const v=ks(c=>c.timeFormatPreference),h=r==="graph",d={checkout:"Check out this commit as detached HEAD?",cherryPick:"Cherry-pick this commit onto the current branch?",revert:"Stage a revert of this commit?",merge:"Merge this commit into the current branch?",rebase:"Rebase current branch onto this commit?",resetSoft:"Soft reset — HEAD moves, staged changes preserved.",resetMixed:"Mixed reset — HEAD moves, changes unstaged.",resetHard:"Hard reset — HEAD moves, all uncommitted changes permanently discarded."},N={soft:"Soft — keep staged",mixed:"Mixed — unstage changes",hard:"Hard — discard all changes"},[C,k]=n.useState(null),[Y,G]=n.useState(!1),[z,W]=n.useState(""),[M,L]=n.useState(null),[A,u]=n.useState(new Set),[I,H]=n.useState(new Map),[J,V]=n.useState(new Set),te=async()=>{if(y){k("checkout");try{await Ur(y,l.hash),g.success("Checked out (detached HEAD)"),m?.()}catch(c){g.error(String(c.message))}finally{k(null)}}},T=async()=>{if(!(!y||!z.trim())){k("createBranch");try{await zr(y,z.trim(),l.hash),G(!1),W(""),m?.()}catch(c){g.error(String(c.message))}finally{k(null)}}},Q=async()=>{if(y){k("cherryPick");try{const c=await Hr(y,l.hash);c.conflict?F?.({conflict:!0,conflictFiles:c.conflictFiles,operation:"cherry-pick"}):m?.()}catch(c){g.error(String(c.message))}finally{k(null)}}},ue=async()=>{if(y){k("revert");try{const c=await _r(y,l.hash);c.conflict?F?.({conflict:!0,conflictFiles:c.conflictFiles,operation:"revert"}):m?.()}catch(c){g.error(String(c.message))}finally{k(null)}}},ne=async(c,$=!1)=>{if(!(!y||C!==null)){k("reset");try{await Gr(y,l.hash,c,$),m?.()}catch(_){g.error(String(_.message))}finally{k(null)}}},Fe=async()=>{if(!M)return;const c=M;switch(L(null),c){case"checkout":return te();case"cherryPick":return Q();case"revert":return ue();case"merge":return Be();case"rebase":return me();case"resetSoft":return ne("soft");case"resetMixed":return ne("mixed");case"resetHard":return ne("hard",!0)}},Be=async()=>{if(y){k("merge");try{const c=await Or(y,{branch:l.hash});c.conflict?F?.({conflict:!0,conflictFiles:c.conflictFiles,operation:"merge"}):m?.()}catch(c){g.error(String(c.message))}finally{k(null)}}},me=async()=>{if(y){k("rebase");try{const c=await Tr(y,{onto:l.hash});c.conflict?F?.({conflict:!0,conflictFiles:c.conflictFiles,operation:"rebase"}):m?.()}catch(c){g.error(String(c.message))}finally{k(null)}}},P=n.useCallback(async c=>{const $=c.path;if(!y){H(_=>new Map(_).set($,"error"));return}H(_=>hs(new Map(_).set($,"loading")));try{const _=$r(y,l.hash,c.path,!1),he=new Promise((fe,X)=>{setTimeout(()=>X(new Error(`Timed out after ${ls}ms`)),ls)}),we=await Promise.race([_,he]);H(fe=>hs(new Map(fe).set($,we)))}catch{H(_=>new Map(_).set($,"error"))}},[y,l.hash]),K=n.useCallback(async c=>{const $=c.path;if(c.changeType==="R"||c.isBinary){u(fe=>{const X=new Set(fe);return X.has($)?X.delete($):X.add($),X});return}const _=I.get($);if(A.has($)&&_&&_!=="error"){u(fe=>{const X=new Set(fe);return X.delete($),X});return}u(fe=>{const X=new Set(fe);return X.add($),X}),!(_&&_!=="error"||c.insertions+c.deletions>cs&&!J.has($))&&await P(c)},[I,J,P,A]);return e.jsxs("li",{children:[e.jsxs("div",{role:"button",tabIndex:0,"aria-expanded":b,onClick:p,onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),p())},className:ee("w-full flex items-start gap-3 px-3 py-2 text-left transition-colors",h?"hover:bg-[var(--interactive-hover)]/40":b?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[h&&t&&j!==void 0?e.jsx("div",{className:"-my-2 shrink-0 self-stretch",children:e.jsx(Fa,{laned:t,totalLanes:j,isExpanded:b})}):e.jsx("div",{className:"h-2 w-2 translate-y-2 rounded-full shrink-0",style:{backgroundColor:"var(--status-success)"},"aria-hidden":!0}),e.jsxs("div",{className:"min-w-0 flex-1",children:[h?(()=>{const c=Pa(l.refs);return c.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 mb-0.5",children:c.map($=>e.jsx("span",{className:ee("inline-flex items-center px-1.5 py-0 typography-micro rounded font-medium",$.isHead?"bg-[var(--chart-1)] text-[var(--primary-foreground)]":$.isTag?"bg-[var(--chart-5)] text-[var(--primary-foreground)]":"bg-[var(--interactive-hover)] text-[var(--foreground)]"),children:$.label},$.label))}):null})():null,e.jsx("p",{className:"typography-ui-label font-medium text-foreground line-clamp-1",children:l.message}),e.jsxs("div",{className:"flex items-center gap-1 typography-meta text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1 min-w-0 truncate",children:[e.jsx("span",{className:"truncate min-w-[3ch]",title:l.author_name,children:l.author_name}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("span",{className:"truncate min-w-0",title:fs(l.date,v),children:fs(l.date,v)})]}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("code",{className:"shrink-0 font-mono",children:l.hash.slice(0,8)}),e.jsxs(st,{children:[e.jsx(rt,{asChild:!0,children:e.jsx(D,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:c=>{c.stopPropagation(),S(l.hash)},children:e.jsx(R,{name:"file-copy",className:"size-3"})})}),e.jsx(at,{sideOffset:8,children:"Copy SHA"})]})]})]})]}),b&&e.jsxs("div",{className:"px-3 pb-2 pl-8 border-t border-border/40",children:[h&&M?e.jsxs("div",{className:"flex items-center gap-2 py-2 border-b border-border/30 mb-2",children:[e.jsx("span",{className:"typography-micro text-muted-foreground flex-1 min-w-0",children:d[M]}),e.jsxs(D,{variant:"destructive",size:"xs",className:"h-6 shrink-0",disabled:C!==null,onClick:c=>{c.stopPropagation(),Fe()},children:[C!==null?e.jsx(R,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,"Confirm"]}),e.jsx(D,{variant:"ghost",size:"xs",className:"h-6 shrink-0",disabled:C!==null,onClick:c=>{c.stopPropagation(),L(null)},children:"Cancel"})]}):h?e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 py-2 border-b border-border/30 mb-2",children:[e.jsx(D,{variant:"outline",size:"xs",className:"h-6",disabled:C!==null,onClick:c=>{c.stopPropagation(),L("checkout")},children:"Checkout"}),Y?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("input",{autoFocus:!0,value:z,onChange:c=>W(c.target.value),onKeyDown:c=>{c.key==="Enter"&&T(),c.key==="Escape"&&(G(!1),W(""))},placeholder:"Branch name",className:"h-6 text-xs px-2 rounded border border-border/60 bg-background min-w-0 w-32"}),e.jsxs(D,{variant:"outline",size:"xs",className:"h-6",disabled:!z.trim()||C!==null,onClick:c=>{c.stopPropagation(),T()},children:[C==="createBranch"?e.jsx(R,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,"Create"]})]}):e.jsx(D,{variant:"outline",size:"xs",className:"h-6",onClick:c=>{c.stopPropagation(),G(!0)},children:"Create branch here"}),e.jsx(D,{variant:"outline",size:"xs",className:"h-6",disabled:C!==null,onClick:c=>{c.stopPropagation(),L("cherryPick")},children:"Cherry-pick"}),e.jsx(D,{variant:"outline",size:"xs",className:"h-6",disabled:C!==null,onClick:c=>{c.stopPropagation(),L("revert")},children:"Revert"}),e.jsxs(ys,{children:[e.jsx(js,{asChild:!0,children:e.jsxs(D,{variant:"outline",size:"xs",className:"h-6",disabled:C!==null,onClick:c=>c.stopPropagation(),children:[C==="reset"?e.jsx(R,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,"Reset..."]})}),e.jsx(ws,{align:"start",className:"min-w-max",children:["soft","mixed","hard"].map(c=>e.jsx(Br,{disabled:C!==null,onSelect:$=>{$.stopPropagation(),L(`reset${c.charAt(0).toUpperCase()+c.slice(1)}`)},children:N[c]},c))})]}),e.jsx(D,{variant:"outline",size:"xs",className:"h-6",disabled:C!==null,onClick:c=>{c.stopPropagation(),L("merge")},children:"Merge into current"}),e.jsx(D,{variant:"outline",size:"xs",className:"h-6",disabled:C!==null,onClick:c=>{c.stopPropagation(),L("rebase")},children:"Rebase onto this"})]}):null,w?e.jsxs("div",{className:"flex items-center gap-2 py-2",children:[e.jsx(R,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Loading files..."})]}):x.length===0?e.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:"No files"}):e.jsx("ul",{className:"space-y-0.5 py-2",children:x.map(c=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:()=>K(c),className:ee("w-full flex items-center gap-2 typography-micro text-left cursor-pointer transition-colors rounded px-1",A.has(c.path)?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[e.jsx("span",{className:ee("font-semibold w-3 text-center shrink-0",Ma(c.changeType)),children:c.changeType}),e.jsx("span",{className:"truncate text-foreground min-w-0",title:c.path,children:c.path}),!c.isBinary&&e.jsxs("span",{className:"shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",c.insertions]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",c.deletions]})]}),c.isBinary&&e.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:"Binary"}),e.jsx(R,{name:A.has(c.path)?"arrow-down-s":"arrow-right-s",className:"size-3 shrink-0 text-muted-foreground"})]}),A.has(c.path)&&e.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:c.changeType==="R"?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Renamed file — diff not supported"}):c.isBinary?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Binary file — no diff available"}):(()=>{const $=c.insertions+c.deletions;if(!J.has(c.path)&&$>cs)return e.jsxs("div",{className:"flex flex-col items-start gap-1 px-3 py-2 text-sm text-muted-foreground",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:`Large diff (${$} changed lines)`}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Rendering may be slow. You can still view the diff by clicking below."}),e.jsx(D,{type:"button",variant:"ghost",size:"xs",className:"h-6 px-0 text-primary hover:bg-transparent hover:underline",onClick:()=>{V(he=>new Set(he).add(c.path)),P(c)},children:"Render anyway"})]});const _=I.get(c.path);return _==="loading"||_===void 0?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Loading diff..."}):_==="error"?e.jsx("button",{type:"button",onClick:()=>K(c),className:"w-full text-left px-3 py-2 text-sm text-muted-foreground hover:bg-[var(--interactive-hover)] transition-colors",children:"Failed to load diff. Click to retry."}):e.jsx(Ca,{original:_.original,modified:_.modified,language:Ar(c.path)||"",fileName:c.path,renderSideBySide:!1,layout:"inline",enableComments:!1})})()})]},c.path))})]})]})}),gs=["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 et(l){return gs[l%gs.length]}function $a(l){if(l.length===0)return[];const r=[],t=[];for(let j=0;j<l.length;j++){const b=l[j],p=[];for(let h=0;h<r.length;h++)r[h]===b.hash&&p.push(h);let x=p.length>0?p[0]:-1;if(x===-1){const h=r.indexOf(null);h!==-1?x=h:(x=r.length,r.push(null))}const w=p.slice(1),S=et(x),y=r[x]===b.hash,F=b.parents.length>0;F?r[x]=b.parents[0]:r[x]=null;const m=[];for(let h=1;h<b.parents.length;h++){const d=b.parents[h],N=r.indexOf(d);if(N!==-1)m.push(N);else{const C=r.indexOf(null),k=C!==-1?C:r.length;r[k]=d,k===r.length&&r.push(d),m.push(k)}}const v=[];y&&F?v.push({fromLane:x,toLane:x,color:S,type:"commit-lane"}):y&&!F?v.push({fromLane:x,toLane:x,color:S,type:"top-stub"}):!y&&F&&v.push({fromLane:x,toLane:x,color:S,type:"bottom-stub"});for(const h of w)v.push({fromLane:h,toLane:x,color:et(h),type:"merge-in"}),r[h]=null;for(const h of m)v.push({fromLane:x,toLane:h,color:et(h),type:"branch-out"});for(let h=0;h<r.length;h++)r[h]!==null&&h!==x&&(m.includes(h)||v.push({fromLane:h,toLane:h,color:et(h),type:"passing"}));t.push({commit:b,lane:x,color:S,connectors:v})}return t}const Ba=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],Aa=({mode:l="history",log:r,isLogLoading:t,logMaxCount:j,onLogMaxCountChange:b,expandedCommitHashes:p,onToggleCommit:x,commitFilesMap:w,loadingCommitHashes:S,onCopyHash:y,directory:F,showHeader:m=!0,contentMaxHeightClassName:v="max-h-[50vh]",branchDivider:h=null,onConflict:d,onActionSuccess:N})=>{const[C,k]=n.useState(!0),Y=l==="graph",G=n.useMemo(()=>Y&&r?$a(r.all):[],[Y,r]),z=n.useMemo(()=>Math.max(1,...G.map(T=>T.lane+1)),[G]),W=n.useMemo(()=>new Map(G.map(T=>[T.commit.hash,T])),[G]);if(!r)return null;const M=h!==null&&h.insertBeforeIndex>0&&h.insertBeforeIndex<r.all.length,L=h!==null&&h.insertBeforeIndex===r.all.length,A=M||L,u=M?r.all.slice(0,h.insertBeforeIndex):L?r.all:[],I=M?r.all.slice(h.insertBeforeIndex):[],H=h?.direction==="down"?e.jsx(R,{name:"arrow-down-s",className:"size-3.5"}):e.jsx(R,{name:"arrow-up",className:"size-3.5"}),J=T=>e.jsx("ul",{className:"divide-y divide-border/60",children:T.map(Q=>e.jsx(La,{entry:Q,mode:l,laned:Y?W.get(Q.hash):void 0,totalLanes:Y?z:void 0,isExpanded:p.has(Q.hash),onToggle:()=>x(Q.hash),files:w.get(Q.hash)??[],isLoadingFiles:S.has(Q.hash),onCopyHash:y,directory:F,onConflict:d,onActionSuccess:N},Q.hash))}),V=r.all.length>=j?e.jsx("div",{className:"flex justify-center py-2 border-t border-border/40",children:e.jsx(D,{type:"button",variant:"ghost",size:"xs",onClick:()=>b(j+25),disabled:t,className:"px-3 text-muted-foreground hover:text-foreground",children:t?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(R,{name:"loader-4",className:"size-3 animate-spin"}),"Loading..."]}):"Load more"})}):null,te=e.jsx(Wr,{outerClassName:`min-h-0 ${v}`,className:"h-full w-full",children:r.all.length===0?e.jsx("div",{className:"flex h-full items-center justify-center p-4",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:"No commits found"})}):A&&h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col gap-0",children:[u.length>0?e.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:J(u)}):null,e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5","aria-hidden":!0,children:[e.jsx("span",{className:"h-px flex-1 bg-border/60"}),e.jsxs("span",{className:"inline-flex max-w-[80%] items-center gap-1 typography-micro text-muted-foreground",children:[e.jsx("span",{className:"truncate",title:h.branchName,children:h.branchName}),H]}),e.jsx("span",{className:"h-px flex-1 bg-border/60"})]}),I.length>0?e.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:J(I)}):null]}),V]}):e.jsxs(e.Fragment,{children:[J(r.all),V]})});return m?e.jsxs(ja,{open:C,onOpenChange:k,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(wa,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"History"}),e.jsxs("div",{className:"flex items-center gap-2",children:[C&&e.jsx("div",{onClick:T=>T.stopPropagation(),onPointerDown:T=>T.stopPropagation(),children:e.jsxs(Vr,{value:String(j),onValueChange:T=>b(Number(T)),disabled:t,children:[e.jsx(Yr,{size:"sm",className:"w-auto",disabled:t,children:e.jsx(qr,{placeholder:"Commits"})}),e.jsx(Jr,{children:Ba.map(T=>e.jsx(Kr,{value:String(T.value),children:T.label},T.value))})]})}),C?e.jsx(R,{name:"arrow-up-s",className:"size-4 text-muted-foreground"}):e.jsx(R,{name:"arrow-down-s",className:"size-4 text-muted-foreground"})]})]}),e.jsx(va,{children:te})]}):A?e.jsx("section",{className:"h-full min-h-0",children:te}):e.jsx("section",{className:"h-full min-h-0 rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:te})},Da=({open:l,onOpenChange:r,conflictFiles:t=[],directory:j,operation:b,onAbort:p,onClearState:x})=>{const w=kt(u=>u.openNewSessionDraft),S=kt(u=>u.currentSessionId),y=rs(u=>u.setPendingInputText),F=rs(u=>u.setPendingSyntheticParts),m=ks(u=>u.setActiveMainTab),[v,h]=n.useState(!1),[d,N]=n.useState(null),[C,k]=n.useState(null);n.useEffect(()=>{!l||!j||(h(!0),k(null),N(null),Qr(j).then(u=>{N(u)}).catch(u=>{const I=u instanceof Error?u.message:"Failed to load conflict details";k(I)}).finally(()=>{h(!1)}))},[l,j]);const Y=n.useCallback(async()=>{if(!d)return null;const u=b==="merge"?"merge":"rebase",I=d.headInfo||(b==="merge"?"MERGE_HEAD":"REBASE_HEAD"),H=b==="merge"?"git commit --no-edit":"git rebase --continue",J=await as("git.conflict.resolve.visible",{operation_label:u,head_ref:I}),V=await as("git.conflict.resolve.instructions",{operation_label:u,directory:j,operation:b,head_info:d.headInfo||"N/A",continue_cmd:H}),te=`${u} conflict context (JSON)
3
+ ${JSON.stringify({directory:j,operation:d.operation,headInfo:d.headInfo,statusPorcelain:d.statusPorcelain,unmergedFiles:d.unmergedFiles,diff:d.diff},null,2)}`;return{visibleText:J,instructionsText:V,payloadText:te}},[d,j,b]),G=()=>{p(),r(!1)},z=()=>{x?.(),r(!1)},W=async()=>{const u=await Y();if(!u){g.error("No conflict details available");return}if(!S){g.error("No active session",{description:"Open or create a session to resolve conflicts."});return}y(u.visibleText,"replace"),F([{text:u.instructionsText,synthetic:!0},{text:u.payloadText,synthetic:!0}]),m("chat"),x?.(),r(!1)},M=async()=>{const u=await Y();if(!u){g.error("No conflict details available");return}w({directoryOverride:j,initialPrompt:u.visibleText,syntheticParts:[{text:u.instructionsText,synthetic:!0},{text:u.payloadText,synthetic:!0}]}),m("chat"),x?.(),r(!1)},L=b==="merge"?"Merge":"Rebase",A=d?.unmergedFiles||t;return e.jsx(ke,{open:l,onOpenChange:r,children:e.jsx(Re,{className:"max-w-md w-[calc(100vw-2rem)]",children:e.jsxs("div",{className:"flex flex-col gap-4 overflow-hidden",children:[e.jsxs(Ie,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{name:"alert",className:"size-5 shrink-0 text-[var(--status-warning)]"}),e.jsx(Ee,{children:`${L} conflicts detected`})]}),e.jsx($e,{children:`Resolve the ${b} conflicts to continue.`})]}),v&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-4 text-muted-foreground",children:[e.jsx(R,{name:"loader-4",className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-meta",children:"Loading conflict details..."})]}),C&&e.jsx("div",{className:"rounded-lg bg-[var(--status-error-bg)] p-3 text-[var(--status-error)] typography-meta break-words",children:`Failed to load conflict details: ${C}`}),A.length>0&&e.jsxs("div",{className:"space-y-2 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Conflicted files:"}),e.jsx("span",{className:"typography-micro px-1.5 py-0.5 rounded bg-[var(--surface-elevated)] text-muted-foreground",children:A.length})]}),e.jsx("div",{className:"bg-[var(--surface-elevated)] rounded-lg p-3 max-h-40 overflow-y-auto overflow-x-hidden",children:e.jsx("ul",{className:"space-y-1",children:A.map(u=>e.jsx("li",{className:"typography-micro text-foreground font-mono truncate block",title:u,children:u},u))})})]}),d?.headInfo&&e.jsxs("div",{className:"space-y-1 overflow-hidden",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"HEAD information:"}),e.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:d.headInfo})]}),e.jsxs("div",{className:"flex flex-col gap-2 pt-2",children:[e.jsxs(D,{variant:"default",onClick:()=>{M()},disabled:v||!d,className:"w-full gap-2",children:[v?e.jsx(R,{name:"loader-4",className:"size-4 animate-spin"}):e.jsx(R,{name:"add",className:"size-4"}),"Resolve in new session"]}),e.jsxs(D,{variant:"outline",onClick:()=>{W()},disabled:v||!d||!S,className:"w-full gap-2",children:[v?e.jsx(R,{name:"loader-4",className:"size-4 animate-spin"}):e.jsx(R,{name:"chat-1",className:"size-4"}),"Resolve in current session"]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(D,{variant:"ghost",size:"sm",onClick:z,className:"flex-1",children:"Continue later"}),e.jsx(D,{variant:"destructive",size:"sm",onClick:G,className:"flex-1",children:`Abort ${L}`})]})]})]})})})},za=({open:l,onOpenChange:r,operation:t,targetBranch:j,onConfirm:b})=>{const[p,x]=n.useState(!0),[w,S]=n.useState(!1),y=t==="merge"?"Merge":"Rebase",F=async()=>{S(!0);try{await b(p),r(!1)}catch(v){const h=v instanceof Error?v.message:`Failed to ${t}`;g.error(h)}finally{S(!1)}},m=()=>{w||r(!1)};return e.jsx(ke,{open:l,onOpenChange:w?void 0:r,children:e.jsxs(Re,{className:"max-w-md",children:[e.jsxs(Ie,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{name:"alert",className:"size-5 text-[var(--status-warning)]"}),e.jsx(Ee,{children:"Uncommitted Changes"})]}),e.jsx($e,{children:`Stash your local changes before starting the ${t}.`})]}),e.jsxs("div",{className:"py-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground mb-3",children:"This will:"}),e.jsxs("ol",{className:"list-decimal list-inside space-y-1 typography-meta text-foreground",children:[e.jsx("li",{children:"Stash your uncommitted changes"}),e.jsxs("li",{children:[t==="merge"?"Merge":"Rebase"," ",t==="merge"?"with":"onto"," ",e.jsx("span",{className:"font-mono text-primary",children:j})]}),p&&e.jsx("li",{children:"Restore your stashed changes"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 py-2",children:[e.jsx(Xr,{checked:p,onChange:x,disabled:w,ariaLabel:"Restore stashed changes after operation"}),e.jsx("span",{className:"typography-ui-label text-foreground cursor-pointer select-none",onClick:()=>!w&&x(!p),children:`Restore stashed changes after ${t}`})]}),e.jsxs(Rt,{className:"gap-2",children:[e.jsx(D,{variant:"ghost",size:"sm",onClick:m,disabled:w,children:"Cancel"}),e.jsx(D,{variant:"default",size:"sm",onClick:F,disabled:w,className:"gap-1.5",children:w?e.jsxs(e.Fragment,{children:[e.jsx(R,{name:"loader-4",className:"size-4 animate-spin"}),"Processing..."]}):`${y}`})]})]})})},Ga=({mergeInProgress:l,rebaseInProgress:r,onContinue:t,onAbort:j,onResolveWithAI:b,conflictCount:p=0,isLoading:x=!1})=>{const[w,S]=n.useState(null),y=l&&l.head,F=r&&(r.headName||r.onto),m=y?"merge":F?"rebase":null;if(!m)return null;const v=async()=>{S("continue");try{await t()}finally{S(null)}},h=async()=>{S("abort");try{await j()}finally{S(null)}},d=w!==null,N=p>0,C=m==="merge"?"Merge":"Rebase";let k="";l?k=l.message?`Merging: ${l.message}`:`Merging ${l.head}`:r&&(k=r.headName?`Rebasing ${r.headName} onto ${r.onto||""}`:"Rebase in progress");const Y=N?p===1?`${C} in progress: ${p} conflict`:`${C} in progress: ${p} conflicts`:`${C} in progress`,G=N?"Resolve conflicts, then continue the operation.":"All conflicts resolved. Continue to finish the operation.";return e.jsx("div",{className:"mx-4 mt-3 overflow-hidden rounded-lg border border-[var(--status-warning-border)]",children:e.jsxs("div",{className:"flex flex-col gap-3 p-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"typography-label text-[var(--status-warning)]",children:Y}),k&&e.jsx("p",{className:"typography-micro break-words text-muted-foreground",children:k})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("p",{className:"typography-micro min-w-0 flex-1 text-muted-foreground",children:G}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsxs(D,{variant:"ghost",size:"sm",onClick:h,disabled:d||x,className:"gap-1.5",children:[w==="abort"?e.jsx(R,{name:"loader-4",className:"size-4 animate-spin"}):e.jsx(R,{name:"close",className:"size-4"}),"Abort"]}),N?b&&e.jsx(D,{variant:"default",size:"sm",onClick:b,disabled:d||x,children:"Resolve with AI"}):e.jsxs(D,{variant:"default",size:"sm",onClick:v,disabled:d||x,className:"gap-1.5",children:[w==="continue"?e.jsx(R,{name:"loader-4",className:"size-4 animate-spin"}):e.jsx(R,{name:"check",className:"size-4"}),"Continue"]})]})]})]})})},Ta=({currentBranch:l,localBranches:r,remoteBranches:t,onMerge:j,onRebase:b,disabled:p=!1,isOperating:x=!1,operationLogs:w=[],onOperationComplete:S,mode:y="dialog",defaultTargetBranch:F})=>{const[m,v]=n.useState(!1),[h,d]=n.useState("merge"),[N,C]=n.useState(null),[k,Y]=n.useState(!1),[G,z]=n.useState(""),W=n.useRef(null),M=n.useRef(null),L=p||x,A=l||"current branch",u=w.length>0&&w.every(P=>P.status==="done"||P.status==="error"),I=w.some(P=>P.status==="error");n.useEffect(()=>{M.current&&(M.current.scrollTop=M.current.scrollHeight)},[w]);const H=n.useMemo(()=>{const P=G.toLowerCase(),K=new Set(t.map($=>$.slice($.indexOf("/")+1)).filter(Boolean)),c=r.filter($=>$!==l&&!K.has($));return P?c.filter($=>$.toLowerCase().includes(P)):c},[G,r,l,t]),J=n.useMemo(()=>{const P=G.toLowerCase();return P?t.filter(K=>K.toLowerCase().includes(P)):t},[G,t]),V=n.useCallback(()=>F&&(t.includes(F)||r.includes(F))?F:null,[F,r,t]),te=()=>{v(!0),C(V()),d("merge"),z("")},T=P=>{C(P),Y(!1),z("")},Q=()=>{N&&(h==="merge"?j(N):b(N))},ue=()=>{x||(C(null),d("merge"),z(""),v(!1))},ne=()=>{x&&!u||(u&&S?.(),C(null),d("merge"),z(""),v(!1))};n.useEffect(()=>{k||z("")},[k]),n.useEffect(()=>{y==="dialog"||N||C(V())},[y,V,N]);const me=x?e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{ref:M,className:"rounded-lg border border-border bg-muted/30 p-3 max-h-48 overflow-y-auto",children:e.jsx("div",{className:"space-y-2",children:w.map((P,K)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"mt-0.5 shrink-0",children:[P.status==="running"&&e.jsx(R,{name:"loader-4",className:"size-3.5 animate-spin text-primary"}),P.status==="done"&&e.jsx(R,{name:"check",className:"size-3.5 text-success"}),P.status==="error"&&e.jsx(R,{name:"close",className:"size-3.5 text-destructive"}),P.status==="pending"&&e.jsx("div",{className:"size-3.5 rounded-full border border-muted-foreground/30"})]}),e.jsx("span",{className:ee("typography-micro",P.status==="error"&&"text-destructive",P.status==="done"&&"text-muted-foreground",P.status==="running"&&"text-foreground",P.status==="pending"&&"text-muted-foreground/60"),children:P.message})]},K))})}),u?y==="dialog"?e.jsx(Rt,{children:e.jsx(D,{variant:"default",size:"sm",onClick:ne,children:I?"Close":"Done"})}):e.jsx("div",{className:"flex justify-end",children:e.jsx(D,{variant:"default",size:"sm",onClick:ne,children:I?"Close":"Done"})}):null]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Operation"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>d("merge"),className:ee("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",h==="merge"?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{name:"git-merge",className:ee("size-4",h==="merge"?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:ee("typography-ui-label",h==="merge"?"text-foreground":"text-muted-foreground"),children:"Merge"})]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Create a merge commit and preserve branch history."})]}),e.jsxs("button",{type:"button",onClick:()=>d("rebase"),className:ee("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",h==="rebase"?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{name:"git-branch",className:ee("size-4",h==="rebase"?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:ee("typography-ui-label",h==="rebase"?"text-foreground":"text-muted-foreground"),children:"Rebase"})]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Replay your commits on top of the selected branch."})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:h==="merge"?`Branch to merge into ${A}`:"Branch to rebase onto"}),e.jsxs(ys,{open:k,onOpenChange:Y,modal:!1,children:[e.jsx(js,{asChild:!0,children:e.jsxs("button",{type:"button",className:ee(Zr({size:"default"}),"w-full"),children:[e.jsx("span",{className:ee("truncate",!N&&"text-muted-foreground"),children:N||"Select Branch"}),e.jsx(R,{name:"arrow-down-s",className:"size-4 opacity-60 shrink-0"})]})}),e.jsx(ws,{align:"start",sideOffset:6,className:"w-[var(--anchor-width)] p-0 max-h-[min(var(--available-height),24rem)] flex flex-col overflow-hidden",children:e.jsxs(vs,{className:"h-full min-h-0",children:[e.jsx(Cs,{ref:W,placeholder:"Search branches...",value:G,onValueChange:z,onKeyDown:P=>P.stopPropagation()}),e.jsxs(Ns,{className:"h-full min-h-0",disableHorizontal:!0,children:[e.jsx(Ss,{children:"No branches found."}),H.length>0&&e.jsx(It,{heading:"Local branches",children:H.map(P=>e.jsx(Et,{onSelect:()=>T(P),children:e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:P})},`local-${P}`))}),H.length>0&&J.length>0?e.jsx(ea,{}):null,J.length>0&&e.jsx(It,{heading:"Remote branches",children:J.map(P=>e.jsx(Et,{onSelect:()=>T(P),children:e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:P})},`remote-${P}`))})]})]})})]})]}),N?e.jsx("div",{className:"rounded-lg bg-muted/50 p-3",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:h==="merge"?e.jsxs(e.Fragment,{children:["This will merge"," ",e.jsx("span",{className:"font-mono text-foreground",children:N})," ","into"," ",e.jsx("span",{className:"font-mono text-foreground",children:A})]}):e.jsxs(e.Fragment,{children:["This will rebase"," ",e.jsx("span",{className:"font-mono text-foreground",children:A})," ","onto"," ",e.jsx("span",{className:"font-mono text-foreground",children:N})]})})}):null,y==="dialog"?e.jsxs(Rt,{className:"gap-2 pt-1",children:[e.jsx(D,{variant:"ghost",size:"sm",onClick:ue,children:"Cancel"}),e.jsx(D,{variant:"default",size:"sm",onClick:Q,disabled:!N,className:"gap-1.5",children:h==="merge"?e.jsxs(e.Fragment,{children:[e.jsx(R,{name:"git-merge",className:"size-4"}),"Merge"]}):e.jsxs(e.Fragment,{children:[e.jsx(R,{name:"git-branch",className:"size-4"}),"Rebase"]})})]}):e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(D,{variant:"destructive",size:"sm",onClick:ue,disabled:L,children:"Reset"}),e.jsx("div",{className:"flex-1"}),e.jsx(D,{variant:"default",size:"sm",onClick:Q,disabled:L||!N,children:h==="merge"?"Merge":"Rebase"})]})]});return y==="bare"?me:y==="inline"?e.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[e.jsx("header",{className:"border-b border-border/40 px-0 py-3",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:"Update branch"}),e.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Bring the latest changes into"," ",e.jsx("span",{className:"font-mono text-foreground",children:A}),"."]})]})}),e.jsx("div",{className:"pt-3",children:me})]}):e.jsxs(e.Fragment,{children:[e.jsxs(st,{children:[e.jsx(rt,{asChild:!0,children:e.jsxs(D,{variant:"outline",size:"sm",className:"gap-1.5",onClick:te,disabled:L,children:[x?e.jsx(R,{name:"loader-4",className:"size-4 animate-spin"}):e.jsx(R,{name:"git-merge",className:"size-4"}),e.jsx("span",{children:"Merge/Rebase"})]})}),e.jsx(at,{sideOffset:8,children:"Update this branch from another branch."})]}),e.jsx(ke,{open:m,onOpenChange:P=>{P?v(!0):ne()},children:e.jsxs(Re,{className:"max-w-md",children:[e.jsxs(Ie,{children:[e.jsx(Ee,{children:"Update branch"}),e.jsx($e,{children:x?u?I?"Operation Failed":"Operation Completed":h==="merge"?"Merging In Progress":"Rebasing In Progress":e.jsxs(e.Fragment,{children:["Choose how to bring another branch into"," ",e.jsx("span",{className:"font-mono text-foreground",children:A}),"."]})})]}),me]})})]})},Oa=l=>{const{remoteNames:r,localBranches:t,worktreeCreatedFromBranch:j,rootBranchHint:b,defaultBranch:p,headBranch:x}=l,w=typeof x=="string"?x.trim():"",S=h=>{if(!h)return"";let d=h.trim();if(!d||d==="HEAD")return"";if(t.includes(d))return d;d.startsWith("refs/heads/")&&(d=d.slice(11)),d.startsWith("heads/")&&(d=d.slice(6)),d.startsWith("remotes/")&&(d=d.slice(8));const N=d.indexOf("/");if(N>0){const C=d.slice(0,N);if(r.has(C)){const k=d.slice(N+1).trim();k&&(d=k)}}return d},y=h=>{const d=S(typeof h=="string"?h:"");return d&&d!==w?d:""},F=y(j);if(F)return F;const m=y(b);if(m)return m;const v=y(p);return v||(t.includes("main")?"main":t.includes("master")?"master":t.includes("develop")?"develop":"main")},_a=l=>{const{baseBranch:r,localBranches:t,remoteBranches:j}=l;return t.includes(r)?!0:j.some(b=>{const p=b.indexOf("/");return p>0&&b.slice(p+1)===r})},Ha=({runMutation:l,onMutationComplete:r,onMutationError:t,onPathsComplete:j,scheduleFlush:b})=>{const p=[];let x=!1;return{enqueue:S=>{const y=p[p.length-1];if(y?.directory===S.directory&&y.direction===S.direction){S.paths.forEach(F=>y.paths.add(F));return}p.push(S)},flush:()=>{if(x)return;const S=p.shift();if(!S)return;x=!0;const y={directory:S.directory,direction:S.direction,paths:Array.from(S.paths),rollback:S.rollback};(async()=>{try{await l(y),r(y)}catch(F){t(y,F)}finally{j(y.paths),x=!1,p.length>0&&b()}})()},clear:()=>{p.length=0},size:()=>p.length,isRunning:()=>x}},ps=ga(()=>Rr(()=>import("./DiffView-k3lX2PiV.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118])).then(l=>({default:l.DiffView}))),Ua=15e3,Wa=40,Va=20,xs={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:"},Ya=(l,r)=>{const t=l.toLowerCase(),j=/^([a-z]+)(?:\(.*\))?!?:/,b=t.match(j);if(b){const w=b[1],S=xs[w];if(S)return r.find(y=>y.code===S)||null}const p=t.split(" ")[0],x=xs[p];return x&&r.find(w=>w.code===x)||null},qa=20,Le=new Map,Ja=(l,r)=>{if(Le.delete(l),Le.set(l,r),Le.size>qa){const t=Le.keys().next().value;t!==void 0&&Le.delete(t)}},tt=l=>(l||"").replace(/\\/g,"/").replace(/\/+$/,""),bs=l=>{const r=l.index?.trim();return!!(r&&r!=="?")},ii=({isActive:l})=>{const{git:r}=ta(),t=sa(),j=kt(s=>s.currentSessionId),{profiles:b,globalIdentity:p,defaultGitIdentityId:x,loadProfiles:w,loadGlobalIdentity:S,loadDefaultGitIdentityId:y}=pa(ns(s=>({profiles:s.profiles,globalIdentity:s.globalIdentity,defaultGitIdentityId:s.defaultGitIdentityId,loadProfiles:s.loadProfiles,loadGlobalIdentity:s.loadGlobalIdentity,loadDefaultGitIdentityId:s.loadDefaultGitIdentityId}))),F=ra(t??null),m=aa(t??null),v=na(t??null),h=oa(t??null),d=ia(t??null),N=la(t??null),C=ca(t??null),{setActiveDirectory:k,fetchAll:Y,ensureAll:G,fetchStatus:z,fetchBranches:W,fetchLog:M,setLogMaxCount:L,fetchIdentity:A,prefetchDiffs:u,clearDiffCache:I,moveStatusPathsOptimistically:H,restoreStatus:J,bumpIndexRevision:V}=da(ns(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})));n.useRef(null);const te=n.useRef(null),T=n.useRef(null),Q=n.useRef(null),ue=n.useRef(!0);n.useEffect(()=>()=>{ue.current=!1},[]);const ne=n.useCallback(()=>{te.current!==null&&(window.clearTimeout(te.current),te.current=null)},[]),Fe=n.useCallback(s=>{ne(),te.current=window.setTimeout(()=>{te.current=null,tt(s)===tt(t)&&z(s,r,{silent:!0})},Ua)},[ne,t,z,r]);n.useEffect(()=>ne,[ne]);const Be=n.useCallback(()=>{T.current!==null&&(window.clearTimeout(T.current),T.current=null)},[]),me=n.useCallback(()=>{T.current===null&&(T.current=window.setTimeout(()=>{T.current=null,Q.current?.()},0))},[]),P=n.useCallback(async(s,o,a)=>{if(o==="stage"){if(r.stageGitFiles){await r.stageGitFiles(s,a);return}await Promise.all(a.map(i=>r.stageGitFile(s,i)));return}if(r.unstageGitFiles){await r.unstageGitFiles(s,a);return}await Promise.all(a.map(i=>r.unstageGitFile(s,i)))},[r]),K=n.useMemo(()=>Ha({runMutation:({directory:s,direction:o,paths:a})=>P(s,o,a),onMutationComplete:({directory:s})=>{V(s),Fe(s)},onMutationError:({directory:s,direction:o,rollback:a},i)=>{a?.(),V(s),Fe(s);const f=o==="stage"?"Failed to stage changes":"Failed to unstage changes";g.error(i instanceof Error?i.message:f)},onPathsComplete:s=>{Dt(o=>{const a=new Set(o);return s.forEach(i=>a.delete(i)),a})},scheduleFlush:me}),[V,P,me,Fe]);n.useEffect(()=>(Q.current=K.flush,()=>{Q.current=null}),[K]),n.useEffect(()=>()=>K.clear(),[K]),n.useEffect(()=>Be,[Be]);const c=n.useMemo(()=>t?Le.get(t)??null:null,[t]),$=ua(s=>s.settingsGitmojiEnabled),{gitmojis:_}=Ra($),[he,we]=n.useState(c?.commitMessage??""),[fe,X]=n.useState(!1),Ft=n.useRef(null),[Mt,Ge]=n.useState(null),[Fs,nt]=n.useState(!1),[Pt,Lt]=n.useState(null),[ge,Ms]=n.useState(25),[Ps,$t]=n.useState(!1),{triggerFireworks:Ls}=xa(),Bt=n.useRef(new Map),Te=n.useRef(0),ot=n.useCallback(()=>{Te.current+=1,ue.current&&$t(!0)},[]),it=n.useCallback(()=>{Te.current=Math.max(0,Te.current-1),ue.current&&Te.current===0&&$t(!1)},[]),[At,Oe]=n.useState(new Set),[$s,Dt]=n.useState(new Set),[zt,Gt]=n.useState(!1),[Ka,Bs]=n.useState(0),[As,Tt]=n.useState(!1),[lt,Ot]=n.useState(c?.generatedHighlights??[]),_e=n.useCallback(()=>Ot([]),[]),[Ds,_t]=n.useState(!1),zs=$s.size>0||K.size()>0||K.isRunning(),Ht=n.useCallback(()=>{const s=Ft.current;s&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{s.scrollTo({top:s.scrollHeight,behavior:"smooth"})})})},[]),[ct,Gs]=n.useState(new Set),[He,Ts]=n.useState(new Map),[Ue,dt]=n.useState(new Set),ut=n.useRef(He),Ae=n.useRef(Ue),[mt,ht]=n.useState([]),[Se,ft]=n.useState(null),[Os,Ut]=n.useState(null),[Wt,gt]=n.useState(null),[_s,We]=n.useState([]),[Hs,ie]=n.useState(!1),[Us,pe]=n.useState([]),[Ve,xe]=n.useState("merge"),[Ws,pt]=n.useState(null),[xt,Vt]=n.useState(!1),[bt,Vs]=n.useState(100),[Ys,qs]=n.useState(0),[Z,Ye]=n.useState(null),[Js,Me]=n.useState(null),[Yt,qt]=n.useState(""),le=n.useMemo(()=>j?`pichamber.conflict:${j}`:null,[j]),be=n.useCallback((s,o,a)=>{if(!le||typeof window>"u")return;const i={directory:s,conflictFiles:o,operation:a};window.localStorage.setItem(le,JSON.stringify(i))},[le]),oe=n.useCallback(()=>{!le||typeof window>"u"||window.localStorage.removeItem(le)},[le]);n.useEffect(()=>{if(!le||typeof window>"u"||!t)return;const s=window.localStorage.getItem(le);if(s)try{const o=JSON.parse(s);if(o.directory!==t){window.localStorage.removeItem(le);return}pe(o.conflictFiles??[]),xe(o.operation??"merge"),ie(!0)}catch{window.localStorage.removeItem(le)}},[le,t]);const[Ks,yt]=n.useState(!1),[jt,Jt]=n.useState("merge"),[wt,Kt]=n.useState(""),Qs=n.useCallback(s=>{ma(s).then(o=>{if(o.ok){g.success("Commit hash copied");return}g.error("Failed to copy")})},[]),Xs=n.useCallback(s=>{Gs(o=>{const a=new Set(o);return a.has(s)?a.delete(s):a.add(s),a})},[]);n.useEffect(()=>{ut.current=He},[He]),n.useEffect(()=>{Ae.current=Ue},[Ue]),n.useEffect(()=>{if(!t||!r)return;const s=Array.from(ct).filter(a=>!ut.current.has(a)&&!Ae.current.has(a));if(s.length===0)return;let o=!1;return dt(a=>{const i=new Set(a);for(const f of s)i.add(f);return Ae.current=i,i}),Promise.all(s.map(a=>r.getCommitFiles(t,a).then(i=>({hash:a,files:i.files})).catch(i=>(console.error("Failed to fetch commit files:",i),{hash:a,files:[]})))).then(a=>{o||(Ts(i=>{const f=new Map(i);for(const{hash:E,files:U}of a)f.set(E,U);return ut.current=f,f}),dt(i=>{const f=new Set(i);for(const{hash:E}of a)f.delete(E);return Ae.current=f,f}))}),()=>{o=!0,dt(a=>{let i=!1;const f=new Set(a);for(const E of s)f.delete(E)&&(i=!0);return i?(Ae.current=f,f):a})}},[ct,t,r]),n.useEffect(()=>{t&&Ja(t,{directory:t,commitMessage:he,generatedHighlights:lt})},[he,t,lt]),n.useEffect(()=>{l&&(w(),S(),y())},[l,w,S,y]),n.useEffect(()=>{if(!l)return;if(!t||!r?.getRemoteUrl){ft(null);return}let s=!1;return r.getRemoteUrl(t).then(o=>{s||ft(o)}).catch(()=>{s||ft(null)}),()=>{s=!0}},[l,t,r]);const qe=n.useCallback(async()=>{if(!t||!r?.getRemotes){ht([]);return}try{const s=await r.getRemotes(t);ue.current&&ht(s)}catch{ue.current&&ht([])}},[t,r]);n.useEffect(()=>{l&&qe()},[l,qe]),n.useEffect(()=>{l&&t&&(k(t),G(t,r))},[l,t,k,G,r]),n.useEffect(()=>{if(l&&t)return ha.onGitRefreshHint(s=>{tt(s.directory)===tt(t)&&(s.paths?.length&&I(t,s.paths),z(t,r,{silent:!0}))})},[l,I,t,z,r]);const O=n.useCallback(async(s=!0)=>{if(t)try{await Promise.all([z(t,r),W(t,r)])}catch(o){if(s){const a=o instanceof Error?o.message:"Failed to refresh repository";g.error(a)}}},[t,r,z,W]),q=n.useCallback(async()=>{t&&await M(t,r,ge)},[t,r,M,ge]),vt=n.useCallback(async()=>{t&&await A(t,r)},[t,r,A]);n.useEffect(()=>{if(!l||!t||!r?.hasLocalIdentity||F!==!0)return;const s=typeof x=="string"?x.trim():"";if(!s||s==="global"||Bt.current.get(t)===s)return;let a=!1;return(async()=>{try{const f=await r.hasLocalIdentity?.(t);if(a||f===!0)return;ot(),await r.setGitIdentity(t,s),Bt.current.set(t,s),await vt()}catch(f){console.warn("Failed to auto-apply default git identity:",f)}finally{a||it()}})(),()=>{a=!0}},[l,ot,t,x,it,r,F,vt]);const ve=n.useMemo(()=>m?[...m.files??[]].sort((o,a)=>o.path.localeCompare(a.path)):[],[m]),ye=n.useMemo(()=>ve.filter(bs),[ve]);n.useEffect(()=>{if(!t||ve.length===0)return;const s=[],o=new Set,a=f=>{!f||o.has(f)||(o.add(f),s.push(f))};if(ye.forEach(f=>a(f.path)),ve.slice(0,Va).forEach(f=>a(f.path)),s.length===0)return;const i=window.setTimeout(()=>{u(t,r,s,{maxFiles:Wa})},120);return()=>{window.clearTimeout(i)}},[ve,t,r,u,ye]);const Qt=s=>s?.pushed[0]?.remote||m?.tracking?.split("/")[0]||ae.find(o=>o.name==="origin")?.name||ae[0]?.name||"origin",Xt=async(s,o)=>{if(t){Ge(s);try{const a=i=>{const f=`${i.name}/`,E=m?.tracking?.startsWith(f)?m.tracking.slice(f.length):void 0;return{remote:i.name,branch:E,rebase:!0}};if(s==="fetch"){if(!o)throw new Error("No remote available for fetch");await r.gitFetch(t,{remote:o.name}),g.success(`Fetched from ${o.name}`)}else if(s==="pull"){if(!o)throw new Error("No remote available for pull");const i=await r.gitPull(t,a(o));g.success(i.files.length===1?`Pulled ${i.files.length} file from ${o.name}`:`Pulled ${i.files.length} files from ${o.name}`)}else if(s==="push"){const i=await r.gitPush(t);g.success(`Pushed to ${Qt(i)}`)}else if(s==="sync"){if(!o)throw new Error("No remote available for sync");let i=0,f=!1;await r.gitFetch(t,{remote:o.name});const E=await r.getGitStatus(t);if((E.behind??0)>0){if((E.files?.length??0)>0){g.error("Commit or stash your changes before syncing");return}i=(await r.gitPull(t,a(o))).files.length}((await r.getGitStatus(t)).ahead??0)>0&&(await r.gitPush(t),f=!0),i>0&&f?g.success(i===1?`Pulled ${i} file from ${o.name} and pushed to upstream`:`Pulled ${i} files from ${o.name} and pushed to upstream`):i>0?g.success(i===1?`Pulled ${i} file from ${o.name}`:`Pulled ${i} files from ${o.name}`):f?g.success(`Pushed to ${o.name}`):g.success("Already up to date")}await O(!1),await q()}catch(a){const i=a instanceof Error?a.message:`${s==="sync"?"Sync Changes":s==="pull"?"Pull":s} failed`;g.error(i)}finally{Ge(null)}}},Zs=n.useCallback(async s=>{if(!t)return;const o=s.name.trim();if(!o){g.error("Remote name is required");return}if(o==="origin"){g.error("Cannot remove the origin remote");return}Ut(o);try{await r.removeRemote(t,{remote:o}),g.success(`Removed remote ${o}`),await Promise.all([O(!1),qe()])}catch(a){const i=a instanceof Error?a.message:`Failed to remove ${o}`;g.error(i)}finally{Ut(null)}},[t,r,qe,O]),Zt=async(s={})=>{if(!t)return;if(!he.trim()){g.error("Enter a commit message");return}const o=ye.map(i=>i.path).sort();if(o.length===0){g.error("Stage at least one file to commit");return}const a=s.pushAfter?"commitAndPush":"commit";Lt(a);try{if(await r.createGitCommit(t,he.trim(),{files:o,stageFiles:[]}),V(t),g.success("Commit created"),we(""),_e(),await O(),s.pushAfter){const i=m?.tracking?.split("/")[0],f=ae.find(kr=>kr.name===i)??ae[0];if(!f)throw new Error("No remote available");Ge("sync");const E=`${f.name}/`,U=m?.tracking?.startsWith(E)?m.tracking.slice(E.length):void 0;await r.gitFetch(t,{remote:f.name});const B=await r.getGitStatus(t);if((B.behind??0)>0){if((B.files?.length??0)>0){g.error("Commit or stash your changes before syncing"),await O(!1);return}await r.gitPull(t,{remote:f.name,branch:U,rebase:!0})}const re=await r.getGitStatus(t);let Pe;(re.ahead??0)>0&&(Pe=await r.gitPush(t)),g.success(`Pushed to ${Qt(Pe)}`),Ls(),await O(!1)}else await O(!1);await q(),Bs(i=>i+1)}catch(i){const f=i instanceof Error?i.message:"Failed to create commit";g.error(f)}finally{Lt(null),s.pushAfter&&Ge(null)}},er=n.useCallback(async()=>{if(!t)return;const s=ye.map(o=>o.path).sort();if(s.length===0){g.error("Stage at least one file to describe");return}console.error("[git-generation][browser] generate button clicked",{directory:t,selectedFiles:s.length}),Tt(!0);try{const{message:o}=await fa(t,s),a=o.subject?.trim()??"",i=Array.isArray(o.highlights)?o.highlights:[];if(a){let f=a;if($&&_.length>0){const E=Ya(a,_);if(E){const{code:U,emoji:B}=E;!a.startsWith(U)&&!a.startsWith(B)&&(f=`${U} ${a}`)}}we(f)}Ot(i),Ht()}catch(o){console.error("[git-generation][browser] GitView generate handler failed",{message:o instanceof Error?o.message:String(o),error:o});const a=o instanceof Error?o.message:"Failed to generate commit message";g.error(a)}finally{Tt(!1)}},[t,ye,$,_,Ht]),tr=async(s,o)=>{if(!t||!m)return;const a=m.current??null,i=o?.name??"origin";try{await r.createBranch(t,s,a??"HEAD"),g.success(`Created branch ${s}`),await r.checkoutBranch(t,s);let f=!1;try{await r.gitPush(t,{remote:i,branch:s,options:["--set-upstream"]}),f=!0}catch(E){const U=E instanceof Error?E.message:`Unable to push new branch to ${i}.`;g.warning("Branch created locally, but failed to set upstream.",{description:e.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",U]})})}await O(),await q(),f&&g.success(`Set upstream for ${s} to ${i}`)}catch(f){const E=f instanceof Error?f.message:"Failed to create branch";throw g.error(E),f}},sr=async(s,o)=>{if(t)try{await r.renameBranch(t,s,o),g.success(`Renamed ${s} to ${o}`),await O(),await q()}catch(a){const i=a instanceof Error?a.message:`Failed to rename ${s} to ${o}`;g.error(i)}},rr=async s=>{if(!t)return;const o=s.replace(/^remotes\//,"");if(m?.current!==o)try{await r.checkoutBranch(t,o),g.success(`Checked out ${o}`),await O(),await q()}catch(a){const i=a instanceof Error?a.message:`Failed to checkout ${o}`;g.error(i)}},ar=async s=>{if(t){ot();try{await r.setGitIdentity(t,s.id),g.success(`Applied identity: ${s.name}`),await vt()}catch(o){const a=o instanceof Error?o.message:"Failed to apply identity";g.error(a)}finally{it()}}},De=n.useMemo(()=>v?.all?v.all.filter(s=>!s.startsWith("remotes/")).sort():[],[v]),je=n.useMemo(()=>v?.all?v.all.filter(s=>s.startsWith("remotes/")).map(s=>s.replace(/^remotes\//,"")).sort():[],[v]),ae=n.useMemo(()=>{if(mt.length>0)return mt;const s=new Set,o=m?.tracking?.trim();o&&o.includes("/")&&s.add(o.split("/")[0]);for(const a of je){const i=a.indexOf("/");i>0&&s.add(a.slice(0,i))}return s.size===0&&Se&&s.add("origin"),Array.from(s).map(a=>({name:a,fetchUrl:Se??"",pushUrl:Se??""}))},[mt,je,Se,m?.tracking]),ce=m?.current??null,es=n.useMemo(()=>{const s=m?.tracking?.trim().split("/")[0];return(s&&v?.defaultBranches?.[s])??v?.defaultBranches?.origin},[v,m?.tracking]),de=n.useMemo(()=>Oa({remoteNames:new Set(ae.map(s=>s.name)),localBranches:De,defaultBranch:es,headBranch:ce}),[ce,es,ae,De]),Ct=!!(ce&&de&&ce!==de&&(m?.tracking||ae.length>0)&&typeof r.getGitRangeDiff=="function"&&_a({baseBranch:de,localBranches:De,remoteBranches:je})),nr=n.useMemo(()=>ae.map(a=>a.name).map(a=>`${a}/${de}`).find(a=>je.includes(a))??de,[de,ae,je]),or=n.useMemo(()=>{const s=new Map;p&&s.set(p.id,p);let o=null;if(Se)try{let a=Se.trim();a.startsWith("git@")&&(a=`https://${a.slice(4).replace(":","/")}`),a.endsWith(".git")&&(a=a.slice(0,-4));const i=new URL(a);o=i.hostname+i.pathname}catch{}for(const a of b){if(a.authType!=="token"){s.set(a.id,a);continue}const i=a.host;if(!i){s.set(a.id,a);continue}if(!i.includes("/")){s.set(a.id,a);continue}o&&o===i&&s.set(a.id,a)}return Array.from(s.values())},[b,p,Se]),ir=n.useMemo(()=>{if(d?.userName&&d?.userEmail){const s=b.find(o=>o.userName===d.userName&&o.userEmail===d.userEmail);return s||(p&&p.userName===d.userName&&p.userEmail===d.userEmail?p:{id:"local-config",name:d.userName,userName:d.userName,userEmail:d.userEmail,sshKey:d.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return p??null},[d,b,p]),lr=ye.length,cr=N||Mt!==null||Pt!==null,ts=!!ce;n.useEffect(()=>{if(!t||!r||!h?.all?.length||!ce||!de||ce===de){Me(null);return}let s=!1;return(async()=>{try{const a=await r.getGitLog(t,{from:de,to:"HEAD",maxCount:ge});if(s)return;const i=new Set((a?.all??[]).map(E=>E.hash).filter(E=>typeof E=="string"&&E.length>0));if(i.size===0){Me(null);return}const f=h.all.findIndex(E=>!i.has(E.hash));if(f===0){Me(null);return}if(f===-1){Me({insertBeforeIndex:h.all.length,branchName:ce,direction:"up"});return}Me({insertBeforeIndex:f,branchName:ce,direction:"up"})}catch{s||Me(null)}})(),()=>{s=!0}},[de,ce,t,r,h,ge]),n.useEffect(()=>{pt(null)},[t]),n.useEffect(()=>{if(Z!=="graph"||!t){Z!=="graph"&&pt(null);return}let s=!1;return Vt(!0),r.getGitLog(t,{maxCount:bt,all:!0}).then(o=>{s||pt(o)}).catch(o=>{console.error("Failed to fetch graph log:",o)}).finally(()=>{s||Vt(!1)}),()=>{s=!0}},[Z,t,bt,Ys,r]),n.useCallback((s,o)=>{if(!t||s.length===0)return;const a=Array.from(new Set(s));Dt(f=>{const E=new Set(f);return a.forEach(U=>E.add(U)),E});const i=H(t,a,o);K.enqueue({directory:t,direction:o,paths:new Set(a),rollback:()=>J(t,i)}),me()},[t,K,H,J,me]),n.useCallback(async s=>{if(t){Oe(o=>{const a=new Set(o);return a.add(s),a});try{await r.revertGitFile(t,s,{scope:"working"}),g.success(`Reverted ${s}`),await O(!1)}catch(o){const a=o instanceof Error?o.message:"Failed to revert changes";g.error(a)}finally{Oe(o=>{const a=new Set(o);return a.delete(s),a})}}},[t,O,r]);const Je=n.useCallback(async(s,o,a="all")=>{if(!t||s.length===0)return;const i=Array.from(new Set(s));if(zt||i.some(B=>At.has(B)))return;const f=new Set(ye.map(B=>B.path)),E=a==="all"&&i.some(B=>f.has(B));o&&Gt(!0),Oe(B=>{const re=new Set(B);return i.forEach(Pe=>re.add(Pe)),re});const U=[];try{if(await Promise.all(i.map(async B=>{try{await r.revertGitFile(t,B,{scope:a})}catch(re){U.push({path:B,message:re instanceof Error?re.message:"Failed to revert changes"})}})),E&&U.length<i.length&&V(t),await O(!1),U.length===0)g.success(i.length===1?`Reverted ${i.length} file`:`Reverted ${i.length} files`);else if(U.length===i.length)g.error(U[0]?.message||"Failed to revert changes");else{const B=i.length-U.length;g.warning(B===1?`Reverted ${B} file, ${U.length} failed`:`Reverted ${B} files, ${U.length} failed`)}}finally{Oe(B=>{const re=new Set(B);return i.forEach(Pe=>re.delete(Pe)),re}),o&&Gt(!1)}},[V,t,r,zt,O,At,ye]);n.useCallback(async s=>{await Je(s,!0)},[Je]),n.useCallback(async s=>{await Je(s,!1,"working")},[Je]);const dr=n.useCallback(()=>nt(!0),[]),ur=n.useCallback(s=>{if(s.length===0)return;const o=s.map(a=>a.trim()).filter(Boolean);if(o.length===0){_e();return}we(a=>{const i=a.trim(),f=i.length>0?`
4
+
5
+ `:"";return`${i}${f}${o.join(`
6
+ `)}`.trim()}),_e()},[_e]),mr=n.useCallback((s,o)=>{const a=o||s;we(i=>{const f=i.trimStart();return f.startsWith(s)||o&&f.startsWith(o)?i:`${a.endsWith(" ")?a:`${a} `}${i}`.trimStart()}),qt(""),X(!1)},[]),Ke=n.useCallback(s=>{const o=s instanceof Error?s.message.toLowerCase():"";return o.includes("uncommitted changes")||o.includes("local changes")||o.includes("your local changes would be overwritten")||o.includes("please commit your changes or stash them")||o.includes("cannot rebase: you have unstaged changes")||o.includes("error: cannot pull with rebase")},[]),Ce=n.useCallback((s,o)=>{We(a=>[...a,{message:s,status:o,timestamp:Date.now()}])},[]),se=n.useCallback((s,o)=>{We(a=>{if(a.length===0)return a;const i=[...a];return i[i.length-1]={...i[i.length-1],status:s,...o?{message:o}:{}},i})},[]),Qe=n.useCallback(()=>{We([])},[]),hr=n.useCallback(()=>{We([]),gt(null)},[]),Xe=n.useCallback(s=>{const o=s.trim(),a=new Set(ae.map(f=>f.name)),i=o.indexOf("/");if(i>0){const f=o.slice(0,i),E=o.slice(i+1);if(a.has(f)&&E)return{branch:o,remote:f,remoteBranch:E}}for(const f of ae){const E=`${f.name}/${o}`;if(je.includes(E))return{branch:E,remote:f.name,remoteBranch:o}}return{branch:o,remote:null,remoteBranch:null}},[ae,je]),fr=n.useCallback(async s=>{if(!t)return;gt("merge"),Qe();const o=m?.current,a=Xe(s);try{a.remote&&a.remoteBranch&&(Ce(`Fetching ${a.remote}/${a.remoteBranch}...`,"running"),await r.gitFetch(t,{remote:a.remote,branch:a.remoteBranch}),se("done",`Fetched ${a.remote}/${a.remoteBranch}`)),Ce(`Merging ${a.branch} into ${o}...`,"running");const i=await r.merge(t,{branch:a.branch});i.conflict?(se("error","Merge conflicts detected"),pe(i.conflictFiles??[]),xe("merge"),ie(!0),be(t,i.conflictFiles??[],"merge")):(se("done",`Merged ${a.branch} into ${o}`),oe(),Ce("Refreshing repository status...","running"),await O(),await q(),se("done","Repository status updated"))}catch(i){if(Ke(i))se("error","Uncommitted changes detected"),Jt("merge"),Kt(a.branch),yt(!0);else{const f=i instanceof Error?i.message:`Failed to merge ${a.branch}`;se("error",f)}}},[t,r,m,Xe,O,q,Ke,be,oe,Ce,se,Qe]),gr=n.useCallback(async s=>{if(!t)return;gt("rebase"),Qe();const o=m?.current,a=Xe(s);try{a.remote&&a.remoteBranch&&(Ce(`Fetching ${a.remote}/${a.remoteBranch}...`,"running"),await r.gitFetch(t,{remote:a.remote,branch:a.remoteBranch}),se("done",`Fetched ${a.remote}/${a.remoteBranch}`)),Ce(`Rebasing ${o} onto ${a.branch}...`,"running");const i=await r.rebase(t,{onto:a.branch});i.conflict?(se("error","Rebase conflicts detected"),pe(i.conflictFiles??[]),xe("rebase"),ie(!0),be(t,i.conflictFiles??[],"rebase")):(se("done",`Rebased ${o} onto ${a.branch}`),oe(),Ce("Refreshing repository status...","running"),await O(),await q(),se("done","Repository status updated"))}catch(i){if(Ke(i))se("error","Uncommitted changes detected"),Jt("rebase"),Kt(a.branch),yt(!0);else{const f=i instanceof Error?i.message:`Failed to rebase onto ${a.branch}`;se("error",f)}}},[t,r,m,Xe,O,q,Ke,be,oe,Ce,se,Qe]),pr=n.useCallback(async()=>{if(t)try{Ve==="merge"?(await r.abortMerge(t),g.success("Merge aborted")):(await r.abortRebase(t),g.success("Rebase aborted")),oe(),await O(),await q()}catch(s){const o=s instanceof Error?s.message:`Failed to abort ${Ve}`;g.error(o)}},[t,r,Ve,O,q,oe]),xr=n.useMemo(()=>m?.files?m.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,[m?.files]),br=n.useCallback(async()=>{if(t)try{const s=!!m?.mergeInProgress?.head,o=!!(m?.rebaseInProgress?.headName||m?.rebaseInProgress?.onto);if(s){const a=await r.continueMerge(t);a.conflict?(pe(a.conflictFiles??[]),xe("merge"),ie(!0),be(t,a.conflictFiles??[],"merge"),g.error("Merge conflicts detected")):(oe(),g.success("Merge completed"),await O(),await q())}else if(o){const a=await r.continueRebase(t);a.conflict?(pe(a.conflictFiles??[]),xe("rebase"),ie(!0),be(t,a.conflictFiles??[],"rebase"),g.error("Rebase conflicts detected")):(oe(),g.success("Rebase step completed"),await O(),await q())}}catch(s){const o=s instanceof Error?s.message:"Failed to continue operation";g.error(o)}},[t,r,m,O,q,be,oe]),yr=n.useCallback(async()=>{if(t)try{!!m?.mergeInProgress?.head?(await r.abortMerge(t),g.success("Merge aborted")):(await r.abortRebase(t),g.success("Rebase aborted")),oe(),await O(),await q()}catch(s){const o=s instanceof Error?s.message:"Failed to abort operation";g.error(o)}},[t,r,m,O,q,oe]),jr=n.useCallback(()=>{if(!t)return;const o=!!m?.mergeInProgress?.head?"merge":"rebase",a=m?.files?.filter(i=>i.index==="U"||i.working_dir==="U").map(i=>i.path)??[];a.length>0&&pe(a),xe(o),ie(!0)},[t,m]),wr=n.useCallback(async s=>{if(!t)return;const o=m?.current,a=jt,i=wt,f=(m?.files??[]).some(bs);try{await r.stash(t,{message:`Auto-stash before ${a} with ${i}`,includeUntracked:!0}),f&&V(t)}catch(B){const re=B instanceof Error?B.message:"Failed to stash changes";g.error(re);return}let E=!1,U=!1;try{if(a==="merge"){const B=await r.merge(t,{branch:i});B.conflict?(U=!0,pe(B.conflictFiles??[]),xe("merge"),ie(!0)):(E=!0,g.success(`Merged ${i} into ${o||""}`))}else{const B=await r.rebase(t,{onto:i});B.conflict?(U=!0,pe(B.conflictFiles??[]),xe("rebase"),ie(!0)):(E=!0,g.success(`Rebased ${o||""} onto ${i}`))}if(s&&E)try{await r.stashPop(t),V(t),g.success("Stashed changes restored")}catch(B){const re=B instanceof Error?B.message:"Failed to restore stash";g.error(re)}else s&&U&&g.info("Stash restored manually required");await O(),await q()}catch(B){if(s)try{await r.stashPop(t),V(t)}catch{}throw B}},[V,t,r,m,jt,wt,O,q]),vr=n.useCallback(s=>{Ms(s),t&&(L(t,s),M(t,r,s))},[t,M,r,L]),Cr=n.useCallback(s=>{Vs(s)},[]),Nr=n.useCallback(()=>{Ye(null),t&&(z(t,r),W(t,r),M(t,r,ge))},[t,z,W,M,ge,r]),Sr=n.useCallback(s=>{if(s.conflict){if(s.operation==="cherry-pick"||s.operation==="revert"){g.error("Conflict",{description:`Conflicts in: ${s.conflictFiles?.join(", ")??"unknown files"}. Resolve manually and commit, or abort with git cherry-pick/revert --abort.`}),t&&(z(t,r),W(t,r),M(t,r,ge));return}pe(s.conflictFiles??[]),xe(s.operation),ie(!0),t&&be(t,s.conflictFiles??[],s.operation)}},[pe,xe,ie,be,t,z,W,M,ge,r]);return t?F===null||F===!0&&!m?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(R,{name:"loader-4",className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-ui-label",children:"Checking repository..."})]})}):F===!1?e.jsx("div",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:e.jsx(n.Suspense,{fallback:null,children:e.jsx(ps,{diffScope:"turn",hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,flushContent:!0})})}):e.jsxs("div",{className:ee("flex h-full flex-col overflow-hidden"),children:[e.jsx(ba,{status:m,localBranches:De,remoteBranches:je,branchInfo:v?.branches,syncAction:Mt,remotes:ae,onFetch:s=>Xt("fetch",s),onSync:s=>Xt("sync",s),onRemoveRemote:Zs,removingRemoteName:Os,onCheckoutBranch:rr,onCreateBranch:tr,onRenameBranch:sr,activeIdentityProfile:ir,availableIdentities:or,onSelectIdentity:ar,isApplyingIdentity:Ps,isWorktreeMode:!1,onOpenHistory:()=>Ye("history"),onOpenGraph:()=>Ye("graph"),onOpenStashes:dr,onOpenUpdateBranch:ts?()=>_t(!0):void 0,pullRequest:null,prChecks:null}),t&&(m?.mergeInProgress?.head||m?.rebaseInProgress?.headName||m?.rebaseInProgress?.onto)&&e.jsx(Ga,{mergeInProgress:m?.mergeInProgress,rebaseInProgress:m?.rebaseInProgress,onContinue:br,onAbort:yr,onResolveWithAI:jr,conflictCount:xr,isLoading:N}),e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:e.jsx("div",{className:"flex h-full min-h-0 flex-col",children:(ve?.length??0)>0||Ct?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e.jsx(n.Suspense,{fallback:null,children:e.jsx(ps,{diffScope:ve.length>0?"all":"branch",branchBase:Ct?de:null,branchHead:Ct?ce:null,showOpenInEditorAction:!0,hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,flushContent:!0})})}),ve.length>0?e.jsx("div",{ref:Ft,className:"shrink-0 px-4 pb-4 pt-2",children:e.jsx(ya,{stagedCount:lr,commitMessage:he,onCommitMessageChange:we,generatedHighlights:lt,onInsertHighlights:ur,onGenerateMessage:er,isGeneratingMessage:As,onCommit:()=>Zt({pushAfter:!1}),onCommitAndPush:()=>Zt({pushAfter:!0}),commitAction:Pt,hasPendingIndexMutation:zs,gitmojiEnabled:$,onOpenGitmojiPicker:()=>X(!0)})}):null]}):e.jsx(Ea,{onOpenStashes:()=>nt(!0)})})}),e.jsx(ke,{open:Ds,onOpenChange:s=>{!s&&Wt!==null||_t(s)},children:e.jsxs(Re,{className:"max-w-2xl min-h-[26rem]",children:[e.jsxs(Ie,{children:[e.jsx(Ee,{children:"Update branch"}),e.jsxs($e,{children:["Bring the latest changes into"," ",e.jsx("span",{className:"font-mono text-foreground",children:m?.current??""}),"."]})]}),ts?e.jsx(Ta,{mode:"bare",currentBranch:m?.current,localBranches:De,remoteBranches:je,defaultTargetBranch:nr,onMerge:fr,onRebase:gr,disabled:cr,isOperating:Wt!==null,operationLogs:_s,onOperationComplete:hr}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Branch actions unavailable in this repository state"})]})}),e.jsx(ke,{open:Z!==null,onOpenChange:s=>{s||Ye(null)},children:e.jsxs(Re,{className:"max-w-5xl h-[90vh] max-h-[90vh] flex flex-col overflow-hidden",children:[e.jsxs(Ie,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(Ee,{children:Z==="graph"?"Graph":"History"}),e.jsxs(D,{type:"button",variant:"ghost",size:"sm",className:"mr-6 h-7 shrink-0 gap-1.5 px-2",onClick:()=>{if(Z==="graph"){qs(s=>s+1);return}t&&M(t,r,ge)},disabled:Z==="graph"?xt:C,title:"Refresh","aria-label":"Refresh",children:[e.jsx(R,{name:"refresh",className:ee("size-4",(Z==="graph"?xt:C)&&"animate-spin")}),"Refresh"]})]}),e.jsx($e,{children:"Browse recent commits and inspect changed files."})]}),e.jsx("div",{className:"flex-1 min-h-0",children:e.jsx(Aa,{mode:Z==="graph"?"graph":"history",log:Z==="graph"?Ws??h:h,isLogLoading:Z==="graph"&&xt||C,logMaxCount:Z==="graph"?bt:ge,onLogMaxCountChange:Z==="graph"?Cr:vr,expandedCommitHashes:ct,onToggleCommit:Xs,commitFilesMap:He,loadingCommitHashes:Ue,onCopyHash:Qs,directory:t??void 0,showHeader:!1,contentMaxHeightClassName:"h-full max-h-none",branchDivider:Z==="graph"?null:Js,onConflict:Z==="graph"?Sr:void 0,onActionSuccess:Z==="graph"?Nr:void 0})})]})}),e.jsx(Ia,{open:Fs,onOpenChange:nt,directory:t,hasUncommittedChanges:(m?.files?.length??0)>0,hasStagedChanges:ye.length>0,uncommittedFileCount:m?.files?.length??0,onChanged:async s=>{t&&s?.affectsIndex&&V(t),await O(!1),await q()}}),e.jsx(ke,{open:fe,onOpenChange:X,children:e.jsxs(Re,{className:"max-w-md p-0 overflow-hidden",children:[e.jsx(Ie,{className:"px-4 pt-4",children:e.jsx(Ee,{children:"Insert gitmoji"})}),e.jsxs(vs,{className:"h-[420px]",children:[e.jsx(Cs,{placeholder:"Search gitmoji...",value:Yt,onValueChange:qt}),e.jsxs(Ns,{children:[e.jsx(Ss,{children:"No gitmoji found"}),e.jsx(It,{children:(_.length===0?[]:_.filter(s=>{const o=Yt.trim().toLowerCase();return o?s.emoji.includes(o)||s.code.toLowerCase().includes(o)||s.description.toLowerCase().includes(o):!0})).map(s=>e.jsxs(Et,{onSelect:()=>mr(s.emoji,s.code),children:[e.jsx("span",{className:"text-lg",children:s.emoji}),e.jsx("span",{className:"typography-ui-label text-foreground",children:s.code}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:s.description})]},s.code))})]})]})]})}),t&&e.jsx(Da,{open:Hs,onOpenChange:ie,conflictFiles:Us,directory:t,operation:Ve,onAbort:pr,onClearState:oe}),e.jsx(za,{open:Ks,onOpenChange:yt,operation:jt,targetBranch:wt,onConfirm:wr})]}):e.jsx("div",{className:"flex h-full items-center justify-center px-4 text-center",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:"Select a session or directory to view Git status"})})};export{ii as GitView};
@@ -1 +1 @@
1
- import{da as M,dP as Z,dQ as Fe,dR as Ce,dS as ke,dT as Ie,dU as ze,dV as Ne,dW as Oe,B as ee,I as te,dX as Ve}from"./useAppFontEffects-DXASDavv.js";import{a as ie,s as Pe,b as Se,c as ne,d as ve,g as Be,e as re,f as I,h as De,i as Ue,j as _e,k as We,R as Ge,I as je,p as se,l as $e,m as qe,n as Ke,o as Je,w as Ye,q as ae,u as Xe,r as Qe,t as Ze,v as et,x as oe,S as tt,y as it,z as nt,A as rt,B as ye,C as he,F as st}from"./web-components-CNPQSzpa.js";import{G as at,u as ot,W as ht,a as lt,b as dt,n as le,t as ct}from"./Virtualizer-BxW2CJGB.js";import{j as C,r as k,R as L}from"./vendor-react-DYyjh7Q0.js";import{j as ut,i as j,f as A,a as ft,k as de,l as pt,m as ce,d as gt,n as ue,b as mt,o as B,q as fe}from"./computeVirtualFileMetrics-DdXkLFAD.js";import{a as F,i as K,l as pe,h as Ct,r as St}from"./isFilePlainText-BcfhE9FH.js";import{t as H}from"./vendor-hast-util-to-html-BKBhbTDb.js";let vt=-1;var yt=class{options;onRenderUpdate;workerManager;__id=`file-renderer:${++vt}`;highlighter;renderCache;computedLang="text";lineAnnotations={};lineCache;textDoucmentCache=new WeakMap;constructor(i={theme:M},e,t){this.options=i,this.onRenderUpdate=e,this.workerManager=t,t?.isWorkingPool()!==!0&&(this.highlighter=ie(i.theme??M)?ut():void 0)}setOptions(i){this.options=i}mergeOptions(i){this.options={...this.options,...i}}setLineAnnotations(i){this.lineAnnotations={};for(const e of i){const t=this.lineAnnotations[e.lineNumber]??[];this.lineAnnotations[e.lineNumber]=t,t.push(e)}}cleanUp(){this.recycle(),this.workerManager=void 0,this.onRenderUpdate=void 0}recycle(){this.clearRenderCache(),this.highlighter=void 0,this.workerManager?.cleanUpTasks(this),this.lineCache=void 0}clearRenderCache(){const i=this.renderCache;this.renderCache=void 0,i!=null&&i.isDirty===!0&&i.file.cacheKey!=null&&this.workerManager?.evictFileFromCache(i.file.cacheKey)}hydrate(i){const{options:e}=this.getRenderOptions(i),t=$(this.getOrCreateLineCache(i).length,this.getTokenizeMaxLength());let n=this.workerManager?.getFileResultCache(i);n!=null&&!F(e,n.options)&&(n=void 0),this.renderCache??={file:i,options:e,highlighted:!t&&!K(i),result:t?void 0:n?.result,renderRange:void 0},this.workerManager?.isWorkingPool()===!0?this.renderCache.result==null&&!t&&this.workerManager.highlightFileAST(this,i):this.highlighter==null&&(this.computedLang=i.lang??j(i.name),this.initializeHighlighter())}getRenderOptions(i){const e=(()=>{if(this.workerManager?.isWorkingPool()===!0)return this.workerManager.getFileRenderOptions();const{theme:n=M,tokenizeMaxLineLength:r=1e3}=this.options;return{theme:n,useTokenTransformer:Pe(this.options),tokenizeMaxLineLength:r}})(),{renderCache:t}=this;return t?.result==null?{options:e,forceHighlight:!0}:!A(i,t.file)||!F(e,t.options)?{options:e,forceHighlight:!0}:{options:e,forceHighlight:!1}}getOrCreateLineCache(i){if(i.cacheKey==null)return this.lineCache=void 0,pe(i.contents);let{lineCache:e}=this;return(e==null||e.cacheKey!==i.cacheKey)&&(e={cacheKey:i.cacheKey,lines:pe(i.contents)}),this.lineCache=e,e.lines}getLineCount(i){return this.textDoucmentCache.get(i)?.lineCount??this.getOrCreateLineCache(i).length}updateRenderCache(i,e){if(this.renderCache==null)return;const{result:t}=this.renderCache;if(t!=null){for(const[n,r]of i)t.code[n]={type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:r.map(([s,a,o])=>s===0&&a===""?o===""?{type:"element",tagName:"br",properties:{},children:[]}:{type:"text",value:o}:{type:"element",tagName:"span",properties:{"data-char":s,style:`--diffs-token-${e}:${a};`},children:[{type:"text",value:o}]})};t.baseThemeType=e,this.renderCache.isDirty=!0}}applyDocumentChange(i){if(this.renderCache==null)return;const{file:e,result:t}=this.renderCache;if(t!=null&&t.code.length!==i.lineCount){t.code.length=Math.min(t.code.length,i.lineCount);for(let n=t.code.length;n<i.lineCount;n++)t.code.push({type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:[{type:"element",tagName:"span",properties:{"data-char":0},children:[{type:"text",value:i.getLineText(n)}]}]});this.renderCache.isDirty=!0}this.textDoucmentCache.set(e,i)}renderFile(i=this.renderCache?.file,e=Z){if(i==null)return;let{options:t,forceHighlight:n}=this.getRenderOptions(i);const r=this.getMatchingWorkerResultCache(i,t);r!=null&&!this.hasHighlightedRenderCache(i,t)&&(this.renderCache={file:i,highlighted:!0,renderRange:void 0,...r},n=!1),this.renderCache??={file:i,highlighted:!1,options:t,result:void 0,renderRange:void 0};const s=this.getOrCreateLineCache(i),a=i.contents.length>0,o=!a||K(i)||$(s.length,this.getTokenizeMaxLength()),h=!A(i,this.renderCache.file),d=!Se(this.renderCache.renderRange,e);if(this.workerManager?.isWorkingPool()===!0)(o||this.renderCache.result==null||!this.renderCache.highlighted&&(h||d))&&(this.renderCache.file=i,this.renderCache.options=t,this.renderCache.highlighted=!1,(this.renderCache.result==null||h||d||n)&&(this.renderCache.result=this.workerManager.getPlainFileAST(i,e.startingLine,e.totalLines,s)),this.renderCache.renderRange=e),!o&&a&&(!this.renderCache.highlighted||n)&&this.workerManager.highlightFileAST(this,i);else{this.computedLang=i.lang??j(i.name);const l=this.highlighter!=null&&ie(t.theme),c=this.highlighter!=null&&ne(this.computedLang),u=!o&&c;if(this.highlighter!=null&&l&&(n||o||!this.renderCache.highlighted&&u||this.renderCache.result==null)){const{result:p,options:f}=this.renderFileWithHighlighter(i,this.highlighter,o||!c);this.renderCache={file:i,options:f,highlighted:u,result:p,renderRange:void 0}}(!l||!o&&!c)&&this.asyncHighlight(i).then(({result:p,options:f})=>{this.renderCache!=null&&(this.renderCache.highlighted=!1),this.onHighlightSuccess(i,p,f,!o)})}return this.renderCache.result!=null?this.processFileResult(this.renderCache.file,e,this.renderCache.result):void 0}async asyncRender(i,e=Z){const{result:t}=await this.asyncHighlight(i);return this.processFileResult(i,e,t)}async asyncHighlight(i){const e=$(this.getOrCreateLineCache(i).length,this.getTokenizeMaxLength());this.computedLang=e?"text":i.lang??j(i.name);const t=this.highlighter!=null&&Ct(ft(this.options.theme)),n=e||this.highlighter!=null&&ne(this.computedLang);return(this.highlighter==null||!t||!n)&&(this.highlighter=await this.initializeHighlighter()),this.renderFileWithHighlighter(i,this.highlighter,e)}renderFileWithHighlighter(i,e,t=!1){const{options:n}=this.getRenderOptions(i);return{result:St(i,e,n,{forcePlainText:t}),options:n}}processFileResult(i,e,{code:t,themeStyles:n,baseThemeType:r}){const s=this.getLineCount(i),{disableFileHeader:a=!1}=this.options,o=[],h=ue(),d=Math.min(e.startingLine+e.totalLines,s);let l=0;const c=ve(e)?Be(this.lineAnnotations):void 0;c!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:-1,lineIndex:-1,annotations:c.map(u=>I(u))})),l++);for(let u=e.startingLine;u<d;u++){const p=u+1,f=t[u];if(f==null){const g="FileRenderer.processFileResult: Line doesnt exist";throw console.error(g,{name:i.name,lineIndex:u,lineNumber:p}),new Error(g)}h.children.push(pt("context",p,`${u}`)),o.push(f),l++;const S=this.lineAnnotations[p];S!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:0,lineIndex:p,annotations:S.map(g=>I(g))})),l++)}return h.properties.style=`grid-row: span ${l}`,{gutterAST:h.children??[],contentAST:o,preAST:this.createPreElement(s),headerAST:a?void 0:this.renderHeader(i),totalLines:s,rowCount:l,themeStyles:n,baseThemeType:r,bufferBefore:e.bufferBefore,bufferAfter:e.bufferAfter,css:""}}renderHeader(i){const{headerRenderMode:e="default",stickyHeader:t=!1}=this.options;return De({fileOrDiff:i,mode:e,stickyHeader:t})}renderFullHTML(i){return H(this.renderFullAST(i))}renderFullAST(i,e=[]){return e.push(ce({tagName:"code",children:this.renderCodeAST(i),properties:{"data-code":""}})),{...i.preAST,children:e}}renderCodeAST(i){const e=ue();return e.children=i.gutterAST,e.properties.style=`grid-row: span ${i.rowCount}`,[e,Ue(i.contentAST,i.rowCount)]}renderPartialHTML(i,e=!1){return e?H(ce({tagName:"code",children:i,properties:{"data-code":""}})):H(i)}async initializeHighlighter(){return this.highlighter=await gt(_e(this.computedLang,this.options)),this.highlighter}onHighlightSuccess(i,e,t,n=!0){if(this.renderCache==null)return;const r=!A(i,this.renderCache.file)||!this.renderCache.highlighted||!F(t,this.renderCache.options);this.renderCache={file:i,options:t,highlighted:n,result:e,renderRange:void 0},r&&this.onRenderUpdate?.()}getMatchingWorkerResultCache(i,e){const t=this.workerManager?.getFileResultCache(i);if(!(t==null||!F(e,t.options)))return t}hasHighlightedRenderCache(i,e){const{renderCache:t}=this;return t?.result!=null&&t.highlighted&&A(i,t.file)&&F(e,t.options)}onHighlightError(i){console.error(i)}getTokenizeMaxLength(){return this.options.tokenizeMaxLength??1e5}createPreElement(i){const{disableLineNumbers:e=!1,overflow:t="scroll"}=this.options;return We({type:"file",diffIndicators:"none",disableBackground:!0,disableLineNumbers:e,overflow:t,split:!1,totalLines:i})}};function $(i,e){return i>e}function Tt(i,e){return i.lineNumber===e.lineNumber&&i.metadata===e.metadata}function ge(i){return{theme:i?.theme,disableLineNumbers:i?.disableLineNumbers,overflow:i?.overflow,themeType:i?.themeType,collapsed:i?.collapsed,disableFileHeader:i?.disableFileHeader,disableVirtualizationBuffers:i?.disableVirtualizationBuffers,stickyHeader:i?.stickyHeader,preferredHighlighter:i?.preferredHighlighter,useCSSClasses:i?.useCSSClasses,useTokenTransformer:i?.useTokenTransformer,tokenizeMaxLineLength:i?.tokenizeMaxLineLength,tokenizeMaxLength:i?.tokenizeMaxLength,unsafeCSS:i?.unsafeCSS,headerRenderMode:i?.renderCustomHeader!=null?"custom":"default"}}const bt=[""];let Rt=-1;var Te=class{options;workerManager;isContainerManaged;static LoadedCustomComponent=!0;__id=`file:${++Rt}`;type="file";fileContainer;spriteSVG;pre;code;bufferBefore;bufferAfter;themeCSSStyle;appliedThemeCSS;hasAdoptedThemeCSS=!1;unsafeCSSStyle;appliedUnsafeCSS;gutterUtilityContent;errorWrapper;placeHolder;lastRenderedHeaderHTML;cachedHeaderHTML;appliedPreAttributes;lastRowCount;mounted=!1;headerElement;headerCustom;headerPrefix;headerFilenameSuffix;headerMetadata;fileRenderer;resizeManager;interactionManager;annotationCache=new Map;lineAnnotations=[];managersDirty=!1;file;renderRange;enabled=!0;editor;constructor(e={theme:M},t,n=!1){this.options=e,this.workerManager=t,this.isContainerManaged=n,this.fileRenderer=new yt(e,this.handleHighlightRender,this.workerManager),this.resizeManager=new Ge,this.interactionManager=new je("file",se(e)),this.workerManager?.subscribeToThemeChanges(this)}handleHighlightRender=()=>{this.rerender()};rerender(){!this.enabled||this.file==null||this.render({file:this.file,forceRender:!0,renderRange:this.renderRange})}onThemeChange(){this.fileRenderer.clearRenderCache(),this.rerender()}setOptions(e){e!=null&&(this.options=e,this.cachedHeaderHTML=void 0,this.syncInteractionOptions())}syncInteractionOptions(){this.interactionManager.setOptions(se(this.options))}mergeOptions(e){this.options={...this.options,...e}}setThemeType(e){(this.options.themeType??"system")!==e&&(this.mergeOptions({themeType:e}),this.applyCachedThemeState(e))}applyCachedThemeState(e){if(typeof this.options.theme=="string"||this.fileContainer==null||this.appliedThemeCSS==null)return!1;const t=this.appliedThemeCSS.baseThemeType??e;return this.appliedThemeCSS.themeType===t?!1:(this.applyThemeState(this.fileContainer,this.appliedThemeCSS.themeStyles,e,this.appliedThemeCSS.baseThemeType),!0)}hasThemeChanged(){return this.appliedThemeCSS!=null&&!mt(this.appliedThemeCSS.theme,this.options.theme??M)}getHoveredLine=()=>this.interactionManager.getHoveredLine();setLineAnnotations(e){this.lineAnnotations=e}setSelectedLines(e,t){this.interactionManager.setSelection(e,t)}flushManagers(){if(!this.managersDirty||this.pre==null){this.managersDirty=!1;return}const{overflow:e="scroll"}=this.options;this.interactionManager.setup(this.pre),this.resizeManager.setup(this.pre,e==="wrap"),this.managersDirty=!1}cleanUp(e=!1){this.emitPostRender(!0),this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.managersDirty=!1,this.workerManager?.unsubscribeToThemeChanges(this),this.renderRange=void 0,this.isContainerManaged||this.fileContainer?.remove(),this.fileContainer=void 0,this.mounted=!1,e||(this.lineAnnotations=[]),this.annotationCache.clear(),this.pre=void 0,this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.lastRenderedHeaderHTML=void 0,e||(this.cachedHeaderHTML=void 0),this.errorWrapper=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.placeHolder=void 0,this.unsafeCSSStyle=void 0,e?this.fileRenderer.recycle():(this.fileRenderer.cleanUp(),this.workerManager=void 0,this.file=void 0),this.enabled=!1,this.editor?.cleanUp(),this.editor=void 0}virtualizedSetup(){this.enabled=!0,this.workerManager?.subscribeToThemeChanges(this)}hydrate(e){const{fileContainer:t,prerenderedHTML:n,preventEmit:r=!1,file:s,lineAnnotations:a}=e;this.hydrateElements(t,n),Lt(this.pre,s,this.options.collapsed)||At(this.headerElement,s,this.options.disableFileHeader)?this.render({...e,preventEmit:!0}):this.hydrationSetup({file:s,lineAnnotations:a}),r||this.emitPostRender()}hydrateElements(e,t){this.fileContainer!==e&&this.emitPostRender(!0),$e(e,t);for(const n of Array.from(e.shadowRoot?.children??[])){if(n instanceof SVGElement){this.spriteSVG=n;continue}if(n instanceof HTMLElement){if(n instanceof HTMLPreElement){this.pre=n,this.appliedPreAttributes=void 0;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-theme-css")){this.themeCSSStyle=n;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-unsafe-css")){this.unsafeCSSStyle=n,this.appliedUnsafeCSS=n.textContent;continue}if("diffsHeader"in n.dataset){this.headerElement=n,this.lastRenderedHeaderHTML=void 0;continue}}}this.pre!=null&&(this.syncCodeNodeFromPre(this.pre),this.pre.removeAttribute("data-dehydrated")),this.fileContainer=e,this.hydrateMeasuredScrollbar()}hydrationSetup({file:e,lineAnnotations:t}){this.lineAnnotations=t??this.lineAnnotations,this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),this.pre!=null&&(this.fileRenderer.hydrate(e),this.renderAnnotations(),this.renderGutterUtility(),this.injectUnsafeCSS(),this.managersDirty=!0,this.flushManagers())}getOrCreateLineCache(e=this.file){return e!=null?this.fileRenderer.getOrCreateLineCache(e):bt}updateBuffers(e){this.pre!=null&&this.applyBuffers(this.pre,e)}syncRenderViewToEditor(){const e=this.editor,t=this.fileContainer,n=this.file;e!=null&&t!=null&&n!=null&&this.fileRenderer.initializeHighlighter().then(r=>{e.__syncRenderView(r,t,n,this.lineAnnotations,this.renderRange)})}attachEditor(e){return this.editor?.cleanUp(),this.editor=e,this.interactionManager.setEditorAttached(!0),this.syncRenderViewToEditor(),()=>{this.editor=void 0,this.interactionManager.setEditorAttached(!1)}}applyDocumentChange(e,t){this.fileRenderer.applyDocumentChange(e),t!=null&&t!==this.lineAnnotations&&this.file!=null&&(this.setLineAnnotations(t),this.fileRenderer.setLineAnnotations(this.lineAnnotations),this.renderAnnotations())}updateRenderCache(e,t){this.fileRenderer.updateRenderCache(e,t)}render({file:e,fileContainer:t,forceRender:n=!1,preventEmit:r=!1,containerWrapper:s,deferManagers:a=!1,lineAnnotations:o,renderRange:h}){if(!this.enabled)throw new Error("File.render: attempting to call render after cleaned up");this.editor?.__postponeBackgroundTokenizeToNextFrame();const{collapsed:d=!1,themeType:l="system"}=this.options,c=d?void 0:h,u=this.renderRange,p=this.hasThemeChanged(),f=o!=null&&(o.length>0||this.lineAnnotations.length>0)?o!==this.lineAnnotations:!1,S=!A(this.file,e);if(!d&&!n&&Se(c,this.renderRange)&&!S&&!f&&!p)return this.applyCachedThemeState(l);this.renderRange=c,S&&(this.cachedHeaderHTML=void 0),this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),o!=null&&this.setLineAnnotations(o),this.fileRenderer.setLineAnnotations(this.lineAnnotations);const{disableErrorHandling:g=!1,disableFileHeader:y=!1}=this.options;if(y&&(this.headerElement!=null&&(this.headerElement.remove(),this.headerElement=void 0,this.lastRenderedHeaderHTML=void 0),this.clearHeaderSlots()),t=this.getOrCreateFileContainerNode(t,s),this.applyCachedThemeState(l),d){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{const m=this.fileRenderer.renderFile(e,Fe);m!=null&&this.applyThemeState(t,m.themeStyles,l,m.baseThemeType),m?.headerAST!=null&&this.applyHeaderToDOM(m.headerAST,t),this.injectUnsafeCSS()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}try{const m=this.getOrCreatePreNode(t);if(!this.canPartiallyRender(n,f,S||p)||!this.applyPartialRender(u,c)){const v=this.fileRenderer.renderFile(e,c);if(v==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.initialize().then(()=>this.rerender()),!1;this.applyThemeState(t,v.themeStyles,l,v.baseThemeType),v.headerAST!=null&&this.applyHeaderToDOM(v.headerAST,t),this.applyFullRender(v,m)}this.applyBuffers(m,c),this.injectUnsafeCSS(),this.managersDirty=!0,a||this.flushManagers(),this.renderAnnotations(),this.renderGutterUtility(),this.editor!=null&&this.syncRenderViewToEditor()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}emitPostRender(e=!1){const{fileContainer:t,options:{onPostRender:n}}=this;if(e){if(!this.mounted||(this.mounted=!1,t==null))return;n?.(t,this,"unmount");return}if(t==null)return;const r=this.mounted?"update":"mount";this.mounted=!0,n?.(t,this,r)}removeRenderedCode(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.code?.remove(),this.code=void 0,this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0}clearAuxiliaryNodes(){for(const{element:e}of this.annotationCache.values())e.remove();this.annotationCache.clear(),this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0}canPartiallyRender(e,t,n){return!(e||t||n)}renderPlaceholder(e){if(this.fileContainer==null)return!1;if(this.emitPostRender(!0),this.cleanChildNodes(),this.placeHolder==null){const t=this.fileContainer.shadowRoot??this.fileContainer.attachShadow({mode:"open"});this.placeHolder=document.createElement("div"),this.placeHolder.dataset.placeholder="",t.appendChild(this.placeHolder)}return this.placeHolder.style.setProperty("height",`${e}px`),!0}primeHighlightCache(){const{file:e,workerManager:t}=this;e==null||e.cacheKey==null||t==null||K(e)||this.fileRenderer.getOrCreateLineCache(e).length>(this.options.tokenizeMaxLength??1e5)||t.primeFileHighlightCache(e)}cleanChildNodes(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferAfter?.remove(),this.bufferBefore?.remove(),this.code?.remove(),this.errorWrapper?.remove(),this.headerElement?.remove(),this.gutterUtilityContent?.remove(),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.pre?.remove(),this.spriteSVG?.remove(),this.themeCSSStyle?.remove(),this.unsafeCSSStyle?.remove(),this.bufferAfter=void 0,this.bufferBefore=void 0,this.code=void 0,this.errorWrapper=void 0,this.headerElement=void 0,this.gutterUtilityContent=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.pre=void 0,this.spriteSVG=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.lastRenderedHeaderHTML=void 0,this.lastRowCount=void 0,this.mounted=!1}renderAnnotations(){if(this.isContainerManaged||this.fileContainer==null){for(const{element:n}of this.annotationCache.values())n.remove();this.annotationCache.clear();return}const e=new Map(this.annotationCache),{renderAnnotation:t}=this.options;if(t!=null&&this.lineAnnotations.length>0)for(const[n,r]of this.lineAnnotations.entries()){const s=`${n}-${I(r)}`;let a=this.annotationCache.get(s);if(a==null||!Tt(r,a.annotation)){a?.element.remove();const o=t(r);if(o==null)continue;a={element:qe(I(r)),annotation:r},a.element.appendChild(o),this.fileContainer.appendChild(a.element),this.annotationCache.set(s,a)}e.delete(s)}for(const[n,{element:r}]of e.entries())this.annotationCache.delete(n),r.remove()}renderGutterUtility(){const{renderGutterUtility:e}=this.options;if(this.fileContainer==null||e==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const t=e(this.interactionManager.getHoveredLine);if(t!=null&&this.gutterUtilityContent!=null)return;if(t==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const n=Ke();n.appendChild(t),this.fileContainer.appendChild(n),this.gutterUtilityContent=n}injectUnsafeCSS(){const{unsafeCSS:e}=this.options,t=this.fileContainer?.shadowRoot;if(t!=null){if(e==null||e===""){this.unsafeCSSStyle!=null&&(this.unsafeCSSStyle.remove(),this.unsafeCSSStyle=void 0),this.appliedUnsafeCSS=void 0;return}this.unsafeCSSStyle?.parentNode===t&&this.appliedUnsafeCSS===e||(this.unsafeCSSStyle??=Je(),this.unsafeCSSStyle.parentNode!==t&&t.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=Ye(e),this.appliedUnsafeCSS=e)}}applyThemeState(e,t,n,r){const s=e.shadowRoot??e.attachShadow({mode:"open"}),a=r??n,o=this.options.theme??M,h=typeof o=="string"?o:{...o},d=ae(s);if(this.themeCSSStyle?.parentNode===s&&this.appliedThemeCSS?.themeStyles===t&&this.appliedThemeCSS.themeType===a&&this.appliedThemeCSS.scrollbarGutter===d){this.appliedThemeCSS.theme=h;return}if(this.hasAdoptedThemeCSS&&this.themeCSSStyle?.parentNode===s){this.hasAdoptedThemeCSS=!1,this.appliedThemeCSS={theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:d};return}this.themeCSSStyle=Xe({shadowRoot:s,currentNode:this.themeCSSStyle,themeCSS:Qe(t,a,d)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:d}:void 0}hydrateMeasuredScrollbar(){const e=this.fileContainer?.shadowRoot;e==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=Ze(this.themeCSSStyle.textContent??"",ae(e)))}applyFullRender(e,t){this.cleanupErrorWrapper(),this.applyPreNodeAttributes(t,e),this.code=et({code:this.code});const n=this.fileRenderer.renderCodeAST(e);if(this.code.childElementCount>=2)for(let r=0;r<2;r++){const s=this.code.children[r],a=n[r];s.innerHTML=H(a.children),s.style.cssText=a.properties.style}else this.code.innerHTML=H(n);t.contains(this.code)||t.replaceChildren(this.code),this.lastRowCount=e.rowCount}applyPartialRender(e,t){if(e==null||t==null)return!1;const{file:n,code:r}=this,s=r!=null?this.getColumns(r):void 0;if(n==null||r==null||s==null)return!1;const a=e.startingLine,o=t.startingLine,h=e.totalLines===1/0?Number.POSITIVE_INFINITY:a+e.totalLines,d=t.totalLines===1/0?Number.POSITIVE_INFINITY:o+t.totalLines,l=Math.max(a,o),c=Math.min(h,d);if(c<=l||!this.trimDOMToOverlap(s.gutter,l,c)||!this.trimDOMToOverlap(s.content,l,c))return!1;let{length:u}=s.content.children;const p=(y,m)=>{if(!(m<=0))return this.fileRenderer.renderFile(n,{startingLine:y,totalLines:m,bufferBefore:0,bufferAfter:0})},f=o<l?p(o,l-o):void 0;if(f===void 0&&o<l)return!1;const S=d===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:Math.max(0,d-c),g=d>c?p(c,S):void 0;return g===void 0&&d>c?!1:(this.cleanupErrorWrapper(),f!=null&&(s.gutter.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.gutterAST)),s.content.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.contentAST)),u+=f.rowCount),g!=null&&(s.gutter.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.gutterAST)),s.content.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.contentAST)),u+=g.rowCount),this.lastRowCount!==u&&(s.gutter.style.setProperty("grid-row",`span ${u}`),s.content.style.setProperty("grid-row",`span ${u}`),this.lastRowCount=u),!0)}getColumns(e){const t=e.children[0],n=e.children[1];if(!(!(t instanceof HTMLElement)||!(n instanceof HTMLElement)||t.dataset.gutter==null||n.dataset.content==null))return{gutter:t,content:n}}trimDOMToOverlap(e,t,n){const r=this.getDOMBoundaryIndices(e,[t,n]),s=r.get(t)??e.children.length,a=r.get(n)??e.children.length;if(s>a)return!1;for(let o=e.children.length-1;o>=a;o-=1)e.children[o]?.remove();for(let o=s-1;o>=0;o-=1)e.children[o]?.remove();return!0}getDOMBoundaryIndices(e,t){const n=[...new Set(t)].sort((h,d)=>h-d),r=new Map;if(n.length===0)return r;let s=0,a=n[s];const{children:o}=e;a===0&&(r.set(0,0),s+=1,a=n[s]);for(let h=0;h<o.length;h+=1){const d=o[h];if(!(d instanceof HTMLElement))continue;const l=this.getLineIndexFromDOMNode(d);if(l!=null){for(;a!=null&&l>=a;)r.set(a,h),s+=1,a=n[s];if(s>=n.length)break}}for(const h of n)r.has(h)||r.set(h,o.length);return r}getLineIndexFromDOMNode(e){const t=e.dataset.lineIndex;if(t==null)return;const n=Number(t);return Number.isNaN(n)?void 0:n}applyBuffers(e,t){if(t==null||this.shouldDisableVirtualizationBuffers()){this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0);return}t.bufferBefore>0?(this.bufferBefore==null&&(this.bufferBefore=document.createElement("div"),this.bufferBefore.dataset.virtualizerBuffer="before",e.before(this.bufferBefore)),this.bufferBefore.style.setProperty("height",`${t.bufferBefore}px`),this.bufferBefore.style.setProperty("contain","strict")):this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),t.bufferAfter>0?(this.bufferAfter==null&&(this.bufferAfter=document.createElement("div"),this.bufferAfter.dataset.virtualizerBuffer="after",e.after(this.bufferAfter)),this.bufferAfter.style.setProperty("height",`${t.bufferAfter}px`),this.bufferAfter.style.setProperty("contain","strict")):this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0)}shouldDisableVirtualizationBuffers(){return this.options.disableVirtualizationBuffers??!1}applyHeaderToDOM(e,t){const{file:n}=this;if(n==null)return;this.cleanupErrorWrapper(),this.placeHolder?.remove(),this.placeHolder=void 0;const r=this.cachedHeaderHTML??H(e);if(this.cachedHeaderHTML=r,r!==this.lastRenderedHeaderHTML){const d=document.createElement("div");d.innerHTML=r;const l=d.firstElementChild;if(!(l instanceof HTMLElement))return;this.headerElement!=null?t.shadowRoot?.replaceChild(l,this.headerElement):t.shadowRoot?.prepend(l),this.headerElement=l,this.lastRenderedHeaderHTML=r}if(this.isContainerManaged)return;const{renderHeaderPrefix:s,renderHeaderFilenameSuffix:a,renderCustomHeader:o,renderHeaderMetadata:h}=this.options;if(o!=null){const d=o(n)??void 0;this.headerCustom=this.upsertHeaderSlotElement(t,this.headerCustom,Ce,d),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0}else{const d=s?.(n)??void 0,l=a?.(n)??void 0,c=h?.(n)??void 0;this.headerPrefix=this.upsertHeaderSlotElement(t,this.headerPrefix,ke,d),this.headerFilenameSuffix=this.upsertHeaderSlotElement(t,this.headerFilenameSuffix,Ie,l),this.headerMetadata=this.upsertHeaderSlotElement(t,this.headerMetadata,ze,c),this.headerCustom?.remove(),this.headerCustom=void 0}}clearHeaderSlots(){this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0}upsertHeaderSlotElement(e,t,n,r){if(r==null){t?.remove();return}const s=t??this.createHeaderSlotElement(n);return t==null&&e.appendChild(s),this.replaceHeaderSlotContent(s,r),s}replaceHeaderSlotContent(e,t){e.replaceChildren(),t instanceof Element?e.appendChild(t):e.innerText=`${t}`}createHeaderSlotElement(e){const t=document.createElement("div");return t.slot=e,t}getOrCreateFileContainerNode(e,t){const{fileContainer:n}=this,r=e??n??document.createElement("diffs-container"),s=n!==r;return s&&this.emitPostRender(!0),this.fileContainer=r,n!=null&&s&&(this.lastRenderedHeaderHTML=void 0,this.headerElement=void 0),t!=null&&this.fileContainer.parentNode!==t&&t.appendChild(this.fileContainer),s&&this.adoptReusableShellElements(this.fileContainer),this.ensureSpriteSVG(this.fileContainer),this.fileContainer}adoptReusableShellElements(e){const{shadowRoot:t}=e;if(t!=null)for(const n of t.children)n instanceof SVGElement?this.spriteSVG??=n:oe(n)&&n.hasAttribute("data-theme-css")?(this.themeCSSStyle??=n,this.hasAdoptedThemeCSS=!0):oe(n)&&n.hasAttribute("data-unsafe-css")&&(this.unsafeCSSStyle??=n,this.appliedUnsafeCSS??=this.options.unsafeCSS??void 0)}ensureSpriteSVG(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});if(this.spriteSVG==null){const n=document.createElement("div");n.innerHTML=tt;const r=n.firstChild;r instanceof SVGElement&&(this.spriteSVG=r)}this.spriteSVG!=null&&this.spriteSVG.parentNode!==t&&t.appendChild(this.spriteSVG)}getOrCreatePreNode(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});return this.pre==null?(this.pre=document.createElement("pre"),this.appliedPreAttributes=void 0,this.code=void 0,t.appendChild(this.pre)):this.pre.parentNode!==t&&(e.shadowRoot?.appendChild(this.pre),this.appliedPreAttributes=void 0),this.placeHolder?.remove(),this.placeHolder=void 0,this.pre}syncCodeNodeFromPre(e){this.code=void 0;for(const t of Array.from(e.children))if(t instanceof HTMLElement&&t.hasAttribute("data-code")){this.code=t;return}}applyPreNodeAttributes(e,{totalLines:t}){const{overflow:n="scroll",disableLineNumbers:r=!1}=this.options,s={type:"file",split:!1,overflow:n,disableLineNumbers:r,diffIndicators:"none",disableBackground:!0,totalLines:t};it(s,this.appliedPreAttributes)||(nt(e,s),this.appliedPreAttributes=s)}applyErrorToDOM(e,t){this.cleanupErrorWrapper(),this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0;const n=t.shadowRoot??t.attachShadow({mode:"open"});this.errorWrapper??=document.createElement("div"),this.errorWrapper.dataset.errorWrapper="",this.errorWrapper.textContent="",n.appendChild(this.errorWrapper);const r=document.createElement("div");r.dataset.errorMessage="",r.innerText=e.message,this.errorWrapper.appendChild(r);const s=document.createElement("pre");s.dataset.errorStack="",s.innerText=e.stack??"No Error Stack",this.errorWrapper.appendChild(s)}cleanupErrorWrapper(){this.errorWrapper?.remove(),this.errorWrapper=void 0}};function Lt(i,e,t=!1){return!t&&i==null&&e!=null}function At(i,e,t=!1){return i==null&&e!=null&&!t}const Mt=5e3;let Ht=-1;function xt(i,e){return(i.overflow??"scroll")!==(e.overflow??"scroll")||(i.collapsed??!1)!==(e.collapsed??!1)||(i.disableLineNumbers??!1)!==(e.disableLineNumbers??!1)||(i.disableFileHeader??!1)!==(e.disableFileHeader??!1)||i.unsafeCSS!==e.unsafeCSS}var wt=class extends Te{virtualizer;metrics;__id=`virtualized-file:${++Ht}`;top;height=0;cache={heights:new Map,checkpoints:[],fileAnnotationHeight:0};isVisible=!1;isSetup=!1;layoutDirty=!0;forceRenderOverride;currentCollapsed;constructor(i,e,t=Ne,n,r=!1){super(i,n,r),this.virtualizer=e,this.metrics=t}setMetrics(i,e=!1){!e&&rt(this.metrics,i)||(this.metrics=i,this.resetLayoutCache())}setLineAnnotations(i){this.syncLineAnnotations(i)&&this.resetLayoutCache()}syncLineAnnotations(i){return i==null||i===this.lineAnnotations||i.length===0&&this.lineAnnotations.length===0?!1:(super.setLineAnnotations(i),!0)}hasLineAnnotations(){return this.lineAnnotations.some(i=>i.lineNumber>0)}getLineHeight(i,e=!1){const t=this.cache.heights.get(i);if(t!=null)return t;const n=e?2:1;return this.metrics.lineHeight*n}setOptions(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setOptions cannot be used inside CodeView. Update CodeView options instead.");if(i==null)return;const{options:e}=this,t=!ye(e,i),n=xt(e,i);super.setOptions(i),n&&this.resetLayoutCache(!0),t&&(this.forceRenderOverride=!0),t&&this.virtualizer.instanceChanged(this,n)}setThemeType(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setThemeType cannot be used inside CodeView. Update CodeView options instead.");super.setThemeType(i)}resetLayoutCache(i=!1){this.layoutDirty=!0,this.cache.fileAnnotationHeight=0,this.cache.heights.size>0&&this.cache.heights.clear(),this.cache.checkpoints.length>0&&(this.cache.checkpoints.length=0),this.renderRange!=null&&(this.renderRange=void 0),i&&this.isSimpleMode()&&this.computeApproximateSize()}reconcileHeights(){let i=!1;if(this.fileContainer==null||this.file==null)return this.height!==0&&(i=!0),this.height=0,i;const{overflow:e="scroll"}=this.options;if(this.top=this.getVirtualizedTop(),e==="scroll"&&this.lineAnnotations.length===0&&!this.isResizeDebuggingEnabled()||this.code==null)return i;const t=this.code.children[1];if(!(t instanceof HTMLElement))return i;const n=he(this.lineAnnotations);if(this.renderRange!=null&&n&&ve(this.renderRange)){const r=Et(t)??0;r!==this.cache.fileAnnotationHeight&&(this.cache.fileAnnotationHeight=r,i=!0)}else!n&&this.cache.fileAnnotationHeight!==0&&(this.cache.fileAnnotationHeight=0,i=!0);for(const r of t.children){if(!(r instanceof HTMLElement))continue;const s=r.dataset.lineIndex;if(s==null)continue;const a=Number(s);let o=r.getBoundingClientRect().height,h=!1;r.nextElementSibling instanceof HTMLElement&&("lineAnnotation"in r.nextElementSibling.dataset||"noNewline"in r.nextElementSibling.dataset)&&("noNewline"in r.nextElementSibling.dataset&&(h=!0),o+=r.nextElementSibling.getBoundingClientRect().height);const d=this.getLineHeight(a,h);o!==d&&(i=!0,o===this.metrics.lineHeight*(h?2:1)?this.cache.heights.delete(a):this.cache.heights.set(a,o))}return(i||this.isResizeDebuggingEnabled())&&this.computeApproximateSize(!0),i}onRender=i=>this.fileContainer==null||this.file==null?!1:(i&&(this.top=this.getVirtualizedTop()),this.render({file:this.file}));prepareCodeViewItem(i,e,t,n){const r=this.syncLineAnnotations(n);let s=t?.resetFileLayoutCache===!0||r;t?.metrics!=null&&(this.metrics=t.metrics,s=!0);const{collapsed:a=!1}=this.options;return this.currentCollapsed!==a&&(this.currentCollapsed=a,s=!0),s&&this.resetLayoutCache(),this.file!==i&&(this.layoutDirty=!0),this.file=i,this.top=e,this.computeApproximateSize(),this.height}getLinePosition(i){if(this.file==null||i<1)return;const{disableFileHeader:e=!1,collapsed:t=!1}=this.options,n=this.fileRenderer.getLineCount(this.file)-1;let r=B(this.metrics,e);if(t||n<0)return{top:r,height:0};const s=Math.min(Math.max(i-1,0),n),{overflow:a="scroll"}=this.options,{lineHeight:o}=this.metrics;if(r+=this.cache.fileAnnotationHeight,a==="scroll"&&!this.hasLineAnnotations())return{top:r+s*o,height:o};const h=this.getLayoutCheckpointBeforeLineIndex(s);r=h?.top??r;for(let d=h?.lineIndex??0;d<s;d++)r+=this.getLineHeight(d,!1);return{top:r,height:this.getLineHeight(s,!1)}}getNumericScrollAnchor(i){if(this.file==null||this.renderRange==null)return;const{disableFileHeader:e=!1,collapsed:t=!1,overflow:n="scroll"}=this.options;if(t||this.renderRange.totalLines<=0)return;const r=this.fileRenderer.getLineCount(this.file)-1;if(r<0)return;const s=B(this.metrics,e),a=Math.min(this.renderRange.startingLine,r),o=Math.min(a+this.renderRange.totalLines-1,r);if(o<a)return;const{fileAnnotationHeight:h}=this.cache;if(n==="scroll"&&!this.hasLineAnnotations()){const{lineHeight:l}=this.metrics,c=s+(a===0?h:this.renderRange.bufferBefore),u=a+Math.max(Math.ceil((i-c)/l),0);return u>o?void 0:{lineNumber:u+1,top:s+h+u*l}}let d=s+(a===0?h:this.renderRange.bufferBefore);for(let l=a;l<=o;l++){if(d>=i)return{lineNumber:l+1,top:d};d+=this.getLineHeight(l)}}getVirtualizedHeight(){return this.height}getAdvancedStickySpecs(i){if(this.top==null||this.file==null)return;if(this.options.collapsed===!0)return{topOffset:this.top,height:this.height};const e=i!=null?this.computeRenderRangeFromWindow(this.file,this.top,i):this.renderRange;if(e==null)return;const{bufferBefore:t,bufferAfter:n,totalLines:r}=e;let s=0;if(r===0){const a=i??this.virtualizer.getWindowSpecs();this.top<a.top&&(s=n)}return{topOffset:this.top+t+s,height:this.height-(t+n)}}cleanUp(i=!1){this.fileContainer!=null&&this.isSimpleMode()&&this.getSimpleVirtualizer()?.disconnect(this.fileContainer),i||this.resetLayoutCache(),this.isSetup=!1,super.cleanUp(i)}computeApproximateSize(i=!1){const e=this.isResizeDebuggingEnabled();if(!i&&!this.layoutDirty&&!e)return;const t=this.height===0;if(this.height=0,this.cache.checkpoints=[],this.file==null){this.layoutDirty=!1;return}const{disableFileHeader:n=!1,collapsed:r=!1,overflow:s="scroll"}=this.options,{lineHeight:a}=this.metrics,o=this.fileRenderer.getLineCount(this.file),h=B(this.metrics,n),d=fe(this.metrics);if(this.height+=h,r){this.layoutDirty=!1;return}if(this.height+=this.cache.fileAnnotationHeight,s==="scroll"&&!this.hasLineAnnotations())this.height+=o*a;else for(let l=0;l<o;l++)this.addLayoutCheckpoint(l,this.height),this.height+=this.getLineHeight(l,!1);if(o>0&&(this.height+=d),this.fileContainer!=null&&e&&!t){const l=this.fileContainer.getBoundingClientRect();l.height!==this.height?console.log("VirtualizedFile.computeApproximateSize: computed height doesnt match",{name:this.file.name,elementHeight:l.height,computedHeight:this.height}):console.log("VirtualizedFile.computeApproximateSize: computed height IS CORRECT")}this.layoutDirty=!1}setVisibility(i){this.isAdvancedMode()||this.fileContainer==null||(i&&!this.isVisible?(this.top=this.getVirtualizedTop(),this.isVisible=!0):!i&&this.isVisible&&(this.isVisible=!1,this.rerender()))}rerender(){!this.enabled||this.file==null||(this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!1))}applyDocumentChange(i,e,t=!1){const{heights:n,checkpoints:r}=this.cache,s=this.renderRange;if(super.applyDocumentChange(i,e),this.getSimpleVirtualizer()?.markDOMDirty(),this.layoutDirty=!0,n.size>0&&n.clear(),r.length>0&&(r.length=0),this.isSimpleMode()&&this.computeApproximateSize(),t&&s!==void 0&&this.file!==void 0){const a=this.virtualizer.getWindowSpecs(),o=this.computeRenderRangeFromWindow(this.file,this.top??0,a);o.bufferAfter!==s.bufferAfter&&this.updateBuffers(o)}}render({fileContainer:i,file:e,forceRender:t=!1,lineAnnotations:n,...r}){const s=this.file==null||!A(this.file,e),{forceRenderOverride:a,isSetup:o}=this;this.forceRenderOverride=void 0;const h=this.syncLineAnnotations(n);if(h&&this.resetLayoutCache(),this.file=e,i=this.getOrCreateFileContainerNode(i),this.file==null)return console.error("VirtualizedFile.render: attempting to virtually render when we dont have file"),!1;if(o)this.top??=this.getVirtualizedTop(),s&&this.isSimpleMode()&&(this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache(!0));else{this.computeApproximateSize();const u=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(u==null)throw new Error("VirtualizedFile.render: simple virtualizer is not available");u.connect(i,this),this.isVisible=u.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode())return this.renderPlaceholder(this.height);const d=this.virtualizer.getWindowSpecs(),l=this.top??0,c=this.computeRenderRangeFromWindow(this.file,l,d);return super.render({file:this.file,fileContainer:i,renderRange:c,lineAnnotations:n,forceRender:(a??t)||h,...r})}syncVirtualizedTop(){this.top=this.getVirtualizedTop()}shouldDisableVirtualizationBuffers(){return this.isAdvancedMode()||super.shouldDisableVirtualizationBuffers()}isSimpleMode(){return this.virtualizer.type==="simple"}isAdvancedMode(){return this.virtualizer.type==="advanced"}addLayoutCheckpoint(i,e){i%Mt===0&&this.cache.checkpoints.push({lineIndex:i,top:e})}getLayoutCheckpointBeforeLineIndex(i){if(i<=0||this.cache.checkpoints.length===0)return;let e=0,t=this.cache.checkpoints.length-1,n;for(;e<=t;){const r=e+t>>1,s=this.cache.checkpoints[r];if(s==null)throw new Error("VirtualizedFile: invalid checkpoint index");s.lineIndex<=i?(n=s,e=r+1):t=r-1}return n}getLayoutCheckpointBeforeTop(i,e){let t=0,n=this.cache.checkpoints.length-1,r=-1;for(;t<=n;){const s=t+n>>1,a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");a.top<=i?(r=s,t=s+1):n=s-1}if(e==null)return r>=0?this.cache.checkpoints[r]:void 0;for(let s=r;s>=0;s--){const a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");if(a.lineIndex%e===0)return a}}getVirtualizedTop(){return this.virtualizer.type==="advanced"?this.virtualizer.getLocalTopForInstance(this):this.fileContainer!=null?this.virtualizer.getOffsetInScrollContainer(this.fileContainer):0}getSimpleVirtualizer(){return this.virtualizer.type==="simple"?this.virtualizer:void 0}isResizeDebuggingEnabled(){return this.getSimpleVirtualizer()?.config.resizeDebugging??!1}computeRenderRangeFromWindow(i,e,{top:t,bottom:n}){const{disableFileHeader:r=!1,overflow:s="scroll"}=this.options,{hunkLineCount:a,lineHeight:o}=this.metrics,h=this.fileRenderer.getLineCount(i),d=this.height,l=B(this.metrics,r),c=h>0?fe(this.metrics):0,{fileAnnotationHeight:u}=this.cache,p=l+u,f=Math.max(0,d-l-u-c),S=he(this.lineAnnotations),g=e+l,y=u>0&&S&&g<n&&g+u>t;if(e<t-d||e>n)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};if(h<=a)return{startingLine:0,totalLines:a,bufferBefore:0,bufferAfter:0};const m=Math.ceil(Math.max(n-t,0)/o),v=Math.ceil(m/a)*a+a*2,z=v/a,D=(t+n)/2;if(s==="scroll"&&!this.hasLineAnnotations()){const R=e+p,P=R+f;if(!y&&!(R<n&&P>t))return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};const w=Math.floor(y&&D<e+p?0:(D-(e+p))/o),b=Math.floor(w/a)-Math.floor(z/2),xe=Math.ceil(h/a),E=Math.max(0,Math.min(b,xe))*a,Q=b<0?v+b*a:v,we=E===0?0:u+E*o,Ee=Math.min(Q,h-E);return{startingLine:E,totalLines:Q,bufferBefore:we,bufferAfter:Math.max(0,(h-E-Ee)*o)}}const be=z,N=[],U=this.getLayoutCheckpointBeforeTop(Math.max(0,t-e-v*o*2),a);let T=e+(U?.top??p),_=U?.lineIndex??0,O,V,x;const Re=U?.lineIndex??0;for(let R=Re;R<h;R++){const P=_%a===0,w=Math.floor(_/a);if(P&&(N[w]=T-(e+p),x!=null)){if(x<=0)break;x--}const b=this.getLineHeight(R,!1);T>t-b&&T<n&&(O??=w),T+b>D&&(V??=w),x==null&&T>=n&&P&&(x=be),_++,T+=b}if(O==null)if(y)O=0,V=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};V??=O;const W=Math.round(V-z/2),Le=Math.max(0,Math.ceil(h/a)-z),G=Math.max(0,Math.min(W,Le)),J=G*a,Y=W<0?v+W*a:v,Ae=N[G]??0,Me=J===0?0:u+Ae,X=G+Y/a,He=X<N.length?f-N[X]:f-(T-e-p);return{startingLine:J,totalLines:Y,bufferBefore:Me,bufferAfter:Math.max(0,He)}}};function Et(i){let e;for(const t of i.children)t instanceof HTMLElement&&t.dataset.lineAnnotation===st&&(e=Math.max(e??0,t.getBoundingClientRect().height));return e}function Ft({file:i,renderCustomHeader:e,renderHeaderPrefix:t,renderHeaderFilenameSuffix:n,renderHeaderMetadata:r,renderAnnotation:s,lineAnnotations:a,renderGutterUtility:o,getHoveredLine:h}){const d=e?.(i),l=t?.(i),c=n?.(i),u=r?.(i);return C.jsxs(C.Fragment,{children:[d!=null?C.jsx("div",{slot:Ce,children:d}):C.jsxs(C.Fragment,{children:[l!=null&&C.jsx("div",{slot:"header-prefix",children:l}),c!=null&&C.jsx("div",{slot:"header-filename-suffix",children:c}),u!=null&&C.jsx("div",{slot:"header-metadata",children:u})]}),s!=null&&a?.map((p,f)=>C.jsx("div",{slot:I(p),children:s(p)},f)),o!=null&&C.jsx("div",{slot:"gutter-utility-slot",style:at,children:o(h)})]})}const me=typeof window>"u"?k.useEffect:k.useLayoutEffect;function kt({file:i,options:e,lineAnnotations:t,selectedLines:n,prerenderedHTML:r,metrics:s,hasGutterRenderUtility:a,hasCustomHeader:o,disableWorkerPool:h,contentEditable:d}){const l=ot(),c=n!==void 0,u=k.useContext(ht),p=lt(),f=k.useRef(null),S=dt(g=>{if(g!=null){if(f.current!=null)throw new Error("File: An instance should not already exist when a node is created");l!=null?f.current=new wt(q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),l,s,h?void 0:u,!0):f.current=new Te(q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),h?void 0:u,!0),f.current.hydrate({file:i,fileContainer:g,lineAnnotations:t,prerenderedHTML:r})}else{if(f.current==null)throw new Error("File: A File instance should exist when unmounting");f.current.cleanUp(),f.current=null}});return me(()=>{if(f.current==null)return;const g=q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),y=!ye(f.current.options,g);f.current.setOptions(g),f.current.render({file:i,lineAnnotations:t,forceRender:y}),n!==void 0&&f.current.setSelectedLines(n)}),me(()=>{if(d&&f.current!=null){if(p===void 0)throw new Error("File: Editor is not attached");return p.edit(f.current)}},[d,p]),{ref:S,getHoveredLine:k.useCallback(()=>f.current?.getHoveredLine(),[])}}function q({options:i,controlledSelection:e,contentEditable:t,hasCustomHeader:n,hasEditor:r,hasGutterRenderUtility:s}){const a=t&&r,o=e||s||n;if(!o&&!a)return i;let h={...i};return o&&(h={...h,controlledSelection:e,renderCustomHeader:n?le:i?.renderCustomHeader,renderGutterUtility:s?le:i?.renderGutterUtility}),a&&(h={...h,useTokenTransformer:!0,enableGutterUtility:!1,enableLineSelection:!1,lineHoverHighlight:"disabled"}),h}function Ut({file:i,lineAnnotations:e,selectedLines:t,options:n,metrics:r,className:s,style:a,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:d,renderHeaderFilenameSuffix:l,renderHeaderMetadata:c,prerenderedHTML:u,renderGutterUtility:p,disableWorkerPool:f=!1,contentEditable:S=!1}){const{ref:g,getHoveredLine:y}=kt({file:i,options:n,metrics:r,lineAnnotations:e,selectedLines:t,prerenderedHTML:u,hasGutterRenderUtility:p!=null,hasCustomHeader:h!=null,disableWorkerPool:f,contentEditable:S});return C.jsx(Oe,{ref:g,className:s,style:a,children:ct(Ft({file:i,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:d,renderHeaderFilenameSuffix:l,renderHeaderMetadata:c,renderGutterUtility:p,lineAnnotations:e,getHoveredLine:y}),u)})}const _t=L.memo(function({jsonString:e,className:t,maxHeight:n="100%",initiallyExpandedDepth:r=2}){const s=L.useRef(null),[a,o]=L.useState(null),h=L.useMemo(()=>{try{const c=e.trim();if(!c)return o("Empty JSON content"),null;const u=JSON.parse(c);return o(null),u}catch(c){return o(c instanceof Error?c.message:"Invalid JSON"),null}},[e]),d=L.useCallback(()=>{s.current?.expandAll()},[]),l=L.useCallback(()=>{s.current?.collapseAll()},[]);return a?C.jsx("div",{className:t,children:C.jsxs("div",{className:"rounded-md border border-[var(--interactive-border)] bg-[var(--syntax-base-background)] p-4",children:[C.jsx("div",{className:"mb-1 font-medium text-[var(--surface-foreground)]",children:"Invalid JSON"}),C.jsx("div",{className:"font-mono text-xs text-[var(--surface-mutedForeground)]",children:a})]})}):h===null?null:C.jsxs("div",{className:t,children:[C.jsxs("div",{className:"flex items-center gap-1 border-b border-[var(--interactive-border)] px-2 py-1",children:[C.jsxs(ee,{variant:"ghost",size:"xs",onClick:d,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-down-s",className:"h-3 w-3"}),"Expand All"]}),C.jsxs(ee,{variant:"ghost",size:"xs",onClick:l,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-up-s",className:"h-3 w-3"}),"Collapse All"]})]}),C.jsx("div",{className:"bg-[var(--syntax-base-background)] py-1",style:{maxHeight:n,overflow:"auto"},children:C.jsx(Ve,{ref:s,data:h,maxHeight:n,initiallyExpandedDepth:r})})]})});export{Ut as F,_t as J};
1
+ import{dc as M,dR as Q,dS as Fe,dT as Ce,dU as ke,dV as Ie,dW as ze,dX as Ne,dY as Oe,B as ee,I as te,dZ as Ve}from"./useAppFontEffects-DqOhrZWx.js";import{a as ie,s as Pe,b as Se,c as ne,d as ve,g as Be,e as re,f as I,h as De,i as Ue,j as _e,k as We,R as Ge,I as je,p as se,l as $e,m as qe,n as Ke,o as Ye,w as Je,q as ae,u as Xe,r as Ze,t as Qe,v as et,x as oe,S as tt,y as it,z as nt,A as rt,B as ye,C as he,F as st}from"./web-components-P2py0R8j.js";import{G as at,u as ot,W as ht,a as lt,b as dt,n as le,t as ct}from"./Virtualizer-BxW2CJGB.js";import{j as C,r as k,R as L}from"./vendor-react-DYyjh7Q0.js";import{j as ut,i as j,f as A,a as ft,k as de,l as pt,m as ce,d as gt,n as ue,b as mt,o as B,q as fe}from"./computeVirtualFileMetrics-CInbUZiB.js";import{a as F,i as K,l as pe,h as Ct,r as St}from"./isFilePlainText-D4iUTBdr.js";import{t as H}from"./vendor-hast-util-to-html-BKBhbTDb.js";let vt=-1;var yt=class{options;onRenderUpdate;workerManager;__id=`file-renderer:${++vt}`;highlighter;renderCache;computedLang="text";lineAnnotations={};lineCache;textDoucmentCache=new WeakMap;constructor(i={theme:M},e,t){this.options=i,this.onRenderUpdate=e,this.workerManager=t,t?.isWorkingPool()!==!0&&(this.highlighter=ie(i.theme??M)?ut():void 0)}setOptions(i){this.options=i}mergeOptions(i){this.options={...this.options,...i}}setLineAnnotations(i){this.lineAnnotations={};for(const e of i){const t=this.lineAnnotations[e.lineNumber]??[];this.lineAnnotations[e.lineNumber]=t,t.push(e)}}cleanUp(){this.recycle(),this.workerManager=void 0,this.onRenderUpdate=void 0}recycle(){this.clearRenderCache(),this.highlighter=void 0,this.workerManager?.cleanUpTasks(this),this.lineCache=void 0}clearRenderCache(){const i=this.renderCache;this.renderCache=void 0,i!=null&&i.isDirty===!0&&i.file.cacheKey!=null&&this.workerManager?.evictFileFromCache(i.file.cacheKey)}hydrate(i){const{options:e}=this.getRenderOptions(i),t=$(this.getOrCreateLineCache(i).length,this.getTokenizeMaxLength());let n=this.workerManager?.getFileResultCache(i);n!=null&&!F(e,n.options)&&(n=void 0),this.renderCache??={file:i,options:e,highlighted:!t&&!K(i),result:t?void 0:n?.result,renderRange:void 0},this.workerManager?.isWorkingPool()===!0?this.renderCache.result==null&&!t&&this.workerManager.highlightFileAST(this,i):this.highlighter==null&&(this.computedLang=i.lang??j(i.name),this.initializeHighlighter())}getRenderOptions(i){const e=(()=>{if(this.workerManager?.isWorkingPool()===!0)return this.workerManager.getFileRenderOptions();const{theme:n=M,tokenizeMaxLineLength:r=1e3}=this.options;return{theme:n,useTokenTransformer:Pe(this.options),tokenizeMaxLineLength:r}})(),{renderCache:t}=this;return t?.result==null?{options:e,forceHighlight:!0}:!A(i,t.file)||!F(e,t.options)?{options:e,forceHighlight:!0}:{options:e,forceHighlight:!1}}getOrCreateLineCache(i){if(i.cacheKey==null)return this.lineCache=void 0,pe(i.contents);let{lineCache:e}=this;return(e==null||e.cacheKey!==i.cacheKey)&&(e={cacheKey:i.cacheKey,lines:pe(i.contents)}),this.lineCache=e,e.lines}getLineCount(i){return this.textDoucmentCache.get(i)?.lineCount??this.getOrCreateLineCache(i).length}updateRenderCache(i,e){if(this.renderCache==null)return;const{result:t}=this.renderCache;if(t!=null){for(const[n,r]of i)t.code[n]={type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:r.map(([s,a,o])=>s===0&&a===""?o===""?{type:"element",tagName:"br",properties:{},children:[]}:{type:"text",value:o}:{type:"element",tagName:"span",properties:{"data-char":s,style:`--diffs-token-${e}:${a};`},children:[{type:"text",value:o}]})};t.baseThemeType=e,this.renderCache.isDirty=!0}}applyDocumentChange(i){if(this.renderCache==null)return;const{file:e,result:t}=this.renderCache;if(t!=null&&t.code.length!==i.lineCount){t.code.length=Math.min(t.code.length,i.lineCount);for(let n=t.code.length;n<i.lineCount;n++)t.code.push({type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:[{type:"element",tagName:"span",properties:{"data-char":0},children:[{type:"text",value:i.getLineText(n)}]}]});this.renderCache.isDirty=!0}this.textDoucmentCache.set(e,i)}renderFile(i=this.renderCache?.file,e=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),d=!Se(this.renderCache.renderRange,e);if(this.workerManager?.isWorkingPool()===!0)(o||this.renderCache.result==null||!this.renderCache.highlighted&&(h||d))&&(this.renderCache.file=i,this.renderCache.options=t,this.renderCache.highlighted=!1,(this.renderCache.result==null||h||d||n)&&(this.renderCache.result=this.workerManager.getPlainFileAST(i,e.startingLine,e.totalLines,s)),this.renderCache.renderRange=e),!o&&a&&(!this.renderCache.highlighted||n)&&this.workerManager.highlightFileAST(this,i);else{this.computedLang=i.lang??j(i.name);const l=this.highlighter!=null&&ie(t.theme),c=this.highlighter!=null&&ne(this.computedLang),u=!o&&c;if(this.highlighter!=null&&l&&(n||o||!this.renderCache.highlighted&&u||this.renderCache.result==null)){const{result:p,options:f}=this.renderFileWithHighlighter(i,this.highlighter,o||!c);this.renderCache={file:i,options:f,highlighted:u,result:p,renderRange:void 0}}(!l||!o&&!c)&&this.asyncHighlight(i).then(({result:p,options:f})=>{this.renderCache!=null&&(this.renderCache.highlighted=!1),this.onHighlightSuccess(i,p,f,!o)})}return this.renderCache.result!=null?this.processFileResult(this.renderCache.file,e,this.renderCache.result):void 0}async asyncRender(i,e=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??j(i.name);const t=this.highlighter!=null&&Ct(ft(this.options.theme)),n=e||this.highlighter!=null&&ne(this.computedLang);return(this.highlighter==null||!t||!n)&&(this.highlighter=await this.initializeHighlighter()),this.renderFileWithHighlighter(i,this.highlighter,e)}renderFileWithHighlighter(i,e,t=!1){const{options:n}=this.getRenderOptions(i);return{result:St(i,e,n,{forcePlainText:t}),options:n}}processFileResult(i,e,{code:t,themeStyles:n,baseThemeType:r}){const s=this.getLineCount(i),{disableFileHeader:a=!1}=this.options,o=[],h=ue(),d=Math.min(e.startingLine+e.totalLines,s);let l=0;const c=ve(e)?Be(this.lineAnnotations):void 0;c!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:-1,lineIndex:-1,annotations:c.map(u=>I(u))})),l++);for(let u=e.startingLine;u<d;u++){const p=u+1,f=t[u];if(f==null){const g="FileRenderer.processFileResult: Line doesnt exist";throw console.error(g,{name:i.name,lineIndex:u,lineNumber:p}),new Error(g)}h.children.push(pt("context",p,`${u}`)),o.push(f),l++;const S=this.lineAnnotations[p];S!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:0,lineIndex:p,annotations:S.map(g=>I(g))})),l++)}return h.properties.style=`grid-row: span ${l}`,{gutterAST:h.children??[],contentAST:o,preAST:this.createPreElement(s),headerAST:a?void 0:this.renderHeader(i),totalLines:s,rowCount:l,themeStyles:n,baseThemeType:r,bufferBefore:e.bufferBefore,bufferAfter:e.bufferAfter,css:""}}renderHeader(i){const{headerRenderMode:e="default",stickyHeader:t=!1}=this.options;return De({fileOrDiff:i,mode:e,stickyHeader:t})}renderFullHTML(i){return H(this.renderFullAST(i))}renderFullAST(i,e=[]){return e.push(ce({tagName:"code",children:this.renderCodeAST(i),properties:{"data-code":""}})),{...i.preAST,children:e}}renderCodeAST(i){const e=ue();return e.children=i.gutterAST,e.properties.style=`grid-row: span ${i.rowCount}`,[e,Ue(i.contentAST,i.rowCount)]}renderPartialHTML(i,e=!1){return e?H(ce({tagName:"code",children:i,properties:{"data-code":""}})):H(i)}async initializeHighlighter(){return this.highlighter=await gt(_e(this.computedLang,this.options)),this.highlighter}onHighlightSuccess(i,e,t,n=!0){if(this.renderCache==null)return;const r=!A(i,this.renderCache.file)||!this.renderCache.highlighted||!F(t,this.renderCache.options);this.renderCache={file:i,options:t,highlighted:n,result:e,renderRange:void 0},r&&this.onRenderUpdate?.()}getMatchingWorkerResultCache(i,e){const t=this.workerManager?.getFileResultCache(i);if(!(t==null||!F(e,t.options)))return t}hasHighlightedRenderCache(i,e){const{renderCache:t}=this;return t?.result!=null&&t.highlighted&&A(i,t.file)&&F(e,t.options)}onHighlightError(i){console.error(i)}getTokenizeMaxLength(){return this.options.tokenizeMaxLength??1e5}createPreElement(i){const{disableLineNumbers:e=!1,overflow:t="scroll"}=this.options;return We({type:"file",diffIndicators:"none",disableBackground:!0,disableLineNumbers:e,overflow:t,split:!1,totalLines:i})}};function $(i,e){return i>e}function Tt(i,e){return i.lineNumber===e.lineNumber&&i.metadata===e.metadata}function ge(i){return{theme:i?.theme,disableLineNumbers:i?.disableLineNumbers,overflow:i?.overflow,themeType:i?.themeType,collapsed:i?.collapsed,disableFileHeader:i?.disableFileHeader,disableVirtualizationBuffers:i?.disableVirtualizationBuffers,stickyHeader:i?.stickyHeader,preferredHighlighter:i?.preferredHighlighter,useCSSClasses:i?.useCSSClasses,useTokenTransformer:i?.useTokenTransformer,tokenizeMaxLineLength:i?.tokenizeMaxLineLength,tokenizeMaxLength:i?.tokenizeMaxLength,unsafeCSS:i?.unsafeCSS,headerRenderMode:i?.renderCustomHeader!=null?"custom":"default"}}const bt=[""];let Rt=-1;var Te=class{options;workerManager;isContainerManaged;static LoadedCustomComponent=!0;__id=`file:${++Rt}`;type="file";fileContainer;spriteSVG;pre;code;bufferBefore;bufferAfter;themeCSSStyle;appliedThemeCSS;hasAdoptedThemeCSS=!1;unsafeCSSStyle;appliedUnsafeCSS;gutterUtilityContent;errorWrapper;placeHolder;lastRenderedHeaderHTML;cachedHeaderHTML;appliedPreAttributes;lastRowCount;mounted=!1;headerElement;headerCustom;headerPrefix;headerFilenameSuffix;headerMetadata;fileRenderer;resizeManager;interactionManager;annotationCache=new Map;lineAnnotations=[];managersDirty=!1;file;renderRange;enabled=!0;editor;constructor(e={theme:M},t,n=!1){this.options=e,this.workerManager=t,this.isContainerManaged=n,this.fileRenderer=new yt(e,this.handleHighlightRender,this.workerManager),this.resizeManager=new Ge,this.interactionManager=new je("file",se(e)),this.workerManager?.subscribeToThemeChanges(this)}handleHighlightRender=()=>{this.rerender()};rerender(){!this.enabled||this.file==null||this.render({file:this.file,forceRender:!0,renderRange:this.renderRange})}onThemeChange(){this.fileRenderer.clearRenderCache(),this.rerender()}setOptions(e){e!=null&&(this.options=e,this.cachedHeaderHTML=void 0,this.syncInteractionOptions())}syncInteractionOptions(){this.interactionManager.setOptions(se(this.options))}mergeOptions(e){this.options={...this.options,...e}}setThemeType(e){(this.options.themeType??"system")!==e&&(this.mergeOptions({themeType:e}),this.applyCachedThemeState(e))}applyCachedThemeState(e){if(typeof this.options.theme=="string"||this.fileContainer==null||this.appliedThemeCSS==null)return!1;const t=this.appliedThemeCSS.baseThemeType??e;return this.appliedThemeCSS.themeType===t?!1:(this.applyThemeState(this.fileContainer,this.appliedThemeCSS.themeStyles,e,this.appliedThemeCSS.baseThemeType),!0)}hasThemeChanged(){return this.appliedThemeCSS!=null&&!mt(this.appliedThemeCSS.theme,this.options.theme??M)}getHoveredLine=()=>this.interactionManager.getHoveredLine();setLineAnnotations(e){this.lineAnnotations=e}setSelectedLines(e,t){this.interactionManager.setSelection(e,t)}flushManagers(){if(!this.managersDirty||this.pre==null){this.managersDirty=!1;return}const{overflow:e="scroll"}=this.options;this.interactionManager.setup(this.pre),this.resizeManager.setup(this.pre,e==="wrap"),this.managersDirty=!1}cleanUp(e=!1){this.emitPostRender(!0),this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.managersDirty=!1,this.workerManager?.unsubscribeToThemeChanges(this),this.renderRange=void 0,this.isContainerManaged||this.fileContainer?.remove(),this.fileContainer=void 0,this.mounted=!1,e||(this.lineAnnotations=[]),this.annotationCache.clear(),this.pre=void 0,this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.lastRenderedHeaderHTML=void 0,e||(this.cachedHeaderHTML=void 0),this.errorWrapper=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.placeHolder=void 0,this.unsafeCSSStyle=void 0,e?this.fileRenderer.recycle():(this.fileRenderer.cleanUp(),this.workerManager=void 0,this.file=void 0),this.enabled=!1,this.editor?.cleanUp(),this.editor=void 0}virtualizedSetup(){this.enabled=!0,this.workerManager?.subscribeToThemeChanges(this)}hydrate(e){const{fileContainer:t,prerenderedHTML:n,preventEmit:r=!1,file:s,lineAnnotations:a}=e;this.hydrateElements(t,n),Lt(this.pre,s,this.options.collapsed)||At(this.headerElement,s,this.options.disableFileHeader)?this.render({...e,preventEmit:!0}):this.hydrationSetup({file:s,lineAnnotations:a}),r||this.emitPostRender()}hydrateElements(e,t){this.fileContainer!==e&&this.emitPostRender(!0),$e(e,t);for(const n of Array.from(e.shadowRoot?.children??[])){if(n instanceof SVGElement){this.spriteSVG=n;continue}if(n instanceof HTMLElement){if(n instanceof HTMLPreElement){this.pre=n,this.appliedPreAttributes=void 0;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-theme-css")){this.themeCSSStyle=n;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-unsafe-css")){this.unsafeCSSStyle=n,this.appliedUnsafeCSS=n.textContent;continue}if("diffsHeader"in n.dataset){this.headerElement=n,this.lastRenderedHeaderHTML=void 0;continue}}}this.pre!=null&&(this.syncCodeNodeFromPre(this.pre),this.pre.removeAttribute("data-dehydrated")),this.fileContainer=e,this.hydrateMeasuredScrollbar()}hydrationSetup({file:e,lineAnnotations:t}){this.lineAnnotations=t??this.lineAnnotations,this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),this.pre!=null&&(this.fileRenderer.hydrate(e),this.renderAnnotations(),this.renderGutterUtility(),this.injectUnsafeCSS(),this.managersDirty=!0,this.flushManagers())}getOrCreateLineCache(e=this.file){return e!=null?this.fileRenderer.getOrCreateLineCache(e):bt}updateBuffers(e){this.pre!=null&&this.applyBuffers(this.pre,e)}syncRenderViewToEditor(){const e=this.editor,t=this.fileContainer,n=this.file;e!=null&&t!=null&&n!=null&&this.fileRenderer.initializeHighlighter().then(r=>{e.__syncRenderView(r,t,n,this.lineAnnotations,this.renderRange)})}attachEditor(e){return this.editor?.cleanUp(),this.editor=e,this.interactionManager.setEditorAttached(!0),this.syncRenderViewToEditor(),()=>{this.editor=void 0,this.interactionManager.setEditorAttached(!1)}}applyDocumentChange(e,t){this.fileRenderer.applyDocumentChange(e),t!=null&&t!==this.lineAnnotations&&this.file!=null&&(this.setLineAnnotations(t),this.fileRenderer.setLineAnnotations(this.lineAnnotations),this.renderAnnotations())}updateRenderCache(e,t){this.fileRenderer.updateRenderCache(e,t)}render({file:e,fileContainer:t,forceRender:n=!1,preventEmit:r=!1,containerWrapper:s,deferManagers:a=!1,lineAnnotations:o,renderRange:h}){if(!this.enabled)throw new Error("File.render: attempting to call render after cleaned up");this.editor?.__postponeBackgroundTokenizeToNextFrame();const{collapsed:d=!1,themeType:l="system"}=this.options,c=d?void 0:h,u=this.renderRange,p=this.hasThemeChanged(),f=o!=null&&(o.length>0||this.lineAnnotations.length>0)?o!==this.lineAnnotations:!1,S=!A(this.file,e);if(!d&&!n&&Se(c,this.renderRange)&&!S&&!f&&!p)return this.applyCachedThemeState(l);this.renderRange=c,S&&(this.cachedHeaderHTML=void 0),this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),o!=null&&this.setLineAnnotations(o),this.fileRenderer.setLineAnnotations(this.lineAnnotations);const{disableErrorHandling:g=!1,disableFileHeader:y=!1}=this.options;if(y&&(this.headerElement!=null&&(this.headerElement.remove(),this.headerElement=void 0,this.lastRenderedHeaderHTML=void 0),this.clearHeaderSlots()),t=this.getOrCreateFileContainerNode(t,s),this.applyCachedThemeState(l),d){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{const m=this.fileRenderer.renderFile(e,Fe);m!=null&&this.applyThemeState(t,m.themeStyles,l,m.baseThemeType),m?.headerAST!=null&&this.applyHeaderToDOM(m.headerAST,t),this.injectUnsafeCSS()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}try{const m=this.getOrCreatePreNode(t);if(!this.canPartiallyRender(n,f,S||p)||!this.applyPartialRender(u,c)){const v=this.fileRenderer.renderFile(e,c);if(v==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.initialize().then(()=>this.rerender()),!1;this.applyThemeState(t,v.themeStyles,l,v.baseThemeType),v.headerAST!=null&&this.applyHeaderToDOM(v.headerAST,t),this.applyFullRender(v,m)}this.applyBuffers(m,c),this.injectUnsafeCSS(),this.managersDirty=!0,a||this.flushManagers(),this.renderAnnotations(),this.renderGutterUtility(),this.editor!=null&&this.syncRenderViewToEditor()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}emitPostRender(e=!1){const{fileContainer:t,options:{onPostRender:n}}=this;if(e){if(!this.mounted||(this.mounted=!1,t==null))return;n?.(t,this,"unmount");return}if(t==null)return;const r=this.mounted?"update":"mount";this.mounted=!0,n?.(t,this,r)}removeRenderedCode(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.code?.remove(),this.code=void 0,this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0}clearAuxiliaryNodes(){for(const{element:e}of this.annotationCache.values())e.remove();this.annotationCache.clear(),this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0}canPartiallyRender(e,t,n){return!(e||t||n)}renderPlaceholder(e){if(this.fileContainer==null)return!1;if(this.emitPostRender(!0),this.cleanChildNodes(),this.placeHolder==null){const t=this.fileContainer.shadowRoot??this.fileContainer.attachShadow({mode:"open"});this.placeHolder=document.createElement("div"),this.placeHolder.dataset.placeholder="",t.appendChild(this.placeHolder)}return this.placeHolder.style.setProperty("height",`${e}px`),!0}primeHighlightCache(){const{file:e,workerManager:t}=this;e==null||e.cacheKey==null||t==null||K(e)||this.fileRenderer.getOrCreateLineCache(e).length>(this.options.tokenizeMaxLength??1e5)||t.primeFileHighlightCache(e)}cleanChildNodes(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferAfter?.remove(),this.bufferBefore?.remove(),this.code?.remove(),this.errorWrapper?.remove(),this.headerElement?.remove(),this.gutterUtilityContent?.remove(),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.pre?.remove(),this.spriteSVG?.remove(),this.themeCSSStyle?.remove(),this.unsafeCSSStyle?.remove(),this.bufferAfter=void 0,this.bufferBefore=void 0,this.code=void 0,this.errorWrapper=void 0,this.headerElement=void 0,this.gutterUtilityContent=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.pre=void 0,this.spriteSVG=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.lastRenderedHeaderHTML=void 0,this.lastRowCount=void 0,this.mounted=!1}renderAnnotations(){if(this.isContainerManaged||this.fileContainer==null){for(const{element:n}of this.annotationCache.values())n.remove();this.annotationCache.clear();return}const e=new Map(this.annotationCache),{renderAnnotation:t}=this.options;if(t!=null&&this.lineAnnotations.length>0)for(const[n,r]of this.lineAnnotations.entries()){const s=`${n}-${I(r)}`;let a=this.annotationCache.get(s);if(a==null||!Tt(r,a.annotation)){a?.element.remove();const o=t(r);if(o==null)continue;a={element:qe(I(r)),annotation:r},a.element.appendChild(o),this.fileContainer.appendChild(a.element),this.annotationCache.set(s,a)}e.delete(s)}for(const[n,{element:r}]of e.entries())this.annotationCache.delete(n),r.remove()}renderGutterUtility(){const{renderGutterUtility:e}=this.options;if(this.fileContainer==null||e==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const t=e(this.interactionManager.getHoveredLine);if(t!=null&&this.gutterUtilityContent!=null)return;if(t==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const n=Ke();n.appendChild(t),this.fileContainer.appendChild(n),this.gutterUtilityContent=n}injectUnsafeCSS(){const{unsafeCSS:e}=this.options,t=this.fileContainer?.shadowRoot;if(t!=null){if(e==null||e===""){this.unsafeCSSStyle!=null&&(this.unsafeCSSStyle.remove(),this.unsafeCSSStyle=void 0),this.appliedUnsafeCSS=void 0;return}this.unsafeCSSStyle?.parentNode===t&&this.appliedUnsafeCSS===e||(this.unsafeCSSStyle??=Ye(),this.unsafeCSSStyle.parentNode!==t&&t.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=Je(e),this.appliedUnsafeCSS=e)}}applyThemeState(e,t,n,r){const s=e.shadowRoot??e.attachShadow({mode:"open"}),a=r??n,o=this.options.theme??M,h=typeof o=="string"?o:{...o},d=ae(s);if(this.themeCSSStyle?.parentNode===s&&this.appliedThemeCSS?.themeStyles===t&&this.appliedThemeCSS.themeType===a&&this.appliedThemeCSS.scrollbarGutter===d){this.appliedThemeCSS.theme=h;return}if(this.hasAdoptedThemeCSS&&this.themeCSSStyle?.parentNode===s){this.hasAdoptedThemeCSS=!1,this.appliedThemeCSS={theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:d};return}this.themeCSSStyle=Xe({shadowRoot:s,currentNode:this.themeCSSStyle,themeCSS:Ze(t,a,d)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:d}:void 0}hydrateMeasuredScrollbar(){const e=this.fileContainer?.shadowRoot;e==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=Qe(this.themeCSSStyle.textContent??"",ae(e)))}applyFullRender(e,t){this.cleanupErrorWrapper(),this.applyPreNodeAttributes(t,e),this.code=et({code:this.code});const n=this.fileRenderer.renderCodeAST(e);if(this.code.childElementCount>=2)for(let r=0;r<2;r++){const s=this.code.children[r],a=n[r];s.innerHTML=H(a.children),s.style.cssText=a.properties.style}else this.code.innerHTML=H(n);t.contains(this.code)||t.replaceChildren(this.code),this.lastRowCount=e.rowCount}applyPartialRender(e,t){if(e==null||t==null)return!1;const{file:n,code:r}=this,s=r!=null?this.getColumns(r):void 0;if(n==null||r==null||s==null)return!1;const a=e.startingLine,o=t.startingLine,h=e.totalLines===1/0?Number.POSITIVE_INFINITY:a+e.totalLines,d=t.totalLines===1/0?Number.POSITIVE_INFINITY:o+t.totalLines,l=Math.max(a,o),c=Math.min(h,d);if(c<=l||!this.trimDOMToOverlap(s.gutter,l,c)||!this.trimDOMToOverlap(s.content,l,c))return!1;let{length:u}=s.content.children;const p=(y,m)=>{if(!(m<=0))return this.fileRenderer.renderFile(n,{startingLine:y,totalLines:m,bufferBefore:0,bufferAfter:0})},f=o<l?p(o,l-o):void 0;if(f===void 0&&o<l)return!1;const S=d===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:Math.max(0,d-c),g=d>c?p(c,S):void 0;return g===void 0&&d>c?!1:(this.cleanupErrorWrapper(),f!=null&&(s.gutter.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.gutterAST)),s.content.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.contentAST)),u+=f.rowCount),g!=null&&(s.gutter.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.gutterAST)),s.content.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.contentAST)),u+=g.rowCount),this.lastRowCount!==u&&(s.gutter.style.setProperty("grid-row",`span ${u}`),s.content.style.setProperty("grid-row",`span ${u}`),this.lastRowCount=u),!0)}getColumns(e){const t=e.children[0],n=e.children[1];if(!(!(t instanceof HTMLElement)||!(n instanceof HTMLElement)||t.dataset.gutter==null||n.dataset.content==null))return{gutter:t,content:n}}trimDOMToOverlap(e,t,n){const r=this.getDOMBoundaryIndices(e,[t,n]),s=r.get(t)??e.children.length,a=r.get(n)??e.children.length;if(s>a)return!1;for(let o=e.children.length-1;o>=a;o-=1)e.children[o]?.remove();for(let o=s-1;o>=0;o-=1)e.children[o]?.remove();return!0}getDOMBoundaryIndices(e,t){const n=[...new Set(t)].sort((h,d)=>h-d),r=new Map;if(n.length===0)return r;let s=0,a=n[s];const{children:o}=e;a===0&&(r.set(0,0),s+=1,a=n[s]);for(let h=0;h<o.length;h+=1){const d=o[h];if(!(d instanceof HTMLElement))continue;const l=this.getLineIndexFromDOMNode(d);if(l!=null){for(;a!=null&&l>=a;)r.set(a,h),s+=1,a=n[s];if(s>=n.length)break}}for(const h of n)r.has(h)||r.set(h,o.length);return r}getLineIndexFromDOMNode(e){const t=e.dataset.lineIndex;if(t==null)return;const n=Number(t);return Number.isNaN(n)?void 0:n}applyBuffers(e,t){if(t==null||this.shouldDisableVirtualizationBuffers()){this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0);return}t.bufferBefore>0?(this.bufferBefore==null&&(this.bufferBefore=document.createElement("div"),this.bufferBefore.dataset.virtualizerBuffer="before",e.before(this.bufferBefore)),this.bufferBefore.style.setProperty("height",`${t.bufferBefore}px`),this.bufferBefore.style.setProperty("contain","strict")):this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),t.bufferAfter>0?(this.bufferAfter==null&&(this.bufferAfter=document.createElement("div"),this.bufferAfter.dataset.virtualizerBuffer="after",e.after(this.bufferAfter)),this.bufferAfter.style.setProperty("height",`${t.bufferAfter}px`),this.bufferAfter.style.setProperty("contain","strict")):this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0)}shouldDisableVirtualizationBuffers(){return this.options.disableVirtualizationBuffers??!1}applyHeaderToDOM(e,t){const{file:n}=this;if(n==null)return;this.cleanupErrorWrapper(),this.placeHolder?.remove(),this.placeHolder=void 0;const r=this.cachedHeaderHTML??H(e);if(this.cachedHeaderHTML=r,r!==this.lastRenderedHeaderHTML){const d=document.createElement("div");d.innerHTML=r;const l=d.firstElementChild;if(!(l instanceof HTMLElement))return;this.headerElement!=null?t.shadowRoot?.replaceChild(l,this.headerElement):t.shadowRoot?.prepend(l),this.headerElement=l,this.lastRenderedHeaderHTML=r}if(this.isContainerManaged)return;const{renderHeaderPrefix:s,renderHeaderFilenameSuffix:a,renderCustomHeader:o,renderHeaderMetadata:h}=this.options;if(o!=null){const d=o(n)??void 0;this.headerCustom=this.upsertHeaderSlotElement(t,this.headerCustom,Ce,d),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0}else{const d=s?.(n)??void 0,l=a?.(n)??void 0,c=h?.(n)??void 0;this.headerPrefix=this.upsertHeaderSlotElement(t,this.headerPrefix,ke,d),this.headerFilenameSuffix=this.upsertHeaderSlotElement(t,this.headerFilenameSuffix,Ie,l),this.headerMetadata=this.upsertHeaderSlotElement(t,this.headerMetadata,ze,c),this.headerCustom?.remove(),this.headerCustom=void 0}}clearHeaderSlots(){this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0}upsertHeaderSlotElement(e,t,n,r){if(r==null){t?.remove();return}const s=t??this.createHeaderSlotElement(n);return t==null&&e.appendChild(s),this.replaceHeaderSlotContent(s,r),s}replaceHeaderSlotContent(e,t){e.replaceChildren(),t instanceof Element?e.appendChild(t):e.innerText=`${t}`}createHeaderSlotElement(e){const t=document.createElement("div");return t.slot=e,t}getOrCreateFileContainerNode(e,t){const{fileContainer:n}=this,r=e??n??document.createElement("diffs-container"),s=n!==r;return s&&this.emitPostRender(!0),this.fileContainer=r,n!=null&&s&&(this.lastRenderedHeaderHTML=void 0,this.headerElement=void 0),t!=null&&this.fileContainer.parentNode!==t&&t.appendChild(this.fileContainer),s&&this.adoptReusableShellElements(this.fileContainer),this.ensureSpriteSVG(this.fileContainer),this.fileContainer}adoptReusableShellElements(e){const{shadowRoot:t}=e;if(t!=null)for(const n of t.children)n instanceof SVGElement?this.spriteSVG??=n:oe(n)&&n.hasAttribute("data-theme-css")?(this.themeCSSStyle??=n,this.hasAdoptedThemeCSS=!0):oe(n)&&n.hasAttribute("data-unsafe-css")&&(this.unsafeCSSStyle??=n,this.appliedUnsafeCSS??=this.options.unsafeCSS??void 0)}ensureSpriteSVG(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});if(this.spriteSVG==null){const n=document.createElement("div");n.innerHTML=tt;const r=n.firstChild;r instanceof SVGElement&&(this.spriteSVG=r)}this.spriteSVG!=null&&this.spriteSVG.parentNode!==t&&t.appendChild(this.spriteSVG)}getOrCreatePreNode(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});return this.pre==null?(this.pre=document.createElement("pre"),this.appliedPreAttributes=void 0,this.code=void 0,t.appendChild(this.pre)):this.pre.parentNode!==t&&(e.shadowRoot?.appendChild(this.pre),this.appliedPreAttributes=void 0),this.placeHolder?.remove(),this.placeHolder=void 0,this.pre}syncCodeNodeFromPre(e){this.code=void 0;for(const t of Array.from(e.children))if(t instanceof HTMLElement&&t.hasAttribute("data-code")){this.code=t;return}}applyPreNodeAttributes(e,{totalLines:t}){const{overflow:n="scroll",disableLineNumbers:r=!1}=this.options,s={type:"file",split:!1,overflow:n,disableLineNumbers:r,diffIndicators:"none",disableBackground:!0,totalLines:t};it(s,this.appliedPreAttributes)||(nt(e,s),this.appliedPreAttributes=s)}applyErrorToDOM(e,t){this.cleanupErrorWrapper(),this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0;const n=t.shadowRoot??t.attachShadow({mode:"open"});this.errorWrapper??=document.createElement("div"),this.errorWrapper.dataset.errorWrapper="",this.errorWrapper.textContent="",n.appendChild(this.errorWrapper);const r=document.createElement("div");r.dataset.errorMessage="",r.innerText=e.message,this.errorWrapper.appendChild(r);const s=document.createElement("pre");s.dataset.errorStack="",s.innerText=e.stack??"No Error Stack",this.errorWrapper.appendChild(s)}cleanupErrorWrapper(){this.errorWrapper?.remove(),this.errorWrapper=void 0}};function Lt(i,e,t=!1){return!t&&i==null&&e!=null}function At(i,e,t=!1){return i==null&&e!=null&&!t}const Mt=5e3;let Ht=-1;function xt(i,e){return(i.overflow??"scroll")!==(e.overflow??"scroll")||(i.collapsed??!1)!==(e.collapsed??!1)||(i.disableLineNumbers??!1)!==(e.disableLineNumbers??!1)||(i.disableFileHeader??!1)!==(e.disableFileHeader??!1)||i.unsafeCSS!==e.unsafeCSS}var wt=class extends Te{virtualizer;metrics;__id=`virtualized-file:${++Ht}`;top;height=0;cache={heights:new Map,checkpoints:[],fileAnnotationHeight:0};isVisible=!1;isSetup=!1;layoutDirty=!0;forceRenderOverride;currentCollapsed;constructor(i,e,t=Ne,n,r=!1){super(i,n,r),this.virtualizer=e,this.metrics=t}setMetrics(i,e=!1){!e&&rt(this.metrics,i)||(this.metrics=i,this.resetLayoutCache())}setLineAnnotations(i){this.syncLineAnnotations(i)&&this.resetLayoutCache()}syncLineAnnotations(i){return i==null||i===this.lineAnnotations||i.length===0&&this.lineAnnotations.length===0?!1:(super.setLineAnnotations(i),!0)}hasLineAnnotations(){return this.lineAnnotations.some(i=>i.lineNumber>0)}getLineHeight(i,e=!1){const t=this.cache.heights.get(i);if(t!=null)return t;const n=e?2:1;return this.metrics.lineHeight*n}setOptions(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setOptions cannot be used inside CodeView. Update CodeView options instead.");if(i==null)return;const{options:e}=this,t=!ye(e,i),n=xt(e,i);super.setOptions(i),n&&this.resetLayoutCache(!0),t&&(this.forceRenderOverride=!0),t&&this.virtualizer.instanceChanged(this,n)}setThemeType(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setThemeType cannot be used inside CodeView. Update CodeView options instead.");super.setThemeType(i)}resetLayoutCache(i=!1){this.layoutDirty=!0,this.cache.fileAnnotationHeight=0,this.cache.heights.size>0&&this.cache.heights.clear(),this.cache.checkpoints.length>0&&(this.cache.checkpoints.length=0),this.renderRange!=null&&(this.renderRange=void 0),i&&this.isSimpleMode()&&this.computeApproximateSize()}reconcileHeights(){let i=!1;if(this.fileContainer==null||this.file==null)return this.height!==0&&(i=!0),this.height=0,i;const{overflow:e="scroll"}=this.options;if(this.top=this.getVirtualizedTop(),e==="scroll"&&this.lineAnnotations.length===0&&!this.isResizeDebuggingEnabled()||this.code==null)return i;const t=this.code.children[1];if(!(t instanceof HTMLElement))return i;const n=he(this.lineAnnotations);if(this.renderRange!=null&&n&&ve(this.renderRange)){const r=Et(t)??0;r!==this.cache.fileAnnotationHeight&&(this.cache.fileAnnotationHeight=r,i=!0)}else!n&&this.cache.fileAnnotationHeight!==0&&(this.cache.fileAnnotationHeight=0,i=!0);for(const r of t.children){if(!(r instanceof HTMLElement))continue;const s=r.dataset.lineIndex;if(s==null)continue;const a=Number(s);let o=r.getBoundingClientRect().height,h=!1;r.nextElementSibling instanceof HTMLElement&&("lineAnnotation"in r.nextElementSibling.dataset||"noNewline"in r.nextElementSibling.dataset)&&("noNewline"in r.nextElementSibling.dataset&&(h=!0),o+=r.nextElementSibling.getBoundingClientRect().height);const d=this.getLineHeight(a,h);o!==d&&(i=!0,o===this.metrics.lineHeight*(h?2:1)?this.cache.heights.delete(a):this.cache.heights.set(a,o))}return(i||this.isResizeDebuggingEnabled())&&this.computeApproximateSize(!0),i}onRender=i=>this.fileContainer==null||this.file==null?!1:(i&&(this.top=this.getVirtualizedTop()),this.render({file:this.file}));prepareCodeViewItem(i,e,t,n){const r=this.syncLineAnnotations(n);let s=t?.resetFileLayoutCache===!0||r;t?.metrics!=null&&(this.metrics=t.metrics,s=!0);const{collapsed:a=!1}=this.options;return this.currentCollapsed!==a&&(this.currentCollapsed=a,s=!0),s&&this.resetLayoutCache(),this.file!==i&&(this.layoutDirty=!0),this.file=i,this.top=e,this.computeApproximateSize(),this.height}getLinePosition(i){if(this.file==null||i<1)return;const{disableFileHeader:e=!1,collapsed:t=!1}=this.options,n=this.fileRenderer.getLineCount(this.file)-1;let r=B(this.metrics,e);if(t||n<0)return{top:r,height:0};const s=Math.min(Math.max(i-1,0),n),{overflow:a="scroll"}=this.options,{lineHeight:o}=this.metrics;if(r+=this.cache.fileAnnotationHeight,a==="scroll"&&!this.hasLineAnnotations())return{top:r+s*o,height:o};const h=this.getLayoutCheckpointBeforeLineIndex(s);r=h?.top??r;for(let d=h?.lineIndex??0;d<s;d++)r+=this.getLineHeight(d,!1);return{top:r,height:this.getLineHeight(s,!1)}}getNumericScrollAnchor(i){if(this.file==null||this.renderRange==null)return;const{disableFileHeader:e=!1,collapsed:t=!1,overflow:n="scroll"}=this.options;if(t||this.renderRange.totalLines<=0)return;const r=this.fileRenderer.getLineCount(this.file)-1;if(r<0)return;const s=B(this.metrics,e),a=Math.min(this.renderRange.startingLine,r),o=Math.min(a+this.renderRange.totalLines-1,r);if(o<a)return;const{fileAnnotationHeight:h}=this.cache;if(n==="scroll"&&!this.hasLineAnnotations()){const{lineHeight:l}=this.metrics,c=s+(a===0?h:this.renderRange.bufferBefore),u=a+Math.max(Math.ceil((i-c)/l),0);return u>o?void 0:{lineNumber:u+1,top:s+h+u*l}}let d=s+(a===0?h:this.renderRange.bufferBefore);for(let l=a;l<=o;l++){if(d>=i)return{lineNumber:l+1,top:d};d+=this.getLineHeight(l)}}getVirtualizedHeight(){return this.height}getAdvancedStickySpecs(i){if(this.top==null||this.file==null)return;if(this.options.collapsed===!0)return{topOffset:this.top,height:this.height};const e=i!=null?this.computeRenderRangeFromWindow(this.file,this.top,i):this.renderRange;if(e==null)return;const{bufferBefore:t,bufferAfter:n,totalLines:r}=e;let s=0;if(r===0){const a=i??this.virtualizer.getWindowSpecs();this.top<a.top&&(s=n)}return{topOffset:this.top+t+s,height:this.height-(t+n)}}cleanUp(i=!1){this.fileContainer!=null&&this.isSimpleMode()&&this.getSimpleVirtualizer()?.disconnect(this.fileContainer),i||this.resetLayoutCache(),this.isSetup=!1,super.cleanUp(i)}computeApproximateSize(i=!1){const e=this.isResizeDebuggingEnabled();if(!i&&!this.layoutDirty&&!e)return;const t=this.height===0;if(this.height=0,this.cache.checkpoints=[],this.file==null){this.layoutDirty=!1;return}const{disableFileHeader:n=!1,collapsed:r=!1,overflow:s="scroll"}=this.options,{lineHeight:a}=this.metrics,o=this.fileRenderer.getLineCount(this.file),h=B(this.metrics,n),d=fe(this.metrics);if(this.height+=h,r){this.layoutDirty=!1;return}if(this.height+=this.cache.fileAnnotationHeight,s==="scroll"&&!this.hasLineAnnotations())this.height+=o*a;else for(let l=0;l<o;l++)this.addLayoutCheckpoint(l,this.height),this.height+=this.getLineHeight(l,!1);if(o>0&&(this.height+=d),this.fileContainer!=null&&e&&!t){const l=this.fileContainer.getBoundingClientRect();l.height!==this.height?console.log("VirtualizedFile.computeApproximateSize: computed height doesnt match",{name:this.file.name,elementHeight:l.height,computedHeight:this.height}):console.log("VirtualizedFile.computeApproximateSize: computed height IS CORRECT")}this.layoutDirty=!1}setVisibility(i){this.isAdvancedMode()||this.fileContainer==null||(i&&!this.isVisible?(this.top=this.getVirtualizedTop(),this.isVisible=!0):!i&&this.isVisible&&(this.isVisible=!1,this.rerender()))}rerender(){!this.enabled||this.file==null||(this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!1))}applyDocumentChange(i,e,t=!1){const{heights:n,checkpoints:r}=this.cache,s=this.renderRange;if(super.applyDocumentChange(i,e),this.getSimpleVirtualizer()?.markDOMDirty(),this.layoutDirty=!0,n.size>0&&n.clear(),r.length>0&&(r.length=0),this.isSimpleMode()&&this.computeApproximateSize(),t&&s!==void 0&&this.file!==void 0){const a=this.virtualizer.getWindowSpecs(),o=this.computeRenderRangeFromWindow(this.file,this.top??0,a);o.bufferAfter!==s.bufferAfter&&this.updateBuffers(o)}}render({fileContainer:i,file:e,forceRender:t=!1,lineAnnotations:n,...r}){const s=this.file==null||!A(this.file,e),{forceRenderOverride:a,isSetup:o}=this;this.forceRenderOverride=void 0;const h=this.syncLineAnnotations(n);if(h&&this.resetLayoutCache(),this.file=e,i=this.getOrCreateFileContainerNode(i),this.file==null)return console.error("VirtualizedFile.render: attempting to virtually render when we dont have file"),!1;if(o)this.top??=this.getVirtualizedTop(),s&&this.isSimpleMode()&&(this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache(!0));else{this.computeApproximateSize();const u=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(u==null)throw new Error("VirtualizedFile.render: simple virtualizer is not available");u.connect(i,this),this.isVisible=u.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode())return this.renderPlaceholder(this.height);const d=this.virtualizer.getWindowSpecs(),l=this.top??0,c=this.computeRenderRangeFromWindow(this.file,l,d);return super.render({file:this.file,fileContainer:i,renderRange:c,lineAnnotations:n,forceRender:(a??t)||h,...r})}syncVirtualizedTop(){this.top=this.getVirtualizedTop()}shouldDisableVirtualizationBuffers(){return this.isAdvancedMode()||super.shouldDisableVirtualizationBuffers()}isSimpleMode(){return this.virtualizer.type==="simple"}isAdvancedMode(){return this.virtualizer.type==="advanced"}addLayoutCheckpoint(i,e){i%Mt===0&&this.cache.checkpoints.push({lineIndex:i,top:e})}getLayoutCheckpointBeforeLineIndex(i){if(i<=0||this.cache.checkpoints.length===0)return;let e=0,t=this.cache.checkpoints.length-1,n;for(;e<=t;){const r=e+t>>1,s=this.cache.checkpoints[r];if(s==null)throw new Error("VirtualizedFile: invalid checkpoint index");s.lineIndex<=i?(n=s,e=r+1):t=r-1}return n}getLayoutCheckpointBeforeTop(i,e){let t=0,n=this.cache.checkpoints.length-1,r=-1;for(;t<=n;){const s=t+n>>1,a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");a.top<=i?(r=s,t=s+1):n=s-1}if(e==null)return r>=0?this.cache.checkpoints[r]:void 0;for(let s=r;s>=0;s--){const a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");if(a.lineIndex%e===0)return a}}getVirtualizedTop(){return this.virtualizer.type==="advanced"?this.virtualizer.getLocalTopForInstance(this):this.fileContainer!=null?this.virtualizer.getOffsetInScrollContainer(this.fileContainer):0}getSimpleVirtualizer(){return this.virtualizer.type==="simple"?this.virtualizer:void 0}isResizeDebuggingEnabled(){return this.getSimpleVirtualizer()?.config.resizeDebugging??!1}computeRenderRangeFromWindow(i,e,{top:t,bottom:n}){const{disableFileHeader:r=!1,overflow:s="scroll"}=this.options,{hunkLineCount:a,lineHeight:o}=this.metrics,h=this.fileRenderer.getLineCount(i),d=this.height,l=B(this.metrics,r),c=h>0?fe(this.metrics):0,{fileAnnotationHeight:u}=this.cache,p=l+u,f=Math.max(0,d-l-u-c),S=he(this.lineAnnotations),g=e+l,y=u>0&&S&&g<n&&g+u>t;if(e<t-d||e>n)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};if(h<=a)return{startingLine:0,totalLines:a,bufferBefore:0,bufferAfter:0};const m=Math.ceil(Math.max(n-t,0)/o),v=Math.ceil(m/a)*a+a*2,z=v/a,D=(t+n)/2;if(s==="scroll"&&!this.hasLineAnnotations()){const R=e+p,P=R+f;if(!y&&!(R<n&&P>t))return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};const w=Math.floor(y&&D<e+p?0:(D-(e+p))/o),b=Math.floor(w/a)-Math.floor(z/2),xe=Math.ceil(h/a),E=Math.max(0,Math.min(b,xe))*a,Z=b<0?v+b*a:v,we=E===0?0:u+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,O,V,x;const Re=U?.lineIndex??0;for(let R=Re;R<h;R++){const P=_%a===0,w=Math.floor(_/a);if(P&&(N[w]=T-(e+p),x!=null)){if(x<=0)break;x--}const b=this.getLineHeight(R,!1);T>t-b&&T<n&&(O??=w),T+b>D&&(V??=w),x==null&&T>=n&&P&&(x=be),_++,T+=b}if(O==null)if(y)O=0,V=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:d-l-c};V??=O;const W=Math.round(V-z/2),Le=Math.max(0,Math.ceil(h/a)-z),G=Math.max(0,Math.min(W,Le)),Y=G*a,J=W<0?v+W*a:v,Ae=N[G]??0,Me=Y===0?0:u+Ae,X=G+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 Et(i){let e;for(const t of i.children)t instanceof HTMLElement&&t.dataset.lineAnnotation===st&&(e=Math.max(e??0,t.getBoundingClientRect().height));return e}function Ft({file:i,renderCustomHeader:e,renderHeaderPrefix:t,renderHeaderFilenameSuffix:n,renderHeaderMetadata:r,renderAnnotation:s,lineAnnotations:a,renderGutterUtility:o,getHoveredLine:h}){const d=e?.(i),l=t?.(i),c=n?.(i),u=r?.(i);return C.jsxs(C.Fragment,{children:[d!=null?C.jsx("div",{slot:Ce,children:d}):C.jsxs(C.Fragment,{children:[l!=null&&C.jsx("div",{slot:"header-prefix",children:l}),c!=null&&C.jsx("div",{slot:"header-filename-suffix",children:c}),u!=null&&C.jsx("div",{slot:"header-metadata",children:u})]}),s!=null&&a?.map((p,f)=>C.jsx("div",{slot:I(p),children:s(p)},f)),o!=null&&C.jsx("div",{slot:"gutter-utility-slot",style:at,children:o(h)})]})}const me=typeof window>"u"?k.useEffect:k.useLayoutEffect;function kt({file:i,options:e,lineAnnotations:t,selectedLines:n,prerenderedHTML:r,metrics:s,hasGutterRenderUtility:a,hasCustomHeader:o,disableWorkerPool:h,contentEditable:d}){const l=ot(),c=n!==void 0,u=k.useContext(ht),p=lt(),f=k.useRef(null),S=dt(g=>{if(g!=null){if(f.current!=null)throw new Error("File: An instance should not already exist when a node is created");l!=null?f.current=new wt(q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),l,s,h?void 0:u,!0):f.current=new Te(q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),h?void 0:u,!0),f.current.hydrate({file:i,fileContainer:g,lineAnnotations:t,prerenderedHTML:r})}else{if(f.current==null)throw new Error("File: A File instance should exist when unmounting");f.current.cleanUp(),f.current=null}});return me(()=>{if(f.current==null)return;const g=q({controlledSelection:c,contentEditable:d,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),y=!ye(f.current.options,g);f.current.setOptions(g),f.current.render({file:i,lineAnnotations:t,forceRender:y}),n!==void 0&&f.current.setSelectedLines(n)}),me(()=>{if(d&&f.current!=null){if(p===void 0)throw new Error("File: Editor is not attached");return p.edit(f.current)}},[d,p]),{ref:S,getHoveredLine:k.useCallback(()=>f.current?.getHoveredLine(),[])}}function q({options:i,controlledSelection:e,contentEditable:t,hasCustomHeader:n,hasEditor:r,hasGutterRenderUtility:s}){const a=t&&r,o=e||s||n;if(!o&&!a)return i;let h={...i};return o&&(h={...h,controlledSelection:e,renderCustomHeader:n?le:i?.renderCustomHeader,renderGutterUtility:s?le:i?.renderGutterUtility}),a&&(h={...h,useTokenTransformer:!0,enableGutterUtility:!1,enableLineSelection:!1,lineHoverHighlight:"disabled"}),h}function Ut({file:i,lineAnnotations:e,selectedLines:t,options:n,metrics:r,className:s,style:a,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:d,renderHeaderFilenameSuffix:l,renderHeaderMetadata:c,prerenderedHTML:u,renderGutterUtility:p,disableWorkerPool:f=!1,contentEditable:S=!1}){const{ref:g,getHoveredLine:y}=kt({file:i,options:n,metrics:r,lineAnnotations:e,selectedLines:t,prerenderedHTML:u,hasGutterRenderUtility:p!=null,hasCustomHeader:h!=null,disableWorkerPool:f,contentEditable:S});return C.jsx(Oe,{ref:g,className:s,style:a,children:ct(Ft({file:i,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:d,renderHeaderFilenameSuffix:l,renderHeaderMetadata:c,renderGutterUtility:p,lineAnnotations:e,getHoveredLine:y}),u)})}const _t=L.memo(function({jsonString:e,className:t,maxHeight:n="100%",initiallyExpandedDepth:r=2}){const s=L.useRef(null),[a,o]=L.useState(null),h=L.useMemo(()=>{try{const c=e.trim();if(!c)return o("Empty JSON content"),null;const u=JSON.parse(c);return o(null),u}catch(c){return o(c instanceof Error?c.message:"Invalid JSON"),null}},[e]),d=L.useCallback(()=>{s.current?.expandAll()},[]),l=L.useCallback(()=>{s.current?.collapseAll()},[]);return a?C.jsx("div",{className:t,children:C.jsxs("div",{className:"rounded-md border border-[var(--interactive-border)] bg-[var(--syntax-base-background)] p-4",children:[C.jsx("div",{className:"mb-1 font-medium text-[var(--surface-foreground)]",children:"Invalid JSON"}),C.jsx("div",{className:"font-mono text-xs text-[var(--surface-mutedForeground)]",children:a})]})}):h===null?null:C.jsxs("div",{className:t,children:[C.jsxs("div",{className:"flex items-center gap-1 border-b border-[var(--interactive-border)] px-2 py-1",children:[C.jsxs(ee,{variant:"ghost",size:"xs",onClick:d,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-down-s",className:"h-3 w-3"}),"Expand All"]}),C.jsxs(ee,{variant:"ghost",size:"xs",onClick:l,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-up-s",className:"h-3 w-3"}),"Collapse All"]})]}),C.jsx("div",{className:"bg-[var(--syntax-base-background)] py-1",style:{maxHeight:n,overflow:"auto"},children:C.jsx(Ve,{ref:s,data:h,maxHeight:n,initiallyExpandedDepth:r})})]})});export{Ut as F,_t as J};