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.
- package/out/main/chunks/{remote-hosts-B8_tzg_n.js → remote-hosts-CSiGJAfm.js} +1 -1
- package/out/main/chunks/{session-search-sql-2EUzjHAT.js → session-search-sql-D51BmAO2.js} +5 -5
- package/out/main/index.js +4397 -4086
- package/out/main/session-search-worker.js +1 -1
- package/out/preload/index.mjs +36 -2
- package/out/renderer/assets/{24BXRY42-eTlQfl4v.js → 24BXRY42-0UXaaWjY.js} +1 -1
- package/out/renderer/assets/{4FHPYW2L-BHx1bBmw.js → 4FHPYW2L-BWpHahlW.js} +1 -1
- package/out/renderer/assets/{4LWW3ZNH-D7lTurDT.js → 4LWW3ZNH-CPyJ9o9Y.js} +1 -1
- package/out/renderer/assets/{5XYWFMKW-e04QMbw9.js → 5XYWFMKW-ZZpHHfGa.js} +1 -1
- package/out/renderer/assets/{64PMEAB3-DTIFpDpU.js → 64PMEAB3-DOEnEuzl.js} +1 -1
- package/out/renderer/assets/{6BEWHPQE-BrYtHcZG.js → 6BEWHPQE-C2ZZckdj.js} +1 -1
- package/out/renderer/assets/{6PIGVMFT-CoAPPYTl.js → 6PIGVMFT-CRGq6eh3.js} +1 -1
- package/out/renderer/assets/{75JW6PN6-JbXPfJg4.js → 75JW6PN6-CYzAa9yx.js} +1 -1
- package/out/renderer/assets/{7XWI72E6-CFY3Kecs.js → 7XWI72E6-C_GZbyIF.js} +1 -1
- package/out/renderer/assets/{BGW36YJW-DhmSG9tb.js → BGW36YJW-BAwgTZ_z.js} +1 -1
- package/out/renderer/assets/{CGIZI67J-Cr9B0EmW.js → CGIZI67J-BxXITbQC.js} +1 -1
- package/out/renderer/assets/{CodeEditor-C6EJBlGG.js → CodeEditor-CLsAw7eu.js} +2 -2
- package/out/renderer/assets/{ComposerEditor-oFIdMkLB.js → ComposerEditor-BqnIn2NQ.js} +1 -1
- package/out/renderer/assets/{DNNCRC2E-CMqlK0W6.js → DNNCRC2E-kbsNJgPT.js} +1 -1
- package/out/renderer/assets/DiffsTab--BHt7StP.js +3 -0
- package/out/renderer/assets/{E67EBMDD-C_T2QnwF.js → E67EBMDD-BOeJkFNZ.js} +1 -1
- package/out/renderer/assets/{EFYWJBJK-Cbn-VZcb.js → EFYWJBJK-CFT5CQUG.js} +1 -1
- package/out/renderer/assets/{EXE5EH6O-SXdUe5We.js → EXE5EH6O-Cbj5xPKl.js} +1 -1
- package/out/renderer/assets/{EditorWorkers-bVeEZI8X.js → EditorWorkers-CXBU_HFf.js} +1 -1
- package/out/renderer/assets/{FilesTab-DtM2Q5R0.js → FilesTab-CZHD0eBx.js} +4 -4
- package/out/renderer/assets/{G6GPDDNC-XfFyRa0j.js → G6GPDDNC-Ax6dML4i.js} +1 -1
- package/out/renderer/assets/{G76NGGFM-Bj_m2WLJ.js → G76NGGFM-BxPXXNt_.js} +1 -1
- package/out/renderer/assets/{GH6G3TJC-wPRy41Zv.js → GH6G3TJC-CiCXY2r6.js} +1 -1
- package/out/renderer/assets/{HPNUA7RO-BhLNmX-t.js → HPNUA7RO-DiyW9VGu.js} +1 -1
- package/out/renderer/assets/{HQRGC5D7-dvTAT1Uv.js → HQRGC5D7-ArfvIYAC.js} +1 -1
- package/out/renderer/assets/{IX6Z2TVR-CzV_umYo.js → IX6Z2TVR-Df9chdw8.js} +1 -1
- package/out/renderer/assets/IconButtonTip-D0dQOfg6.js +1 -0
- package/out/renderer/assets/{J77NQRCJ-DTwwq3Ci.js → J77NQRCJ-DOWauTsf.js} +1 -1
- package/out/renderer/assets/{JAD36DTZ-DArKsMUT.js → JAD36DTZ-CJDdMCD5.js} +1 -1
- package/out/renderer/assets/{LF3NJQAX-DjYdE7YV.js → LF3NJQAX-B89ZqOpY.js} +1 -1
- package/out/renderer/assets/{LRZCOFJZ-C7m8fw-0.js → LRZCOFJZ-BBX_wZ5T.js} +1 -1
- package/out/renderer/assets/{N5NF2FGY-CqGhgjNF.js → N5NF2FGY-BoIFu-8L.js} +1 -1
- package/out/renderer/assets/{N7OWWQHY-BRk68LVa.js → N7OWWQHY-CloOgGu1.js} +1 -1
- package/out/renderer/assets/{NT5JY5WP-B1NtxJ-K.js → NT5JY5WP-BhjzefjG.js} +1 -1
- package/out/renderer/assets/{OT7W3RNY-CtDQ--Ld.js → OT7W3RNY-BRzBqtKB.js} +1 -1
- package/out/renderer/assets/{P67P66DB-LeAz_z3Z.js → P67P66DB-Dw-K1Ghu.js} +1 -1
- package/out/renderer/assets/{PFLLLM7K-CgODCVD8.js → PFLLLM7K-DfSPUrIT.js} +1 -1
- package/out/renderer/assets/{PUAMC4MJ-9REX_vGK.js → PUAMC4MJ-BnY1F2cF.js} +1 -1
- package/out/renderer/assets/{PVFCHRLY-CK5jTRjy.js → PVFCHRLY-BcyVPS3n.js} +1 -1
- package/out/renderer/assets/{PinnedSavedView-Dtdra7Gq.js → PinnedSavedView-ciRhY0cN.js} +1 -1
- package/out/renderer/assets/{QQW2P742-B2snHr_6.js → QQW2P742-D6aitZ24.js} +1 -1
- package/out/renderer/assets/{S63OEDPG-BeWWF1tc.js → S63OEDPG-Dlz1a9cD.js} +1 -1
- package/out/renderer/assets/{SG5TVYLW-ClCsbQ87.js → SG5TVYLW-Bu7LZZpx.js} +1 -1
- package/out/renderer/assets/{SavedViewArtifact-ATjDgAUF.js → SavedViewArtifact-CM9L4mc8.js} +1 -1
- package/out/renderer/assets/{SidebarPreviewPane-DHllX0GN.js → SidebarPreviewPane-DkOCt7Gb.js} +1 -1
- package/out/renderer/assets/{TranscriptViews-DD_JshFH.js → TranscriptViews-aYvP71ow.js} +1 -1
- package/out/renderer/assets/{UGRSUGA2-jP6nv8HL.js → UGRSUGA2-avwOtJG1.js} +1 -1
- package/out/renderer/assets/{V44WA6U7-Dr_tS3uH.js → V44WA6U7-DMF87Y7j.js} +1 -1
- package/out/renderer/assets/{V67O4WWV-BRn52u9c.js → V67O4WWV-BsDLuBDb.js} +1 -1
- package/out/renderer/assets/{VBUCM3YD-0sLtn_Zp.js → VBUCM3YD-C6FrRswP.js} +1 -1
- package/out/renderer/assets/{VINGRCPA-n98Gf7V0.js → VINGRCPA-Do3Pv3Tc.js} +1 -1
- package/out/renderer/assets/{ViewBlock-DdcTHRu3.js → ViewBlock-B-ppjb34.js} +3 -3
- package/out/renderer/assets/{ViewCharts-BAw6tExV.js → ViewCharts-jvS22ppO.js} +2 -2
- package/out/renderer/assets/{ViewCustom-BzwMbjqg.js → ViewCustom-yFkoy6a-.js} +1 -1
- package/out/renderer/assets/{ViewExtension-Ch5_33Ra.js → ViewExtension-DuHxho6W.js} +1 -1
- package/out/renderer/assets/{ViewInputs-BHooAs2f.js → ViewInputs-VAMDh56H.js} +1 -1
- package/out/renderer/assets/{ViewMcpApp-CJnOESMk.js → ViewMcpApp-CH_W9CZt.js} +1 -1
- package/out/renderer/assets/{ViewSessionAction-BHJv5QNb.js → ViewSessionAction-66veqRhO.js} +1 -1
- package/out/renderer/assets/{ViewTables-DBTupg46.js → ViewTables-CKKDcYKH.js} +1 -1
- package/out/renderer/assets/{WL6DNKX4-Csfp__Nw.js → WL6DNKX4-Cq-YK4Uf.js} +1 -1
- package/out/renderer/assets/{WQ63CJYP-oSbguA5n.js → WQ63CJYP-fjrhTSVs.js} +1 -1
- package/out/renderer/assets/{XOYAOB3S-DfDDKmX8.js → XOYAOB3S-CAQPI0he.js} +1 -1
- package/out/renderer/assets/{Y5LQLG3M-BnZ8APdi.js → Y5LQLG3M-DKntYAaW.js} +1 -1
- package/out/renderer/assets/{YIK6JTN6-Bunk5CDx.js → YIK6JTN6-CcjcC5JX.js} +1 -1
- package/out/renderer/assets/{core-BbPUgmX7.js → core-Cj89wpQh.js} +4 -4
- package/out/renderer/assets/{file-tabs-CFdJBYJ9.js → file-tabs-PoAgFa7v.js} +1 -1
- package/out/renderer/assets/{ghostty-web-Dn7o-dzQ.js → ghostty-web-DiMuvUtH.js} +1 -1
- package/out/renderer/assets/{highlights-eTGcn9lP.js → highlights-7WH0ppQl.js} +1 -1
- package/out/renderer/assets/{highlights-D4Jo_Sz0.js → highlights-DnSmFBdQ.js} +1 -1
- package/out/renderer/assets/index-CiuUSFeC.js +11 -0
- package/out/renderer/assets/kit-CD3F-f6F.js +147 -0
- package/out/renderer/assets/{langs-CXhlGiW6.js → langs-D5CRC9qz.js} +1 -1
- package/out/renderer/assets/{lazy-D3tN-GAO.js → lazy-CUmWiDAP.js} +3 -3
- package/out/renderer/assets/{loader-DGyfh0zB.js → loader-CPY9efuc.js} +1 -1
- package/out/renderer/assets/{pierre-theme-BZvsTYqQ.js → pierre-theme-BrzM0xZU.js} +3 -3
- package/out/renderer/assets/setting-demos-BW7cG2_G.css +1 -0
- package/out/renderer/assets/setting-demos-DEURBrvf.js +1 -0
- package/out/renderer/assets/{shiki-Wqv4XEGM.js → shiki-DFrbO9j3.js} +1 -1
- package/out/renderer/assets/{sidebar-layout-sK8ujsHX.js → sidebar-layout-fobokay5.js} +1 -1
- package/out/renderer/assets/{stream-tokenizer-C18hljKL.js → stream-tokenizer-CT1HAjvR.js} +1 -1
- package/out/renderer/assets/{themes-Dfx1_kFe.js → themes-Cj62ov9J.js} +1 -1
- package/out/renderer/assets/{useFind-BBxfQuQ2.js → useFind-Cdl0rVJO.js} +3 -3
- package/out/renderer/assets/{useFolderChanges-BcfSJoBT.js → useFolderChanges-C9L_NOgw.js} +2 -2
- package/out/renderer/assets/{view-preview-B2Rj--lZ.js → view-preview-BvCO9WZH.js} +1 -1
- package/out/renderer/assets/{zoom-reset-l-YVDJrI.js → zoom-reset-COqHFP45.js} +1 -1
- package/out/renderer/index.html +5 -5
- package/out/renderer/view-preview.html +6 -6
- package/package.json +2 -2
- package/out/renderer/assets/DiffsTab-D690H0Dy.js +0 -3
- package/out/renderer/assets/IconButtonTip-P9QUxPjA.js +0 -1
- package/out/renderer/assets/index-c95EBMdk.js +0 -8
- package/out/renderer/assets/kit-C9O_D5xC.js +0 -147
- package/out/renderer/assets/setting-demos-B0787McX.js +0 -1
- package/out/renderer/assets/setting-demos-vtrBsYTd.css +0 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./loader-
|
|
2
|
-
import{_ as __vitePreload}from"./kit-C9O_D5xC.js";import{g as getDefaultExportFromCjs,r as reactExports,j as jsxRuntimeExports}from"./vendor-react-CxJ4vs-5.js";const DIFFS_TAG_NAME="diffs-container";(()=>{try{return!1}catch{return!1}})();const COMMIT_METADATA_SPLIT=/(?=^From [a-f0-9]+ .+$)/m,GIT_DIFF_FILE_BREAK_REGEX=/(?=^diff --git)/gm,SPLIT_WITH_NEWLINES=/(?<=\n)/,FILENAME_HEADER_REGEX=/^(---|\+\+\+)\s+([^\t\r\n]+)/,INDEX_LINE_METADATA=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,HEADER_PREFIX_SLOT_ID="header-prefix",HEADER_FILENAME_SUFFIX_SLOT_ID="header-filename-suffix",HEADER_METADATA_SLOT_ID="header-metadata",CUSTOM_HEADER_SLOT_ID="header-custom",DEFAULT_THEMES={dark:"pierre-dark",light:"pierre-light"},THEME_CSS_ATTRIBUTE="data-theme-css",UNSAFE_CSS_ATTRIBUTE="data-unsafe-css",DIFFS_SCROLLBAR_MEASURE_ATTRIBUTE="data-diffs-scrollbar-measure",DIFFS_SCROLLBAR_GUTTER_MEASURED_PROPERTY="--diffs-scrollbar-gutter-measured",DEFAULT_TOKENIZE_MAX_LENGTH=1e5,DEFAULT_VIRTUAL_FILE_METRICS={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8};({...DEFAULT_VIRTUAL_FILE_METRICS});const DEFAULT_EXPANDED_REGION=Object.freeze({fromStart:0,fromEnd:0}),DEFAULT_RENDER_RANGE={startingLine:0,totalLines:1/0,bufferBefore:0,bufferAfter:0},EMPTY_LINE_ANNOTATIONS=Object.freeze([]),EMPTY_RENDER_RANGE={startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:0};let activeType,holds=0;var HighlighterDisposedError=class extends Error{constructor(){super("Highlighter is disposed"),this.name="HighlighterDisposedError"}};function getHighlighterType(){return activeType}function resolveHighlighterType(type){return type??activeType??"shiki-js"}function assertHighlighterType(type){if(activeType!=null&&activeType!==type)throw new Error(`Cannot load the "${type}" highlighter while "${activeType}" is in use. Only one highlighter type can be active at a time; dispose every "${activeType}" instance (disposeHighlighter() disposes the shared one) before switching.`)}function acquireHighlighterType(type){assertHighlighterType(type),activeType=type,holds++}function releaseHighlighterType(){holds--,holds===0&&(activeType=void 0)}const ResolvedLanguages=new Map,ResolvingLanguages=new Map,RegisteredCustomLanguages=new Map,AttachedLanguages=new Set;function getThemes(theme=DEFAULT_THEMES){const themesArr=[];return typeof theme=="string"?themesArr.push(theme):(themesArr.push(theme.dark),themesArr.push(theme.light)),themesArr}function isWorkerContext(){return typeof WorkerGlobalScope<"u"&&typeof self<"u"&&self instanceof WorkerGlobalScope}function createCachedLoader(loader){let cached;return()=>cached??=loader().then(loaded=>(cached=loaded,loaded),error=>{throw cached=void 0,error})}function unwrapDefault(value){return value!==null&&typeof value=="object"&&"default"in value?value.default:value}var DuplicateThemeError=class extends Error{constructor(name){super(`Theme "${name}" is already registered`),this.name="DuplicateThemeError"}},UnregisteredThemeError=class extends Error{constructor(name){super(`No loader registered for theme "${name}"`),this.name="UnregisteredThemeError"}},UnresolvedThemeError=class extends Error{constructor(name){super(`Theme "${name}" has not been resolved`),this.name="UnresolvedThemeError"}};function createThemeResolver(options={}){const loaders=new Map,resolved=new Map,inflight=new Map;let cacheGeneration=0;function registerTheme(name,loader){if(loaders.has(name))throw new DuplicateThemeError(name);loaders.set(name,loader)}function registerThemeIfAbsent(name,loader){return loaders.has(name)?!1:(loaders.set(name,loader),!0)}function hasRegisteredTheme(name){return loaders.has(name)}function resolveTheme(name){const cached=resolved.get(name);if(cached!==void 0)return Promise.resolve(cached);const existing=inflight.get(name);if(existing!==void 0)return existing;const loader=loaders.get(name);if(loader===void 0&&options.fallbackLoader===void 0)return Promise.reject(new UnregisteredThemeError(name));const generation=cacheGeneration,promise=Promise.resolve().then(()=>loader!==void 0?loader():options.fallbackLoader?.(name)).then(async result=>{if(result===void 0)throw new UnregisteredThemeError(name);const loaded=unwrapDefault(result),theme=options.normalizeTheme===void 0?loaded:await options.normalizeTheme(loaded,name);return generation===cacheGeneration&&resolved.set(name,theme),inflight.get(name)===promise&&inflight.delete(name),theme}).catch(err=>{throw inflight.get(name)===promise&&inflight.delete(name),err});return inflight.set(name,promise),promise}function resolveThemes2(names){return Promise.all(names.map(name=>resolveTheme(name)))}function seedResolvedTheme(name,theme){resolved.set(name,theme)}function seedResolvedThemes(entries){for(const[name,theme]of entries)seedResolvedTheme(name,theme)}function getResolvedTheme(name){return resolved.get(name)}function getResolvedThemes2(names){const themes=[];for(const name of names){const theme=resolved.get(name);if(theme===void 0)throw new UnresolvedThemeError(name);themes.push(theme)}return themes}function hasResolvedTheme(name){return resolved.has(name)}function hasResolvedThemes2(names){for(const name of names)if(!resolved.has(name))return!1;return!0}function getResolvedOrResolveTheme(name){const cached=resolved.get(name);return cached!==void 0?cached:resolveTheme(name)}function clearResolvedThemes(){cacheGeneration++,resolved.clear(),inflight.clear()}return{clearResolvedThemes,getResolvedOrResolveTheme,getResolvedTheme,getResolvedThemes:getResolvedThemes2,hasRegisteredTheme,hasResolvedTheme,hasResolvedThemes:hasResolvedThemes2,registerTheme,registerThemeIfAbsent,resolveTheme,resolveThemes:resolveThemes2,seedResolvedTheme,seedResolvedThemes}}const customThemes=new Map,resolvers=new Map,loadHighlightsThemeCatalog=createCachedLoader(()=>__vitePreload(()=>import("./loader-DGyfh0zB.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url)),loadPierreThemeCatalog=createCachedLoader(()=>__vitePreload(()=>import("./themes-Dfx1_kFe.js"),__vite__mapDeps([8,1,2,3,4,5,6,7]),import.meta.url)),loadShikiCore=createCachedLoader(()=>__vitePreload(()=>import("./core-DDlYtZEa.js").then(n=>n.b),__vite__mapDeps([9,10,4,2,5]),import.meta.url)),ZED_COLOR_ALIASES=[["editor.lineHighlightBackground","editor.active_line.background"],["editor.selectionBackground","element.selected"],["editor.findMatchBackground","search.match_background"],["editor.findMatchHighlightBackground","search.match_background"],["editorBracketMatch.background","editor.document_highlight.bracket_background"],["editorError.foreground","error"],["editorWarning.foreground","warning"],["editorInfo.foreground","info"],["editorHint.foreground","hint"],["gitDecoration.addedResourceForeground","created","terminal.ansi.green"],["gitDecoration.deletedResourceForeground","deleted","terminal.ansi.red"],["gitDecoration.modifiedResourceForeground","modified","terminal.ansi.blue"]];function createHighlightsTheme(name,raw){const theme="themes"in raw?raw.themes[0]:raw;if(theme==null)throw new Error(`Theme "${name}" is an empty Zed theme family.`);const zed={...theme,name},colors={};for(const[key,value]of Object.entries(zed.style))typeof value=="string"&&(colors[key]=value);const player=zed.style.players?.[0];player?.cursor!=null&&(colors["editorCursor.foreground"]??=player.cursor),player?.selection!=null&&(colors["editor.selectionBackground"]??=player.selection);for(const[target,...sources]of ZED_COLOR_ALIASES){if(colors[target]!=null)continue;const source=sources.find(key=>colors[key]!=null);source!=null&&(colors[target]=colors[source])}if(zed.cssVariables===!0)colors["editor.foreground"]="var(--hls-foreground)",colors["editor.background"]="var(--hls-background)";else if(typeof zed.cssVariables=="object"){colors["editor.foreground"]??=colors.text??colors.foreground??"foreground",colors["editor.background"]??=colors.background??"background";const{prefix="--hls-",defaults}=zed.cssVariables;for(const[key,value]of Object.entries(colors)){const fallback=defaults?.[value];colors[key]=`var(${prefix}${value}${fallback?`, ${fallback}`:""})`}}const type=zed.appearance==="light"?"light":"dark";return{name,type,colors,zed,fg:colors["editor.foreground"]??colors.text??colors.foreground??(type==="light"?"#333333":"#bbbbbb"),bg:colors["editor.background"]??colors.background??(type==="light"?"#ffffff":"#1e1e1e")}}function createDiffsThemeResolver(backend){let resolver=resolvers.get(backend);return resolver!=null||(resolver=createThemeResolver({fallbackLoader:async name=>{if(typeof __DIFFS_WORKER__<"u"?__DIFFS_WORKER__:isWorkerContext())throw new Error(`Theme "${name}" cannot be resolved from a worker context. Themes must be pre-resolved on the main thread and passed to the worker via the resolvedThemes parameter.`);const custom=customThemes.get(name);if(backend==="highlights"){const loader=custom?.zed??custom?.diffs;if(loader!=null){const loaded=await loader(),theme="default"in loaded?loaded.default:loaded;if("zed"in theme&&theme.zed!=null)return theme;if("style"in theme||"themes"in theme)return createHighlightsTheme(name,theme);throw new Error(`Theme "${name}" is a TextMate theme; register a Zed theme with registerCustomTheme(name, loader, 'zed') for Highlights.`)}const catalog=loadHighlightsThemeCatalog(),{themes}=catalog instanceof Promise?await catalog:catalog,bundledLoader=themes[name];if(bundledLoader!=null)return createHighlightsTheme(name,(await bundledLoader()).default);if(custom?.textmate!=null)throw new Error(`Theme "${name}" is only registered for TextMate; use registerCustomTheme(name, loader, 'zed') for Highlights.`)}else{const loader=custom?.textmate??custom?.diffs;let loaded;if(loader!=null){const result=await loader();loaded="default"in result?result.default:result}else{const catalog=loadPierreThemeCatalog(),{themes}=catalog instanceof Promise?await catalog:catalog,descriptor=themes.getTheme(name);if(descriptor==null&&custom?.zed!=null)throw new Error(`Theme "${name}" is only registered for Zed; use registerCustomTheme(name, loader, 'textmate') for Shiki.`);if(descriptor==null)throw new Error(`No valid theme loader registered for "${name}"`);const result=await descriptor.load();loaded="default"in result?result.default:result}if("style"in loaded||"themes"in loaded)throw new Error(`Theme "${name}" is a Zed theme; use preferredHighlighter: 'highlights' or register a TextMate theme for Shiki.`);const core=loadShikiCore(),{normalizeTheme,createCssVariablesTheme}=core instanceof Promise?await core:core;if("cssVariables"in loaded&&loaded.cssVariables!=null)return{...loaded,textmate:normalizeTheme(createCssVariablesTheme(loaded.cssVariables))};if("textmate"in loaded&&loaded.textmate!=null)return{...loaded,textmate:normalizeTheme(loaded.textmate)};const textmate=normalizeTheme(loaded);return{name:textmate.name,type:textmate.type,fg:textmate.fg,bg:textmate.bg,colors:textmate.colors,textmate}}throw new Error(`No valid theme loader registered for "${name}"`)},normalizeTheme:(theme,name)=>{if(theme.name!==name)throw new Error(`resolvedTheme: themeName: ${name} does not match theme.name: ${theme.name}`);return theme}}),resolvers.set(backend,resolver)),resolver}function areThemesAttached(themes,highlighter2=resolveHighlighterType()){return typeof highlighter2!="string"&&highlighter2.isDisposed?!1:(typeof highlighter2=="string"?createDiffsThemeResolver(highlighter2):highlighter2.themeResolver).hasResolvedThemes(getThemes(themes))}let highlighter;async function createHighlighter(type){const resolvedType=resolveHighlighterType(type);acquireHighlighterType(resolvedType);try{if(resolvedType==="highlights"){const{HighlightsHighlighter}=await __vitePreload(async()=>{const{HighlightsHighlighter:HighlightsHighlighter2}=await import("./highlights-eTGcn9lP.js");return{HighlightsHighlighter:HighlightsHighlighter2}},__vite__mapDeps([11,12,13,10,4,2,5,14,1,3,6,7]),import.meta.url);return new HighlightsHighlighter}const{ShikiHighlighter}=await __vitePreload(async()=>{const{ShikiHighlighter:ShikiHighlighter2}=await import("./shiki-Wqv4XEGM.js");return{ShikiHighlighter:ShikiHighlighter2}},__vite__mapDeps([15,1,2,3,4,5,6,7,12,13,10,16,9]),import.meta.url);return await ShikiHighlighter.create(resolvedType)}finally{releaseHighlighterType()}}async function getSharedHighlighter({themes,langs,preferredHighlighter}){dropDisposedHighlighter();const cached=highlighter??=createHighlighter(getHighlighterType()??preferredHighlighter);let instance;try{instance=await cached}catch(error){throw highlighter===cached&&(highlighter=void 0),error}if(highlighter===cached&&(highlighter=instance),await Promise.all([instance.themeResolver.resolveThemes(themes),instance.loadLanguages(langs)]),instance.isDisposed)throw new HighlighterDisposedError;return instance}function dropDisposedHighlighter(){highlighter!=null&&!("then"in highlighter)&&highlighter.isDisposed&&(highlighter=void 0)}function getHighlighterIfLoaded({theme,lang,langs}={}){dropDisposedHighlighter();const instance=highlighter;if(!(instance==null||"then"in instance||theme!=null&&!areThemesAttached(theme,instance)||(lang!=null||langs!=null)&&!instance.hasLoadedLanguages([...lang!=null?[lang]:[],...langs??[]])))return instance}function areThemesEqual(themeA,themeB){return themeA==null||themeB==null||typeof themeA=="string"||typeof themeB=="string"?themeA===themeB:themeA.dark===themeB.dark&&themeA.light===themeB.light}function createTextNodeElement(value){return{type:"text",value}}function createHastElement({tagName,children=[],properties={}}){return{type:"element",tagName,properties,children}}function createIconElement({name,width=16,height=16,properties}){return createHastElement({tagName:"svg",properties:{width,height,viewBox:"0 0 16 16",...properties},children:[createHastElement({tagName:"use",properties:{href:`#${name.replace(/^#/,"")}`}})]})}function createGutterWrapper(children){return createHastElement({tagName:"div",properties:{"data-gutter":""},children})}function createGutterItem(lineType,lineNumber,lineIndex,properties={}){return createHastElement({tagName:"div",properties:{"data-line-type":lineType,"data-column-number":lineNumber,"data-line-index":lineIndex,...properties},children:lineNumber!=null?[createHastElement({tagName:"span",properties:{"data-line-number-content":""},children:[createTextNodeElement(`${lineNumber}`)]})]:void 0})}function createGutterGap(type,bufferType,size){return createHastElement({tagName:"div",properties:{"data-gutter-buffer":bufferType,"data-buffer-size":size,"data-line-type":bufferType==="annotation"?void 0:type,style:bufferType==="annotation"?`grid-row: span ${size};`:`grid-row: span ${size};min-height:calc(${size} * 1lh);`}})}function areLanguagesAttached(languages,highlighter2){const names=Array.isArray(languages)?languages:[languages];return highlighter2!=null?highlighter2.hasLoadedLanguages(names):names.every(name=>name==="text"||name==="ansi"||AttachedLanguages.has(name))}function areFileRenderOptionsEqual(optionsA,optionsB){return areThemesEqual(optionsA.theme,optionsB.theme)&&optionsA.useTokenTransformer===optionsB.useTokenTransformer&&optionsA.tokenizeMaxLineLength===optionsB.tokenizeMaxLineLength}const CUSTOM_EXTENSION_TO_FILE_FORMAT=new Map;let customExtensionsVersion=0;const EXTENSION_TO_FILE_FORMAT={"1c":"1c",abap:"abap",as:"actionscript-3",ada:"ada",adb:"ada",ads:"ada",adoc:"asciidoc",asciidoc:"asciidoc","component.html":"angular-html","component.ts":"angular-ts",conf:"nginx",htaccess:"apache",cls:"tex",trigger:"apex",apl:"apl",applescript:"applescript",scpt:"applescript",ara:"ara",asm:"asm",s:"riscv",astro:"astro",awk:"awk",bal:"ballerina",sh:"zsh",bash:"zsh",bat:"cmd",cmd:"cmd",be:"berry",beancount:"beancount",bib:"bibtex",bicep:"bicep","blade.php":"blade",bsl:"bsl",c:"c",h:"objective-cpp",cs:"csharp",cpp:"cpp",hpp:"cpp",cc:"cpp",cxx:"cpp",hh:"cpp",cdc:"cdc",cairo:"cairo",clar:"clarity",clj:"clojure",cljs:"clojure",cljc:"clojure",soy:"soy",cmake:"cmake","CMakeLists.txt":"cmake",cob:"cobol",cbl:"cobol",cobol:"cobol",CODEOWNERS:"codeowners",ql:"ql",coffee:"coffeescript",lisp:"lisp",cl:"lisp",lsp:"lisp",log:"log",v:"verilog",cql:"cql",cr:"crystal",css:"css",csv:"csv",cue:"cue",cypher:"cypher",cyp:"cypher",d:"d",dart:"dart",dax:"dax",desktop:"desktop",diff:"diff",patch:"diff",Dockerfile:"dockerfile",dockerfile:"dockerfile",env:"dotenv",dm:"dream-maker",edge:"edge",el:"emacs-lisp",ex:"elixir",exs:"elixir",elm:"elm",erb:"erb",erl:"erlang",hrl:"erlang",f:"fortran-fixed-form",for:"fortran-fixed-form",fs:"fsharp",fsi:"fsharp",fsx:"fsharp",f03:"f03",f08:"f08",f18:"f18",f77:"f77",f90:"fortran-free-form",f95:"fortran-free-form",fnl:"fennel",fish:"fish",ftl:"ftl",tres:"gdresource",res:"gdresource",gd:"gdscript",gdshader:"gdshader",gs:"genie",feature:"gherkin",COMMIT_EDITMSG:"git-commit","git-rebase-todo":"git-rebase",gjs:"glimmer-js",gleam:"gleam",gts:"glimmer-ts",glsl:"glsl",vert:"glsl",frag:"glsl",shader:"shaderlab",gp:"gnuplot",plt:"gnuplot",gnuplot:"gnuplot",go:"go",graphql:"graphql",gql:"graphql",groovy:"groovy",gvy:"groovy",hack:"hack",haml:"haml",hbs:"handlebars",handlebars:"handlebars",hs:"haskell",lhs:"haskell",hx:"haxe",hcl:"hcl",hjson:"hjson",hlsl:"hlsl",fx:"hlsl",html:"html",htm:"html",http:"http",rest:"http",hxml:"hxml",hy:"hy",imba:"imba",ini:"ini",cfg:"ini",jade:"pug",pug:"pug",java:"java",js:"javascript",mjs:"javascript",cjs:"javascript",jinja:"jinja",jinja2:"jinja",j2:"jinja",jison:"jison",jl:"julia",json:"json",json5:"json5",jsonc:"jsonc",jsonl:"jsonl",jsonnet:"jsonnet",libsonnet:"jsonnet",jssm:"jssm",jsx:"jsx",kt:"kotlin",kts:"kts",kql:"kusto",tex:"tex",ltx:"tex",lean:"lean4",less:"less",liquid:"liquid",lit:"lit",ll:"llvm",logo:"logo",lua:"lua",luau:"luau",Makefile:"makefile",mk:"makefile",makefile:"makefile",md:"markdown",markdown:"markdown",marko:"marko",m:"wolfram",mat:"matlab",mdc:"mdc",mdx:"mdx",wiki:"wikitext",mediawiki:"wikitext",mmd:"mermaid",mermaid:"mermaid",mips:"mipsasm",mojo:"mojo","🔥":"mojo",move:"move",nar:"narrat",nf:"nextflow",nim:"nim",nims:"nim",nimble:"nim",nix:"nix",nu:"nushell",mm:"objective-cpp",ml:"ocaml",mli:"ocaml",mll:"ocaml",mly:"ocaml",odin:"odin",pas:"pascal",p:"pascal",pl:"prolog",pm:"perl",t:"perl",raku:"raku",p6:"raku",pl6:"raku",php:"php",phtml:"php",pls:"plsql",sql:"sql",po:"po",polar:"polar",pcss:"postcss",pot:"pot",potx:"potx",pq:"powerquery",pqm:"powerquery",ps1:"powershell",psm1:"powershell",psd1:"powershell",prisma:"prisma",pro:"prolog",P:"prolog",properties:"properties",proto:"protobuf",pp:"puppet",purs:"purescript",py:"python",pyw:"python",pyi:"python",BUCK:"python",BUILD:"python",PACKAGE:"python",WORKSPACE:"python",Tiltfile:"python",bazel:"python",bxl:"python",bzl:"python",bzlmod:"python",star:"python",sky:"python",qml:"qml",qmldir:"qmldir",qss:"qss",r:"r",R:"r",rkt:"racket",rktl:"racket",razor:"razor",cshtml:"razor",rb:"ruby",rbw:"ruby",reg:"reg",regex:"regexp",rel:"rel",rs:"rust",rst:"rst",rake:"ruby",gemspec:"ruby",jbuilder:"ruby",builder:"ruby",rabl:"ruby",arb:"ruby",ru:"ruby",podspec:"ruby",Gemfile:"ruby",Rakefile:"ruby",Guardfile:"ruby",Capfile:"ruby",Berksfile:"ruby",Brewfile:"ruby",Vagrantfile:"ruby",Thorfile:"ruby",Appraisals:"ruby",Dangerfile:"ruby",sas:"sas",sass:"sass",scala:"scala",sc:"scala",scm:"scheme",ss:"scheme",sld:"scheme",scss:"scss",sdbl:"sdbl",shadergraph:"shader",st:"smalltalk",sol:"solidity",sparql:"sparql",rq:"sparql",spl:"splunk",config:"ssh-config",do:"stata",ado:"stata",dta:"stata",styl:"stylus",stylus:"stylus",svelte:"svelte",swift:"swift",sv:"system-verilog",svh:"system-verilog",service:"systemd",socket:"systemd",device:"systemd",timer:"systemd",talon:"talonscript",tasl:"tasl",tcl:"tcl",templ:"templ",tf:"tf",tfvars:"tfvars",toml:"toml",ts:"typescript",mts:"typescript",cts:"typescript",tsp:"typespec",tsv:"tsv",tsx:"tsx",ttl:"turtle",twig:"twig",typ:"typst",vv:"v",vala:"vala",vapi:"vala",vb:"vb",vbs:"vb",bas:"vb",vh:"verilog",vhd:"vhdl",vhdl:"vhdl",vim:"vimscript",vue:"vue","vine.ts":"vue-vine",vy:"vyper",wasm:"wasm",wat:"wasm",wy:"文言",wgsl:"wgsl",wit:"wit",wl:"wolfram",nb:"wolfram",xml:"xml",xsl:"xsl",xslt:"xsl",yaml:"yaml",yml:"yml",zs:"zenscript",zig:"zig",zsh:"zsh",sty:"tex"};function getFiletypeFromFileName(fileName){const format=matchFiletypeFromName(fileName);if(format!=null)return format;const baseName=fileName.split(/[/\\]/).pop()??fileName;return baseName===fileName?"text":matchFiletypeFromName(baseName)??"text"}function matchFiletypeFromName(fileName){if(CUSTOM_EXTENSION_TO_FILE_FORMAT.has(fileName))return CUSTOM_EXTENSION_TO_FILE_FORMAT.get(fileName)??"text";if(Object.hasOwn(EXTENSION_TO_FILE_FORMAT,fileName))return EXTENSION_TO_FILE_FORMAT[fileName]??null;const compoundMatch=fileName.match(/\.([^/\\]+\.[^/\\]+)$/);if(compoundMatch!=null){if(CUSTOM_EXTENSION_TO_FILE_FORMAT.has(compoundMatch[1]))return CUSTOM_EXTENSION_TO_FILE_FORMAT.get(compoundMatch[1])??"text";if(Object.hasOwn(EXTENSION_TO_FILE_FORMAT,compoundMatch[1]))return EXTENSION_TO_FILE_FORMAT[compoundMatch[1]]??"text"}const simpleMatch=fileName.match(/\.([^.]+)$/)?.[1]??"";return CUSTOM_EXTENSION_TO_FILE_FORMAT.has(simpleMatch)?CUSTOM_EXTENSION_TO_FILE_FORMAT.get(simpleMatch)??"text":Object.hasOwn(EXTENSION_TO_FILE_FORMAT,simpleMatch)?EXTENSION_TO_FILE_FORMAT[simpleMatch]??"text":null}function getCustomExtensionsVersion(){return customExtensionsVersion}function getCustomExtensionsMap(){return Object.fromEntries(CUSTOM_EXTENSION_TO_FILE_FORMAT)}function formatCSSVariablePrefix(type){return`--${type==="token"?"diffs-token":"diffs"}-`}const HEX_TRANSPARENT_RE=/^#(?:[0-9a-f]{3}0|[0-9a-f]{6}00)$/i,ALPHA_ZERO_RE=/^0(?:\.0+)?%?$/;function getFunctionalAlpha(color){const openParen=color.indexOf("(");if(openParen<=0||!color.endsWith(")"))return;const fn=color.slice(0,openParen).trim();if(!/^(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color)$/i.test(fn))return;const inner=color.slice(openParen+1,-1).trim();if(inner.length===0)return;const slashIndex=inner.lastIndexOf("/");if(slashIndex!==-1)return inner.slice(slashIndex+1).trim();if(/^(?:rgba|hsla)$/i.test(fn)){const parts=inner.split(",");if(parts.length===4)return parts[3]?.trim()}}function parseHexRgba(color){const match=/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})\b/i.exec(color.trim());if(match==null)return null;const hex=match[1];let expanded,alpha=1;return hex.length===3?expanded=hex.split("").map(c=>c+c).join(""):hex.length===6?expanded=hex:(expanded=hex.slice(0,6),alpha=parseInt(hex.slice(6,8),16)/255),[parseInt(expanded.slice(0,2),16),parseInt(expanded.slice(2,4),16),parseInt(expanded.slice(4,6),16),alpha]}function relativeLuminance(color){if(color==null)return null;const rgba=parseHexRgba(color);if(rgba==null)return null;const r=rgba[0]/255,g=rgba[1]/255,b=rgba[2]/255,channel=v=>v<=.03928?v/12.92:((v+.055)/1.055)**2.4;return .2126*channel(r)+.7152*channel(g)+.0722*channel(b)}function contrastRatio(a,b){const[hi,lo]=a>b?[a,b]:[b,a];return(hi+.05)/(lo+.05)}function compositeOverBg(fgColor,bgColor){if(bgColor==null)return;const fgParts=parseHexRgba(fgColor),bgParts=parseHexRgba(bgColor);if(fgParts==null||bgParts==null)return;const[fr,fg,fb,fa]=fgParts,[br,bg,bb]=bgParts;return"#"+[Math.round(fr*fa+br*(1-fa)),Math.round(fg*fa+bg*(1-fa)),Math.round(fb*fa+bb*(1-fa))].map(v=>v.toString(16).padStart(2,"0")).join("")}function isFullyTransparent(color){if(color==null)return!1;const normalized=color.trim().toLowerCase();if(normalized==="transparent"||HEX_TRANSPARENT_RE.test(normalized))return!0;const alpha=getFunctionalAlpha(normalized);return alpha!=null&&ALPHA_ZERO_RE.test(alpha)}function isDarkSurface(bg,fgHint){const fromBg=relativeLuminance(bg);if(fromBg!=null)return fromBg<.4;const fromFg=relativeLuminance(fgHint);return fromFg!=null?fromFg>.6:!1}function surfacesMatch(a,b){if(a==null||b==null)return!1;if(a.trim().toLowerCase()===b.trim().toLowerCase())return!0;const la=relativeLuminance(a),lb=relativeLuminance(b);return la==null||lb==null?!1:Math.abs(la-lb)<.06}function hoverWouldEraseText(hover,bg,fg){if(bg==null||fg==null)return!1;const hoverL=relativeLuminance(hover),bgL=relativeLuminance(bg),fgL=relativeLuminance(fg);return hoverL==null||bgL==null||fgL==null?!1:Math.abs(hoverL-fgL)<Math.abs(hoverL-bgL)}function pickReadableForeground(bg,candidates){const bgL=relativeLuminance(bg),firstDefined=candidates.find(candidate=>candidate!=null&&candidate!=="");if(bgL==null)return firstDefined;let best,bestRatio=-1;for(const candidate of candidates){if(candidate==null||candidate==="")continue;const candidateL=relativeLuminance(candidate);if(candidateL==null)continue;const ratio=contrastRatio(bgL,candidateL);if(ratio>=3)return candidate;ratio>bestRatio&&(best=candidate,bestRatio=ratio)}return best??firstDefined}function deriveMutedFg(primaryFg,bg){if(bg==null)return primaryFg;const fgParts=parseHexRgba(primaryFg),bgParts=parseHexRgba(bg),bgL=relativeLuminance(bg);if(fgParts==null||bgParts==null||bgL==null)return`color-mix(in srgb, ${primaryFg} 70%, ${bg})`;const[fr,fg2,fb]=fgParts,[br,bg3,bb]=bgParts;for(const weight of[.6,.7,.8,.9]){const hex="#"+[Math.round(fr*weight+br*(1-weight)),Math.round(fg2*weight+bg3*(1-weight)),Math.round(fb*weight+bb*(1-weight))].map(v=>v.toString(16).padStart(2,"0")).join(""),L=relativeLuminance(hex);if(L!=null&&contrastRatio(bgL,L)>=4.5)return hex}return primaryFg}const cache=new WeakMap;function normalizeThemeColors(theme){const cached=cache.get(theme);if(cached!=null)return cached;const originalColors=theme.colors??{},colors={...originalColors},editorBackground=originalColors["editor.background"]??theme.bg,editorForeground=originalColors["editor.foreground"]??theme.fg,sidebarBackground=originalColors["sideBar.background"]??editorBackground,sidebarForeground=originalColors["sideBar.foreground"]??editorForeground;fill(colors,"editor.background",editorBackground),fill(colors,"editor.foreground",editorForeground),fill(colors,"sideBar.background",sidebarBackground),fill(colors,"sideBar.foreground",sidebarForeground),fill(colors,"input.background",originalColors["input.background"]??sidebarBackground),fill(colors,"sideBarSectionHeader.foreground",originalColors["sideBarSectionHeader.foreground"]??sidebarForeground),fill(colors,"list.activeSelectionForeground",originalColors["list.activeSelectionForeground"]??sidebarForeground),fill(colors,"gitDecoration.addedResourceForeground",firstColor(originalColors["gitDecoration.addedResourceForeground"],originalColors["terminal.ansiGreen"],originalColors["editorGutter.addedBackground"])),fill(colors,"gitDecoration.modifiedResourceForeground",firstColor(originalColors["gitDecoration.modifiedResourceForeground"],originalColors["terminal.ansiBlue"],originalColors["editorGutter.modifiedBackground"])),fill(colors,"gitDecoration.deletedResourceForeground",firstColor(originalColors["gitDecoration.deletedResourceForeground"],originalColors["terminal.ansiRed"],originalColors["editorGutter.deletedBackground"]));const focusRing=(isFullyTransparent(originalColors["list.focusOutline"])?void 0:originalColors["list.focusOutline"])??(isFullyTransparent(originalColors.focusBorder)?void 0:originalColors.focusBorder);focusRing!=null?colors["list.focusOutline"]=focusRing:delete colors["list.focusOutline"];const hover=originalColors["list.hoverBackground"];hover!=null&&(matchesSurface(hover,sidebarBackground)||hoverWouldEraseText(hover,sidebarBackground,sidebarForeground))&&delete colors["list.hoverBackground"];const result=Object.freeze({...theme,colors:Object.freeze(colors)});return cache.set(theme,result),result}function fill(colors,key,value){value!=null&&value!==""&&(colors[key]=value)}function firstColor(...candidates){for(const candidate of candidates)if(candidate!=null&&candidate!=="")return candidate}function matchesSurface(color,surface){return surface!=null&&color.toLowerCase()===surface.toLowerCase()}function getHighlighterThemeStyles({theme=DEFAULT_THEMES,highlighter:highlighter2,prefix}){let styles="";if(typeof theme=="string"){const themeData=highlighter2.getTheme(theme),normalized=getThemeColors(themeData,highlighter2);styles+=`color:${normalized.fg};`,styles+=`background-color:${normalized.bg};`,styles+=`${formatCSSVariablePrefix("global")}fg:${normalized.fg};`,styles+=`${formatCSSVariablePrefix("global")}bg:${normalized.bg};`,styles+=getGitVariables(themeData,prefix)}else{let themeData=highlighter2.getTheme(theme.dark),normalized=getThemeColors(themeData,highlighter2);styles+=`${formatCSSVariablePrefix("global")}dark:${normalized.fg};`,styles+=`${formatCSSVariablePrefix("global")}dark-bg:${normalized.bg};`,styles+=getGitVariables(themeData,"dark"),themeData=highlighter2.getTheme(theme.light),normalized=getThemeColors(themeData,highlighter2),styles+=`${formatCSSVariablePrefix("global")}light:${normalized.fg};`,styles+=`${formatCSSVariablePrefix("global")}light-bg:${normalized.bg};`,styles+=getGitVariables(themeData,"light")}return styles}function getThemeColors(theme,highlighter2){if(highlighter2.name==="highlights"&&theme.zed?.cssVariables===!0){const prefix=formatCSSVariablePrefix("token");return{fg:`var(${prefix}foreground)`,bg:`var(${prefix}background)`}}return normalizeThemeColors(theme)}function getGitVariables(themeData,modePrefix){modePrefix=modePrefix!=null?`${modePrefix}-`:"";let styles="";const additionGreen=themeData.colors?.["gitDecoration.addedResourceForeground"]??themeData.colors?.["terminal.ansiGreen"];additionGreen!=null&&(styles+=`${formatCSSVariablePrefix("global")}${modePrefix}addition-color:${additionGreen};`);const deletionRed=themeData.colors?.["gitDecoration.deletedResourceForeground"]??themeData.colors?.["terminal.ansiRed"];deletionRed!=null&&(styles+=`${formatCSSVariablePrefix("global")}${modePrefix}deletion-color:${deletionRed};`);const modifiedBlue=themeData.colors?.["gitDecoration.modifiedResourceForeground"]??themeData.colors?.["terminal.ansiBlue"];return modifiedBlue!=null&&(styles+=`${formatCSSVariablePrefix("global")}${modePrefix}modified-color:${modifiedBlue};`),styles}function processLine(node,line,state){const lineInfo=typeof state.lineInfo=="function"?state.lineInfo(line):state.lineInfo[line-1];if(lineInfo==null){const errorMessage=`processLine: line ${line}, contains no state.lineInfo`;throw console.error(errorMessage,{node,line,state}),new Error(errorMessage)}return node.tagName="div",node.properties["data-line"]=lineInfo.lineNumber,node.properties["data-alt-line"]=lineInfo.altLineNumber,node.properties["data-line-type"]=lineInfo.type,node.properties["data-line-index"]=lineInfo.lineIndex,node.children.length===0&&node.children.push(createTextNodeElement(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./loader-CPY9efuc.js","./kit-CD3F-f6F.js","./vendor-react-CxJ4vs-5.js","./vendor-motion-C2jPaSqL.js","./vendor-owxl31sT.js","./vendor-DeJTMLhw.css","./core-Cj89wpQh.js","./vendor-editor-gVJMCtGz.js","./themes-Cj62ov9J.js","./core-DDlYtZEa.js","./index-C-yjveB4.js","./highlights-7WH0ppQl.js","./stream-tokenizer-CT1HAjvR.js","./hastToHtml-C4ea9WpN.js","./default-B6K4UlPD.js","./shiki-DFrbO9j3.js","./utils-qCteL8MB.js","./langs-D5CRC9qz.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as __vitePreload}from"./kit-CD3F-f6F.js";import{g as getDefaultExportFromCjs,r as reactExports,j as jsxRuntimeExports}from"./vendor-react-CxJ4vs-5.js";const DIFFS_TAG_NAME="diffs-container";(()=>{try{return!1}catch{return!1}})();const COMMIT_METADATA_SPLIT=/(?=^From [a-f0-9]+ .+$)/m,GIT_DIFF_FILE_BREAK_REGEX=/(?=^diff --git)/gm,SPLIT_WITH_NEWLINES=/(?<=\n)/,FILENAME_HEADER_REGEX=/^(---|\+\+\+)\s+([^\t\r\n]+)/,INDEX_LINE_METADATA=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,HEADER_PREFIX_SLOT_ID="header-prefix",HEADER_FILENAME_SUFFIX_SLOT_ID="header-filename-suffix",HEADER_METADATA_SLOT_ID="header-metadata",CUSTOM_HEADER_SLOT_ID="header-custom",DEFAULT_THEMES={dark:"pierre-dark",light:"pierre-light"},THEME_CSS_ATTRIBUTE="data-theme-css",UNSAFE_CSS_ATTRIBUTE="data-unsafe-css",DIFFS_SCROLLBAR_MEASURE_ATTRIBUTE="data-diffs-scrollbar-measure",DIFFS_SCROLLBAR_GUTTER_MEASURED_PROPERTY="--diffs-scrollbar-gutter-measured",DEFAULT_TOKENIZE_MAX_LENGTH=1e5,DEFAULT_VIRTUAL_FILE_METRICS={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8};({...DEFAULT_VIRTUAL_FILE_METRICS});const DEFAULT_EXPANDED_REGION=Object.freeze({fromStart:0,fromEnd:0}),DEFAULT_RENDER_RANGE={startingLine:0,totalLines:1/0,bufferBefore:0,bufferAfter:0},EMPTY_LINE_ANNOTATIONS=Object.freeze([]),EMPTY_RENDER_RANGE={startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:0};let activeType,holds=0;var HighlighterDisposedError=class extends Error{constructor(){super("Highlighter is disposed"),this.name="HighlighterDisposedError"}};function getHighlighterType(){return activeType}function resolveHighlighterType(type){return type??activeType??"shiki-js"}function assertHighlighterType(type){if(activeType!=null&&activeType!==type)throw new Error(`Cannot load the "${type}" highlighter while "${activeType}" is in use. Only one highlighter type can be active at a time; dispose every "${activeType}" instance (disposeHighlighter() disposes the shared one) before switching.`)}function acquireHighlighterType(type){assertHighlighterType(type),activeType=type,holds++}function releaseHighlighterType(){holds--,holds===0&&(activeType=void 0)}const ResolvedLanguages=new Map,ResolvingLanguages=new Map,RegisteredCustomLanguages=new Map,AttachedLanguages=new Set;function getThemes(theme=DEFAULT_THEMES){const themesArr=[];return typeof theme=="string"?themesArr.push(theme):(themesArr.push(theme.dark),themesArr.push(theme.light)),themesArr}function isWorkerContext(){return typeof WorkerGlobalScope<"u"&&typeof self<"u"&&self instanceof WorkerGlobalScope}function createCachedLoader(loader){let cached;return()=>cached??=loader().then(loaded=>(cached=loaded,loaded),error=>{throw cached=void 0,error})}function unwrapDefault(value){return value!==null&&typeof value=="object"&&"default"in value?value.default:value}var DuplicateThemeError=class extends Error{constructor(name){super(`Theme "${name}" is already registered`),this.name="DuplicateThemeError"}},UnregisteredThemeError=class extends Error{constructor(name){super(`No loader registered for theme "${name}"`),this.name="UnregisteredThemeError"}},UnresolvedThemeError=class extends Error{constructor(name){super(`Theme "${name}" has not been resolved`),this.name="UnresolvedThemeError"}};function createThemeResolver(options={}){const loaders=new Map,resolved=new Map,inflight=new Map;let cacheGeneration=0;function registerTheme(name,loader){if(loaders.has(name))throw new DuplicateThemeError(name);loaders.set(name,loader)}function registerThemeIfAbsent(name,loader){return loaders.has(name)?!1:(loaders.set(name,loader),!0)}function hasRegisteredTheme(name){return loaders.has(name)}function resolveTheme(name){const cached=resolved.get(name);if(cached!==void 0)return Promise.resolve(cached);const existing=inflight.get(name);if(existing!==void 0)return existing;const loader=loaders.get(name);if(loader===void 0&&options.fallbackLoader===void 0)return Promise.reject(new UnregisteredThemeError(name));const generation=cacheGeneration,promise=Promise.resolve().then(()=>loader!==void 0?loader():options.fallbackLoader?.(name)).then(async result=>{if(result===void 0)throw new UnregisteredThemeError(name);const loaded=unwrapDefault(result),theme=options.normalizeTheme===void 0?loaded:await options.normalizeTheme(loaded,name);return generation===cacheGeneration&&resolved.set(name,theme),inflight.get(name)===promise&&inflight.delete(name),theme}).catch(err=>{throw inflight.get(name)===promise&&inflight.delete(name),err});return inflight.set(name,promise),promise}function resolveThemes2(names){return Promise.all(names.map(name=>resolveTheme(name)))}function seedResolvedTheme(name,theme){resolved.set(name,theme)}function seedResolvedThemes(entries){for(const[name,theme]of entries)seedResolvedTheme(name,theme)}function getResolvedTheme(name){return resolved.get(name)}function getResolvedThemes2(names){const themes=[];for(const name of names){const theme=resolved.get(name);if(theme===void 0)throw new UnresolvedThemeError(name);themes.push(theme)}return themes}function hasResolvedTheme(name){return resolved.has(name)}function hasResolvedThemes2(names){for(const name of names)if(!resolved.has(name))return!1;return!0}function getResolvedOrResolveTheme(name){const cached=resolved.get(name);return cached!==void 0?cached:resolveTheme(name)}function clearResolvedThemes(){cacheGeneration++,resolved.clear(),inflight.clear()}return{clearResolvedThemes,getResolvedOrResolveTheme,getResolvedTheme,getResolvedThemes:getResolvedThemes2,hasRegisteredTheme,hasResolvedTheme,hasResolvedThemes:hasResolvedThemes2,registerTheme,registerThemeIfAbsent,resolveTheme,resolveThemes:resolveThemes2,seedResolvedTheme,seedResolvedThemes}}const customThemes=new Map,resolvers=new Map,loadHighlightsThemeCatalog=createCachedLoader(()=>__vitePreload(()=>import("./loader-CPY9efuc.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url)),loadPierreThemeCatalog=createCachedLoader(()=>__vitePreload(()=>import("./themes-Cj62ov9J.js"),__vite__mapDeps([8,1,2,3,4,5,6,7]),import.meta.url)),loadShikiCore=createCachedLoader(()=>__vitePreload(()=>import("./core-DDlYtZEa.js").then(n=>n.b),__vite__mapDeps([9,10,4,2,5]),import.meta.url)),ZED_COLOR_ALIASES=[["editor.lineHighlightBackground","editor.active_line.background"],["editor.selectionBackground","element.selected"],["editor.findMatchBackground","search.match_background"],["editor.findMatchHighlightBackground","search.match_background"],["editorBracketMatch.background","editor.document_highlight.bracket_background"],["editorError.foreground","error"],["editorWarning.foreground","warning"],["editorInfo.foreground","info"],["editorHint.foreground","hint"],["gitDecoration.addedResourceForeground","created","terminal.ansi.green"],["gitDecoration.deletedResourceForeground","deleted","terminal.ansi.red"],["gitDecoration.modifiedResourceForeground","modified","terminal.ansi.blue"]];function createHighlightsTheme(name,raw){const theme="themes"in raw?raw.themes[0]:raw;if(theme==null)throw new Error(`Theme "${name}" is an empty Zed theme family.`);const zed={...theme,name},colors={};for(const[key,value]of Object.entries(zed.style))typeof value=="string"&&(colors[key]=value);const player=zed.style.players?.[0];player?.cursor!=null&&(colors["editorCursor.foreground"]??=player.cursor),player?.selection!=null&&(colors["editor.selectionBackground"]??=player.selection);for(const[target,...sources]of ZED_COLOR_ALIASES){if(colors[target]!=null)continue;const source=sources.find(key=>colors[key]!=null);source!=null&&(colors[target]=colors[source])}if(zed.cssVariables===!0)colors["editor.foreground"]="var(--hls-foreground)",colors["editor.background"]="var(--hls-background)";else if(typeof zed.cssVariables=="object"){colors["editor.foreground"]??=colors.text??colors.foreground??"foreground",colors["editor.background"]??=colors.background??"background";const{prefix="--hls-",defaults}=zed.cssVariables;for(const[key,value]of Object.entries(colors)){const fallback=defaults?.[value];colors[key]=`var(${prefix}${value}${fallback?`, ${fallback}`:""})`}}const type=zed.appearance==="light"?"light":"dark";return{name,type,colors,zed,fg:colors["editor.foreground"]??colors.text??colors.foreground??(type==="light"?"#333333":"#bbbbbb"),bg:colors["editor.background"]??colors.background??(type==="light"?"#ffffff":"#1e1e1e")}}function createDiffsThemeResolver(backend){let resolver=resolvers.get(backend);return resolver!=null||(resolver=createThemeResolver({fallbackLoader:async name=>{if(typeof __DIFFS_WORKER__<"u"?__DIFFS_WORKER__:isWorkerContext())throw new Error(`Theme "${name}" cannot be resolved from a worker context. Themes must be pre-resolved on the main thread and passed to the worker via the resolvedThemes parameter.`);const custom=customThemes.get(name);if(backend==="highlights"){const loader=custom?.zed??custom?.diffs;if(loader!=null){const loaded=await loader(),theme="default"in loaded?loaded.default:loaded;if("zed"in theme&&theme.zed!=null)return theme;if("style"in theme||"themes"in theme)return createHighlightsTheme(name,theme);throw new Error(`Theme "${name}" is a TextMate theme; register a Zed theme with registerCustomTheme(name, loader, 'zed') for Highlights.`)}const catalog=loadHighlightsThemeCatalog(),{themes}=catalog instanceof Promise?await catalog:catalog,bundledLoader=themes[name];if(bundledLoader!=null)return createHighlightsTheme(name,(await bundledLoader()).default);if(custom?.textmate!=null)throw new Error(`Theme "${name}" is only registered for TextMate; use registerCustomTheme(name, loader, 'zed') for Highlights.`)}else{const loader=custom?.textmate??custom?.diffs;let loaded;if(loader!=null){const result=await loader();loaded="default"in result?result.default:result}else{const catalog=loadPierreThemeCatalog(),{themes}=catalog instanceof Promise?await catalog:catalog,descriptor=themes.getTheme(name);if(descriptor==null&&custom?.zed!=null)throw new Error(`Theme "${name}" is only registered for Zed; use registerCustomTheme(name, loader, 'textmate') for Shiki.`);if(descriptor==null)throw new Error(`No valid theme loader registered for "${name}"`);const result=await descriptor.load();loaded="default"in result?result.default:result}if("style"in loaded||"themes"in loaded)throw new Error(`Theme "${name}" is a Zed theme; use preferredHighlighter: 'highlights' or register a TextMate theme for Shiki.`);const core=loadShikiCore(),{normalizeTheme,createCssVariablesTheme}=core instanceof Promise?await core:core;if("cssVariables"in loaded&&loaded.cssVariables!=null)return{...loaded,textmate:normalizeTheme(createCssVariablesTheme(loaded.cssVariables))};if("textmate"in loaded&&loaded.textmate!=null)return{...loaded,textmate:normalizeTheme(loaded.textmate)};const textmate=normalizeTheme(loaded);return{name:textmate.name,type:textmate.type,fg:textmate.fg,bg:textmate.bg,colors:textmate.colors,textmate}}throw new Error(`No valid theme loader registered for "${name}"`)},normalizeTheme:(theme,name)=>{if(theme.name!==name)throw new Error(`resolvedTheme: themeName: ${name} does not match theme.name: ${theme.name}`);return theme}}),resolvers.set(backend,resolver)),resolver}function areThemesAttached(themes,highlighter2=resolveHighlighterType()){return typeof highlighter2!="string"&&highlighter2.isDisposed?!1:(typeof highlighter2=="string"?createDiffsThemeResolver(highlighter2):highlighter2.themeResolver).hasResolvedThemes(getThemes(themes))}let highlighter;async function createHighlighter(type){const resolvedType=resolveHighlighterType(type);acquireHighlighterType(resolvedType);try{if(resolvedType==="highlights"){const{HighlightsHighlighter}=await __vitePreload(async()=>{const{HighlightsHighlighter:HighlightsHighlighter2}=await import("./highlights-7WH0ppQl.js");return{HighlightsHighlighter:HighlightsHighlighter2}},__vite__mapDeps([11,12,13,10,4,2,5,14,1,3,6,7]),import.meta.url);return new HighlightsHighlighter}const{ShikiHighlighter}=await __vitePreload(async()=>{const{ShikiHighlighter:ShikiHighlighter2}=await import("./shiki-DFrbO9j3.js");return{ShikiHighlighter:ShikiHighlighter2}},__vite__mapDeps([15,1,2,3,4,5,6,7,12,13,10,16,9]),import.meta.url);return await ShikiHighlighter.create(resolvedType)}finally{releaseHighlighterType()}}async function getSharedHighlighter({themes,langs,preferredHighlighter}){dropDisposedHighlighter();const cached=highlighter??=createHighlighter(getHighlighterType()??preferredHighlighter);let instance;try{instance=await cached}catch(error){throw highlighter===cached&&(highlighter=void 0),error}if(highlighter===cached&&(highlighter=instance),await Promise.all([instance.themeResolver.resolveThemes(themes),instance.loadLanguages(langs)]),instance.isDisposed)throw new HighlighterDisposedError;return instance}function dropDisposedHighlighter(){highlighter!=null&&!("then"in highlighter)&&highlighter.isDisposed&&(highlighter=void 0)}function getHighlighterIfLoaded({theme,lang,langs}={}){dropDisposedHighlighter();const instance=highlighter;if(!(instance==null||"then"in instance||theme!=null&&!areThemesAttached(theme,instance)||(lang!=null||langs!=null)&&!instance.hasLoadedLanguages([...lang!=null?[lang]:[],...langs??[]])))return instance}function areThemesEqual(themeA,themeB){return themeA==null||themeB==null||typeof themeA=="string"||typeof themeB=="string"?themeA===themeB:themeA.dark===themeB.dark&&themeA.light===themeB.light}function createTextNodeElement(value){return{type:"text",value}}function createHastElement({tagName,children=[],properties={}}){return{type:"element",tagName,properties,children}}function createIconElement({name,width=16,height=16,properties}){return createHastElement({tagName:"svg",properties:{width,height,viewBox:"0 0 16 16",...properties},children:[createHastElement({tagName:"use",properties:{href:`#${name.replace(/^#/,"")}`}})]})}function createGutterWrapper(children){return createHastElement({tagName:"div",properties:{"data-gutter":""},children})}function createGutterItem(lineType,lineNumber,lineIndex,properties={}){return createHastElement({tagName:"div",properties:{"data-line-type":lineType,"data-column-number":lineNumber,"data-line-index":lineIndex,...properties},children:lineNumber!=null?[createHastElement({tagName:"span",properties:{"data-line-number-content":""},children:[createTextNodeElement(`${lineNumber}`)]})]:void 0})}function createGutterGap(type,bufferType,size){return createHastElement({tagName:"div",properties:{"data-gutter-buffer":bufferType,"data-buffer-size":size,"data-line-type":bufferType==="annotation"?void 0:type,style:bufferType==="annotation"?`grid-row: span ${size};`:`grid-row: span ${size};min-height:calc(${size} * 1lh);`}})}function areLanguagesAttached(languages,highlighter2){const names=Array.isArray(languages)?languages:[languages];return highlighter2!=null?highlighter2.hasLoadedLanguages(names):names.every(name=>name==="text"||name==="ansi"||AttachedLanguages.has(name))}function areFileRenderOptionsEqual(optionsA,optionsB){return areThemesEqual(optionsA.theme,optionsB.theme)&&optionsA.useTokenTransformer===optionsB.useTokenTransformer&&optionsA.tokenizeMaxLineLength===optionsB.tokenizeMaxLineLength}const CUSTOM_EXTENSION_TO_FILE_FORMAT=new Map;let customExtensionsVersion=0;const EXTENSION_TO_FILE_FORMAT={"1c":"1c",abap:"abap",as:"actionscript-3",ada:"ada",adb:"ada",ads:"ada",adoc:"asciidoc",asciidoc:"asciidoc","component.html":"angular-html","component.ts":"angular-ts",conf:"nginx",htaccess:"apache",cls:"tex",trigger:"apex",apl:"apl",applescript:"applescript",scpt:"applescript",ara:"ara",asm:"asm",s:"riscv",astro:"astro",awk:"awk",bal:"ballerina",sh:"zsh",bash:"zsh",bat:"cmd",cmd:"cmd",be:"berry",beancount:"beancount",bib:"bibtex",bicep:"bicep","blade.php":"blade",bsl:"bsl",c:"c",h:"objective-cpp",cs:"csharp",cpp:"cpp",hpp:"cpp",cc:"cpp",cxx:"cpp",hh:"cpp",cdc:"cdc",cairo:"cairo",clar:"clarity",clj:"clojure",cljs:"clojure",cljc:"clojure",soy:"soy",cmake:"cmake","CMakeLists.txt":"cmake",cob:"cobol",cbl:"cobol",cobol:"cobol",CODEOWNERS:"codeowners",ql:"ql",coffee:"coffeescript",lisp:"lisp",cl:"lisp",lsp:"lisp",log:"log",v:"verilog",cql:"cql",cr:"crystal",css:"css",csv:"csv",cue:"cue",cypher:"cypher",cyp:"cypher",d:"d",dart:"dart",dax:"dax",desktop:"desktop",diff:"diff",patch:"diff",Dockerfile:"dockerfile",dockerfile:"dockerfile",env:"dotenv",dm:"dream-maker",edge:"edge",el:"emacs-lisp",ex:"elixir",exs:"elixir",elm:"elm",erb:"erb",erl:"erlang",hrl:"erlang",f:"fortran-fixed-form",for:"fortran-fixed-form",fs:"fsharp",fsi:"fsharp",fsx:"fsharp",f03:"f03",f08:"f08",f18:"f18",f77:"f77",f90:"fortran-free-form",f95:"fortran-free-form",fnl:"fennel",fish:"fish",ftl:"ftl",tres:"gdresource",res:"gdresource",gd:"gdscript",gdshader:"gdshader",gs:"genie",feature:"gherkin",COMMIT_EDITMSG:"git-commit","git-rebase-todo":"git-rebase",gjs:"glimmer-js",gleam:"gleam",gts:"glimmer-ts",glsl:"glsl",vert:"glsl",frag:"glsl",shader:"shaderlab",gp:"gnuplot",plt:"gnuplot",gnuplot:"gnuplot",go:"go",graphql:"graphql",gql:"graphql",groovy:"groovy",gvy:"groovy",hack:"hack",haml:"haml",hbs:"handlebars",handlebars:"handlebars",hs:"haskell",lhs:"haskell",hx:"haxe",hcl:"hcl",hjson:"hjson",hlsl:"hlsl",fx:"hlsl",html:"html",htm:"html",http:"http",rest:"http",hxml:"hxml",hy:"hy",imba:"imba",ini:"ini",cfg:"ini",jade:"pug",pug:"pug",java:"java",js:"javascript",mjs:"javascript",cjs:"javascript",jinja:"jinja",jinja2:"jinja",j2:"jinja",jison:"jison",jl:"julia",json:"json",json5:"json5",jsonc:"jsonc",jsonl:"jsonl",jsonnet:"jsonnet",libsonnet:"jsonnet",jssm:"jssm",jsx:"jsx",kt:"kotlin",kts:"kts",kql:"kusto",tex:"tex",ltx:"tex",lean:"lean4",less:"less",liquid:"liquid",lit:"lit",ll:"llvm",logo:"logo",lua:"lua",luau:"luau",Makefile:"makefile",mk:"makefile",makefile:"makefile",md:"markdown",markdown:"markdown",marko:"marko",m:"wolfram",mat:"matlab",mdc:"mdc",mdx:"mdx",wiki:"wikitext",mediawiki:"wikitext",mmd:"mermaid",mermaid:"mermaid",mips:"mipsasm",mojo:"mojo","🔥":"mojo",move:"move",nar:"narrat",nf:"nextflow",nim:"nim",nims:"nim",nimble:"nim",nix:"nix",nu:"nushell",mm:"objective-cpp",ml:"ocaml",mli:"ocaml",mll:"ocaml",mly:"ocaml",odin:"odin",pas:"pascal",p:"pascal",pl:"prolog",pm:"perl",t:"perl",raku:"raku",p6:"raku",pl6:"raku",php:"php",phtml:"php",pls:"plsql",sql:"sql",po:"po",polar:"polar",pcss:"postcss",pot:"pot",potx:"potx",pq:"powerquery",pqm:"powerquery",ps1:"powershell",psm1:"powershell",psd1:"powershell",prisma:"prisma",pro:"prolog",P:"prolog",properties:"properties",proto:"protobuf",pp:"puppet",purs:"purescript",py:"python",pyw:"python",pyi:"python",BUCK:"python",BUILD:"python",PACKAGE:"python",WORKSPACE:"python",Tiltfile:"python",bazel:"python",bxl:"python",bzl:"python",bzlmod:"python",star:"python",sky:"python",qml:"qml",qmldir:"qmldir",qss:"qss",r:"r",R:"r",rkt:"racket",rktl:"racket",razor:"razor",cshtml:"razor",rb:"ruby",rbw:"ruby",reg:"reg",regex:"regexp",rel:"rel",rs:"rust",rst:"rst",rake:"ruby",gemspec:"ruby",jbuilder:"ruby",builder:"ruby",rabl:"ruby",arb:"ruby",ru:"ruby",podspec:"ruby",Gemfile:"ruby",Rakefile:"ruby",Guardfile:"ruby",Capfile:"ruby",Berksfile:"ruby",Brewfile:"ruby",Vagrantfile:"ruby",Thorfile:"ruby",Appraisals:"ruby",Dangerfile:"ruby",sas:"sas",sass:"sass",scala:"scala",sc:"scala",scm:"scheme",ss:"scheme",sld:"scheme",scss:"scss",sdbl:"sdbl",shadergraph:"shader",st:"smalltalk",sol:"solidity",sparql:"sparql",rq:"sparql",spl:"splunk",config:"ssh-config",do:"stata",ado:"stata",dta:"stata",styl:"stylus",stylus:"stylus",svelte:"svelte",swift:"swift",sv:"system-verilog",svh:"system-verilog",service:"systemd",socket:"systemd",device:"systemd",timer:"systemd",talon:"talonscript",tasl:"tasl",tcl:"tcl",templ:"templ",tf:"tf",tfvars:"tfvars",toml:"toml",ts:"typescript",mts:"typescript",cts:"typescript",tsp:"typespec",tsv:"tsv",tsx:"tsx",ttl:"turtle",twig:"twig",typ:"typst",vv:"v",vala:"vala",vapi:"vala",vb:"vb",vbs:"vb",bas:"vb",vh:"verilog",vhd:"vhdl",vhdl:"vhdl",vim:"vimscript",vue:"vue","vine.ts":"vue-vine",vy:"vyper",wasm:"wasm",wat:"wasm",wy:"文言",wgsl:"wgsl",wit:"wit",wl:"wolfram",nb:"wolfram",xml:"xml",xsl:"xsl",xslt:"xsl",yaml:"yaml",yml:"yml",zs:"zenscript",zig:"zig",zsh:"zsh",sty:"tex"};function getFiletypeFromFileName(fileName){const format=matchFiletypeFromName(fileName);if(format!=null)return format;const baseName=fileName.split(/[/\\]/).pop()??fileName;return baseName===fileName?"text":matchFiletypeFromName(baseName)??"text"}function matchFiletypeFromName(fileName){if(CUSTOM_EXTENSION_TO_FILE_FORMAT.has(fileName))return CUSTOM_EXTENSION_TO_FILE_FORMAT.get(fileName)??"text";if(Object.hasOwn(EXTENSION_TO_FILE_FORMAT,fileName))return EXTENSION_TO_FILE_FORMAT[fileName]??null;const compoundMatch=fileName.match(/\.([^/\\]+\.[^/\\]+)$/);if(compoundMatch!=null){if(CUSTOM_EXTENSION_TO_FILE_FORMAT.has(compoundMatch[1]))return CUSTOM_EXTENSION_TO_FILE_FORMAT.get(compoundMatch[1])??"text";if(Object.hasOwn(EXTENSION_TO_FILE_FORMAT,compoundMatch[1]))return EXTENSION_TO_FILE_FORMAT[compoundMatch[1]]??"text"}const simpleMatch=fileName.match(/\.([^.]+)$/)?.[1]??"";return CUSTOM_EXTENSION_TO_FILE_FORMAT.has(simpleMatch)?CUSTOM_EXTENSION_TO_FILE_FORMAT.get(simpleMatch)??"text":Object.hasOwn(EXTENSION_TO_FILE_FORMAT,simpleMatch)?EXTENSION_TO_FILE_FORMAT[simpleMatch]??"text":null}function getCustomExtensionsVersion(){return customExtensionsVersion}function getCustomExtensionsMap(){return Object.fromEntries(CUSTOM_EXTENSION_TO_FILE_FORMAT)}function formatCSSVariablePrefix(type){return`--${type==="token"?"diffs-token":"diffs"}-`}const HEX_TRANSPARENT_RE=/^#(?:[0-9a-f]{3}0|[0-9a-f]{6}00)$/i,ALPHA_ZERO_RE=/^0(?:\.0+)?%?$/;function getFunctionalAlpha(color){const openParen=color.indexOf("(");if(openParen<=0||!color.endsWith(")"))return;const fn=color.slice(0,openParen).trim();if(!/^(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color)$/i.test(fn))return;const inner=color.slice(openParen+1,-1).trim();if(inner.length===0)return;const slashIndex=inner.lastIndexOf("/");if(slashIndex!==-1)return inner.slice(slashIndex+1).trim();if(/^(?:rgba|hsla)$/i.test(fn)){const parts=inner.split(",");if(parts.length===4)return parts[3]?.trim()}}function parseHexRgba(color){const match=/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})\b/i.exec(color.trim());if(match==null)return null;const hex=match[1];let expanded,alpha=1;return hex.length===3?expanded=hex.split("").map(c=>c+c).join(""):hex.length===6?expanded=hex:(expanded=hex.slice(0,6),alpha=parseInt(hex.slice(6,8),16)/255),[parseInt(expanded.slice(0,2),16),parseInt(expanded.slice(2,4),16),parseInt(expanded.slice(4,6),16),alpha]}function relativeLuminance(color){if(color==null)return null;const rgba=parseHexRgba(color);if(rgba==null)return null;const r=rgba[0]/255,g=rgba[1]/255,b=rgba[2]/255,channel=v=>v<=.03928?v/12.92:((v+.055)/1.055)**2.4;return .2126*channel(r)+.7152*channel(g)+.0722*channel(b)}function contrastRatio(a,b){const[hi,lo]=a>b?[a,b]:[b,a];return(hi+.05)/(lo+.05)}function compositeOverBg(fgColor,bgColor){if(bgColor==null)return;const fgParts=parseHexRgba(fgColor),bgParts=parseHexRgba(bgColor);if(fgParts==null||bgParts==null)return;const[fr,fg,fb,fa]=fgParts,[br,bg,bb]=bgParts;return"#"+[Math.round(fr*fa+br*(1-fa)),Math.round(fg*fa+bg*(1-fa)),Math.round(fb*fa+bb*(1-fa))].map(v=>v.toString(16).padStart(2,"0")).join("")}function isFullyTransparent(color){if(color==null)return!1;const normalized=color.trim().toLowerCase();if(normalized==="transparent"||HEX_TRANSPARENT_RE.test(normalized))return!0;const alpha=getFunctionalAlpha(normalized);return alpha!=null&&ALPHA_ZERO_RE.test(alpha)}function isDarkSurface(bg,fgHint){const fromBg=relativeLuminance(bg);if(fromBg!=null)return fromBg<.4;const fromFg=relativeLuminance(fgHint);return fromFg!=null?fromFg>.6:!1}function surfacesMatch(a,b){if(a==null||b==null)return!1;if(a.trim().toLowerCase()===b.trim().toLowerCase())return!0;const la=relativeLuminance(a),lb=relativeLuminance(b);return la==null||lb==null?!1:Math.abs(la-lb)<.06}function hoverWouldEraseText(hover,bg,fg){if(bg==null||fg==null)return!1;const hoverL=relativeLuminance(hover),bgL=relativeLuminance(bg),fgL=relativeLuminance(fg);return hoverL==null||bgL==null||fgL==null?!1:Math.abs(hoverL-fgL)<Math.abs(hoverL-bgL)}function pickReadableForeground(bg,candidates){const bgL=relativeLuminance(bg),firstDefined=candidates.find(candidate=>candidate!=null&&candidate!=="");if(bgL==null)return firstDefined;let best,bestRatio=-1;for(const candidate of candidates){if(candidate==null||candidate==="")continue;const candidateL=relativeLuminance(candidate);if(candidateL==null)continue;const ratio=contrastRatio(bgL,candidateL);if(ratio>=3)return candidate;ratio>bestRatio&&(best=candidate,bestRatio=ratio)}return best??firstDefined}function deriveMutedFg(primaryFg,bg){if(bg==null)return primaryFg;const fgParts=parseHexRgba(primaryFg),bgParts=parseHexRgba(bg),bgL=relativeLuminance(bg);if(fgParts==null||bgParts==null||bgL==null)return`color-mix(in srgb, ${primaryFg} 70%, ${bg})`;const[fr,fg2,fb]=fgParts,[br,bg3,bb]=bgParts;for(const weight of[.6,.7,.8,.9]){const hex="#"+[Math.round(fr*weight+br*(1-weight)),Math.round(fg2*weight+bg3*(1-weight)),Math.round(fb*weight+bb*(1-weight))].map(v=>v.toString(16).padStart(2,"0")).join(""),L=relativeLuminance(hex);if(L!=null&&contrastRatio(bgL,L)>=4.5)return hex}return primaryFg}const cache=new WeakMap;function normalizeThemeColors(theme){const cached=cache.get(theme);if(cached!=null)return cached;const originalColors=theme.colors??{},colors={...originalColors},editorBackground=originalColors["editor.background"]??theme.bg,editorForeground=originalColors["editor.foreground"]??theme.fg,sidebarBackground=originalColors["sideBar.background"]??editorBackground,sidebarForeground=originalColors["sideBar.foreground"]??editorForeground;fill(colors,"editor.background",editorBackground),fill(colors,"editor.foreground",editorForeground),fill(colors,"sideBar.background",sidebarBackground),fill(colors,"sideBar.foreground",sidebarForeground),fill(colors,"input.background",originalColors["input.background"]??sidebarBackground),fill(colors,"sideBarSectionHeader.foreground",originalColors["sideBarSectionHeader.foreground"]??sidebarForeground),fill(colors,"list.activeSelectionForeground",originalColors["list.activeSelectionForeground"]??sidebarForeground),fill(colors,"gitDecoration.addedResourceForeground",firstColor(originalColors["gitDecoration.addedResourceForeground"],originalColors["terminal.ansiGreen"],originalColors["editorGutter.addedBackground"])),fill(colors,"gitDecoration.modifiedResourceForeground",firstColor(originalColors["gitDecoration.modifiedResourceForeground"],originalColors["terminal.ansiBlue"],originalColors["editorGutter.modifiedBackground"])),fill(colors,"gitDecoration.deletedResourceForeground",firstColor(originalColors["gitDecoration.deletedResourceForeground"],originalColors["terminal.ansiRed"],originalColors["editorGutter.deletedBackground"]));const focusRing=(isFullyTransparent(originalColors["list.focusOutline"])?void 0:originalColors["list.focusOutline"])??(isFullyTransparent(originalColors.focusBorder)?void 0:originalColors.focusBorder);focusRing!=null?colors["list.focusOutline"]=focusRing:delete colors["list.focusOutline"];const hover=originalColors["list.hoverBackground"];hover!=null&&(matchesSurface(hover,sidebarBackground)||hoverWouldEraseText(hover,sidebarBackground,sidebarForeground))&&delete colors["list.hoverBackground"];const result=Object.freeze({...theme,colors:Object.freeze(colors)});return cache.set(theme,result),result}function fill(colors,key,value){value!=null&&value!==""&&(colors[key]=value)}function firstColor(...candidates){for(const candidate of candidates)if(candidate!=null&&candidate!=="")return candidate}function matchesSurface(color,surface){return surface!=null&&color.toLowerCase()===surface.toLowerCase()}function getHighlighterThemeStyles({theme=DEFAULT_THEMES,highlighter:highlighter2,prefix}){let styles="";if(typeof theme=="string"){const themeData=highlighter2.getTheme(theme),normalized=getThemeColors(themeData,highlighter2);styles+=`color:${normalized.fg};`,styles+=`background-color:${normalized.bg};`,styles+=`${formatCSSVariablePrefix("global")}fg:${normalized.fg};`,styles+=`${formatCSSVariablePrefix("global")}bg:${normalized.bg};`,styles+=getGitVariables(themeData,prefix)}else{let themeData=highlighter2.getTheme(theme.dark),normalized=getThemeColors(themeData,highlighter2);styles+=`${formatCSSVariablePrefix("global")}dark:${normalized.fg};`,styles+=`${formatCSSVariablePrefix("global")}dark-bg:${normalized.bg};`,styles+=getGitVariables(themeData,"dark"),themeData=highlighter2.getTheme(theme.light),normalized=getThemeColors(themeData,highlighter2),styles+=`${formatCSSVariablePrefix("global")}light:${normalized.fg};`,styles+=`${formatCSSVariablePrefix("global")}light-bg:${normalized.bg};`,styles+=getGitVariables(themeData,"light")}return styles}function getThemeColors(theme,highlighter2){if(highlighter2.name==="highlights"&&theme.zed?.cssVariables===!0){const prefix=formatCSSVariablePrefix("token");return{fg:`var(${prefix}foreground)`,bg:`var(${prefix}background)`}}return normalizeThemeColors(theme)}function getGitVariables(themeData,modePrefix){modePrefix=modePrefix!=null?`${modePrefix}-`:"";let styles="";const additionGreen=themeData.colors?.["gitDecoration.addedResourceForeground"]??themeData.colors?.["terminal.ansiGreen"];additionGreen!=null&&(styles+=`${formatCSSVariablePrefix("global")}${modePrefix}addition-color:${additionGreen};`);const deletionRed=themeData.colors?.["gitDecoration.deletedResourceForeground"]??themeData.colors?.["terminal.ansiRed"];deletionRed!=null&&(styles+=`${formatCSSVariablePrefix("global")}${modePrefix}deletion-color:${deletionRed};`);const modifiedBlue=themeData.colors?.["gitDecoration.modifiedResourceForeground"]??themeData.colors?.["terminal.ansiBlue"];return modifiedBlue!=null&&(styles+=`${formatCSSVariablePrefix("global")}${modePrefix}modified-color:${modifiedBlue};`),styles}function processLine(node,line,state){const lineInfo=typeof state.lineInfo=="function"?state.lineInfo(line):state.lineInfo[line-1];if(lineInfo==null){const errorMessage=`processLine: line ${line}, contains no state.lineInfo`;throw console.error(errorMessage,{node,line,state}),new Error(errorMessage)}return node.tagName="div",node.properties["data-line"]=lineInfo.lineNumber,node.properties["data-alt-line"]=lineInfo.altLineNumber,node.properties["data-line-type"]=lineInfo.type,node.properties["data-line-index"]=lineInfo.lineIndex,node.children.length===0&&node.children.push(createTextNodeElement(`
|
|
3
3
|
`)),node}const htmlStyleCache=new WeakMap;function tokenStyle(token,cacheHtmlStyle=!1){const{htmlStyle}=token;if(htmlStyle!=null){let style2=cacheHtmlStyle?htmlStyleCache.get(htmlStyle):void 0;if(style2==null){style2="";for(const name in htmlStyle)style2+=`${style2===""?"":";"}${name}:${htmlStyle[name]}`;cacheHtmlStyle&&htmlStyleCache.set(htmlStyle,style2)}return style2}let style=token.color!=null?`color:${token.color}`:"";if(token.bgColor!=null&&(style+=`;background-color:${token.bgColor}`),token.fontStyle!=null){(token.fontStyle&1)!==0&&(style+=";font-style:italic"),(token.fontStyle&2)!==0&&(style+=";font-weight:bold");const underline=(token.fontStyle&4)!==0,strikethrough=(token.fontStyle&8)!==0;(underline||strikethrough)&&(style+=`;text-decoration:${underline?"underline":""}${underline&&strikethrough?" ":""}${strikethrough?"line-through":""}`)}return style.replace(/^;/,"")}function setDeferredArrayItem(array,index,create,{retain=!0}={}){let initialized=!1,cached;Object.defineProperty(array,index,{configurable:!0,enumerable:!0,get(){if(initialized)return cached;const value=create();return retain?(cached=value,initialized=!0,Object.getOwnPropertyDescriptor(array,index)?.configurable===!0&&Object.defineProperty(array,index,{configurable:!0,enumerable:!0,writable:!0,value:cached}),cached):value},set(value){if(Object.getOwnPropertyDescriptor(array,index)?.configurable===!0)Object.defineProperty(array,index,{configurable:!0,enumerable:!0,writable:!0,value});else{if(Object.isFrozen(array))throw new TypeError(`Cannot assign to read only array index '${index}'`);cached=value,initialized=!0}}})}const NO_TOKEN=Symbol("no-token"),MULTIPLE_TOKENS=Symbol("multiple-tokens");function wrapTokenFragments(container){const ownTokenChar=getTokenChar(container);if(ownTokenChar!=null)return ownTokenChar;let containerTokenState=NO_TOKEN;const wrappedChildren=[];let currentTokenChildren=[],currentTokenChar;const flushTokenChildren=()=>{if(currentTokenChildren.length===0||currentTokenChar==null){currentTokenChildren=[],currentTokenChar=void 0;return}if(currentTokenChildren.length===1){const child=currentTokenChildren[0];if(child?.type==="element"){setTokenChar(child,currentTokenChar);for(const grandChild of child.children)stripTokenChar(grandChild)}else stripTokenChar(child);wrappedChildren.push(child),currentTokenChildren=[],currentTokenChar=void 0;return}for(const child of currentTokenChildren)stripTokenChar(child);wrappedChildren.push(createHastElement({tagName:"span",properties:{"data-char":currentTokenChar},children:currentTokenChildren})),currentTokenChildren=[],currentTokenChar=void 0},mergeContainerTokenState=childTokenState=>{if(childTokenState!==NO_TOKEN){if(childTokenState===MULTIPLE_TOKENS){containerTokenState=MULTIPLE_TOKENS;return}if(containerTokenState===NO_TOKEN){containerTokenState=childTokenState;return}containerTokenState!==childTokenState&&(containerTokenState=MULTIPLE_TOKENS)}};for(const child of container.children){const childTokenState=child.type==="element"?wrapTokenFragments(child):NO_TOKEN;if(mergeContainerTokenState(childTokenState),typeof childTokenState!="number"){flushTokenChildren(),wrappedChildren.push(child);continue}currentTokenChar!=null&¤tTokenChar!==childTokenState&&flushTokenChildren(),currentTokenChar??=childTokenState,currentTokenChildren.push(child)}return flushTokenChildren(),container.children=wrappedChildren,containerTokenState}function getTokenChar(node){const value=node.properties["data-char"];if(typeof value=="number")return value}function stripTokenChar(node){if(node.type==="element"){node.properties["data-char"]=void 0;for(const child of node.children)stripTokenChar(child)}}function setTokenChar(node,char){node.properties["data-char"]=char}function renderTokenLines(lines,{state,lazyLineAST=!1,cacheHtmlStyles=!1,useTokenTransformer=!1,mergeWhitespaces="always",decorations=[],lineOffsets=[]}){let decorationsByLine;for(const decoration of decorations){const byLine=decorationsByLine??=new Map,normalized={...decoration,start:getDecorationPosition(decoration.start,lineOffsets),end:getDecorationPosition(decoration.end,lineOffsets)},lastLine=Math.min(normalized.end.line,lines.length-1);for(let line=normalized.start.line;line<=lastLine;line++){let spans=byLine.get(line);spans==null&&byLine.set(line,spans=[]),spans.push(normalized)}}const renderLine=(tokens,lineIndex)=>{let normalized;if(useTokenTransformer||mergeWhitespaces!=="never"){let pendingWhitespace="",whitespaceOffset=0;for(let i=0;i<tokens.length;i++){let token=tokens[i];if(useTokenTransformer){const content=token.content.trim();if(content!==""&&content!==token.content){normalized??=tokens.slice(0,i);const start=token.content.indexOf(content);start>0&&normalized.push({content:token.content.slice(0,start),offset:token.offset}),normalized.push({...token,content,offset:token.offset+start});const end=start+content.length;end<token.content.length&&normalized.push({content:token.content.slice(end),offset:token.offset+end});continue}}else{const decoratedWhitespace=((token.fontStyle??0)&12)!==0;if(!decoratedWhitespace&&/^\s+$/.test(token.content)&&i<tokens.length-1){normalized??=tokens.slice(0,i),pendingWhitespace===""&&(whitespaceOffset=token.offset),pendingWhitespace+=token.content;continue}pendingWhitespace!==""&&normalized!=null&&(decoratedWhitespace?normalized.push({content:pendingWhitespace,offset:whitespaceOffset}):token={...token,content:pendingWhitespace+token.content,offset:whitespaceOffset},pendingWhitespace="")}normalized?.push(token)}}normalized??=tokens;const line={type:"element",tagName:state==null?"span":"div",properties:state==null?{class:"line"}:{},children:[]},spans=decorationsByLine?.get(lineIndex),column=spans==null?appendTokens(line,normalized,useTokenTransformer,cacheHtmlStyles):appendDecoratedTokens(line,normalized,spans,lineIndex,useTokenTransformer,cacheHtmlStyles);return useTokenTransformer&&column===0&&line.children.push({type:"element",tagName:"br",properties:{},children:[]}),useTokenTransformer&&spans!=null&&wrapTokenFragments(line),state==null?line:processLine(line,lineIndex+1,state)};if(!lazyLineAST)return lines.map(renderLine);const rows=new Array(lines.length);for(let index=0;index<lines.length;index++){const tokens=lines[index];setDeferredArrayItem(rows,index,()=>renderLine(tokens,index))}return rows}function appendTokens(line,tokens,useTokenTransformer,cacheHtmlStyles){let column=0;for(const token of tokens)token.content!==""&&(line.children.push(createTokenSpan(token,tokenStyle(token,cacheHtmlStyles),token.content,column,useTokenTransformer)),column+=token.content.length);return column}function appendDecoratedTokens(line,tokens,spans,lineIndex,useTokenTransformer,cacheHtmlStyles){spans.length>1&&spans.sort((a,b)=>a.start.line!==b.start.line?a.start.line-b.start.line:a.start.character!==b.start.character?a.start.character-b.start.character:a.end.line!==b.end.line?b.end.line-a.end.line:b.end.character-a.end.character);const lineLength=tokens.reduce((length,token)=>length+token.content.length,0),boundaries=[];for(let order=0;order<spans.length;order++){const decoration=spans[order],range={decoration,order,from:decoration.start.line===lineIndex?decoration.start.character:0,to:decoration.end.line===lineIndex?decoration.end.character:lineLength};boundaries.push({position:Math.max(0,Math.min(range.from,lineLength)),range,start:!0},{position:Math.max(0,Math.min(range.to,lineLength)),range,start:!1})}boundaries.sort((a,b)=>a.position-b.position);const active=[],decorationStack=[];let boundaryIndex=0;const updateActive=(range,add)=>{let low=0,high=active.length;for(;low<high;){const middle=low+high>>>1;active[middle].order<range.order?low=middle+1:high=middle}add?active.splice(low,0,range):active[low]===range&&active.splice(low,1)},getParent=()=>{let parent2=line,depth=0;for(const range of active){if(decorationStack[depth]?.range!==range){decorationStack.length=depth;const wrapper={type:"element",tagName:"span",properties:{...range.decoration.properties},children:[]};parent2.children.push(wrapper),decorationStack.push({range,node:wrapper})}parent2=decorationStack[depth++].node}return decorationStack.length=depth,parent2};let parent=line;const advanceBoundary=position=>{const first=boundaryIndex;for(;boundaries[boundaryIndex]?.position===position;)boundaryIndex++;let hasMarker=!1;for(let i=first;i<boundaryIndex;i++){const{range,start}=boundaries[i];!start&&range.from!==range.to&&position<lineLength&&updateActive(range,!1)}for(let i=first;i<boundaryIndex;i++){const{range,start}=boundaries[i];start&&range.from<=position&&range.to>=position&&(range.to>position||range.from===position||position===lineLength)&&(updateActive(range,!0),range.from===range.to&&(hasMarker=!0))}if(hasMarker){getParent();for(let i=first;i<boundaryIndex;i++){const{range,start}=boundaries[i];start&&range.from===range.to&&updateActive(range,!1)}}position<lineLength&&(parent=getParent())};let column=0;for(const token of tokens){if(token.content==="")continue;const start=column,end=start+token.content.length,style=tokenStyle(token,cacheHtmlStyles);for(;column<end;){boundaries[boundaryIndex]?.position===column&&advanceBoundary(column);const to=Math.min(end,boundaries[boundaryIndex]?.position??end);parent.children.push(createTokenSpan(token,style,column===start&&to===end?token.content:token.content.slice(column-start,to-start),start,useTokenTransformer)),column=to}}return boundaries[boundaryIndex]?.position===column&&advanceBoundary(column),column}function createTokenSpan(token,style,text,start,useTokenTransformer){const properties=token.htmlAttrs!=null?{...token.htmlAttrs}:{};return style!==""&&(properties.style=style),useTokenTransformer&&(properties["data-char"]=start),{type:"element",tagName:"span",properties,children:[{type:"text",value:text}]}}function getDecorationPosition(position,lineOffsets){if(typeof position!="number")return position;let low=0,high=lineOffsets.length;for(;low+1<high;){const middle=low+high>>>1;lineOffsets[middle]<=position?low=middle:high=middle}return{line:low,character:position-(lineOffsets[low]??0)}}const LINE_FEED=10,CARRIAGE_RETURN=13,DENSE_LINE_BREAK_BLOCK_SIZE=4,DENSE_LINE_BREAK_BLOCK_SPAN=40;function computeLineOffsets(contents){const offsets=[0];let carriageReturn=contents.indexOf("\r"),lineFeed=contents.indexOf(`
|
|
4
4
|
`),blockStart=0,blockBreaks=0;for(;carriageReturn!==-1||lineFeed!==-1;){let nextOffset;if(carriageReturn!==-1&&(lineFeed===-1||carriageReturn<lineFeed)?lineFeed===carriageReturn+1?(nextOffset=lineFeed+1,carriageReturn=contents.indexOf("\r",nextOffset),lineFeed=contents.indexOf(`
|
|
5
5
|
`,nextOffset)):(nextOffset=carriageReturn+1,carriageReturn=contents.indexOf("\r",nextOffset)):(nextOffset=lineFeed+1,lineFeed=contents.indexOf(`
|
|
6
6
|
`,nextOffset)),offsets.push(nextOffset),++blockBreaks===DENSE_LINE_BREAK_BLOCK_SIZE){if(nextOffset-blockStart<=DENSE_LINE_BREAK_BLOCK_SPAN){for(let i=nextOffset;i<contents.length;i++){const char=contents.charCodeAt(i);(char===LINE_FEED||char===CARRIAGE_RETURN)&&(char===CARRIAGE_RETURN&&i+1<contents.length&&contents.charCodeAt(i+1)===LINE_FEED&&i++,offsets.push(i+1))}return offsets}blockStart=nextOffset,blockBreaks=0}}return offsets}function countLineBreaks(contents){let count=0;for(let i=0;i<contents.length;i++){const char=contents.charCodeAt(i);(char===LINE_FEED||char===CARRIAGE_RETURN)&&(char===CARRIAGE_RETURN&&i+1<contents.length&&contents.charCodeAt(i+1)===LINE_FEED&&i++,count++)}return count}function linesFromFileContents(contents){const offsets=computeLineOffsets(contents);return Array.from({length:offsets.length},(_,i)=>{const start=offsets[i],end=offsets[i+1]??contents.length;return contents.slice(start,end)})}function appendItems(target,items){for(const item of items)target.push(item)}function getTokenOptions(lang,theme,tokenizeMaxLineLength){return{lang,...typeof theme=="string"?{theme}:{themes:theme},defaultColor:!1,cssVariablePrefix:formatCSSVariablePrefix("token"),tokenizeMaxLineLength,tokenizeTimeLimit:0}}const DEFAULT_PLAIN_TEXT_OPTIONS$1={forcePlainText:!1};function renderFileWithHighlighter(file,highlighter2,{theme,tokenizeMaxLineLength,useTokenTransformer},{forcePlainText,lazyLineAST=!1,startingLine,totalLines,lines}=DEFAULT_PLAIN_TEXT_OPTIONS$1){forcePlainText?(startingLine??=0,totalLines??=1/0):(startingLine=0,totalLines=1/0);const isWindowedHighlight=startingLine>0||totalLines<1/0,state={lineInfo:[]},lang=forcePlainText?"text":file.lang??getFiletypeFromFileName(file.name),baseThemeType=typeof theme=="string"?highlighter2.getTheme(theme).type:void 0,themeStyles=getHighlighterThemeStyles({theme,highlighter:highlighter2});state.lineInfo=shikiLineNumber=>({type:"context",lineIndex:shikiLineNumber-1+startingLine,lineNumber:shikiLineNumber+startingLine});const highlightedLines=renderTokenLines(highlighter2.codeToTokens(normalizeHighlightLineEndings(isWindowedHighlight?extractWindowedFileContent(lines??linesFromFileContents(file.contents),startingLine,totalLines):file.contents),getTokenOptions(lang,theme,tokenizeMaxLineLength)).tokens,{state,useTokenTransformer,lazyLineAST:lazyLineAST&&!forcePlainText&&!useTokenTransformer,cacheHtmlStyles:highlighter2.name==="highlights"}),code=isWindowedHighlight?new Array(startingLine):highlightedLines;return isWindowedHighlight&&appendItems(code,highlightedLines),{code,themeStyles,baseThemeType}}function normalizeHighlightLineEndings(contents){return contents.replace(/\r(?!\n)/g,`
|
|
7
|
-
`)}function extractWindowedFileContent(lines,startingLine,totalLines){if(lines.length===0)return"";const endLine=Math.min(startingLine+totalLines,lines.length);return lines.slice(startingLine,endLine).join("")}function isFilePlainText(file){return(file.lang??getFiletypeFromFileName(file.name))==="text"}var WorkerPoolTerminatedError=class extends Error{constructor(){super("WorkerPoolManager: operation canceled because the pool terminated"),this.name="WorkerPoolTerminatedError"}},WorkerPoolTaskCanceledError=class extends Error{constructor(){super("WorkerPoolManager: operation canceled before the task completed"),this.name="WorkerPoolTaskCanceledError"}},WorkerPoolWorkerError=class extends Error{constructor(message,options){super(message,options),this.name="WorkerPoolWorkerError"}};const reportedWorkerErrors=new WeakSet;function markWorkerErrorReported(error){reportedWorkerErrors.add(error)}function isWorkerPoolCancellation(error){return error instanceof WorkerPoolTerminatedError||error instanceof WorkerPoolTaskCanceledError}function isHandledWorkerPoolError(error){return isWorkerPoolCancellation(error)||error instanceof WorkerPoolWorkerError&&reportedWorkerErrors.has(error)}function computeVirtualFileMetrics(metrics){return{...DEFAULT_VIRTUAL_FILE_METRICS,...metrics}}function getVirtualFileHeaderRegion(metrics,disableFileHeader){return getVirtualFileHeaderHeight(metrics,disableFileHeader)+getVirtualFilePaddingTop(metrics,disableFileHeader)}function getVirtualFileHeaderHeight(metrics,disableFileHeader){return disableFileHeader?0:metrics.diffHeaderHeight}function getVirtualFilePaddingTop(metrics,disableFileHeader){return metrics.paddingTop??(disableFileHeader?metrics.spacing:0)}function getVirtualFilePaddingBottom(metrics){return metrics.paddingBottom??metrics.spacing}function getDefaultHunkSeparatorHeight(type){switch(type){case"simple":return 4;case"metadata":case"line-info":case"line-info-basic":case"custom":return 32}}function areDiffTargetsEqual(diffA,diffB){return diffA?.cacheKey!=null||diffB?.cacheKey!=null?diffA?.cacheKey===diffB?.cacheKey:diffA===diffB}function areFilesEqual(fileA,fileB){return fileA?.cacheKey===fileB?.cacheKey&&fileA?.contents===fileB?.contents&&fileA?.name===fileB?.name&&fileA?.lang===fileB?.lang}function getHunkSideStartBoundary(start,count){return start-(count===0?0:1)}function getHunkSideEndBoundary(start,count){return getHunkSideStartBoundary(start,count)+count}function cleanLastNewline(contents){let end=contents.length;return contents.charCodeAt(end-1)===10&&(end--,contents.charCodeAt(end-1)===13&&end--),contents.slice(0,end)}class Diff{diff(oldStr,newStr,options={}){let callback;typeof options=="function"?(callback=options,options={}):"callback"in options&&(callback=options.callback);const oldString=this.castInput(oldStr,options),newString=this.castInput(newStr,options),oldTokens=this.removeEmpty(this.tokenize(oldString,options)),newTokens=this.removeEmpty(this.tokenize(newString,options));return this.diffWithOptionsObj(oldTokens,newTokens,options,callback)}diffWithOptionsObj(oldTokens,newTokens,options,callback){var _a;const done=value=>{if(value=this.postProcess(value,options),callback){setTimeout(function(){callback(value)},0);return}else return value},newLen=newTokens.length,oldLen=oldTokens.length;let editLength=1,maxEditLength=newLen+oldLen;options.maxEditLength!=null&&(maxEditLength=Math.min(maxEditLength,options.maxEditLength));const maxExecutionTime=(_a=options.timeout)!==null&&_a!==void 0?_a:1/0,abortAfterTimestamp=Date.now()+maxExecutionTime,bestPath=[{oldPos:-1,lastComponent:void 0}];let newPos=this.extractCommon(bestPath[0],newTokens,oldTokens,0,options);if(bestPath[0].oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(bestPath[0].lastComponent,newTokens,oldTokens));let minDiagonalToConsider=-1/0,maxDiagonalToConsider=1/0;const execEditLength=()=>{for(let diagonalPath=Math.max(minDiagonalToConsider,-editLength);diagonalPath<=Math.min(maxDiagonalToConsider,editLength);diagonalPath+=2){let basePath;const removePath=bestPath[diagonalPath-1],addPath=bestPath[diagonalPath+1];removePath&&(bestPath[diagonalPath-1]=void 0);let canAdd=!1;if(addPath){const addPathNewPos=addPath.oldPos-diagonalPath;canAdd=addPath&&0<=addPathNewPos&&addPathNewPos<newLen}const canRemove=removePath&&removePath.oldPos+1<oldLen;if(!canAdd&&!canRemove){bestPath[diagonalPath]=void 0;continue}if(!canRemove||canAdd&&removePath.oldPos<addPath.oldPos?basePath=this.addToPath(addPath,!0,!1,0,options):basePath=this.addToPath(removePath,!1,!0,1,options),newPos=this.extractCommon(basePath,newTokens,oldTokens,diagonalPath,options),basePath.oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(basePath.lastComponent,newTokens,oldTokens))||!0;bestPath[diagonalPath]=basePath,basePath.oldPos+1>=oldLen&&(maxDiagonalToConsider=Math.min(maxDiagonalToConsider,diagonalPath-1)),newPos+1>=newLen&&(minDiagonalToConsider=Math.max(minDiagonalToConsider,diagonalPath+1))}editLength++};if(callback)(function exec(){setTimeout(function(){if(editLength>maxEditLength||Date.now()>abortAfterTimestamp)return callback(void 0);execEditLength()||exec()},0)})();else for(;editLength<=maxEditLength&&Date.now()<=abortAfterTimestamp;){const ret=execEditLength();if(ret)return ret}}addToPath(path,added,removed,oldPosInc,options){const last=path.lastComponent;return last&&!options.oneChangePerToken&&last.added===added&&last.removed===removed?{oldPos:path.oldPos+oldPosInc,lastComponent:{count:last.count+1,added,removed,previousComponent:last.previousComponent}}:{oldPos:path.oldPos+oldPosInc,lastComponent:{count:1,added,removed,previousComponent:last}}}extractCommon(basePath,newTokens,oldTokens,diagonalPath,options){const newLen=newTokens.length,oldLen=oldTokens.length;let oldPos=basePath.oldPos,newPos=oldPos-diagonalPath,commonCount=0;for(;newPos+1<newLen&&oldPos+1<oldLen&&this.equals(oldTokens[oldPos+1],newTokens[newPos+1],options);)newPos++,oldPos++,commonCount++,options.oneChangePerToken&&(basePath.lastComponent={count:1,previousComponent:basePath.lastComponent,added:!1,removed:!1});return commonCount&&!options.oneChangePerToken&&(basePath.lastComponent={count:commonCount,previousComponent:basePath.lastComponent,added:!1,removed:!1}),basePath.oldPos=oldPos,newPos}equals(left,right,options){return options.comparator?options.comparator(left,right):left===right||!!options.ignoreCase&&left.toLowerCase()===right.toLowerCase()}removeEmpty(array){const ret=[];for(let i=0;i<array.length;i++)array[i]&&ret.push(array[i]);return ret}castInput(value,options){return value}tokenize(value,options){return Array.from(value)}join(chars){return chars.join("")}postProcess(changeObjects,options){return changeObjects}get useLongestToken(){return!1}buildValues(lastComponent,newTokens,oldTokens){const components=[];let nextComponent;for(;lastComponent;)components.push(lastComponent),nextComponent=lastComponent.previousComponent,delete lastComponent.previousComponent,lastComponent=nextComponent;components.reverse();const componentLen=components.length;let componentPos=0,newPos=0,oldPos=0;for(;componentPos<componentLen;componentPos++){const component=components[componentPos];if(component.removed)component.value=this.join(oldTokens.slice(oldPos,oldPos+component.count)),oldPos+=component.count;else{if(!component.added&&this.useLongestToken){let value=newTokens.slice(newPos,newPos+component.count);value=value.map(function(value2,i){const oldValue=oldTokens[oldPos+i];return oldValue.length>value2.length?oldValue:value2}),component.value=this.join(value)}else component.value=this.join(newTokens.slice(newPos,newPos+component.count));newPos+=component.count,component.added||(oldPos+=component.count)}}return components}}class CharacterDiff extends Diff{}const characterDiff=new CharacterDiff;function diffChars(oldStr,newStr,options){return characterDiff.diff(oldStr,newStr,options)}const extendedWordChars="a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}";class WordsWithSpaceDiff extends Diff{tokenize(value){const regex=new RegExp(`(\\r?\\n)|[${extendedWordChars}]+|[^\\S\\n\\r]+|[^${extendedWordChars}]`,"ug");return value.match(regex)||[]}}const wordsWithSpaceDiff=new WordsWithSpaceDiff;function diffWordsWithSpace(oldStr,newStr,options){return wordsWithSpaceDiff.diff(oldStr,newStr,options)}function areDiffRenderOptionsEqual(optionsA,optionsB){return areThemesEqual(optionsA.theme,optionsB.theme)&&optionsA.useTokenTransformer===optionsB.useTokenTransformer&&optionsA.tokenizeMaxLineLength===optionsB.tokenizeMaxLineLength&&optionsA.lineDiffType===optionsB.lineDiffType&&optionsA.maxLineDiffLength===optionsB.maxLineDiffLength}function createDiffSpanDecoration({line,spanStart,spanLength}){return{start:{line,character:spanStart},end:{line,character:spanStart+spanLength},properties:{"data-diff-span":""},alwaysWrap:!0}}function pushOrJoinSpan({item,arr,enableJoin,isNeutral=!1,isLastItem=!1}){const lastItem=arr[arr.length-1];if(lastItem==null||isLastItem||!enableJoin){arr.push([isNeutral?0:1,item.value]);return}const isLastItemNeutral=lastItem[0]===0;if(isNeutral===isLastItemNeutral||isNeutral&&item.value.length===1&&!isLastItemNeutral){lastItem[1]+=item.value;return}arr.push([isNeutral?0:1,item.value])}function getHunkAdditionLineRange(hunk){return[getHunkSideStartBoundary(hunk.additionStart,hunk.additionCount)+1,getHunkSideEndBoundary(hunk.additionStart,hunk.additionCount)+1]}function getExpandedRegion({isPartial,rangeSize,expandedHunks,hunkIndex,collapsedContextThreshold}){const normalizedRangeSize=Math.max(rangeSize,0);if(normalizedRangeSize===0||isPartial)return{fromStart:0,fromEnd:0,rangeSize:normalizedRangeSize,collapsedLines:normalizedRangeSize,renderAll:!1};if(expandedHunks===!0||normalizedRangeSize<=collapsedContextThreshold)return{fromStart:normalizedRangeSize,fromEnd:0,rangeSize:normalizedRangeSize,collapsedLines:0,renderAll:!0};const region=expandedHunks?.get(hunkIndex),fromStart=Math.min(Math.max(region?.fromStart??0,0),normalizedRangeSize),fromEnd=Math.min(Math.max(region?.fromEnd??0,0),normalizedRangeSize),expandedCount=fromStart+fromEnd,renderAll=expandedCount>=normalizedRangeSize;return{fromStart:renderAll?normalizedRangeSize:fromStart,fromEnd:renderAll?0:fromEnd,rangeSize:normalizedRangeSize,collapsedLines:Math.max(normalizedRangeSize-expandedCount,0),renderAll}}function hasTrailingContextMismatch(fileDiff){const lastHunk=fileDiff.hunks[fileDiff.hunks.length-1];if(lastHunk==null||fileDiff.isPartial||fileDiff.additionLines.length===0||fileDiff.deletionLines.length===0)return!1;const additionRemaining=fileDiff.additionLines.length-getHunkSideEndBoundary(lastHunk.additionStart,lastHunk.additionCount),deletionRemaining=fileDiff.deletionLines.length-getHunkSideEndBoundary(lastHunk.deletionStart,lastHunk.deletionCount);return additionRemaining<=0&&deletionRemaining<=0?!1:additionRemaining!==deletionRemaining}function getTrailingContextRangeSize({fileDiff,errorPrefix}){const lastHunk=fileDiff.hunks[fileDiff.hunks.length-1];if(lastHunk==null||fileDiff.isPartial||fileDiff.additionLines.length===0||fileDiff.deletionLines.length===0)return 0;const additionRemaining=fileDiff.additionLines.length-getHunkSideEndBoundary(lastHunk.additionStart,lastHunk.additionCount),deletionRemaining=fileDiff.deletionLines.length-getHunkSideEndBoundary(lastHunk.deletionStart,lastHunk.deletionCount);if(additionRemaining<=0&&deletionRemaining<=0)return 0;if(additionRemaining!==deletionRemaining)throw new Error(`${errorPrefix}: trailing context mismatch (additions=${additionRemaining}, deletions=${deletionRemaining}) for ${fileDiff.name}`);return Math.min(additionRemaining,deletionRemaining)}function getTrailingExpandedRegion({fileDiff,hunkIndex,expandedHunks,collapsedContextThreshold,errorPrefix}){if(hunkIndex!==fileDiff.hunks.length-1)return;const trailingRangeSize=getTrailingContextRangeSize({fileDiff,errorPrefix});if(trailingRangeSize<=0)return;if(expandedHunks===!0||trailingRangeSize<=collapsedContextThreshold)return{fromStart:trailingRangeSize,fromEnd:0,rangeSize:trailingRangeSize,collapsedLines:0,renderAll:!0};const region=expandedHunks?.get(fileDiff.hunks.length),fromStart=Math.min(Math.max(region?.fromStart??0,0),trailingRangeSize);return{fromStart,fromEnd:0,rangeSize:trailingRangeSize,collapsedLines:trailingRangeSize-fromStart,renderAll:fromStart>=trailingRangeSize}}function isAdditionLineRenderable({fileDiff,lineNumber,expandedHunks,collapsedContextThreshold}){if(expandedHunks===!0||fileDiff.isPartial)return!0;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;return region.renderAll||lineNumber<gapStart+region.fromStart||lineNumber>=hunkStart-region.fromEnd}if(lineNumber<hunkEnd)return!0}const trailingRegion=getTrailingExpandedRegion({fileDiff,hunkIndex:fileDiff.hunks.length-1,expandedHunks,collapsedContextThreshold,errorPrefix:"isAdditionLineRenderable"});if(trailingRegion==null||trailingRegion.renderAll)return!0;const lastHunk=fileDiff.hunks[fileDiff.hunks.length-1],[,trailingStart]=getHunkAdditionLineRange(lastHunk);return lineNumber<trailingStart+trailingRegion.fromStart||lineNumber>=trailingStart+trailingRegion.rangeSize}function getNearestRenderableAdditionLine({fileDiff,lineNumber,direction,expandedHunks,collapsedContextThreshold}){if(expandedHunks===!0||fileDiff.isPartial)return lineNumber;const ranges=[];let modeledEnd=1;for(const[hunkIndex,hunk]of fileDiff.hunks.entries()){const[hunkStart,hunkEnd]=getHunkAdditionLineRange(hunk),region=getExpandedRegion({isPartial:fileDiff.isPartial,rangeSize:hunk.collapsedBefore,expandedHunks,hunkIndex,collapsedContextThreshold}),gapStart=hunkStart-region.rangeSize;region.renderAll?ranges.push([gapStart,hunkStart]):(region.fromStart>0&&ranges.push([gapStart,gapStart+region.fromStart]),region.fromEnd>0&&ranges.push([hunkStart-region.fromEnd,hunkStart])),ranges.push([hunkStart,hunkEnd]),modeledEnd=hunkEnd}const trailingRegion=getTrailingExpandedRegion({fileDiff,hunkIndex:fileDiff.hunks.length-1,expandedHunks,collapsedContextThreshold,errorPrefix:"getNearestRenderableAdditionLine"});if(trailingRegion!=null){const trailingStart=modeledEnd;modeledEnd=trailingStart+trailingRegion.rangeSize,trailingRegion.renderAll?ranges.push([trailingStart,modeledEnd]):trailingRegion.fromStart>0&&ranges.push([trailingStart,trailingStart+trailingRegion.fromStart])}if(lineNumber>=modeledEnd)return lineNumber;if(direction==="down"){for(const[start,end]of ranges)if(end>lineNumber)return Math.max(start,lineNumber);return}for(let index=ranges.length-1;index>=0;index--){const[start,end]=ranges[index];if(start<=lineNumber)return Math.min(end-1,lineNumber)}}function getHunkSeparatorHeight({type,metrics}){return metrics.hunkSeparatorHeight??getDefaultHunkSeparatorHeight(type)}function getHunkSeparatorGap({type,metrics}){return type==="simple"||type==="metadata"||type==="line-info-basic"?0:metrics.spacing}function hasLeadingHunkSeparator({type,hunkIndex,hunkSpecs}){switch(type){case"simple":return hunkIndex>0;case"metadata":return hunkSpecs!=null;case"line-info":case"line-info-basic":case"custom":return!0}}function hasTrailingHunkSeparator(type){return type!=="simple"&&type!=="metadata"}function getLeadingHunkSeparatorLayout({type,metrics,hunkIndex,hunkSpecs}){if(!hasLeadingHunkSeparator({type,hunkIndex,hunkSpecs}))return;const height=getHunkSeparatorHeight({type,metrics}),gap=getHunkSeparatorGap({type,metrics}),gapBefore=hunkIndex>0?gap:0,gapAfter=gap;return{height,gapBefore,gapAfter,totalHeight:gapBefore+height+gapAfter}}function getTrailingHunkSeparatorLayout({type,metrics}){if(!hasTrailingHunkSeparator(type))return;const height=getHunkSeparatorHeight({type,metrics}),gapBefore=getHunkSeparatorGap({type,metrics});return{height,gapBefore,gapAfter:0,totalHeight:gapBefore+height}}function iterateOverDiff({diff,diffStyle,startingLine=0,totalLines=1/0,expandedHunks,collapsedContextThreshold=1,callback}){const iterationStart=getIterationStartState({diff,diffStyle,startingLine,expandedHunks,collapsedContextThreshold}),state={viewportStart:startingLine,viewportEnd:startingLine+totalLines,isWindowedHighlight:startingLine>0||totalLines<1/0,splitCount:iterationStart.splitCount,unifiedCount:iterationStart.unifiedCount,finalHunkIndex:diff.hunks.length-1,shouldBreak(){if(!state.isWindowedHighlight)return!1;const breakUnified=state.unifiedCount>=startingLine+totalLines,breakSplit=state.splitCount>=startingLine+totalLines;return diffStyle==="unified"?breakUnified:(diffStyle==="split"||breakUnified)&&breakSplit},shouldSkip(unifiedCount,splitCount){if(!state.isWindowedHighlight)return!1;const skipUnified=unifiedCount>0&&state.unifiedCount+unifiedCount<=startingLine,skipSplit=splitCount>0&&state.splitCount+splitCount<=startingLine;return diffStyle==="unified"?skipUnified:(diffStyle==="split"||skipUnified)&&skipSplit},incrementCounts(unifiedValue,splitValue){(diffStyle==="unified"||diffStyle==="both")&&(state.unifiedCount+=unifiedValue),(diffStyle==="split"||diffStyle==="both")&&(state.splitCount+=splitValue)},isInWindow(unifiedHeight,splitHeight){if(!state.isWindowedHighlight)return!0;const unifiedInWindow=state.isInUnifiedWindow(unifiedHeight),splitInWindow=state.isInSplitWindow(splitHeight);return diffStyle==="unified"?unifiedInWindow:diffStyle==="split"?splitInWindow:unifiedInWindow||splitInWindow},isInUnifiedWindow(unifiedHeight){return!state.isWindowedHighlight||state.unifiedCount>=startingLine-unifiedHeight&&state.unifiedCount<startingLine+totalLines},isInSplitWindow(splitHeight){return!state.isWindowedHighlight||state.splitCount>=startingLine-splitHeight&&state.splitCount<startingLine+totalLines},emit(props,silent=!1){return silent||(diffStyle==="unified"?state.incrementCounts(1,0):diffStyle==="split"?state.incrementCounts(0,1):state.incrementCounts(1,1)),callback(props)??!1}};hunkIterator:for(let hunkIndex=iterationStart.hunkIndex;hunkIndex<diff.hunks.length;hunkIndex++){let getTrailingCollapsedAfter=function(unifiedLineIndex2,splitLineIndex2){return trailingRegion==null||trailingRegion.collapsedLines<=0||trailingRegion.fromStart+trailingRegion.fromEnd>0?0:diffStyle==="unified"?unifiedLineIndex2===hunk.unifiedLineStart+hunk.unifiedLineCount-1?trailingRegion.collapsedLines:0:splitLineIndex2===hunk.splitLineStart+hunk.splitLineCount-1?trailingRegion.collapsedLines:0},consumePendingCollapsed=function(){return consumedCollapsed?0:(consumedCollapsed=!0,leadingRegion.collapsedLines)};const hunk=diff.hunks[hunkIndex];if(hunk==null)throw new Error("iterateOverDiff: invalid hunk index");if(state.shouldBreak())break;const deletionBoundary=getHunkSideStartBoundary(hunk.deletionStart,hunk.deletionCount),additionBoundary=getHunkSideStartBoundary(hunk.additionStart,hunk.additionCount),deletionStartIndex=!diff.isPartial&&hunk.deletionCount===0?deletionBoundary:hunk.deletionLineIndex,additionStartIndex=!diff.isPartial&&hunk.additionCount===0?additionBoundary:hunk.additionLineIndex,leadingRegion=getExpandedRegion({isPartial:diff.isPartial,rangeSize:hunk.collapsedBefore,expandedHunks,hunkIndex,collapsedContextThreshold}),trailingRegion=hunkIndex===state.finalHunkIndex?getTrailingExpandedRegion({fileDiff:diff,hunkIndex,expandedHunks,collapsedContextThreshold,errorPrefix:"iterateOverDiff"}):void 0,expandedLineCount=leadingRegion.fromStart+leadingRegion.fromEnd;let consumedCollapsed=leadingRegion.collapsedLines===0;if(state.shouldSkip(expandedLineCount,expandedLineCount))state.incrementCounts(expandedLineCount,expandedLineCount),consumePendingCollapsed();else{let unifiedLineIndex2=hunk.unifiedLineStart-leadingRegion.rangeSize,splitLineIndex2=hunk.splitLineStart-leadingRegion.rangeSize,deletionLineIndex2=deletionStartIndex-leadingRegion.rangeSize,additionLineIndex2=additionStartIndex-leadingRegion.rangeSize,deletionLineNumber2=deletionBoundary+1-leadingRegion.rangeSize,additionLineNumber2=additionBoundary+1-leadingRegion.rangeSize;if(walkContextLines(state,leadingRegion.fromStart,diffStyle,index=>state.emit({hunkIndex,hunk,collapsedBefore:0,collapsedAfter:0,type:"context-expanded",deletionLine:{lineNumber:deletionLineNumber2+index,lineIndex:deletionLineIndex2+index,noEOFCR:!1,unifiedLineIndex:unifiedLineIndex2+index,splitLineIndex:splitLineIndex2+index},additionLine:{unifiedLineIndex:unifiedLineIndex2+index,splitLineIndex:splitLineIndex2+index,lineIndex:additionLineIndex2+index,lineNumber:additionLineNumber2+index,noEOFCR:!1}}))||(unifiedLineIndex2=hunk.unifiedLineStart-leadingRegion.fromEnd,splitLineIndex2=hunk.splitLineStart-leadingRegion.fromEnd,deletionLineIndex2=deletionStartIndex-leadingRegion.fromEnd,additionLineIndex2=additionStartIndex-leadingRegion.fromEnd,deletionLineNumber2=deletionBoundary+1-leadingRegion.fromEnd,additionLineNumber2=additionBoundary+1-leadingRegion.fromEnd,walkContextLines(state,leadingRegion.fromEnd,diffStyle,index=>state.emit({hunkIndex,hunk,collapsedBefore:consumePendingCollapsed(),collapsedAfter:0,type:"context-expanded",deletionLine:{lineNumber:deletionLineNumber2+index,lineIndex:deletionLineIndex2+index,noEOFCR:!1,unifiedLineIndex:unifiedLineIndex2+index,splitLineIndex:splitLineIndex2+index},additionLine:{unifiedLineIndex:unifiedLineIndex2+index,splitLineIndex:splitLineIndex2+index,lineIndex:additionLineIndex2+index,lineNumber:additionLineNumber2+index,noEOFCR:!1}}),()=>{consumePendingCollapsed()})))break hunkIterator}let unifiedLineIndex=hunk.unifiedLineStart,splitLineIndex=hunk.splitLineStart,deletionLineIndex=deletionStartIndex,additionLineIndex=additionStartIndex,deletionLineNumber=deletionBoundary+1,additionLineNumber=additionBoundary+1;const lastContent=hunk.hunkContent.at(-1);for(const content of hunk.hunkContent){if(state.shouldBreak())break hunkIterator;const isLastContent=content===lastContent;if(content.type==="context"){if(state.shouldSkip(content.lines,content.lines))state.incrementCounts(content.lines,content.lines),consumePendingCollapsed();else if(walkContextLines(state,content.lines,diffStyle,index=>{const isLastLine=isLastContent&&index===content.lines-1,unifiedRowIndex=unifiedLineIndex+index,splitRowIndex=splitLineIndex+index;return state.emit({hunkIndex,hunk,collapsedBefore:consumePendingCollapsed(),collapsedAfter:getTrailingCollapsedAfter(unifiedRowIndex,splitRowIndex),type:"context",deletionLine:{lineNumber:deletionLineNumber+index,lineIndex:deletionLineIndex+index,noEOFCR:isLastLine&&hunk.noEOFCRDeletions,unifiedLineIndex:unifiedRowIndex,splitLineIndex:splitRowIndex},additionLine:{unifiedLineIndex:unifiedRowIndex,splitLineIndex:splitRowIndex,lineIndex:additionLineIndex+index,lineNumber:additionLineNumber+index,noEOFCR:isLastLine&&hunk.noEOFCRAdditions}})},()=>{consumePendingCollapsed()}))break hunkIterator;unifiedLineIndex+=content.lines,splitLineIndex+=content.lines,deletionLineIndex+=content.lines,additionLineIndex+=content.lines,deletionLineNumber+=content.lines,additionLineNumber+=content.lines}else{const splitCount=Math.max(content.deletions,content.additions),unifiedCount=content.deletions+content.additions;if(!state.shouldSkip(unifiedCount,splitCount)){const iterationRanges=getChangeIterationRanges(state,content,diffStyle);(iterationRanges[0]?.[0]??0)>0&&consumePendingCollapsed();for(const[rangeStart,rangeEnd]of iterationRanges)for(let index=rangeStart;index<rangeEnd;index++){const collapsedAfter=getTrailingCollapsedAfter(unifiedLineIndex+index,diffStyle==="unified"?splitLineIndex+(index<content.deletions?index:index-content.deletions):splitLineIndex+index);if(state.emit(getChangeLineData({hunkIndex,hunk,collapsedBefore:consumePendingCollapsed(),collapsedAfter,diffStyle,index,unifiedLineIndex,splitLineIndex,additionLineIndex,deletionLineIndex,additionLineNumber,deletionLineNumber,content,isLastContent,unifiedCount,splitCount}),!0))break hunkIterator}}consumePendingCollapsed(),state.incrementCounts(unifiedCount,splitCount),unifiedLineIndex+=unifiedCount,splitLineIndex+=splitCount,deletionLineIndex+=content.deletions,additionLineIndex+=content.additions,deletionLineNumber+=content.deletions,additionLineNumber+=content.additions}}if(trailingRegion!=null){const{collapsedLines,fromStart,fromEnd}=trailingRegion,len=fromStart+fromEnd;if(walkContextLines(state,len,diffStyle,index=>{const isLastLine=index===len-1;return state.emit({hunkIndex:diff.hunks.length,hunk:void 0,collapsedBefore:0,collapsedAfter:isLastLine?collapsedLines:0,type:"context-expanded",deletionLine:{lineNumber:deletionLineNumber+index,lineIndex:deletionLineIndex+index,noEOFCR:!1,unifiedLineIndex:unifiedLineIndex+index,splitLineIndex:splitLineIndex+index},additionLine:{unifiedLineIndex:unifiedLineIndex+index,splitLineIndex:splitLineIndex+index,lineIndex:additionLineIndex+index,lineNumber:additionLineNumber+index,noEOFCR:!1}})},void 0,()=>state.shouldBreak()))break hunkIterator}}}function getIterationStartState({diff,diffStyle,startingLine,expandedHunks,collapsedContextThreshold}){if(startingLine<=0||diffStyle==="both")return{hunkIndex:0,splitCount:0,unifiedCount:0};const prefixCounts=getHunkPrefixCounts({diff,expandedHunks,collapsedContextThreshold});let low=0,high=diff.hunks.length-1,result=diff.hunks.length;for(;low<=high;){const mid=low+high>>1,counts2=prefixCounts[mid+1];if(counts2==null)throw new Error("iterateOverDiff: invalid hunk prefix index");(diffStyle==="unified"?counts2.unifiedCount:counts2.splitCount)>startingLine?(result=mid,high=mid-1):low=mid+1}if(result>=diff.hunks.length){const counts2=prefixCounts[diff.hunks.length];if(counts2==null)throw new Error("iterateOverDiff: invalid terminal hunk prefix index");return{hunkIndex:diff.hunks.length,splitCount:counts2.splitCount,unifiedCount:counts2.unifiedCount}}const counts=prefixCounts[result];if(counts==null)throw new Error("iterateOverDiff: invalid selected hunk prefix index");return{hunkIndex:result,splitCount:counts.splitCount,unifiedCount:counts.unifiedCount}}function getHunkPrefixCounts({diff,expandedHunks,collapsedContextThreshold}){let splitCount=0,unifiedCount=0;const finalHunkIndex=diff.hunks.length-1,prefixCounts=[{splitCount:0,unifiedCount:0}];for(let index=0;index<diff.hunks.length;index++){const hunk=diff.hunks[index];if(hunk==null)throw new Error("iterateOverDiff: invalid hunk summary index");const leadingRegion=getExpandedRegion({isPartial:diff.isPartial,rangeSize:hunk.collapsedBefore,expandedHunks,hunkIndex:index,collapsedContextThreshold}),leadingCount=leadingRegion.fromStart+leadingRegion.fromEnd;splitCount+=leadingCount+hunk.splitLineCount,unifiedCount+=leadingCount+hunk.unifiedLineCount;const trailingRegion=index===finalHunkIndex?getTrailingExpandedRegion({fileDiff:diff,hunkIndex:index,expandedHunks,collapsedContextThreshold,errorPrefix:"iterateOverDiff"}):void 0;if(trailingRegion!=null){const trailingCount=trailingRegion.fromStart+trailingRegion.fromEnd;splitCount+=trailingCount,unifiedCount+=trailingCount}prefixCounts.push({splitCount,unifiedCount})}return prefixCounts}function getContextLineIterationBounds(state,count,diffStyle){if(!state.isWindowedHighlight||count<=0)return[0,count];const ranges=[];function pushRange(currentCount){const start2=Math.max(0,state.viewportStart-currentCount),end2=Math.min(count,state.viewportEnd-currentCount);end2>start2&&ranges.push([start2,end2])}if(diffStyle!=="split"&&pushRange(state.unifiedCount),diffStyle!=="unified"&&pushRange(state.splitCount),ranges.length===0)return[0,0];let start=ranges[0][0],end=ranges[0][1];for(let index=1;index<ranges.length;index++){const range=ranges[index];start=Math.min(start,range[0]),end=Math.max(end,range[1])}return[start,end]}function walkContextLines(state,count,diffStyle,callback,onSkippedStart,shouldBreak){const[startIndex,endIndex]=getContextLineIterationBounds(state,count,diffStyle);startIndex>0&&(state.incrementCounts(startIndex,startIndex),onSkippedStart?.());let index=startIndex;for(;index<count;){if(shouldBreak?.()===!0)return!0;if(index>=endIndex){state.incrementCounts(count-index,count-index);break}if(state.isInWindow(0,0)){if(callback(index)===!0)return!0}else state.incrementCounts(1,1);index++}return!1}function getChangeIterationRanges(state,content,diffStyle){if(!state.isWindowedHighlight)return[[0,diffStyle==="unified"?content.deletions+content.additions:Math.max(content.deletions,content.additions)]];const useUnified=diffStyle!=="split",useSplit=diffStyle!=="unified",iterationSpace=diffStyle==="unified"?"unified":"split",iterationRanges=[];function getVisibleRange(start,count){if(start+count<=state.viewportStart||start>=state.viewportEnd)return;const visibleStart=Math.max(0,state.viewportStart-start),visibleEnd=Math.min(count,state.viewportEnd-start);return visibleEnd>visibleStart?[visibleStart,visibleEnd]:void 0}function mapRangeToIteration(range,kind){return iterationSpace==="split"?range:kind==="additions"?[range[0]+content.deletions,range[1]+content.deletions]:range}function pushRange(range,kind){if(range==null)return;const[start,end]=mapRangeToIteration(range,kind);end>start&&iterationRanges.push([start,end])}if(useUnified&&(pushRange(getVisibleRange(state.unifiedCount,content.deletions),"deletions"),pushRange(getVisibleRange(state.unifiedCount+content.deletions,content.additions),"additions")),useSplit&&(pushRange(getVisibleRange(state.splitCount,content.deletions),"deletions"),pushRange(getVisibleRange(state.splitCount,content.additions),"additions")),iterationRanges.length===0)return iterationRanges;iterationRanges.sort((a,b)=>a[0]-b[0]);const merged=[iterationRanges[0]];for(const[start,end]of iterationRanges.slice(1)){const last=merged[merged.length-1];start<=last[1]?last[1]=Math.max(last[1],end):merged.push([start,end])}return merged}function getChangeLineData({hunkIndex,hunk,collapsedAfter,collapsedBefore,diffStyle,index,unifiedLineIndex,splitLineIndex,additionLineIndex,deletionLineIndex,additionLineNumber,deletionLineNumber,content,isLastContent,unifiedCount,splitCount}){const unifiedDeletionLineIndex=index<content.deletions?unifiedLineIndex+index:void 0,unifiedAdditionLineIndex=diffStyle==="unified"?index>=content.deletions?unifiedLineIndex+index:void 0:index<content.additions?unifiedLineIndex+content.deletions+index:void 0,resolvedSplitLineIndex=diffStyle==="unified"?splitLineIndex+(index<content.deletions?index:index-content.deletions):splitLineIndex+index,deletionLineIndexValue=index<content.deletions?deletionLineIndex+index:void 0,deletionLineNumberValue=index<content.deletions?deletionLineNumber+index:void 0,additionLineIndexValue=diffStyle==="unified"?index>=content.deletions?additionLineIndex+(index-content.deletions):void 0:index<content.additions?additionLineIndex+index:void 0,additionLineNumberValue=diffStyle==="unified"?index>=content.deletions?additionLineNumber+(index-content.deletions):void 0:index<content.additions?additionLineNumber+index:void 0,noEOFCRDeletion=diffStyle==="unified"?isLastContent&&index===content.deletions-1&&hunk.noEOFCRDeletions:isLastContent&&index===splitCount-1&&hunk.noEOFCRDeletions,noEOFCRAddition=diffStyle==="unified"?isLastContent&&index===unifiedCount-1&&hunk.noEOFCRAdditions:isLastContent&&index===splitCount-1&&hunk.noEOFCRAdditions,deletionLine=deletionLineIndexValue!=null&&deletionLineNumberValue!=null&&unifiedDeletionLineIndex!=null?{lineNumber:deletionLineNumberValue,lineIndex:deletionLineIndexValue,noEOFCR:noEOFCRDeletion,unifiedLineIndex:unifiedDeletionLineIndex,splitLineIndex:resolvedSplitLineIndex}:void 0,additionLine=additionLineIndexValue!=null&&additionLineNumberValue!=null&&unifiedAdditionLineIndex!=null?{unifiedLineIndex:unifiedAdditionLineIndex,splitLineIndex:resolvedSplitLineIndex,lineIndex:additionLineIndexValue,lineNumber:additionLineNumberValue,noEOFCR:noEOFCRAddition}:void 0;if(deletionLine==null&&additionLine!=null)return{type:"change",hunkIndex,hunk,collapsedAfter,collapsedBefore,deletionLine:void 0,additionLine};if(deletionLine!=null&&additionLine==null)return{type:"change",hunkIndex,hunk,collapsedAfter,collapsedBefore,deletionLine,additionLine:void 0};if(deletionLine==null||additionLine==null)throw new Error("iterateOverDiff: missing change line data");return{type:"change",hunkIndex,hunk,collapsedAfter,collapsedBefore,deletionLine,additionLine}}const DEFAULT_PLAIN_TEXT_OPTIONS={forcePlainText:!1};function renderDiffWithHighlighter(diff,highlighter2,options,{forcePlainText,lazyLineAST=!1,startingLine,totalLines,expandedHunks,collapsedContextThreshold=1}=DEFAULT_PLAIN_TEXT_OPTIONS){forcePlainText?(startingLine??=0,totalLines??=1/0):(startingLine=0,totalLines=1/0);const isWindowedHighlight=startingLine>0||totalLines<1/0;lazyLineAST&&=!forcePlainText&&!options.useTokenTransformer;const baseThemeType=typeof options.theme=="string"?highlighter2.getTheme(options.theme).type:void 0,themeStyles=getHighlighterThemeStyles({theme:options.theme,highlighter:highlighter2}),lineDiffType=forcePlainText&&!isWindowedHighlight&&(diff.unifiedLineCount>1e3||diff.splitLineCount>1e3)?"none":options.lineDiffType,code={deletionLines:[],additionLines:[]},{maxLineDiffLength}=options,shouldGroupAll=!forcePlainText&&!diff.isPartial,expandedHunksForIteration=forcePlainText?expandedHunks:void 0,buckets=new Map;function getBucketForHunk(hunkIndex){const index=shouldGroupAll?0:hunkIndex,bucket=buckets.get(index)??createBucket();return buckets.set(index,bucket),bucket}function appendContent(lineContent,lineIndex,segments,contentWrapper){if(isWindowedHighlight){let segment=segments.at(-1);(segment==null||segment.targetIndex+segment.count!==lineIndex)&&(segment={targetIndex:lineIndex,originalOffset:contentWrapper.length,count:0},segments.push(segment)),segment.count++}contentWrapper.push(lineContent)}iterateOverDiff({diff,diffStyle:"both",startingLine,totalLines,expandedHunks:isWindowedHighlight?expandedHunksForIteration:!0,collapsedContextThreshold,callback:({hunkIndex,additionLine,deletionLine,type})=>{const bucket=getBucketForHunk(hunkIndex),splitLineIndex=additionLine!=null?additionLine.splitLineIndex:deletionLine.splitLineIndex;type==="change"&&additionLine!=null&&deletionLine!=null&&computeLineDiffDecorations({additionLine:diff.additionLines[additionLine.lineIndex],deletionLine:diff.deletionLines[deletionLine.lineIndex],deletionLineIndex:bucket.deletionContent.length,additionLineIndex:bucket.additionContent.length,deletionDecorations:bucket.deletionDecorations,additionDecorations:bucket.additionDecorations,lineDiffType,maxLineDiffLength}),deletionLine!=null&&(appendContent(diff.deletionLines[deletionLine.lineIndex],deletionLine.lineIndex,bucket.deletionSegments,bucket.deletionContent),bucket.deletionInfo.push({type:type==="change"?"change-deletion":type,lineNumber:deletionLine.lineNumber,altLineNumber:type==="change"?void 0:additionLine.lineNumber??void 0,lineIndex:`${deletionLine.unifiedLineIndex},${splitLineIndex}`})),additionLine!=null&&(appendContent(diff.additionLines[additionLine.lineIndex],additionLine.lineIndex,bucket.additionSegments,bucket.additionContent),bucket.additionInfo.push({type:type==="change"?"change-addition":type,lineNumber:additionLine.lineNumber,altLineNumber:type==="change"?void 0:deletionLine.lineNumber??void 0,lineIndex:`${additionLine.unifiedLineIndex},${splitLineIndex}`}))}});for(const bucket of buckets.values()){if(bucket.deletionContent.length===0&&bucket.additionContent.length===0)continue;const deletionFile={name:diff.prevName??diff.name,contents:bucket.deletionContent.value},additionFile={name:diff.name,contents:bucket.additionContent.value},{deletionLines,additionLines}=renderTwoFiles({deletionFile,deletionInfo:bucket.deletionInfo,deletionDecorations:bucket.deletionDecorations,additionFile,additionInfo:bucket.additionInfo,additionDecorations:bucket.additionDecorations,highlighter:highlighter2,options,languageOverride:forcePlainText?"text":diff.lang,lazyLineAST});if(shouldGroupAll){code.deletionLines=deletionLines,code.additionLines=additionLines;continue}for(const[target,lines,segments]of[[code.deletionLines,deletionLines,bucket.deletionSegments],[code.additionLines,additionLines,bucket.additionSegments]])if(segments.length>0)for(const segment of segments)for(let index=0;index<segment.count;index++)target[segment.targetIndex+index]=lines[segment.originalOffset+index];else if(lazyLineAST){const offset=target.length;for(let index=0;index<lines.length;index++)setDeferredArrayItem(target,offset+index,()=>lines[index])}else appendItems(target,lines)}return{code,themeStyles,baseThemeType}}function pushWordLineDecorations(lineDiff,{deletionLineIndex,additionLineIndex,deletionDecorations,additionDecorations}){let deletionOffset=0,additionOffset=0,deletionStart=-1,deletionEnd=0,additionStart=-1,additionEnd=0;for(const{value,added,removed}of lineDiff)removed?(deletionStart===-1&&(deletionStart=deletionOffset),deletionOffset+=value.length,deletionEnd=deletionOffset):added?(additionStart===-1&&(additionStart=additionOffset),additionOffset+=value.length,additionEnd=additionOffset):(deletionOffset+=value.length,additionOffset+=value.length);deletionStart!==-1&&deletionDecorations.push(createDiffSpanDecoration({line:deletionLineIndex,spanStart:deletionStart,spanLength:deletionEnd-deletionStart})),additionStart!==-1&&additionDecorations.push(createDiffSpanDecoration({line:additionLineIndex,spanStart:additionStart,spanLength:additionEnd-additionStart}))}function computeLineDiffDecorations({deletionLine,additionLine,deletionLineIndex,additionLineIndex,deletionDecorations,additionDecorations,lineDiffType,maxLineDiffLength}){if(deletionLine==null||additionLine==null||lineDiffType==="none"||(deletionLine=cleanLastNewline(deletionLine),additionLine=cleanLastNewline(additionLine),deletionLine.length>maxLineDiffLength||additionLine.length>maxLineDiffLength))return;const lineDiff=lineDiffType==="char"?diffChars(deletionLine,additionLine):diffWordsWithSpace(deletionLine,additionLine);if(lineDiffType==="word-line"){pushWordLineDecorations(lineDiff,{deletionLineIndex,additionLineIndex,deletionDecorations,additionDecorations});return}const deletionSpans=[],additionSpans=[],enableJoin=lineDiffType==="word-alt",lastItem=lineDiff.at(-1);for(const item of lineDiff){const isLastItem=item===lastItem;!item.added&&!item.removed?(pushOrJoinSpan({item,arr:deletionSpans,enableJoin,isNeutral:!0,isLastItem}),pushOrJoinSpan({item,arr:additionSpans,enableJoin,isNeutral:!0,isLastItem})):item.removed?pushOrJoinSpan({item,arr:deletionSpans,enableJoin,isLastItem}):pushOrJoinSpan({item,arr:additionSpans,enableJoin,isLastItem})}let spanIndex=0;for(const span of deletionSpans)span[0]===1&&deletionDecorations.push(createDiffSpanDecoration({line:deletionLineIndex,spanStart:spanIndex,spanLength:span[1].length})),spanIndex+=span[1].length;spanIndex=0;for(const span of additionSpans)span[0]===1&&additionDecorations.push(createDiffSpanDecoration({line:additionLineIndex,spanStart:spanIndex,spanLength:span[1].length})),spanIndex+=span[1].length}function createBucket(){return{deletionContent:{push(value){this.value+=value,this.length++},value:"",length:0},additionContent:{push(value){this.value+=value,this.length++},value:"",length:0},deletionInfo:[],additionInfo:[],deletionDecorations:[],additionDecorations:[],deletionSegments:[],additionSegments:[]}}function renderTwoFiles({lazyLineAST,deletionFile,additionFile,deletionInfo,additionInfo,highlighter:highlighter2,deletionDecorations,additionDecorations,languageOverride,options:{theme,useTokenTransformer,tokenizeMaxLineLength}}){const renderFile=(file,lineInfo,decorations)=>file.contents===""?[]:renderTokenLines(highlighter2.codeToTokens(cleanLastNewline(file.contents),getTokenOptions(languageOverride??getFiletypeFromFileName(file.name),theme,tokenizeMaxLineLength)).tokens,{state:{lineInfo},useTokenTransformer,decorations,lazyLineAST,cacheHtmlStyles:highlighter2.name==="highlights"});return{deletionLines:renderFile(deletionFile,deletionInfo,deletionDecorations),additionLines:renderFile(additionFile,additionInfo,additionDecorations)}}function isDiffPlainText(diff){const computedLang=diff.lang??getFiletypeFromFileName(diff.name),computedPreviousLang=diff.lang??(diff.prevName!=null?getFiletypeFromFileName(diff.prevName):"text");return computedLang==="text"&&computedPreviousLang==="text"}function getResolvedLanguages(languages){const resolvedLanguages=[];for(const language of languages){const resolvedLanguage=ResolvedLanguages.get(language);if(resolvedLanguage==null)throw new Error(`getResolvedLanguages: ${language} is not resolved. Please resolve languages before calling getResolvedLanguages`);resolvedLanguages.push(resolvedLanguage)}return resolvedLanguages}async function resolveLanguage(lang){if(typeof __DIFFS_WORKER__<"u"?__DIFFS_WORKER__:isWorkerContext())throw new Error(`resolveLanguage("${lang}") cannot be called from a worker context. Languages must be pre-resolved on the main thread and passed to the worker via the resolvedLanguages parameter.`);const pending=ResolvingLanguages.get(lang);if(pending!=null)return pending;const resolver=(async()=>{let loader=RegisteredCustomLanguages.get(lang);if(loader==null){const{bundledLanguages}=await __vitePreload(async()=>{const{bundledLanguages:bundledLanguages2}=await import("./langs-CXhlGiW6.js");return{bundledLanguages:bundledLanguages2}},__vite__mapDeps([17,1,2,3,4,5,6,7]),import.meta.url);Object.prototype.hasOwnProperty.call(bundledLanguages,lang)&&(loader=bundledLanguages[lang])}if(loader==null)throw new Error(`resolveLanguage: "${lang}" not found in bundled or custom languages`);const{default:data}=await loader(),resolvedLang={name:lang,data};return ResolvedLanguages.has(lang)||ResolvedLanguages.set(lang,resolvedLang),resolvedLang})();ResolvingLanguages.set(lang,resolver);try{return await resolver}finally{ResolvingLanguages.get(lang)===resolver&&ResolvingLanguages.delete(lang)}}function getResolvedOrResolveLanguage(language){return ResolvedLanguages.get(language)??resolveLanguage(language)}function hasResolvedLanguages(languages){for(const language of Array.isArray(languages)?languages:[languages])if(!ResolvedLanguages.has(language))return!1;return!0}async function resolveLanguages(languages){const resolvedLanguages=[],languagesToResolve=[];for(const language of languages){if(language==="text"||language==="ansi")continue;const maybeResolvedLanguage=getResolvedOrResolveLanguage(language)??resolveLanguage(language);"then"in maybeResolvedLanguage?languagesToResolve.push(maybeResolvedLanguage):resolvedLanguages.push(maybeResolvedLanguage)}return languagesToResolve.length>0&&await Promise.all(languagesToResolve).then(_resolvedLanguages=>{for(const resolvedLanguage of _resolvedLanguages){if(resolvedLanguage==null)throw new Error("resolvedLanguages: unable to resolve language");resolvedLanguages.push(resolvedLanguage)}}),resolvedLanguages}function getResolvedThemes(themeNames,backend=resolveHighlighterType()){return createDiffsThemeResolver(backend).getResolvedThemes(themeNames)}function hasResolvedThemes(themeNames,backend=resolveHighlighterType()){return createDiffsThemeResolver(backend).hasResolvedThemes(themeNames)}function resolveThemes(themes,backend=resolveHighlighterType()){return createDiffsThemeResolver(backend).resolveThemes(themes)}var lru$1={exports:{}},lru=lru$1.exports,hasRequiredLru;function requireLru(){return hasRequiredLru||(hasRequiredLru=1,(function(module,exports){(function(g,c){c(exports)})(lru,function(g){const c=Symbol("newer"),e=Symbol("older");class n{constructor(a,b){typeof a!="number"&&(b=a,a=0),this.size=0,this.limit=a,this.oldest=this.newest=void 0,this._keymap=new Map,b&&(this.assign(b),a<1&&(this.limit=this.size))}_markEntryAsUsed(a){a!==this.newest&&(a[c]&&(a===this.oldest&&(this.oldest=a[c]),a[c][e]=a[e]),a[e]&&(a[e][c]=a[c]),a[c]=void 0,a[e]=this.newest,this.newest&&(this.newest[c]=a),this.newest=a)}assign(a){let b,d=this.limit||Number.MAX_VALUE;this._keymap.clear();let m=a[Symbol.iterator]();for(let h=m.next();!h.done;h=m.next()){let f=new l(h.value[0],h.value[1]);if(this._keymap.set(f.key,f),b?(b[c]=f,f[e]=b):this.oldest=f,b=f,d--==0)throw new Error("overflow")}this.newest=b,this.size=this._keymap.size}get(a){var b=this._keymap.get(a);return b?(this._markEntryAsUsed(b),b.value):void 0}set(a,b){var d=this._keymap.get(a);return d?(d.value=b,this._markEntryAsUsed(d),this):(this._keymap.set(a,d=new l(a,b)),this.newest?(this.newest[c]=d,d[e]=this.newest):this.oldest=d,this.newest=d,++this.size,this.size>this.limit&&this.shift(),this)}shift(){var a=this.oldest;if(a)return this.oldest[c]?(this.oldest=this.oldest[c],this.oldest[e]=void 0):(this.oldest=void 0,this.newest=void 0),a[c]=a[e]=void 0,this._keymap.delete(a.key),--this.size,[a.key,a.value]}find(a){let b=this._keymap.get(a);return b?b.value:void 0}has(a){return this._keymap.has(a)}delete(a){var b=this._keymap.get(a);return b?(this._keymap.delete(b.key),b[c]&&b[e]?(b[e][c]=b[c],b[c][e]=b[e]):b[c]?(b[c][e]=void 0,this.oldest=b[c]):b[e]?(b[e][c]=void 0,this.newest=b[e]):this.oldest=this.newest=void 0,this.size--,b.value):void 0}clear(){this.oldest=this.newest=void 0,this.size=0,this._keymap.clear()}keys(){return new j(this.oldest)}values(){return new k(this.oldest)}entries(){return this}[Symbol.iterator](){return new i(this.oldest)}forEach(a,b){typeof b!="object"&&(b=this);let d=this.oldest;for(;d;)a.call(b,d.value,d.key,this),d=d[c]}toJSON(){for(var a=new Array(this.size),b=0,d=this.oldest;d;)a[b++]={key:d.key,value:d.value},d=d[c];return a}toString(){for(var a="",b=this.oldest;b;)a+=String(b.key)+":"+b.value,b=b[c],b&&(a+=" < ");return a}}g.LRUMap=n;function l(a,b){this.key=a,this.value=b,this[c]=void 0,this[e]=void 0}function i(a){this.entry=a}i.prototype[Symbol.iterator]=function(){return this},i.prototype.next=function(){let a=this.entry;return a?(this.entry=a[c],{done:!1,value:[a.key,a.value]}):{done:!0,value:void 0}};function j(a){this.entry=a}j.prototype[Symbol.iterator]=function(){return this},j.prototype.next=function(){let a=this.entry;return a?(this.entry=a[c],{done:!1,value:a.key}):{done:!0,value:void 0}};function k(a){this.entry=a}k.prototype[Symbol.iterator]=function(){return this},k.prototype.next=function(){let a=this.entry;return a?(this.entry=a[c],{done:!1,value:a.value}):{done:!0,value:void 0}}})})(lru$1,lru$1.exports)),lru$1.exports}var lruExports=requireLru();const LRUMapPkg=getDefaultExportFromCjs(lruExports),HOLE=0,TEXT=1,ELEMENT=2,STRING=4,INTEGER=5,EXTRA=6,PRIMITIVES=[void 0,null,!0,!1];function decodeHastLines(encoded){if(Array.isArray(encoded))return encoded;const{ops,offsets,strings,text,extras}=encoded,lines=new Array(offsets.length/2);let position=0,textPosition=0;function decodeNodes(count){const nodes=new Array(count);for(let index=0;index<count;index++){const kind=ops[position++];if(kind!==HOLE)if(kind===TEXT){const end=textPosition+ops[position++];nodes[index]={type:"text",value:text.slice(textPosition,end)},textPosition=end}else if(kind===ELEMENT){const tagName=strings[ops[position++]],properties={};for(let remaining=ops[position++];remaining>0;remaining--){const key=strings[ops[position++]],type=ops[position++],value=type===STRING?strings[ops[position++]]:type===INTEGER?ops[position++]:type===EXTRA?extras[ops[position++]]:PRIMITIVES[type];key==="__proto__"?Object.defineProperty(properties,key,{value,enumerable:!0,configurable:!0,writable:!0}):properties[key]=value}nodes[index]={type:"element",tagName,properties,children:decodeNodes(ops[position++])}}else nodes[index]=extras[ops[position++]]}return nodes}for(let index=0;index<lines.length;index++)ops[offsets[index*2]]!==HOLE&&setDeferredArrayItem(lines,index,()=>(position=offsets[index*2],textPosition=offsets[index*2+1],decodeNodes(1)[0]),{retain:!1});return lines}const IGNORE_RESPONSE=Symbol("IGNORE_RESPONSE"),DEFAULT_WORKER_INITIALIZATION_TIMEOUT=1e4;var WorkerPoolManager=class{options;preferredHighlighter;renderOptions;renderOptionsRequestVersion=0;renderOptionsVersion=0;initialized=!1;workers=[];queuedTasks=[];queuedTaskByInstance=new Map;taskByHighlightKey=new Map;activeTaskById=new Map;activeRequestByInstance=new Map;nextRequestId=0;themeSubscribers=new Set;workersFailed=!1;terminated=!1;statSubscribers=new Set;fileCache;diffCache;_queuedBroadcast;lifecycleGeneration=0;constructor(options,{langs,theme=DEFAULT_THEMES,useTokenTransformer=!1,lineDiffType="word-alt",maxLineDiffLength=1e3,tokenizeMaxLineLength=1e3,preferredHighlighter}){this.options=options,this.preferredHighlighter=resolveHighlighterType(preferredHighlighter),this.renderOptions={theme,useTokenTransformer,lineDiffType,maxLineDiffLength,tokenizeMaxLineLength},this.fileCache=new LRUMapPkg.LRUMap(options.totalASTLRUCacheSize??100),this.diffCache=new LRUMapPkg.LRUMap(options.totalASTLRUCacheSize??100),this.queueInitialization(langs)}isWorkingPool(){return!this.workersFailed&&!this.terminated}shouldHighlightOnMainThread(fileOrDiff){const{mainThreadMaxCharacters=-1}=this.options;return("contents"in fileOrDiff?fileOrDiff.contents.length:fileOrDiff.deletionCharacterCount+fileOrDiff.additionCharacterCount)<=mainThreadMaxCharacters}getFileResultCache(file){return file.cacheKey!=null?this.fileCache.get(file.cacheKey):void 0}getDiffResultCache(diff){return diff.cacheKey!=null?this.diffCache.get(diff.cacheKey):void 0}setFileResultCache(cacheKey,{result,options}){return cacheKey==null||!areFileRenderOptionsEqual(options,this.getFileRenderOptions())?!1:(this.fileCache.set(cacheKey,{result,options}),this.queueBroadcastStateChanges(),!0)}setDiffResultCache(cacheKey,{result,options}){return cacheKey==null||!areDiffRenderOptionsEqual(options,this.getDiffRenderOptions())?!1:(this.diffCache.set(cacheKey,{result,options}),this.queueBroadcastStateChanges(),!0)}inspectCaches(){const{fileCache,diffCache}=this;return{fileCache,diffCache}}evictFileFromCache(cacheKey){try{return this.fileCache.delete(cacheKey)!==void 0}finally{this.queueBroadcastStateChanges()}}evictDiffFromCache(cacheKey){try{return this.diffCache.delete(cacheKey)!==void 0}finally{this.queueBroadcastStateChanges()}}async setRenderOptions({theme=this.renderOptions.theme??DEFAULT_THEMES,useTokenTransformer=this.renderOptions.useTokenTransformer??!1,lineDiffType=this.renderOptions.lineDiffType??"word-alt",maxLineDiffLength=this.renderOptions.maxLineDiffLength??1e3,tokenizeMaxLineLength=this.renderOptions.tokenizeMaxLineLength??1e3}){const{lifecycleGeneration}=this,renderOptionsRequestVersion=++this.renderOptionsRequestVersion,isCurrentRequest=()=>this.isCurrentLifecycle(lifecycleGeneration)&&this.renderOptionsRequestVersion===renderOptionsRequestVersion;try{const newRenderOptions={theme,useTokenTransformer,lineDiffType,maxLineDiffLength,tokenizeMaxLineLength};if(!this.isInitialized())try{await this.initialize()}catch(error){if(!this.workersFailed)throw error}if(!isCurrentRequest()||areDiffRenderOptionsEqual(newRenderOptions,this.renderOptions))return;const themeNames=getThemes(theme);let resolvedThemes=[];if(areThemesEqual(newRenderOptions.theme,this.renderOptions.theme)||(resolvedThemes=hasResolvedThemes(themeNames,this.preferredHighlighter)?getResolvedThemes(themeNames,this.preferredHighlighter):await resolveThemes(themeNames,this.preferredHighlighter)),!isCurrentRequest()||getHighlighterIfLoaded({theme})==null&&(await this.loadSharedHighlighter(themeNames,["text"]),!isCurrentRequest()))return;const workerSetup=this.setRenderOptionsOnWorkers(newRenderOptions,resolvedThemes);this.renderOptions=newRenderOptions,this.renderOptionsVersion++,this.diffCache.clear(),this.fileCache.clear(),this.invalidateRenderTasks();for(const instance of this.themeSubscribers)instance.onThemeChange();await workerSetup}catch(error){if(error instanceof WorkerPoolTerminatedError||!isCurrentRequest())return;throw error}}getPreferredHighlighter(){return this.preferredHighlighter}getFileRenderOptions(){const{tokenizeMaxLineLength,theme,useTokenTransformer}=this.renderOptions;return{theme,useTokenTransformer,tokenizeMaxLineLength}}getDiffRenderOptions(){return{...this.renderOptions}}async setRenderOptionsOnWorkers(renderOptions,resolvedThemes){if(this.workersFailed)return;this.isInitialized()||await this.initialize();const taskPromises=[];for(const managedWorker of this.workers){if(!managedWorker.initialized)throw console.log({managedWorker}),new Error("setRenderOptionsOnWorkers: Somehow we have an uninitialized worker");taskPromises.push(new Promise((resolve,reject)=>{const id=this.generateRequestId(),task={type:"set-render-options",id,request:{type:"set-render-options",id,renderOptions,resolvedThemes},resolve,reject,requestStart:Date.now()};this.activeTaskById.set(id,task),managedWorker.pendingSetupRequestId=id,managedWorker.worker.postMessage(task.request)}))}await Promise.all(taskPromises)}subscribeToThemeChanges(instance){return this.themeSubscribers.add(instance),this.queueBroadcastStateChanges(),()=>{this.unsubscribeToThemeChanges(instance),this.queueBroadcastStateChanges()}}unsubscribeToThemeChanges(instance){this.themeSubscribers.delete(instance),this.queueBroadcastStateChanges()}subscribeToStatChanges(callback){return this.statSubscribers.add(callback),callback(this.getStats()),()=>{this.statSubscribers.delete(callback)}}queueBroadcastStateChanges(){this._queuedBroadcast==null&&(this._queuedBroadcast=requestAnimationFrame(this._broadcastStateChanges))}_broadcastStateChanges=()=>{this._queuedBroadcast!=null&&(cancelAnimationFrame(this._queuedBroadcast),this._queuedBroadcast=void 0);const stats=this.getStats();for(const callback of this.statSubscribers)callback(stats)};cleanUpTasks(instance){this.detachInstanceFromQueuedTasks(instance);const requestId=this.activeRequestByInstance.get(instance);if(requestId!=null){const task=this.activeTaskById.get(requestId);isRenderTask(task)?(this.detachInstanceFromRenderTask(task,instance),!task.primeCache&&task.instances.size===0&&this.removeActiveTask(task)):this.activeTaskById.delete(requestId)}this.activeRequestByInstance.delete(instance),this.queueBroadcastStateChanges()}isInitialized(){return this.initialized===!0}async initialize(languages=[]){if(this.initialized===!0){getHighlighterIfLoaded({theme:this.renderOptions.theme})==null&&await this.loadSharedHighlighter(getThemes(this.renderOptions.theme),["text",...languages]);return}else if(this.initialized===!1){this.terminated=!1;const{lifecycleGeneration}=this,initialization=new Promise((resolve,reject)=>{(async()=>{try{const themes=getThemes(this.renderOptions.theme),resolvedThemes=hasResolvedThemes(themes,this.preferredHighlighter)?getResolvedThemes(themes,this.preferredHighlighter):await resolveThemes(themes,this.preferredHighlighter);if(!this.isCurrentLifecycle(lifecycleGeneration)){resolve();return}let resolvedLanguages=[];if(this.preferredHighlighter!=="highlights"&&(resolvedLanguages=hasResolvedLanguages(languages)?getResolvedLanguages(languages):await resolveLanguages(languages)),!this.isCurrentLifecycle(lifecycleGeneration)){resolve();return}if(await Promise.all([this.loadSharedHighlighter(themes,["text",...languages]),this.initializeWorkers(resolvedThemes,resolvedLanguages)]),!this.isCurrentLifecycle(lifecycleGeneration)){this.terminateWorkers(),resolve();return}this.initialized=!0,this.drainQueue(),this.queueBroadcastStateChanges(),resolve()}catch(e){if(e instanceof WorkerPoolTerminatedError||!this.isCurrentLifecycle(lifecycleGeneration)){resolve();return}this.initialized=!1,this.workersFailed=!0,this.cancelActiveWorkerTasks(),this.terminateWorkers(),this.activeTaskById.clear();for(const task of this.queuedTasks)this.rejectRenderTaskCallbacks(task,normalizeWorkerError(e));this.queueBroadcastStateChanges(),reject(e)}})()});return this.initialized=initialization,this.queueBroadcastStateChanges(),initialization}else return this.initialized}async loadSharedHighlighter(themes,langs){try{await getSharedHighlighter({themes,langs,preferredHighlighter:this.preferredHighlighter})}catch(error){if(!(error instanceof HighlighterDisposedError))throw error}}async initializeWorkers(resolvedThemes,resolvedLanguages){this.workersFailed=!1;const initPromises=[],customExtensionVersion=getCustomExtensionsVersion(),customExtensionMap=customExtensionVersion>0?getCustomExtensionsMap():void 0;this.workers.length>0&&this.terminateWorkers();for(let i=0;i<(this.options.poolSize??8);i++){const worker=this.options.workerFactory(),managedWorker={worker,requestId:void 0,pendingSetupRequestId:void 0,initialized:!1,langs:new Set(["text",...resolvedLanguages.map(({name})=>name)]),customExtensionsVersion:0};worker.addEventListener("message",event=>{this.handleWorkerMessage(managedWorker,event.data)}),worker.addEventListener("error",error=>this.handleWorkerError(managedWorker,error)),this.workers.push(managedWorker),initPromises.push(new Promise((resolve,reject)=>{const id=this.generateRequestId(),task={type:"initialize",id,request:{type:"initialize",resultFormat:"hast-ops-v1",id,renderOptions:this.renderOptions,preferredHighlighter:this.preferredHighlighter,resolvedThemes,resolvedLanguages,customExtensionsVersion:customExtensionMap!=null?customExtensionVersion:void 0,customExtensionMap},resolve(){managedWorker.initialized=!0,resolve()},reject,requestStart:Date.now()};managedWorker.pendingSetupRequestId=id,this.activeTaskById.set(id,task),this.executeTask(managedWorker,task)}))}const timeoutMs=this.options.workerInitializationTimeout??DEFAULT_WORKER_INITIALIZATION_TIMEOUT;let timeoutId;try{await Promise.race([Promise.all(initPromises),new Promise((_,reject)=>{timeoutId=setTimeout(()=>{reject(new Error(`WorkerPoolManager: worker initialization timed out after ${timeoutMs}ms`))},timeoutMs)})])}finally{timeoutId!=null&&clearTimeout(timeoutId)}}handleWorkerError(managedWorker,event){const{onWorkerError}=this.options;if(onWorkerError!=null)try{onWorkerError(event,managedWorker.worker)}catch(hookError){console.error("WorkerPoolManager: onWorkerError threw:",hookError)}else console.error("Worker error:",event,managedWorker);const{pendingSetupRequestId}=managedWorker;if(pendingSetupRequestId==null)return;const task=this.activeTaskById.get(pendingSetupRequestId);if(task?.type!=="initialize")return;const error=errorFromWorkerErrorEvent(event);onWorkerError!=null&&markWorkerErrorReported(error),task.reject(error),this.cleanWorkerAndTask(managedWorker,task)}drainQueue=()=>{if(this._queuedDrain=void 0,!(this.initialized!==!0||this.queuedTasks.length===0)){for(let i=0;i<this.queuedTasks.length;){const task=this.queuedTasks[i];if(this.hasActiveRequest(task)){i++;continue}const langs=getLangsFromRequest(task.request),availableWorker=this.getAvailableWorker(langs);if(availableWorker==null)break;this.queuedTasks.splice(i,1),this.assignWorkerToTask(task,availableWorker),this.resolveLanguagesAndExecuteTask(availableWorker,task,langs)}this.queueBroadcastStateChanges()}};highlightFileAST(instance,file){const cachedResult=this.getFileResultCache(file);isFilePlainText(file)||cachedResult!=null&&areFileRenderOptionsEqual(cachedResult.options,this.getFileRenderOptions())||this.hasMatchingFileInstanceTask(instance,file)||this.submitTask(instance,{type:"file",file})}primeFileHighlightCache(file){if(!this.isWorkingPool())return Promise.reject(new Error("WorkerPoolManager.primeFileHighlightCache: worker pool is not working"));if(!this.shouldPrimeFileHighlightCache(file))return Promise.resolve();if(this.shouldHighlightOnMainThread(file)){const options=this.getFileRenderOptions();return this.primeHighlightCacheOnMainThread(getLangsFromRequest({type:"file",file}),options.theme,highlighter2=>this.setFileResultCache(file.cacheKey,{result:renderFileWithHighlighter(file,highlighter2,options),options}))}const task=this.getOrCreateFileHighlightCacheTask(file);return task!=null?this.createRenderTaskCallbacks(task):Promise.resolve()}shouldPrimeFileHighlightCache(file){if(file.cacheKey==null)return console.warn(`WorkerPoolManager.primeFileHighlightCache: priming highlight cache requires file.cacheKey; skipping "${file.name}".`),!1;const cachedResult=this.getFileResultCache(file);return!isFilePlainText(file)&&(cachedResult==null||!areFileRenderOptionsEqual(cachedResult.options,this.getFileRenderOptions()))}getOrCreateFileHighlightCacheTask(file){const highlightKey=this.getFileHighlightKey(file);if(highlightKey==null)return;const existingTask=this.getTaskByHighlightKey(highlightKey);if(existingTask!=null){if(existingTask.type!=="file")throw new Error("WorkerPoolManager.getOrCreateFileHighlightCacheTask: Invalid task type");return existingTask.primeCache=!0,existingTask}else{const task=this.submitCacheTask({type:"file",file},highlightKey);if(task.type!=="file")throw new Error("WorkerPoolManager.getOrCreateFileHighlightCacheTask: Invalid task created");return task}}getPlainFileAST(file,startingLine,totalLines,lines){const highlighter2=getHighlighterIfLoaded({theme:this.renderOptions.theme});if(highlighter2==null){this.queueInitialization();return}return renderFileWithHighlighter(file,highlighter2,this.renderOptions,{forcePlainText:!0,startingLine,totalLines,lines})}highlightDiffAST(instance,diff){const cachedResult=this.getDiffResultCache(diff);isDiffPlainText(diff)||cachedResult!=null&&areDiffRenderOptionsEqual(cachedResult.options,this.getDiffRenderOptions())||this.hasMatchingDiffInstanceTask(instance,diff)||this.submitTask(instance,{type:"diff",diff})}primeDiffHighlightCache(diff){if(!this.isWorkingPool())return Promise.reject(new Error("WorkerPoolManager.primeDiffHighlightCache: worker pool is not working"));if(!this.shouldPrimeDiffHighlightCache(diff))return Promise.resolve();if(this.shouldHighlightOnMainThread(diff)){const options=this.getDiffRenderOptions();return this.primeHighlightCacheOnMainThread(getLangsFromRequest({type:"diff",diff}),options.theme,highlighter2=>this.setDiffResultCache(diff.cacheKey,{result:renderDiffWithHighlighter(diff,highlighter2,options),options}))}const task=this.getOrCreateDiffHighlightCacheTask(diff);return task!=null?this.createRenderTaskCallbacks(task):Promise.resolve()}shouldPrimeDiffHighlightCache(diff){if(diff.cacheKey==null)return console.warn(`WorkerPoolManager.primeDiffHighlightCache: priming highlight cache requires diff.cacheKey; skipping "${diff.prevName??diff.name}" -> "${diff.name}".`),!1;const cachedResult=this.getDiffResultCache(diff);return!isDiffPlainText(diff)&&(cachedResult==null||!areDiffRenderOptionsEqual(cachedResult.options,this.getDiffRenderOptions()))}primeHighlightCacheOnMainThread(langs,theme,highlightAndCacheResult){function highlightAndCacheIfLoaded(){const highlighter2=getHighlighterIfLoaded({theme,langs});return highlighter2!=null&&highlightAndCacheResult(highlighter2)}if(highlightAndCacheIfLoaded())return Promise.resolve();const{lifecycleGeneration}=this;return this.loadSharedHighlighter(getThemes(theme),["text",...langs]).then(()=>{if(!this.isCurrentLifecycle(lifecycleGeneration))throw new WorkerPoolTerminatedError;if(!highlightAndCacheIfLoaded())throw new WorkerPoolTaskCanceledError})}getOrCreateDiffHighlightCacheTask(diff){const highlightKey=this.getDiffHighlightKey(diff);if(highlightKey==null)return;const existingTask=this.getTaskByHighlightKey(highlightKey);if(existingTask!=null){if(existingTask.type!=="diff")throw new Error("WorkerPoolManager.getOrCreateDiffHighlightCacheTask: Invalid task type");return existingTask.primeCache=!0,existingTask}else{const task=this.submitCacheTask({type:"diff",diff},highlightKey);if(task.type!=="diff")throw new Error("WorkerPoolManager.getOrCreateDiffHighlightCacheTask: Invalid task created");return task}}getPlainDiffAST(diff,startingLine,totalLines,expandedHunks,collapsedContextThreshold){const highlighter2=getHighlighterIfLoaded({theme:this.renderOptions.theme});if(highlighter2==null){this.queueInitialization();return}return renderDiffWithHighlighter(diff,highlighter2,this.renderOptions,{forcePlainText:!0,startingLine,totalLines,expandedHunks,collapsedContextThreshold})}terminate(){this.lifecycleGeneration++,this.cancelActiveWorkerTasks(),this.terminateWorkers();const error=new WorkerPoolTerminatedError;for(const task of this.queuedTasks)this.rejectRenderTaskCallbacks(task,error);this.fileCache.clear(),this.diffCache.clear(),this.activeRequestByInstance.clear(),this.queuedTasks.length=0,this.queuedTaskByInstance.clear(),this.taskByHighlightKey.clear(),this.activeTaskById.clear(),this.initialized=!1,this.workersFailed=!1,this.terminated=!0,this.queueBroadcastStateChanges()}isCurrentLifecycle(lifecycleGeneration){return this.lifecycleGeneration===lifecycleGeneration}queueInitialization(languages){this.initialize(languages).catch(error=>{isHandledWorkerPoolError(error)||console.error(error)})}cancelActiveWorkerTasks(){const error=new WorkerPoolTerminatedError;for(const task of this.activeTaskById.values())"reject"in task?task.reject(error):isRenderTask(task)&&this.rejectRenderTaskCallbacks(task,error)}terminateWorkers(){for(const managedWorker of this.workers)managedWorker.worker.terminate();this.workers.length=0}getStats(){return{managerState:this.initialized===!1?"waiting":this.initialized!==!0?"initializing":"initialized",totalWorkers:this.workers.length,workersFailed:this.workersFailed,busyWorkers:this.workers.filter(w=>w.requestId!=null||w.pendingSetupRequestId!=null).length,queuedTasks:this.queuedTasks.length,activeTasks:this.activeTaskById.size,themeSubscribers:this.themeSubscribers.size,fileCacheSize:this.fileCache.size,diffCacheSize:this.diffCache.size}}submitTask(instance,request){this.initialized===!1&&this.queueInitialization();const highlightKey=this.getHighlightKeyForRequest(request),existingTask=highlightKey!=null?this.getTaskByHighlightKey(highlightKey):void 0;if(existingTask!=null){this.detachInstanceFromQueuedTasks(instance,existingTask),this.addInstanceToTask(existingTask,instance),this.queueBroadcastStateChanges();return}this.detachInstanceFromQueuedTasks(instance);const id=this.generateRequestId(),requestStart=Date.now(),{renderOptionsVersion}=this,task=(()=>{switch(request.type){case"file":return{type:"file",id,request:{...request,id},instances:new Set([instance]),primeCache:!1,highlightKey,callbacks:new Set,renderOptionsVersion,requestStart};case"diff":return{type:"diff",id,request:{...request,id},instances:new Set([instance]),primeCache:!1,highlightKey,callbacks:new Set,renderOptionsVersion,requestStart}}})();this.enqueueRenderTask(task,instance)}submitCacheTask(request,highlightKey){this.initialized===!1&&this.queueInitialization();const id=this.generateRequestId(),requestStart=Date.now(),{renderOptionsVersion}=this,task=(()=>{switch(request.type){case"file":return{type:"file",id,request:{...request,id},instances:new Set,primeCache:!0,highlightKey,callbacks:new Set,renderOptionsVersion,requestStart};case"diff":return{type:"diff",id,request:{...request,id},instances:new Set,primeCache:!0,highlightKey,callbacks:new Set,renderOptionsVersion,requestStart}}})();return this.enqueueRenderTask(task),task}enqueueRenderTask(task,instance){this.queuedTasks.push(task),instance!=null&&this.queuedTaskByInstance.set(instance,task),task.highlightKey!=null&&this.taskByHighlightKey.set(task.highlightKey,task),this.queueDrain()}async resolveLanguagesAndExecuteTask(availableWorker,task,langs){try{const highlighter2=getHighlighterIfLoaded(),mainThreadLangs=langs.filter(lang=>highlighter2==null||!areLanguagesAttached(lang,highlighter2));mainThreadLangs.length>0&&this.loadSharedHighlighter(getThemes(this.renderOptions.theme),["text",...mainThreadLangs]).catch(error=>{console.error(error)});const workerMissingLangs=this.preferredHighlighter==="highlights"?[]:langs.filter(lang=>!availableWorker.langs.has(lang));if(workerMissingLangs.length>0&&(hasResolvedLanguages(workerMissingLangs)?task.request.resolvedLanguages=getResolvedLanguages(workerMissingLangs):task.request.resolvedLanguages=await resolveLanguages(workerMissingLangs)),!this.activeTaskById.has(task.id)){availableWorker.requestId===task.id&&(this.cleanWorkerAndTask(availableWorker,task),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain());return}this.executeTask(availableWorker,task)}catch(error){this.rejectRenderTaskCallbacks(task,normalizeWorkerError(error)),this.cleanWorkerAndTask(availableWorker,task),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain()}}handleWorkerMessage(managedWorker,response){const task=this.activeTaskById.get(response.id);try{if(task==null)throw IGNORE_RESPONSE;if(response.type==="error"){const error=new Error(response.error);if(response.stack&&(error.stack=response.stack),"reject"in task)task.reject(error);else if(isRenderTask(task))this.notifyHighlightError(task,error),this.rejectRenderTaskCallbacks(task,error);else throw new Error("handleWorkerMessage: unknown task type");throw error}else{if(isRenderTask(task))for(const{name}of task.request.resolvedLanguages??[])managedWorker.langs.add(name);switch(response.requestType){case"initialize":if(task.type!=="initialize")throw new Error("handleWorkerMessage: task/response dont match");this.syncCustomExtensionVersion(managedWorker,task.request),task.resolve();break;case"set-render-options":if(task.type!=="set-render-options")throw new Error("handleWorkerMessage: task/response dont match");task.resolve();break;case"file":{if(task.type!=="file")throw new Error("handleWorkerMessage: task/response dont match");const{options}=response;if(!this.isCurrentRenderTask(task)||!areFileRenderOptionsEqual(options,this.getFileRenderOptions()))throw IGNORE_RESPONSE;const{request}=task,result={...response.result,code:decodeHastLines(response.result.code)};this.syncCustomExtensionVersion(managedWorker,request),task.cacheKeyAtDispatch!=null&&this.fileCache.set(task.cacheKeyAtDispatch,{result,options}),this.resolveRenderTaskCallbacks(task),this.notifyFileInstances(task,result,options);break}case"diff":{if(task.type!=="diff")throw new Error("handleWorkerMessage: task/response dont match");const{options}=response;if(!this.isCurrentRenderTask(task)||!areDiffRenderOptionsEqual(options,this.getDiffRenderOptions()))throw IGNORE_RESPONSE;const{request}=task,result={...response.result,code:{deletionLines:decodeHastLines(response.result.code.deletionLines),additionLines:decodeHastLines(response.result.code.additionLines)}};this.syncCustomExtensionVersion(managedWorker,request),task.cacheKeyAtDispatch!=null&&this.diffCache.set(task.cacheKeyAtDispatch,{result,options}),this.resolveRenderTaskCallbacks(task),this.notifyDiffInstances(task,result,options);break}}}}catch(error){error!==IGNORE_RESPONSE&&console.error(error,task,response)}this.cleanWorkerAndTask(managedWorker,task,response.id),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain()}_queuedDrain;queueDrain(){this._queuedDrain==null&&(this._queuedDrain=Promise.resolve().then(this.drainQueue),this.queueBroadcastStateChanges())}assignWorkerToTask(task,managedWorker){managedWorker.requestId=task.id,isRenderTask(task)&&(this.clearQueuedInstanceRequests(task),this.trackInstanceRequests(task)),this.activeTaskById.set(task.id,task)}cleanWorkerAndTask(managedWorker,task,requestId=task?.id){managedWorker.requestId===requestId&&(managedWorker.requestId=void 0),managedWorker.pendingSetupRequestId===requestId&&(managedWorker.pendingSetupRequestId=void 0),task!=null&&(isRenderTask(task)&&(this.rejectRenderTaskCallbacks(task,new WorkerPoolTaskCanceledError),this.clearInstanceRequests(task),this.clearHighlightKey(task)),this.activeTaskById.delete(task.id))}executeTask(managedWorker,task){shouldSyncCustomExtensions(task.request)&&this.maybeAttachCustomExtensions(managedWorker,task.request),this.activeTaskById.has(task.id)||this.assignWorkerToTask(task,managedWorker);try{task.type==="file"?task.cacheKeyAtDispatch=task.request.file.cacheKey:task.type==="diff"&&(task.cacheKeyAtDispatch=task.request.diff.cacheKey),managedWorker.worker.postMessage(task.request)}catch(error){console.error("Failed to post message to worker:",error),isRenderTask(task)?(this.notifyHighlightError(task,error),this.rejectRenderTaskCallbacks(task,normalizeWorkerError(error))):"reject"in task&&task.reject(error),this.cleanWorkerAndTask(managedWorker,task),this.queuedTasks.length>0&&this.queueDrain()}this.queueBroadcastStateChanges()}maybeAttachCustomExtensions(managedWorker,request){if(request.customExtensionsVersion!=null)return;const version=getCustomExtensionsVersion();managedWorker.customExtensionsVersion>=version||(request.customExtensionsVersion=version,request.customExtensionMap=getCustomExtensionsMap())}syncCustomExtensionVersion(managedWorker,request){request.customExtensionsVersion!=null&&(managedWorker.customExtensionsVersion=request.customExtensionsVersion)}getAvailableWorker(langs){let worker;for(const managedWorker of this.workers){if(managedWorker.requestId!=null||managedWorker.pendingSetupRequestId!=null||!managedWorker.initialized)continue;if(worker=managedWorker,langs.length===0)break;let hasEveryLang=!0;for(const lang of langs)if(!managedWorker.langs.has(lang)){hasEveryLang=!1;break}if(hasEveryLang)break}return worker}getFileHighlightKey(file){if(file.cacheKey!=null)return`file:${file.cacheKey}:${this.renderOptionsVersion}`}getDiffHighlightKey(diff){if(diff.cacheKey!=null)return`diff:${diff.cacheKey}:${this.renderOptionsVersion}`}getHighlightKeyForRequest(request){switch(request.type){case"file":return this.getFileHighlightKey(request.file);case"diff":return this.getDiffHighlightKey(request.diff)}}hasActiveRequest(task){for(const instance of getInstances(task))if(this.activeRequestByInstance.has(instance))return!0;return!1}addInstanceToTask(task,instance){task.type,task.instances.add(instance),this.activeTaskById.has(task.id)?this.activeRequestByInstance.set(instance,task.id):this.queuedTaskByInstance.set(instance,task)}detachInstanceFromQueuedTasks(instance,exceptTask){const task=this.queuedTaskByInstance.get(instance);task==null||task===exceptTask||(this.queuedTaskByInstance.delete(instance),this.detachInstanceFromRenderTask(task,instance),!task.primeCache&&task.instances.size===0&&this.removeQueuedTask(task))}detachInstanceFromRenderTask(task,instance){task.type,task.instances.delete(instance)}removeQueuedTask(task){const index=this.queuedTasks.indexOf(task);index!==-1&&this.queuedTasks.splice(index,1),this.rejectRenderTaskCallbacks(task,new WorkerPoolTaskCanceledError),this.clearQueuedInstanceRequests(task),this.clearHighlightKey(task)}removeActiveTask(task){this.rejectRenderTaskCallbacks(task,new WorkerPoolTaskCanceledError),this.clearInstanceRequests(task),this.clearHighlightKey(task),this.activeTaskById.delete(task.id)}createRenderTaskCallbacks(task){return new Promise((resolve,reject)=>{task.callbacks.add({resolve,reject})})}resolveRenderTaskCallbacks(task){for(const callbacks of task.callbacks)callbacks.resolve();task.callbacks.clear()}rejectRenderTaskCallbacks(task,error){for(const callbacks of task.callbacks)callbacks.reject(error);task.callbacks.clear()}invalidateRenderTasks(){for(let index=this.queuedTasks.length-1;index>=0;index--){const task=this.queuedTasks[index];task.renderOptionsVersion!==this.renderOptionsVersion&&this.removeQueuedTask(task)}for(const task of Array.from(this.activeTaskById.values()))isRenderTask(task)&&task.renderOptionsVersion!==this.renderOptionsVersion&&this.removeActiveTask(task)}clearQueuedInstanceRequests(task){for(const instance of getInstances(task))this.queuedTaskByInstance.get(instance)===task&&this.queuedTaskByInstance.delete(instance)}clearHighlightKey(task){task.highlightKey!=null&&this.taskByHighlightKey.get(task.highlightKey)===task&&this.taskByHighlightKey.delete(task.highlightKey)}trackInstanceRequests(task){for(const instance of getInstances(task))this.activeRequestByInstance.set(instance,task.id)}clearInstanceRequests(task){for(const instance of getInstances(task))this.activeRequestByInstance.get(instance)===task.id&&this.activeRequestByInstance.delete(instance)}notifyFileInstances(task,result,options){for(const instance of task.instances)this.activeRequestByInstance.get(instance)===task.id&&instance.onHighlightSuccess(task.request.file,result,options)}notifyDiffInstances(task,result,options){for(const instance of task.instances)this.activeRequestByInstance.get(instance)===task.id&&instance.onHighlightSuccess(task.request.diff,result,options)}notifyHighlightError(task,error){for(const instance of getInstances(task))this.activeRequestByInstance.get(instance)===task.id&&instance.onHighlightError(error)}hasMatchingFileInstanceTask(instance,file){for(const task of this.iterateRenderTasks())if(task.type==="file"&&this.isCurrentRenderTask(task)&&task.instances.has(instance)&&areFilesEqual(file,task.request.file))return!0;return!1}hasMatchingDiffInstanceTask(instance,diff){for(const task of this.iterateRenderTasks())if(task.type==="diff"&&this.isCurrentRenderTask(task)&&task.instances.has(instance)&&areDiffTargetsEqual(task.request.diff,diff))return!0;return!1}getTaskByHighlightKey(highlightKey){const task=this.taskByHighlightKey.get(highlightKey);return task!=null&&this.isCurrentRenderTask(task)?task:void 0}isCurrentRenderTask(task){return task.renderOptionsVersion===this.renderOptionsVersion}*iterateRenderTasks(){for(const task of this.queuedTasks)yield task;for(const task of this.activeTaskById.values())isRenderTask(task)&&(yield task)}generateRequestId(){return`req_${++this.nextRequestId}`}};function shouldSyncCustomExtensions(request){return request.type==="initialize"||request.type==="file"||request.type==="diff"}function getLangsFromRequest(request){const langs=new Set;switch(request.type){case"file":langs.add(request.file.lang??getFiletypeFromFileName(request.file.name));break;case"diff":langs.add(request.diff.lang??getFiletypeFromFileName(request.diff.name)),langs.add(request.diff.lang??getFiletypeFromFileName(request.diff.prevName??"-"))}return langs.delete("text"),Array.from(langs)}function isRenderTask(task){return task?.type==="file"||task?.type==="diff"}function getInstances(task){return task.instances}function normalizeWorkerError(error){if(error instanceof Error)return error;if(error!=null&&typeof error=="object"){if("error"in error&&error.error instanceof Error)return error.error;if("message"in error&&typeof error.message=="string")return new Error(error.message)}return new Error(String(error))}function errorFromWorkerErrorEvent(event){const cause="error"in event?event.error:void 0,message="message"in event&&typeof event.message=="string"&&event.message!==""?event.message:cause instanceof Error?cause.message:"the worker script failed to load (the error event carries no message)";return new WorkerPoolWorkerError(`WorkerPoolManager: worker failed: ${message}`,cause instanceof Error?{cause}:void 0)}let workerPoolSingleton;function getOrCreateWorkerPoolSingleton({poolOptions,highlighterOptions}){return workerPoolSingleton??=new WorkerPoolManager(poolOptions,highlighterOptions),workerPoolSingleton}function terminateWorkerPoolSingleton(){workerPoolSingleton!=null&&(workerPoolSingleton.terminate(),workerPoolSingleton=void 0)}const WorkerPoolContext=reactExports.createContext(void 0);let instanceCount=0;function WorkerPoolContextProvider({children,poolOptions,highlighterOptions}){const[poolManager]=reactExports.useState(()=>{if(!(typeof window>"u"))return getOrCreateWorkerPoolSingleton({poolOptions,highlighterOptions})});return reactExports.useInsertionEffect(()=>{if(poolManager!=null)return instanceCount++,()=>{instanceCount--}},[poolManager]),reactExports.useEffect(()=>()=>{instanceCount===0&&terminateWorkerPoolSingleton()},[]),jsxRuntimeExports.jsx(WorkerPoolContext.Provider,{value:poolManager,children})}function useWorkerPool(){return reactExports.useContext(WorkerPoolContext)}const DIFFS_HOST_STYLE={"--diffs-bg-context-override":"var(--zg-bg)","--diffs-bg-context-gutter-override":"var(--zg-bg)","--diffs-bg-separator-override":"var(--zg-tray)","--diffs-bg-buffer-override":"var(--zg-bg)","--diffs-bg-hover-override":"var(--zg-row-hover)","--diffs-bg-addition-override":"var(--zg-diff-add-bg)","--diffs-bg-addition-emphasis-override":"var(--zg-diff-add-content-bg)","--diffs-bg-addition-number-override":"var(--zg-diff-add-bg)","--diffs-bg-deletion-override":"var(--zg-diff-remove-bg)","--diffs-bg-deletion-emphasis-override":"var(--zg-diff-remove-content-bg)","--diffs-bg-deletion-number-override":"var(--zg-diff-remove-bg)","--diffs-fg-number-override":"var(--zg-text-subtle)","--diffs-editor-selection-bg":"color-mix(in srgb, var(--zg-accent) 28%, transparent)","--diffs-fg-number-addition-override":"var(--zg-diff-add-fg)","--diffs-fg-number-deletion-override":"var(--zg-diff-remove-fg)","--diffs-bg-selection-override":"var(--zg-accent-soft)","--diffs-bg-selection-number-override":"var(--zg-accent-soft-strong)","--diffs-annotation-bg":"var(--zg-tray)","--diffs-font-family":"var(--zg-font-mono)","--diffs-header-font-family":"var(--zg-font-ui)","--diffs-font-size":"var(--zg-font-size-code)","--diffs-line-height":"calc(var(--zg-font-size-code) * 1.65)"},PREFERRED_HIGHLIGHTER="highlights",VIRTUALIZER_CONFIG={overscrollSize:600,intersectionObserverMargin:1200},DIFFS_UNSAFE_CSS=`
|
|
7
|
+
`)}function extractWindowedFileContent(lines,startingLine,totalLines){if(lines.length===0)return"";const endLine=Math.min(startingLine+totalLines,lines.length);return lines.slice(startingLine,endLine).join("")}function isFilePlainText(file){return(file.lang??getFiletypeFromFileName(file.name))==="text"}var WorkerPoolTerminatedError=class extends Error{constructor(){super("WorkerPoolManager: operation canceled because the pool terminated"),this.name="WorkerPoolTerminatedError"}},WorkerPoolTaskCanceledError=class extends Error{constructor(){super("WorkerPoolManager: operation canceled before the task completed"),this.name="WorkerPoolTaskCanceledError"}},WorkerPoolWorkerError=class extends Error{constructor(message,options){super(message,options),this.name="WorkerPoolWorkerError"}};const reportedWorkerErrors=new WeakSet;function markWorkerErrorReported(error){reportedWorkerErrors.add(error)}function isWorkerPoolCancellation(error){return error instanceof WorkerPoolTerminatedError||error instanceof WorkerPoolTaskCanceledError}function isHandledWorkerPoolError(error){return isWorkerPoolCancellation(error)||error instanceof WorkerPoolWorkerError&&reportedWorkerErrors.has(error)}function computeVirtualFileMetrics(metrics){return{...DEFAULT_VIRTUAL_FILE_METRICS,...metrics}}function getVirtualFileHeaderRegion(metrics,disableFileHeader){return getVirtualFileHeaderHeight(metrics,disableFileHeader)+getVirtualFilePaddingTop(metrics,disableFileHeader)}function getVirtualFileHeaderHeight(metrics,disableFileHeader){return disableFileHeader?0:metrics.diffHeaderHeight}function getVirtualFilePaddingTop(metrics,disableFileHeader){return metrics.paddingTop??(disableFileHeader?metrics.spacing:0)}function getVirtualFilePaddingBottom(metrics){return metrics.paddingBottom??metrics.spacing}function getDefaultHunkSeparatorHeight(type){switch(type){case"simple":return 4;case"metadata":case"line-info":case"line-info-basic":case"custom":return 32}}function areDiffTargetsEqual(diffA,diffB){return diffA?.cacheKey!=null||diffB?.cacheKey!=null?diffA?.cacheKey===diffB?.cacheKey:diffA===diffB}function areFilesEqual(fileA,fileB){return fileA?.cacheKey===fileB?.cacheKey&&fileA?.contents===fileB?.contents&&fileA?.name===fileB?.name&&fileA?.lang===fileB?.lang}function getHunkSideStartBoundary(start,count){return start-(count===0?0:1)}function getHunkSideEndBoundary(start,count){return getHunkSideStartBoundary(start,count)+count}function cleanLastNewline(contents){let end=contents.length;return contents.charCodeAt(end-1)===10&&(end--,contents.charCodeAt(end-1)===13&&end--),contents.slice(0,end)}class Diff{diff(oldStr,newStr,options={}){let callback;typeof options=="function"?(callback=options,options={}):"callback"in options&&(callback=options.callback);const oldString=this.castInput(oldStr,options),newString=this.castInput(newStr,options),oldTokens=this.removeEmpty(this.tokenize(oldString,options)),newTokens=this.removeEmpty(this.tokenize(newString,options));return this.diffWithOptionsObj(oldTokens,newTokens,options,callback)}diffWithOptionsObj(oldTokens,newTokens,options,callback){var _a;const done=value=>{if(value=this.postProcess(value,options),callback){setTimeout(function(){callback(value)},0);return}else return value},newLen=newTokens.length,oldLen=oldTokens.length;let editLength=1,maxEditLength=newLen+oldLen;options.maxEditLength!=null&&(maxEditLength=Math.min(maxEditLength,options.maxEditLength));const maxExecutionTime=(_a=options.timeout)!==null&&_a!==void 0?_a:1/0,abortAfterTimestamp=Date.now()+maxExecutionTime,bestPath=[{oldPos:-1,lastComponent:void 0}];let newPos=this.extractCommon(bestPath[0],newTokens,oldTokens,0,options);if(bestPath[0].oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(bestPath[0].lastComponent,newTokens,oldTokens));let minDiagonalToConsider=-1/0,maxDiagonalToConsider=1/0;const execEditLength=()=>{for(let diagonalPath=Math.max(minDiagonalToConsider,-editLength);diagonalPath<=Math.min(maxDiagonalToConsider,editLength);diagonalPath+=2){let basePath;const removePath=bestPath[diagonalPath-1],addPath=bestPath[diagonalPath+1];removePath&&(bestPath[diagonalPath-1]=void 0);let canAdd=!1;if(addPath){const addPathNewPos=addPath.oldPos-diagonalPath;canAdd=addPath&&0<=addPathNewPos&&addPathNewPos<newLen}const canRemove=removePath&&removePath.oldPos+1<oldLen;if(!canAdd&&!canRemove){bestPath[diagonalPath]=void 0;continue}if(!canRemove||canAdd&&removePath.oldPos<addPath.oldPos?basePath=this.addToPath(addPath,!0,!1,0,options):basePath=this.addToPath(removePath,!1,!0,1,options),newPos=this.extractCommon(basePath,newTokens,oldTokens,diagonalPath,options),basePath.oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(basePath.lastComponent,newTokens,oldTokens))||!0;bestPath[diagonalPath]=basePath,basePath.oldPos+1>=oldLen&&(maxDiagonalToConsider=Math.min(maxDiagonalToConsider,diagonalPath-1)),newPos+1>=newLen&&(minDiagonalToConsider=Math.max(minDiagonalToConsider,diagonalPath+1))}editLength++};if(callback)(function exec(){setTimeout(function(){if(editLength>maxEditLength||Date.now()>abortAfterTimestamp)return callback(void 0);execEditLength()||exec()},0)})();else for(;editLength<=maxEditLength&&Date.now()<=abortAfterTimestamp;){const ret=execEditLength();if(ret)return ret}}addToPath(path,added,removed,oldPosInc,options){const last=path.lastComponent;return last&&!options.oneChangePerToken&&last.added===added&&last.removed===removed?{oldPos:path.oldPos+oldPosInc,lastComponent:{count:last.count+1,added,removed,previousComponent:last.previousComponent}}:{oldPos:path.oldPos+oldPosInc,lastComponent:{count:1,added,removed,previousComponent:last}}}extractCommon(basePath,newTokens,oldTokens,diagonalPath,options){const newLen=newTokens.length,oldLen=oldTokens.length;let oldPos=basePath.oldPos,newPos=oldPos-diagonalPath,commonCount=0;for(;newPos+1<newLen&&oldPos+1<oldLen&&this.equals(oldTokens[oldPos+1],newTokens[newPos+1],options);)newPos++,oldPos++,commonCount++,options.oneChangePerToken&&(basePath.lastComponent={count:1,previousComponent:basePath.lastComponent,added:!1,removed:!1});return commonCount&&!options.oneChangePerToken&&(basePath.lastComponent={count:commonCount,previousComponent:basePath.lastComponent,added:!1,removed:!1}),basePath.oldPos=oldPos,newPos}equals(left,right,options){return options.comparator?options.comparator(left,right):left===right||!!options.ignoreCase&&left.toLowerCase()===right.toLowerCase()}removeEmpty(array){const ret=[];for(let i=0;i<array.length;i++)array[i]&&ret.push(array[i]);return ret}castInput(value,options){return value}tokenize(value,options){return Array.from(value)}join(chars){return chars.join("")}postProcess(changeObjects,options){return changeObjects}get useLongestToken(){return!1}buildValues(lastComponent,newTokens,oldTokens){const components=[];let nextComponent;for(;lastComponent;)components.push(lastComponent),nextComponent=lastComponent.previousComponent,delete lastComponent.previousComponent,lastComponent=nextComponent;components.reverse();const componentLen=components.length;let componentPos=0,newPos=0,oldPos=0;for(;componentPos<componentLen;componentPos++){const component=components[componentPos];if(component.removed)component.value=this.join(oldTokens.slice(oldPos,oldPos+component.count)),oldPos+=component.count;else{if(!component.added&&this.useLongestToken){let value=newTokens.slice(newPos,newPos+component.count);value=value.map(function(value2,i){const oldValue=oldTokens[oldPos+i];return oldValue.length>value2.length?oldValue:value2}),component.value=this.join(value)}else component.value=this.join(newTokens.slice(newPos,newPos+component.count));newPos+=component.count,component.added||(oldPos+=component.count)}}return components}}class CharacterDiff extends Diff{}const characterDiff=new CharacterDiff;function diffChars(oldStr,newStr,options){return characterDiff.diff(oldStr,newStr,options)}const extendedWordChars="a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}";class WordsWithSpaceDiff extends Diff{tokenize(value){const regex=new RegExp(`(\\r?\\n)|[${extendedWordChars}]+|[^\\S\\n\\r]+|[^${extendedWordChars}]`,"ug");return value.match(regex)||[]}}const wordsWithSpaceDiff=new WordsWithSpaceDiff;function diffWordsWithSpace(oldStr,newStr,options){return wordsWithSpaceDiff.diff(oldStr,newStr,options)}function areDiffRenderOptionsEqual(optionsA,optionsB){return areThemesEqual(optionsA.theme,optionsB.theme)&&optionsA.useTokenTransformer===optionsB.useTokenTransformer&&optionsA.tokenizeMaxLineLength===optionsB.tokenizeMaxLineLength&&optionsA.lineDiffType===optionsB.lineDiffType&&optionsA.maxLineDiffLength===optionsB.maxLineDiffLength}function createDiffSpanDecoration({line,spanStart,spanLength}){return{start:{line,character:spanStart},end:{line,character:spanStart+spanLength},properties:{"data-diff-span":""},alwaysWrap:!0}}function pushOrJoinSpan({item,arr,enableJoin,isNeutral=!1,isLastItem=!1}){const lastItem=arr[arr.length-1];if(lastItem==null||isLastItem||!enableJoin){arr.push([isNeutral?0:1,item.value]);return}const isLastItemNeutral=lastItem[0]===0;if(isNeutral===isLastItemNeutral||isNeutral&&item.value.length===1&&!isLastItemNeutral){lastItem[1]+=item.value;return}arr.push([isNeutral?0:1,item.value])}function getHunkAdditionLineRange(hunk){return[getHunkSideStartBoundary(hunk.additionStart,hunk.additionCount)+1,getHunkSideEndBoundary(hunk.additionStart,hunk.additionCount)+1]}function getExpandedRegion({isPartial,rangeSize,expandedHunks,hunkIndex,collapsedContextThreshold}){const normalizedRangeSize=Math.max(rangeSize,0);if(normalizedRangeSize===0||isPartial)return{fromStart:0,fromEnd:0,rangeSize:normalizedRangeSize,collapsedLines:normalizedRangeSize,renderAll:!1};if(expandedHunks===!0||normalizedRangeSize<=collapsedContextThreshold)return{fromStart:normalizedRangeSize,fromEnd:0,rangeSize:normalizedRangeSize,collapsedLines:0,renderAll:!0};const region=expandedHunks?.get(hunkIndex),fromStart=Math.min(Math.max(region?.fromStart??0,0),normalizedRangeSize),fromEnd=Math.min(Math.max(region?.fromEnd??0,0),normalizedRangeSize),expandedCount=fromStart+fromEnd,renderAll=expandedCount>=normalizedRangeSize;return{fromStart:renderAll?normalizedRangeSize:fromStart,fromEnd:renderAll?0:fromEnd,rangeSize:normalizedRangeSize,collapsedLines:Math.max(normalizedRangeSize-expandedCount,0),renderAll}}function hasTrailingContextMismatch(fileDiff){const lastHunk=fileDiff.hunks[fileDiff.hunks.length-1];if(lastHunk==null||fileDiff.isPartial||fileDiff.additionLines.length===0||fileDiff.deletionLines.length===0)return!1;const additionRemaining=fileDiff.additionLines.length-getHunkSideEndBoundary(lastHunk.additionStart,lastHunk.additionCount),deletionRemaining=fileDiff.deletionLines.length-getHunkSideEndBoundary(lastHunk.deletionStart,lastHunk.deletionCount);return additionRemaining<=0&&deletionRemaining<=0?!1:additionRemaining!==deletionRemaining}function getTrailingContextRangeSize({fileDiff,errorPrefix}){const lastHunk=fileDiff.hunks[fileDiff.hunks.length-1];if(lastHunk==null||fileDiff.isPartial||fileDiff.additionLines.length===0||fileDiff.deletionLines.length===0)return 0;const additionRemaining=fileDiff.additionLines.length-getHunkSideEndBoundary(lastHunk.additionStart,lastHunk.additionCount),deletionRemaining=fileDiff.deletionLines.length-getHunkSideEndBoundary(lastHunk.deletionStart,lastHunk.deletionCount);if(additionRemaining<=0&&deletionRemaining<=0)return 0;if(additionRemaining!==deletionRemaining)throw new Error(`${errorPrefix}: trailing context mismatch (additions=${additionRemaining}, deletions=${deletionRemaining}) for ${fileDiff.name}`);return Math.min(additionRemaining,deletionRemaining)}function getTrailingExpandedRegion({fileDiff,hunkIndex,expandedHunks,collapsedContextThreshold,errorPrefix}){if(hunkIndex!==fileDiff.hunks.length-1)return;const trailingRangeSize=getTrailingContextRangeSize({fileDiff,errorPrefix});if(trailingRangeSize<=0)return;if(expandedHunks===!0||trailingRangeSize<=collapsedContextThreshold)return{fromStart:trailingRangeSize,fromEnd:0,rangeSize:trailingRangeSize,collapsedLines:0,renderAll:!0};const region=expandedHunks?.get(fileDiff.hunks.length),fromStart=Math.min(Math.max(region?.fromStart??0,0),trailingRangeSize);return{fromStart,fromEnd:0,rangeSize:trailingRangeSize,collapsedLines:trailingRangeSize-fromStart,renderAll:fromStart>=trailingRangeSize}}function isAdditionLineRenderable({fileDiff,lineNumber,expandedHunks,collapsedContextThreshold}){if(expandedHunks===!0||fileDiff.isPartial)return!0;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;return region.renderAll||lineNumber<gapStart+region.fromStart||lineNumber>=hunkStart-region.fromEnd}if(lineNumber<hunkEnd)return!0}const trailingRegion=getTrailingExpandedRegion({fileDiff,hunkIndex:fileDiff.hunks.length-1,expandedHunks,collapsedContextThreshold,errorPrefix:"isAdditionLineRenderable"});if(trailingRegion==null||trailingRegion.renderAll)return!0;const lastHunk=fileDiff.hunks[fileDiff.hunks.length-1],[,trailingStart]=getHunkAdditionLineRange(lastHunk);return lineNumber<trailingStart+trailingRegion.fromStart||lineNumber>=trailingStart+trailingRegion.rangeSize}function getNearestRenderableAdditionLine({fileDiff,lineNumber,direction,expandedHunks,collapsedContextThreshold}){if(expandedHunks===!0||fileDiff.isPartial)return lineNumber;const ranges=[];let modeledEnd=1;for(const[hunkIndex,hunk]of fileDiff.hunks.entries()){const[hunkStart,hunkEnd]=getHunkAdditionLineRange(hunk),region=getExpandedRegion({isPartial:fileDiff.isPartial,rangeSize:hunk.collapsedBefore,expandedHunks,hunkIndex,collapsedContextThreshold}),gapStart=hunkStart-region.rangeSize;region.renderAll?ranges.push([gapStart,hunkStart]):(region.fromStart>0&&ranges.push([gapStart,gapStart+region.fromStart]),region.fromEnd>0&&ranges.push([hunkStart-region.fromEnd,hunkStart])),ranges.push([hunkStart,hunkEnd]),modeledEnd=hunkEnd}const trailingRegion=getTrailingExpandedRegion({fileDiff,hunkIndex:fileDiff.hunks.length-1,expandedHunks,collapsedContextThreshold,errorPrefix:"getNearestRenderableAdditionLine"});if(trailingRegion!=null){const trailingStart=modeledEnd;modeledEnd=trailingStart+trailingRegion.rangeSize,trailingRegion.renderAll?ranges.push([trailingStart,modeledEnd]):trailingRegion.fromStart>0&&ranges.push([trailingStart,trailingStart+trailingRegion.fromStart])}if(lineNumber>=modeledEnd)return lineNumber;if(direction==="down"){for(const[start,end]of ranges)if(end>lineNumber)return Math.max(start,lineNumber);return}for(let index=ranges.length-1;index>=0;index--){const[start,end]=ranges[index];if(start<=lineNumber)return Math.min(end-1,lineNumber)}}function getHunkSeparatorHeight({type,metrics}){return metrics.hunkSeparatorHeight??getDefaultHunkSeparatorHeight(type)}function getHunkSeparatorGap({type,metrics}){return type==="simple"||type==="metadata"||type==="line-info-basic"?0:metrics.spacing}function hasLeadingHunkSeparator({type,hunkIndex,hunkSpecs}){switch(type){case"simple":return hunkIndex>0;case"metadata":return hunkSpecs!=null;case"line-info":case"line-info-basic":case"custom":return!0}}function hasTrailingHunkSeparator(type){return type!=="simple"&&type!=="metadata"}function getLeadingHunkSeparatorLayout({type,metrics,hunkIndex,hunkSpecs}){if(!hasLeadingHunkSeparator({type,hunkIndex,hunkSpecs}))return;const height=getHunkSeparatorHeight({type,metrics}),gap=getHunkSeparatorGap({type,metrics}),gapBefore=hunkIndex>0?gap:0,gapAfter=gap;return{height,gapBefore,gapAfter,totalHeight:gapBefore+height+gapAfter}}function getTrailingHunkSeparatorLayout({type,metrics}){if(!hasTrailingHunkSeparator(type))return;const height=getHunkSeparatorHeight({type,metrics}),gapBefore=getHunkSeparatorGap({type,metrics});return{height,gapBefore,gapAfter:0,totalHeight:gapBefore+height}}function iterateOverDiff({diff,diffStyle,startingLine=0,totalLines=1/0,expandedHunks,collapsedContextThreshold=1,callback}){const iterationStart=getIterationStartState({diff,diffStyle,startingLine,expandedHunks,collapsedContextThreshold}),state={viewportStart:startingLine,viewportEnd:startingLine+totalLines,isWindowedHighlight:startingLine>0||totalLines<1/0,splitCount:iterationStart.splitCount,unifiedCount:iterationStart.unifiedCount,finalHunkIndex:diff.hunks.length-1,shouldBreak(){if(!state.isWindowedHighlight)return!1;const breakUnified=state.unifiedCount>=startingLine+totalLines,breakSplit=state.splitCount>=startingLine+totalLines;return diffStyle==="unified"?breakUnified:(diffStyle==="split"||breakUnified)&&breakSplit},shouldSkip(unifiedCount,splitCount){if(!state.isWindowedHighlight)return!1;const skipUnified=unifiedCount>0&&state.unifiedCount+unifiedCount<=startingLine,skipSplit=splitCount>0&&state.splitCount+splitCount<=startingLine;return diffStyle==="unified"?skipUnified:(diffStyle==="split"||skipUnified)&&skipSplit},incrementCounts(unifiedValue,splitValue){(diffStyle==="unified"||diffStyle==="both")&&(state.unifiedCount+=unifiedValue),(diffStyle==="split"||diffStyle==="both")&&(state.splitCount+=splitValue)},isInWindow(unifiedHeight,splitHeight){if(!state.isWindowedHighlight)return!0;const unifiedInWindow=state.isInUnifiedWindow(unifiedHeight),splitInWindow=state.isInSplitWindow(splitHeight);return diffStyle==="unified"?unifiedInWindow:diffStyle==="split"?splitInWindow:unifiedInWindow||splitInWindow},isInUnifiedWindow(unifiedHeight){return!state.isWindowedHighlight||state.unifiedCount>=startingLine-unifiedHeight&&state.unifiedCount<startingLine+totalLines},isInSplitWindow(splitHeight){return!state.isWindowedHighlight||state.splitCount>=startingLine-splitHeight&&state.splitCount<startingLine+totalLines},emit(props,silent=!1){return silent||(diffStyle==="unified"?state.incrementCounts(1,0):diffStyle==="split"?state.incrementCounts(0,1):state.incrementCounts(1,1)),callback(props)??!1}};hunkIterator:for(let hunkIndex=iterationStart.hunkIndex;hunkIndex<diff.hunks.length;hunkIndex++){let getTrailingCollapsedAfter=function(unifiedLineIndex2,splitLineIndex2){return trailingRegion==null||trailingRegion.collapsedLines<=0||trailingRegion.fromStart+trailingRegion.fromEnd>0?0:diffStyle==="unified"?unifiedLineIndex2===hunk.unifiedLineStart+hunk.unifiedLineCount-1?trailingRegion.collapsedLines:0:splitLineIndex2===hunk.splitLineStart+hunk.splitLineCount-1?trailingRegion.collapsedLines:0},consumePendingCollapsed=function(){return consumedCollapsed?0:(consumedCollapsed=!0,leadingRegion.collapsedLines)};const hunk=diff.hunks[hunkIndex];if(hunk==null)throw new Error("iterateOverDiff: invalid hunk index");if(state.shouldBreak())break;const deletionBoundary=getHunkSideStartBoundary(hunk.deletionStart,hunk.deletionCount),additionBoundary=getHunkSideStartBoundary(hunk.additionStart,hunk.additionCount),deletionStartIndex=!diff.isPartial&&hunk.deletionCount===0?deletionBoundary:hunk.deletionLineIndex,additionStartIndex=!diff.isPartial&&hunk.additionCount===0?additionBoundary:hunk.additionLineIndex,leadingRegion=getExpandedRegion({isPartial:diff.isPartial,rangeSize:hunk.collapsedBefore,expandedHunks,hunkIndex,collapsedContextThreshold}),trailingRegion=hunkIndex===state.finalHunkIndex?getTrailingExpandedRegion({fileDiff:diff,hunkIndex,expandedHunks,collapsedContextThreshold,errorPrefix:"iterateOverDiff"}):void 0,expandedLineCount=leadingRegion.fromStart+leadingRegion.fromEnd;let consumedCollapsed=leadingRegion.collapsedLines===0;if(state.shouldSkip(expandedLineCount,expandedLineCount))state.incrementCounts(expandedLineCount,expandedLineCount),consumePendingCollapsed();else{let unifiedLineIndex2=hunk.unifiedLineStart-leadingRegion.rangeSize,splitLineIndex2=hunk.splitLineStart-leadingRegion.rangeSize,deletionLineIndex2=deletionStartIndex-leadingRegion.rangeSize,additionLineIndex2=additionStartIndex-leadingRegion.rangeSize,deletionLineNumber2=deletionBoundary+1-leadingRegion.rangeSize,additionLineNumber2=additionBoundary+1-leadingRegion.rangeSize;if(walkContextLines(state,leadingRegion.fromStart,diffStyle,index=>state.emit({hunkIndex,hunk,collapsedBefore:0,collapsedAfter:0,type:"context-expanded",deletionLine:{lineNumber:deletionLineNumber2+index,lineIndex:deletionLineIndex2+index,noEOFCR:!1,unifiedLineIndex:unifiedLineIndex2+index,splitLineIndex:splitLineIndex2+index},additionLine:{unifiedLineIndex:unifiedLineIndex2+index,splitLineIndex:splitLineIndex2+index,lineIndex:additionLineIndex2+index,lineNumber:additionLineNumber2+index,noEOFCR:!1}}))||(unifiedLineIndex2=hunk.unifiedLineStart-leadingRegion.fromEnd,splitLineIndex2=hunk.splitLineStart-leadingRegion.fromEnd,deletionLineIndex2=deletionStartIndex-leadingRegion.fromEnd,additionLineIndex2=additionStartIndex-leadingRegion.fromEnd,deletionLineNumber2=deletionBoundary+1-leadingRegion.fromEnd,additionLineNumber2=additionBoundary+1-leadingRegion.fromEnd,walkContextLines(state,leadingRegion.fromEnd,diffStyle,index=>state.emit({hunkIndex,hunk,collapsedBefore:consumePendingCollapsed(),collapsedAfter:0,type:"context-expanded",deletionLine:{lineNumber:deletionLineNumber2+index,lineIndex:deletionLineIndex2+index,noEOFCR:!1,unifiedLineIndex:unifiedLineIndex2+index,splitLineIndex:splitLineIndex2+index},additionLine:{unifiedLineIndex:unifiedLineIndex2+index,splitLineIndex:splitLineIndex2+index,lineIndex:additionLineIndex2+index,lineNumber:additionLineNumber2+index,noEOFCR:!1}}),()=>{consumePendingCollapsed()})))break hunkIterator}let unifiedLineIndex=hunk.unifiedLineStart,splitLineIndex=hunk.splitLineStart,deletionLineIndex=deletionStartIndex,additionLineIndex=additionStartIndex,deletionLineNumber=deletionBoundary+1,additionLineNumber=additionBoundary+1;const lastContent=hunk.hunkContent.at(-1);for(const content of hunk.hunkContent){if(state.shouldBreak())break hunkIterator;const isLastContent=content===lastContent;if(content.type==="context"){if(state.shouldSkip(content.lines,content.lines))state.incrementCounts(content.lines,content.lines),consumePendingCollapsed();else if(walkContextLines(state,content.lines,diffStyle,index=>{const isLastLine=isLastContent&&index===content.lines-1,unifiedRowIndex=unifiedLineIndex+index,splitRowIndex=splitLineIndex+index;return state.emit({hunkIndex,hunk,collapsedBefore:consumePendingCollapsed(),collapsedAfter:getTrailingCollapsedAfter(unifiedRowIndex,splitRowIndex),type:"context",deletionLine:{lineNumber:deletionLineNumber+index,lineIndex:deletionLineIndex+index,noEOFCR:isLastLine&&hunk.noEOFCRDeletions,unifiedLineIndex:unifiedRowIndex,splitLineIndex:splitRowIndex},additionLine:{unifiedLineIndex:unifiedRowIndex,splitLineIndex:splitRowIndex,lineIndex:additionLineIndex+index,lineNumber:additionLineNumber+index,noEOFCR:isLastLine&&hunk.noEOFCRAdditions}})},()=>{consumePendingCollapsed()}))break hunkIterator;unifiedLineIndex+=content.lines,splitLineIndex+=content.lines,deletionLineIndex+=content.lines,additionLineIndex+=content.lines,deletionLineNumber+=content.lines,additionLineNumber+=content.lines}else{const splitCount=Math.max(content.deletions,content.additions),unifiedCount=content.deletions+content.additions;if(!state.shouldSkip(unifiedCount,splitCount)){const iterationRanges=getChangeIterationRanges(state,content,diffStyle);(iterationRanges[0]?.[0]??0)>0&&consumePendingCollapsed();for(const[rangeStart,rangeEnd]of iterationRanges)for(let index=rangeStart;index<rangeEnd;index++){const collapsedAfter=getTrailingCollapsedAfter(unifiedLineIndex+index,diffStyle==="unified"?splitLineIndex+(index<content.deletions?index:index-content.deletions):splitLineIndex+index);if(state.emit(getChangeLineData({hunkIndex,hunk,collapsedBefore:consumePendingCollapsed(),collapsedAfter,diffStyle,index,unifiedLineIndex,splitLineIndex,additionLineIndex,deletionLineIndex,additionLineNumber,deletionLineNumber,content,isLastContent,unifiedCount,splitCount}),!0))break hunkIterator}}consumePendingCollapsed(),state.incrementCounts(unifiedCount,splitCount),unifiedLineIndex+=unifiedCount,splitLineIndex+=splitCount,deletionLineIndex+=content.deletions,additionLineIndex+=content.additions,deletionLineNumber+=content.deletions,additionLineNumber+=content.additions}}if(trailingRegion!=null){const{collapsedLines,fromStart,fromEnd}=trailingRegion,len=fromStart+fromEnd;if(walkContextLines(state,len,diffStyle,index=>{const isLastLine=index===len-1;return state.emit({hunkIndex:diff.hunks.length,hunk:void 0,collapsedBefore:0,collapsedAfter:isLastLine?collapsedLines:0,type:"context-expanded",deletionLine:{lineNumber:deletionLineNumber+index,lineIndex:deletionLineIndex+index,noEOFCR:!1,unifiedLineIndex:unifiedLineIndex+index,splitLineIndex:splitLineIndex+index},additionLine:{unifiedLineIndex:unifiedLineIndex+index,splitLineIndex:splitLineIndex+index,lineIndex:additionLineIndex+index,lineNumber:additionLineNumber+index,noEOFCR:!1}})},void 0,()=>state.shouldBreak()))break hunkIterator}}}function getIterationStartState({diff,diffStyle,startingLine,expandedHunks,collapsedContextThreshold}){if(startingLine<=0||diffStyle==="both")return{hunkIndex:0,splitCount:0,unifiedCount:0};const prefixCounts=getHunkPrefixCounts({diff,expandedHunks,collapsedContextThreshold});let low=0,high=diff.hunks.length-1,result=diff.hunks.length;for(;low<=high;){const mid=low+high>>1,counts2=prefixCounts[mid+1];if(counts2==null)throw new Error("iterateOverDiff: invalid hunk prefix index");(diffStyle==="unified"?counts2.unifiedCount:counts2.splitCount)>startingLine?(result=mid,high=mid-1):low=mid+1}if(result>=diff.hunks.length){const counts2=prefixCounts[diff.hunks.length];if(counts2==null)throw new Error("iterateOverDiff: invalid terminal hunk prefix index");return{hunkIndex:diff.hunks.length,splitCount:counts2.splitCount,unifiedCount:counts2.unifiedCount}}const counts=prefixCounts[result];if(counts==null)throw new Error("iterateOverDiff: invalid selected hunk prefix index");return{hunkIndex:result,splitCount:counts.splitCount,unifiedCount:counts.unifiedCount}}function getHunkPrefixCounts({diff,expandedHunks,collapsedContextThreshold}){let splitCount=0,unifiedCount=0;const finalHunkIndex=diff.hunks.length-1,prefixCounts=[{splitCount:0,unifiedCount:0}];for(let index=0;index<diff.hunks.length;index++){const hunk=diff.hunks[index];if(hunk==null)throw new Error("iterateOverDiff: invalid hunk summary index");const leadingRegion=getExpandedRegion({isPartial:diff.isPartial,rangeSize:hunk.collapsedBefore,expandedHunks,hunkIndex:index,collapsedContextThreshold}),leadingCount=leadingRegion.fromStart+leadingRegion.fromEnd;splitCount+=leadingCount+hunk.splitLineCount,unifiedCount+=leadingCount+hunk.unifiedLineCount;const trailingRegion=index===finalHunkIndex?getTrailingExpandedRegion({fileDiff:diff,hunkIndex:index,expandedHunks,collapsedContextThreshold,errorPrefix:"iterateOverDiff"}):void 0;if(trailingRegion!=null){const trailingCount=trailingRegion.fromStart+trailingRegion.fromEnd;splitCount+=trailingCount,unifiedCount+=trailingCount}prefixCounts.push({splitCount,unifiedCount})}return prefixCounts}function getContextLineIterationBounds(state,count,diffStyle){if(!state.isWindowedHighlight||count<=0)return[0,count];const ranges=[];function pushRange(currentCount){const start2=Math.max(0,state.viewportStart-currentCount),end2=Math.min(count,state.viewportEnd-currentCount);end2>start2&&ranges.push([start2,end2])}if(diffStyle!=="split"&&pushRange(state.unifiedCount),diffStyle!=="unified"&&pushRange(state.splitCount),ranges.length===0)return[0,0];let start=ranges[0][0],end=ranges[0][1];for(let index=1;index<ranges.length;index++){const range=ranges[index];start=Math.min(start,range[0]),end=Math.max(end,range[1])}return[start,end]}function walkContextLines(state,count,diffStyle,callback,onSkippedStart,shouldBreak){const[startIndex,endIndex]=getContextLineIterationBounds(state,count,diffStyle);startIndex>0&&(state.incrementCounts(startIndex,startIndex),onSkippedStart?.());let index=startIndex;for(;index<count;){if(shouldBreak?.()===!0)return!0;if(index>=endIndex){state.incrementCounts(count-index,count-index);break}if(state.isInWindow(0,0)){if(callback(index)===!0)return!0}else state.incrementCounts(1,1);index++}return!1}function getChangeIterationRanges(state,content,diffStyle){if(!state.isWindowedHighlight)return[[0,diffStyle==="unified"?content.deletions+content.additions:Math.max(content.deletions,content.additions)]];const useUnified=diffStyle!=="split",useSplit=diffStyle!=="unified",iterationSpace=diffStyle==="unified"?"unified":"split",iterationRanges=[];function getVisibleRange(start,count){if(start+count<=state.viewportStart||start>=state.viewportEnd)return;const visibleStart=Math.max(0,state.viewportStart-start),visibleEnd=Math.min(count,state.viewportEnd-start);return visibleEnd>visibleStart?[visibleStart,visibleEnd]:void 0}function mapRangeToIteration(range,kind){return iterationSpace==="split"?range:kind==="additions"?[range[0]+content.deletions,range[1]+content.deletions]:range}function pushRange(range,kind){if(range==null)return;const[start,end]=mapRangeToIteration(range,kind);end>start&&iterationRanges.push([start,end])}if(useUnified&&(pushRange(getVisibleRange(state.unifiedCount,content.deletions),"deletions"),pushRange(getVisibleRange(state.unifiedCount+content.deletions,content.additions),"additions")),useSplit&&(pushRange(getVisibleRange(state.splitCount,content.deletions),"deletions"),pushRange(getVisibleRange(state.splitCount,content.additions),"additions")),iterationRanges.length===0)return iterationRanges;iterationRanges.sort((a,b)=>a[0]-b[0]);const merged=[iterationRanges[0]];for(const[start,end]of iterationRanges.slice(1)){const last=merged[merged.length-1];start<=last[1]?last[1]=Math.max(last[1],end):merged.push([start,end])}return merged}function getChangeLineData({hunkIndex,hunk,collapsedAfter,collapsedBefore,diffStyle,index,unifiedLineIndex,splitLineIndex,additionLineIndex,deletionLineIndex,additionLineNumber,deletionLineNumber,content,isLastContent,unifiedCount,splitCount}){const unifiedDeletionLineIndex=index<content.deletions?unifiedLineIndex+index:void 0,unifiedAdditionLineIndex=diffStyle==="unified"?index>=content.deletions?unifiedLineIndex+index:void 0:index<content.additions?unifiedLineIndex+content.deletions+index:void 0,resolvedSplitLineIndex=diffStyle==="unified"?splitLineIndex+(index<content.deletions?index:index-content.deletions):splitLineIndex+index,deletionLineIndexValue=index<content.deletions?deletionLineIndex+index:void 0,deletionLineNumberValue=index<content.deletions?deletionLineNumber+index:void 0,additionLineIndexValue=diffStyle==="unified"?index>=content.deletions?additionLineIndex+(index-content.deletions):void 0:index<content.additions?additionLineIndex+index:void 0,additionLineNumberValue=diffStyle==="unified"?index>=content.deletions?additionLineNumber+(index-content.deletions):void 0:index<content.additions?additionLineNumber+index:void 0,noEOFCRDeletion=diffStyle==="unified"?isLastContent&&index===content.deletions-1&&hunk.noEOFCRDeletions:isLastContent&&index===splitCount-1&&hunk.noEOFCRDeletions,noEOFCRAddition=diffStyle==="unified"?isLastContent&&index===unifiedCount-1&&hunk.noEOFCRAdditions:isLastContent&&index===splitCount-1&&hunk.noEOFCRAdditions,deletionLine=deletionLineIndexValue!=null&&deletionLineNumberValue!=null&&unifiedDeletionLineIndex!=null?{lineNumber:deletionLineNumberValue,lineIndex:deletionLineIndexValue,noEOFCR:noEOFCRDeletion,unifiedLineIndex:unifiedDeletionLineIndex,splitLineIndex:resolvedSplitLineIndex}:void 0,additionLine=additionLineIndexValue!=null&&additionLineNumberValue!=null&&unifiedAdditionLineIndex!=null?{unifiedLineIndex:unifiedAdditionLineIndex,splitLineIndex:resolvedSplitLineIndex,lineIndex:additionLineIndexValue,lineNumber:additionLineNumberValue,noEOFCR:noEOFCRAddition}:void 0;if(deletionLine==null&&additionLine!=null)return{type:"change",hunkIndex,hunk,collapsedAfter,collapsedBefore,deletionLine:void 0,additionLine};if(deletionLine!=null&&additionLine==null)return{type:"change",hunkIndex,hunk,collapsedAfter,collapsedBefore,deletionLine,additionLine:void 0};if(deletionLine==null||additionLine==null)throw new Error("iterateOverDiff: missing change line data");return{type:"change",hunkIndex,hunk,collapsedAfter,collapsedBefore,deletionLine,additionLine}}const DEFAULT_PLAIN_TEXT_OPTIONS={forcePlainText:!1};function renderDiffWithHighlighter(diff,highlighter2,options,{forcePlainText,lazyLineAST=!1,startingLine,totalLines,expandedHunks,collapsedContextThreshold=1}=DEFAULT_PLAIN_TEXT_OPTIONS){forcePlainText?(startingLine??=0,totalLines??=1/0):(startingLine=0,totalLines=1/0);const isWindowedHighlight=startingLine>0||totalLines<1/0;lazyLineAST&&=!forcePlainText&&!options.useTokenTransformer;const baseThemeType=typeof options.theme=="string"?highlighter2.getTheme(options.theme).type:void 0,themeStyles=getHighlighterThemeStyles({theme:options.theme,highlighter:highlighter2}),lineDiffType=forcePlainText&&!isWindowedHighlight&&(diff.unifiedLineCount>1e3||diff.splitLineCount>1e3)?"none":options.lineDiffType,code={deletionLines:[],additionLines:[]},{maxLineDiffLength}=options,shouldGroupAll=!forcePlainText&&!diff.isPartial,expandedHunksForIteration=forcePlainText?expandedHunks:void 0,buckets=new Map;function getBucketForHunk(hunkIndex){const index=shouldGroupAll?0:hunkIndex,bucket=buckets.get(index)??createBucket();return buckets.set(index,bucket),bucket}function appendContent(lineContent,lineIndex,segments,contentWrapper){if(isWindowedHighlight){let segment=segments.at(-1);(segment==null||segment.targetIndex+segment.count!==lineIndex)&&(segment={targetIndex:lineIndex,originalOffset:contentWrapper.length,count:0},segments.push(segment)),segment.count++}contentWrapper.push(lineContent)}iterateOverDiff({diff,diffStyle:"both",startingLine,totalLines,expandedHunks:isWindowedHighlight?expandedHunksForIteration:!0,collapsedContextThreshold,callback:({hunkIndex,additionLine,deletionLine,type})=>{const bucket=getBucketForHunk(hunkIndex),splitLineIndex=additionLine!=null?additionLine.splitLineIndex:deletionLine.splitLineIndex;type==="change"&&additionLine!=null&&deletionLine!=null&&computeLineDiffDecorations({additionLine:diff.additionLines[additionLine.lineIndex],deletionLine:diff.deletionLines[deletionLine.lineIndex],deletionLineIndex:bucket.deletionContent.length,additionLineIndex:bucket.additionContent.length,deletionDecorations:bucket.deletionDecorations,additionDecorations:bucket.additionDecorations,lineDiffType,maxLineDiffLength}),deletionLine!=null&&(appendContent(diff.deletionLines[deletionLine.lineIndex],deletionLine.lineIndex,bucket.deletionSegments,bucket.deletionContent),bucket.deletionInfo.push({type:type==="change"?"change-deletion":type,lineNumber:deletionLine.lineNumber,altLineNumber:type==="change"?void 0:additionLine.lineNumber??void 0,lineIndex:`${deletionLine.unifiedLineIndex},${splitLineIndex}`})),additionLine!=null&&(appendContent(diff.additionLines[additionLine.lineIndex],additionLine.lineIndex,bucket.additionSegments,bucket.additionContent),bucket.additionInfo.push({type:type==="change"?"change-addition":type,lineNumber:additionLine.lineNumber,altLineNumber:type==="change"?void 0:deletionLine.lineNumber??void 0,lineIndex:`${additionLine.unifiedLineIndex},${splitLineIndex}`}))}});for(const bucket of buckets.values()){if(bucket.deletionContent.length===0&&bucket.additionContent.length===0)continue;const deletionFile={name:diff.prevName??diff.name,contents:bucket.deletionContent.value},additionFile={name:diff.name,contents:bucket.additionContent.value},{deletionLines,additionLines}=renderTwoFiles({deletionFile,deletionInfo:bucket.deletionInfo,deletionDecorations:bucket.deletionDecorations,additionFile,additionInfo:bucket.additionInfo,additionDecorations:bucket.additionDecorations,highlighter:highlighter2,options,languageOverride:forcePlainText?"text":diff.lang,lazyLineAST});if(shouldGroupAll){code.deletionLines=deletionLines,code.additionLines=additionLines;continue}for(const[target,lines,segments]of[[code.deletionLines,deletionLines,bucket.deletionSegments],[code.additionLines,additionLines,bucket.additionSegments]])if(segments.length>0)for(const segment of segments)for(let index=0;index<segment.count;index++)target[segment.targetIndex+index]=lines[segment.originalOffset+index];else if(lazyLineAST){const offset=target.length;for(let index=0;index<lines.length;index++)setDeferredArrayItem(target,offset+index,()=>lines[index])}else appendItems(target,lines)}return{code,themeStyles,baseThemeType}}function pushWordLineDecorations(lineDiff,{deletionLineIndex,additionLineIndex,deletionDecorations,additionDecorations}){let deletionOffset=0,additionOffset=0,deletionStart=-1,deletionEnd=0,additionStart=-1,additionEnd=0;for(const{value,added,removed}of lineDiff)removed?(deletionStart===-1&&(deletionStart=deletionOffset),deletionOffset+=value.length,deletionEnd=deletionOffset):added?(additionStart===-1&&(additionStart=additionOffset),additionOffset+=value.length,additionEnd=additionOffset):(deletionOffset+=value.length,additionOffset+=value.length);deletionStart!==-1&&deletionDecorations.push(createDiffSpanDecoration({line:deletionLineIndex,spanStart:deletionStart,spanLength:deletionEnd-deletionStart})),additionStart!==-1&&additionDecorations.push(createDiffSpanDecoration({line:additionLineIndex,spanStart:additionStart,spanLength:additionEnd-additionStart}))}function computeLineDiffDecorations({deletionLine,additionLine,deletionLineIndex,additionLineIndex,deletionDecorations,additionDecorations,lineDiffType,maxLineDiffLength}){if(deletionLine==null||additionLine==null||lineDiffType==="none"||(deletionLine=cleanLastNewline(deletionLine),additionLine=cleanLastNewline(additionLine),deletionLine.length>maxLineDiffLength||additionLine.length>maxLineDiffLength))return;const lineDiff=lineDiffType==="char"?diffChars(deletionLine,additionLine):diffWordsWithSpace(deletionLine,additionLine);if(lineDiffType==="word-line"){pushWordLineDecorations(lineDiff,{deletionLineIndex,additionLineIndex,deletionDecorations,additionDecorations});return}const deletionSpans=[],additionSpans=[],enableJoin=lineDiffType==="word-alt",lastItem=lineDiff.at(-1);for(const item of lineDiff){const isLastItem=item===lastItem;!item.added&&!item.removed?(pushOrJoinSpan({item,arr:deletionSpans,enableJoin,isNeutral:!0,isLastItem}),pushOrJoinSpan({item,arr:additionSpans,enableJoin,isNeutral:!0,isLastItem})):item.removed?pushOrJoinSpan({item,arr:deletionSpans,enableJoin,isLastItem}):pushOrJoinSpan({item,arr:additionSpans,enableJoin,isLastItem})}let spanIndex=0;for(const span of deletionSpans)span[0]===1&&deletionDecorations.push(createDiffSpanDecoration({line:deletionLineIndex,spanStart:spanIndex,spanLength:span[1].length})),spanIndex+=span[1].length;spanIndex=0;for(const span of additionSpans)span[0]===1&&additionDecorations.push(createDiffSpanDecoration({line:additionLineIndex,spanStart:spanIndex,spanLength:span[1].length})),spanIndex+=span[1].length}function createBucket(){return{deletionContent:{push(value){this.value+=value,this.length++},value:"",length:0},additionContent:{push(value){this.value+=value,this.length++},value:"",length:0},deletionInfo:[],additionInfo:[],deletionDecorations:[],additionDecorations:[],deletionSegments:[],additionSegments:[]}}function renderTwoFiles({lazyLineAST,deletionFile,additionFile,deletionInfo,additionInfo,highlighter:highlighter2,deletionDecorations,additionDecorations,languageOverride,options:{theme,useTokenTransformer,tokenizeMaxLineLength}}){const renderFile=(file,lineInfo,decorations)=>file.contents===""?[]:renderTokenLines(highlighter2.codeToTokens(cleanLastNewline(file.contents),getTokenOptions(languageOverride??getFiletypeFromFileName(file.name),theme,tokenizeMaxLineLength)).tokens,{state:{lineInfo},useTokenTransformer,decorations,lazyLineAST,cacheHtmlStyles:highlighter2.name==="highlights"});return{deletionLines:renderFile(deletionFile,deletionInfo,deletionDecorations),additionLines:renderFile(additionFile,additionInfo,additionDecorations)}}function isDiffPlainText(diff){const computedLang=diff.lang??getFiletypeFromFileName(diff.name),computedPreviousLang=diff.lang??(diff.prevName!=null?getFiletypeFromFileName(diff.prevName):"text");return computedLang==="text"&&computedPreviousLang==="text"}function getResolvedLanguages(languages){const resolvedLanguages=[];for(const language of languages){const resolvedLanguage=ResolvedLanguages.get(language);if(resolvedLanguage==null)throw new Error(`getResolvedLanguages: ${language} is not resolved. Please resolve languages before calling getResolvedLanguages`);resolvedLanguages.push(resolvedLanguage)}return resolvedLanguages}async function resolveLanguage(lang){if(typeof __DIFFS_WORKER__<"u"?__DIFFS_WORKER__:isWorkerContext())throw new Error(`resolveLanguage("${lang}") cannot be called from a worker context. Languages must be pre-resolved on the main thread and passed to the worker via the resolvedLanguages parameter.`);const pending=ResolvingLanguages.get(lang);if(pending!=null)return pending;const resolver=(async()=>{let loader=RegisteredCustomLanguages.get(lang);if(loader==null){const{bundledLanguages}=await __vitePreload(async()=>{const{bundledLanguages:bundledLanguages2}=await import("./langs-D5CRC9qz.js");return{bundledLanguages:bundledLanguages2}},__vite__mapDeps([17,1,2,3,4,5,6,7]),import.meta.url);Object.prototype.hasOwnProperty.call(bundledLanguages,lang)&&(loader=bundledLanguages[lang])}if(loader==null)throw new Error(`resolveLanguage: "${lang}" not found in bundled or custom languages`);const{default:data}=await loader(),resolvedLang={name:lang,data};return ResolvedLanguages.has(lang)||ResolvedLanguages.set(lang,resolvedLang),resolvedLang})();ResolvingLanguages.set(lang,resolver);try{return await resolver}finally{ResolvingLanguages.get(lang)===resolver&&ResolvingLanguages.delete(lang)}}function getResolvedOrResolveLanguage(language){return ResolvedLanguages.get(language)??resolveLanguage(language)}function hasResolvedLanguages(languages){for(const language of Array.isArray(languages)?languages:[languages])if(!ResolvedLanguages.has(language))return!1;return!0}async function resolveLanguages(languages){const resolvedLanguages=[],languagesToResolve=[];for(const language of languages){if(language==="text"||language==="ansi")continue;const maybeResolvedLanguage=getResolvedOrResolveLanguage(language)??resolveLanguage(language);"then"in maybeResolvedLanguage?languagesToResolve.push(maybeResolvedLanguage):resolvedLanguages.push(maybeResolvedLanguage)}return languagesToResolve.length>0&&await Promise.all(languagesToResolve).then(_resolvedLanguages=>{for(const resolvedLanguage of _resolvedLanguages){if(resolvedLanguage==null)throw new Error("resolvedLanguages: unable to resolve language");resolvedLanguages.push(resolvedLanguage)}}),resolvedLanguages}function getResolvedThemes(themeNames,backend=resolveHighlighterType()){return createDiffsThemeResolver(backend).getResolvedThemes(themeNames)}function hasResolvedThemes(themeNames,backend=resolveHighlighterType()){return createDiffsThemeResolver(backend).hasResolvedThemes(themeNames)}function resolveThemes(themes,backend=resolveHighlighterType()){return createDiffsThemeResolver(backend).resolveThemes(themes)}var lru$1={exports:{}},lru=lru$1.exports,hasRequiredLru;function requireLru(){return hasRequiredLru||(hasRequiredLru=1,(function(module,exports){(function(g,c){c(exports)})(lru,function(g){const c=Symbol("newer"),e=Symbol("older");class n{constructor(a,b){typeof a!="number"&&(b=a,a=0),this.size=0,this.limit=a,this.oldest=this.newest=void 0,this._keymap=new Map,b&&(this.assign(b),a<1&&(this.limit=this.size))}_markEntryAsUsed(a){a!==this.newest&&(a[c]&&(a===this.oldest&&(this.oldest=a[c]),a[c][e]=a[e]),a[e]&&(a[e][c]=a[c]),a[c]=void 0,a[e]=this.newest,this.newest&&(this.newest[c]=a),this.newest=a)}assign(a){let b,d=this.limit||Number.MAX_VALUE;this._keymap.clear();let m=a[Symbol.iterator]();for(let h=m.next();!h.done;h=m.next()){let f=new l(h.value[0],h.value[1]);if(this._keymap.set(f.key,f),b?(b[c]=f,f[e]=b):this.oldest=f,b=f,d--==0)throw new Error("overflow")}this.newest=b,this.size=this._keymap.size}get(a){var b=this._keymap.get(a);return b?(this._markEntryAsUsed(b),b.value):void 0}set(a,b){var d=this._keymap.get(a);return d?(d.value=b,this._markEntryAsUsed(d),this):(this._keymap.set(a,d=new l(a,b)),this.newest?(this.newest[c]=d,d[e]=this.newest):this.oldest=d,this.newest=d,++this.size,this.size>this.limit&&this.shift(),this)}shift(){var a=this.oldest;if(a)return this.oldest[c]?(this.oldest=this.oldest[c],this.oldest[e]=void 0):(this.oldest=void 0,this.newest=void 0),a[c]=a[e]=void 0,this._keymap.delete(a.key),--this.size,[a.key,a.value]}find(a){let b=this._keymap.get(a);return b?b.value:void 0}has(a){return this._keymap.has(a)}delete(a){var b=this._keymap.get(a);return b?(this._keymap.delete(b.key),b[c]&&b[e]?(b[e][c]=b[c],b[c][e]=b[e]):b[c]?(b[c][e]=void 0,this.oldest=b[c]):b[e]?(b[e][c]=void 0,this.newest=b[e]):this.oldest=this.newest=void 0,this.size--,b.value):void 0}clear(){this.oldest=this.newest=void 0,this.size=0,this._keymap.clear()}keys(){return new j(this.oldest)}values(){return new k(this.oldest)}entries(){return this}[Symbol.iterator](){return new i(this.oldest)}forEach(a,b){typeof b!="object"&&(b=this);let d=this.oldest;for(;d;)a.call(b,d.value,d.key,this),d=d[c]}toJSON(){for(var a=new Array(this.size),b=0,d=this.oldest;d;)a[b++]={key:d.key,value:d.value},d=d[c];return a}toString(){for(var a="",b=this.oldest;b;)a+=String(b.key)+":"+b.value,b=b[c],b&&(a+=" < ");return a}}g.LRUMap=n;function l(a,b){this.key=a,this.value=b,this[c]=void 0,this[e]=void 0}function i(a){this.entry=a}i.prototype[Symbol.iterator]=function(){return this},i.prototype.next=function(){let a=this.entry;return a?(this.entry=a[c],{done:!1,value:[a.key,a.value]}):{done:!0,value:void 0}};function j(a){this.entry=a}j.prototype[Symbol.iterator]=function(){return this},j.prototype.next=function(){let a=this.entry;return a?(this.entry=a[c],{done:!1,value:a.key}):{done:!0,value:void 0}};function k(a){this.entry=a}k.prototype[Symbol.iterator]=function(){return this},k.prototype.next=function(){let a=this.entry;return a?(this.entry=a[c],{done:!1,value:a.value}):{done:!0,value:void 0}}})})(lru$1,lru$1.exports)),lru$1.exports}var lruExports=requireLru();const LRUMapPkg=getDefaultExportFromCjs(lruExports),HOLE=0,TEXT=1,ELEMENT=2,STRING=4,INTEGER=5,EXTRA=6,PRIMITIVES=[void 0,null,!0,!1];function decodeHastLines(encoded){if(Array.isArray(encoded))return encoded;const{ops,offsets,strings,text,extras}=encoded,lines=new Array(offsets.length/2);let position=0,textPosition=0;function decodeNodes(count){const nodes=new Array(count);for(let index=0;index<count;index++){const kind=ops[position++];if(kind!==HOLE)if(kind===TEXT){const end=textPosition+ops[position++];nodes[index]={type:"text",value:text.slice(textPosition,end)},textPosition=end}else if(kind===ELEMENT){const tagName=strings[ops[position++]],properties={};for(let remaining=ops[position++];remaining>0;remaining--){const key=strings[ops[position++]],type=ops[position++],value=type===STRING?strings[ops[position++]]:type===INTEGER?ops[position++]:type===EXTRA?extras[ops[position++]]:PRIMITIVES[type];key==="__proto__"?Object.defineProperty(properties,key,{value,enumerable:!0,configurable:!0,writable:!0}):properties[key]=value}nodes[index]={type:"element",tagName,properties,children:decodeNodes(ops[position++])}}else nodes[index]=extras[ops[position++]]}return nodes}for(let index=0;index<lines.length;index++)ops[offsets[index*2]]!==HOLE&&setDeferredArrayItem(lines,index,()=>(position=offsets[index*2],textPosition=offsets[index*2+1],decodeNodes(1)[0]),{retain:!1});return lines}const IGNORE_RESPONSE=Symbol("IGNORE_RESPONSE"),DEFAULT_WORKER_INITIALIZATION_TIMEOUT=1e4;var WorkerPoolManager=class{options;preferredHighlighter;renderOptions;renderOptionsRequestVersion=0;renderOptionsVersion=0;initialized=!1;workers=[];queuedTasks=[];queuedTaskByInstance=new Map;taskByHighlightKey=new Map;activeTaskById=new Map;activeRequestByInstance=new Map;nextRequestId=0;themeSubscribers=new Set;workersFailed=!1;terminated=!1;statSubscribers=new Set;fileCache;diffCache;_queuedBroadcast;lifecycleGeneration=0;constructor(options,{langs,theme=DEFAULT_THEMES,useTokenTransformer=!1,lineDiffType="word-alt",maxLineDiffLength=1e3,tokenizeMaxLineLength=1e3,preferredHighlighter}){this.options=options,this.preferredHighlighter=resolveHighlighterType(preferredHighlighter),this.renderOptions={theme,useTokenTransformer,lineDiffType,maxLineDiffLength,tokenizeMaxLineLength},this.fileCache=new LRUMapPkg.LRUMap(options.totalASTLRUCacheSize??100),this.diffCache=new LRUMapPkg.LRUMap(options.totalASTLRUCacheSize??100),this.queueInitialization(langs)}isWorkingPool(){return!this.workersFailed&&!this.terminated}shouldHighlightOnMainThread(fileOrDiff){const{mainThreadMaxCharacters=-1}=this.options;return("contents"in fileOrDiff?fileOrDiff.contents.length:fileOrDiff.deletionCharacterCount+fileOrDiff.additionCharacterCount)<=mainThreadMaxCharacters}getFileResultCache(file){return file.cacheKey!=null?this.fileCache.get(file.cacheKey):void 0}getDiffResultCache(diff){return diff.cacheKey!=null?this.diffCache.get(diff.cacheKey):void 0}setFileResultCache(cacheKey,{result,options}){return cacheKey==null||!areFileRenderOptionsEqual(options,this.getFileRenderOptions())?!1:(this.fileCache.set(cacheKey,{result,options}),this.queueBroadcastStateChanges(),!0)}setDiffResultCache(cacheKey,{result,options}){return cacheKey==null||!areDiffRenderOptionsEqual(options,this.getDiffRenderOptions())?!1:(this.diffCache.set(cacheKey,{result,options}),this.queueBroadcastStateChanges(),!0)}inspectCaches(){const{fileCache,diffCache}=this;return{fileCache,diffCache}}evictFileFromCache(cacheKey){try{return this.fileCache.delete(cacheKey)!==void 0}finally{this.queueBroadcastStateChanges()}}evictDiffFromCache(cacheKey){try{return this.diffCache.delete(cacheKey)!==void 0}finally{this.queueBroadcastStateChanges()}}async setRenderOptions({theme=this.renderOptions.theme??DEFAULT_THEMES,useTokenTransformer=this.renderOptions.useTokenTransformer??!1,lineDiffType=this.renderOptions.lineDiffType??"word-alt",maxLineDiffLength=this.renderOptions.maxLineDiffLength??1e3,tokenizeMaxLineLength=this.renderOptions.tokenizeMaxLineLength??1e3}){const{lifecycleGeneration}=this,renderOptionsRequestVersion=++this.renderOptionsRequestVersion,isCurrentRequest=()=>this.isCurrentLifecycle(lifecycleGeneration)&&this.renderOptionsRequestVersion===renderOptionsRequestVersion;try{const newRenderOptions={theme,useTokenTransformer,lineDiffType,maxLineDiffLength,tokenizeMaxLineLength};if(!this.isInitialized())try{await this.initialize()}catch(error){if(!this.workersFailed)throw error}if(!isCurrentRequest()||areDiffRenderOptionsEqual(newRenderOptions,this.renderOptions))return;const themeNames=getThemes(theme);let resolvedThemes=[];if(areThemesEqual(newRenderOptions.theme,this.renderOptions.theme)||(resolvedThemes=hasResolvedThemes(themeNames,this.preferredHighlighter)?getResolvedThemes(themeNames,this.preferredHighlighter):await resolveThemes(themeNames,this.preferredHighlighter)),!isCurrentRequest()||getHighlighterIfLoaded({theme})==null&&(await this.loadSharedHighlighter(themeNames,["text"]),!isCurrentRequest()))return;const workerSetup=this.setRenderOptionsOnWorkers(newRenderOptions,resolvedThemes);this.renderOptions=newRenderOptions,this.renderOptionsVersion++,this.diffCache.clear(),this.fileCache.clear(),this.invalidateRenderTasks();for(const instance of this.themeSubscribers)instance.onThemeChange();await workerSetup}catch(error){if(error instanceof WorkerPoolTerminatedError||!isCurrentRequest())return;throw error}}getPreferredHighlighter(){return this.preferredHighlighter}getFileRenderOptions(){const{tokenizeMaxLineLength,theme,useTokenTransformer}=this.renderOptions;return{theme,useTokenTransformer,tokenizeMaxLineLength}}getDiffRenderOptions(){return{...this.renderOptions}}async setRenderOptionsOnWorkers(renderOptions,resolvedThemes){if(this.workersFailed)return;this.isInitialized()||await this.initialize();const taskPromises=[];for(const managedWorker of this.workers){if(!managedWorker.initialized)throw console.log({managedWorker}),new Error("setRenderOptionsOnWorkers: Somehow we have an uninitialized worker");taskPromises.push(new Promise((resolve,reject)=>{const id=this.generateRequestId(),task={type:"set-render-options",id,request:{type:"set-render-options",id,renderOptions,resolvedThemes},resolve,reject,requestStart:Date.now()};this.activeTaskById.set(id,task),managedWorker.pendingSetupRequestId=id,managedWorker.worker.postMessage(task.request)}))}await Promise.all(taskPromises)}subscribeToThemeChanges(instance){return this.themeSubscribers.add(instance),this.queueBroadcastStateChanges(),()=>{this.unsubscribeToThemeChanges(instance),this.queueBroadcastStateChanges()}}unsubscribeToThemeChanges(instance){this.themeSubscribers.delete(instance),this.queueBroadcastStateChanges()}subscribeToStatChanges(callback){return this.statSubscribers.add(callback),callback(this.getStats()),()=>{this.statSubscribers.delete(callback)}}queueBroadcastStateChanges(){this._queuedBroadcast==null&&(this._queuedBroadcast=requestAnimationFrame(this._broadcastStateChanges))}_broadcastStateChanges=()=>{this._queuedBroadcast!=null&&(cancelAnimationFrame(this._queuedBroadcast),this._queuedBroadcast=void 0);const stats=this.getStats();for(const callback of this.statSubscribers)callback(stats)};cleanUpTasks(instance){this.detachInstanceFromQueuedTasks(instance);const requestId=this.activeRequestByInstance.get(instance);if(requestId!=null){const task=this.activeTaskById.get(requestId);isRenderTask(task)?(this.detachInstanceFromRenderTask(task,instance),!task.primeCache&&task.instances.size===0&&this.removeActiveTask(task)):this.activeTaskById.delete(requestId)}this.activeRequestByInstance.delete(instance),this.queueBroadcastStateChanges()}isInitialized(){return this.initialized===!0}async initialize(languages=[]){if(this.initialized===!0){getHighlighterIfLoaded({theme:this.renderOptions.theme})==null&&await this.loadSharedHighlighter(getThemes(this.renderOptions.theme),["text",...languages]);return}else if(this.initialized===!1){this.terminated=!1;const{lifecycleGeneration}=this,initialization=new Promise((resolve,reject)=>{(async()=>{try{const themes=getThemes(this.renderOptions.theme),resolvedThemes=hasResolvedThemes(themes,this.preferredHighlighter)?getResolvedThemes(themes,this.preferredHighlighter):await resolveThemes(themes,this.preferredHighlighter);if(!this.isCurrentLifecycle(lifecycleGeneration)){resolve();return}let resolvedLanguages=[];if(this.preferredHighlighter!=="highlights"&&(resolvedLanguages=hasResolvedLanguages(languages)?getResolvedLanguages(languages):await resolveLanguages(languages)),!this.isCurrentLifecycle(lifecycleGeneration)){resolve();return}if(await Promise.all([this.loadSharedHighlighter(themes,["text",...languages]),this.initializeWorkers(resolvedThemes,resolvedLanguages)]),!this.isCurrentLifecycle(lifecycleGeneration)){this.terminateWorkers(),resolve();return}this.initialized=!0,this.drainQueue(),this.queueBroadcastStateChanges(),resolve()}catch(e){if(e instanceof WorkerPoolTerminatedError||!this.isCurrentLifecycle(lifecycleGeneration)){resolve();return}this.initialized=!1,this.workersFailed=!0,this.cancelActiveWorkerTasks(),this.terminateWorkers(),this.activeTaskById.clear();for(const task of this.queuedTasks)this.rejectRenderTaskCallbacks(task,normalizeWorkerError(e));this.queueBroadcastStateChanges(),reject(e)}})()});return this.initialized=initialization,this.queueBroadcastStateChanges(),initialization}else return this.initialized}async loadSharedHighlighter(themes,langs){try{await getSharedHighlighter({themes,langs,preferredHighlighter:this.preferredHighlighter})}catch(error){if(!(error instanceof HighlighterDisposedError))throw error}}async initializeWorkers(resolvedThemes,resolvedLanguages){this.workersFailed=!1;const initPromises=[],customExtensionVersion=getCustomExtensionsVersion(),customExtensionMap=customExtensionVersion>0?getCustomExtensionsMap():void 0;this.workers.length>0&&this.terminateWorkers();for(let i=0;i<(this.options.poolSize??8);i++){const worker=this.options.workerFactory(),managedWorker={worker,requestId:void 0,pendingSetupRequestId:void 0,initialized:!1,langs:new Set(["text",...resolvedLanguages.map(({name})=>name)]),customExtensionsVersion:0};worker.addEventListener("message",event=>{this.handleWorkerMessage(managedWorker,event.data)}),worker.addEventListener("error",error=>this.handleWorkerError(managedWorker,error)),this.workers.push(managedWorker),initPromises.push(new Promise((resolve,reject)=>{const id=this.generateRequestId(),task={type:"initialize",id,request:{type:"initialize",resultFormat:"hast-ops-v1",id,renderOptions:this.renderOptions,preferredHighlighter:this.preferredHighlighter,resolvedThemes,resolvedLanguages,customExtensionsVersion:customExtensionMap!=null?customExtensionVersion:void 0,customExtensionMap},resolve(){managedWorker.initialized=!0,resolve()},reject,requestStart:Date.now()};managedWorker.pendingSetupRequestId=id,this.activeTaskById.set(id,task),this.executeTask(managedWorker,task)}))}const timeoutMs=this.options.workerInitializationTimeout??DEFAULT_WORKER_INITIALIZATION_TIMEOUT;let timeoutId;try{await Promise.race([Promise.all(initPromises),new Promise((_,reject)=>{timeoutId=setTimeout(()=>{reject(new Error(`WorkerPoolManager: worker initialization timed out after ${timeoutMs}ms`))},timeoutMs)})])}finally{timeoutId!=null&&clearTimeout(timeoutId)}}handleWorkerError(managedWorker,event){const{onWorkerError}=this.options;if(onWorkerError!=null)try{onWorkerError(event,managedWorker.worker)}catch(hookError){console.error("WorkerPoolManager: onWorkerError threw:",hookError)}else console.error("Worker error:",event,managedWorker);const{pendingSetupRequestId}=managedWorker;if(pendingSetupRequestId==null)return;const task=this.activeTaskById.get(pendingSetupRequestId);if(task?.type!=="initialize")return;const error=errorFromWorkerErrorEvent(event);onWorkerError!=null&&markWorkerErrorReported(error),task.reject(error),this.cleanWorkerAndTask(managedWorker,task)}drainQueue=()=>{if(this._queuedDrain=void 0,!(this.initialized!==!0||this.queuedTasks.length===0)){for(let i=0;i<this.queuedTasks.length;){const task=this.queuedTasks[i];if(this.hasActiveRequest(task)){i++;continue}const langs=getLangsFromRequest(task.request),availableWorker=this.getAvailableWorker(langs);if(availableWorker==null)break;this.queuedTasks.splice(i,1),this.assignWorkerToTask(task,availableWorker),this.resolveLanguagesAndExecuteTask(availableWorker,task,langs)}this.queueBroadcastStateChanges()}};highlightFileAST(instance,file){const cachedResult=this.getFileResultCache(file);isFilePlainText(file)||cachedResult!=null&&areFileRenderOptionsEqual(cachedResult.options,this.getFileRenderOptions())||this.hasMatchingFileInstanceTask(instance,file)||this.submitTask(instance,{type:"file",file})}primeFileHighlightCache(file){if(!this.isWorkingPool())return Promise.reject(new Error("WorkerPoolManager.primeFileHighlightCache: worker pool is not working"));if(!this.shouldPrimeFileHighlightCache(file))return Promise.resolve();if(this.shouldHighlightOnMainThread(file)){const options=this.getFileRenderOptions();return this.primeHighlightCacheOnMainThread(getLangsFromRequest({type:"file",file}),options.theme,highlighter2=>this.setFileResultCache(file.cacheKey,{result:renderFileWithHighlighter(file,highlighter2,options),options}))}const task=this.getOrCreateFileHighlightCacheTask(file);return task!=null?this.createRenderTaskCallbacks(task):Promise.resolve()}shouldPrimeFileHighlightCache(file){if(file.cacheKey==null)return console.warn(`WorkerPoolManager.primeFileHighlightCache: priming highlight cache requires file.cacheKey; skipping "${file.name}".`),!1;const cachedResult=this.getFileResultCache(file);return!isFilePlainText(file)&&(cachedResult==null||!areFileRenderOptionsEqual(cachedResult.options,this.getFileRenderOptions()))}getOrCreateFileHighlightCacheTask(file){const highlightKey=this.getFileHighlightKey(file);if(highlightKey==null)return;const existingTask=this.getTaskByHighlightKey(highlightKey);if(existingTask!=null){if(existingTask.type!=="file")throw new Error("WorkerPoolManager.getOrCreateFileHighlightCacheTask: Invalid task type");return existingTask.primeCache=!0,existingTask}else{const task=this.submitCacheTask({type:"file",file},highlightKey);if(task.type!=="file")throw new Error("WorkerPoolManager.getOrCreateFileHighlightCacheTask: Invalid task created");return task}}getPlainFileAST(file,startingLine,totalLines,lines){const highlighter2=getHighlighterIfLoaded({theme:this.renderOptions.theme});if(highlighter2==null){this.queueInitialization();return}return renderFileWithHighlighter(file,highlighter2,this.renderOptions,{forcePlainText:!0,startingLine,totalLines,lines})}highlightDiffAST(instance,diff){const cachedResult=this.getDiffResultCache(diff);isDiffPlainText(diff)||cachedResult!=null&&areDiffRenderOptionsEqual(cachedResult.options,this.getDiffRenderOptions())||this.hasMatchingDiffInstanceTask(instance,diff)||this.submitTask(instance,{type:"diff",diff})}primeDiffHighlightCache(diff){if(!this.isWorkingPool())return Promise.reject(new Error("WorkerPoolManager.primeDiffHighlightCache: worker pool is not working"));if(!this.shouldPrimeDiffHighlightCache(diff))return Promise.resolve();if(this.shouldHighlightOnMainThread(diff)){const options=this.getDiffRenderOptions();return this.primeHighlightCacheOnMainThread(getLangsFromRequest({type:"diff",diff}),options.theme,highlighter2=>this.setDiffResultCache(diff.cacheKey,{result:renderDiffWithHighlighter(diff,highlighter2,options),options}))}const task=this.getOrCreateDiffHighlightCacheTask(diff);return task!=null?this.createRenderTaskCallbacks(task):Promise.resolve()}shouldPrimeDiffHighlightCache(diff){if(diff.cacheKey==null)return console.warn(`WorkerPoolManager.primeDiffHighlightCache: priming highlight cache requires diff.cacheKey; skipping "${diff.prevName??diff.name}" -> "${diff.name}".`),!1;const cachedResult=this.getDiffResultCache(diff);return!isDiffPlainText(diff)&&(cachedResult==null||!areDiffRenderOptionsEqual(cachedResult.options,this.getDiffRenderOptions()))}primeHighlightCacheOnMainThread(langs,theme,highlightAndCacheResult){function highlightAndCacheIfLoaded(){const highlighter2=getHighlighterIfLoaded({theme,langs});return highlighter2!=null&&highlightAndCacheResult(highlighter2)}if(highlightAndCacheIfLoaded())return Promise.resolve();const{lifecycleGeneration}=this;return this.loadSharedHighlighter(getThemes(theme),["text",...langs]).then(()=>{if(!this.isCurrentLifecycle(lifecycleGeneration))throw new WorkerPoolTerminatedError;if(!highlightAndCacheIfLoaded())throw new WorkerPoolTaskCanceledError})}getOrCreateDiffHighlightCacheTask(diff){const highlightKey=this.getDiffHighlightKey(diff);if(highlightKey==null)return;const existingTask=this.getTaskByHighlightKey(highlightKey);if(existingTask!=null){if(existingTask.type!=="diff")throw new Error("WorkerPoolManager.getOrCreateDiffHighlightCacheTask: Invalid task type");return existingTask.primeCache=!0,existingTask}else{const task=this.submitCacheTask({type:"diff",diff},highlightKey);if(task.type!=="diff")throw new Error("WorkerPoolManager.getOrCreateDiffHighlightCacheTask: Invalid task created");return task}}getPlainDiffAST(diff,startingLine,totalLines,expandedHunks,collapsedContextThreshold){const highlighter2=getHighlighterIfLoaded({theme:this.renderOptions.theme});if(highlighter2==null){this.queueInitialization();return}return renderDiffWithHighlighter(diff,highlighter2,this.renderOptions,{forcePlainText:!0,startingLine,totalLines,expandedHunks,collapsedContextThreshold})}terminate(){this.lifecycleGeneration++,this.cancelActiveWorkerTasks(),this.terminateWorkers();const error=new WorkerPoolTerminatedError;for(const task of this.queuedTasks)this.rejectRenderTaskCallbacks(task,error);this.fileCache.clear(),this.diffCache.clear(),this.activeRequestByInstance.clear(),this.queuedTasks.length=0,this.queuedTaskByInstance.clear(),this.taskByHighlightKey.clear(),this.activeTaskById.clear(),this.initialized=!1,this.workersFailed=!1,this.terminated=!0,this.queueBroadcastStateChanges()}isCurrentLifecycle(lifecycleGeneration){return this.lifecycleGeneration===lifecycleGeneration}queueInitialization(languages){this.initialize(languages).catch(error=>{isHandledWorkerPoolError(error)||console.error(error)})}cancelActiveWorkerTasks(){const error=new WorkerPoolTerminatedError;for(const task of this.activeTaskById.values())"reject"in task?task.reject(error):isRenderTask(task)&&this.rejectRenderTaskCallbacks(task,error)}terminateWorkers(){for(const managedWorker of this.workers)managedWorker.worker.terminate();this.workers.length=0}getStats(){return{managerState:this.initialized===!1?"waiting":this.initialized!==!0?"initializing":"initialized",totalWorkers:this.workers.length,workersFailed:this.workersFailed,busyWorkers:this.workers.filter(w=>w.requestId!=null||w.pendingSetupRequestId!=null).length,queuedTasks:this.queuedTasks.length,activeTasks:this.activeTaskById.size,themeSubscribers:this.themeSubscribers.size,fileCacheSize:this.fileCache.size,diffCacheSize:this.diffCache.size}}submitTask(instance,request){this.initialized===!1&&this.queueInitialization();const highlightKey=this.getHighlightKeyForRequest(request),existingTask=highlightKey!=null?this.getTaskByHighlightKey(highlightKey):void 0;if(existingTask!=null){this.detachInstanceFromQueuedTasks(instance,existingTask),this.addInstanceToTask(existingTask,instance),this.queueBroadcastStateChanges();return}this.detachInstanceFromQueuedTasks(instance);const id=this.generateRequestId(),requestStart=Date.now(),{renderOptionsVersion}=this,task=(()=>{switch(request.type){case"file":return{type:"file",id,request:{...request,id},instances:new Set([instance]),primeCache:!1,highlightKey,callbacks:new Set,renderOptionsVersion,requestStart};case"diff":return{type:"diff",id,request:{...request,id},instances:new Set([instance]),primeCache:!1,highlightKey,callbacks:new Set,renderOptionsVersion,requestStart}}})();this.enqueueRenderTask(task,instance)}submitCacheTask(request,highlightKey){this.initialized===!1&&this.queueInitialization();const id=this.generateRequestId(),requestStart=Date.now(),{renderOptionsVersion}=this,task=(()=>{switch(request.type){case"file":return{type:"file",id,request:{...request,id},instances:new Set,primeCache:!0,highlightKey,callbacks:new Set,renderOptionsVersion,requestStart};case"diff":return{type:"diff",id,request:{...request,id},instances:new Set,primeCache:!0,highlightKey,callbacks:new Set,renderOptionsVersion,requestStart}}})();return this.enqueueRenderTask(task),task}enqueueRenderTask(task,instance){this.queuedTasks.push(task),instance!=null&&this.queuedTaskByInstance.set(instance,task),task.highlightKey!=null&&this.taskByHighlightKey.set(task.highlightKey,task),this.queueDrain()}async resolveLanguagesAndExecuteTask(availableWorker,task,langs){try{const highlighter2=getHighlighterIfLoaded(),mainThreadLangs=langs.filter(lang=>highlighter2==null||!areLanguagesAttached(lang,highlighter2));mainThreadLangs.length>0&&this.loadSharedHighlighter(getThemes(this.renderOptions.theme),["text",...mainThreadLangs]).catch(error=>{console.error(error)});const workerMissingLangs=this.preferredHighlighter==="highlights"?[]:langs.filter(lang=>!availableWorker.langs.has(lang));if(workerMissingLangs.length>0&&(hasResolvedLanguages(workerMissingLangs)?task.request.resolvedLanguages=getResolvedLanguages(workerMissingLangs):task.request.resolvedLanguages=await resolveLanguages(workerMissingLangs)),!this.activeTaskById.has(task.id)){availableWorker.requestId===task.id&&(this.cleanWorkerAndTask(availableWorker,task),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain());return}this.executeTask(availableWorker,task)}catch(error){this.rejectRenderTaskCallbacks(task,normalizeWorkerError(error)),this.cleanWorkerAndTask(availableWorker,task),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain()}}handleWorkerMessage(managedWorker,response){const task=this.activeTaskById.get(response.id);try{if(task==null)throw IGNORE_RESPONSE;if(response.type==="error"){const error=new Error(response.error);if(response.stack&&(error.stack=response.stack),"reject"in task)task.reject(error);else if(isRenderTask(task))this.notifyHighlightError(task,error),this.rejectRenderTaskCallbacks(task,error);else throw new Error("handleWorkerMessage: unknown task type");throw error}else{if(isRenderTask(task))for(const{name}of task.request.resolvedLanguages??[])managedWorker.langs.add(name);switch(response.requestType){case"initialize":if(task.type!=="initialize")throw new Error("handleWorkerMessage: task/response dont match");this.syncCustomExtensionVersion(managedWorker,task.request),task.resolve();break;case"set-render-options":if(task.type!=="set-render-options")throw new Error("handleWorkerMessage: task/response dont match");task.resolve();break;case"file":{if(task.type!=="file")throw new Error("handleWorkerMessage: task/response dont match");const{options}=response;if(!this.isCurrentRenderTask(task)||!areFileRenderOptionsEqual(options,this.getFileRenderOptions()))throw IGNORE_RESPONSE;const{request}=task,result={...response.result,code:decodeHastLines(response.result.code)};this.syncCustomExtensionVersion(managedWorker,request),task.cacheKeyAtDispatch!=null&&this.fileCache.set(task.cacheKeyAtDispatch,{result,options}),this.resolveRenderTaskCallbacks(task),this.notifyFileInstances(task,result,options);break}case"diff":{if(task.type!=="diff")throw new Error("handleWorkerMessage: task/response dont match");const{options}=response;if(!this.isCurrentRenderTask(task)||!areDiffRenderOptionsEqual(options,this.getDiffRenderOptions()))throw IGNORE_RESPONSE;const{request}=task,result={...response.result,code:{deletionLines:decodeHastLines(response.result.code.deletionLines),additionLines:decodeHastLines(response.result.code.additionLines)}};this.syncCustomExtensionVersion(managedWorker,request),task.cacheKeyAtDispatch!=null&&this.diffCache.set(task.cacheKeyAtDispatch,{result,options}),this.resolveRenderTaskCallbacks(task),this.notifyDiffInstances(task,result,options);break}}}}catch(error){error!==IGNORE_RESPONSE&&console.error(error,task,response)}this.cleanWorkerAndTask(managedWorker,task,response.id),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain()}_queuedDrain;queueDrain(){this._queuedDrain==null&&(this._queuedDrain=Promise.resolve().then(this.drainQueue),this.queueBroadcastStateChanges())}assignWorkerToTask(task,managedWorker){managedWorker.requestId=task.id,isRenderTask(task)&&(this.clearQueuedInstanceRequests(task),this.trackInstanceRequests(task)),this.activeTaskById.set(task.id,task)}cleanWorkerAndTask(managedWorker,task,requestId=task?.id){managedWorker.requestId===requestId&&(managedWorker.requestId=void 0),managedWorker.pendingSetupRequestId===requestId&&(managedWorker.pendingSetupRequestId=void 0),task!=null&&(isRenderTask(task)&&(this.rejectRenderTaskCallbacks(task,new WorkerPoolTaskCanceledError),this.clearInstanceRequests(task),this.clearHighlightKey(task)),this.activeTaskById.delete(task.id))}executeTask(managedWorker,task){shouldSyncCustomExtensions(task.request)&&this.maybeAttachCustomExtensions(managedWorker,task.request),this.activeTaskById.has(task.id)||this.assignWorkerToTask(task,managedWorker);try{task.type==="file"?task.cacheKeyAtDispatch=task.request.file.cacheKey:task.type==="diff"&&(task.cacheKeyAtDispatch=task.request.diff.cacheKey),managedWorker.worker.postMessage(task.request)}catch(error){console.error("Failed to post message to worker:",error),isRenderTask(task)?(this.notifyHighlightError(task,error),this.rejectRenderTaskCallbacks(task,normalizeWorkerError(error))):"reject"in task&&task.reject(error),this.cleanWorkerAndTask(managedWorker,task),this.queuedTasks.length>0&&this.queueDrain()}this.queueBroadcastStateChanges()}maybeAttachCustomExtensions(managedWorker,request){if(request.customExtensionsVersion!=null)return;const version=getCustomExtensionsVersion();managedWorker.customExtensionsVersion>=version||(request.customExtensionsVersion=version,request.customExtensionMap=getCustomExtensionsMap())}syncCustomExtensionVersion(managedWorker,request){request.customExtensionsVersion!=null&&(managedWorker.customExtensionsVersion=request.customExtensionsVersion)}getAvailableWorker(langs){let worker;for(const managedWorker of this.workers){if(managedWorker.requestId!=null||managedWorker.pendingSetupRequestId!=null||!managedWorker.initialized)continue;if(worker=managedWorker,langs.length===0)break;let hasEveryLang=!0;for(const lang of langs)if(!managedWorker.langs.has(lang)){hasEveryLang=!1;break}if(hasEveryLang)break}return worker}getFileHighlightKey(file){if(file.cacheKey!=null)return`file:${file.cacheKey}:${this.renderOptionsVersion}`}getDiffHighlightKey(diff){if(diff.cacheKey!=null)return`diff:${diff.cacheKey}:${this.renderOptionsVersion}`}getHighlightKeyForRequest(request){switch(request.type){case"file":return this.getFileHighlightKey(request.file);case"diff":return this.getDiffHighlightKey(request.diff)}}hasActiveRequest(task){for(const instance of getInstances(task))if(this.activeRequestByInstance.has(instance))return!0;return!1}addInstanceToTask(task,instance){task.type,task.instances.add(instance),this.activeTaskById.has(task.id)?this.activeRequestByInstance.set(instance,task.id):this.queuedTaskByInstance.set(instance,task)}detachInstanceFromQueuedTasks(instance,exceptTask){const task=this.queuedTaskByInstance.get(instance);task==null||task===exceptTask||(this.queuedTaskByInstance.delete(instance),this.detachInstanceFromRenderTask(task,instance),!task.primeCache&&task.instances.size===0&&this.removeQueuedTask(task))}detachInstanceFromRenderTask(task,instance){task.type,task.instances.delete(instance)}removeQueuedTask(task){const index=this.queuedTasks.indexOf(task);index!==-1&&this.queuedTasks.splice(index,1),this.rejectRenderTaskCallbacks(task,new WorkerPoolTaskCanceledError),this.clearQueuedInstanceRequests(task),this.clearHighlightKey(task)}removeActiveTask(task){this.rejectRenderTaskCallbacks(task,new WorkerPoolTaskCanceledError),this.clearInstanceRequests(task),this.clearHighlightKey(task),this.activeTaskById.delete(task.id)}createRenderTaskCallbacks(task){return new Promise((resolve,reject)=>{task.callbacks.add({resolve,reject})})}resolveRenderTaskCallbacks(task){for(const callbacks of task.callbacks)callbacks.resolve();task.callbacks.clear()}rejectRenderTaskCallbacks(task,error){for(const callbacks of task.callbacks)callbacks.reject(error);task.callbacks.clear()}invalidateRenderTasks(){for(let index=this.queuedTasks.length-1;index>=0;index--){const task=this.queuedTasks[index];task.renderOptionsVersion!==this.renderOptionsVersion&&this.removeQueuedTask(task)}for(const task of Array.from(this.activeTaskById.values()))isRenderTask(task)&&task.renderOptionsVersion!==this.renderOptionsVersion&&this.removeActiveTask(task)}clearQueuedInstanceRequests(task){for(const instance of getInstances(task))this.queuedTaskByInstance.get(instance)===task&&this.queuedTaskByInstance.delete(instance)}clearHighlightKey(task){task.highlightKey!=null&&this.taskByHighlightKey.get(task.highlightKey)===task&&this.taskByHighlightKey.delete(task.highlightKey)}trackInstanceRequests(task){for(const instance of getInstances(task))this.activeRequestByInstance.set(instance,task.id)}clearInstanceRequests(task){for(const instance of getInstances(task))this.activeRequestByInstance.get(instance)===task.id&&this.activeRequestByInstance.delete(instance)}notifyFileInstances(task,result,options){for(const instance of task.instances)this.activeRequestByInstance.get(instance)===task.id&&instance.onHighlightSuccess(task.request.file,result,options)}notifyDiffInstances(task,result,options){for(const instance of task.instances)this.activeRequestByInstance.get(instance)===task.id&&instance.onHighlightSuccess(task.request.diff,result,options)}notifyHighlightError(task,error){for(const instance of getInstances(task))this.activeRequestByInstance.get(instance)===task.id&&instance.onHighlightError(error)}hasMatchingFileInstanceTask(instance,file){for(const task of this.iterateRenderTasks())if(task.type==="file"&&this.isCurrentRenderTask(task)&&task.instances.has(instance)&&areFilesEqual(file,task.request.file))return!0;return!1}hasMatchingDiffInstanceTask(instance,diff){for(const task of this.iterateRenderTasks())if(task.type==="diff"&&this.isCurrentRenderTask(task)&&task.instances.has(instance)&&areDiffTargetsEqual(task.request.diff,diff))return!0;return!1}getTaskByHighlightKey(highlightKey){const task=this.taskByHighlightKey.get(highlightKey);return task!=null&&this.isCurrentRenderTask(task)?task:void 0}isCurrentRenderTask(task){return task.renderOptionsVersion===this.renderOptionsVersion}*iterateRenderTasks(){for(const task of this.queuedTasks)yield task;for(const task of this.activeTaskById.values())isRenderTask(task)&&(yield task)}generateRequestId(){return`req_${++this.nextRequestId}`}};function shouldSyncCustomExtensions(request){return request.type==="initialize"||request.type==="file"||request.type==="diff"}function getLangsFromRequest(request){const langs=new Set;switch(request.type){case"file":langs.add(request.file.lang??getFiletypeFromFileName(request.file.name));break;case"diff":langs.add(request.diff.lang??getFiletypeFromFileName(request.diff.name)),langs.add(request.diff.lang??getFiletypeFromFileName(request.diff.prevName??"-"))}return langs.delete("text"),Array.from(langs)}function isRenderTask(task){return task?.type==="file"||task?.type==="diff"}function getInstances(task){return task.instances}function normalizeWorkerError(error){if(error instanceof Error)return error;if(error!=null&&typeof error=="object"){if("error"in error&&error.error instanceof Error)return error.error;if("message"in error&&typeof error.message=="string")return new Error(error.message)}return new Error(String(error))}function errorFromWorkerErrorEvent(event){const cause="error"in event?event.error:void 0,message="message"in event&&typeof event.message=="string"&&event.message!==""?event.message:cause instanceof Error?cause.message:"the worker script failed to load (the error event carries no message)";return new WorkerPoolWorkerError(`WorkerPoolManager: worker failed: ${message}`,cause instanceof Error?{cause}:void 0)}let workerPoolSingleton;function getOrCreateWorkerPoolSingleton({poolOptions,highlighterOptions}){return workerPoolSingleton??=new WorkerPoolManager(poolOptions,highlighterOptions),workerPoolSingleton}function terminateWorkerPoolSingleton(){workerPoolSingleton!=null&&(workerPoolSingleton.terminate(),workerPoolSingleton=void 0)}const WorkerPoolContext=reactExports.createContext(void 0);let instanceCount=0;function WorkerPoolContextProvider({children,poolOptions,highlighterOptions}){const[poolManager]=reactExports.useState(()=>{if(!(typeof window>"u"))return getOrCreateWorkerPoolSingleton({poolOptions,highlighterOptions})});return reactExports.useInsertionEffect(()=>{if(poolManager!=null)return instanceCount++,()=>{instanceCount--}},[poolManager]),reactExports.useEffect(()=>()=>{instanceCount===0&&terminateWorkerPoolSingleton()},[]),jsxRuntimeExports.jsx(WorkerPoolContext.Provider,{value:poolManager,children})}function useWorkerPool(){return reactExports.useContext(WorkerPoolContext)}const DIFFS_HOST_STYLE={"--diffs-bg-context-override":"var(--zg-bg)","--diffs-bg-context-gutter-override":"var(--zg-bg)","--diffs-bg-separator-override":"var(--zg-tray)","--diffs-bg-buffer-override":"var(--zg-bg)","--diffs-bg-hover-override":"var(--zg-row-hover)","--diffs-bg-addition-override":"var(--zg-diff-add-bg)","--diffs-bg-addition-emphasis-override":"var(--zg-diff-add-content-bg)","--diffs-bg-addition-number-override":"var(--zg-diff-add-bg)","--diffs-bg-deletion-override":"var(--zg-diff-remove-bg)","--diffs-bg-deletion-emphasis-override":"var(--zg-diff-remove-content-bg)","--diffs-bg-deletion-number-override":"var(--zg-diff-remove-bg)","--diffs-fg-number-override":"var(--zg-text-subtle)","--diffs-editor-selection-bg":"color-mix(in srgb, var(--zg-accent) 28%, transparent)","--diffs-fg-number-addition-override":"var(--zg-diff-add-fg)","--diffs-fg-number-deletion-override":"var(--zg-diff-remove-fg)","--diffs-bg-selection-override":"var(--zg-accent-soft)","--diffs-bg-selection-number-override":"var(--zg-accent-soft-strong)","--diffs-annotation-bg":"var(--zg-tray)","--diffs-font-family":"var(--zg-font-mono)","--diffs-header-font-family":"var(--zg-font-ui)","--diffs-font-size":"var(--zg-font-size-code)","--diffs-line-height":"calc(var(--zg-font-size-code) * 1.65)"},PREFERRED_HIGHLIGHTER="highlights",VIRTUALIZER_CONFIG={overscrollSize:600,intersectionObserverMargin:1200},DIFFS_UNSAFE_CSS=`
|
|
8
8
|
/* One hover surface: findings ride in our HoverCard; keep pierre's squiggles, drop its popover. */
|
|
9
9
|
[data-marker-popover] { display: none !important; }
|
|
10
10
|
[data-diffs-header] {
|