zidane-gui 9.3.1 → 9.4.0

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 (99) hide show
  1. package/out/main/chunks/{remote-hosts-B8_tzg_n.js → remote-hosts-CSiGJAfm.js} +1 -1
  2. package/out/main/chunks/{session-search-sql-2EUzjHAT.js → session-search-sql-D51BmAO2.js} +5 -5
  3. package/out/main/index.js +4397 -4086
  4. package/out/main/session-search-worker.js +1 -1
  5. package/out/preload/index.mjs +36 -2
  6. package/out/renderer/assets/{24BXRY42-eTlQfl4v.js → 24BXRY42-0UXaaWjY.js} +1 -1
  7. package/out/renderer/assets/{4FHPYW2L-BHx1bBmw.js → 4FHPYW2L-BWpHahlW.js} +1 -1
  8. package/out/renderer/assets/{4LWW3ZNH-D7lTurDT.js → 4LWW3ZNH-CPyJ9o9Y.js} +1 -1
  9. package/out/renderer/assets/{5XYWFMKW-e04QMbw9.js → 5XYWFMKW-ZZpHHfGa.js} +1 -1
  10. package/out/renderer/assets/{64PMEAB3-DTIFpDpU.js → 64PMEAB3-DOEnEuzl.js} +1 -1
  11. package/out/renderer/assets/{6BEWHPQE-BrYtHcZG.js → 6BEWHPQE-C2ZZckdj.js} +1 -1
  12. package/out/renderer/assets/{6PIGVMFT-CoAPPYTl.js → 6PIGVMFT-CRGq6eh3.js} +1 -1
  13. package/out/renderer/assets/{75JW6PN6-JbXPfJg4.js → 75JW6PN6-CYzAa9yx.js} +1 -1
  14. package/out/renderer/assets/{7XWI72E6-CFY3Kecs.js → 7XWI72E6-C_GZbyIF.js} +1 -1
  15. package/out/renderer/assets/{BGW36YJW-DhmSG9tb.js → BGW36YJW-BAwgTZ_z.js} +1 -1
  16. package/out/renderer/assets/{CGIZI67J-Cr9B0EmW.js → CGIZI67J-BxXITbQC.js} +1 -1
  17. package/out/renderer/assets/{CodeEditor-C6EJBlGG.js → CodeEditor-CLsAw7eu.js} +2 -2
  18. package/out/renderer/assets/{ComposerEditor-oFIdMkLB.js → ComposerEditor-BqnIn2NQ.js} +1 -1
  19. package/out/renderer/assets/{DNNCRC2E-CMqlK0W6.js → DNNCRC2E-kbsNJgPT.js} +1 -1
  20. package/out/renderer/assets/DiffsTab--BHt7StP.js +3 -0
  21. package/out/renderer/assets/{E67EBMDD-C_T2QnwF.js → E67EBMDD-BOeJkFNZ.js} +1 -1
  22. package/out/renderer/assets/{EFYWJBJK-Cbn-VZcb.js → EFYWJBJK-CFT5CQUG.js} +1 -1
  23. package/out/renderer/assets/{EXE5EH6O-SXdUe5We.js → EXE5EH6O-Cbj5xPKl.js} +1 -1
  24. package/out/renderer/assets/{EditorWorkers-bVeEZI8X.js → EditorWorkers-CXBU_HFf.js} +1 -1
  25. package/out/renderer/assets/{FilesTab-DtM2Q5R0.js → FilesTab-CZHD0eBx.js} +4 -4
  26. package/out/renderer/assets/{G6GPDDNC-XfFyRa0j.js → G6GPDDNC-Ax6dML4i.js} +1 -1
  27. package/out/renderer/assets/{G76NGGFM-Bj_m2WLJ.js → G76NGGFM-BxPXXNt_.js} +1 -1
  28. package/out/renderer/assets/{GH6G3TJC-wPRy41Zv.js → GH6G3TJC-CiCXY2r6.js} +1 -1
  29. package/out/renderer/assets/{HPNUA7RO-BhLNmX-t.js → HPNUA7RO-DiyW9VGu.js} +1 -1
  30. package/out/renderer/assets/{HQRGC5D7-dvTAT1Uv.js → HQRGC5D7-ArfvIYAC.js} +1 -1
  31. package/out/renderer/assets/{IX6Z2TVR-CzV_umYo.js → IX6Z2TVR-Df9chdw8.js} +1 -1
  32. package/out/renderer/assets/IconButtonTip-D0dQOfg6.js +1 -0
  33. package/out/renderer/assets/{J77NQRCJ-DTwwq3Ci.js → J77NQRCJ-DOWauTsf.js} +1 -1
  34. package/out/renderer/assets/{JAD36DTZ-DArKsMUT.js → JAD36DTZ-CJDdMCD5.js} +1 -1
  35. package/out/renderer/assets/{LF3NJQAX-DjYdE7YV.js → LF3NJQAX-B89ZqOpY.js} +1 -1
  36. package/out/renderer/assets/{LRZCOFJZ-C7m8fw-0.js → LRZCOFJZ-BBX_wZ5T.js} +1 -1
  37. package/out/renderer/assets/{N5NF2FGY-CqGhgjNF.js → N5NF2FGY-BoIFu-8L.js} +1 -1
  38. package/out/renderer/assets/{N7OWWQHY-BRk68LVa.js → N7OWWQHY-CloOgGu1.js} +1 -1
  39. package/out/renderer/assets/{NT5JY5WP-B1NtxJ-K.js → NT5JY5WP-BhjzefjG.js} +1 -1
  40. package/out/renderer/assets/{OT7W3RNY-CtDQ--Ld.js → OT7W3RNY-BRzBqtKB.js} +1 -1
  41. package/out/renderer/assets/{P67P66DB-LeAz_z3Z.js → P67P66DB-Dw-K1Ghu.js} +1 -1
  42. package/out/renderer/assets/{PFLLLM7K-CgODCVD8.js → PFLLLM7K-DfSPUrIT.js} +1 -1
  43. package/out/renderer/assets/{PUAMC4MJ-9REX_vGK.js → PUAMC4MJ-BnY1F2cF.js} +1 -1
  44. package/out/renderer/assets/{PVFCHRLY-CK5jTRjy.js → PVFCHRLY-BcyVPS3n.js} +1 -1
  45. package/out/renderer/assets/{PinnedSavedView-Dtdra7Gq.js → PinnedSavedView-ciRhY0cN.js} +1 -1
  46. package/out/renderer/assets/{QQW2P742-B2snHr_6.js → QQW2P742-D6aitZ24.js} +1 -1
  47. package/out/renderer/assets/{S63OEDPG-BeWWF1tc.js → S63OEDPG-Dlz1a9cD.js} +1 -1
  48. package/out/renderer/assets/{SG5TVYLW-ClCsbQ87.js → SG5TVYLW-Bu7LZZpx.js} +1 -1
  49. package/out/renderer/assets/{SavedViewArtifact-ATjDgAUF.js → SavedViewArtifact-CM9L4mc8.js} +1 -1
  50. package/out/renderer/assets/{SidebarPreviewPane-DHllX0GN.js → SidebarPreviewPane-DkOCt7Gb.js} +1 -1
  51. package/out/renderer/assets/{TranscriptViews-DD_JshFH.js → TranscriptViews-aYvP71ow.js} +1 -1
  52. package/out/renderer/assets/{UGRSUGA2-jP6nv8HL.js → UGRSUGA2-avwOtJG1.js} +1 -1
  53. package/out/renderer/assets/{V44WA6U7-Dr_tS3uH.js → V44WA6U7-DMF87Y7j.js} +1 -1
  54. package/out/renderer/assets/{V67O4WWV-BRn52u9c.js → V67O4WWV-BsDLuBDb.js} +1 -1
  55. package/out/renderer/assets/{VBUCM3YD-0sLtn_Zp.js → VBUCM3YD-C6FrRswP.js} +1 -1
  56. package/out/renderer/assets/{VINGRCPA-n98Gf7V0.js → VINGRCPA-Do3Pv3Tc.js} +1 -1
  57. package/out/renderer/assets/{ViewBlock-DdcTHRu3.js → ViewBlock-B-ppjb34.js} +3 -3
  58. package/out/renderer/assets/{ViewCharts-BAw6tExV.js → ViewCharts-jvS22ppO.js} +2 -2
  59. package/out/renderer/assets/{ViewCustom-BzwMbjqg.js → ViewCustom-yFkoy6a-.js} +1 -1
  60. package/out/renderer/assets/{ViewExtension-Ch5_33Ra.js → ViewExtension-DuHxho6W.js} +1 -1
  61. package/out/renderer/assets/{ViewInputs-BHooAs2f.js → ViewInputs-VAMDh56H.js} +1 -1
  62. package/out/renderer/assets/{ViewMcpApp-CJnOESMk.js → ViewMcpApp-CH_W9CZt.js} +1 -1
  63. package/out/renderer/assets/{ViewSessionAction-BHJv5QNb.js → ViewSessionAction-66veqRhO.js} +1 -1
  64. package/out/renderer/assets/{ViewTables-DBTupg46.js → ViewTables-CKKDcYKH.js} +1 -1
  65. package/out/renderer/assets/{WL6DNKX4-Csfp__Nw.js → WL6DNKX4-Cq-YK4Uf.js} +1 -1
  66. package/out/renderer/assets/{WQ63CJYP-oSbguA5n.js → WQ63CJYP-fjrhTSVs.js} +1 -1
  67. package/out/renderer/assets/{XOYAOB3S-DfDDKmX8.js → XOYAOB3S-CAQPI0he.js} +1 -1
  68. package/out/renderer/assets/{Y5LQLG3M-BnZ8APdi.js → Y5LQLG3M-DKntYAaW.js} +1 -1
  69. package/out/renderer/assets/{YIK6JTN6-Bunk5CDx.js → YIK6JTN6-CcjcC5JX.js} +1 -1
  70. package/out/renderer/assets/{core-BbPUgmX7.js → core-Cj89wpQh.js} +4 -4
  71. package/out/renderer/assets/{file-tabs-CFdJBYJ9.js → file-tabs-PoAgFa7v.js} +1 -1
  72. package/out/renderer/assets/{ghostty-web-Dn7o-dzQ.js → ghostty-web-DiMuvUtH.js} +1 -1
  73. package/out/renderer/assets/{highlights-eTGcn9lP.js → highlights-7WH0ppQl.js} +1 -1
  74. package/out/renderer/assets/{highlights-D4Jo_Sz0.js → highlights-DnSmFBdQ.js} +1 -1
  75. package/out/renderer/assets/index-CiuUSFeC.js +11 -0
  76. package/out/renderer/assets/kit-CD3F-f6F.js +147 -0
  77. package/out/renderer/assets/{langs-CXhlGiW6.js → langs-D5CRC9qz.js} +1 -1
  78. package/out/renderer/assets/{lazy-D3tN-GAO.js → lazy-CUmWiDAP.js} +3 -3
  79. package/out/renderer/assets/{loader-DGyfh0zB.js → loader-CPY9efuc.js} +1 -1
  80. package/out/renderer/assets/{pierre-theme-BZvsTYqQ.js → pierre-theme-BrzM0xZU.js} +3 -3
  81. package/out/renderer/assets/setting-demos-BW7cG2_G.css +1 -0
  82. package/out/renderer/assets/setting-demos-DEURBrvf.js +1 -0
  83. package/out/renderer/assets/{shiki-Wqv4XEGM.js → shiki-DFrbO9j3.js} +1 -1
  84. package/out/renderer/assets/{sidebar-layout-sK8ujsHX.js → sidebar-layout-fobokay5.js} +1 -1
  85. package/out/renderer/assets/{stream-tokenizer-C18hljKL.js → stream-tokenizer-CT1HAjvR.js} +1 -1
  86. package/out/renderer/assets/{themes-Dfx1_kFe.js → themes-Cj62ov9J.js} +1 -1
  87. package/out/renderer/assets/{useFind-BBxfQuQ2.js → useFind-Cdl0rVJO.js} +3 -3
  88. package/out/renderer/assets/{useFolderChanges-BcfSJoBT.js → useFolderChanges-C9L_NOgw.js} +2 -2
  89. package/out/renderer/assets/{view-preview-B2Rj--lZ.js → view-preview-BvCO9WZH.js} +1 -1
  90. package/out/renderer/assets/{zoom-reset-l-YVDJrI.js → zoom-reset-COqHFP45.js} +1 -1
  91. package/out/renderer/index.html +5 -5
  92. package/out/renderer/view-preview.html +6 -6
  93. package/package.json +2 -2
  94. package/out/renderer/assets/DiffsTab-D690H0Dy.js +0 -3
  95. package/out/renderer/assets/IconButtonTip-P9QUxPjA.js +0 -1
  96. package/out/renderer/assets/index-c95EBMdk.js +0 -8
  97. package/out/renderer/assets/kit-C9O_D5xC.js +0 -147
  98. package/out/renderer/assets/setting-demos-B0787McX.js +0 -1
  99. package/out/renderer/assets/setting-demos-vtrBsYTd.css +0 -1
@@ -1,4 +1,4 @@
1
- import{j as jsxRuntimeExports,r as reactExports}from"./vendor-react-CxJ4vs-5.js";import{a8 as SPLIT_WITH_NEWLINES,a9 as getHunkSideStartBoundary,aa as getHunkSideEndBoundary,ab as COMMIT_METADATA_SPLIT,ac as GIT_DIFF_FILE_BREAK_REGEX,ad as FILENAME_HEADER_REGEX,ae as INDEX_LINE_METADATA,af as cleanLastNewline,ag as Diff,G as createHastElement,ah as createTextNodeElement,ai as createIconElement,aj as hasTrailingContextMismatch,ak as getExpandedRegion,al as getTrailingExpandedRegion,D as DEFAULT_THEMES,am as areDiffTargetsEqual,an as areDiffRenderOptionsEqual,ao as isDiffPlainText,O as isHandledWorkerPoolError,ap as DEFAULT_EXPANDED_REGION,a7 as DEFAULT_TOKENIZE_MAX_LENGTH,I as getSharedHighlighter,v as getHighlighterIfLoaded,H as HighlighterDisposedError,y as DEFAULT_RENDER_RANGE,z as areThemesAttached,B as areLanguagesAttached,aq as renderDiffWithHighlighter,ar as iterateOverDiff,as as getTrailingContextRangeSize,E as createGutterGap,J as createGutterWrapper,F as createGutterItem,w as getFiletypeFromFileName,K as EMPTY_LINE_ANNOTATIONS,L as areThemesEqual,N as EMPTY_RENDER_RANGE,M as getThemes,at as isAdditionLineRenderable,au as getNearestRenderableAdditionLine,av as getHunkAdditionLineRange,Q as CUSTOM_HEADER_SLOT_ID,S as HEADER_PREFIX_SLOT_ID,T as HEADER_FILENAME_SUFFIX_SLOT_ID,U as HEADER_METADATA_SLOT_ID,aw as areFilesEqual,Z as getVirtualFileHeaderRegion,ax as getLeadingHunkSeparatorLayout,ay as getTrailingHunkSeparatorLayout,_ as getVirtualFilePaddingBottom,X as computeVirtualFileMetrics,Y as getVirtualFileHeaderHeight,a2 as WorkerPoolContext,a3 as DIFFS_TAG_NAME,a6 as VIRTUALIZER_CONFIG,a4 as DIFFS_UNSAFE_CSS,P as PREFERRED_HIGHLIGHTER,a5 as DIFFS_HOST_STYLE}from"./pierre-theme-BZvsTYqQ.js";import{ab as cloneFileDiffMetadata,g as getLineAnnotationName,b as applyLineTextWithNewline,h as createAnnotationElement,l as getHighlighterOptions,r as resolvePreferredHighlighter,c as areRenderRangesEqual,i as isDefaultRenderRange,m as createPreElement,k as createContentColumn,e as shouldRenderFileAnnotations,f as getFileAnnotations,j as createFileHeaderElement,n as shouldUseTokenTransformer,R as ResizeManager,I as InteractionManager,p as pluckInteractionOptions,o as resolveEditSessionSlotName,w as writeEditSessionAnnotations,W as dequeueRender,t as prerenderHTMLIfNecessary,q as adoptEditSessionAnnotations,V as cloneHunks,X as queueRender,v as createAnnotationWrapperNode,x as createGutterUtilityContentNode,J as isStyleNode,S as SVGSpriteSheet,y as createUnsafeCSSStyleNode,z as wrapUnsafeCSS,A as getMeasuredScrollbarGutter,B as upsertHostThemeStyle,C as wrapThemeCSS,D as patchScrollbarGutterSize,E as isSafari,H as guardWebKitScrollDuringRebuild,G as getOrCreateCodeNode,K as arePrePropertiesEqual,L as setPreNodeProperties,M as areObjectsEqual,O as includesFileAnnotations,N as areOptionsEqual,P as FILE_ANNOTATION_DOM_KEY,ac as MergeConflictSlotStyles,Z as GutterUtilitySlotStyles,_ as useVirtualizer,$ as useCreateEditor,a0 as useStableCallback,a1 as useForceUpdate,a2 as useNextRenderData,a3 as noopRender,a as areFileTargetsEqual,a4 as templateRender,a9 as Virtualizer,a5 as useDetachCleanup,a6 as revealOnHighlight,a7 as scrollReachOnRender}from"./useFind-BBxfQuQ2.js";import{h as hastToHtml}from"./hastToHtml-C4ea9WpN.js";import{aw as useFilesLabels,br as KeyHint,bs as languageFor,n as RowActionsMenu,bt as rangeLabel,bu as serializeCodeSnippet,bv as attachmentName,bw as serializeReviewComment,ap as useEditorEnvironment,bx as excerptFor,by as MediaNav,bz as ZoomableImage,bA as useEditorPrefs,av as useFilesHost,bB as Tooltip,I as IconButton,bl as useNearViewport,ax as filesRootOf}from"./kit-C9O_D5xC.js";import{F as FileIcon,T as TreeChevron}from"./FileIcon-DECOEMOz.js";const CACHE_KEY_VERSION=1;function composeCacheKey(scope,...segments){return`ck${CACHE_KEY_VERSION}:${JSON.stringify([scope,...segments])}`}function splitFileContents$1(contents){return contents!==""?contents.split(SPLIT_WITH_NEWLINES):[]}function hydratePartialDiff(type,fileDiff,files,parseDiffOptions={}){const targetFileDiff=type==="clone"?cloneFileDiffMetadata(fileDiff):fileDiff;if(!targetFileDiff.isPartial)throw new Error("hydratePartialDiff: fileDiff must be partial");switch(targetFileDiff.type){case"change":case"rename-changed":return hydrateTwoSidedFileDiff(targetFileDiff,requireOldFile(targetFileDiff,files),requireNewFile(targetFileDiff,files),parseDiffOptions);case"rename-pure":{const newFile=requireNewFile(targetFileDiff,files);requireMissingOldFile(targetFileDiff,files);const lines=splitFileContents$1(newFile.contents);return targetFileDiff.isPartial=!1,targetFileDiff.deletionLines=lines,targetFileDiff.additionLines=lines,targetFileDiff.deletionCharacterCount=newFile.contents.length,targetFileDiff.additionCharacterCount=newFile.contents.length,setHydratedCacheKey(targetFileDiff,null,newFile,parseDiffOptions),targetFileDiff}}throw new Error(`hydratePartialDiff: ${targetFileDiff.type} diffs cannot be hydrated from loaded files`)}function hydrateTwoSidedFileDiff(fileDiff,oldFile,newFile,parseDiffOptions){const deletionLines=splitFileContents$1(oldFile.contents),additionLines=splitFileContents$1(newFile.contents),{hunks,splitLineCount,unifiedLineCount}=hydrateHunks(fileDiff.hunks,additionLines.length);return fileDiff.hunks=hunks,fileDiff.splitLineCount=splitLineCount,fileDiff.unifiedLineCount=unifiedLineCount,fileDiff.isPartial=!1,fileDiff.deletionLines=deletionLines,fileDiff.additionLines=additionLines,fileDiff.deletionCharacterCount=oldFile.contents.length,fileDiff.additionCharacterCount=newFile.contents.length,setHydratedCacheKey(fileDiff,oldFile,newFile,parseDiffOptions),fileDiff}function hydrateHunks(hunks,totalAdditionLines){let splitLineCount=0,unifiedLineCount=0,lastHunkAdditionEnd=0;const hydratedHunks=[];for(const hunk of hunks){const additionLineIndex=Math.max(hunk.additionStart-1,0),deletionLineIndex=Math.max(hunk.deletionStart-1,0);let contentAdditionLineIndex=additionLineIndex,contentDeletionLineIndex=deletionLineIndex,hunkAdditionLines=0,hunkDeletionLines=0,hunkSplitLineCount=0,hunkUnifiedLineCount=0;const hunkContent=[];for(const content of hunk.hunkContent){if(content.type==="context"){hunkContent.push({...content,additionLineIndex:contentAdditionLineIndex,deletionLineIndex:contentDeletionLineIndex}),contentAdditionLineIndex+=content.lines,contentDeletionLineIndex+=content.lines,hunkSplitLineCount+=content.lines,hunkUnifiedLineCount+=content.lines;continue}hunkContent.push({...content,additionLineIndex:contentAdditionLineIndex,deletionLineIndex:contentDeletionLineIndex}),contentAdditionLineIndex+=content.additions,contentDeletionLineIndex+=content.deletions,hunkAdditionLines+=content.additions,hunkDeletionLines+=content.deletions,hunkSplitLineCount+=Math.max(content.additions,content.deletions),hunkUnifiedLineCount+=content.additions+content.deletions}const collapsedBefore=Math.max(getHunkSideStartBoundary(hunk.additionStart,hunk.additionCount)-lastHunkAdditionEnd,0);hydratedHunks.push({...hunk,collapsedBefore,additionLineIndex,deletionLineIndex,additionLines:hunkAdditionLines,deletionLines:hunkDeletionLines,hunkContent,splitLineStart:splitLineCount+collapsedBefore,unifiedLineStart:unifiedLineCount+collapsedBefore,splitLineCount:hunkSplitLineCount,unifiedLineCount:hunkUnifiedLineCount}),splitLineCount+=collapsedBefore+hunkSplitLineCount,unifiedLineCount+=collapsedBefore+hunkUnifiedLineCount,lastHunkAdditionEnd=getHunkSideEndBoundary(hunk.additionStart,hunk.additionCount)}if(hydratedHunks.length>0){const lastHunk=hydratedHunks[hydratedHunks.length-1],lastHunkEnd=getHunkSideEndBoundary(lastHunk.additionStart,lastHunk.additionCount),collapsedAfter=Math.max(totalAdditionLines-lastHunkEnd,0);splitLineCount+=collapsedAfter,unifiedLineCount+=collapsedAfter}return{hunks:hydratedHunks,splitLineCount,unifiedLineCount}}function requireOldFile(fileDiff,files){if(files.oldFile==null)throw new Error(`hydratePartialDiff: ${fileDiff.type} diff for ${fileDiff.name} requires oldFile`);return files.oldFile}function requireNewFile(fileDiff,files){if(files.newFile==null)throw new Error(`hydratePartialDiff: ${fileDiff.type} diff for ${fileDiff.name} requires newFile`);return files.newFile}function requireMissingOldFile(fileDiff,files){if(files.oldFile!==null)throw new Error(`hydratePartialDiff: ${fileDiff.type} diff for ${fileDiff.name} requires oldFile to be null`)}function getHydratedCacheKey(fileDiff,oldFile,newFile,parseDiffOptions){return fileDiff.cacheKey!=null?`${fileDiff.cacheKey}:hydrated`:getLoadedFileCacheKey(oldFile,newFile,parseDiffOptions)}function setHydratedCacheKey(fileDiff,oldFile,newFile,parseDiffOptions){const cacheKey=getHydratedCacheKey(fileDiff,oldFile,newFile,parseDiffOptions);if(cacheKey==null){delete fileDiff.cacheKey;return}fileDiff.cacheKey=cacheKey}function getLoadedFileCacheKey(oldFile,newFile,parseDiffOptions){return oldFile!=null&&newFile!=null?oldFile.cacheKey!=null&&newFile.cacheKey!=null?composeCacheKey(parseDiffOptions.disableLineMatching===!0?"hydrated-files-raw":"hydrated-files",oldFile.cacheKey,newFile.cacheKey):void 0:oldFile?.cacheKey??newFile?.cacheKey}const stringDetachEncoder=new TextEncoder,stringDetachDecoder=new TextDecoder("utf-8",{ignoreBOM:!0}),SURROGATE_CODE_UNIT_PATTERN=/[\uD800-\uDFFF]/,STRING_DETACH_INITIAL_BUFFER_SIZE=1024;let stringDetachBuffer=new Uint8Array(STRING_DETACH_INITIAL_BUFFER_SIZE);function releaseStringDetachBuffer(){stringDetachBuffer.length!==STRING_DETACH_INITIAL_BUFFER_SIZE&&(stringDetachBuffer=new Uint8Array(STRING_DETACH_INITIAL_BUFFER_SIZE))}function detachString(value){if(value.length===0)return value;if(SURROGATE_CODE_UNIT_PATTERN.test(value))return JSON.parse(JSON.stringify(value));const requiredByteLength=value.length*3;stringDetachBuffer.length<requiredByteLength&&(stringDetachBuffer=new Uint8Array(requiredByteLength));const{written}=stringDetachEncoder.encodeInto(value,stringDetachBuffer);return stringDetachDecoder.decode(stringDetachBuffer.subarray(0,written))}const filenameDecoder=new TextDecoder("utf-8",{ignoreBOM:!0}),NAMED_ESCAPES={'"':'"',"\\":"\\",a:"\x07",b:"\b",t:" ",n:`
1
+ import{j as jsxRuntimeExports,r as reactExports}from"./vendor-react-CxJ4vs-5.js";import{a8 as SPLIT_WITH_NEWLINES,a9 as getHunkSideStartBoundary,aa as getHunkSideEndBoundary,ab as COMMIT_METADATA_SPLIT,ac as GIT_DIFF_FILE_BREAK_REGEX,ad as FILENAME_HEADER_REGEX,ae as INDEX_LINE_METADATA,af as cleanLastNewline,ag as Diff,G as createHastElement,ah as createTextNodeElement,ai as createIconElement,aj as hasTrailingContextMismatch,ak as getExpandedRegion,al as getTrailingExpandedRegion,D as DEFAULT_THEMES,am as areDiffTargetsEqual,an as areDiffRenderOptionsEqual,ao as isDiffPlainText,O as isHandledWorkerPoolError,ap as DEFAULT_EXPANDED_REGION,a7 as DEFAULT_TOKENIZE_MAX_LENGTH,I as getSharedHighlighter,v as getHighlighterIfLoaded,H as HighlighterDisposedError,y as DEFAULT_RENDER_RANGE,z as areThemesAttached,B as areLanguagesAttached,aq as renderDiffWithHighlighter,ar as iterateOverDiff,as as getTrailingContextRangeSize,E as createGutterGap,J as createGutterWrapper,F as createGutterItem,w as getFiletypeFromFileName,K as EMPTY_LINE_ANNOTATIONS,L as areThemesEqual,N as EMPTY_RENDER_RANGE,M as getThemes,at as isAdditionLineRenderable,au as getNearestRenderableAdditionLine,av as getHunkAdditionLineRange,Q as CUSTOM_HEADER_SLOT_ID,S as HEADER_PREFIX_SLOT_ID,T as HEADER_FILENAME_SUFFIX_SLOT_ID,U as HEADER_METADATA_SLOT_ID,aw as areFilesEqual,Z as getVirtualFileHeaderRegion,ax as getLeadingHunkSeparatorLayout,ay as getTrailingHunkSeparatorLayout,_ as getVirtualFilePaddingBottom,X as computeVirtualFileMetrics,Y as getVirtualFileHeaderHeight,a2 as WorkerPoolContext,a3 as DIFFS_TAG_NAME,a6 as VIRTUALIZER_CONFIG,a4 as DIFFS_UNSAFE_CSS,P as PREFERRED_HIGHLIGHTER,a5 as DIFFS_HOST_STYLE}from"./pierre-theme-BrzM0xZU.js";import{ab as cloneFileDiffMetadata,g as getLineAnnotationName,b as applyLineTextWithNewline,h as createAnnotationElement,l as getHighlighterOptions,r as resolvePreferredHighlighter,c as areRenderRangesEqual,i as isDefaultRenderRange,m as createPreElement,k as createContentColumn,e as shouldRenderFileAnnotations,f as getFileAnnotations,j as createFileHeaderElement,n as shouldUseTokenTransformer,R as ResizeManager,I as InteractionManager,p as pluckInteractionOptions,o as resolveEditSessionSlotName,w as writeEditSessionAnnotations,W as dequeueRender,t as prerenderHTMLIfNecessary,q as adoptEditSessionAnnotations,V as cloneHunks,X as queueRender,v as createAnnotationWrapperNode,x as createGutterUtilityContentNode,J as isStyleNode,S as SVGSpriteSheet,y as createUnsafeCSSStyleNode,z as wrapUnsafeCSS,A as getMeasuredScrollbarGutter,B as upsertHostThemeStyle,C as wrapThemeCSS,D as patchScrollbarGutterSize,E as isSafari,H as guardWebKitScrollDuringRebuild,G as getOrCreateCodeNode,K as arePrePropertiesEqual,L as setPreNodeProperties,M as areObjectsEqual,O as includesFileAnnotations,N as areOptionsEqual,P as FILE_ANNOTATION_DOM_KEY,ac as MergeConflictSlotStyles,Z as GutterUtilitySlotStyles,_ as useVirtualizer,$ as useCreateEditor,a0 as useStableCallback,a1 as useForceUpdate,a2 as useNextRenderData,a3 as noopRender,a as areFileTargetsEqual,a4 as templateRender,a9 as Virtualizer,a5 as useDetachCleanup,a6 as revealOnHighlight,a7 as scrollReachOnRender}from"./useFind-Cdl0rVJO.js";import{h as hastToHtml}from"./hastToHtml-C4ea9WpN.js";import{aw as useFilesLabels,bt as KeyHint,bu as languageFor,n as RowActionsMenu,bv as rangeLabel,bw as serializeCodeSnippet,bx as attachmentName,by as serializeReviewComment,ap as useEditorEnvironment,bz as excerptFor,bA as MediaNav,bB as ZoomableImage,bC as useEditorPrefs,av as useFilesHost,bD as Tooltip,I as IconButton,bm as useNearViewport,ay as filesRootOf}from"./kit-CD3F-f6F.js";import{F as FileIcon,T as TreeChevron}from"./FileIcon-DECOEMOz.js";const CACHE_KEY_VERSION=1;function composeCacheKey(scope,...segments){return`ck${CACHE_KEY_VERSION}:${JSON.stringify([scope,...segments])}`}function splitFileContents$1(contents){return contents!==""?contents.split(SPLIT_WITH_NEWLINES):[]}function hydratePartialDiff(type,fileDiff,files,parseDiffOptions={}){const targetFileDiff=type==="clone"?cloneFileDiffMetadata(fileDiff):fileDiff;if(!targetFileDiff.isPartial)throw new Error("hydratePartialDiff: fileDiff must be partial");switch(targetFileDiff.type){case"change":case"rename-changed":return hydrateTwoSidedFileDiff(targetFileDiff,requireOldFile(targetFileDiff,files),requireNewFile(targetFileDiff,files),parseDiffOptions);case"rename-pure":{const newFile=requireNewFile(targetFileDiff,files);requireMissingOldFile(targetFileDiff,files);const lines=splitFileContents$1(newFile.contents);return targetFileDiff.isPartial=!1,targetFileDiff.deletionLines=lines,targetFileDiff.additionLines=lines,targetFileDiff.deletionCharacterCount=newFile.contents.length,targetFileDiff.additionCharacterCount=newFile.contents.length,setHydratedCacheKey(targetFileDiff,null,newFile,parseDiffOptions),targetFileDiff}}throw new Error(`hydratePartialDiff: ${targetFileDiff.type} diffs cannot be hydrated from loaded files`)}function hydrateTwoSidedFileDiff(fileDiff,oldFile,newFile,parseDiffOptions){const deletionLines=splitFileContents$1(oldFile.contents),additionLines=splitFileContents$1(newFile.contents),{hunks,splitLineCount,unifiedLineCount}=hydrateHunks(fileDiff.hunks,additionLines.length);return fileDiff.hunks=hunks,fileDiff.splitLineCount=splitLineCount,fileDiff.unifiedLineCount=unifiedLineCount,fileDiff.isPartial=!1,fileDiff.deletionLines=deletionLines,fileDiff.additionLines=additionLines,fileDiff.deletionCharacterCount=oldFile.contents.length,fileDiff.additionCharacterCount=newFile.contents.length,setHydratedCacheKey(fileDiff,oldFile,newFile,parseDiffOptions),fileDiff}function hydrateHunks(hunks,totalAdditionLines){let splitLineCount=0,unifiedLineCount=0,lastHunkAdditionEnd=0;const hydratedHunks=[];for(const hunk of hunks){const additionLineIndex=Math.max(hunk.additionStart-1,0),deletionLineIndex=Math.max(hunk.deletionStart-1,0);let contentAdditionLineIndex=additionLineIndex,contentDeletionLineIndex=deletionLineIndex,hunkAdditionLines=0,hunkDeletionLines=0,hunkSplitLineCount=0,hunkUnifiedLineCount=0;const hunkContent=[];for(const content of hunk.hunkContent){if(content.type==="context"){hunkContent.push({...content,additionLineIndex:contentAdditionLineIndex,deletionLineIndex:contentDeletionLineIndex}),contentAdditionLineIndex+=content.lines,contentDeletionLineIndex+=content.lines,hunkSplitLineCount+=content.lines,hunkUnifiedLineCount+=content.lines;continue}hunkContent.push({...content,additionLineIndex:contentAdditionLineIndex,deletionLineIndex:contentDeletionLineIndex}),contentAdditionLineIndex+=content.additions,contentDeletionLineIndex+=content.deletions,hunkAdditionLines+=content.additions,hunkDeletionLines+=content.deletions,hunkSplitLineCount+=Math.max(content.additions,content.deletions),hunkUnifiedLineCount+=content.additions+content.deletions}const collapsedBefore=Math.max(getHunkSideStartBoundary(hunk.additionStart,hunk.additionCount)-lastHunkAdditionEnd,0);hydratedHunks.push({...hunk,collapsedBefore,additionLineIndex,deletionLineIndex,additionLines:hunkAdditionLines,deletionLines:hunkDeletionLines,hunkContent,splitLineStart:splitLineCount+collapsedBefore,unifiedLineStart:unifiedLineCount+collapsedBefore,splitLineCount:hunkSplitLineCount,unifiedLineCount:hunkUnifiedLineCount}),splitLineCount+=collapsedBefore+hunkSplitLineCount,unifiedLineCount+=collapsedBefore+hunkUnifiedLineCount,lastHunkAdditionEnd=getHunkSideEndBoundary(hunk.additionStart,hunk.additionCount)}if(hydratedHunks.length>0){const lastHunk=hydratedHunks[hydratedHunks.length-1],lastHunkEnd=getHunkSideEndBoundary(lastHunk.additionStart,lastHunk.additionCount),collapsedAfter=Math.max(totalAdditionLines-lastHunkEnd,0);splitLineCount+=collapsedAfter,unifiedLineCount+=collapsedAfter}return{hunks:hydratedHunks,splitLineCount,unifiedLineCount}}function requireOldFile(fileDiff,files){if(files.oldFile==null)throw new Error(`hydratePartialDiff: ${fileDiff.type} diff for ${fileDiff.name} requires oldFile`);return files.oldFile}function requireNewFile(fileDiff,files){if(files.newFile==null)throw new Error(`hydratePartialDiff: ${fileDiff.type} diff for ${fileDiff.name} requires newFile`);return files.newFile}function requireMissingOldFile(fileDiff,files){if(files.oldFile!==null)throw new Error(`hydratePartialDiff: ${fileDiff.type} diff for ${fileDiff.name} requires oldFile to be null`)}function getHydratedCacheKey(fileDiff,oldFile,newFile,parseDiffOptions){return fileDiff.cacheKey!=null?`${fileDiff.cacheKey}:hydrated`:getLoadedFileCacheKey(oldFile,newFile,parseDiffOptions)}function setHydratedCacheKey(fileDiff,oldFile,newFile,parseDiffOptions){const cacheKey=getHydratedCacheKey(fileDiff,oldFile,newFile,parseDiffOptions);if(cacheKey==null){delete fileDiff.cacheKey;return}fileDiff.cacheKey=cacheKey}function getLoadedFileCacheKey(oldFile,newFile,parseDiffOptions){return oldFile!=null&&newFile!=null?oldFile.cacheKey!=null&&newFile.cacheKey!=null?composeCacheKey(parseDiffOptions.disableLineMatching===!0?"hydrated-files-raw":"hydrated-files",oldFile.cacheKey,newFile.cacheKey):void 0:oldFile?.cacheKey??newFile?.cacheKey}const stringDetachEncoder=new TextEncoder,stringDetachDecoder=new TextDecoder("utf-8",{ignoreBOM:!0}),SURROGATE_CODE_UNIT_PATTERN=/[\uD800-\uDFFF]/,STRING_DETACH_INITIAL_BUFFER_SIZE=1024;let stringDetachBuffer=new Uint8Array(STRING_DETACH_INITIAL_BUFFER_SIZE);function releaseStringDetachBuffer(){stringDetachBuffer.length!==STRING_DETACH_INITIAL_BUFFER_SIZE&&(stringDetachBuffer=new Uint8Array(STRING_DETACH_INITIAL_BUFFER_SIZE))}function detachString(value){if(value.length===0)return value;if(SURROGATE_CODE_UNIT_PATTERN.test(value))return JSON.parse(JSON.stringify(value));const requiredByteLength=value.length*3;stringDetachBuffer.length<requiredByteLength&&(stringDetachBuffer=new Uint8Array(requiredByteLength));const{written}=stringDetachEncoder.encodeInto(value,stringDetachBuffer);return stringDetachDecoder.decode(stringDetachBuffer.subarray(0,written))}const filenameDecoder=new TextDecoder("utf-8",{ignoreBOM:!0}),NAMED_ESCAPES={'"':'"',"\\":"\\",a:"\x07",b:"\b",t:" ",n:`
2
2
  `,v:"\v",f:"\f",r:"\r"};function parseQuotedDiffFileName(input){if(input[0]!=='"')return;let fileName="",index=1;for(;index<input.length;){const char=input[index];if(char==='"')return{fileName,rawLength:index+1};if(char!=="\\"){fileName+=char,index++;continue}const escaped=NAMED_ESCAPES[input[index+1]];if(escaped!=null){fileName+=escaped,index+=2;continue}const bytes=[];do{const byte=readOctalByte(input,index+1);if(byte==null)return;bytes.push(byte),index+=4}while(input[index]==="\\"&&input[index+1]>="0"&&input[index+1]<="7");fileName+=filenameDecoder.decode(new Uint8Array(bytes))}}function readOctalByte(input,index){const first=input.charCodeAt(index)-48,second=input.charCodeAt(index+1)-48,third=input.charCodeAt(index+2)-48;if(first>=0&&first<=3&&second>=0&&second<=7&&third>=0&&third<=7)return first*64+second*8+third}const MAX_ALIGNMENT_COMPARISONS=4096,MIN_IMPROVEMENT_PER_PAIR=.5;function realignChangeContentBySimilarity(diff){for(const hunk of diff.hunks)for(let index=0;index<hunk.hunkContent.length;index++){const content=hunk.hunkContent[index];if(content.type!=="change")continue;const replacement=realignChangeBlock(diff,content);replacement!=null&&(hunk.hunkContent.splice(index,1,...replacement),index+=replacement.length-1)}}function slideBlankBoundaryBlocksUp(hunk,diff,resolveSlide){const{hunkContent}=hunk;for(let index=1;index<hunkContent.length;index++){const block=hunkContent[index],previous=hunkContent[index-1];if(block.type!=="change"||block.additions>0&&block.deletions>0||previous.type!=="context")continue;const isInsert=block.additions>0,lines=isInsert?diff.additionLines:diff.deletionLines,blockStart=isInsert?block.additionLineIndex:block.deletionLineIndex,blockLength=isInsert?block.additions:block.deletions,unit=lines[blockStart]??"";if(unit.trim()!=="")continue;let uniform=!0;for(let offset=1;offset<blockLength;offset++)if(lines[blockStart+offset]!==unit){uniform=!1;break}if(!uniform)continue;let slide=0;for(;slide<previous.lines&&diff.additionLines[previous.additionLineIndex+previous.lines-1-slide]===unit;)slide++;if(slide===0||index===1&&slide===previous.lines||resolveSlide!=null&&(slide=resolveSlide(block,slide),slide===0))continue;block.additionLineIndex-=slide,block.deletionLineIndex-=slide;const blockAdditionEnd=block.additionLineIndex+block.additions,blockDeletionEnd=block.deletionLineIndex+block.deletions,next=hunkContent[index+1];next?.type==="context"?(next.lines+=slide,next.additionLineIndex=blockAdditionEnd,next.deletionLineIndex=blockDeletionEnd):hunkContent.splice(index+1,0,{type:"context",lines:slide,additionLineIndex:blockAdditionEnd,deletionLineIndex:blockDeletionEnd}),previous.lines-=slide,previous.lines===0&&(hunkContent.splice(index-1,1),index--)}}function realignChangeBlock(diff,content){const{deletions,additions,deletionLineIndex,additionLineIndex}=content,pairCount=Math.min(deletions,additions),surplus=Math.abs(additions-deletions);if(pairCount===0||surplus===0||pairCount*(surplus+1)>MAX_ALIGNMENT_COMPARISONS)return null;const strippedDeletions=[];for(let line=0;line<deletions;line++)strippedDeletions.push(stripWhitespace(diff.deletionLines[deletionLineIndex+line]??""));const strippedAdditions=[];for(let line=0;line<additions;line++)strippedAdditions.push(stripWhitespace(diff.additionLines[additionLineIndex+line]??""));const additionsAreLonger=additions>deletions;let bestOffset=0,bestScore=-1;for(let offset=0;offset<=surplus;offset++){let score=0;for(let pair=0;pair<pairCount;pair++)score+=lineSimilarity(strippedDeletions[pair+(additionsAreLonger?0:offset)],strippedAdditions[pair+(additionsAreLonger?offset:0)]);offset===0?bestScore=score+pairCount*MIN_IMPROVEMENT_PER_PAIR:score>bestScore&&(bestScore=score,bestOffset=offset)}if(bestOffset===0)return null;const blocks=[],pushBlock=(blockDeletions,blockAdditions,blockDeletionIndex,blockAdditionIndex)=>{(blockDeletions>0||blockAdditions>0)&&blocks.push({type:"change",deletions:blockDeletions,additions:blockAdditions,deletionLineIndex:blockDeletionIndex,additionLineIndex:blockAdditionIndex})};return additionsAreLonger?(pushBlock(0,bestOffset,deletionLineIndex,additionLineIndex),pushBlock(pairCount,pairCount,deletionLineIndex,additionLineIndex+bestOffset),pushBlock(0,additions-pairCount-bestOffset,deletionLineIndex+pairCount,additionLineIndex+bestOffset+pairCount)):(pushBlock(bestOffset,0,deletionLineIndex,additionLineIndex),pushBlock(pairCount,pairCount,deletionLineIndex+bestOffset,additionLineIndex),pushBlock(deletions-pairCount-bestOffset,0,deletionLineIndex+bestOffset+pairCount,additionLineIndex+pairCount)),blocks}const WHITESPACE=/\s+/g;function stripWhitespace(line){return line.replace(WHITESPACE,"")}function lineSimilarity(a,b){if(a===b)return 1;const maxLength=Math.max(a.length,b.length),minLength=Math.min(a.length,b.length);if(minLength===0)return 0;let prefix=0;for(;prefix<minLength&&a[prefix]===b[prefix];)prefix++;let suffix=0;for(;suffix<minLength-prefix&&a[a.length-1-suffix]===b[b.length-1-suffix];)suffix++;return(prefix+suffix)/maxLength}const GIT_DIFF_HEADER_FILENAMES=/^diff --git ("a\/(?:[^"\\]|\\.)*"|a\/.+?) ("b\/(?:[^"\\]|\\.)*"|b\/.+?)$/;function _processPatch(data,{cacheKeyPrefix,disableLineMatching,throwOnError=!1}={},patchIndex){const isGitDiff=isGitDiffPatch(data),rawFiles=isGitDiff?splitGitDiffFiles(data):splitUnifiedDiffFiles(data),cacheKeyScope=disableLineMatching===!0?"patch-file-raw":"patch-file";let patchMetadata;const files=[];for(const fileOrPatchMetadata of rawFiles){if(isGitDiff&&!GIT_DIFF_FILE_BREAK_REGEX.test(fileOrPatchMetadata)){if(patchMetadata==null)patchMetadata=detachString(fileOrPatchMetadata);else{if(throwOnError)throw Error("parsePatchContent: unknown file blob");console.error("parsePatchContent: unknown file blob:",fileOrPatchMetadata)}continue}else if(!isGitDiff&&!startsWithUnifiedDiffFileHeader(fileOrPatchMetadata)){if(patchMetadata==null)patchMetadata=detachString(fileOrPatchMetadata);else{if(throwOnError)throw Error("parsePatchContent: unknown file blob");console.error("parsePatchContent: unknown file blob:",fileOrPatchMetadata)}continue}const currentFile=_processFile(fileOrPatchMetadata,{cacheKey:cacheKeyPrefix!=null?patchIndex==null?composeCacheKey(cacheKeyScope,cacheKeyPrefix,String(files.length)):composeCacheKey(cacheKeyScope,cacheKeyPrefix,String(patchIndex),String(files.length)):void 0,isGitDiff,disableLineMatching,throwOnError});currentFile!=null&&files.push(currentFile)}return{patchMetadata,files}}function processFile(fileDiffString,options){try{return _processFile(fileDiffString,options)}finally{releaseStringDetachBuffer()}}function _processFile(fileDiffString,{cacheKey,disableLineMatching=!1,isGitDiff=GIT_DIFF_FILE_BREAK_REGEX.test(fileDiffString),oldFile,newFile,throwOnError=!1}={}){let lastHunkEnd=0;const hunks=splitAtLinePrefix(fileDiffString,"@@ ");let currentFile;const isPartial=oldFile==null||newFile==null;let deletionLineIndex=0,additionLineIndex=0;for(const hunk of hunks){const lines=splitWithNewlines(hunk),firstLine=lines[0];if(firstLine==null){if(throwOnError)throw Error("parsePatchContent: invalid hunk");console.error("parsePatchContent: invalid hunk",hunk);continue}const fileHeader=parseHunkHeader(firstLine);let additionLines=0,deletionLines=0;if(fileHeader==null||currentFile==null){if(currentFile!=null){if(throwOnError)throw Error("parsePatchContent: Invalid hunk");console.error("parsePatchContent: Invalid hunk",hunk);continue}currentFile={name:"",type:"change",hunks:[],splitLineCount:0,unifiedLineCount:0,isPartial,additionLines:!isPartial&&oldFile!=null&&newFile!=null?splitFileContents(newFile.contents):[],deletionLines:!isPartial&&oldFile!=null&&newFile!=null?splitFileContents(oldFile.contents):[],additionCharacterCount:!isPartial&&oldFile!=null&&newFile!=null?newFile.contents.length:0,deletionCharacterCount:!isPartial&&oldFile!=null&&newFile!=null?oldFile.contents.length:0,cacheKey:maybeDetachOptionalString(cacheKey)},currentFile.additionLines.length===1&&newFile?.contents===""&&(currentFile.additionLines.length=0),currentFile.deletionLines.length===1&&oldFile?.contents===""&&(currentFile.deletionLines.length=0);for(const line of lines){if(line.startsWith("diff --git")){const filenameMatch2=line.trim().match(GIT_DIFF_HEADER_FILENAMES);if(filenameMatch2==null){if(throwOnError)throw Error("parsePatchContent: invalid git diff header");console.error("parsePatchContent: invalid git diff header",line);continue}const prevName=decodeDiffFileName(filenameMatch2[1],!0),name=decodeDiffFileName(filenameMatch2[2],!0);currentFile.name=detachString(name),prevName!==name&&(currentFile.prevName=detachString(prevName));continue}const filenameMatch=line.startsWith("---")||line.startsWith("+++")?line.match(FILENAME_HEADER_REGEX):null;if(filenameMatch!=null){const[,type,rawFileName]=filenameMatch,fileName=decodeDiffFileName(rawFileName,isGitDiff);if(type==="---"&&fileName!=="/dev/null"){const detachedFileName=detachString(fileName);currentFile.prevName=detachedFileName,currentFile.name=detachedFileName}else type==="+++"&&fileName!=="/dev/null"&&(currentFile.name=detachString(fileName))}else if(isGitDiff){if(line.startsWith("new mode ")&&(currentFile.mode=detachString(line.slice(8).trim())),line.startsWith("old mode ")&&(currentFile.prevMode=detachString(line.slice(8).trim())),line.startsWith("new file mode")&&(currentFile.type="new",currentFile.mode=detachString(line.slice(13).trim())),line.startsWith("deleted file mode")&&(currentFile.type="deleted",currentFile.mode=detachString(line.slice(17).trim())),line.startsWith("similarity index")&&(line.startsWith("similarity index 100%")?currentFile.type="rename-pure":currentFile.type="rename-changed"),line.startsWith("index ")){const[,prevObjectId,newObjectId,mode]=line.trim().match(INDEX_LINE_METADATA)??[];prevObjectId!=null&&(currentFile.prevObjectId=detachString(prevObjectId)),newObjectId!=null&&(currentFile.newObjectId=detachString(newObjectId)),mode!=null&&(currentFile.mode=detachString(mode))}(line.startsWith("rename from ")||line.startsWith("copy from "))&&(currentFile.prevName=detachString(decodeDiffFileName(line.slice(line.startsWith("rename")?12:10)))),(line.startsWith("rename to ")||line.startsWith("copy to "))&&(currentFile.name=detachString(decodeDiffFileName(line.slice(line.startsWith("rename")?10:8))))}}continue}let currentContent,lastLineType;for(;lines.length>0&&(lines[lines.length-1]===`
3
3
  `||lines[lines.length-1]==="\r"||lines[lines.length-1]===`\r
4
4
  `||lines[lines.length-1]==="");)lines.pop();const{additionStart,deletionStart}=fileHeader;deletionLineIndex=isPartial?deletionLineIndex:deletionStart-1,additionLineIndex=isPartial?additionLineIndex:additionStart-1;const hunkData={collapsedBefore:0,splitLineCount:0,splitLineStart:0,unifiedLineCount:0,unifiedLineStart:0,additionCount:fileHeader.additionCount,additionStart,additionLines,deletionCount:fileHeader.deletionCount,deletionStart,deletionLines,deletionLineIndex,additionLineIndex,hunkContent:[],hunkContext:maybeDetachOptionalString(fileHeader.hunkContext),hunkSpecs:detachString(firstLine),noEOFCRAdditions:!1,noEOFCRDeletions:!1};let parsedAdditionLines=0,parsedDeletionLines=0;for(let lineIndex=1;lineIndex<lines.length;lineIndex++){const rawLine=lines[lineIndex];if(parsedAdditionLines>=hunkData.additionCount&&parsedDeletionLines>=hunkData.deletionCount&&!rawLine.startsWith("\\")){if(!(isHunkBodyLine(rawLine)&&!isFormatPatchVersionSeparator(rawLine)))break;if(throwOnError)throw Error("parsePatchContent: hunk has more lines than expected")}const firstChar=rawLine[0];if(firstChar!=="+"&&firstChar!=="-"&&firstChar!==" "&&firstChar!=="\\"){if(throwOnError)throw Error("parsePatchContent: invalid hunk line");console.error(`parseLineType: Invalid firstChar: "${firstChar}", full line: "${rawLine}"`),console.error("processFile: invalid rawLine:",rawLine);continue}const type=parseRawLineType(firstChar);if(type==="addition"){if(throwOnError&&parsedAdditionLines>=hunkData.additionCount)throw Error("parsePatchContent: hunk has too many addition lines");const line=getParsedLineContent(rawLine);(currentContent==null||currentContent.type!=="change")&&(currentContent=createContentGroup("change",deletionLineIndex,additionLineIndex),hunkData.hunkContent.push(currentContent)),additionLineIndex++,parsedAdditionLines++,isPartial&&(currentFile.additionLines.push(line),currentFile.additionCharacterCount+=line.length),currentContent.additions++,additionLines++,lastLineType="addition"}else if(type==="deletion"){if(throwOnError&&parsedDeletionLines>=hunkData.deletionCount)throw Error("parsePatchContent: hunk has too many deletion lines");const line=getParsedLineContent(rawLine);(currentContent==null||currentContent.type!=="change")&&(currentContent=createContentGroup("change",deletionLineIndex,additionLineIndex),hunkData.hunkContent.push(currentContent)),deletionLineIndex++,parsedDeletionLines++,isPartial&&(currentFile.deletionLines.push(line),currentFile.deletionCharacterCount+=line.length),currentContent.deletions++,deletionLines++,lastLineType="deletion"}else if(type==="context"){if(throwOnError&&(parsedDeletionLines>=hunkData.deletionCount||parsedAdditionLines>=hunkData.additionCount))throw Error("parsePatchContent: hunk has too many context lines");const line=getParsedLineContent(rawLine);(currentContent==null||currentContent.type!=="context")&&(currentContent=createContentGroup("context",deletionLineIndex,additionLineIndex),hunkData.hunkContent.push(currentContent)),additionLineIndex++,deletionLineIndex++,parsedAdditionLines++,parsedDeletionLines++,isPartial&&(currentFile.deletionLines.push(line),currentFile.additionLines.push(line),currentFile.deletionCharacterCount+=line.length,currentFile.additionCharacterCount+=line.length),currentContent.lines++,lastLineType="context"}else if(type==="metadata"&&currentContent!=null){if(currentContent.type==="context"?(hunkData.noEOFCRAdditions=!0,hunkData.noEOFCRDeletions=!0):lastLineType==="deletion"?hunkData.noEOFCRDeletions=!0:lastLineType==="addition"&&(hunkData.noEOFCRAdditions=!0),isPartial&&(lastLineType==="addition"||lastLineType==="context")){const lastIndex=currentFile.additionLines.length-1;if(lastIndex>=0){const line=currentFile.additionLines[lastIndex],cleanedLine=cleanLastNewline(line);currentFile.additionLines[lastIndex]=cleanedLine,currentFile.additionCharacterCount+=cleanedLine.length-line.length}}if(isPartial&&(lastLineType==="deletion"||lastLineType==="context")){const lastIndex=currentFile.deletionLines.length-1;if(lastIndex>=0){const line=currentFile.deletionLines[lastIndex],cleanedLine=cleanLastNewline(line);currentFile.deletionLines[lastIndex]=cleanedLine,currentFile.deletionCharacterCount+=cleanedLine.length-line.length}}}}if(parsedAdditionLines!==hunkData.additionCount||parsedDeletionLines!==hunkData.deletionCount){if(throwOnError)throw Error("parsePatchContent: hunk line count mismatch");console.error(`parsePatchContent: hunk line count mismatch: "${firstLine.trimEnd()}", declared old/new ${hunkData.deletionCount}/${hunkData.additionCount}, parsed old/new ${parsedDeletionLines}/${parsedAdditionLines}`);const repairedAdditionStart=getHunkSideStartBoundary(hunkData.additionStart,hunkData.additionCount)+(parsedAdditionLines===0?0:1),repairedDeletionStart=getHunkSideStartBoundary(hunkData.deletionStart,hunkData.deletionCount)+(parsedDeletionLines===0?0:1);if(!isPartial){const additionStartDelta=repairedAdditionStart-hunkData.additionStart,deletionStartDelta=repairedDeletionStart-hunkData.deletionStart;hunkData.additionLineIndex+=additionStartDelta,hunkData.deletionLineIndex+=deletionStartDelta;for(const content of hunkData.hunkContent)content.additionLineIndex+=additionStartDelta,content.deletionLineIndex+=deletionStartDelta}hunkData.additionStart=repairedAdditionStart,hunkData.deletionStart=repairedDeletionStart,hunkData.additionCount=parsedAdditionLines,hunkData.deletionCount=parsedDeletionLines}hunkData.additionLines=additionLines,hunkData.deletionLines=deletionLines,hunkData.collapsedBefore=Math.max(getHunkSideStartBoundary(hunkData.additionStart,hunkData.additionCount)-lastHunkEnd,0),currentFile.hunks.push(hunkData),lastHunkEnd=getHunkSideEndBoundary(hunkData.additionStart,hunkData.additionCount);for(const content of hunkData.hunkContent)content.type==="context"?(hunkData.splitLineCount+=content.lines,hunkData.unifiedLineCount+=content.lines):(hunkData.splitLineCount+=Math.max(content.additions,content.deletions),hunkData.unifiedLineCount+=content.deletions+content.additions);hunkData.splitLineStart=currentFile.splitLineCount+hunkData.collapsedBefore,hunkData.unifiedLineStart=currentFile.unifiedLineCount+hunkData.collapsedBefore,currentFile.splitLineCount+=hunkData.collapsedBefore+hunkData.splitLineCount,currentFile.unifiedLineCount+=hunkData.collapsedBefore+hunkData.unifiedLineCount}if(currentFile!=null){if(throwOnError&&isPartial&&!isGitDiff&&currentFile.hunks.length===0)throw Error("parsePatchContent: unified file has no hunks");if(currentFile.hunks.length>0&&!isPartial&&currentFile.additionLines.length>0&&currentFile.deletionLines.length>0){const lastHunk=currentFile.hunks[currentFile.hunks.length-1],lastHunkEnd2=getHunkSideEndBoundary(lastHunk.additionStart,lastHunk.additionCount),totalFileLines=currentFile.additionLines.length,collapsedAfter=Math.max(totalFileLines-lastHunkEnd2,0);currentFile.splitLineCount+=collapsedAfter,currentFile.unifiedLineCount+=collapsedAfter}return isGitDiff||(currentFile.prevName!=null&&currentFile.name!==currentFile.prevName?currentFile.hunks.length>0?currentFile.type="rename-changed":currentFile.type="rename-pure":(oldFile==null||oldFile.contents==="")&&newFile!=null&&newFile.contents!==""?currentFile.type="new":oldFile!=null&&oldFile.contents!==""&&(newFile==null||newFile.contents==="")&&(currentFile.type="deleted")),currentFile.type!=="rename-pure"&&currentFile.type!=="rename-changed"&&(currentFile.prevName=void 0),disableLineMatching||realignChangeContentBySimilarity(currentFile),currentFile}}function parsePatchFiles(data,options={}){const{cacheKeyPrefix,throwOnError=!1}=options,patches=[],rawPatches=hasCommitMetadataBoundary(data)?data.split(COMMIT_METADATA_SPLIT):[data];for(const patch of rawPatches)try{patches.push(_processPatch(patch,options,cacheKeyPrefix!=null?patches.length:void 0))}catch(error){if(throwOnError)throw error;console.error(error)}finally{releaseStringDetachBuffer()}return patches}function decodeDiffFileName(value,stripGitPrefix=!1){const rawName=value.trim(),name=rawName.startsWith('"')?parseQuotedDiffFileName(rawName)?.fileName??rawName:rawName;return stripGitPrefix&&(name.startsWith("a/")||name.startsWith("b/"))?name.slice(2):name}function hasCommitMetadataBoundary(data){return data.startsWith("From ")||data.includes(`
@@ -31,4 +31,4 @@ ${prefix}`,firstBoundaryIndex=contents.startsWith(prefix)?0:findLinePrefixIndex(
31
31
  `)===!0}function createPlainAdditionLineElement(lineIndex,lineText,unifiedLineIndex=lineIndex,splitLineIndex=lineIndex){return{type:"element",tagName:"div",properties:{"data-line":lineIndex+1,"data-line-index":`${unifiedLineIndex},${splitLineIndex}`,"data-line-type":"context"},children:[{type:"element",tagName:"span",properties:{"data-char":0},children:[{type:"text",value:lineText}]}]}}function getEditorDocumentLines(textDocument){const lines=[];let characterCount=0;for(let line=0;line<textDocument.lineCount;line++){const text=textDocument.getLineText(line,!0);lines.push(text),characterCount+=text.length}return{lines,characterCount}}function getDiffLanguages(diff){if(diff.lang!=null)return[diff.lang];const deletionLang=getFiletypeFromFileName(diff.prevName??diff.name),additionLang=getFiletypeFromFileName(diff.name);return deletionLang===additionLang?[additionLang]:[deletionLang,additionLang]}function isDiffMassive(diff,tokenizeMaxLength){return Math.max(diff.additionLines.length,diff.deletionLines.length)>tokenizeMaxLength}function canHydrateCollapsedContext$1(fileDiff,hasFileLoader){return fileDiff.isPartial&&hasFileLoader&&(fileDiff.type==="change"||fileDiff.type==="rename-changed")}function areDiffLineAnnotationsEqual(annotationA,annotationB){return annotationA.lineNumber===annotationB.lineNumber&&annotationA.side===annotationB.side&&annotationA.metadata===annotationB.metadata}function areHunkDataEqual(hunkA,hunkB){return hunkA.slotName===hunkB.slotName&&hunkA.hunkIndex===hunkB.hunkIndex&&hunkA.lines===hunkB.lines&&hunkA.lineCountKnown===hunkB.lineCountKnown&&hunkA.type===hunkB.type&&hunkA.expandable?.chunked===hunkB.expandable?.chunked&&hunkA.expandable?.up===hunkB.expandable?.up&&hunkA.expandable?.down===hunkB.expandable?.down}async function awaitWithTimeout(callback,timeout=300){let timeoutId;try{await Promise.race([callback(),new Promise(resolve=>{timeoutId=setTimeout(resolve,timeout)})])}finally{timeoutId!=null&&clearTimeout(timeoutId)}}function getDiffFileInput({oldFile,newFile},context){if(!(oldFile===void 0&&newFile===void 0)){if(oldFile===void 0||newFile===void 0)throw new Error(`${context}: Pass null for an intentionally missing oldFile or newFile side`);if(oldFile===null){if(newFile===null)throw new Error(`${context}: You must pass oldFile, newFile, or both`);return{oldFile,newFile}}return newFile===null?{oldFile,newFile}:{oldFile,newFile}}}function getDiffHunksRendererOptions(options){return{theme:options?.theme,disableLineNumbers:options?.disableLineNumbers,overflow:options?.overflow,collapsed:options?.collapsed,disableFileHeader:options?.disableFileHeader,disableVirtualizationBuffers:options?.disableVirtualizationBuffers,stickyHeader:options?.stickyHeader,preferredHighlighter:options?.preferredHighlighter,useCSSClasses:options?.useCSSClasses,useTokenTransformer:shouldUseTokenTransformer(options),tokenizeMaxLineLength:options?.tokenizeMaxLineLength,tokenizeMaxLength:options?.tokenizeMaxLength,diffStyle:options?.diffStyle,diffIndicators:options?.diffIndicators,disableBackground:options?.disableBackground,hunkSeparators:typeof options?.hunkSeparators=="function"?"custom":options?.hunkSeparators,expandUnchanged:options?.expandUnchanged,loadDiffFiles:options?.loadDiffFiles,parseDiffOptions:options?.parseDiffOptions,collapsedContextThreshold:options?.collapsedContextThreshold,lineDiffType:options?.lineDiffType,maxLineDiffLength:options?.maxLineDiffLength,expansionLineCount:options?.expansionLineCount,headerRenderMode:options?.renderCustomHeader!=null?"custom":"default"}}function canHydrateDiff(fileDiff){return fileDiff.isPartial&&(fileDiff.type==="change"||fileDiff.type==="rename-changed"||fileDiff.type==="rename-pure")}function createEditSessionDiff(fileDiff){const editSessionDiff={...fileDiff};return delete editSessionDiff.cacheKey,editSessionDiff}function shouldResetUndoState(prevDiff,nextDiff){if(prevDiff.isPartial||nextDiff.isPartial)throw new Error("FileDiff.shouldResetEditorForExternalDiff: diffs must be fully hydrated");const prevLanguage=prevDiff.lang??getFiletypeFromFileName(prevDiff.name),nextLanguage=nextDiff.lang??getFiletypeFromFileName(nextDiff.name),prevHasOldFile=prevDiff.type!=="new",nextHasOldFile=nextDiff.type!=="new";return prevDiff.name!==nextDiff.name||prevLanguage!==nextLanguage||prevHasOldFile!==nextHasOldFile||prevDiff.deletionLines.length!==nextDiff.deletionLines.length?!0:prevDiff.deletionLines.some((line,index)=>line!==nextDiff.deletionLines[index])}function areLinesEqual(first,second){return first.length===second.length&&first.every((line,index)=>line===second[index])}function canRestoreDiffSession(snapshot,inputDiff){const{oldFile}=snapshot;return oldFile==null?inputDiff.type==="new":inputDiff.type!=="new"&&oldFile.name===(inputDiff.prevName??inputDiff.name)&&areLinesEqual(oldFile.lines,inputDiff.deletionLines)}let instanceId$1=-1;var FileDiff$1=class{options;workerManager;requestOwnerRender;static LoadedCustomComponent=!0;__id=`file-diff:${++instanceId$1}`;type="file-diff";fileContainer;spriteSVG;pre;codeUnified;codeDeletions;codeAdditions;bufferBefore;bufferAfter;themeCSSStyle;appliedThemeCSS;hasAdoptedThemeCSS=!1;unsafeCSSStyle;appliedUnsafeCSS;gutterUtilityContent;headerElement;headerPrefix;headerFilenameSuffix;headerMetadata;headerCustom;separatorCache=new Map;errorWrapper;placeHolder;hunksRenderer;resizeManager;scrollSyncManager;interactionManager;annotationCache=new Map;get lineAnnotations(){return this.renderedData?.lineAnnotations??EMPTY_LINE_ANNOTATIONS}managersDirty=!1;deletionFile;additionFile;fileDiff;editSession;renderedData;pendingData;forceRenderOverride;renderRange;pendingFiles;appliedPreAttributes;headerCache={lastRenderedHTML:void 0,html:void 0,fileDiff:void 0};lastRowCount;mounted=!1;enabled=!0;editor;refreshViewTimeout;lineStateRefreshPending=!1;deferredSelectedLines;deferredEditorActiveLine;constructor(options={theme:DEFAULT_THEMES},workerManager,requestOwnerRender){this.options=options,this.workerManager=workerManager,this.requestOwnerRender=requestOwnerRender,this.hunksRenderer=this.createHunksRenderer(options),this.resizeManager=new ResizeManager,this.scrollSyncManager=new ScrollSyncManager,this.interactionManager=new InteractionManager("diff",pluckInteractionOptions(options,typeof options.hunkSeparators=="function"||(options.hunkSeparators??"line-info")==="line-info"||options.hunkSeparators==="line-info-basic"?this.handleExpandHunk:void 0,this.getLineIndex)),this.workerManager?.subscribeToThemeChanges(this),this.enabled=!0}handleHighlightRender=()=>{this.rerender()};getTheme(){return this.workerManager?.getDiffRenderOptions().theme??this.options.theme??DEFAULT_THEMES}getHunksRendererOptions(options){return getDiffHunksRendererOptions(options)}createHunksRenderer(options){return new DiffHunksRenderer(this.getHunksRendererOptions(options),this.getAnnotationSlotName,this.handleHighlightRender,this.workerManager)}getLineIndex=(lineNumber,side="additions")=>this.getLineIndexForDiff(this.getDiffForLineIndex(),lineNumber,side);getDiffForLineIndex(){return this.getRenderedDiff()}getLineIndexForDiff(fileDiff,lineNumber,side){if(fileDiff==null)return;const lastHunk=fileDiff.hunks.at(-1);let targetUnifiedIndex,targetSplitIndex;hunkIterator:for(const hunk of fileDiff.hunks){const hunkStart=side==="deletions"?hunk.deletionStart:hunk.additionStart,hunkCount=side==="deletions"?hunk.deletionCount:hunk.additionCount;let currentLineNumber=getHunkSideStartBoundary(hunkStart,hunkCount)+1,splitIndex=hunk.splitLineStart,unifiedIndex=hunk.unifiedLineStart;if(lineNumber<currentLineNumber){const difference=currentLineNumber-lineNumber;targetUnifiedIndex=Math.max(unifiedIndex-difference,0),targetSplitIndex=Math.max(splitIndex-difference,0);break hunkIterator}if(lineNumber>=currentLineNumber+hunkCount){if(hunk===lastHunk){const difference=lineNumber-(currentLineNumber+hunkCount);targetUnifiedIndex=unifiedIndex+hunk.unifiedLineCount+difference,targetSplitIndex=splitIndex+hunk.splitLineCount+difference;break hunkIterator}continue}for(const content of hunk.hunkContent)if(content.type==="context")if(lineNumber<currentLineNumber+content.lines){const difference=lineNumber-currentLineNumber;targetSplitIndex=splitIndex+difference,targetUnifiedIndex=unifiedIndex+difference;break hunkIterator}else currentLineNumber+=content.lines,splitIndex+=content.lines,unifiedIndex+=content.lines;else{const sideCount=side==="deletions"?content.deletions:content.additions;if(lineNumber<currentLineNumber+sideCount){const indexDifference=lineNumber-currentLineNumber;targetUnifiedIndex=unifiedIndex+(side==="additions"?content.deletions:0)+indexDifference,targetSplitIndex=splitIndex+indexDifference;break hunkIterator}else currentLineNumber+=sideCount,splitIndex+=Math.max(content.deletions,content.additions),unifiedIndex+=content.deletions+content.additions}break hunkIterator}if(!(targetUnifiedIndex==null||targetSplitIndex==null))return[targetUnifiedIndex,targetSplitIndex]}setOptions(options){options!=null&&(this.options=options,this.clearReusableHeader(),this.hunksRenderer.setOptions(this.getHunksRendererOptions(options)),this.syncInteractionOptions())}syncInteractionOptions(){this.interactionManager.setOptions(pluckInteractionOptions(this.options,typeof this.options.hunkSeparators=="function"||(this.options.hunkSeparators??"line-info")==="line-info"||this.options.hunkSeparators==="line-info-basic"?this.handleExpandHunk:void 0,this.getLineIndex))}mergeOptions(options){this.options={...this.options,...options}}setThemeType(themeType){(this.options.themeType??"system")!==themeType&&(this.mergeOptions({themeType}),this.applyCachedThemeState(themeType))}applyCachedThemeState(themeType){if(typeof this.options.theme=="string"||this.fileContainer==null||this.appliedThemeCSS==null)return!1;const effectiveThemeType=this.appliedThemeCSS.baseThemeType??themeType;return this.appliedThemeCSS.themeType===effectiveThemeType?!1:(this.applyThemeState(this.fileContainer,this.appliedThemeCSS.themeStyles,themeType,this.appliedThemeCSS.baseThemeType),!0)}hasThemeChanged(){return this.appliedThemeCSS!=null&&!areThemesEqual(this.appliedThemeCSS.theme,this.getTheme())}getHoveredLine=()=>this.interactionManager.getHoveredLine();getAnnotationSlotName=annotation=>resolveEditSessionSlotName(this.editSession?.annotations,annotation,getLineAnnotationName);getLatestAnnotations(){return this.pendingData?.lineAnnotations??this.editSession?.annotations?.current??this.lineAnnotations}getAnnotationsForDiff(fileDiff){const{pendingData}=this;return pendingData!=null&&areDiffTargetsEqual(fileDiff,pendingData.fileDiff)?pendingData.lineAnnotations:this.lineAnnotations}isNewAnnotations(lineAnnotations){const session=this.editSession?.annotations;return lineAnnotations===this.getLatestAnnotations()?!1:session==null||lineAnnotations!==session.provided&&lineAnnotations!==session.current}setLineAnnotations(lineAnnotations){const sessionAnnotations=this.editSession?.annotations;if(sessionAnnotations!=null){if(!this.isNewAnnotations(lineAnnotations))return;writeEditSessionAnnotations(sessionAnnotations,lineAnnotations,getLineAnnotationName)}const fileDiff=this.getWorkingDiff();fileDiff!=null&&(this.pendingData={fileDiff,lineAnnotations})}syncEditSessionAnnotationsFromEditor(lineAnnotations){const session=this.editSession?.annotations;return session==null||lineAnnotations===session.current?!1:(session.current=lineAnnotations,this.renderedData!=null&&(this.renderedData.lineAnnotations=lineAnnotations),this.pendingData=void 0,this.hunksRenderer.setLineAnnotations(lineAnnotations),this.renderAnnotations(),!0)}canPartiallyRender(forceRender,annotationsChanged,didContentChange){return!(forceRender||annotationsChanged||didContentChange||typeof this.options.hunkSeparators=="function")}setSelectedLines(range,options){this.lineStateRefreshPending?this.deferredSelectedLines=[range,options]:this.interactionManager.setSelection(range,options)}setEditorActiveLine(lineNumber,options){this.lineStateRefreshPending?this.deferredEditorActiveLine=[lineNumber,options]:this.interactionManager.setEditorActiveLine(lineNumber,{lineNumberOnly:options?.lineNumberOnly,side:options?.side??"additions"})}flushDeferredLineState(){const{deferredEditorActiveLine:editorActiveLine,deferredSelectedLines:selectedLines}=this;this.lineStateRefreshPending=!1,this.deferredEditorActiveLine=void 0,this.deferredSelectedLines=void 0,editorActiveLine!=null&&this.setEditorActiveLine(...editorActiveLine),selectedLines!=null&&this.interactionManager.setSelection(...selectedLines)}flushManagers(){if(!this.managersDirty||this.pre==null){this.managersDirty=!1;return}const{diffStyle="split",overflow="scroll"}=this.options;this.interactionManager.setup(this.pre),this.resizeManager.setup(this.pre,{disableAnnotations:overflow==="wrap",columnVariables:this.shouldApplyColumnVariables(overflow)?"apply":"measure"}),overflow==="scroll"&&diffStyle==="split"?this.scrollSyncManager.setup(this.pre,this.codeDeletions,this.codeAdditions):this.scrollSyncManager.cleanUp(),this.managersDirty=!1}shouldApplyColumnVariables(overflow){return typeof this.options.hunkSeparators=="function"?!0:overflow==="scroll"&&(this.lineAnnotations.length>0||this.pre?.hasAttribute("data-has-merge-conflict")===!0)}getCodeScrollLeft(){return Math.max(this.codeUnified?.scrollLeft??0,this.codeDeletions?.scrollLeft??0,this.codeAdditions?.scrollLeft??0)}setCodeScrollLeft(position){this.codeUnified!=null&&(this.codeUnified.scrollLeft=position),this.codeAdditions!=null&&(this.codeAdditions.scrollLeft=position),this.codeDeletions!=null&&(this.codeDeletions.scrollLeft=position)}__getEffectiveCodeOptions(){return{...this.options,...this.hunksRenderer.getEffectiveCodeOptions()}}cleanUp(recycle=!1){const{editor}=this;dequeueRender(this.handleEditSessionRender),this.emitPostRender(!0),editor?.cleanUp(recycle?"recycle":"discard"),recycle||(this.editor=void 0),this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.scrollSyncManager.cleanUp(),this.managersDirty=!1,this.workerManager?.unsubscribeToThemeChanges(this),this.renderRange=void 0,recycle||(this.pendingFiles=void 0),this.isComponentManaged||this.fileContainer?.remove(),this.fileContainer=void 0,this.mounted=!1,recycle||(this.renderedData=void 0,this.pendingData=void 0),this.clearAuxiliaryNodes(),this.annotationCache.clear(),this.pre?.remove(),this.pre=void 0,this.codeUnified=void 0,this.codeDeletions=void 0,this.codeAdditions=void 0,this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.appliedPreAttributes=void 0,this.headerElement?.remove(),this.headerElement=void 0,this.clearHeaderSlots(),this.placeHolder?.remove(),this.placeHolder=void 0,this.headerCache.lastRenderedHTML=void 0,recycle||this.clearReusableHeader(),this.errorWrapper?.remove(),this.errorWrapper=void 0,this.spriteSVG=void 0,this.lastRowCount=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,recycle?this.hunksRenderer.recycle():(this.hunksRenderer.cleanUp(),this.workerManager=void 0,this.fileDiff=void 0,this.editSession=void 0,this.deletionFile=void 0,this.additionFile=void 0),this.refreshViewTimeout!=null&&(clearTimeout(this.refreshViewTimeout),this.refreshViewTimeout=void 0),this.lineStateRefreshPending=!1,this.deferredEditorActiveLine=void 0,this.deferredSelectedLines=void 0,this.enabled=!1}virtualizedSetup(){this.enabled=!0,this.workerManager?.subscribeToThemeChanges(this)}hydrate({fileContainer,prerenderedHTML,preventEmit=!1,lineAnnotations,fileDiff,...fileInputProps}){if(!this.enabled)throw new Error("FileDiff.hydrate: attempting to call hydrate after cleaned up");if(this.fileContainer!=null)throw new Error("FileDiff.hydrate: hydrate can only be called before the instance has rendered or hydrated");const fileInput=getDiffFileInput(fileInputProps,"FileDiff.hydrate"),oldFile=fileInput?.oldFile,newFile=fileInput?.newFile;this.hydrateElements(fileContainer,prerenderedHTML);const forceEditorRender=this.editor!=null;forceEditorRender||shouldRenderCode(this.pre,hasDiffContent({fileDiff,oldFile,newFile}),this.options.collapsed)||shouldRenderHeader(this.headerElement,hasDiffHeaderContent({fileDiff,oldFile,newFile}),this.options.disableFileHeader)?this.render({...fileInputProps,fileContainer,lineAnnotations,fileDiff,forceRender:forceEditorRender||fileInputProps.forceRender,preventEmit:!0}):this.hydrationSetup({fileDiff,lineAnnotations,...fileInput}),preventEmit||this.emitPostRender()}hydrateElements(fileContainer,prerenderedHTML){this.fileContainer!==fileContainer&&this.emitPostRender(!0),prerenderHTMLIfNecessary(fileContainer,prerenderedHTML);for(const element of fileContainer.shadowRoot?.children??[]){if(element instanceof SVGElement){this.spriteSVG=element;continue}if(element instanceof HTMLElement){if(element instanceof HTMLPreElement){this.pre=element;for(const code of element.children)!(code instanceof HTMLElement)||code.tagName.toLowerCase()!=="code"||("deletions"in code.dataset&&(this.codeDeletions=code),"additions"in code.dataset&&(this.codeAdditions=code),"unified"in code.dataset&&(this.codeUnified=code));continue}if("diffsHeader"in element.dataset){this.headerElement=element;continue}if(element instanceof HTMLStyleElement&&element.hasAttribute("data-theme-css")){this.themeCSSStyle=element;continue}if(element instanceof HTMLStyleElement&&element.hasAttribute("data-unsafe-css")){this.unsafeCSSStyle=element,this.appliedUnsafeCSS=element.textContent;continue}}}this.pre!=null&&(this.syncCodeNodesFromPre(this.pre),this.pre.removeAttribute("data-dehydrated")),this.fileContainer=fileContainer,this.hydrateMeasuredScrollbar()}hydrationSetup({fileDiff,oldFile,newFile,lineAnnotations}){const hydratedAnnotations=lineAnnotations??this.getLatestAnnotations();this.pendingData=void 0,this.additionFile=newFile,this.deletionFile=oldFile,this.fileDiff=fileDiff??(oldFile!==void 0&&newFile!==void 0?parseDiffFromFile(oldFile,newFile,this.options.parseDiffOptions):void 0),this.renderedData=this.fileDiff!=null?{fileDiff:this.fileDiff,lineAnnotations:hydratedAnnotations}:void 0,this.fileDiff!=null&&this.adoptRenderData(this.fileDiff),this.pre!=null&&(this.syncInteractionOptions(),this.hunksRenderer.hydrate(this.fileDiff),this.renderAnnotations(),this.renderGutterUtility(),this.injectUnsafeCSS(),this.managersDirty=!0,this.flushManagers())}rerender(){!this.enabled||this.getInputDiff()==null&&this.additionFile==null&&this.deletionFile==null||this.requestRender()||this.render({forceRender:!0,renderRange:this.renderRange})}requestRender(){const{requestOwnerRender}=this;return this.editSession!=null||requestOwnerRender==null?!1:(this.forceRenderOverride=!0,requestOwnerRender(),!0)}get isComponentManaged(){return this.requestOwnerRender!=null}onThemeChange(){this.hunksRenderer.clearRenderCache(),this.rerender()}handleExpandHunk=(hunkIndex,direction,expansionLineCountOverride)=>{this.expandHunk(hunkIndex,direction,expansionLineCountOverride)};expandHunk=(hunkIndex,direction,expansionLineCountOverride)=>{this.loadFilesIfNecessary(),this.hunksRenderer.expandHunk(hunkIndex,direction,expansionLineCountOverride),this.rerender()};loadFilesIfNecessary(){const fileDiff=this.getInputDiff(),{loadDiffFiles}=this.options;if(fileDiff==null||!canHydrateDiff(fileDiff)||this.pendingFiles?.fileDiff===fileDiff)return;if(loadDiffFiles==null)throw new Error("FileDiff: loadDiffFiles is required to load full files for a partial diff");const promise=this.loadFilesForDiff(fileDiff,loadDiffFiles),pendingFiles=this.pendingFiles={fileDiff,promise},clearPendingFiles=()=>{this.pendingFiles===pendingFiles&&(this.pendingFiles=void 0)};pendingFiles.promise=promise.finally(clearPendingFiles)}__canAttachEditor(){const fileDiff=this.getInputDiff();return fileDiff!=null&&!fileDiff.isPartial}async prepareForEditing(){if(this.__canAttachEditor())return;const pending=this.__prepareForEditing();if(pending==null){const fileDiff=this.getInputDiff();throw fileDiff?.isPartial===!0&&!canHydrateDiff(fileDiff)?new Error("FileDiff.prepareForEditing: this partial diff cannot be hydrated; provide a complete diff"):new Error("FileDiff.prepareForEditing: a partial diff requires loadDiffFiles")}if(await pending,!this.__canAttachEditor())throw new Error("FileDiff.prepareForEditing: the diff did not finish loading")}__prepareForEditing(){if(this.__canAttachEditor())return;const fileDiff=this.getInputDiff();if(fileDiff?.isPartial===!0&&!canHydrateDiff(fileDiff))throw new Error("FileDiff: this partial diff cannot be hydrated; provide a complete diff to edit");return this.loadFilesIfNecessary(),this.pendingFiles?.promise}async loadFilesForDiff(fileDiff,loadDiffFiles){try{const files=await loadDiffFiles(fileDiff);if(this.getInputDiff()!==fileDiff)return;await this.handleFilesLoaded(fileDiff,files)}catch(error){if(this.options.disableErrorHandling===!0)throw error;console.error(error)}}async handleFilesLoaded(expectedDiff,files){if(!(this.getInputDiff()!==expectedDiff||!expectedDiff.isPartial)){if(hydratePartialDiff("merge",expectedDiff,files,this.options.parseDiffOptions),this.setHydratedState(files),this.installHydratedSessionDiff(expectedDiff)){this.rerender();return}await awaitWithTimeout(()=>this.primeHighlightCache(expectedDiff)),!(!this.enabled||this.getInputDiff()!==expectedDiff)&&this.rerender()}}installHydratedSessionDiff(expectedDiff){if(expectedDiff.isPartial)throw new Error("FileDiff.installHydratedSessionDiff: diffs cannot be partial for editing");return this.getInputDiff()!==expectedDiff?!1:this.editSession?.outgoingDiff!=null?(this.installEditSession(expectedDiff),!0):!1}updateInputDiff(incomingDiff,lineAnnotations){if(areDiffTargetsEqual(this.getInputDiff(),incomingDiff))return!1;const previousAnnotations=this.getLatestAnnotations();this.fileDiff=incomingDiff;const{editSession:previousSession}=this,outgoingDiff=previousSession?.outgoingDiff??previousSession?.diff;return previousSession!=null&&(incomingDiff.isPartial?previousSession.inputDiff=incomingDiff:this.installEditSession(incomingDiff),this.editSession!=null&&(this.editSession.outgoingDiff=outgoingDiff)),this.editSession?.annotations!=null&&lineAnnotations!=null&&(this.editSession.annotations=adoptEditSessionAnnotations(lineAnnotations,getLineAnnotationName,this.editSession.annotations)),this.pendingData={fileDiff:this.editSession?.diff??incomingDiff,lineAnnotations:this.editSession?.annotations?.current??lineAnnotations??previousAnnotations},outgoingDiff!=null&&incomingDiff.isPartial&&this.loadFilesIfNecessary(),!0}installEditSession(inputDiff,retainedDocument,retainedSession){const inputContents=inputDiff.additionLines.join(""),retainedLines=retainedDocument!=null?splitFileContents$1(retainedDocument.contents):void 0,restoreRetainedSession=retainedSession!=null&&canRestoreDiffSession(retainedSession,inputDiff);if(retainedSession!=null&&!restoreRetainedSession)throw new Error("FileDiff: retained session cannot resume against a different old file");if(retainedDocument!=null&&retainedDocument.contents!==inputContents&&!restoreRetainedSession)throw new Error("FileDiff: retained edits are missing their diff session state");const usesInputDocument=retainedDocument==null||retainedDocument.name===inputDiff.name&&retainedDocument.lang===inputDiff.lang&&retainedDocument.contents===inputContents,sessionDiff=createEditSessionDiff(inputDiff);retainedDocument!=null&&retainedLines!=null&&!usesInputDocument&&(sessionDiff.name=retainedDocument.name,sessionDiff.lang=retainedDocument.lang),restoreRetainedSession&&retainedSession!=null&&retainedDocument!=null&&retainedLines!=null&&(sessionDiff.additionLines=retainedLines,sessionDiff.additionCharacterCount=retainedDocument.contents.length,sessionDiff.type=retainedSession.type,sessionDiff.hunks=retainedSession.hunks,sessionDiff.editSessionDirty=!0,recomputeDiffRenderLineCounts(sessionDiff));const annotations=this.editSession?.annotations??adoptEditSessionAnnotations(this.getLatestAnnotations(),getLineAnnotationName);this.editSession={diff:sessionDiff,inputDiff,annotations,outgoingDiff:this.editSession?.outgoingDiff},this.pendingData={fileDiff:sessionDiff,lineAnnotations:annotations.current},this.hunksRenderer.beginEditSession(sessionDiff,usesInputDocument&&!restoreRetainedSession?inputDiff:void 0)}setHydratedState(files){this.deletionFile=files.oldFile,this.additionFile=files.newFile,this.workerManager?.cleanUpTasks(this.hunksRenderer),this.hunksRenderer.clearRenderCache()}render({fileDiff,deferManagers=!1,forceRender=!1,preventEmit=!1,lineAnnotations,fileContainer,containerWrapper,renderRange,...fileInputProps}){if(!this.enabled)throw new Error("FileDiff.render: attempting to call render after cleaned up");forceRender=this.forceRenderOverride??forceRender,this.forceRenderOverride=void 0;const fileInput=getDiffFileInput(fileInputProps,"FileDiff.render"),oldFile=fileInput?.oldFile,newFile=fileInput?.newFile;this.editor?.__postponeBgTokenizeToNextFrame();const{collapsed=!1,themeType="system",expandUnchanged=!1}=this.options,nextRenderRange=collapsed?void 0:renderRange,themeChanged=this.hasThemeChanged(),hasFileInput=fileInput!=null,filesDidChange=hasFileInput&&(!areOptionalFilesEqual$1(oldFile,this.deletionFile)||!areOptionalFilesEqual$1(newFile,this.additionFile));let diffDidChange=fileDiff!=null&&!areDiffTargetsEqual(fileDiff,this.getInputDiff());const annotationsChanged=lineAnnotations!=null&&(lineAnnotations.length>0||this.getLatestAnnotations().length>0)?this.isNewAnnotations(lineAnnotations):!1;if(!collapsed&&areRenderRangesEqual(nextRenderRange,this.renderRange)&&!forceRender&&!annotationsChanged&&!themeChanged&&(fileDiff!=null&&!diffDidChange||fileDiff==null&&!filesDidChange)){const rendered=this.applyCachedThemeState(themeType);return rendered&&this.finalizeRender(),rendered}let nextParsedFileDiff;fileDiff==null&&hasFileInput&&(filesDidChange||this.getInputDiff()==null)&&(nextParsedFileDiff=parseDiffFromFile(fileInput.oldFile,fileInput.newFile,this.options.parseDiffOptions));const{renderRange:previousRenderRange}=this;this.renderRange=nextRenderRange,hasFileInput?(this.deletionFile=oldFile,this.additionFile=newFile):fileDiff!=null&&(this.deletionFile=void 0,this.additionFile=void 0),fileDiff!=null&&diffDidChange?this.updateInputDiff(fileDiff,lineAnnotations):nextParsedFileDiff!=null&&(diffDidChange=!0,this.updateInputDiff(nextParsedFileDiff,lineAnnotations)),diffDidChange&&this.clearReusableHeader(),lineAnnotations!=null&&this.setLineAnnotations(lineAnnotations);const workingDiff=this.getWorkingDiff();if(workingDiff==null)return!1;workingDiff.editSessionDirty===!0&&this.shouldSelfHealEditSession()&&(finishEditSessionForDiff(workingDiff,this.options.parseDiffOptions),this.hunksRenderer.refreshHighlightedResult()),expandUnchanged&&this.loadFilesIfNecessary(),this.hunksRenderer.setOptions(this.getHunksRendererOptions(this.options)),this.syncInteractionOptions(),this.prepareRenderData(this.hunksRenderer.getDiffForNextRender(workingDiff));const{disableErrorHandling=!1,disableFileHeader=!1}=this.options;if(disableFileHeader&&(this.headerElement!=null&&(this.headerElement.remove(),this.headerElement=void 0,this.headerCache.lastRenderedHTML=void 0),this.clearHeaderSlots()),fileContainer=this.getOrCreateFileContainer(fileContainer,containerWrapper),this.applyCachedThemeState(themeType),collapsed){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{const hunksResult=this.hunksRenderer.renderDiff(workingDiff,EMPTY_RENDER_RANGE);hunksResult!=null&&this.applyThemeState(fileContainer,hunksResult.themeStyles,themeType,hunksResult.baseThemeType),hunksResult?.headerElement!=null&&this.applyHeaderToDOM(hunksResult.headerElement,fileContainer,hunksResult.fileDiff),this.renderSeparators([]),this.adoptRenderData(hunksResult?.fileDiff??workingDiff),this.injectUnsafeCSS()}catch(error){if(disableErrorHandling)throw error;console.error(error),error instanceof Error&&this.applyErrorToDOM(error,fileContainer)}return this.finalizeRender(),preventEmit||this.emitPostRender(),!0}try{const pre=this.getOrCreatePreNode(fileContainer);if(this.canPartiallyRender(forceRender,annotationsChanged,filesDidChange||diffDidChange||themeChanged||!areDiffTargetsEqual(this.getRenderedDiff(),workingDiff))&&this.applyPartialRender({fileDiff:workingDiff,previousRenderRange,renderRange:nextRenderRange})){const renderedDiff=this.getRenderedDiff();renderedDiff!=null&&this.adoptRenderData(renderedDiff)}else{const hunksResult=this.hunksRenderer.renderDiff(workingDiff,nextRenderRange);if(hunksResult==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.isWorkingPool()&&this.workerManager.initialize().catch(()=>{}).then(()=>this.rerender()),!1;this.applyThemeState(fileContainer,hunksResult.themeStyles,themeType,hunksResult.baseThemeType),hunksResult.headerElement!=null&&this.applyHeaderToDOM(hunksResult.headerElement,fileContainer,hunksResult.fileDiff),hunksResult.additionsContentAST!=null||hunksResult.deletionsContentAST!=null||hunksResult.unifiedContentAST!=null?this.applyHunksToDOM(pre,hunksResult):this.pre!=null&&(this.pre.remove(),this.pre=void 0),this.renderSeparators(hunksResult.hunkData),this.adoptRenderData(hunksResult.fileDiff)}this.applyBuffers(pre,nextRenderRange),this.injectUnsafeCSS(),this.renderAnnotations(),this.renderGutterUtility(),this.managersDirty=!0,deferManagers||this.flushManagers(),this.finalizeRender(),this.editor!=null&&this.syncRenderViewToEditor()}catch(error){if(disableErrorHandling)throw error;console.error(error),error instanceof Error&&this.applyErrorToDOM(error,fileContainer)}return preventEmit||this.emitPostRender(),!0}finalizeRender(){}emitPostRender(unmount=!1){const{fileContainer,options:{onPostRender}}=this;if(unmount){if(!this.mounted||(this.mounted=!1,fileContainer==null))return;this.options.onPostRender?.(fileContainer,this,"unmount");return}if(fileContainer==null)return;const phase=this.mounted?"update":"mount";this.mounted=!0,onPostRender?.(fileContainer,this,phase)}getInputDiff(){return this.fileDiff}getWorkingDiff(fallbackDiff=this.fileDiff){return this.editSession?.diff??fallbackDiff}getRenderedDiff(){return this.renderedData?.fileDiff}__getNextRenderData({fileDiff,lineAnnotations}){const sessionAnnotations=this.editSession?.annotations;if(sessionAnnotations!=null)return{fileDiff,lineAnnotations:lineAnnotations!=null&&this.isNewAnnotations(lineAnnotations)?lineAnnotations:sessionAnnotations.provided};const workingDiff=this.getWorkingDiff(fileDiff)??fileDiff,nextDiff=this.hunksRenderer.getDiffForNextRender(workingDiff);return{fileDiff:nextDiff,lineAnnotations:lineAnnotations!=null&&areDiffTargetsEqual(nextDiff,workingDiff)?lineAnnotations:this.getAnnotationsForDiff(nextDiff)}}prepareRenderData(fileDiff){this.hunksRenderer.setLineAnnotations(this.getAnnotationsForDiff(fileDiff))}adoptRenderData(fileDiff){const{pendingData}=this,matchesPending=pendingData!=null&&areDiffTargetsEqual(fileDiff,pendingData.fileDiff);this.renderedData={fileDiff,lineAnnotations:matchesPending?pendingData.lineAnnotations:this.lineAnnotations},matchesPending&&(this.pendingData=void 0)}syncRenderViewToEditor(){const{editor,fileContainer}=this,lineAnnotations=this.getLatestAnnotations(),renderRange=this.computeEditorRenderRange(this.renderRange),fileDiff=this.getWorkingDiff();if(editor==null||fileContainer==null||fileDiff==null||fileDiff.isPartial)return;const sync=highlighter2=>{if(!this.enabled||this.editor!==editor||this.fileContainer!==fileContainer||this.getWorkingDiff()!==fileDiff)return;const replacement=this.editSession?.outgoingDiff,inputDiff=this.getInputDiff(),externalDocument=replacement!=null&&inputDiff!=null&&replacement!==fileDiff,resetHistory=externalDocument&&replacement!=null&&inputDiff!=null?shouldResetUndoState(replacement,inputDiff):!1;editor.__syncRenderView({highlighter:highlighter2,fileContainer,fileDiff,lineAnnotations,renderRange,externalDocument,resetHistory})},theme=this.getTheme(),lang=fileDiff.lang??getFiletypeFromFileName(fileDiff.name),highlighter=getHighlighterIfLoaded({theme,lang});highlighter!=null?sync(highlighter):getSharedHighlighter({themes:getThemes(theme),langs:["text",lang],preferredHighlighter:resolvePreferredHighlighter(this.workerManager,this.options)}).then(sync).catch(error=>{error instanceof HighlighterDisposedError||console.error(error)})}computeEditorRenderRange(renderRange){const fileDiff=this.getWorkingDiff();if(renderRange==null||fileDiff==null||isDefaultRenderRange(renderRange))return renderRange;const{diffStyle="split",expandUnchanged=!1,collapsedContextThreshold=1}=this.options;let firstLineNumber,lastLineNumber;return iterateOverDiff({diff:fileDiff,diffStyle,startingLine:renderRange.startingLine,totalLines:renderRange.totalLines,expandedHunks:expandUnchanged?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold,callback:({additionLine})=>{additionLine!=null&&(firstLineNumber??=additionLine.lineNumber,lastLineNumber=additionLine.lineNumber)}}),firstLineNumber==null||lastLineNumber==null?{...renderRange,startingLine:0,totalLines:0}:{...renderRange,startingLine:firstLineNumber-1,totalLines:lastLineNumber-firstLineNumber+1}}__acknowledgeDocumentUpdate(){this.editSession!=null&&(this.editSession.outgoingDiff=void 0)}__acceptEditorChange(event){const{lineAnnotations}=event;lineAnnotations!=null&&this.syncEditSessionAnnotationsFromEditor(lineAnnotations)}emitEditChange(event){const{onEditChange}=this.options;onEditChange?.(event)}__captureDocumentSessionState(clone=!0){const fileDiff=this.getInputDiff();let{diff:sessionDiff,outgoingDiff}=this.editSession??{};if(outgoingDiff!=null&&fileDiff!=null){if(!fileDiff.isPartial&&shouldResetUndoState(outgoingDiff,fileDiff))return;sessionDiff=outgoingDiff}if(!(sessionDiff==null||sessionDiff.isPartial))return{diffSession:{oldFile:sessionDiff.type!=="new"?{name:sessionDiff.prevName??sessionDiff.name,lines:clone?[...sessionDiff.deletionLines]:sessionDiff.deletionLines}:null,type:sessionDiff.type,hunks:clone?cloneHunks(sessionDiff.hunks):sessionDiff.hunks},hasChanges:sessionDiff.editSessionDirty===!0}}__attachEditor(editor){if(this.type!=="file-diff")throw new Error(`FileDiff.__attachEditor: cannot attach an editor to a "${this.type}" diff`);if(this.editor!=null)throw new Error("FileDiff.__attachEditor: an editor is already attached");if(!this.__canAttachEditor())throw new Error("FileDiff.__attachEditor: a complete diff is required before editing");const detach=()=>{this.editor=void 0,this.finishEditSession()};try{return this.resumeEditorRendering(editor),detach}catch(error){throw detach(),error}}__resumeEditor(editor){if(this.editor!==editor)throw new Error("FileDiff.__resumeEditor: editor association changed");this.resumeEditorRendering(editor)}resumeEditorRendering(editor){const inputDiff=this.getInputDiff(),pendingReplacement=this.editSession?.outgoingDiff;pendingReplacement!=null&&inputDiff!=null&&!inputDiff.isPartial&&this.editSession?.diff===pendingReplacement&&this.installEditSession(inputDiff);const initialInputDiff=this.editSession==null&&inputDiff!=null&&!inputDiff.isPartial?inputDiff:void 0;initialInputDiff!=null?this.installEditSession(initialInputDiff,editor.__getDocumentContents(getAdditionFile(initialInputDiff)),editor.__getDocumentSessionState()):this.editSession!=null&&this.hunksRenderer.beginEditSession(this.editSession.diff),this.editor=editor,this.getInputDiff()?.isPartial===!0&&this.loadFilesIfNecessary();const editSessionDiff=this.editSession?.diff;this.hunksRenderer.editorRenderReady()?(editSessionDiff!=null&&this.hunksRenderer.diffCache===editSessionDiff&&this.adoptRenderData(editSessionDiff),this.syncRenderViewToEditor()):this.rerender()}finishEditSession(){this.hunksRenderer.endEditSession(),this.finalizeEditSessionHunks()}__completeEditSession(editor,mode){this.settleEditSession(mode==="install",editor)}settleEditSession(installResult,editor){const{editSession}=this;if(editSession==null)return;const{diff:editSessionDiff,inputDiff,annotations:editSessionAnnotations}=editSession,inputAnnotations=editSessionAnnotations?.provided??this.lineAnnotations;if(this.editor!=null)throw new Error("FileDiff.__completeEditSession: detach the editor before completing the session");this.hunksRenderer.endEditSession(),this.finalizeEditSessionHunks();const sessionAnnotationsCurrent=editSessionAnnotations?.current;let acceptedDiff,acceptedOldFile=null,acceptedNewFile=null,failed=!1,failure;if(editor==null)throw new Error("FileDiff.__completeEditSession: editor is required for completion");const completedDiff=cloneFileDiffMetadata(editSessionDiff),newFile={name:completedDiff.name,contents:completedDiff.additionLines.join("")};completedDiff.lang!=null&&(newFile.lang=completedDiff.lang);const event={fileDiff:completedDiff,editor,originalFileDiff:inputDiff,oldFile:completedDiff.type==="new"?null:{name:completedDiff.prevName??completedDiff.name,contents:completedDiff.deletionLines.join("")},newFile,lineAnnotations:sessionAnnotationsCurrent,originalLineAnnotations:inputAnnotations};Object.freeze(event);try{if(editor.__emitEditComplete(event),this.options.onEditComplete?.(event)==="accept"){if(completedDiff.cacheKey!=null&&completedDiff.cacheKey===inputDiff.cacheKey)throw new Error("FileDiff.__completeEditSession: an accepted diff must not reuse the replaced diff cacheKey");acceptedDiff=completedDiff,acceptedOldFile=event.oldFile,acceptedNewFile=event.newFile}}catch(error){failed=!0,failure=error}if(installResult&&acceptedDiff!=null&&this.additionFile!=null&&(this.deletionFile=acceptedOldFile,this.additionFile=acceptedNewFile),this.editSession=void 0,this.fileDiff=installResult&&acceptedDiff!=null?acceptedDiff:inputDiff,this.pendingData={fileDiff:this.fileDiff,lineAnnotations:installResult&&acceptedDiff!=null?sessionAnnotationsCurrent??inputAnnotations:inputAnnotations},installResult&&this.fileContainer!=null&&this.rerender(),failed)throw failure}finalizeEditSessionHunks(){const fileDiff=this.getWorkingDiff();if(fileDiff==null||fileDiff.editSessionDirty!==!0)return!1;const{collapsedContextThreshold=1}=this.options,anchors=captureExpansionAnchors(fileDiff,this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold);return finishEditSessionForDiff(fileDiff,this.options.parseDiffOptions),this.hunksRenderer.setExpandedHunksMap(rebuildExpansionFromAnchors(fileDiff,anchors)),this.hunksRenderer.refreshHighlightedResult(),this.escalateEditSessionRender(),!0}applyDocumentChange(textDocument,newLineAnnotations){const editSessionDiff=this.editSession?.diff;if(editSessionDiff==null)throw new Error("FileDiff.applyDocumentChange: requires an active edit session");this.detachAdditionLines(),this.hunksRenderer.beginEditSession(editSessionDiff),this.hunksRenderer.applyDocumentChange(textDocument),newLineAnnotations!=null&&this.syncEditSessionAnnotationsFromEditor(newLineAnnotations),this.rerender(),this.interactionManager.setSelectionDirty()}applySuspendedDocumentChange(textDocument,newLineAnnotations){this.applyDocumentChange(textDocument,newLineAnnotations),this.hunksRenderer.clearRenderCache()}updateRenderCache(dirtyLines,themeType,options={}){const editSessionDiff=this.editSession?.diff;if(editSessionDiff==null)throw new Error("FileDiff.updateRenderCache: requires an active edit session");this.detachAdditionLines(),this.hunksRenderer.beginEditSession(editSessionDiff);const{shouldRefreshDiffsView,lineCountChangeInFlight}=options;if(this.hunksRenderer.updateRenderCache(dirtyLines,themeType,lineCountChangeInFlight,options.changedDocumentLines,options.documentLineCount)){this.refreshViewTimeout!=null&&(clearTimeout(this.refreshViewTimeout),this.refreshViewTimeout=void 0),this.lineStateRefreshPending=!0,this.escalateEditSessionRender();return}shouldRefreshDiffsView===!0&&(this.refreshViewTimeout!=null&&clearTimeout(this.refreshViewTimeout),this.lineStateRefreshPending=!0,this.refreshViewTimeout=setTimeout(()=>{this.refreshViewTimeout=void 0,this.options.diffStyle==="split"?this.refreshSplitDiffView():this.refreshUnifiedDiffView(),this.flushDeferredLineState()},150))}detachAdditionLines(){const{diff:editSessionDiff,inputDiff}=this.editSession??{};editSessionDiff!=null&&(editSessionDiff.additionLines===inputDiff?.additionLines||editSessionDiff.additionLines===editSessionDiff.deletionLines)&&(editSessionDiff.additionLines=[...editSessionDiff.additionLines])}isLineRenderable(lineNumber){const fileDiff=this.getRenderedDiff();if(fileDiff==null)return!0;const{expandUnchanged=!1,collapsedContextThreshold=1}=this.options;return isAdditionLineRenderable({fileDiff,lineNumber,expandedHunks:expandUnchanged?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold})}getNearestRenderableLine(lineNumber,direction){const fileDiff=this.getRenderedDiff();if(fileDiff==null)return lineNumber;const{expandUnchanged=!1,collapsedContextThreshold=1}=this.options;return getNearestRenderableAdditionLine({fileDiff,lineNumber,direction,expandedHunks:expandUnchanged?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold})}revealLine(lineNumber){const fileDiff=this.getRenderedDiff(),{expandUnchanged=!1,collapsedContextThreshold=1,expansionLineCount=100}=this.options;if(fileDiff==null||fileDiff.isPartial||expandUnchanged)return!1;const expandedHunks=this.hunksRenderer.getExpandedHunksMap();for(const[hunkIndex,hunk]of fileDiff.hunks.entries()){const[hunkStart,hunkEnd]=getHunkAdditionLineRange(hunk);if(lineNumber<hunkStart){const region=getExpandedRegion({isPartial:fileDiff.isPartial,rangeSize:hunk.collapsedBefore,expandedHunks,hunkIndex,collapsedContextThreshold}),gapStart=hunkStart-region.rangeSize;if(region.renderAll||lineNumber<gapStart+region.fromStart||lineNumber>=hunkStart-region.fromEnd)return!1;const fromStartDistance=lineNumber-(gapStart+region.fromStart)+1,fromEndDistance=hunkStart-region.fromEnd-lineNumber;return fromStartDistance<=fromEndDistance?this.expandHunk(hunkIndex,"up",fromStartDistance+expansionLineCount):this.expandHunk(hunkIndex,"down",fromEndDistance+expansionLineCount),!0}if(lineNumber<hunkEnd)return!1}const trailingRegion=getTrailingExpandedRegion({fileDiff,hunkIndex:fileDiff.hunks.length-1,expandedHunks,collapsedContextThreshold,errorPrefix:"FileDiff.revealLine"});if(trailingRegion==null||trailingRegion.renderAll)return!1;const lastHunk=fileDiff.hunks[fileDiff.hunks.length-1],[,trailingStart]=getHunkAdditionLineRange(lastHunk);return lineNumber<trailingStart+trailingRegion.fromStart||lineNumber>=trailingStart+trailingRegion.rangeSize?!1:(this.expandHunk(fileDiff.hunks.length,"up",lineNumber-(trailingStart+trailingRegion.fromStart)+1+expansionLineCount),!0)}shouldSelfHealEditSession(){return this.editor==null}escalateEditSessionRender(){queueRender(this.handleEditSessionRender)}handleEditSessionRender=()=>{this.rerender(),this.flushDeferredLineState()};removeRenderedCode(){this.resizeManager.cleanUp(),this.scrollSyncManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.codeUnified?.remove(),this.codeUnified=void 0,this.codeDeletions?.remove(),this.codeDeletions=void 0,this.codeAdditions?.remove(),this.codeAdditions=void 0,this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0}clearAuxiliaryNodes(){for(const{element}of this.separatorCache.values())element.remove();this.separatorCache.clear();for(const{element}of this.annotationCache.values())element.remove();this.annotationCache.clear(),this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0}renderPlaceholder(height){if(this.fileContainer==null)return!1;if(this.emitPostRender(!0),this.cleanChildNodes(),this.placeHolder==null){const shadowRoot=this.fileContainer.shadowRoot??this.fileContainer.attachShadow({mode:"open"});this.placeHolder=document.createElement("div"),this.placeHolder.dataset.placeholder="",shadowRoot.appendChild(this.placeHolder)}return this.setPlaceholderHeight(height)}setPlaceholderHeight(height){return this.placeHolder==null?!1:(this.placeHolder.style.setProperty("height",`${height}px`),!0)}async primeHighlightCache(fileDiff=this.getInputDiff()){const{workerManager}=this;if(fileDiff==null||workerManager==null||!workerManager.isWorkingPool()||fileDiff.cacheKey==null||isDiffPlainText(fileDiff))return;const tokenizeMaxLength=this.options.tokenizeMaxLength??1e5;Math.max(fileDiff.additionLines.length,fileDiff.deletionLines.length)>tokenizeMaxLength||await workerManager.primeDiffHighlightCache(fileDiff).catch(error=>{isHandledWorkerPoolError(error)||console.error(error)})}cleanChildNodes(){this.resizeManager.cleanUp(),this.scrollSyncManager.cleanUp(),this.interactionManager.cleanUp(),this.clearAuxiliaryNodes(),this.bufferAfter?.remove(),this.bufferBefore?.remove(),this.codeAdditions?.remove(),this.codeDeletions?.remove(),this.codeUnified?.remove(),this.errorWrapper?.remove(),this.headerElement?.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.codeAdditions=void 0,this.codeDeletions=void 0,this.codeUnified=void 0,this.errorWrapper=void 0,this.headerElement=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.headerCache.lastRenderedHTML=void 0,this.lastRowCount=void 0,this.mounted=!1}renderSeparators(hunkData){const{hunkSeparators}=this.options;if(this.isComponentManaged||this.fileContainer==null||typeof hunkSeparators!="function"){for(const{element}of this.separatorCache.values())element.remove();this.separatorCache.clear();return}const staleSeparators=new Map(this.separatorCache);for(const hunk of hunkData){const id=hunk.slotName;let cache=this.separatorCache.get(id);if(cache==null||!areHunkDataEqual(hunk,cache.hunkData)){cache?.element.remove();const element=document.createElement("div");element.style.display="contents",element.slot=hunk.slotName;const child=hunkSeparators(hunk,this);child!=null&&element.appendChild(child),this.fileContainer.appendChild(element),cache={element,hunkData:hunk},this.separatorCache.set(id,cache)}staleSeparators.delete(id)}for(const[id,{element}]of staleSeparators.entries())this.separatorCache.delete(id),element.remove()}renderAnnotations(){if(this.isComponentManaged||this.fileContainer==null){for(const{element}of this.annotationCache.values())element.remove();this.annotationCache.clear();return}const staleAnnotations=new Map(this.annotationCache),{renderedData,options:{renderAnnotation}}=this;if(renderAnnotation!=null&&renderedData!=null){const{fileDiff,lineAnnotations}=renderedData;for(const[index,annotation]of lineAnnotations.entries()){const name=this.getAnnotationSlotName(annotation),id=`${index}-${name}`;let cache=this.annotationCache.get(id);if(cache==null||cache.fileDiff!==fileDiff||!areDiffLineAnnotationsEqual(annotation,cache.annotation)){cache?.element.remove();const content=renderAnnotation(annotation,fileDiff);if(content==null)continue;cache={element:createAnnotationWrapperNode(name),annotation,fileDiff},cache.element.appendChild(content),this.fileContainer.appendChild(cache.element),this.annotationCache.set(id,cache)}staleAnnotations.delete(id)}}for(const[id,{element}]of staleAnnotations.entries())this.annotationCache.delete(id),element.remove()}renderGutterUtility(){const{renderGutterUtility}=this.options;if(this.fileContainer==null||renderGutterUtility==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const element=renderGutterUtility(this.interactionManager.getHoveredLine);if(element!=null&&this.gutterUtilityContent!=null)return;if(element==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const gutterUtilityContent=createGutterUtilityContentNode();gutterUtilityContent.appendChild(element),this.fileContainer.appendChild(gutterUtilityContent),this.gutterUtilityContent=gutterUtilityContent}getOrCreateFileContainer(fileContainer,parentNode){const{fileContainer:previousContainer}=this,nextContainer=fileContainer??previousContainer??document.createElement("diffs-container"),containerChanged=previousContainer!==nextContainer;return previousContainer!=null&&containerChanged&&this.editor?.__captureFocusForDOMReplacement(),containerChanged&&this.emitPostRender(!0),this.fileContainer=nextContainer,previousContainer!=null&&containerChanged&&(this.headerCache.lastRenderedHTML=void 0,this.headerElement=void 0),parentNode!=null&&this.fileContainer.parentNode!==parentNode&&parentNode.appendChild(this.fileContainer),containerChanged&&this.adoptReusableShellElements(this.fileContainer),this.ensureSpriteSVG(this.fileContainer),this.fileContainer}adoptReusableShellElements(fileContainer){const{shadowRoot}=fileContainer;if(shadowRoot!=null)for(const element of shadowRoot.children)element instanceof SVGElement?this.spriteSVG??=element:isStyleNode(element)&&element.hasAttribute("data-theme-css")?(this.themeCSSStyle??=element,this.hasAdoptedThemeCSS=!0):isStyleNode(element)&&element.hasAttribute("data-unsafe-css")&&(this.unsafeCSSStyle??=element,this.appliedUnsafeCSS??=this.options.unsafeCSS??void 0)}ensureSpriteSVG(fileContainer){const shadowRoot=fileContainer.shadowRoot??fileContainer.attachShadow({mode:"open"});if(this.spriteSVG==null){const fragment=document.createElement("div");fragment.innerHTML=SVGSpriteSheet;const firstChild=fragment.firstChild;firstChild instanceof SVGElement&&(this.spriteSVG=firstChild)}this.spriteSVG!=null&&this.spriteSVG.parentNode!==shadowRoot&&shadowRoot.appendChild(this.spriteSVG)}getOrCreatePreNode(container){const shadowRoot=container.shadowRoot??container.attachShadow({mode:"open"});return this.pre==null?(this.pre=document.createElement("pre"),this.appliedPreAttributes=void 0,this.codeUnified=void 0,this.codeDeletions=void 0,this.codeAdditions=void 0,shadowRoot.appendChild(this.pre)):this.pre.parentNode!==shadowRoot&&(this.editor?.__captureFocusForDOMReplacement(),shadowRoot.appendChild(this.pre),this.appliedPreAttributes=void 0),this.placeHolder?.remove(),this.placeHolder=void 0,this.pre}syncCodeNodesFromPre(pre){this.codeUnified=void 0,this.codeDeletions=void 0,this.codeAdditions=void 0;for(const child of Array.from(pre.children))child instanceof HTMLElement&&(child.hasAttribute("data-unified")?this.codeUnified=child:child.hasAttribute("data-deletions")?this.codeDeletions=child:child.hasAttribute("data-additions")&&(this.codeAdditions=child))}applyHeaderToDOM(headerAST,container,fileDiff){this.cleanupErrorWrapper(),this.placeHolder?.remove(),this.placeHolder=void 0;const{headerCache:{fileDiff:cachedHeaderDiff,html:cachedHeaderHTML,lastRenderedHTML}}=this,headerHTML=(fileDiff!==this.editSession?.diff&&areDiffTargetsEqual(cachedHeaderDiff,fileDiff)?cachedHeaderHTML:void 0)??hastToHtml(headerAST);if(this.headerCache.html=headerHTML,this.headerCache.fileDiff=fileDiff,headerHTML!==lastRenderedHTML){const tempDiv=document.createElement("div");tempDiv.innerHTML=headerHTML;const newHeader=tempDiv.firstElementChild;if(!(newHeader instanceof HTMLElement))return;this.headerElement!=null?container.shadowRoot?.replaceChild(newHeader,this.headerElement):container.shadowRoot?.prepend(newHeader),this.headerElement=newHeader,this.headerCache.lastRenderedHTML=headerHTML}if(this.isComponentManaged)return;const{renderCustomHeader,renderHeaderPrefix,renderHeaderFilenameSuffix,renderHeaderMetadata}=this.options;if(renderCustomHeader!=null){const content2=renderCustomHeader(fileDiff)??void 0;this.headerCustom=this.upsertHeaderSlotElement(container,this.headerCustom,CUSTOM_HEADER_SLOT_ID,content2),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0;return}const prefix=renderHeaderPrefix?.(fileDiff)??void 0,suffix=renderHeaderFilenameSuffix?.(fileDiff)??void 0,content=renderHeaderMetadata?.(fileDiff)??void 0;this.headerPrefix=this.upsertHeaderSlotElement(container,this.headerPrefix,HEADER_PREFIX_SLOT_ID,prefix),this.headerFilenameSuffix=this.upsertHeaderSlotElement(container,this.headerFilenameSuffix,HEADER_FILENAME_SUFFIX_SLOT_ID,suffix),this.headerMetadata=this.upsertHeaderSlotElement(container,this.headerMetadata,HEADER_METADATA_SLOT_ID,content),this.headerCustom?.remove(),this.headerCustom=void 0}clearReusableHeader(){this.headerCache.html=void 0,this.headerCache.fileDiff=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(container,current,slot,content){if(content==null){current?.remove();return}const element=current??this.createHeaderSlotElement(slot);return current==null&&container.appendChild(element),this.replaceHeaderSlotContent(element,content),element}replaceHeaderSlotContent(element,content){element.replaceChildren(),content instanceof Element?element.appendChild(content):element.innerText=`${content}`}createHeaderSlotElement(slot){const element=document.createElement("div");return element.slot=slot,element}injectUnsafeCSS(){const{unsafeCSS}=this.options;this.pre?.toggleAttribute("data-custom-styles",!!unsafeCSS);const shadowRoot=this.fileContainer?.shadowRoot;if(shadowRoot!=null){if(unsafeCSS==null||unsafeCSS===""){this.unsafeCSSStyle!=null&&(this.unsafeCSSStyle.remove(),this.unsafeCSSStyle=void 0),this.appliedUnsafeCSS=void 0;return}this.unsafeCSSStyle?.parentNode===shadowRoot&&this.appliedUnsafeCSS===unsafeCSS||(this.unsafeCSSStyle??=createUnsafeCSSStyleNode(),this.unsafeCSSStyle.parentNode!==shadowRoot&&shadowRoot.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=wrapUnsafeCSS(unsafeCSS),this.appliedUnsafeCSS=unsafeCSS)}}applyThemeState(container,themeStyles,themeType,baseThemeType){const shadowRoot=container.shadowRoot??container.attachShadow({mode:"open"}),effectiveThemeType=baseThemeType??themeType,currentTheme=this.getTheme(),theme=typeof currentTheme=="string"?currentTheme:{...currentTheme},scrollbarGutter=getMeasuredScrollbarGutter(shadowRoot);if(this.themeCSSStyle?.parentNode===shadowRoot&&this.appliedThemeCSS?.themeStyles===themeStyles&&this.appliedThemeCSS.themeType===effectiveThemeType&&this.appliedThemeCSS.scrollbarGutter===scrollbarGutter){this.appliedThemeCSS.theme=theme;return}if(this.hasAdoptedThemeCSS&&this.themeCSSStyle?.parentNode===shadowRoot){this.hasAdoptedThemeCSS=!1,this.appliedThemeCSS={theme,themeStyles,themeType:effectiveThemeType,baseThemeType,scrollbarGutter};return}this.themeCSSStyle=upsertHostThemeStyle({shadowRoot,currentNode:this.themeCSSStyle,themeCSS:wrapThemeCSS(themeStyles,effectiveThemeType,scrollbarGutter)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme,themeStyles,themeType:effectiveThemeType,baseThemeType,scrollbarGutter}:void 0}hydrateMeasuredScrollbar(){const shadowRoot=this.fileContainer?.shadowRoot;shadowRoot==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=patchScrollbarGutterSize(this.themeCSSStyle.textContent??"",getMeasuredScrollbarGutter(shadowRoot)))}shouldGuardRebuildScroll(){return this.editor!=null&&isSafari()}applyHunksToDOM(pre,result){this.shouldGuardRebuildScroll()?guardWebKitScrollDuringRebuild(pre,()=>this.replaceCodeColumns(pre,result)):this.replaceCodeColumns(pre,result)}applyCodeColumnsInPlace(code,ast,rowCount){const columns=this.getColumnPair(code);if(columns==null)return!1;const gutterChildren=getElementChildren(ast[0]),contentChildren=getElementChildren(ast[1]);return gutterChildren==null||contentChildren==null?!1:(columns.gutter.innerHTML=hastToHtml(gutterChildren),columns.content.innerHTML=hastToHtml(contentChildren),rowCount!==this.lastRowCount&&(columns.gutter.style.setProperty("grid-row",`span ${rowCount}`),columns.content.style.setProperty("grid-row",`span ${rowCount}`)),!0)}replaceCodeColumns(pre,result){const{overflow="scroll"}=this.options,containerSize=(this.options.hunkSeparators??"line-info")==="line-info",rowSpan=overflow==="wrap"?result.rowCount:void 0;this.cleanupErrorWrapper(),this.applyPreNodeAttributes(pre,result);let shouldReplace=!1;const codeElements=[],unifiedAST=this.hunksRenderer.renderCodeAST("unified",result),deletionsAST=this.hunksRenderer.renderCodeAST("deletions",result),additionsAST=this.hunksRenderer.renderCodeAST("additions",result);this.editor?.__captureFocusForDOMReplacement(),unifiedAST!=null?(shouldReplace=this.codeUnified==null||this.codeAdditions!=null||this.codeDeletions!=null,this.codeDeletions?.remove(),this.codeDeletions=void 0,this.codeAdditions?.remove(),this.codeAdditions=void 0,this.codeUnified=getOrCreateCodeNode({code:this.codeUnified,columnType:"unified",rowSpan,containerSize}),this.applyCodeColumnsInPlace(this.codeUnified,unifiedAST,result.rowCount)||(this.codeUnified.innerHTML=this.hunksRenderer.renderPartialHTML(unifiedAST)),codeElements.push(this.codeUnified)):deletionsAST!=null||additionsAST!=null?(deletionsAST!=null?(shouldReplace=this.codeDeletions==null||this.codeUnified!=null,this.codeUnified?.remove(),this.codeUnified=void 0,this.codeDeletions=getOrCreateCodeNode({code:this.codeDeletions,columnType:"deletions",rowSpan,containerSize}),this.applyCodeColumnsInPlace(this.codeDeletions,deletionsAST,result.rowCount)||(this.codeDeletions.innerHTML=this.hunksRenderer.renderPartialHTML(deletionsAST)),codeElements.push(this.codeDeletions)):(this.codeDeletions?.remove(),this.codeDeletions=void 0),additionsAST!=null?(shouldReplace=shouldReplace||this.codeAdditions==null||this.codeUnified!=null,this.codeUnified?.remove(),this.codeUnified=void 0,this.codeAdditions=getOrCreateCodeNode({code:this.codeAdditions,columnType:"additions",rowSpan,containerSize}),this.applyCodeColumnsInPlace(this.codeAdditions,additionsAST,result.rowCount)||(this.codeAdditions.innerHTML=this.hunksRenderer.renderPartialHTML(additionsAST)),codeElements.push(this.codeAdditions)):(this.codeAdditions?.remove(),this.codeAdditions=void 0)):(this.codeUnified?.remove(),this.codeUnified=void 0,this.codeDeletions?.remove(),this.codeDeletions=void 0,this.codeAdditions?.remove(),this.codeAdditions=void 0),codeElements.length===0?pre.textContent="":shouldReplace&&pre.replaceChildren(...codeElements),this.lastRowCount=result.rowCount}applyPartialRender({fileDiff,previousRenderRange,renderRange}){const{pre,codeUnified,codeAdditions,codeDeletions,options:{diffStyle="split"}}=this;if(pre==null||previousRenderRange==null||renderRange==null||!Number.isFinite(previousRenderRange.totalLines)||!Number.isFinite(renderRange.totalLines)||this.lastRowCount==null)return!1;const codeElements=this.getCodeColumns(diffStyle,codeUnified,codeDeletions,codeAdditions);if(codeElements==null)return!1;const previousStart=previousRenderRange.startingLine,nextStart=renderRange.startingLine,previousEnd=previousStart+previousRenderRange.totalLines,nextEnd=nextStart+renderRange.totalLines,overlapStart=Math.max(previousStart,nextStart),overlapEnd=Math.min(previousEnd,nextEnd);if(overlapEnd<=overlapStart)return!1;const trimStart=Math.max(0,overlapStart-previousStart),trimEnd=Math.max(0,previousEnd-overlapEnd),trimResult=this.trimColumns({columns:codeElements,trimStart,trimEnd,previousStart,overlapStart,overlapEnd,diffStyle});if(trimResult<0)throw new Error("FileDiff.applyPartialRender: failed to trim to overlap");if(this.lastRowCount<trimResult)throw new Error("FileDiff.applyPartialRender: trimmed beyond DOM row count");let rowCount=this.lastRowCount-trimResult;const renderChunk=(startingLine,totalLines)=>{if(!(totalLines<=0))return this.hunksRenderer.renderDiff(fileDiff,{startingLine,totalLines,bufferBefore:0,bufferAfter:0})},prependResult=renderChunk(nextStart,Math.max(overlapStart-nextStart,0));if(prependResult==null&&nextStart<overlapStart)return!1;const appendResult=renderChunk(overlapEnd,Math.max(nextEnd-overlapEnd,0));if(appendResult==null&&nextEnd>overlapEnd)return!1;const applyChunk=(result,insertPosition)=>{if(result!=null){if(diffStyle==="unified"&&!Array.isArray(codeElements))this.insertPartialHTML(diffStyle,codeElements,result,insertPosition);else if(diffStyle==="split"&&Array.isArray(codeElements))this.insertPartialHTML(diffStyle,codeElements,result,insertPosition);else throw new Error("FileDiff.applyPartialRender.applyChunk: invalid chunk application");rowCount+=result.rowCount,this.adoptRenderData(result.fileDiff)}};return this.cleanupErrorWrapper(),applyChunk(prependResult,"afterbegin"),applyChunk(appendResult,"beforeend"),this.lastRowCount!==rowCount&&(this.applyRowSpan(diffStyle,codeElements,rowCount),this.lastRowCount=rowCount),!0}insertPartialHTML(diffStyle,columns,result,insertPosition){if(diffStyle==="unified"&&!Array.isArray(columns)){const unifiedAST=this.hunksRenderer.renderCodeAST("unified",result);this.renderPartialColumn(columns,unifiedAST,insertPosition)}else if(diffStyle==="split"&&Array.isArray(columns)){const deletionsAST=this.hunksRenderer.renderCodeAST("deletions",result),additionsAST=this.hunksRenderer.renderCodeAST("additions",result);this.renderPartialColumn(columns[0],deletionsAST,insertPosition),this.renderPartialColumn(columns[1],additionsAST,insertPosition)}else throw new Error("FileDiff.insertPartialHTML: Invalid argument composition")}refreshSplitDiffView(){const fileDiff=this.getWorkingDiff();if(this.options.diffStyle!=="split"||fileDiff==null)return;const hunksResult=this.hunksRenderer.renderDiff(fileDiff,this.renderRange);if(hunksResult==null)return;const columns=this.getCodeColumns("split",this.codeUnified,this.codeDeletions,this.codeAdditions);if(!Array.isArray(columns))return;const applyLineType=(type,column)=>{if(column==null)return;const ast=this.hunksRenderer.renderCodeAST(type,hunksResult),gutterChildren=getElementChildren(ast?.[0]),contentChildren=getElementChildren(ast?.[1]);for(const[el,astChildren]of[[column.gutter,gutterChildren],[column.content,contentChildren]])if(astChildren!=null&&el.childElementCount===astChildren.length)for(let i=0;i<astChildren.length;i++){const gutterElement=el.children[i],lineType=astChildren[i].properties["data-line-type"];lineType!=null&&gutterElement.dataset.lineType!==lineType&&(gutterElement.dataset.lineType=lineType)}};applyLineType("deletions",columns[0]),applyLineType("additions",columns[1]),this.adoptRenderData(hunksResult.fileDiff)}refreshUnifiedDiffView(){const fileDiff=this.getWorkingDiff();if(this.options.diffStyle!=="unified"||fileDiff==null)return;const hunksResult=this.hunksRenderer.renderDiff(fileDiff,this.renderRange);if(hunksResult==null)return;const columns=this.getCodeColumns("unified",this.codeUnified,this.codeDeletions,this.codeAdditions);if(columns==null||Array.isArray(columns))return;const ast=this.hunksRenderer.renderCodeAST("unified",hunksResult),gutterChildren=getElementChildren(ast?.[0]),contentChildren=getElementChildren(ast?.[1]),applyColumns=()=>{for(const[el,astChildren]of[[columns.gutter,gutterChildren],[columns.content,contentChildren]])astChildren!=null&&(el.innerHTML=hastToHtml(astChildren));hunksResult.rowCount!==this.lastRowCount&&(this.applyRowSpan("unified",columns,hunksResult.rowCount),this.lastRowCount=hunksResult.rowCount),this.adoptRenderData(hunksResult.fileDiff)};this.shouldGuardRebuildScroll()?guardWebKitScrollDuringRebuild(this.pre,applyColumns):applyColumns(),this.renderSeparators(hunksResult.hunkData),this.managersDirty=!0,this.flushManagers(),this.syncRenderViewToEditor()}renderPartialColumn(column,ast,insertPosition){if(column==null||ast==null)return;const gutterChildren=getElementChildren(ast[0]),contentChildren=getElementChildren(ast[1]);if(gutterChildren==null||contentChildren==null)throw new Error("FileDiff.insertPartialHTML: Unexpected AST structure");const firstHASTElement=contentChildren.at(0);insertPosition==="beforeend"&&firstHASTElement?.type==="element"&&typeof firstHASTElement.properties["data-buffer-size"]=="number"&&this.mergeBuffersIfNecessary(firstHASTElement.properties["data-buffer-size"],column.content.children[column.content.children.length-1],column.gutter.children[column.gutter.children.length-1],gutterChildren,contentChildren,!0);const lastHASTElement=contentChildren.at(-1);insertPosition==="afterbegin"&&lastHASTElement?.type==="element"&&typeof lastHASTElement.properties["data-buffer-size"]=="number"&&this.mergeBuffersIfNecessary(lastHASTElement.properties["data-buffer-size"],column.content.children[0],column.gutter.children[0],gutterChildren,contentChildren,!1),column.gutter.insertAdjacentHTML(insertPosition,this.hunksRenderer.renderPartialHTML(gutterChildren)),column.content.insertAdjacentHTML(insertPosition,this.hunksRenderer.renderPartialHTML(contentChildren))}mergeBuffersIfNecessary(adjustmentSize,contentElement,gutterElement,gutterChildren,contentChildren,fromStart){if(!(contentElement instanceof HTMLElement)||!(gutterElement instanceof HTMLElement))return;const currentSize=this.getBufferSize(contentElement.dataset);currentSize!=null&&(fromStart?(gutterChildren.shift(),contentChildren.shift()):(gutterChildren.pop(),contentChildren.pop()),this.updateBufferSize(contentElement,currentSize+adjustmentSize),this.updateBufferSize(gutterElement,currentSize+adjustmentSize))}applyRowSpan(diffStyle,columns,rowCount){const applySpan=column=>{column!=null&&(column.gutter.style.setProperty("grid-row",`span ${rowCount}`),column.content.style.setProperty("grid-row",`span ${rowCount}`))};if(diffStyle==="unified"&&!Array.isArray(columns))applySpan(columns);else if(diffStyle==="split"&&Array.isArray(columns))applySpan(columns[0]),applySpan(columns[1]);else throw new Error("dun fuuuuked up")}trimColumnRows(columns,preTrimCount,postTrimStart){let visibleLineIndex=0,rowCount=0,rowIndex=0,pendingMetadataTrim=!1;const hasPostTrim=postTrimStart>=0;if(columns==null)return 0;const contentChildren=Array.from(columns.content.children),gutterChildren=Array.from(columns.gutter.children);if(contentChildren.length!==gutterChildren.length)throw new Error("FileDiff.trimColumnRows: columns do not match");for(;rowIndex<contentChildren.length&&!(preTrimCount<=0&&!hasPostTrim&&!pendingMetadataTrim);){const gutterElement=gutterChildren[rowIndex],contentElement=contentChildren[rowIndex];if(rowIndex++,!(gutterElement instanceof HTMLElement)||!(contentElement instanceof HTMLElement))throw console.error({gutterElement,contentElement}),new Error("FileDiff.trimColumnRows: invalid row elements");if(pendingMetadataTrim&&(pendingMetadataTrim=!1,gutterElement.dataset.gutterBuffer==="annotation"&&"lineAnnotation"in contentElement.dataset||gutterElement.dataset.gutterBuffer==="metadata"&&"noNewline"in contentElement.dataset)){gutterElement.remove(),contentElement.remove(),rowCount++;continue}if("lineIndex"in gutterElement.dataset&&"lineIndex"in contentElement.dataset){(preTrimCount>0||hasPostTrim&&visibleLineIndex>=postTrimStart)&&(gutterElement.remove(),contentElement.remove(),preTrimCount>0&&(preTrimCount--,preTrimCount===0&&(pendingMetadataTrim=!0)),rowCount++),visibleLineIndex++;continue}if("separator"in gutterElement.dataset&&"separator"in contentElement.dataset){(preTrimCount>0||hasPostTrim&&visibleLineIndex>=postTrimStart)&&(gutterElement.remove(),contentElement.remove(),rowCount++);continue}if(gutterElement.dataset.gutterBuffer==="annotation"&&"lineAnnotation"in contentElement.dataset){(preTrimCount>0||hasPostTrim&&visibleLineIndex>=postTrimStart)&&(gutterElement.remove(),contentElement.remove(),rowCount++);continue}if(gutterElement.dataset.gutterBuffer==="metadata"&&"noNewline"in contentElement.dataset){(preTrimCount>0||hasPostTrim&&visibleLineIndex>=postTrimStart)&&(gutterElement.remove(),contentElement.remove(),rowCount++);continue}if(gutterElement.dataset.gutterBuffer==="buffer"&&"contentBuffer"in contentElement.dataset){const totalRows=this.getBufferSize(contentElement.dataset);if(totalRows==null)throw new Error("FileDiff.trimColumnRows: invalid element");if(preTrimCount>0){const rowsToRemove=Math.min(preTrimCount,totalRows),newSize=totalRows-rowsToRemove;newSize>0?(this.updateBufferSize(gutterElement,newSize),this.updateBufferSize(contentElement,newSize),rowCount+=rowsToRemove):(gutterElement.remove(),contentElement.remove(),rowCount+=totalRows),preTrimCount-=rowsToRemove,preTrimCount===0&&newSize===0&&(pendingMetadataTrim=!0)}else if(hasPostTrim){const bufferStart=visibleLineIndex,bufferEnd=visibleLineIndex+totalRows-1;if(postTrimStart<=bufferStart)gutterElement.remove(),contentElement.remove(),rowCount+=totalRows;else if(postTrimStart<=bufferEnd){const rowsToRemove=bufferEnd-postTrimStart+1,newSize=totalRows-rowsToRemove;this.updateBufferSize(gutterElement,newSize),this.updateBufferSize(contentElement,newSize),rowCount+=rowsToRemove}}visibleLineIndex+=totalRows;continue}throw console.error({gutterElement,contentElement}),new Error("FileDiff.trimColumnRows: unknown row elements")}return rowCount}trimColumns({columns,diffStyle,overlapEnd,overlapStart,previousStart,trimEnd,trimStart}){const preTrimCount=Math.max(0,overlapStart-previousStart),postTrimStart=overlapEnd-previousStart;if(postTrimStart<0)throw new Error("FileDiff.trimColumns: overlap ends before previous");const shouldTrimStart=trimStart>0,shouldTrimEnd=trimEnd>0;if(!shouldTrimStart&&!shouldTrimEnd)return 0;const effectivePreTrimCount=shouldTrimStart?preTrimCount:0,effectivePostTrimStart=shouldTrimEnd?postTrimStart:-1;if(diffStyle==="unified"&&!Array.isArray(columns))return this.trimColumnRows(columns,effectivePreTrimCount,effectivePostTrimStart);if(diffStyle==="split"&&Array.isArray(columns)){const deletionsTrim=this.trimColumnRows(columns[0],effectivePreTrimCount,effectivePostTrimStart),additionsTrim=this.trimColumnRows(columns[1],effectivePreTrimCount,effectivePostTrimStart);if(columns[0]!=null&&columns[1]!=null&&deletionsTrim!==additionsTrim)throw new Error("FileDiff.trimColumns: split columns out of sync");return columns[0]!=null?deletionsTrim:additionsTrim}else throw console.error({diffStyle,columns}),new Error("FileDiff.trimColumns: Invalid columns for diffType")}getBufferSize(properties){const parsed=Number.parseInt(properties?.bufferSize??"",10);return Number.isNaN(parsed)?void 0:parsed}updateBufferSize(element,size){element.dataset.bufferSize=`${size}`,element.style.setProperty("grid-row",`span ${size}`),element.style.setProperty("min-height",`calc(${size} * 1lh)`)}getColumnPair(code){if(code==null)return;const gutter=code.children[0],content=code.children[1];if(!(!(gutter instanceof HTMLElement)||!(content instanceof HTMLElement)||gutter.dataset.gutter==null||content.dataset.content==null))return{gutter,content}}getCodeColumns(diffStyle,codeUnified,codeDeletions,codeAdditions){if(diffStyle==="unified")return this.getColumnPair(codeUnified);{const deletions=this.getColumnPair(codeDeletions),additions=this.getColumnPair(codeAdditions);return deletions!=null||additions!=null?[deletions,additions]:void 0}}updateBuffers(renderRange){this.pre!=null&&this.applyBuffers(this.pre,renderRange)}applyBuffers(pre,renderRange){if(renderRange==null||this.shouldDisableVirtualizationBuffers()){this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0);return}renderRange.bufferBefore>0?(this.bufferBefore==null&&(this.bufferBefore=document.createElement("div"),this.bufferBefore.dataset.virtualizerBuffer="before",pre.before(this.bufferBefore)),this.bufferBefore.style.setProperty("height",`${renderRange.bufferBefore}px`),this.bufferBefore.style.setProperty("contain","strict")):this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),renderRange.bufferAfter>0?(this.bufferAfter==null&&(this.bufferAfter=document.createElement("div"),this.bufferAfter.dataset.virtualizerBuffer="after",pre.after(this.bufferAfter)),this.bufferAfter.style.setProperty("height",`${renderRange.bufferAfter}px`),this.bufferAfter.style.setProperty("contain","strict")):this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0)}shouldDisableVirtualizationBuffers(){return this.options.disableVirtualizationBuffers??!1}applyPreNodeAttributes(pre,{additionsContentAST,deletionsContentAST,totalLines},customProperties){const{diffIndicators="bars",disableBackground=!1,disableLineNumbers=!1,overflow="scroll",diffStyle="split"}=this.options,preProperties={type:"diff",diffIndicators,disableBackground,disableLineNumbers,overflow,split:diffStyle==="unified"?!1:additionsContentAST!=null&&deletionsContentAST!=null,totalLines,customProperties};arePrePropertiesEqual(preProperties,this.appliedPreAttributes)||(setPreNodeProperties(pre,preProperties),this.appliedPreAttributes=preProperties)}applyErrorToDOM(error,container){this.cleanupErrorWrapper(),this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0;const shadowRoot=container.shadowRoot??container.attachShadow({mode:"open"});this.errorWrapper??=document.createElement("div"),this.errorWrapper.dataset.errorWrapper="",this.errorWrapper.textContent="",shadowRoot.appendChild(this.errorWrapper);const errorMessage=document.createElement("div");errorMessage.dataset.errorMessage="",errorMessage.innerText=error.message,this.errorWrapper.appendChild(errorMessage);const errorStack=document.createElement("pre");errorStack.dataset.errorStack="",errorStack.innerText=error.stack??"No Error Stack",this.errorWrapper.appendChild(errorStack)}cleanupErrorWrapper(){this.errorWrapper?.remove(),this.errorWrapper=void 0}};function getAdditionFile(fileDiff){return{name:fileDiff.name,lang:fileDiff.lang,contents:fileDiff.additionLines.join("")}}function areOptionalFilesEqual$1(fileA,fileB){return fileA==null||fileB==null?fileA==null&&fileB==null:areFilesEqual(fileA,fileB)}function hasDiffContent({fileDiff,oldFile,newFile}){return fileDiff!=null&&fileDiff.hunks.length>0||oldFile!=null||newFile!=null}function hasDiffHeaderContent({fileDiff,oldFile,newFile}){return fileDiff!=null||oldFile!=null||newFile!=null}function shouldRenderCode(pre,hasContent,collapsed=!1){return!collapsed&&pre==null&&hasContent}function shouldRenderHeader(headerElement,hasContent,disableFileHeader=!1){return headerElement==null&&hasContent&&!disableFileHeader}function getElementChildren(node){if(!(node==null||node.type!=="element"))return node.children??[]}function computeEstimatedDiffHeights({fileDiff,metrics,disableFileHeader,hunkSeparators,expandUnchanged,expandedHunks:configuredExpandedHunks,collapsedContextThreshold,canHydratePartialDiff}){let splitHeight=getVirtualFileHeaderRegion(metrics,disableFileHeader),unifiedHeight=splitHeight;const expandedHunks=expandUnchanged?!0:configuredExpandedHunks,finalHunkIndex=fileDiff.hunks.length-1;for(let hunkIndex=0;hunkIndex<fileDiff.hunks.length;hunkIndex++){const hunk=fileDiff.hunks[hunkIndex];if(hunk==null)throw new Error("computeEstimatedDiffHeights: invalid hunk index");const leadingRegion=getExpandedRegion({isPartial:fileDiff.isPartial,rangeSize:hunk.collapsedBefore,expandedHunks,hunkIndex,collapsedContextThreshold}),leadingExpandedHeight=(leadingRegion.fromStart+leadingRegion.fromEnd)*metrics.lineHeight;if(splitHeight+=leadingExpandedHeight,unifiedHeight+=leadingExpandedHeight,leadingRegion.collapsedLines>0){const separatorHeight=getLeadingHunkSeparatorLayout({type:hunkSeparators,metrics,hunkIndex,hunkSpecs:hunk.hunkSpecs})?.totalHeight??0;splitHeight+=separatorHeight,unifiedHeight+=separatorHeight}splitHeight+=hunk.splitLineCount*metrics.lineHeight,unifiedHeight+=hunk.unifiedLineCount*metrics.lineHeight;const metadataLineCounts=getNoNewlineMetadataLineCounts(hunk);splitHeight+=metadataLineCounts.split*metrics.lineHeight,unifiedHeight+=metadataLineCounts.unified*metrics.lineHeight;const trailingRegion=hunkIndex===finalHunkIndex?getTrailingExpandedRegion({fileDiff,hunkIndex,expandedHunks,collapsedContextThreshold,errorPrefix:"computeEstimatedDiffHeights"}):void 0;if(trailingRegion!=null){const trailingExpandedHeight=(trailingRegion.fromStart+trailingRegion.fromEnd)*metrics.lineHeight;if(splitHeight+=trailingExpandedHeight,unifiedHeight+=trailingExpandedHeight,trailingRegion.collapsedLines>0){const separatorHeight=getTrailingHunkSeparatorLayout({type:hunkSeparators,metrics})?.totalHeight??0;splitHeight+=separatorHeight,unifiedHeight+=separatorHeight}}else if(hunkIndex===finalHunkIndex&&fileDiff.isPartial&&canHydratePartialDiff){const separatorHeight=getTrailingHunkSeparatorLayout({type:hunkSeparators,metrics})?.totalHeight??0;splitHeight+=separatorHeight,unifiedHeight+=separatorHeight}}if(fileDiff.hunks.length>0){const paddingBottom=getVirtualFilePaddingBottom(metrics);splitHeight+=paddingBottom,unifiedHeight+=paddingBottom}return{splitHeight,unifiedHeight}}function getNoNewlineMetadataLineCounts(hunk){if(!hunk.noEOFCRAdditions&&!hunk.noEOFCRDeletions)return{split:0,unified:0};const lastContent=hunk.hunkContent.at(-1);if(lastContent==null)return{split:0,unified:0};if(lastContent.type==="context"){const metadataRows=lastContent.lines>0?1:0;return{split:metadataRows,unified:metadataRows}}return getChangeNoNewlineMetadataLineCounts(hunk,lastContent)}function getChangeNoNewlineMetadataLineCounts(hunk,content){const unified=(content.deletions>0&&hunk.noEOFCRDeletions?1:0)+(content.additions>0&&hunk.noEOFCRAdditions?1:0),splitDeletionHasMetadata=content.deletions>0&&hunk.noEOFCRDeletions,splitAdditionHasMetadata=content.additions>0&&hunk.noEOFCRAdditions;return{split:splitDeletionHasMetadata||splitAdditionHasMetadata?1:0,unified}}const VIRTUALIZED_FILE_DIFF_LAYOUT_CHECKPOINT_INTERVAL=3e3,NO_GHOST_TEXT_ROWS=new Map;let instanceId=-1;var VirtualizedFileDiff=class extends FileDiff$1{__id=`little-virtualized-file-diff:${++instanceId}`;renderType="virtualized";top;height=0;metrics;cache={heightDeltas:new Map,measuredHeightDeltaTotal:0,estimatedSplitHeight:void 0,estimatedUnifiedHeight:void 0,checkpoints:[],totalLines:0,fileAnnotationHeight:0,ghostTextRows:NO_GHOST_TEXT_ROWS,ghostTextRowsByIndex:new Map};isVisible=!1;isSetup=!1;virtualizer;layoutDirty=!0;currentCollapsed;pendingHydratedDiff;pendingExpansions;pendingRender;constructor(options,virtualizer,metrics,workerManager,requestOwnerRender){super(options,workerManager,requestOwnerRender),this.virtualizer=virtualizer,this.metrics=computeVirtualFileMetrics(metrics)}setMetrics(metrics,force=!1){const nextMetrics=computeVirtualFileMetrics(metrics);!force&&areObjectsEqual(this.metrics,nextMetrics)||(this.metrics=nextMetrics,this.resetLayoutCache({includeEstimatedHeights:!0}))}setLineAnnotations(lineAnnotations){this.syncLineAnnotations(lineAnnotations)&&(this.forceRenderOverride=!0)}syncLineAnnotations(lineAnnotations){return lineAnnotations==null||!this.isNewAnnotations(lineAnnotations)||lineAnnotations.length===0&&this.getLatestAnnotations().length===0?!1:(super.setLineAnnotations(lineAnnotations),!0)}syncEditSessionAnnotationsFromEditor(lineAnnotations){return super.syncEditSessionAnnotationsFromEditor(lineAnnotations)?(this.forceRenderOverride=!0,!0):!1}setFileAnnotationHeight(nextHeight){const previousHeight=this.cache.fileAnnotationHeight;return nextHeight===previousHeight?!1:(this.cache.fileAnnotationHeight=nextHeight,this.cache.measuredHeightDeltaTotal+=nextHeight-previousHeight,!0)}hasFileAnnotations(fileDiff){const lineAnnotations=this.getLayoutAnnotations();return includesFileAnnotations(lineAnnotations)?lineAnnotations.some(annotation=>annotation.lineNumber!==0?!1:fileDiff.type==="new"?annotation.side==="additions":fileDiff.type==="deleted"?annotation.side==="deletions":!0):!1}getLineHeight(lineIndex,hasMetadataLine=!1){return this.getEstimatedLineHeight(hasMetadataLine)+(this.cache.heightDeltas.get(lineIndex)??0)}getEstimatedLineHeight(hasMetadataLine=!1){const multiplier=hasMetadataLine?2:1;return this.metrics.lineHeight*multiplier}setOptions(options){if(this.isAdvancedMode())throw new Error("VirtualizedFileDiff.setOptions cannot be used inside CodeView. Update CodeView options instead.");if(options==null)return;const{options:previousOptions}=this,optionsChanged=!areOptionsEqual(previousOptions,options),layoutChanged=optionsChanged&&hasDiffLayoutOptionChanged(previousOptions,options);super.setOptions(options),layoutChanged&&this.resetLayoutCache({forceSimpleRecompute:!0,includeEstimatedHeights:hasDiffEstimateOptionChanged(previousOptions,options)}),optionsChanged&&(this.forceRenderOverride=!0),optionsChanged&&this.isSimpleMode()&&this.virtualizer.instanceChanged(this,layoutChanged)}setThemeType(themeType){if(this.isAdvancedMode())throw new Error("VirtualizedFileDiff.setThemeType cannot be used inside CodeView. Update CodeView options instead.");super.setThemeType(themeType)}resetLayoutCache({forceSimpleRecompute=!1,includeEstimatedHeights=!1,resetRenderRange=!0}={}){this.layoutDirty=!0,this.cache.fileAnnotationHeight=0,this.cache.heightDeltas.clear(),this.cache.measuredHeightDeltaTotal=0,this.cache.ghostTextRows=NO_GHOST_TEXT_ROWS,this.cache.ghostTextRowsByIndex.size>0&&this.cache.ghostTextRowsByIndex.clear(),this.invalidateDerivedLayoutCache(includeEstimatedHeights,resetRenderRange),forceSimpleRecompute&&this.isSimpleMode()&&this.computeApproximateSize()}invalidateDerivedLayoutCache(includeEstimatedHeights,resetRenderRange=!0){this.layoutDirty=!0,this.cache.checkpoints.length>0&&(this.cache.checkpoints.length=0),this.cache.totalLines!==0&&(this.cache.totalLines=0),includeEstimatedHeights&&(this.cache.estimatedSplitHeight=void 0,this.cache.estimatedUnifiedHeight=void 0),this.renderRange!=null&&resetRenderRange&&(this.renderRange=void 0)}applyGhostTextRows(fileDiff,ghostTextRows){const{cache:{heightDeltas,ghostTextRows:folded,ghostTextRowsByIndex:previous},metrics:{lineHeight}}=this;if(folded===ghostTextRows)return!1;const diffStyle=this.getDiffStyle(),next=new Map;for(const[line,rows]of ghostTextRows){const indexes2=this.getLineIndexForDiff(fileDiff,line+1,"additions");indexes2!=null&&next.set(diffStyle==="split"?indexes2[1]:indexes2[0],rows)}let changed=!1;for(const rowIndex of new Set([...previous.keys(),...next.keys()])){const delta=((next.get(rowIndex)??0)-(previous.get(rowIndex)??0))*lineHeight;if(delta===0)continue;const nextDelta=(heightDeltas.get(rowIndex)??0)+delta;nextDelta===0?heightDeltas.delete(rowIndex):heightDeltas.set(rowIndex,nextDelta),this.cache.measuredHeightDeltaTotal+=delta,changed=!0}return this.cache.ghostTextRows=ghostTextRows,this.cache.ghostTextRowsByIndex=next,changed}reconcileHeights(){let hasHeightChange=!1;const{options:{overflow="scroll"},metrics:{lineHeight}}=this,fileDiff=this.placeHolder!=null?this.getLayoutDiff():this.getRenderedDiff();if(this.fileContainer==null||fileDiff==null)return this.height!==0&&(hasHeightChange=!0),this.height=0,hasHeightChange;this.top=this.getVirtualizedTop(),hasHeightChange=this.applyGhostTextRows(fileDiff,this.editor?.__getGhostTextRows()??NO_GHOST_TEXT_ROWS);const{ghostTextRowsByIndex}=this.cache,measureAllRows=overflow!=="scroll"||this.lineAnnotations.length>0||this.isResizeDebuggingEnabled();if(this.placeHolder!=null||!measureAllRows&&this.cache.heightDeltas.size===0&&this.cache.fileAnnotationHeight===0)return hasHeightChange&&(this.computeApproximateSize(!0),this.setPlaceholderHeight(this.height)),hasHeightChange;const diffStyle=this.getDiffStyle(),codeGroups=diffStyle==="split"?[this.codeDeletions,this.codeAdditions]:[this.codeUnified];if(this.renderRange!=null&&shouldRenderFileAnnotations(this.renderRange)){const nextFileAnnotationHeight=measureFileAnnotationHeight(codeGroups)??0;this.setFileAnnotationHeight(nextFileAnnotationHeight)&&(hasHeightChange=!0)}for(const codeGroup of codeGroups){if(codeGroup==null)continue;const content=codeGroup.children[1];if(!(content instanceof HTMLElement))continue;const skipsGhostRows=diffStyle==="split"&&codeGroup===this.codeDeletions;for(const line of content.children){if(!(line instanceof HTMLElement))continue;const lineIndexAttr=line.dataset.lineIndex;if(lineIndexAttr==null)continue;const lineIndex=parseLineIndex(lineIndexAttr,diffStyle),ghostRows=ghostTextRowsByIndex.get(lineIndex)??0;if(skipsGhostRows&&ghostRows>0)continue;const previousDelta=this.cache.heightDeltas.get(lineIndex)??0;if(!measureAllRows&&previousDelta===ghostRows*lineHeight)continue;let measuredHeight=line.getBoundingClientRect().height+ghostRows*lineHeight,hasMetadata=!1;line.nextElementSibling instanceof HTMLElement&&("lineAnnotation"in line.nextElementSibling.dataset||"noNewline"in line.nextElementSibling.dataset)&&("noNewline"in line.nextElementSibling.dataset&&(hasMetadata=!0),measuredHeight+=line.nextElementSibling.getBoundingClientRect().height);const estimatedHeight=this.getEstimatedLineHeight(hasMetadata),nextDelta=measuredHeight-estimatedHeight;nextDelta!==previousDelta&&(hasHeightChange=!0,this.cache.measuredHeightDeltaTotal+=nextDelta-previousDelta,nextDelta===0?this.cache.heightDeltas.delete(lineIndex):this.cache.heightDeltas.set(lineIndex,nextDelta))}}return(hasHeightChange||this.isResizeDebuggingEnabled())&&this.computeApproximateSize(!0),hasHeightChange}onRender=dirty=>this.fileContainer==null?!1:(dirty&&(this.top=this.getVirtualizedTop()),this.render());flushManagers(){super.flushManagers(),this.lineStateRefreshPending&&this.flushDeferredLineState()}updateCodeViewLayout(fileDiff,top,reset,lineAnnotations){let resetLayoutCache=!1,resetEstimatedHeights=!1;const{pendingExpansions,pendingHydratedDiff,options:{collapsed=!1}}=this;if(pendingHydratedDiff!=null&&(this.pendingHydratedDiff=void 0,pendingHydratedDiff.expectedDiff===fileDiff&&(Object.assign(fileDiff,pendingHydratedDiff.nextDiff),this.setHydratedState(pendingHydratedDiff.files),this.installHydratedSessionDiff(fileDiff),this.forceRenderOverride=!0,resetLayoutCache=!0,resetEstimatedHeights=!0)),pendingExpansions!=null){this.pendingExpansions=void 0;for(const{hunkIndex,direction,expansionLineCountOverride}of pendingExpansions)this.hunksRenderer.expandHunk(hunkIndex,direction,expansionLineCountOverride),this.forceRenderOverride=!0,resetEstimatedHeights=!0}const diffChanged=this.updateInputDiff(fileDiff,lineAnnotations),{pendingRenderDiff,layoutDiffChanged,renderedDiffChanged,annotationsChanged}=this.updatePendingRender(fileDiff,lineAnnotations);return!this.forceRenderOverride&&(diffChanged||renderedDiffChanged||annotationsChanged)&&(this.forceRenderOverride=!0),(reset?.resetDiffLayoutCache===!0||layoutDiffChanged)&&(resetLayoutCache=!0),(layoutDiffChanged||reset?.resetDiffLayoutCache===!0&&reset.includeEstimatedDiffHeights)&&(resetEstimatedHeights=!0),reset?.metrics!=null&&(this.metrics=computeVirtualFileMetrics(reset.metrics),resetLayoutCache=!0,resetEstimatedHeights=!0),this.currentCollapsed!==collapsed&&(this.currentCollapsed=collapsed,resetLayoutCache=!0),resetLayoutCache?this.resetLayoutCache({includeEstimatedHeights:resetEstimatedHeights}):resetEstimatedHeights&&this.invalidateDerivedLayoutCache(!0),this.top=top,this.computeApproximateSize(!1,pendingRenderDiff),this.height}getLinePosition(lineNumber,side="additions"){const fileDiff=this.getLayoutDiff();if(fileDiff==null||lineNumber<1)return;const targetLineIndexes=this.getLineIndexForDiff(fileDiff,lineNumber,side);if(targetLineIndexes==null)return;const{disableFileHeader=!1,expandUnchanged=!1,collapsed=!1,collapsedContextThreshold=1}=this.options,diffStyle=this.getDiffStyle(),hunkSeparators=this.getHunkSeparatorType(),targetLineIndex=diffStyle==="split"?targetLineIndexes[1]:targetLineIndexes[0];this.approximateLayoutCheckpoints(fileDiff);const headerRegion=getVirtualFileHeaderRegion(this.metrics,disableFileHeader),checkpoint=this.getLayoutCheckpointBeforeLineIndex(targetLineIndex);let top=checkpoint?.top??headerRegion+this.cache.fileAnnotationHeight;if(collapsed)return{top:getVirtualFileHeaderHeight(this.metrics,disableFileHeader),height:0};let position;return iterateOverDiff({diff:fileDiff,diffStyle,startingLine:checkpoint?.renderedLineIndex??0,expandedHunks:expandUnchanged?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold,callback:({hunkIndex,hunk,collapsedBefore,collapsedAfter,deletionLine,additionLine})=>{const lineIndex=diffStyle==="split"?additionLine?.splitLineIndex??deletionLine?.splitLineIndex:additionLine?.unifiedLineIndex??deletionLine?.unifiedLineIndex;if(lineIndex==null)throw new Error("VirtualizedFileDiff.getLinePosition: missing line index data");if(collapsedBefore>0){const separator=getLeadingHunkSeparatorLayout({type:hunkSeparators,metrics:this.metrics,hunkIndex,hunkSpecs:hunk?.hunkSpecs});if(separator!=null){if(top+=separator.gapBefore,targetLineIndex>=lineIndex-collapsedBefore&&targetLineIndex<lineIndex)return position={top,height:separator.height},!0;top+=separator.height+separator.gapAfter}}const lineHeight=this.getLineHeight(lineIndex,(additionLine?.noEOFCR??!1)||(deletionLine?.noEOFCR??!1));if(lineIndex===targetLineIndex)return position={top,height:lineHeight},!0;if(top+=lineHeight,collapsedAfter>0){const separator=getTrailingHunkSeparatorLayout({type:hunkSeparators,metrics:this.metrics});if(separator!=null){if(targetLineIndex>lineIndex&&targetLineIndex<=lineIndex+collapsedAfter)return position={top:top+separator.gapBefore,height:separator.height},!0;top+=separator.totalHeight}}return!1}}),position}getEditorViewport(){return this.virtualizer.type==="simple"?this.virtualizer.getRoot():this.virtualizer.getContainerElement()}getNumericScrollAnchor(localViewportTop){const fileDiff=this.getLayoutDiff();if(fileDiff==null)return;const{disableFileHeader=!1,expandUnchanged=!1,collapsed=!1,collapsedContextThreshold=1}=this.options;if(collapsed)return;const diffStyle=this.getDiffStyle(),hunkSeparators=this.getHunkSeparatorType();this.approximateLayoutCheckpoints(fileDiff);const checkpoint=this.getLayoutCheckpointBeforeTop(localViewportTop);let top=checkpoint?.top??getVirtualFileHeaderRegion(this.metrics,disableFileHeader)+this.cache.fileAnnotationHeight,anchor;return iterateOverDiff({diff:fileDiff,diffStyle,startingLine:checkpoint?.renderedLineIndex??0,expandedHunks:expandUnchanged?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold,callback:({hunkIndex,hunk,collapsedBefore,collapsedAfter,deletionLine,additionLine})=>{const lineIndex=diffStyle==="split"?additionLine?.splitLineIndex??deletionLine?.splitLineIndex:additionLine?.unifiedLineIndex??deletionLine?.unifiedLineIndex;if(lineIndex==null)throw new Error("VirtualizedFileDiff.getNumericScrollAnchor: missing line index data");if(collapsedBefore>0){const separator=getLeadingHunkSeparatorLayout({type:hunkSeparators,metrics:this.metrics,hunkIndex,hunkSpecs:hunk?.hunkSpecs});separator!=null&&(top+=separator.totalHeight)}if(top>=localViewportTop&&(deletionLine!=null?anchor={lineNumber:deletionLine.lineNumber,side:"deletions",top}:additionLine!=null&&(anchor={lineNumber:additionLine.lineNumber,side:"additions",top}),anchor!=null))return!0;const lineHeight=this.getLineHeight(lineIndex,(additionLine?.noEOFCR??!1)||(deletionLine?.noEOFCR??!1));if(top+=lineHeight,collapsedAfter>0){const separator=getTrailingHunkSeparatorLayout({type:hunkSeparators,metrics:this.metrics});separator!=null&&(top+=separator.totalHeight)}return!1}}),anchor}getVirtualizedHeight(){return this.height}getAdvancedStickySpecs(windowSpecs){const fileDiff=this.getLayoutDiff();if(this.top==null||fileDiff==null)return;if(this.options.collapsed===!0)return{topOffset:this.top,height:this.height};const renderRange=windowSpecs!=null?this.computeRenderRangeFromWindow(fileDiff,this.top,windowSpecs):this.renderRange;if(renderRange==null)return;const{bufferBefore,bufferAfter,totalLines}=renderRange;let headerOnlyOffset=0;if(totalLines===0){const activeWindow=windowSpecs??this.virtualizer.getWindowSpecs();this.top<activeWindow.top&&(headerOnlyOffset=bufferAfter)}return{topOffset:this.top+bufferBefore+headerOnlyOffset,height:this.height-(bufferBefore+bufferAfter)}}cleanUp(recycle=!1){const hadGhostTextRows=this.cache.ghostTextRows.size>0;hadGhostTextRows&&(this.layoutDirty=!0);const shouldRecomputeLayout=recycle&&this.isAdvancedMode()&&this.fileContainer!=null&&(hadGhostTextRows||!areDiffTargetsEqual(this.getRenderedDiff(),this.getWorkingDiff()));this.fileContainer!=null&&this.isSimpleMode()&&this.getSimpleVirtualizer()?.disconnect(this.fileContainer),recycle||(this.resetLayoutCache({includeEstimatedHeights:!0}),this.pendingExpansions=void 0,this.pendingHydratedDiff=void 0),this.pendingRender=void 0,this.isSetup=!1,super.cleanUp(recycle),shouldRecomputeLayout&&this.virtualizer.instanceChanged(this,!0)}expandHunk=(hunkIndex,direction,expansionLineCountOverride)=>{this.getInputDiff()!=null&&(this.loadFilesIfNecessary(),this.isAdvancedMode()?(this.pendingExpansions??=[],this.pendingExpansions.push({hunkIndex,direction,expansionLineCountOverride})):(this.hunksRenderer.expandHunk(hunkIndex,direction,expansionLineCountOverride),this.resetLayoutCache({includeEstimatedHeights:!0}),this.computeApproximateSize()),this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0))};async handleFilesLoaded(expectedDiff,files){if(!(this.getInputDiff()!==expectedDiff||!expectedDiff.isPartial)){if(this.isAdvancedMode()){const nextDiff=hydratePartialDiff("clone",expectedDiff,files,this.options.parseDiffOptions);if(await awaitWithTimeout(()=>this.primeHighlightCache(nextDiff)),this.getInputDiff()!==expectedDiff)return;this.pendingHydratedDiff={expectedDiff,nextDiff,files}}else{if(hydratePartialDiff("merge",expectedDiff,files,this.options.parseDiffOptions),this.setHydratedState(files),!this.installHydratedSessionDiff(expectedDiff)&&(await awaitWithTimeout(()=>this.primeHighlightCache(expectedDiff)),this.getInputDiff()!==expectedDiff))return;this.resetLayoutCache({includeEstimatedHeights:!0}),this.computeApproximateSize()}this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0)}}loadFilesIfNecessary(){if(this.pendingHydratedDiff!=null){if(this.pendingHydratedDiff.expectedDiff===this.getInputDiff())return;this.pendingHydratedDiff=void 0}super.loadFilesIfNecessary()}isLineRenderable(lineNumber){if(super.isLineRenderable(lineNumber))return!0;const{pendingExpansions}=this,fileDiff=this.getRenderedDiff();if(pendingExpansions==null||pendingExpansions.length===0||fileDiff==null)return!1;const{expansionLineCount=100,collapsedContextThreshold=1}=this.options,staged=new Map(this.hunksRenderer.getExpandedHunksMap());for(const expansion of pendingExpansions){const region={...staged.get(expansion.hunkIndex)??{fromStart:0,fromEnd:0}},count=expansion.expansionLineCountOverride??expansionLineCount;(expansion.direction==="up"||expansion.direction==="both")&&(region.fromStart+=count),(expansion.direction==="down"||expansion.direction==="both")&&(region.fromEnd+=count),staged.set(expansion.hunkIndex,region)}return isAdditionLineRenderable({fileDiff,lineNumber,expandedHunks:staged,collapsedContextThreshold})}invalidateEditSessionLayout(){this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache({forceSimpleRecompute:this.isSimpleMode(),includeEstimatedHeights:!0,resetRenderRange:!1}),this.isSimpleMode()||this.computeApproximateSize(!0),this.getSimpleVirtualizer()?.requestHeightReconcile(this)}escalateEditSessionRender(){this.invalidateEditSessionLayout(),!(!this.enabled||this.getInputDiff()==null)&&(this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0))}shouldSelfHealEditSession(){return!this.isAdvancedMode()&&super.shouldSelfHealEditSession()}setVisibility(visible){this.isAdvancedMode()||this.fileContainer==null||(this.renderRange=void 0,visible&&!this.isVisible?(this.top=this.getVirtualizedTop(),this.isVisible=!0):!visible&&this.isVisible&&(this.isVisible=!1,this.rerender()))}rerender(){if(!this.enabled||this.getInputDiff()==null&&this.additionFile==null&&this.deletionFile==null)return;const workingDiff=this.getWorkingDiff(),nextRenderDiff=workingDiff==null?void 0:this.hunksRenderer.getDiffForNextRender(workingDiff);this.isSimpleMode()&&(this.pendingRender=void 0),this.forceRenderOverride=!0,!(this.isSimpleMode()&&this.requestRender())&&this.virtualizer.instanceChanged(this,!areDiffTargetsEqual(this.getRenderedDiff(),nextRenderDiff))}get isComponentManaged(){return this.getAdvancedVirtualizer()?.isComponentManaged??super.isComponentManaged}syncGhostTextRows(){const codeView=this.getAdvancedVirtualizer();codeView!=null?(codeView.capturePendingLayoutAnchor(),this.layoutDirty=!0,codeView.instanceChanged(this,!0)):this.getSimpleVirtualizer()?.requestHeightReconcile(this)}applyDocumentChange(textDocument,newLineAnnotations,shouldUpdateBuffer=!1){const{renderRange:previousRenderRange}=this;this.getAdvancedVirtualizer()?.capturePendingLayoutAnchor(),super.applyDocumentChange(textDocument,newLineAnnotations),this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache({forceSimpleRecompute:this.isSimpleMode(),includeEstimatedHeights:!0,resetRenderRange:!1});const fileDiff=this.getRenderedDiff();if(!this.isSimpleMode())this.computeApproximateSize(!0);else if(shouldUpdateBuffer&&previousRenderRange!=null&&fileDiff!=null){const windowSpecs=this.virtualizer.getWindowSpecs(),renderRange=this.computeRenderRangeFromWindow(fileDiff,this.top??0,windowSpecs);renderRange.bufferAfter!==previousRenderRange.bufferAfter&&this.updateBuffers(renderRange)}this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0)}computeApproximateSize(force=!1,fileDiff=this.getLayoutDiff()){const shouldValidateSize=this.isResizeDebuggingEnabled();if(!force&&!this.layoutDirty&&!shouldValidateSize)return;const isFirstCompute=this.height===0;if(this.height=0,this.cache.checkpoints=[],this.cache.totalLines=0,fileDiff==null){this.layoutDirty=!1;return}this.applyGhostTextRows(fileDiff,this.editor?.__getGhostTextRows()??NO_GHOST_TEXT_ROWS);const{disableFileHeader=!1,collapsed=!1}=this.options;if(collapsed){this.height+=getVirtualFileHeaderHeight(this.metrics,disableFileHeader),this.layoutDirty=!1;return}this.height=this.getActiveEstimatedHeight(fileDiff)+this.cache.measuredHeightDeltaTotal,shouldValidateSize&&!isFirstCompute&&this.validateComputedHeight(fileDiff),this.layoutDirty=!1}getLayoutDiff(){return this.pendingRender?.diff??this.getRenderedDiff()}getLayoutAnnotations(){const{pendingRender}=this;return pendingRender!=null?this.getAnnotationsForDiff(pendingRender.diff):this.lineAnnotations}getActiveEstimatedHeight(fileDiff=this.getLayoutDiff()){this.ensureEstimatedDiffHeights(fileDiff);const estimatedHeight=this.getDiffStyle()==="split"?this.cache.estimatedSplitHeight:this.cache.estimatedUnifiedHeight;if(estimatedHeight==null)throw new Error("VirtualizedFileDiff.getActiveEstimatedHeight: missing estimated height");return estimatedHeight}ensureEstimatedDiffHeights(fileDiff=this.getLayoutDiff()){if(fileDiff==null){this.cache.estimatedSplitHeight=void 0,this.cache.estimatedUnifiedHeight=void 0;return}if(this.cache.estimatedSplitHeight!=null&&this.cache.estimatedUnifiedHeight!=null)return;const{disableFileHeader=!1,expandUnchanged=!1,collapsedContextThreshold=1}=this.options,{splitHeight,unifiedHeight}=computeEstimatedDiffHeights({fileDiff,metrics:this.metrics,disableFileHeader,hunkSeparators:this.getHunkSeparatorType(),expandUnchanged,expandedHunks:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold,canHydratePartialDiff:canHydrateCollapsedContext(fileDiff,this.options.loadDiffFiles!=null)});this.cache.estimatedSplitHeight=splitHeight,this.cache.estimatedUnifiedHeight=unifiedHeight}validateComputedHeight(fileDiff=this.getLayoutDiff()){if(this.fileContainer==null||fileDiff==null)return;const rect=this.fileContainer.getBoundingClientRect();rect.height!==this.height?console.log("VirtualizedFileDiff.computeApproximateSize: computed height doesnt match",{name:fileDiff.name,elementHeight:rect.height,computedHeight:this.height}):console.log("VirtualizedFileDiff.computeApproximateSize: computed height IS CORRECT")}render({fileContainer,fileDiff,forceRender=!1,lineAnnotations,...fileInputProps}={}){const fileInput=getDiffFileInput(fileInputProps,"VirtualizedFileDiff.render"),hasFileInput=fileInput!=null,oldFile=fileInput?.oldFile,newFile=fileInput?.newFile,filesDidChange=hasFileInput&&(!areOptionalFilesEqual(oldFile,this.deletionFile)||!areOptionalFilesEqual(newFile,this.additionFile));let nextFileDiff=fileDiff??this.getInputDiff();fileDiff==null&&hasFileInput&&(filesDidChange||this.getInputDiff()==null)&&(nextFileDiff=parseDiffFromFile(fileInput.oldFile,fileInput.newFile,this.options.parseDiffOptions));const{forceRenderOverride,isSetup}=this;this.forceRenderOverride=void 0;const targetChanged=nextFileDiff!=null&&!areDiffTargetsEqual(this.getInputDiff(),nextFileDiff),dataChanged=targetChanged||filesDidChange;if(fileContainer=this.getOrCreateFileContainer(fileContainer),nextFileDiff==null)return console.error("VirtualizedFileDiff.render: attempting to virtually render when we dont have the correct data"),!1;targetChanged&&this.updateInputDiff(nextFileDiff,lineAnnotations);const{pendingRenderDiff,layoutDiffChanged,renderedDiffChanged,annotationsChanged}=this.pendingRender!=null&&this.pendingRender.workingDiff===(this.getWorkingDiff(nextFileDiff)??nextFileDiff)?{pendingRenderDiff:this.pendingRender.diff,layoutDiffChanged:!1,renderedDiffChanged:!1,annotationsChanged:this.syncLineAnnotations(lineAnnotations)}:this.updatePendingRender(nextFileDiff,lineAnnotations);if(layoutDiffChanged&&this.resetLayoutCache({includeEstimatedHeights:!0}),isSetup)this.top??=this.getVirtualizedTop(),this.layoutDirty&&this.isSimpleMode()&&(this.getSimpleVirtualizer()?.markDOMDirty(),this.computeApproximateSize(!1,pendingRenderDiff));else{this.computeApproximateSize(!1,pendingRenderDiff);const virtualizer=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(virtualizer==null)throw new Error("VirtualizedFileDiff.render: simple virtualizer is not available");virtualizer.connect(fileContainer,this),this.isVisible=virtualizer.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode()&&(!dataChanged||!isSetup))return fileInput!=null&&(this.deletionFile=oldFile,this.additionFile=newFile),targetChanged&&this.clearReusableHeader(),this.renderPlaceholder(this.height);const windowSpecs=this.virtualizer.getWindowSpecs(),fileTop=this.top??0,renderRange=this.computeRenderRangeFromWindow(pendingRenderDiff,fileTop,windowSpecs);return super.render({fileDiff:nextFileDiff,fileContainer,renderRange,lineAnnotations,forceRender:(forceRenderOverride??forceRender)||annotationsChanged||renderedDiffChanged||targetChanged,...fileInput,...fileInputProps})}finalizeRender(){if(!areDiffTargetsEqual(this.getRenderedDiff(),this.pendingRender?.diff))throw new Error("VirtualizedFileDiff.render: rendered a different diff than its prepared layout");this.pendingRender=void 0,this.isSimpleMode()&&this.getSimpleVirtualizer()?.requestHeightReconcile(this)}updatePendingRender(nextFileDiff,lineAnnotations){const workingDiff=this.getWorkingDiff(nextFileDiff)??nextFileDiff,previousRenderedDiff=this.getRenderedDiff(),{pendingRender}=this,previousLayoutDiff=pendingRender?.diff??previousRenderedDiff,pendingRenderDiff=this.hunksRenderer.getDiffForNextRender(workingDiff);return this.pendingRender={workingDiff,diff:pendingRenderDiff},{pendingRenderDiff,annotationsChanged:this.syncLineAnnotations(lineAnnotations),layoutDiffChanged:!areDiffTargetsEqual(previousLayoutDiff,pendingRenderDiff),renderedDiffChanged:!areDiffTargetsEqual(previousRenderedDiff,pendingRenderDiff)}}syncVirtualizedTop(){this.top=this.getVirtualizedTop()}shouldDisableVirtualizationBuffers(){return this.isAdvancedMode()||super.shouldDisableVirtualizationBuffers()}shouldGuardRebuildScroll(){return!1}isSimpleMode(){return this.virtualizer.type==="simple"}isAdvancedMode(){return this.virtualizer.type==="advanced"}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}getAdvancedVirtualizer(){return this.virtualizer.type==="advanced"?this.virtualizer:void 0}isResizeDebuggingEnabled(){return this.getSimpleVirtualizer()?.config.resizeDebugging??!1}getDiffStyle(){return this.options.diffStyle??"split"}getHunkSeparatorType(){return getOptionHunkSeparatorType(this.options.hunkSeparators)}approximateLayoutCheckpoints(fileDiff){if(!this.layoutDirty&&this.cache.checkpoints.length>0||fileDiff.hunks.length===0||this.options.collapsed===!0)return;const{disableFileHeader=!1,expandUnchanged=!1,collapsedContextThreshold=1}=this.options,finalHunkIndex=fileDiff.hunks.length-1,canHydratePartialDiff=canHydrateCollapsedContext(fileDiff,this.options.loadDiffFiles!=null),diffStyle=this.getDiffStyle(),hunkSeparators=this.getHunkSeparatorType(),expandedHunks=expandUnchanged?!0:this.hunksRenderer.getExpandedHunksMap(),heightDeltaPrefix=createHeightDeltaPrefix(this.cache.heightDeltas);let top=getVirtualFileHeaderRegion(this.metrics,disableFileHeader)+this.cache.fileAnnotationHeight,renderedLineIndex=0;const processRows=({rowCount,startLineIndex,preSeparatorHeight=0,postSeparatorHeight=0,metadataOffsets=[]})=>{if(rowCount<=0)return;const blockStart=renderedLineIndex,blockEnd=renderedLineIndex+rowCount;let nextCheckpoint=getNextCheckpointIndex(blockStart);for(;nextCheckpoint<blockEnd;){const offset=nextCheckpoint-blockStart,checkpointTop=top+(offset>0?preSeparatorHeight:0)+offset*this.metrics.lineHeight+countMetadataOffsetsBefore(metadataOffsets,offset)*this.metrics.lineHeight+sumHeightDeltas(heightDeltaPrefix,startLineIndex,startLineIndex+offset);this.cache.checkpoints.push({renderedLineIndex:nextCheckpoint,lineIndex:startLineIndex+offset,top:checkpointTop}),nextCheckpoint+=VIRTUALIZED_FILE_DIFF_LAYOUT_CHECKPOINT_INTERVAL}top+=preSeparatorHeight+rowCount*this.metrics.lineHeight+metadataOffsets.length*this.metrics.lineHeight+sumHeightDeltas(heightDeltaPrefix,startLineIndex,startLineIndex+rowCount)+postSeparatorHeight,renderedLineIndex=blockEnd};for(let hunkIndex=0;hunkIndex<fileDiff.hunks.length;hunkIndex++){const hunk=fileDiff.hunks[hunkIndex];if(hunk==null)throw new Error("VirtualizedFileDiff.approximateLayoutCheckpoints: invalid hunk index");const leadingRegion=getExpandedRegion({isPartial:fileDiff.isPartial,rangeSize:hunk.collapsedBefore,expandedHunks,hunkIndex,collapsedContextThreshold}),leadingSeparatorHeight=leadingRegion.collapsedLines>0?getLeadingHunkSeparatorLayout({type:hunkSeparators,metrics:this.metrics,hunkIndex,hunkSpecs:hunk.hunkSpecs})?.totalHeight??0:0;processRows({rowCount:leadingRegion.fromStart,startLineIndex:(diffStyle==="split"?hunk.splitLineStart:hunk.unifiedLineStart)-leadingRegion.rangeSize});let pendingLeadingSeparatorHeight=leadingSeparatorHeight;processRows({rowCount:leadingRegion.fromEnd,startLineIndex:(diffStyle==="split"?hunk.splitLineStart:hunk.unifiedLineStart)-leadingRegion.fromEnd,preSeparatorHeight:pendingLeadingSeparatorHeight}),leadingRegion.fromEnd>0&&(pendingLeadingSeparatorHeight=0);const trailingRegion=hunkIndex===finalHunkIndex?getTrailingExpandedRegion({fileDiff,hunkIndex,expandedHunks,collapsedContextThreshold,errorPrefix:"VirtualizedFileDiff"}):void 0,trailingSeparatorHeight=trailingRegion!=null&&trailingRegion.collapsedLines>0?getTrailingHunkSeparatorLayout({type:hunkSeparators,metrics:this.metrics})?.totalHeight??0:hunkIndex===finalHunkIndex&&canHydratePartialDiff?getTrailingHunkSeparatorLayout({type:hunkSeparators,metrics:this.metrics})?.totalHeight??0:0,trailingExpandedCount=trailingRegion!=null?trailingRegion.fromStart+trailingRegion.fromEnd:0,hunkBodyRowCount=diffStyle==="split"?hunk.splitLineCount:hunk.unifiedLineCount,hunkBodyStartLineIndex=diffStyle==="split"?hunk.splitLineStart:hunk.unifiedLineStart;processRows({rowCount:hunkBodyRowCount,startLineIndex:hunkBodyStartLineIndex,preSeparatorHeight:pendingLeadingSeparatorHeight,postSeparatorHeight:trailingExpandedCount===0?trailingSeparatorHeight:0,metadataOffsets:getHunkMetadataOffsets({diffStyle,hunk,rowCount:hunkBodyRowCount})}),trailingRegion!=null&&trailingExpandedCount>0&&processRows({rowCount:trailingExpandedCount,startLineIndex:hunkBodyStartLineIndex+hunkBodyRowCount,postSeparatorHeight:trailingSeparatorHeight})}this.cache.totalLines=renderedLineIndex}getLayoutCheckpointBeforeLineIndex(lineIndex){if(lineIndex<=0||this.cache.checkpoints.length===0)return;let low=0,high=this.cache.checkpoints.length-1,result;for(;low<=high;){const mid=low+high>>1,checkpoint=this.cache.checkpoints[mid];if(checkpoint==null)throw new Error("VirtualizedFileDiff: invalid checkpoint index");checkpoint.lineIndex<=lineIndex?(result=checkpoint,low=mid+1):high=mid-1}return result}getLayoutCheckpointBeforeTop(top,hunkLineCount){let low=0,high=this.cache.checkpoints.length-1,resultIndex=-1;for(;low<=high;){const mid=low+high>>1,checkpoint=this.cache.checkpoints[mid];if(checkpoint==null)throw new Error("VirtualizedFileDiff: invalid checkpoint index");checkpoint.top<=top?(resultIndex=mid,low=mid+1):high=mid-1}if(hunkLineCount==null)return resultIndex>=0?this.cache.checkpoints[resultIndex]:void 0;for(let index=resultIndex;index>=0;index--){const checkpoint=this.cache.checkpoints[index];if(checkpoint==null)throw new Error("VirtualizedFileDiff: invalid checkpoint index");if(checkpoint.renderedLineIndex%hunkLineCount===0)return checkpoint}}getExpandedLineCount(fileDiff,diffStyle){let count=0;if(fileDiff.isPartial){for(const hunk of fileDiff.hunks)count+=diffStyle==="split"?hunk.splitLineCount:hunk.unifiedLineCount;return count}const{expandUnchanged=!1,collapsedContextThreshold=1}=this.options,expandedHunks=expandUnchanged?!0:this.hunksRenderer.getExpandedHunksMap();for(const[hunkIndex,hunk]of fileDiff.hunks.entries()){const hunkCount=diffStyle==="split"?hunk.splitLineCount:hunk.unifiedLineCount;count+=hunkCount;const collapsedBefore=Math.max(hunk.collapsedBefore,0),{fromStart,fromEnd,renderAll}=getExpandedRegion({isPartial:fileDiff.isPartial,rangeSize:collapsedBefore,expandedHunks,hunkIndex,collapsedContextThreshold});collapsedBefore>0&&(count+=renderAll?collapsedBefore:fromStart+fromEnd)}const trailingRegion=getTrailingExpandedRegion({fileDiff,hunkIndex:fileDiff.hunks.length-1,expandedHunks,collapsedContextThreshold,errorPrefix:"VirtualizedFileDiff"});return trailingRegion!=null&&(count+=trailingRegion.fromStart+trailingRegion.fromEnd),count}getLayoutLineCount(fileDiff,diffStyle){const expandedLineCount=this.getExpandedLineCount(fileDiff,diffStyle),metadataLineCount=diffStyle==="split"?fileDiff.splitLineCount:fileDiff.unifiedLineCount;return Math.max(expandedLineCount,metadataLineCount,fileDiff.additionLines.length,fileDiff.deletionLines.length,this.cache.totalLines)}computeRenderRangeFromWindow(fileDiff,fileTop,{top,bottom}){const{disableFileHeader=!1,expandUnchanged=!1,collapsedContextThreshold=1}=this.options,{hunkLineCount,lineHeight}=this.metrics,diffStyle=this.getDiffStyle(),hunkSeparators=this.getHunkSeparatorType(),canHydratePartialDiff=canHydrateCollapsedContext(fileDiff,this.options.loadDiffFiles!=null),fileHeight=this.height;let lineCount=this.getLayoutLineCount(fileDiff,diffStyle);const headerRegion=getVirtualFileHeaderRegion(this.metrics,disableFileHeader),paddingBottom=fileDiff.hunks.length>0?getVirtualFilePaddingBottom(this.metrics):0,{fileAnnotationHeight}=this.cache,codeRegionTop=headerRegion+fileAnnotationHeight,codeHeight=Math.max(0,fileHeight-headerRegion-fileAnnotationHeight-paddingBottom),hasFileAnnotations=this.hasFileAnnotations(fileDiff),fileAnnotationTop=fileTop+headerRegion,measuredFileAnnotationVisible=fileAnnotationHeight>0&&hasFileAnnotations&&fileAnnotationTop<bottom&&fileAnnotationTop+fileAnnotationHeight>top;if(fileTop<top-fileHeight||fileTop>bottom)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:fileHeight-headerRegion-paddingBottom};if(lineCount<=hunkLineCount||fileDiff.hunks.length===0)return{startingLine:0,totalLines:hunkLineCount,bufferBefore:0,bufferAfter:0};this.approximateLayoutCheckpoints(fileDiff),lineCount=this.getLayoutLineCount(fileDiff,diffStyle);const estimatedTargetLines=Math.ceil(Math.max(bottom-top,0)/lineHeight),totalLines=Math.ceil(estimatedTargetLines/hunkLineCount)*hunkLineCount+hunkLineCount,totalHunks=totalLines/hunkLineCount,overflowHunks=totalHunks,hunkOffsets=[],viewportCenter=(top+bottom)/2,checkpoint=this.getLayoutCheckpointBeforeTop(Math.max(0,top-fileTop-totalLines*lineHeight*2),hunkLineCount);let absoluteLineTop=fileTop+(checkpoint?.top??codeRegionTop),currentLine=checkpoint?.renderedLineIndex??0,firstVisibleHunk,centerHunk,overflowCounter;if(iterateOverDiff({diff:fileDiff,diffStyle,startingLine:checkpoint?.renderedLineIndex??0,expandedHunks:expandUnchanged?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold,callback:({hunkIndex,hunk,collapsedBefore,collapsedAfter,deletionLine,additionLine})=>{const splitLineIndex=additionLine!=null?additionLine.splitLineIndex:deletionLine.splitLineIndex,unifiedLineIndex=additionLine!=null?additionLine.unifiedLineIndex:deletionLine.unifiedLineIndex,hasMetadata=(additionLine?.noEOFCR??!1)||(deletionLine?.noEOFCR??!1),isFinalHunkRow=hunkIndex===fileDiff.hunks.length-1&&hunk!=null&&(diffStyle==="split"?splitLineIndex===hunk.splitLineStart+hunk.splitLineCount-1:unifiedLineIndex===hunk.unifiedLineStart+hunk.unifiedLineCount-1),gapAdjustment=(collapsedBefore>0?getLeadingHunkSeparatorLayout({type:hunkSeparators,metrics:this.metrics,hunkIndex,hunkSpecs:hunk?.hunkSpecs}):void 0)?.totalHeight??0;absoluteLineTop+=gapAdjustment;const isAtHunkBoundary=currentLine%hunkLineCount===0,currentHunk=Math.floor(currentLine/hunkLineCount);if(isAtHunkBoundary&&(hunkOffsets[currentHunk]=absoluteLineTop-(fileTop+codeRegionTop+gapAdjustment),overflowCounter!=null)){if(overflowCounter<=0)return!0;overflowCounter--}const lineHeight2=this.getLineHeight(diffStyle==="split"?splitLineIndex:unifiedLineIndex,hasMetadata);if(absoluteLineTop>top-lineHeight2&&absoluteLineTop<bottom&&(firstVisibleHunk??=currentHunk),centerHunk==null&&absoluteLineTop+lineHeight2>viewportCenter&&(centerHunk=currentHunk),overflowCounter==null&&absoluteLineTop>=bottom&&isAtHunkBoundary&&(overflowCounter=overflowHunks),currentLine++,absoluteLineTop+=lineHeight2,collapsedAfter>0||isFinalHunkRow&&canHydratePartialDiff){const trailingSeparator=getTrailingHunkSeparatorLayout({type:hunkSeparators,metrics:this.metrics});trailingSeparator!=null&&(absoluteLineTop<bottom&&absoluteLineTop+trailingSeparator.totalHeight>top&&(firstVisibleHunk??=currentHunk),centerHunk==null&&absoluteLineTop+trailingSeparator.totalHeight>viewportCenter&&(centerHunk=currentHunk),absoluteLineTop+=trailingSeparator.totalHeight)}return!1}}),firstVisibleHunk==null)if(measuredFileAnnotationVisible)firstVisibleHunk=0,centerHunk=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:fileHeight-headerRegion-paddingBottom};centerHunk??=firstVisibleHunk;const idealStartHunk=Math.round(centerHunk-totalHunks/2),maxStartHunk=Math.max(0,Math.ceil(lineCount/hunkLineCount)-totalHunks),startHunk=Math.max(0,Math.min(idealStartHunk,maxStartHunk)),startingLine=startHunk*hunkLineCount,clampedTotalLines=idealStartHunk<0?totalLines+idealStartHunk*hunkLineCount:totalLines,codeBufferBefore=hunkOffsets[startHunk]??0,bufferBefore=startingLine===0?0:fileAnnotationHeight+codeBufferBefore,finalHunkIndex=startHunk+clampedTotalLines/hunkLineCount,bufferAfter=finalHunkIndex<hunkOffsets.length?codeHeight-hunkOffsets[finalHunkIndex]:codeHeight-(absoluteLineTop-fileTop-codeRegionTop);return{startingLine,totalLines:clampedTotalLines,bufferBefore,bufferAfter:Math.max(0,bufferAfter)}}};function measureFileAnnotationHeight(codeGroups){let height;for(const codeGroup of codeGroups){if(codeGroup==null)continue;const content=codeGroup.children[1];if(content instanceof HTMLElement)for(const child of content.children)child instanceof HTMLElement&&child.dataset.lineAnnotation===FILE_ANNOTATION_DOM_KEY&&(height=Math.max(height??0,child.getBoundingClientRect().height))}return height}function createHeightDeltaPrefix(heightDeltas){const entries=Array.from(heightDeltas).sort((a,b)=>a[0]-b[0]),lineIndexes=[],prefixTotals=[0];let total=0;for(const[lineIndex,delta]of entries)lineIndexes.push(lineIndex),total+=delta,prefixTotals.push(total);return{lineIndexes,prefixTotals}}function sumHeightDeltas({lineIndexes,prefixTotals},startLineIndex,endLineIndex){if(startLineIndex>=endLineIndex||lineIndexes.length===0)return 0;const start=lowerBound(lineIndexes,startLineIndex);return(prefixTotals[lowerBound(lineIndexes,endLineIndex)]??0)-(prefixTotals[start]??0)}function lowerBound(values,target){let low=0,high=values.length;for(;low<high;){const mid=low+high>>1,value=values[mid];if(value==null)throw new Error("VirtualizedFileDiff: invalid prefix index");value<target?low=mid+1:high=mid}return low}function getNextCheckpointIndex(renderedLineIndex){return Math.ceil(renderedLineIndex/VIRTUALIZED_FILE_DIFF_LAYOUT_CHECKPOINT_INTERVAL)*VIRTUALIZED_FILE_DIFF_LAYOUT_CHECKPOINT_INTERVAL}function countMetadataOffsetsBefore(metadataOffsets,offset){let count=0;for(const metadataOffset of metadataOffsets)metadataOffset<offset&&count++;return count}function getHunkMetadataOffsets({diffStyle,hunk,rowCount}){if(rowCount<=0||!hunk.noEOFCRAdditions&&!hunk.noEOFCRDeletions)return[];const lastContent=hunk.hunkContent.at(-1);if(lastContent==null)return[];if(lastContent.type==="context")return[rowCount-1];const splitCount=Math.max(lastContent.deletions,lastContent.additions),unifiedCount=lastContent.deletions+lastContent.additions;if(diffStyle==="split")return splitCount>0&&(hunk.noEOFCRAdditions||hunk.noEOFCRDeletions)?[rowCount-1]:[];const offsets=[],contentStartOffset=rowCount-unifiedCount;return lastContent.deletions>0&&hunk.noEOFCRDeletions&&offsets.push(contentStartOffset+lastContent.deletions-1),lastContent.additions>0&&hunk.noEOFCRAdditions&&offsets.push(rowCount-1),offsets}function hasDiffLayoutOptionChanged(previousOptions,nextOptions){return(previousOptions.diffStyle??"split")!==(nextOptions.diffStyle??"split")||(previousOptions.overflow??"scroll")!==(nextOptions.overflow??"scroll")||(previousOptions.collapsed??!1)!==(nextOptions.collapsed??!1)||(previousOptions.disableLineNumbers??!1)!==(nextOptions.disableLineNumbers??!1)||(previousOptions.disableFileHeader??!1)!==(nextOptions.disableFileHeader??!1)||(previousOptions.diffIndicators??"bars")!==(nextOptions.diffIndicators??"bars")||(previousOptions.hunkSeparators??"line-info")!==(nextOptions.hunkSeparators??"line-info")||!!previousOptions.loadDiffFiles!=!!nextOptions.loadDiffFiles||(previousOptions.expandUnchanged??!1)!==(nextOptions.expandUnchanged??!1)||(previousOptions.collapsedContextThreshold??1)!==(nextOptions.collapsedContextThreshold??1)||previousOptions.unsafeCSS!==nextOptions.unsafeCSS}function hasDiffEstimateOptionChanged(previousOptions,nextOptions){return(previousOptions.disableFileHeader??!1)!==(nextOptions.disableFileHeader??!1)||(previousOptions.hunkSeparators??"line-info")!==(nextOptions.hunkSeparators??"line-info")||!!previousOptions.loadDiffFiles!=!!nextOptions.loadDiffFiles||(previousOptions.expandUnchanged??!1)!==(nextOptions.expandUnchanged??!1)||(previousOptions.collapsedContextThreshold??1)!==(nextOptions.collapsedContextThreshold??1)}function canHydrateCollapsedContext(fileDiff,hasFileLoader){return fileDiff.isPartial&&hasFileLoader&&(fileDiff.type==="change"||fileDiff.type==="rename-changed")}function getOptionHunkSeparatorType(hunkSeparators){return typeof hunkSeparators=="function"?"custom":hunkSeparators??"line-info"}function areOptionalFilesEqual(fileA,fileB){return fileA==null||fileB==null?fileA==null&&fileB==null:areFilesEqual(fileA,fileB)}function parseLineIndex(lineIndexAttr,diffStyle){const[unifiedIndex,splitIndex]=lineIndexAttr.split(",").map(Number);return diffStyle==="split"?splitIndex:unifiedIndex}function getMergeConflictActionSlotName({hunkIndex,lineIndex,conflictIndex}){return`merge-conflict-action-${hunkIndex}-${lineIndex}-${conflictIndex}`}function getMergeConflictActionAnchor(action,fileDiff){const hunk=fileDiff.hunks[action.hunkIndex];if(hunk!=null)return{hunkIndex:action.hunkIndex,lineIndex:getUnifiedLineStartForContent(hunk,action.startContentIndex)}}function getUnifiedLineStartForContent(hunk,contentIndex){let lineIndex=hunk.unifiedLineStart;for(let index=0;index<contentIndex;index++){const content=hunk.hunkContent[index];lineIndex+=content.type==="context"?content.lines:content.deletions+content.additions}return lineIndex}function getSingularPatch(patch){const parsedPatches=parsePatchFiles(patch);if(parsedPatches.length!==1)throw console.error(parsedPatches),new Error("PatchDiff: Provided patch must include only 1 patch, with 1 diff");const{files}=parsedPatches[0];if(files.length!==1)throw console.error(files),new Error("FileDiff: Provided patch must contain exactly 1 file diff");return files[0]}function renderDiffChildren({fileDiff,actions,renderCustomHeader,renderHeaderPrefix,renderHeaderFilenameSuffix,renderHeaderMetadata,renderAnnotation,renderGutterUtility,renderMergeConflictUtility,lineAnnotations,getHoveredLine,getInstance,getAnnotationSlotName=getLineAnnotationName}){const customHeader=renderCustomHeader?.(fileDiff),prefix=renderHeaderPrefix?.(fileDiff),suffix=renderHeaderFilenameSuffix?.(fileDiff),metadata=renderHeaderMetadata?.(fileDiff);return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[customHeader!=null?jsxRuntimeExports.jsx("div",{slot:CUSTOM_HEADER_SLOT_ID,children:customHeader}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[prefix!=null&&jsxRuntimeExports.jsx("div",{slot:"header-prefix",children:prefix}),suffix!=null&&jsxRuntimeExports.jsx("div",{slot:"header-filename-suffix",children:suffix}),metadata!=null&&jsxRuntimeExports.jsx("div",{slot:"header-metadata",children:metadata})]}),renderAnnotation!=null&&lineAnnotations?.map((annotation,index)=>jsxRuntimeExports.jsx("div",{slot:getAnnotationSlotName(annotation),children:renderAnnotation(annotation,fileDiff)},index)),actions!=null&&renderMergeConflictUtility!=null&&getInstance!=null&&actions.map(action=>{if(action==null)return;const slot=getSlotName(action,fileDiff);return jsxRuntimeExports.jsx("div",{slot,style:MergeConflictSlotStyles,children:renderMergeConflictUtility(action,getInstance)},slot)}),renderGutterUtility!=null&&jsxRuntimeExports.jsx("div",{slot:"gutter-utility-slot",style:GutterUtilitySlotStyles,children:renderGutterUtility(getHoveredLine)})]})}function getSlotName(action,fileDiff){const anchor=getMergeConflictActionAnchor(action,fileDiff);return anchor!=null?getMergeConflictActionSlotName({hunkIndex:anchor.hunkIndex,lineIndex:anchor.lineIndex,conflictIndex:action.conflictIndex}):void 0}const useIsomorphicLayoutEffect=typeof window>"u"?reactExports.useEffect:reactExports.useLayoutEffect;function useFileDiffInstance({fileDiff,oldFile,newFile,options,editorOptions,editStateKey,lineAnnotations,selectedLines,prerenderedHTML,metrics,hasGutterRenderUtility,hasCustomHeader,disableWorkerPool,edit,onEditChange:_onEditChange,onEditComplete:_onEditComplete}){const simpleVirtualizer=useVirtualizer(),controlledSelection=selectedLines!==void 0,poolManager=reactExports.useContext(WorkerPoolContext),createEditor=useCreateEditor(),[asyncAttachError,setAsyncAttachError]=reactExports.useState(),handleOnEditChange=useStableCallback(event=>_onEditChange?.(event)),onEditChange=_onEditChange!=null?handleOnEditChange:void 0,acceptedCache=reactExports.useRef(null),handleOnEditComplete=useStableCallback(event=>{const decision=_onEditComplete?.(event)??"reject";return decision==="accept"&&(acceptedCache.current={fileDiff:{installed:event.fileDiff,stale:event.originalFileDiff},filePair:fileDiff==null?{fileDiff:event.fileDiff,installed:{oldFile:event.oldFile,newFile:event.newFile},stale:{oldFile:oldFile??null,newFile:newFile??null}}:null,annotations:{installed:event.lineAnnotations,stale:event.originalLineAnnotations}}),decision}),onEditComplete=_onEditComplete!=null?handleOnEditComplete:void 0,effectiveFileDiff=useEffectiveFileDiff({acceptedCache,fileDiff,newFile,oldFile,parseDiffOptions:options?.parseDiffOptions}),instanceRef=reactExports.useRef(null),forceUpdate=useForceUpdate(),accepted=useAcceptedValues(acceptedCache,effectiveFileDiff,lineAnnotations),renderData=useNextRenderData(instanceRef,accepted)??{fileDiff:effectiveFileDiff,lineAnnotations:lineAnnotations??EMPTY_LINE_ANNOTATIONS},disposeEditorRef=reactExports.useRef(null),pendingAttachRef=reactExports.useRef(null),getEditor=useStableCallback(()=>{if(createEditor==null)throw new Error("FileDiff: EditContext is not attached");return createEditor("file-diff",editorOptions??{},editStateKey)}),ref=useStableCallback(fileContainer=>{if(fileContainer!=null){if(instanceRef.current!=null)throw new Error("useFileDiffInstance: An instance should not already exist when a node is created");simpleVirtualizer!=null?instanceRef.current=new VirtualizedFileDiff(mergeFileDiffOptions({controlledSelection,hasCustomHeader,hasGutterRenderUtility,onEditChange,onEditComplete,options}),simpleVirtualizer,metrics,disableWorkerPool?void 0:poolManager,forceUpdate):instanceRef.current=new FileDiff$1(mergeFileDiffOptions({controlledSelection,hasCustomHeader,hasGutterRenderUtility,onEditChange,onEditComplete,options}),disableWorkerPool?void 0:poolManager,forceUpdate),instanceRef.current.hydrate({fileDiff:effectiveFileDiff,fileContainer,lineAnnotations,prerenderedHTML})}else{if(instanceRef.current==null)throw new Error("useFileDiffInstance: A FileDiff instance should exist when unmounting");pendingAttachRef.current=null,instanceRef.current.cleanUp(),instanceRef.current=null,disposeEditorRef.current=null}});useIsomorphicLayoutEffect(()=>{const{current:instance}=instanceRef;if(instance==null)return;const newOptions=mergeFileDiffOptions({controlledSelection,hasCustomHeader,hasGutterRenderUtility,onEditChange,onEditComplete,options}),forceRender=!areOptionsEqual(instance.options,newOptions);if(instance.setOptions(newOptions),!edit&&(pendingAttachRef.current=null,disposeEditorRef.current!=null)){const{current:disposeEditor}=disposeEditorRef;disposeEditorRef.current=null,disposeEditor()}const resolved=resolveAcceptedValues(effectiveFileDiff,lineAnnotations,acceptedCache);if(instance.render({forceRender,fileDiff:resolved.fileDiff,lineAnnotations:resolved.lineAnnotations}),selectedLines!==void 0&&instance.setSelectedLines(selectedLines),!edit||disposeEditorRef.current!=null)return;if(createEditor==null)throw new Error("FileDiff: EditContext is not attached");const attach=()=>{instanceRef.current!==instance||disposeEditorRef.current!=null||!instance.__canAttachEditor()||(disposeEditorRef.current=applyEdit(instance,getEditor),forceUpdate())};if(instance.__canAttachEditor()){pendingAttachRef.current=null,attach();return}const promise=instance.__prepareForEditing();if(promise==null){pendingAttachRef.current=null;return}if(pendingAttachRef.current?.promise===promise)return;const pending={promise};pendingAttachRef.current=pending,promise.then(()=>{pendingAttachRef.current===pending&&(attach(),pendingAttachRef.current=null)}).catch(error=>{pendingAttachRef.current===pending&&(pendingAttachRef.current=null,setAsyncAttachError(error))})});const getHoveredLine=reactExports.useCallback(()=>instanceRef.current?.getHoveredLine(),[]),getAnnotationSlotName=reactExports.useCallback(annotation=>instanceRef.current?.getAnnotationSlotName(annotation)??getLineAnnotationName(annotation),[]);if(asyncAttachError!=null)throw asyncAttachError;return{...renderData,ref,getHoveredLine,getAnnotationSlotName}}function useEffectiveFileDiff({acceptedCache,fileDiff,newFile,oldFile,parseDiffOptions}){return reactExports.useMemo(()=>{if(fileDiff!=null)return fileDiff;const{current:accepted}=acceptedCache,filePair=accepted?.filePair;if(accepted!=null&&filePair!=null){if(isSameFilePair(oldFile,newFile,filePair.stale)||isSameFilePair(oldFile,newFile,filePair.installed))return filePair.fileDiff;accepted.filePair=null}return parseDiffFromFile(oldFile??null,newFile??null,parseDiffOptions)},[acceptedCache,fileDiff,oldFile,newFile,parseDiffOptions])}function isSameFilePair(oldFile,newFile,filePair){return areFileTargetsEqual(oldFile??void 0,filePair.oldFile??void 0)&&areFileTargetsEqual(newFile??void 0,filePair.newFile??void 0)}function useAcceptedValues(acceptedCache,fileDiff,lineAnnotations){"use no memo";return getAcceptedValues(fileDiff,lineAnnotations,acceptedCache.current)}function getAcceptedValues(fileDiff,lineAnnotations,accepted){return{fileDiff:accepted?.fileDiff!=null&&areDiffTargetsEqual(fileDiff,accepted.fileDiff.stale)?accepted.fileDiff.installed:fileDiff,lineAnnotations:accepted?.annotations!=null&&lineAnnotations===accepted.annotations.stale?accepted.annotations.installed:lineAnnotations}}function resolveAcceptedValues(fileDiff,lineAnnotations,acceptedCache){const{current:accepted}=acceptedCache,resolved=getAcceptedValues(fileDiff,lineAnnotations,accepted);return accepted==null||(accepted.fileDiff!=null&&!areDiffTargetsEqual(fileDiff,accepted.fileDiff.stale)&&(accepted.fileDiff=null),lineAnnotations!==accepted.annotations?.stale&&(accepted.annotations=null),accepted.fileDiff==null&&accepted.annotations==null&&accepted.filePair==null&&(acceptedCache.current=null)),resolved}function mergeFileDiffOptions({options,controlledSelection,hasCustomHeader,hasGutterRenderUtility,onEditChange,onEditComplete}){return{...options,controlledSelection,renderCustomHeader:hasCustomHeader?noopRender:options?.renderCustomHeader,renderGutterUtility:hasGutterRenderUtility?noopRender:options?.renderGutterUtility,onEditChange,onEditComplete}}function applyEdit(instance,getEditor){const editor=getEditor();try{return editor.edit(instance)}catch(error){throw editor.cleanUp(),error}}function FileDiff2({fileDiff,options,editorOptions,editStateKey,metrics,lineAnnotations,selectedLines,className,style,prerenderedHTML,renderAnnotation,renderCustomHeader,renderHeaderPrefix,renderHeaderFilenameSuffix,renderHeaderMetadata,renderGutterUtility,disableWorkerPool=!1,edit=!1,onEditChange,onEditComplete}){const{ref,getHoveredLine,getAnnotationSlotName,fileDiff:renderedDiff,lineAnnotations:renderedAnnotations}=useFileDiffInstance({fileDiff,options,editorOptions,editStateKey,metrics,lineAnnotations,selectedLines,prerenderedHTML,hasGutterRenderUtility:renderGutterUtility!=null,hasCustomHeader:renderCustomHeader!=null,disableWorkerPool,edit,onEditChange,onEditComplete}),children=renderDiffChildren({fileDiff:renderedDiff,renderCustomHeader,renderHeaderPrefix,renderHeaderFilenameSuffix,renderHeaderMetadata,renderAnnotation,renderGutterUtility,lineAnnotations:renderedAnnotations,getHoveredLine,getAnnotationSlotName});return jsxRuntimeExports.jsx(DIFFS_TAG_NAME,{ref,className,style,children:templateRender(children,prerenderedHTML)})}function PatchDiff({patch,options,editorOptions,editStateKey,metrics,lineAnnotations,selectedLines,className,style,prerenderedHTML,renderAnnotation,renderCustomHeader,renderHeaderPrefix,renderHeaderFilenameSuffix,renderHeaderMetadata,renderGutterUtility,disableWorkerPool=!1,edit=!1,onEditChange,onEditComplete}){const fileDiff=usePatch(patch),{ref,getHoveredLine,getAnnotationSlotName,fileDiff:renderedDiff,lineAnnotations:renderedAnnotations}=useFileDiffInstance({fileDiff,options,editorOptions,editStateKey,metrics,lineAnnotations,selectedLines,prerenderedHTML,hasGutterRenderUtility:renderGutterUtility!=null,hasCustomHeader:renderCustomHeader!=null,disableWorkerPool,edit,onEditChange,onEditComplete}),children=renderDiffChildren({fileDiff:renderedDiff,renderCustomHeader,renderHeaderPrefix,renderHeaderFilenameSuffix,renderHeaderMetadata,renderAnnotation,lineAnnotations:renderedAnnotations,renderGutterUtility,getHoveredLine,getAnnotationSlotName});return jsxRuntimeExports.jsx(DIFFS_TAG_NAME,{ref,className,style,children:templateRender(children,prerenderedHTML)})}function usePatch(patch){return reactExports.useMemo(()=>getSingularPatch(patch),[patch])}const DIAGNOSTIC_GLYPH={error:{icon:"i-ph-x-circle-fill",tone:"text-zg-danger"},warning:{icon:"i-ph-warning",tone:"text-zg-warn"},info:{icon:"i-ph-info",tone:"text-zg-info"},hint:{icon:"i-ph-lightbulb",tone:"text-[var(--zg-text-muted)]"}};function diagnosticsAt(items,line,column){return items.filter(d=>{const endLine=d.endLine??d.line;if(line<d.line||line>endLine)return!1;const startsBefore=line>d.line||column>=d.column,endsAfter=line<endLine||column<(d.endColumn??d.column+1);return startsBefore&&endsAfter})}function countBySeverity(items){let errors=0,warnings=0,other=0;for(const d of items)d.severity==="error"?errors++:d.severity==="warning"?warnings++:other++;return{errors,warnings,other}}function diagnosticMarkers(items){return items.map(d=>({start:{line:d.line-1,character:Math.max(0,d.column-1)},end:{line:(d.endLine??d.line)-1,character:d.endColumn!==void 0?Math.max(0,d.endColumn-1):Math.max(0,d.column-1)+1},severity:d.severity,message:d.code?`${d.message} (${d.source} ${d.code})`:`${d.message} (${d.source})`,source:d.source}))}function diagnosticsByLine(items){const byLine=new Map;for(const d of items)byLine.set(d.line,[...byLine.get(d.line)??[],d]);return byLine}function absolutePath(t){return t.path.startsWith("/")?t.path:`${t.cwd.replace(/\/$/,"")}/${t.path}`}async function copy(text){try{await navigator.clipboard.writeText(text)}catch(err){console.error("[zidane-ui] clipboard write failed",err)}}function noChatItem(id,label,labels){return{id,label,title:labels.filesNoChat,disabled:!0,onSelect:()=>{}}}function entryItems(t,entries,labels){const dir=t.kind==="folder"?t.path:t.path.slice(0,Math.max(0,t.path.lastIndexOf("/"))),create=[{id:"new-file",label:labels.filesNewFile,group:"new",onSelect:()=>entries.create(dir,"file")},{id:"new-folder",label:labels.filesNewFolder,group:"new",onSelect:()=>entries.create(dir,"folder")}],paste=[{id:"paste",label:labels.filesPaste,group:"edit",disabled:!entries.paste,onSelect:()=>entries.paste?.(dir)}];if(t.path==="")return{before:create,after:paste};const edit=[{id:"rename",label:labels.filesRename,group:"edit",onSelect:()=>entries.rename(t.path)},{id:"duplicate",label:labels.filesDuplicate,group:"edit",onSelect:()=>entries.duplicate(t.path)},{id:"cut",label:labels.filesCut,group:"edit",onSelect:()=>entries.clip(t.path,"cut")},{id:"copy",label:labels.filesCopy,group:"edit",onSelect:()=>entries.clip(t.path,"copy")},...paste],remove=entries.remove?[{id:"delete",label:labels.filesDelete,group:"danger",destructive:!0,onSelect:()=>entries.remove?.(t.path,t.kind)}]:[];return{before:create,after:[...edit,...remove]}}function fileActionItems(t,opts){const{labels,system}=opts,abs=absolutePath(t),chat=opts.chat,entries=opts.entries?entryItems(t,opts.entries,labels):null;if(t.path===""){const rows=entries?[...entries.before,...entries.after]:[];return opts.only?opts.only.flatMap(id=>rows.filter(i=>i.id===id)):rows}const all=[...t.kind==="folder"&&entries?entries.before:[],chat?{id:"chat",label:labels.filesAddToChat,shortcut:"a",onSelect:()=>chat.mention(t.path)}:noChatItem("chat",labels.filesAddToChat,labels),{id:"copy-path",label:labels.filesCopyPath,shortcut:"c",onSelect:()=>{copy(abs)}},{id:"copy-rel",label:labels.filesCopyRelativePath,shortcut:"r",onSelect:()=>{copy(t.path)}}];system?.isLocal(t.cwd)&&all.push({id:"editor",label:t.kind==="file"?labels.filesOpenInEditor:labels.filesOpenFolderInEditor,shortcut:"e",onSelect:()=>{system.openPath(abs).catch(()=>!1)}},{id:"reveal",label:labels.filesRevealInFinder,shortcut:"f",onSelect:()=>{system.revealPath(abs).catch(()=>!1)}}),entries&&all.push(...entries.after);const picked=opts.only?opts.only.flatMap(id=>all.filter(i=>i.id===id)):all;return opts.shortcuts===!1?picked.map(({shortcut:_s,...rest})=>rest):picked}const NO_EDITS=[],useNoEdits=()=>NO_EDITS,useNoKeyScope=()=>{},FilesChatContext=reactExports.createContext(null);function useFilesChat(){return reactExports.useContext(FilesChatContext)}function textSelectionIn(container){const root=container?.shadowRoot,sel=root?.getSelection?.()??window.getSelection();if(!sel||sel.isCollapsed||container&&sel.anchorNode&&!container.contains(sel.anchorNode)&&!root?.contains(sel.anchorNode))return null;const text=sel.toString().replace(/\n$/,"");return text.trim().length>0?text:null}function lineAt(path){for(const node of path){if(!(node instanceof HTMLElement))continue;const raw=node.getAttribute("data-column-number")??node.getAttribute("data-line");if(raw===null)continue;const n=Number.parseInt(raw,10);if(Number.isNaN(n))return null;const side=(node.getAttribute("data-line-type")??"").includes("deletion")?"deletions":"additions";return{start:n,end:n,side}}return null}function resolveCodeMenuTarget(path,selected){const container=path.find(n=>n instanceof Element&&n.tagName==="DIFFS-CONTAINER"),text=textSelectionIn(container??null);if(text)return{kind:"text",text};if(selected)return{kind:"range",range:selected};const line=lineAt(path);return line?{kind:"line",range:line}:null}function ReviewDraft({label,excerpt,onSubmit,onCancel}){const labels=useFilesLabels(),[text,setText]=reactExports.useState(""),preview=excerpt===void 0?null:previewOf(excerpt,labels.filesMoreLines);return jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-1.5 px-3 py-2.5 border-s-2 border-[var(--zg-accent)] bg-[var(--zg-tray)] font-sans",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-zg-meta text-[var(--zg-text-muted)]",children:[jsxRuntimeExports.jsx("span",{className:"i-ph-chat-teardrop-text text-zg-label text-[var(--zg-accent)]","aria-hidden":!0}),jsxRuntimeExports.jsx("span",{children:labels.filesCommentOn(label)}),jsxRuntimeExports.jsxs("span",{className:"ml-auto inline-flex items-center gap-1",children:[jsxRuntimeExports.jsx(KeyHint,{spec:"cmd+enter",size:"sm"})," ",labels.filesToAdd]})]}),preview!==null&&jsxRuntimeExports.jsx("pre",{className:`zg-code-panel m-0 max-h-16 overflow-hidden whitespace-pre text-zg-meta leading-4 font-mono rounded-zg-sm px-2 py-1 !text-[var(--zg-text-muted)] ${preview===""?"italic":""}`,"aria-label":labels.filesSelectedLines,children:preview===""?labels.filesBlankLines:preview}),jsxRuntimeExports.jsx("textarea",{autoFocus:!0,value:text,onChange:e=>setText(e.target.value),onKeyDown:e=>{e.key==="Escape"&&onCancel(),e.key==="Enter"&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),onSubmit(text))},placeholder:labels.filesCommentPlaceholder,rows:2,className:"zg-well w-full min-h-12 resize-y px-2 py-1.5 text-xs leading-5 placeholder:text-[var(--zg-text-muted)] font-sans"}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-end gap-1.5",children:[jsxRuntimeExports.jsx("button",{type:"button",onClick:onCancel,className:"zg-raised zg-press-subtle h-6 px-2 rounded-zg-sm border text-zg-meta text-[var(--zg-text-muted)] hover:text-[var(--zg-text)] cursor-pointer",children:labels.filesCancel}),jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>onSubmit(text),disabled:!text.trim(),className:"zg-press-subtle h-6 px-2.5 rounded-zg-sm border-0 zg-fill text-zg-meta font-medium cursor-pointer disabled:opacity-zg-disabled disabled:cursor-not-allowed",children:labels.filesAddToPrompt})]})]})}function previewOf(excerpt,more){const lines=excerpt.split(`
32
32
  `);if(lines.every(l=>l.trim()===""))return"";const indent=Math.min(...lines.filter(l=>l.trim()).map(l=>l.match(/^\s*/)?.[0].length??0)),shown=lines.slice(0,4).map(l=>l.slice(indent));return lines.length>4?[...shown,more(lines.length-4)].join(`
33
33
  `):shown.join(`
34
- `)}async function copyText(text){try{await navigator.clipboard.writeText(text)}catch(err){console.error("[zidane-ui] clipboard write failed",err)}}function describe(target,labels){return target.kind==="text"?labels.filesSelection:rangeLabel(target.range)}function useCodeReview({filePath,kind,excerptOf,extraItems,chat}){const labels=useFilesLabels(),[selected,setSelected]=reactExports.useState(null),[draft,setDraft]=reactExports.useState(null),[menu,setMenu]=reactExports.useState(null),clear=reactExports.useCallback(()=>{setDraft(null),setSelected(null)},[]);reactExports.useEffect(()=>{if(!selected)return;const onKey=e=>{e.key==="Escape"&&!(e.target instanceof HTMLTextAreaElement)&&clear()};return document.addEventListener("keydown",onKey),()=>document.removeEventListener("keydown",onKey)},[selected,clear]);const language=languageFor(filePath),excerptForTarget=t=>t.kind==="text"?t.text:excerptOf(t.range),addToChat=(to,t)=>{const label=t.kind==="text"?null:rangeLabel(t.range),body=serializeCodeSnippet({filePath,rangeLabel:label,excerpt:excerptForTarget(t),language});to.attach(attachmentName("snippet",filePath,label),body)},openDraft=reactExports.useCallback(range=>{setSelected(range),chat&&setDraft(range)},[chat]);reactExports.useEffect(()=>{chat||setDraft(null)},[chat]);const submitDraft=text=>{if(!draft||!chat||!text.trim())return;const body=serializeReviewComment({kind,filePath,rangeLabel:rangeLabel(draft),excerpt:excerptOf(draft),language,text});chat.attach(attachmentName("comment",filePath,rangeLabel(draft)),body),clear()},onContextMenu=e=>{const target=resolveCodeMenuTarget(e.nativeEvent.composedPath(),selected);!target&&!extraItems?.length||(e.preventDefault(),setMenu(target?{target,at:{x:e.clientX,y:e.clientY}}:{target:{kind:"text",text:""},at:{x:e.clientX,y:e.clientY}}))},items=[];if(menu&&!(menu.target.kind==="text"&&menu.target.text==="")){const t=menu.target,what=describe(t,labels);items.push(chat?{id:"chat",label:labels.filesAddWhatToChat(what),shortcut:"a",onSelect:()=>addToChat(chat,t)}:noChatItem("chat",labels.filesAddWhatToChat(what),labels),...t.kind==="text"?[]:[chat?{id:"comment",label:labels.filesCommentOn(what),shortcut:"m",onSelect:()=>openDraft(t.range)}:noChatItem("comment",labels.filesCommentOn(what),labels)],{id:"copy",label:labels.filesCopyWhat(what),shortcut:"c",onSelect:()=>{copyText(excerptForTarget(t))}})}return extraItems?.length&&items.push(...extraItems),{selected,draft,onSelectionEnd:setSelected,openDraft,canComment:chat!==null,onContextMenu,draftNode:draft?jsxRuntimeExports.jsx(ReviewDraft,{label:rangeLabel(draft),excerpt:excerptOf(draft),onSubmit:submitDraft,onCancel:clear}):null,menuNode:jsxRuntimeExports.jsx(RowActionsMenu,{open:menu!==null,position:menu?.at??null,onClose:()=>setMenu(null),items})}}function DiffViewInner({patch,fileDiff,diffStyle="unified",wrap=!1,hideHeader=!1,selectedLines,onSelectionEnd,onGutterAction,onContextMenu,annotations,renderAnnotation,className}){const{shikiTheme:theme,appearance}=useEditorEnvironment(),selectable=onSelectionEnd!==void 0,host=useDetachCleanup(),latest=reactExports.useRef({onSelectionEnd,onGutterAction,renderAnnotation,wrap});latest.current={onSelectionEnd,onGutterAction,renderAnnotation,wrap};const stable=reactExports.useMemo(()=>({onLineSelectionEnd:r=>latest.current.onSelectionEnd?.(r),onGutterUtilityClick:r=>latest.current.onGutterAction?.(r),renderAnnotation:a=>latest.current.renderAnnotation?.(a)??null,onPostRender:(node,instance,phase)=>{const live=phase!=="unmount";revealOnHighlight(node,live&&isDiffHighlighted(instance,node),phase,live&&colorsDiff(instance)),scrollReachOnRender(node,!latest.current.wrap,phase)}}),[]),hasGutter=onGutterAction!==void 0,options=reactExports.useMemo(()=>({theme,themeType:appearance,diffStyle,overflow:wrap?"wrap":"scroll",lineDiffType:"word-alt",preferredHighlighter:PREFERRED_HIGHLIGHTER,diffIndicators:"bars",hunkSeparators:"line-info",disableFileHeader:hideHeader,stickyHeader:!hideHeader,unsafeCSS:DIFFS_UNSAFE_CSS,onPostRender:stable.onPostRender,...selectable?{enableLineSelection:!0,onLineSelectionEnd:stable.onLineSelectionEnd}:{},...hasGutter?{enableGutterUtility:!0,onGutterUtilityClick:stable.onGutterUtilityClick}:{}}),[theme,appearance,diffStyle,wrap,hideHeader,selectable,hasGutter,stable]),lineAnnotations=reactExports.useMemo(()=>annotations?[...annotations]:void 0,[annotations]),shared={className,style:DIFFS_HOST_STYLE,...selectable?{selectedLines:selectedLines??null}:{},...lineAnnotations?{lineAnnotations}:{},...renderAnnotation?{renderAnnotation:stable.renderAnnotation}:{},options};return jsxRuntimeExports.jsx("div",{ref:host,className:"contents",onContextMenu,children:fileDiff?jsxRuntimeExports.jsx(FileDiff2,{fileDiff,...shared}):jsxRuntimeExports.jsx(PatchDiff,{patch:patch??"",...shared})})}function isDiffHighlighted(instance,node){const cache=instance?.hunksRenderer?.renderCache;return cache&&typeof cache.highlighted=="boolean"?cache.highlighted:node.shadowRoot?.querySelector("[data-line] span[class], [data-line] span[style]")!==null}function colorsDiff(instance){const renderer=instance?.hunksRenderer,diff=renderer?.renderCache?.diff;if(!diff)return!1;const lines=Math.max(diff.additionLines.length,diff.deletionLines.length),max=renderer?.getTokenizeMaxLength?.()??DEFAULT_TOKENIZE_MAX_LENGTH,lang=name=>diff.lang??(name===void 0?"text":getFiletypeFromFileName(name));return lines>0&&lines<=max&&(lang(diff.name)!=="text"||lang(diff.prevName)!=="text")}const DiffView=reactExports.memo(DiffViewInner);function DiffScroller({className,contentClassName,children}){return jsxRuntimeExports.jsx(Virtualizer,{className,contentClassName,config:VIRTUALIZER_CONFIG,children})}function hashText(text){let h=2166136261;for(let i=0;i<text.length;i++)h^=text.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function splitPatch(patch){const out=[],re=/^diff --git /gm;let start=-1;for(let m=re.exec(patch);m;m=re.exec(patch))start>=0&&out.push(patch.slice(start,m.index)),start=m.index;return start>=0&&out.push(patch.slice(start)),out}function sectionKeys(patch){const seen=new Map;return splitPatch(patch).map(text=>{const hash=hashText(text),n=seen.get(hash)??0;return seen.set(hash,n+1),{key:n===0?hash:`${hash}.${n}`,text}})}function parseSection(key,text){try{return parsePatchFiles(text,{cacheKeyPrefix:`wt:${key}:`}).flatMap(p=>p.files)[0]??null}catch{return null}}function parseWorkingTree(req){const known=new Set(req.known);return{id:req.id,files:sectionKeys(req.patch).map(({key,text})=>known.has(key)?{key}:{key,file:parseSection(key,text)})}}function parseFilePatch(patch,cacheKey){return patch.trim()?parsePatchFiles(patch,{cacheKeyPrefix:cacheKey}).flatMap(p=>p.files)[0]:void 0}function createPatchParser(createWorker){let worker=null,broken=createWorker===null,nextId=0;const pending=new Map,fail=()=>{broken=!0,worker?.terminate(),worker=null;const held=[...pending.values()];pending.clear();for(const{request,resolve}of held)resolve(parseWorkingTree(request))};return(patch,known)=>{const id=nextId++,request={id,patch,known};if(broken||!createWorker)return Promise.resolve(parseWorkingTree(request));worker||(worker=createWorker(),worker.onmessage=event=>{pending.get(event.data.id)?.resolve(event.data),pending.delete(event.data.id)},worker.onerror=event=>{event.preventDefault(),fail()},worker.onmessageerror=fail);const live=worker;return new Promise(resolve=>{pending.set(id,{request,resolve}),live.postMessage(request)})}}const ReviewableDiff=reactExports.memo(({fileDiff,diffStyle,wrap,hideHeader=!1})=>{const review=useCodeReview({filePath:fileDiff.name,kind:"diff",excerptOf:range=>excerptFor(fileDiff,range),chat:useFilesChat()}),annotations=reactExports.useMemo(()=>review.draft?[{side:review.draft.endSide??review.draft.side??"additions",lineNumber:Math.max(review.draft.start,review.draft.end),metadata:{kind:"draft",range:review.draft}}]:[],[review.draft]);return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(DiffView,{fileDiff,diffStyle,wrap,hideHeader,selectedLines:review.selected,onSelectionEnd:review.onSelectionEnd,onGutterAction:review.canComment?review.openDraft:void 0,onContextMenu:review.onContextMenu,annotations,renderAnnotation:()=>review.draftNode}),review.menuNode]})});ReviewableDiff.displayName="ReviewableDiff";const IMAGE_LOOK="zg-media-checker rounded-zg-md shadow-[inset_0_0_0_1px_var(--zg-hairline)]";function MediaView({kind,src,name,fit="contain",viewerRef}){const labels=useFilesLabels(),[failed,setFailed]=reactExports.useState(!1),[size,setSize]=reactExports.useState(null);if(failed)return jsxRuntimeExports.jsx("div",{className:"text-zg-meta text-[var(--zg-text-muted)] p-3 text-center",children:labels.filesMediaFailed(name)});const box=fit==="row"?"max-h-72":"max-h-full";if(kind==="pdf")return jsxRuntimeExports.jsx("iframe",{src,title:name,loading:"lazy","data-testid":"media-pdf",className:`block w-full border-0 ${fit==="row"?"h-[28rem] rounded-zg-md":"h-full"}`});if(kind==="image"){const title=size?labels.filesImageSize(name,size.w,size.h):name,onLoad=e=>setSize({w:e.currentTarget.naturalWidth,h:e.currentTarget.naturalHeight});return fit==="contain"?jsxRuntimeExports.jsx(ZoomableImage,{ref:viewerRef,src,alt:name,imgTitle:title,imgTestId:"media-image",imgClassName:`${IMAGE_LOOK} block max-w-full max-h-full w-auto h-auto object-contain`,onLoad,onError:()=>setFailed(!0)}):jsxRuntimeExports.jsx("img",{src,alt:name,title,loading:"lazy",decoding:"async",draggable:!1,onLoad,onError:()=>setFailed(!0),"data-testid":"media-image",className:`${IMAGE_LOOK} block max-w-full ${box} w-auto h-auto object-contain`})}return kind==="video"?jsxRuntimeExports.jsx("video",{src,controls:!0,preload:"metadata",onError:()=>setFailed(!0),"data-testid":"media-video",className:`block max-w-full ${box} rounded-zg-md bg-black`}):jsxRuntimeExports.jsx("audio",{src,controls:!0,preload:"metadata",onError:()=>setFailed(!0),"data-testid":"media-audio",className:"block w-full max-w-md"})}function MediaFrame({name,browse,viewerRef,children}){const onKeyDown=event=>{if(event.target instanceof HTMLMediaElement||event.metaKey||event.ctrlKey||event.altKey)return;const viewer=viewerRef.current;if(event.key==="ArrowRight"&&browse&&browse.count>1)browse.onStep(1);else if(event.key==="ArrowLeft"&&browse&&browse.count>1)browse.onStep(-1);else if((event.key==="+"||event.key==="=")&&viewer)viewer.zoomIn();else if(event.key==="-"&&viewer)viewer.zoomOut();else if(event.key==="0"&&viewer)viewer.reset();else return;event.preventDefault()};return jsxRuntimeExports.jsxs("div",{role:"group","aria-label":name,tabIndex:0,onKeyDown,"data-testid":"media-frame",className:"relative w-full h-full flex items-center justify-center outline-none focus-visible:shadow-[inset_0_0_0_2px_var(--zg-ring)] rounded-zg-md",children:[children,browse&&jsxRuntimeExports.jsx(MediaNav,{index:browse.index,count:browse.count,onStep:browse.onStep,counter:!0})]})}const SETTLE_MS=500,IPC_FAILED={diagnostics:[],ran:[],failed:[{id:"*",reason:"ipc"}]};function useDiagnosticsRun(cwd,paths,request){const ed=useEditorPrefs(),run=useFilesHost().diagnostics,enabled=ed.diagnostics!=="off"&&run!==void 0&&cwd!==null&&paths.length>0,pathKey=reactExports.useMemo(()=>[...paths].sort().join("\0"),[paths]),subject=`${cwd}\0${pathKey}\0${request.lsp}\0${request.rerun??0}\0${ed.diagnosticsDisabled.join(",")}`,key=enabled?`${subject}\0${request.version}`:"",[state,setState]=reactExports.useState(null),started=reactExports.useRef(null);reactExports.useEffect(()=>{if(!enabled||!run||!cwd)return;const controller=new AbortController,{signal}=controller,timer=setTimeout(()=>{started.current=subject,run.run(cwd,[...paths],{disabled:[...ed.diagnosticsDisabled],timeoutMs:ed.diagnosticsTimeoutS*1e3,lsp:request.lsp,signal}).catch(()=>IPC_FAILED).then(result=>{signal.aborted||setState({key,subject,result})})},request.settle&&started.current===subject?SETTLE_MS:0);return()=>{clearTimeout(timer),controller.abort()}},[key]);const held=enabled&&state?.subject===subject?state:null;return{enabled,result:held?.result??null,pending:enabled&&held?.key!==key}}function basename(path){const trimmed=path.replace(/[/\\]+$/,"");return trimmed.slice(Math.max(trimmed.lastIndexOf("/"),trimmed.lastIndexOf("\\"))+1)}const indexes=new WeakMap;function indexOf(paths){let index=indexes.get(paths);if(!index){const bases=paths.map(basename);index={bases,lowerBases:bases.map(b=>b.toLowerCase()),lowerPaths:paths.map(p=>p.toLowerCase())},indexes.set(paths,index)}return index}function nameMatches(paths,query,opts,limit=50){if(!query)return[];const index=indexOf(paths),needle=opts.caseSensitive?query:query.toLowerCase(),bases=opts.caseSensitive?index.bases:index.lowerBases,full=opts.caseSensitive?paths:index.lowerPaths,scored=[];for(let i=0;i<paths.length;i++){const base=bases[i],inBase=base.indexOf(needle);inBase!==-1?scored.push({path:paths[i],rank:inBase,base:base.length}):full[i].includes(needle)&&scored.push({path:paths[i],rank:1e4,base:base.length})}return scored.sort((a,b)=>a.rank-b.rank||a.base-b.base||a.path.length-b.path.length||a.path.localeCompare(b.path)),scored.slice(0,limit).map(s=>s.path)}function splitPath(path){const slash=path.lastIndexOf("/");return slash===-1?{dir:"",base:path}:{dir:path.slice(0,slash),base:path.slice(slash+1)}}const DEBOUNCE_MS=150,MAX_NAMES=50,LEAD=32,PAGE=200,MatchGroups=reactExports.memo(({groups,collapsed,budget,query,opts,spaced,onToggle,onOpenLine,onMore})=>{const labels=useFilesLabels();let left=budget;const shown=[];for(const[path,lines]of groups){if(left<=0)break;const closed=collapsed.has(path);left-=1;const visible=closed?[]:lines.slice(0,Math.max(0,left));left-=visible.length,shown.push({path,lines:visible,closed,total:lines.reduce((n,l)=>n+l.ranges.length,0)})}const last=shown[shown.length-1],truncated=shown.length<groups.length||last!==void 0&&!last.closed&&last.lines.length<groups[shown.length-1][1].length;return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("ul",{"aria-label":labels.filesMatchingLines,className:`m-0 p-0 list-none flex flex-col ${spaced?"mt-2":""}`,children:shown.map(({path,lines,closed,total})=>jsxRuntimeExports.jsxs("li",{children:[jsxRuntimeExports.jsxs("button",{type:"button","data-result":"","data-size":"sm","aria-expanded":!closed,onClick:()=>onToggle(path),className:"zg-menu-row zg-press-subtle",title:path,children:[jsxRuntimeExports.jsx(TreeChevron,{open:!closed,className:"text-[var(--zg-text-muted)]"}),jsxRuntimeExports.jsx(FileIcon,{path}),jsxRuntimeExports.jsx(PathLabel,{path}),jsxRuntimeExports.jsx("span",{className:"zg-meta shrink-0 tabular-nums",children:total})]}),!closed&&lines.length>0&&jsxRuntimeExports.jsx("ul",{className:"m-0 p-0 list-none flex flex-col",children:lines.map(m=>jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsxs("button",{type:"button","data-result":"","data-size":"sm",onClick:()=>onOpenLine(m,query,opts),className:"zg-menu-row zg-press-subtle",style:{paddingLeft:30},"aria-label":labels.filesMatchLine(path,m.line,m.text.trim()),children:[jsxRuntimeExports.jsxs("span",{className:"zg-meta shrink-0 w-8 text-right tabular-nums",children:[m.side==="old"?"−":"",m.line]}),jsxRuntimeExports.jsx(LineText,{match:m})]})},`${m.part??""}:${m.side??""}:${m.line}`))})]},path))}),truncated&&jsxRuntimeExports.jsx(MoreRows,{onNear:onMore},budget)]})});MatchGroups.displayName="MatchGroups";const SearchPanel=reactExports.memo(({label,asked,names,search,onOpenFile,onOpenLine,onClose,inset})=>{const labels=useFilesLabels(),[query,setQuery]=reactExports.useState(""),[caseSensitive,setCaseSensitive]=reactExports.useState(!1),opts=reactExports.useMemo(()=>({caseSensitive}),[caseSensitive]),[result,setResult]=reactExports.useState(null),input=reactExports.useRef(null),list=reactExports.useRef(null),[collapsed,setCollapsed]=reactExports.useState(()=>new Set);reactExports.useEffect(()=>{input.current?.select()},[asked]);const latest=reactExports.useRef(search);latest.current=search,reactExports.useEffect(()=>{if(!query){setResult(null);return}let live=!0;const t=window.setTimeout(()=>{latest.current(query,opts).then(r=>{live&&reactExports.startTransition(()=>setResult({query,matches:r.matches,capped:r.capped,...r.unsupported?{unsupported:r.unsupported}:{}}))})},DEBOUNCE_MS);return()=>{live=!1,window.clearTimeout(t)}},[query,opts]);const namesQuery=reactExports.useDeferredValue(query),nameHits=reactExports.useMemo(()=>namesQuery?names(namesQuery,opts).slice(0,MAX_NAMES):[],[names,namesQuery,opts]),groups=reactExports.useMemo(()=>{const byPath=new Map;for(const m of result?.matches??[]){const lines=byPath.get(m.path);lines?lines.push(m):byPath.set(m.path,[m])}return[...byPath]},[result]),[more,setMore]=reactExports.useState({of:null,pages:0}),budget=PAGE*(1+(more.of===result?more.pages:0)),showMore=reactExports.useCallback(()=>{reactExports.startTransition(()=>setMore(m=>({of:result,pages:(m.of===result?m.pages:0)+1})))},[result]),toggleGroup=reactExports.useCallback(path=>setCollapsed(prev=>{const next=new Set(prev);return next.delete(path)||next.add(path),next}),[]),hitCount=reactExports.useMemo(()=>(result?.matches??[]).reduce((n,m)=>n+m.ranges.length,0),[result]),pending=query!==""&&result?.query!==query,focusResult=(from,direction)=>{const rows=[...list.current?.querySelectorAll("[data-result]")??[]],at=from?rows.indexOf(from):-1,next=rows[at+direction];next?next.focus():direction===-1&&input.current?.focus()},onKeyDown=e=>{e.key==="Escape"?(e.preventDefault(),e.stopPropagation(),onClose()):e.key==="ArrowDown"||e.key==="ArrowUp"?(e.preventDefault(),focusResult(e.target===input.current?null:e.target,e.key==="ArrowDown"?1:-1)):e.key==="Enter"&&e.target===input.current?(e.preventDefault(),list.current?.querySelector("[data-result]")?.click()):e.key.toLowerCase()==="f"&&(e.metaKey||e.ctrlKey)&&e.shiftKey&&(e.preventDefault(),input.current?.select())},summary=query?pending&&!result?labels.filesSearching:result?.unsupported?labels.filesSearchNamesOnly:hitCount+nameHits.length===0?labels.filesNoResults:[nameHits.length>0?labels.filesNameHits(nameHits.length,nameHits.length===MAX_NAMES):null,hitCount>0?labels.filesLineHits(hitCount,result?.capped===!0,groups.length):null].filter(Boolean).join(", "):null;return jsxRuntimeExports.jsxs("div",{role:"search","aria-label":label,className:"flex-1 min-h-0 flex flex-col",onKeyDown,children:[jsxRuntimeExports.jsxs("div",{className:`shrink-0 flex items-center gap-1 h-9 ${inset==="left"?"pl-9 pr-2":inset==="right"?"pl-2 pr-9":"px-2"}`,children:[jsxRuntimeExports.jsxs("label",{className:"zg-well min-w-0 flex-1 flex items-center gap-1.5 h-7 pl-2 pr-1 cursor-text",children:[jsxRuntimeExports.jsx("span",{className:"i-ph-magnifying-glass text-sm text-[var(--zg-text-muted)] shrink-0","aria-hidden":!0}),jsxRuntimeExports.jsx("input",{ref:input,type:"text",value:query,onChange:e=>setQuery(e.target.value),placeholder:label,"aria-label":label,spellCheck:!1,autoFocus:!0,className:"min-w-0 flex-1 bg-transparent border-0 outline-none p-0 text-zg-ui text-[var(--zg-text)] placeholder:text-[var(--zg-text-muted)]"}),jsxRuntimeExports.jsx(Tooltip,{label:labels.filesMatchCase,portal:!0,children:jsxRuntimeExports.jsx("button",{type:"button","aria-pressed":caseSensitive,"aria-label":labels.filesMatchCase,onClick:()=>{setCaseSensitive(v=>!v),input.current?.focus()},className:`zg-press-subtle shrink-0 h-5 px-1 rounded-zg-sm border-0 cursor-pointer text-zg-meta font-medium ${caseSensitive?"before:bg-[var(--zg-row-active)] text-[var(--zg-text)]":"bg-transparent text-[var(--zg-text-muted)] hover:before:bg-[var(--zg-row-hover)]"}`,children:"Aa"})})]}),jsxRuntimeExports.jsx(IconButton,{icon:"i-ph-x",label:labels.filesCloseSearch,title:labels.filesCloseSearchHint,size:"sm",onClick:onClose})]}),summary&&jsxRuntimeExports.jsx("div",{className:"shrink-0 px-3 pb-1 zg-meta","aria-live":"polite",children:summary}),jsxRuntimeExports.jsxs("div",{ref:list,"data-scroll-root":"",className:"flex-1 min-h-0 overflow-y-auto px-2 pb-2",children:[nameHits.length>0&&jsxRuntimeExports.jsx("ul",{"aria-label":labels.filesFileNames,className:"m-0 p-0 list-none flex flex-col",children:nameHits.map(path=>jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsxs("button",{type:"button","data-result":"","data-size":"sm",onClick:()=>onOpenFile(path),className:"zg-menu-row zg-press-subtle",title:path,children:[jsxRuntimeExports.jsx(FileIcon,{path}),jsxRuntimeExports.jsx(PathLabel,{path})]})},path))}),groups.length>0&&result&&jsxRuntimeExports.jsx(MatchGroups,{groups,collapsed,budget,query:result.query,opts,spaced:nameHits.length>0,onToggle:toggleGroup,onOpenLine,onMore:showMore})]})]})});SearchPanel.displayName="SearchPanel";function MoreRows({onNear}){const ref=reactExports.useRef(null),near=useNearViewport(ref,"400px 0px");return reactExports.useEffect(()=>{near&&onNear()},[near,onNear]),jsxRuntimeExports.jsx("div",{ref,"aria-hidden":!0,className:"h-px"})}function PathLabel({path}){const{dir,base}=splitPath(path);return jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[jsxRuntimeExports.jsx("span",{className:"text-[var(--zg-text)]",children:base}),dir&&jsxRuntimeExports.jsx("span",{className:"ml-1.5 text-[var(--zg-text-subtle)]",children:dir})]})}function LineText({match}){const indent=match.text.length-match.text.trimStart().length,from=Math.max(indent,(match.ranges[0]?.start??0)-LEAD),parts=[];let at=from;for(const r of match.ranges){if(r.end<=from)continue;const start=Math.max(r.start,from);start>at&&parts.push({text:match.text.slice(at,start),hit:!1}),parts.push({text:match.text.slice(start,r.end),hit:!0}),at=r.end}return parts.push({text:match.text.slice(at),hit:!1}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 truncate font-mono text-zg-label text-[var(--zg-text-muted)]",children:[from>indent&&"…",parts.map((p,i)=>p.hit?jsxRuntimeExports.jsx("mark",{className:"zg-search-hit",children:p.text},i):jsxRuntimeExports.jsx("span",{children:p.text},i))]})}function NOTHING(){}function useFolderChanges(scope){const watch=useFilesHost().watch,scopeRef=reactExports.useRef(scope);scopeRef.current=scope;const root=scope?filesRootOf(scope):"",cwd=scope?.cwd??"",project=scope?.root??"",bound=scope?.session??null;return reactExports.useCallback(handler=>{const current=scopeRef.current;return!root||!current||!watch?NOTHING:watch(current,handler)},[watch,root,cwd,project,bound])}export{DiffScroller as D,FilesChatContext as F,MediaView as M,ReviewableDiff as R,SearchPanel as S,useFolderChanges as a,createPatchParser as b,countBySeverity as c,useNoEdits as d,useNoKeyScope as e,DiffView as f,DIAGNOSTIC_GLYPH as g,fileActionItems as h,useFilesChat as i,useCodeReview as j,diagnosticsByLine as k,diagnosticMarkers as l,diagnosticsAt as m,nameMatches as n,noChatItem as o,parseFilePatch as p,absolutePath as q,MediaFrame as r,useDiagnosticsRun as u};
34
+ `)}async function copyText(text){try{await navigator.clipboard.writeText(text)}catch(err){console.error("[zidane-ui] clipboard write failed",err)}}function describe(target,labels){return target.kind==="text"?labels.filesSelection:rangeLabel(target.range)}function useCodeReview({filePath,kind,excerptOf,extraItems,chat}){const labels=useFilesLabels(),[selected,setSelected]=reactExports.useState(null),[draft,setDraft]=reactExports.useState(null),[menu,setMenu]=reactExports.useState(null),clear=reactExports.useCallback(()=>{setDraft(null),setSelected(null)},[]);reactExports.useEffect(()=>{if(!selected)return;const onKey=e=>{e.key==="Escape"&&!(e.target instanceof HTMLTextAreaElement)&&clear()};return document.addEventListener("keydown",onKey),()=>document.removeEventListener("keydown",onKey)},[selected,clear]);const language=languageFor(filePath),excerptForTarget=t=>t.kind==="text"?t.text:excerptOf(t.range),addToChat=(to,t)=>{const label=t.kind==="text"?null:rangeLabel(t.range),body=serializeCodeSnippet({filePath,rangeLabel:label,excerpt:excerptForTarget(t),language});to.attach(attachmentName("snippet",filePath,label),body)},openDraft=reactExports.useCallback(range=>{setSelected(range),chat&&setDraft(range)},[chat]);!chat&&draft!==null&&setDraft(null);const submitDraft=text=>{if(!draft||!chat||!text.trim())return;const body=serializeReviewComment({kind,filePath,rangeLabel:rangeLabel(draft),excerpt:excerptOf(draft),language,text});chat.attach(attachmentName("comment",filePath,rangeLabel(draft)),body),clear()},onContextMenu=e=>{const target=resolveCodeMenuTarget(e.nativeEvent.composedPath(),selected);!target&&!extraItems?.length||(e.preventDefault(),setMenu(target?{target,at:{x:e.clientX,y:e.clientY}}:{target:{kind:"text",text:""},at:{x:e.clientX,y:e.clientY}}))},items=[];if(menu&&!(menu.target.kind==="text"&&menu.target.text==="")){const t=menu.target,what=describe(t,labels);items.push(chat?{id:"chat",label:labels.filesAddWhatToChat(what),shortcut:"a",onSelect:()=>addToChat(chat,t)}:noChatItem("chat",labels.filesAddWhatToChat(what),labels),...t.kind==="text"?[]:[chat?{id:"comment",label:labels.filesCommentOn(what),shortcut:"m",onSelect:()=>openDraft(t.range)}:noChatItem("comment",labels.filesCommentOn(what),labels)],{id:"copy",label:labels.filesCopyWhat(what),shortcut:"c",onSelect:()=>{copyText(excerptForTarget(t))}})}return extraItems?.length&&items.push(...extraItems),{selected,draft,onSelectionEnd:setSelected,openDraft,canComment:chat!==null,onContextMenu,draftNode:draft?jsxRuntimeExports.jsx(ReviewDraft,{label:rangeLabel(draft),excerpt:excerptOf(draft),onSubmit:submitDraft,onCancel:clear}):null,menuNode:jsxRuntimeExports.jsx(RowActionsMenu,{open:menu!==null,position:menu?.at??null,onClose:()=>setMenu(null),items})}}function DiffViewInner({patch,fileDiff,diffStyle="unified",wrap=!1,hideHeader=!1,selectedLines,onSelectionEnd,onGutterAction,onContextMenu,annotations,renderAnnotation,className}){const{shikiTheme:theme,appearance}=useEditorEnvironment(),selectable=onSelectionEnd!==void 0,host=useDetachCleanup(),latest=reactExports.useRef({onSelectionEnd,onGutterAction,renderAnnotation,wrap});latest.current={onSelectionEnd,onGutterAction,renderAnnotation,wrap};const stable=reactExports.useMemo(()=>({onLineSelectionEnd:r=>latest.current.onSelectionEnd?.(r),onGutterUtilityClick:r=>latest.current.onGutterAction?.(r),renderAnnotation:a=>latest.current.renderAnnotation?.(a)??null,onPostRender:(node,instance,phase)=>{const live=phase!=="unmount";revealOnHighlight(node,live&&isDiffHighlighted(instance,node),phase,live&&colorsDiff(instance)),scrollReachOnRender(node,!latest.current.wrap,phase)}}),[]),hasGutter=onGutterAction!==void 0,options=reactExports.useMemo(()=>({theme,themeType:appearance,diffStyle,overflow:wrap?"wrap":"scroll",lineDiffType:"word-alt",preferredHighlighter:PREFERRED_HIGHLIGHTER,diffIndicators:"bars",hunkSeparators:"line-info",disableFileHeader:hideHeader,stickyHeader:!hideHeader,unsafeCSS:DIFFS_UNSAFE_CSS,onPostRender:stable.onPostRender,...selectable?{enableLineSelection:!0,onLineSelectionEnd:stable.onLineSelectionEnd}:{},...hasGutter?{enableGutterUtility:!0,onGutterUtilityClick:stable.onGutterUtilityClick}:{}}),[theme,appearance,diffStyle,wrap,hideHeader,selectable,hasGutter,stable]),lineAnnotations=reactExports.useMemo(()=>annotations?[...annotations]:void 0,[annotations]),shared={className,style:DIFFS_HOST_STYLE,...selectable?{selectedLines:selectedLines??null}:{},...lineAnnotations?{lineAnnotations}:{},...renderAnnotation?{renderAnnotation:stable.renderAnnotation}:{},options};return jsxRuntimeExports.jsx("div",{ref:host,className:"contents",onContextMenu,children:fileDiff?jsxRuntimeExports.jsx(FileDiff2,{fileDiff,...shared}):jsxRuntimeExports.jsx(PatchDiff,{patch:patch??"",...shared})})}function isDiffHighlighted(instance,node){const cache=instance?.hunksRenderer?.renderCache;return cache&&typeof cache.highlighted=="boolean"?cache.highlighted:node.shadowRoot?.querySelector("[data-line] span[class], [data-line] span[style]")!==null}function colorsDiff(instance){const renderer=instance?.hunksRenderer,diff=renderer?.renderCache?.diff;if(!diff)return!1;const lines=Math.max(diff.additionLines.length,diff.deletionLines.length),max=renderer?.getTokenizeMaxLength?.()??DEFAULT_TOKENIZE_MAX_LENGTH,lang=name=>diff.lang??(name===void 0?"text":getFiletypeFromFileName(name));return lines>0&&lines<=max&&(lang(diff.name)!=="text"||lang(diff.prevName)!=="text")}const DiffView=reactExports.memo(DiffViewInner);function DiffScroller({className,contentClassName,children}){return jsxRuntimeExports.jsx(Virtualizer,{className,contentClassName,config:VIRTUALIZER_CONFIG,children})}function hashText(text){let h=2166136261;for(let i=0;i<text.length;i++)h^=text.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function splitPatch(patch){const out=[],re=/^diff --git /gm;let start=-1;for(let m=re.exec(patch);m;m=re.exec(patch))start>=0&&out.push(patch.slice(start,m.index)),start=m.index;return start>=0&&out.push(patch.slice(start)),out}function sectionKeys(patch){const seen=new Map;return splitPatch(patch).map(text=>{const hash=hashText(text),n=seen.get(hash)??0;return seen.set(hash,n+1),{key:n===0?hash:`${hash}.${n}`,text}})}function parseSection(key,text){try{return parsePatchFiles(text,{cacheKeyPrefix:`wt:${key}:`}).flatMap(p=>p.files)[0]??null}catch{return null}}function parseWorkingTree(req){const known=new Set(req.known);return{id:req.id,files:sectionKeys(req.patch).map(({key,text})=>known.has(key)?{key}:{key,file:parseSection(key,text)})}}function parseFilePatch(patch,cacheKey){return patch.trim()?parsePatchFiles(patch,{cacheKeyPrefix:cacheKey}).flatMap(p=>p.files)[0]:void 0}function createPatchParser(createWorker){let worker=null,broken=createWorker===null,nextId=0;const pending=new Map,fail=()=>{broken=!0,worker?.terminate(),worker=null;const held=[...pending.values()];pending.clear();for(const{request,resolve}of held)resolve(parseWorkingTree(request))};return(patch,known)=>{const id=nextId++,request={id,patch,known};if(broken||!createWorker)return Promise.resolve(parseWorkingTree(request));worker||(worker=createWorker(),worker.onmessage=event=>{pending.get(event.data.id)?.resolve(event.data),pending.delete(event.data.id)},worker.onerror=event=>{event.preventDefault(),fail()},worker.onmessageerror=fail);const live=worker;return new Promise(resolve=>{pending.set(id,{request,resolve}),live.postMessage(request)})}}const ReviewableDiff=reactExports.memo(({fileDiff,diffStyle,wrap,hideHeader=!1})=>{const review=useCodeReview({filePath:fileDiff.name,kind:"diff",excerptOf:range=>excerptFor(fileDiff,range),chat:useFilesChat()}),annotations=reactExports.useMemo(()=>review.draft?[{side:review.draft.endSide??review.draft.side??"additions",lineNumber:Math.max(review.draft.start,review.draft.end),metadata:{kind:"draft",range:review.draft}}]:[],[review.draft]);return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(DiffView,{fileDiff,diffStyle,wrap,hideHeader,selectedLines:review.selected,onSelectionEnd:review.onSelectionEnd,onGutterAction:review.canComment?review.openDraft:void 0,onContextMenu:review.onContextMenu,annotations,renderAnnotation:()=>review.draftNode}),review.menuNode]})});ReviewableDiff.displayName="ReviewableDiff";const IMAGE_LOOK="zg-media-checker rounded-zg-md shadow-[inset_0_0_0_1px_var(--zg-hairline)]";function MediaView({kind,src,name,fit="contain",viewerRef}){const labels=useFilesLabels(),[failed,setFailed]=reactExports.useState(!1),[size,setSize]=reactExports.useState(null);if(failed)return jsxRuntimeExports.jsx("div",{className:"text-zg-meta text-[var(--zg-text-muted)] p-3 text-center",children:labels.filesMediaFailed(name)});const box=fit==="row"?"max-h-72":"max-h-full";if(kind==="pdf")return jsxRuntimeExports.jsx("iframe",{src,title:name,loading:"lazy","data-testid":"media-pdf",className:`block w-full border-0 ${fit==="row"?"h-[28rem] rounded-zg-md":"h-full"}`});if(kind==="image"){const title=size?labels.filesImageSize(name,size.w,size.h):name,onLoad=e=>setSize({w:e.currentTarget.naturalWidth,h:e.currentTarget.naturalHeight});return fit==="contain"?jsxRuntimeExports.jsx(ZoomableImage,{ref:viewerRef,src,alt:name,imgTitle:title,imgTestId:"media-image",imgClassName:`${IMAGE_LOOK} block max-w-full max-h-full w-auto h-auto object-contain`,onLoad,onError:()=>setFailed(!0)}):jsxRuntimeExports.jsx("img",{src,alt:name,title,loading:"lazy",decoding:"async",draggable:!1,onLoad,onError:()=>setFailed(!0),"data-testid":"media-image",className:`${IMAGE_LOOK} block max-w-full ${box} w-auto h-auto object-contain`})}return kind==="video"?jsxRuntimeExports.jsx("video",{src,controls:!0,preload:"metadata",onError:()=>setFailed(!0),"data-testid":"media-video",className:`block max-w-full ${box} rounded-zg-md bg-black`}):jsxRuntimeExports.jsx("audio",{src,controls:!0,preload:"metadata",onError:()=>setFailed(!0),"data-testid":"media-audio",className:"block w-full max-w-md"})}function MediaFrame({name,browse,viewerRef,children}){const onKeyDown=event=>{if(event.target instanceof HTMLMediaElement||event.metaKey||event.ctrlKey||event.altKey)return;const viewer=viewerRef.current;if(event.key==="ArrowRight"&&browse&&browse.count>1)browse.onStep(1);else if(event.key==="ArrowLeft"&&browse&&browse.count>1)browse.onStep(-1);else if((event.key==="+"||event.key==="=")&&viewer)viewer.zoomIn();else if(event.key==="-"&&viewer)viewer.zoomOut();else if(event.key==="0"&&viewer)viewer.reset();else return;event.preventDefault()};return jsxRuntimeExports.jsxs("div",{role:"group","aria-label":name,tabIndex:0,onKeyDown,"data-testid":"media-frame",className:"relative w-full h-full flex items-center justify-center outline-none focus-visible:shadow-[inset_0_0_0_2px_var(--zg-ring)] rounded-zg-md",children:[children,browse&&jsxRuntimeExports.jsx(MediaNav,{index:browse.index,count:browse.count,onStep:browse.onStep,counter:!0})]})}const SETTLE_MS=500,IPC_FAILED={diagnostics:[],ran:[],failed:[{id:"*",reason:"ipc"}]};function useDiagnosticsRun(cwd,paths,request){const ed=useEditorPrefs(),run=useFilesHost().diagnostics,enabled=ed.diagnostics!=="off"&&run!==void 0&&cwd!==null&&paths.length>0,pathKey=reactExports.useMemo(()=>[...paths].sort().join("\0"),[paths]),subject=`${cwd}\0${pathKey}\0${request.lsp}\0${request.rerun??0}\0${ed.diagnosticsDisabled.join(",")}`,key=enabled?`${subject}\0${request.version}`:"",[state,setState]=reactExports.useState(null),started=reactExports.useRef(null);reactExports.useEffect(()=>{if(!enabled||!run||!cwd)return;const controller=new AbortController,{signal}=controller,timer=setTimeout(()=>{started.current=subject,run.run(cwd,[...paths],{disabled:[...ed.diagnosticsDisabled],timeoutMs:ed.diagnosticsTimeoutS*1e3,lsp:request.lsp,signal}).catch(()=>IPC_FAILED).then(result=>{signal.aborted||setState({key,subject,result})})},request.settle&&started.current===subject?SETTLE_MS:0);return()=>{clearTimeout(timer),controller.abort()}},[key]);const held=enabled&&state?.subject===subject?state:null;return{enabled,result:held?.result??null,pending:enabled&&held?.key!==key}}function basename(path){const trimmed=path.replace(/[/\\]+$/,"");return trimmed.slice(Math.max(trimmed.lastIndexOf("/"),trimmed.lastIndexOf("\\"))+1)}const indexes=new WeakMap;function indexOf(paths){let index=indexes.get(paths);if(!index){const bases=paths.map(basename);index={bases,lowerBases:bases.map(b=>b.toLowerCase()),lowerPaths:paths.map(p=>p.toLowerCase())},indexes.set(paths,index)}return index}function nameMatches(paths,query,opts,limit=50){if(!query)return[];const index=indexOf(paths),needle=opts.caseSensitive?query:query.toLowerCase(),bases=opts.caseSensitive?index.bases:index.lowerBases,full=opts.caseSensitive?paths:index.lowerPaths,scored=[];for(let i=0;i<paths.length;i++){const base=bases[i],inBase=base.indexOf(needle);inBase!==-1?scored.push({path:paths[i],rank:inBase,base:base.length}):full[i].includes(needle)&&scored.push({path:paths[i],rank:1e4,base:base.length})}return scored.sort((a,b)=>a.rank-b.rank||a.base-b.base||a.path.length-b.path.length||a.path.localeCompare(b.path)),scored.slice(0,limit).map(s=>s.path)}function splitPath(path){const slash=path.lastIndexOf("/");return slash===-1?{dir:"",base:path}:{dir:path.slice(0,slash),base:path.slice(slash+1)}}const DEBOUNCE_MS=150,MAX_NAMES=50,LEAD=32,PAGE=200,MatchGroups=reactExports.memo(({groups,collapsed,budget,query,opts,spaced,onToggle,onOpenLine,onMore})=>{const labels=useFilesLabels();let left=budget;const shown=[];for(const[path,lines]of groups){if(left<=0)break;const closed=collapsed.has(path);left-=1;const visible=closed?[]:lines.slice(0,Math.max(0,left));left-=visible.length,shown.push({path,lines:visible,closed,total:lines.reduce((n,l)=>n+l.ranges.length,0)})}const last=shown[shown.length-1],truncated=shown.length<groups.length||last!==void 0&&!last.closed&&last.lines.length<groups[shown.length-1][1].length;return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("ul",{"aria-label":labels.filesMatchingLines,className:`m-0 p-0 list-none flex flex-col ${spaced?"mt-2":""}`,children:shown.map(({path,lines,closed,total})=>jsxRuntimeExports.jsxs("li",{children:[jsxRuntimeExports.jsxs("button",{type:"button","data-result":"","data-size":"sm","aria-expanded":!closed,onClick:()=>onToggle(path),className:"zg-menu-row zg-press-subtle",title:path,children:[jsxRuntimeExports.jsx(TreeChevron,{open:!closed,className:"text-[var(--zg-text-muted)]"}),jsxRuntimeExports.jsx(FileIcon,{path}),jsxRuntimeExports.jsx(PathLabel,{path}),jsxRuntimeExports.jsx("span",{className:"zg-meta shrink-0 tabular-nums",children:total})]}),!closed&&lines.length>0&&jsxRuntimeExports.jsx("ul",{className:"m-0 p-0 list-none flex flex-col",children:lines.map(m=>jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsxs("button",{type:"button","data-result":"","data-size":"sm",onClick:()=>onOpenLine(m,query,opts),className:"zg-menu-row zg-press-subtle",style:{paddingLeft:30},"aria-label":labels.filesMatchLine(path,m.line,m.text.trim()),children:[jsxRuntimeExports.jsxs("span",{className:"zg-meta shrink-0 w-8 text-right tabular-nums",children:[m.side==="old"?"−":"",m.line]}),jsxRuntimeExports.jsx(LineText,{match:m})]})},`${m.part??""}:${m.side??""}:${m.line}`))})]},path))}),truncated&&jsxRuntimeExports.jsx(MoreRows,{onNear:onMore},budget)]})});MatchGroups.displayName="MatchGroups";const SearchPanel=reactExports.memo(({label,asked,names,search,onOpenFile,onOpenLine,onClose,inset})=>{const labels=useFilesLabels(),[query,setQuery]=reactExports.useState(""),[caseSensitive,setCaseSensitive]=reactExports.useState(!1),opts=reactExports.useMemo(()=>({caseSensitive}),[caseSensitive]),[result,setResult]=reactExports.useState(null),input=reactExports.useRef(null),list=reactExports.useRef(null),[collapsed,setCollapsed]=reactExports.useState(()=>new Set);reactExports.useEffect(()=>{input.current?.select()},[asked]);const latest=reactExports.useRef(search);latest.current=search,reactExports.useEffect(()=>{if(!query){setResult(null);return}let live=!0;const t=window.setTimeout(()=>{latest.current(query,opts).then(r=>{live&&reactExports.startTransition(()=>setResult({query,matches:r.matches,capped:r.capped,...r.unsupported?{unsupported:r.unsupported}:{}}))})},DEBOUNCE_MS);return()=>{live=!1,window.clearTimeout(t)}},[query,opts]);const namesQuery=reactExports.useDeferredValue(query),nameHits=reactExports.useMemo(()=>namesQuery?names(namesQuery,opts).slice(0,MAX_NAMES):[],[names,namesQuery,opts]),groups=reactExports.useMemo(()=>{const byPath=new Map;for(const m of result?.matches??[]){const lines=byPath.get(m.path);lines?lines.push(m):byPath.set(m.path,[m])}return[...byPath]},[result]),[more,setMore]=reactExports.useState({of:null,pages:0}),budget=PAGE*(1+(more.of===result?more.pages:0)),showMore=reactExports.useCallback(()=>{reactExports.startTransition(()=>setMore(m=>({of:result,pages:(m.of===result?m.pages:0)+1})))},[result]),toggleGroup=reactExports.useCallback(path=>setCollapsed(prev=>{const next=new Set(prev);return next.delete(path)||next.add(path),next}),[]),hitCount=reactExports.useMemo(()=>(result?.matches??[]).reduce((n,m)=>n+m.ranges.length,0),[result]),pending=query!==""&&result?.query!==query,focusResult=(from,direction)=>{const rows=[...list.current?.querySelectorAll("[data-result]")??[]],at=from?rows.indexOf(from):-1,next=rows[at+direction];next?next.focus():direction===-1&&input.current?.focus()},onKeyDown=e=>{e.key==="Escape"?(e.preventDefault(),e.stopPropagation(),onClose()):e.key==="ArrowDown"||e.key==="ArrowUp"?(e.preventDefault(),focusResult(e.target===input.current?null:e.target,e.key==="ArrowDown"?1:-1)):e.key==="Enter"&&e.target===input.current?(e.preventDefault(),list.current?.querySelector("[data-result]")?.click()):e.key.toLowerCase()==="f"&&(e.metaKey||e.ctrlKey)&&e.shiftKey&&(e.preventDefault(),input.current?.select())},summary=query?pending&&!result?labels.filesSearching:result?.unsupported?labels.filesSearchNamesOnly:hitCount+nameHits.length===0?labels.filesNoResults:[nameHits.length>0?labels.filesNameHits(nameHits.length,nameHits.length===MAX_NAMES):null,hitCount>0?labels.filesLineHits(hitCount,result?.capped===!0,groups.length):null].filter(Boolean).join(", "):null;return jsxRuntimeExports.jsxs("div",{role:"search","aria-label":label,className:"flex-1 min-h-0 flex flex-col",onKeyDown,children:[jsxRuntimeExports.jsxs("div",{className:`shrink-0 flex items-center gap-1 h-9 ${inset==="left"?"pl-9 pr-2":inset==="right"?"pl-2 pr-9":"px-2"}`,children:[jsxRuntimeExports.jsxs("label",{className:"zg-well min-w-0 flex-1 flex items-center gap-1.5 h-7 pl-2 pr-1 cursor-text",children:[jsxRuntimeExports.jsx("span",{className:"i-ph-magnifying-glass text-sm text-[var(--zg-text-muted)] shrink-0","aria-hidden":!0}),jsxRuntimeExports.jsx("input",{ref:input,type:"text",value:query,onChange:e=>setQuery(e.target.value),placeholder:label,"aria-label":label,spellCheck:!1,autoFocus:!0,className:"min-w-0 flex-1 bg-transparent border-0 outline-none p-0 text-zg-ui text-[var(--zg-text)] placeholder:text-[var(--zg-text-muted)]"}),jsxRuntimeExports.jsx(Tooltip,{label:labels.filesMatchCase,portal:!0,children:jsxRuntimeExports.jsx("button",{type:"button","aria-pressed":caseSensitive,"aria-label":labels.filesMatchCase,onClick:()=>{setCaseSensitive(v=>!v),input.current?.focus()},className:`zg-press-subtle shrink-0 h-5 px-1 rounded-zg-sm border-0 cursor-pointer text-zg-meta font-medium ${caseSensitive?"before:bg-[var(--zg-row-active)] text-[var(--zg-text)]":"bg-transparent text-[var(--zg-text-muted)] hover:before:bg-[var(--zg-row-hover)]"}`,children:"Aa"})})]}),jsxRuntimeExports.jsx(IconButton,{icon:"i-ph-x",label:labels.filesCloseSearch,title:labels.filesCloseSearchHint,size:"sm",onClick:onClose})]}),summary&&jsxRuntimeExports.jsx("div",{className:"shrink-0 px-3 pb-1 zg-meta","aria-live":"polite",children:summary}),jsxRuntimeExports.jsxs("div",{ref:list,"data-scroll-root":"",className:"flex-1 min-h-0 overflow-y-auto px-2 pb-2",children:[nameHits.length>0&&jsxRuntimeExports.jsx("ul",{"aria-label":labels.filesFileNames,className:"m-0 p-0 list-none flex flex-col",children:nameHits.map(path=>jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsxs("button",{type:"button","data-result":"","data-size":"sm",onClick:()=>onOpenFile(path),className:"zg-menu-row zg-press-subtle",title:path,children:[jsxRuntimeExports.jsx(FileIcon,{path}),jsxRuntimeExports.jsx(PathLabel,{path})]})},path))}),groups.length>0&&result&&jsxRuntimeExports.jsx(MatchGroups,{groups,collapsed,budget,query:result.query,opts,spaced:nameHits.length>0,onToggle:toggleGroup,onOpenLine,onMore:showMore})]})]})});SearchPanel.displayName="SearchPanel";function MoreRows({onNear}){const ref=reactExports.useRef(null),near=useNearViewport(ref,"400px 0px");return reactExports.useEffect(()=>{near&&onNear()},[near,onNear]),jsxRuntimeExports.jsx("div",{ref,"aria-hidden":!0,className:"h-px"})}function PathLabel({path}){const{dir,base}=splitPath(path);return jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[jsxRuntimeExports.jsx("span",{className:"text-[var(--zg-text)]",children:base}),dir&&jsxRuntimeExports.jsx("span",{className:"ml-1.5 text-[var(--zg-text-subtle)]",children:dir})]})}function LineText({match}){const indent=match.text.length-match.text.trimStart().length,from=Math.max(indent,(match.ranges[0]?.start??0)-LEAD),parts=[];let at=from;for(const r of match.ranges){if(r.end<=from)continue;const start=Math.max(r.start,from);start>at&&parts.push({text:match.text.slice(at,start),hit:!1}),parts.push({text:match.text.slice(start,r.end),hit:!0}),at=r.end}return parts.push({text:match.text.slice(at),hit:!1}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 truncate font-mono text-zg-label text-[var(--zg-text-muted)]",children:[from>indent&&"…",parts.map((p,i)=>p.hit?jsxRuntimeExports.jsx("mark",{className:"zg-search-hit",children:p.text},i):jsxRuntimeExports.jsx("span",{children:p.text},i))]})}function NOTHING(){}function useFolderChanges(scope){const watch=useFilesHost().watch,scopeRef=reactExports.useRef(scope);scopeRef.current=scope;const root=scope?filesRootOf(scope):"",cwd=scope?.cwd??"",project=scope?.root??"",bound=scope?.session??null;return reactExports.useCallback(handler=>{const current=scopeRef.current;return!root||!current||!watch?NOTHING:watch(current,handler)},[watch,root,cwd,project,bound])}export{DiffScroller as D,FilesChatContext as F,MediaView as M,ReviewableDiff as R,SearchPanel as S,useFolderChanges as a,createPatchParser as b,countBySeverity as c,useNoEdits as d,useNoKeyScope as e,DiffView as f,DIAGNOSTIC_GLYPH as g,fileActionItems as h,useFilesChat as i,useCodeReview as j,diagnosticsByLine as k,diagnosticMarkers as l,diagnosticsAt as m,nameMatches as n,noChatItem as o,parseFilePatch as p,absolutePath as q,MediaFrame as r,useDiagnosticsRun as u};