@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
138 lines • 519 kB
JavaScript
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
import{__export}from"./chunk-IKOFCODM.js";function parseTmuxKittyTerminalOverride(raw){return raw==="kitty"||raw==="ghostty"||raw==="warp"?raw:void 0}function identityForTerminal(terminal){return{terminal,placement:terminal==="warp"?"direct":"placeholder"}}function identifyTmuxKittyClient(clientTermname,override){if(override)return identityForTerminal(override);let term=clientTermname.trim().toLowerCase();return term.includes("kitty")?identityForTerminal("kitty"):term.includes("ghostty")?identityForTerminal("ghostty"):term.includes("warp")?identityForTerminal("warp"):null}function topologyReason(state){return state.supportTier==="unsupported"?"unsupported-version":state.nested?"nested":state.clientCount!==1?"multiple-clients":state.focusEvents?state.allowPassthrough==="off"?"passthrough-off":null:"focus-events-off"}function decideTmuxImageCapability(state,override){if(state.kind==="outside")return{enabled:!1,reason:"outside-tmux"};if(state.kind==="unavailable")return{enabled:!1,reason:"probe-unavailable"};let topology=topologyReason(state);if(topology)return{enabled:!1,reason:topology};if(!state.visible)return{enabled:!1,reason:"hidden"};let identity=identifyTmuxKittyClient(state.clientTermname,override);return identity?identity.placement==="direct"&&state.allowPassthrough!=="on"?{enabled:!1,reason:"unsafe-direct-placement"}:{enabled:!0,placement:identity.placement,terminal:identity.terminal}:{enabled:!1,reason:"unknown-client"}}import{execFileSync}from"node:child_process";var TMUX_IMAGE_FORMAT="#{version}|#{allow-passthrough}|#{focus-events}|#{pane_active}|#{window_active}|#{session_attached}|#{client_termname}|#{client_cell_width}|#{client_cell_height}|#{client_termfeatures}",DISABLED_STATE={supportTier:"unsupported",allowPassthrough:"off",focusEvents:!1,paneActive:!1,windowActive:!1,visible:!1,clientCount:0,clientTermname:"",nested:!1,hyperlinks:!1};function defaultExecFile(file,args){return execFileSync(file,[...args],{encoding:"utf8",timeout:250,stdio:["ignore","pipe","ignore"]})}function parseTmuxVersion(version){let match=/^(?:next-)?(\d+)\.(\d+)/.exec(version.trim());if(!match)return null;let major=Number.parseInt(match[1]??"",10),minor=Number.parseInt(match[2]??"",10);return Number.isFinite(major)&&Number.isFinite(minor)?[major,minor]:null}function tmuxSupportTier(version){let parsed=parseTmuxVersion(version);if(!parsed)return"unsupported";let[major,minor]=parsed;return major>3||major===3&&minor>=4?"on-and-all":major===3&&minor===3?"on-only":"unsupported"}function normalizeTmuxAllowPassthrough(raw,supportTier){if(supportTier==="unsupported")return"off";let value=raw.trim().toLowerCase();return value==="1"||value==="on"?"on":value==="all"&&supportTier==="on-and-all"?"all":"off"}function parseBoolean(raw){let value=raw.trim().toLowerCase();return value==="1"||value==="on"}function parsePositiveInteger(raw){if(!/^\d+$/.test(raw))return;let value=Number.parseInt(raw,10);return value>0?value:void 0}function parseClientCount(raw){return/^\d+$/.test(raw)?Number.parseInt(raw,10):0}function isNestedClient(clientTermname){let term=clientTermname.trim().toLowerCase();return term.startsWith("tmux")||term.startsWith("screen")}function parseTmuxImageState(output){let fields=output.trim().split("|");if(fields.length!==10)return{kind:"unavailable",reason:"malformed-output",...DISABLED_STATE};let[version="",rawAllow="",rawFocusEvents="",rawPaneActive="",rawWindowActive="",rawClientCount="",rawClientTermname="",rawCellWidth="",rawCellHeight="",rawTermfeatures=""]=fields,supportTier=tmuxSupportTier(version),clientCount=parseClientCount(rawClientCount),paneActive=parseBoolean(rawPaneActive),windowActive=parseBoolean(rawWindowActive),clientTermname=rawClientTermname.trim(),widthPx=parsePositiveInteger(rawCellWidth),heightPx=parsePositiveInteger(rawCellHeight),cellDimensions2=widthPx&&heightPx?{widthPx,heightPx}:void 0;return{kind:"tmux",version:version.trim(),supportTier,allowPassthrough:normalizeTmuxAllowPassthrough(rawAllow,supportTier),focusEvents:parseBoolean(rawFocusEvents),paneActive,windowActive,visible:paneActive&&windowActive&&clientCount===1,clientCount,clientTermname,nested:isNestedClient(clientTermname),hyperlinks:rawTermfeatures.split(",").map(feature=>feature.trim()).includes("hyperlinks"),...cellDimensions2?{cellDimensions:cellDimensions2}:{}}}function probeTmuxImageState(env=process.env,execFile2=defaultExecFile){let term=env.TERM?.toLowerCase()??"";if(!env.TMUX&&!term.startsWith("tmux"))return{kind:"outside",...DISABLED_STATE};let pane=env.TMUX_PANE,args=["display-message","-p"];pane&&/^%\d+$/.test(pane)&&args.push("-t",pane),args.push(TMUX_IMAGE_FORMAT);try{return parseTmuxImageState(execFile2("tmux",args))}catch{return{kind:"unavailable",reason:"probe-failed",...DISABLED_STATE}}}var MIN_WEZTERM_WINDOWS_IMAGES_VERSION="20250208-160106",WEZTERM_WINDOWS_IMAGES_HINT="update WezTerm to a nightly build to show images inline",WEZTERM_VERSION=/^(\d{8})-(\d{6})-[0-9a-f]+/i;function isOldWindowsWezTerm(version,platform){if(platform!=="win32"||version===void 0)return!1;let match=WEZTERM_VERSION.exec(version);return match?`${match[1]}-${match[2]}`<MIN_WEZTERM_WINDOWS_IMAGES_VERSION:!1}function isVsCodeTerminal(env=process.env){let termProgram=(env.TERM_PROGRAM??"").toLowerCase();return termProgram==="vscode"||termProgram===""&&!!env.VSCODE_IPC_HOOK_CLI}function outerKittyGraphicsMode(clientTermname){let term=clientTermname.trim().toLowerCase();return term.includes("kitty")||term.includes("ghostty")||term.includes("warp")?"placeholder":null}function detectTerminalCapabilities(env=process.env,platform=process.platform,execTmux){let term=env.TERM??"",termProgram=(env.TERM_PROGRAM??"").toLowerCase(),terminalEmulator=env.TERMINAL_EMULATOR??"",colorTerm=env.COLORTERM??"",trueColor=colorTerm==="truecolor"||colorTerm==="24bit"||term.toLowerCase().endsWith("-direct");if(env.TMUX||term.startsWith("tmux")){let state=probeTmuxImageState(env,execTmux),override=parseTmuxKittyTerminalOverride(env.PI_TUI_TMUX_KITTY_TERMINAL),decision=decideTmuxImageCapability(state,override);return{images:decision.enabled?"kitty":null,trueColor,hyperlinks:state.hyperlinks,...decision.enabled?{tmuxPassthrough:!0}:{},...decision.enabled&&decision.placement==="placeholder"?{kittyUnicodePlaceholders:!0}:{},...state.cellDimensions?{cellDimensions:state.cellDimensions}:{}}}return env.KITTY_WINDOW_ID?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="ghostty"?{images:"kitty",trueColor:!0,hyperlinks:!0,kittyUnicodePlaceholders:!0}:env.WARP_SESSION_ID||env.WARP_TERMINAL_SESSION_UUID||termProgram==="warpterminal"?{images:"kitty",trueColor:!0,hyperlinks:!0}:env.WEZTERM_PANE||termProgram==="wezterm"?isOldWindowsWezTerm(env.TERM_PROGRAM_VERSION,platform)?{images:null,trueColor:!0,hyperlinks:!0,imageHint:WEZTERM_WINDOWS_IMAGES_HINT}:{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="iterm.app"||env.ITERM_SESSION_ID?{images:"iterm2",trueColor:!0,hyperlinks:!0}:termProgram==="apple_terminal"?{images:null,trueColor:!1,hyperlinks:!0}:env.WT_SESSION?{images:null,trueColor:!0,hyperlinks:!0}:term.startsWith("screen")?{images:null,trueColor,hyperlinks:!1}:env.CMUX_WORKSPACE_ID||terminalEmulator.includes("JetBrains")?{images:null,trueColor:!0,hyperlinks:!1}:isVsCodeTerminal(env)?{images:null,trueColor:!0,hyperlinks:!0}:platform==="win32"?{images:null,trueColor:!0,hyperlinks:!1}:{images:term==="xterm-kitty"?"kitty":null,trueColor,hyperlinks:!1}}import{homedir}from"node:os";var TERMINAL_ESCAPE_PATTERN=/(?:\u001B\][\s\S]*?(?:\u0007|\u001B\\|\u009C))|[\u001B\u009B][[\]()#;?]*(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]/g;function sanitizeTerminalLabel(value){return value.replace(TERMINAL_ESCAPE_PATTERN,"").replace(/[\u0000-\u001f\u007f-\u009f]+/g," ").replace(/\s+/g," ").trim()}function shortenImagePath(filename){let home=homedir();return home&&(filename===home||filename.startsWith(`${home}/`)||filename.startsWith(`${home}\\`))?`~${filename.slice(home.length)}`:filename}import{execSync}from"node:child_process";import{isAbsolute}from"node:path";import{pathToFileURL}from"node:url";var cachedCapabilities=null,capabilityOverrides={},probedImageProtocol,cellDimensions={widthPx:9,heightPx:18};function getCellDimensions(){return cellDimensions}function setCellDimensions(dims){cellDimensions=dims}function probeTmuxHyperlinks(){try{return execSync("tmux display-message -p '#{client_termfeatures}'",{encoding:"utf8",timeout:250,stdio:["ignore","pipe","ignore"]}).split(",").map(feature=>feature.trim()).includes("hyperlinks")}catch{return!1}}function detectCapabilitiesFromEnvironment(tmuxForwardsHyperlink){let termProgram=process.env.TERM_PROGRAM?.toLowerCase()||"",terminalEmulator=process.env.TERMINAL_EMULATOR?.toLowerCase()||"",term=process.env.TERM?.toLowerCase()||"",colorTerm=process.env.COLORTERM?.toLowerCase()||"",hasTrueColorHint=colorTerm==="truecolor"||colorTerm==="24bit"||term.endsWith("-direct"),isWindowsConsole=process.platform==="win32";return process.env.TMUX||term.startsWith("tmux")?{images:null,trueColor:hasTrueColorHint,hyperlinks:tmuxForwardsHyperlink()}:term.startsWith("screen")?{images:null,trueColor:hasTrueColorHint,hyperlinks:!1}:process.env.KITTY_WINDOW_ID||termProgram==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="ghostty"||term.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.WEZTERM_PANE||termProgram==="wezterm"?isOldWindowsWezTerm(process.env.TERM_PROGRAM_VERSION,process.platform)?{images:null,trueColor:!0,hyperlinks:!0,imageHint:WEZTERM_WINDOWS_IMAGES_HINT}:{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="warpterminal"||process.env.WARP_SESSION_ID||process.env.WARP_TERMINAL_SESSION_UUID?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.ITERM_SESSION_ID||termProgram==="iterm.app"?{images:"iterm2",trueColor:!0,hyperlinks:!0}:process.env.WT_SESSION?{images:null,trueColor:!0,hyperlinks:!0}:termProgram==="alacritty"||termProgram==="zed"?{images:null,trueColor:!0,hyperlinks:!0}:terminalEmulator==="jetbrains-jediterm"?{images:null,trueColor:!0,hyperlinks:!1}:termProgram==="herdr"||process.env.HERDR_ENV==="1"?{images:probedImageProtocol??null,trueColor:hasTrueColorHint,hyperlinks:!1,...probedImageProtocol===void 0?{imageProbe:"kitty"}:{}}:isVsCodeTerminal(process.env)?{images:null,trueColor:!0,hyperlinks:!0}:isWindowsConsole?{images:null,trueColor:!0,hyperlinks:!1}:{images:null,trueColor:hasTrueColorHint,hyperlinks:!1}}function parseBooleanCapabilityOverride(value){return value==="1"?!0:value==="0"?!1:void 0}function setProbedImageProtocol(protocol){probedImageProtocol!==protocol&&(probedImageProtocol=protocol,cachedCapabilities=null)}function withoutImageHint(caps){let{imageHint:_imageHint,imageProbe:_imageProbe,...rest}=caps;return rest}function detectCapabilities(tmuxForwardsHyperlink,tmuxPassthroughState){if(!tmuxForwardsHyperlink||!tmuxPassthroughState){let hyperlinks2=parseBooleanCapabilityOverride(process.env.PI_HYPERLINKS),detected2=detectCapabilitiesFromEnvironment(hyperlinks2===void 0?probeTmuxHyperlinks:()=>hyperlinks2),imageProtocol=process.env.PI_IMAGE_PROTOCOL?.toLowerCase(),images=imageProtocol==="kitty"||imageProtocol==="iterm2"?imageProtocol:imageProtocol==="none"||imageProtocol==="0"?null:void 0,trueColor=parseBooleanCapabilityOverride(process.env.PI_TRUE_COLOR);return{...images!==void 0?withoutImageHint(detected2):detected2,...images!==void 0?{images}:{},...trueColor!==void 0?{trueColor}:{},...hyperlinks2!==void 0?{hyperlinks:hyperlinks2}:{}}}let legacy=tmuxPassthroughState(),hyperlinks=tmuxForwardsHyperlink(),detected=detectTerminalCapabilities({...process.env,TMUX:process.env.TMUX??"compat,0,0"},process.platform,()=>["3.4",legacy.allowPassthrough,"on","1","1","1",legacy.clientTermname,legacy.cellWidthPx??"",legacy.cellHeightPx??"",hyperlinks?"hyperlinks":""].join("|"));return detected.cellDimensions&&setCellDimensions(detected.cellDimensions),{...detected,hyperlinks}}function getCapabilities(){if(!cachedCapabilities){let hyperlinks=capabilityOverrides.hyperlinks,detected=detectCapabilities(hyperlinks===void 0?void 0:()=>hyperlinks);cachedCapabilities={...capabilityOverrides.images!==void 0?withoutImageHint(detected):detected,...capabilityOverrides}}return cachedCapabilities}function getTerminalColorMode(capabilities=getCapabilities()){return capabilities.trueColor?"truecolor":"256color"}function resetCapabilitiesCache(){cachedCapabilities=null}function setCapabilityOverrides(overrides){capabilityOverrides.images===overrides.images&&capabilityOverrides.trueColor===overrides.trueColor&&capabilityOverrides.hyperlinks===overrides.hyperlinks&&capabilityOverrides.imageHint===overrides.imageHint||(capabilityOverrides={...overrides},cachedCapabilities=null)}function setCapabilities(caps){cachedCapabilities=caps}var KITTY_PREFIX="\x1B_G",ITERM2_PREFIX="\x1B]1337;File=";function wrapTmuxPassthrough(sequence){return`\x1BPtmux;${sequence.replaceAll("\x1B","\x1B\x1B")}\x1B\\`}function isImageLine(line){return line.startsWith(KITTY_PREFIX)||line.startsWith(ITERM2_PREFIX)?!0:line.includes(KITTY_PREFIX)||line.includes(ITERM2_PREFIX)}function allocateImageId(){return Math.floor(Math.random()*4294967294)+1}function encodeKitty(base64Data,options={}){let params=["a=T","f=100","q=2"];options.virtual?params.push("U=1"):options.moveCursor===!1&¶ms.push("C=1"),options.columns&¶ms.push(`c=${options.columns}`),options.rows&¶ms.push(`r=${options.rows}`),options.imageId&¶ms.push(`i=${options.imageId}`);let chunks=[];if(base64Data.length<=4096)chunks.push(`\x1B_G${params.join(",")};${base64Data}\x1B\\`);else{let offset=0,isFirst=!0;for(;offset<base64Data.length;){let chunk=base64Data.slice(offset,offset+4096),isLast=offset+4096>=base64Data.length;isFirst?(chunks.push(`\x1B_G${params.join(",")},m=1;${chunk}\x1B\\`),isFirst=!1):isLast?chunks.push(`\x1B_Gm=0;${chunk}\x1B\\`):chunks.push(`\x1B_Gm=1;${chunk}\x1B\\`),offset+=4096}}return getCapabilities().tmuxPassthrough?chunks.map(wrapTmuxPassthrough).join(""):chunks.join("")}var KITTY_PLACEHOLDER=String.fromCodePoint(1109742),KITTY_PLACEHOLDER_DIACRITICS=[773,781,782,784,786,829,830,831,838,842,843,844,848,849,850,855,859,867,868,869,870,871,872,873,874,875,876,877,878,879,1155,1156,1157,1158,1159,1426,1427,1428,1429,1431,1432,1433,1436,1437,1438,1439,1440,1441,1448,1449,1451,1452,1455,1476,1552,1553,1554,1555,1556,1557,1558,1559,1623,1624,1625,1626,1627,1629,1630,1750,1751,1752,1753,1754,1755,1756,1759,1760,1761,1762,1764,1767,1768,1771,1772,1840,1842,1843,1845,1846,1850,1853,1855,1856,1857,1859,1861,1863,1865,1866,2027,2028,2029,2030,2031,2032,2033,2035,2070,2071,2072,2073,2075,2076,2077,2078,2079,2080,2081,2082,2083,2085,2086,2087,2089,2090,2091,2092,2093,2385,2387,2388,3970,3971,3974,3975,4957,4958,4959,6109,6458,6679,6773,6774,6775,6776,6777,6778,6779,6780,7019,7021,7022,7023,7024,7025,7026,7027,7376,7377,7378,7386,7387,7392,7616,7617,7619,7620,7621,7622,7623,7624,7625,7627,7628,7633,7634,7635,7636,7637,7638,7639,7640,7641,7642,7643,7644,7645,7646,7647,7648,7649,7650,7651,7652,7653,7654,7678,8400,8401,8404,8405,8406,8407,8411,8412,8417,8423,8425,8432,11503,11504,11505,11744,11745,11746,11747,11748,11749,11750,11751,11752,11753,11754,11755,11756,11757,11758,11759,11760,11761,11762,11763,11764,11765,11766,11767,11768,11769,11770,11771,11772,11773,11774,11775,42607,42620,42621,42736,42737,43232,43233,43234,43235,43236,43237,43238,43239,43240,43241,43242,43243,43244,43245,43246,43247,43248,43249,43696,43698,43699,43703,43704,43710,43711,43713,65056,65057,65058,65059,65060,65061,65062,68111,68152,119173,119174,119175,119176,119177,119210,119211,119212,119213,119362,119363,119364],KITTY_PLACEHOLDER_MAX=KITTY_PLACEHOLDER_DIACRITICS.length;function buildKittyPlaceholderRow(imageId,row,columns){let rowDiacritic=String.fromCodePoint(KITTY_PLACEHOLDER_DIACRITICS[Math.min(row,KITTY_PLACEHOLDER_MAX-1)]),idHighByte=imageId>>>24&255,idDiacritic=idHighByte>0?String.fromCodePoint(KITTY_PLACEHOLDER_DIACRITICS[idHighByte]):"",r=imageId>>>16&255,g=imageId>>>8&255,b2=imageId&255,cells="";for(let column=0;column<columns;column++){let columnDiacritic=String.fromCodePoint(KITTY_PLACEHOLDER_DIACRITICS[Math.min(column,KITTY_PLACEHOLDER_MAX-1)]);cells+=KITTY_PLACEHOLDER+rowDiacritic+columnDiacritic+idDiacritic}return`\x1B[38;2;${r};${g};${b2}m${cells}\x1B[39m`}function deleteKittyImage(imageId){let sequence=`\x1B_Ga=d,d=I,i=${imageId},q=2\x1B\\`;return getCapabilities().tmuxPassthrough?wrapTmuxPassthrough(sequence):sequence}function deleteAllKittyImages(){let sequence="\x1B_Ga=d,d=A,q=2\x1B\\";return getCapabilities().tmuxPassthrough?wrapTmuxPassthrough(sequence):sequence}function deleteAllKittyPlacements(){return"\x1B_Ga=d,d=a,q=2\x1B\\"}function encodeITerm2(base64Data,options={}){let params=[`inline=${options.inline!==!1?1:0}`,`size=${Buffer.byteLength(base64Data,"base64")}`];if(options.width!==void 0&¶ms.push(`width=${options.width}`),options.height!==void 0&¶ms.push(`height=${options.height}`),options.name){let nameBase64=Buffer.from(options.name).toString("base64");params.push(`name=${nameBase64}`)}return options.preserveAspectRatio===!1&¶ms.push("preserveAspectRatio=0"),`\x1B]1337;File=${params.join(";")}:${base64Data}\x07`}var kittyImageMetadata=new Map,kittyTransmissionGeneration=0;function registerKittyImageMetadata(metadata){if(kittyTransmissionGeneration+=1,kittyImageMetadata.delete(metadata.imageId),kittyImageMetadata.set(metadata.imageId,{...metadata,transmissionGeneration:kittyTransmissionGeneration}),kittyImageMetadata.size>1e3){let oldestImageId=kittyImageMetadata.keys().next().value;oldestImageId!==void 0&&kittyImageMetadata.delete(oldestImageId)}}function getRegisteredKittyImageMetadata(line){let controls=/\x1b_G([^;]*);/.exec(line)?.[1];if(!controls)return;let imageId=/(?:^|,)i=(\d+)(?:,|$)/.exec(controls)?.[1];return imageId===void 0?void 0:kittyImageMetadata.get(Number.parseInt(imageId,10))}function getKittyImageMetadata(line){let metadata=getRegisteredKittyImageMetadata(line);if(metadata)return{imageId:metadata.imageId,columns:metadata.columns,rows:metadata.rows,widthPx:metadata.widthPx,heightPx:metadata.heightPx}}var KITTY_PLACEMENT_CONTROL_KEYS=new Set(["i","p","x","y","w","h","X","Y","c","r","C","U","z","P","Q","H","V"]);function getKittyImagePlacement(line){let match=/\x1b_G([^;]*);/.exec(line),metadata=getRegisteredKittyImageMetadata(line);if(!match||!metadata)return;let commandStart=match.index,commandControls=match[1],transmissionEnd;for(;;){let terminator=line.indexOf("\x1B\\",commandStart+KITTY_PREFIX.length);if(terminator===-1)return;if(transmissionEnd=terminator+2,!/(?:^|,)m=1(?:,|$)/.test(commandControls))break;if(commandStart=transmissionEnd,!line.startsWith(KITTY_PREFIX,commandStart))return;let controlsEnd=line.indexOf(";",commandStart+KITTY_PREFIX.length);if(controlsEnd===-1)return;commandControls=line.slice(commandStart+KITTY_PREFIX.length,controlsEnd)}let sequence=`\x1B_Ga=p,q=2,${match[1].split(",").filter(control=>KITTY_PLACEMENT_CONTROL_KEYS.has(control.split("=",1)[0]??"")).join(",")}\x1B\\`;return{imageId:metadata.imageId,transmissionGeneration:metadata.transmissionGeneration,transmissionBytes:transmissionEnd-match.index,estimatedDecodedBytes:metadata.widthPx*metadata.heightPx*4,sequence,replacementLine:`${line.slice(0,match.index)}${sequence}${line.slice(transmissionEnd)}`}}function cropKittyImageLine(line,hiddenRows,visibleRows){let metadata=getKittyImageMetadata(line),match=/\x1b_G([^;]*);/.exec(line);if(!metadata||!match||hiddenRows<0||hiddenRows>=metadata.rows||visibleRows<=0)return line;let croppedRows=Math.min(visibleRows,metadata.rows-hiddenRows);if(hiddenRows===0&&croppedRows===metadata.rows)return line;let sourceY=Math.floor(metadata.heightPx*hiddenRows/metadata.rows),sourceEnd=Math.ceil(metadata.heightPx*(hiddenRows+croppedRows)/metadata.rows),sourceHeight=Math.max(1,Math.min(metadata.heightPx,sourceEnd)-sourceY),controls=match[1].split(",").filter(control=>!/^[yhr]=/.test(control));return controls.push(`y=${sourceY}`,`h=${sourceHeight}`,`r=${croppedRows}`),`${line.slice(0,match.index)}\x1B_G${controls.join(",")};${line.slice(match.index+match[0].length)}`}function chooseLessDistortedCellCount(upperCount,idealCount){if(upperCount<=1)return upperCount;let lowerCount=upperCount-1,upperDistortion=Math.max(upperCount/idealCount,idealCount/upperCount);return Math.max(lowerCount/idealCount,idealCount/lowerCount)<upperDistortion?lowerCount:upperCount}function calculateImageCellSize(imageDimensions,maxWidthCells,maxHeightCells,cellDimensions2={widthPx:9,heightPx:18},optimizeAspectRatio=!1){let maxWidth=Math.max(1,Math.floor(maxWidthCells)),maxHeight=maxHeightCells===void 0?void 0:Math.max(1,Math.floor(maxHeightCells)),imageWidth=Math.max(1,imageDimensions.widthPx),imageHeight=Math.max(1,imageDimensions.heightPx),widthScale=maxWidth*cellDimensions2.widthPx/imageWidth,heightScale=maxHeight===void 0?widthScale:maxHeight*cellDimensions2.heightPx/imageHeight,scale=Math.min(widthScale,heightScale),scaledWidthPx=imageWidth*scale,scaledHeightPx=imageHeight*scale,columns=Math.max(1,Math.min(maxWidth,Math.ceil(scaledWidthPx/cellDimensions2.widthPx))),heightRows=scaledHeightPx/cellDimensions2.heightPx,rows=Math.max(1,Math.ceil(heightRows));if(maxHeight!==void 0&&(rows=Math.min(maxHeight,rows)),!optimizeAspectRatio)return{columns,rows};if(widthScale<=heightScale){let idealRows=columns*cellDimensions2.widthPx*imageHeight/(imageWidth*cellDimensions2.heightPx);rows=chooseLessDistortedCellCount(rows,idealRows)}else{let idealColumns=rows*cellDimensions2.heightPx*imageWidth/(imageHeight*cellDimensions2.widthPx);columns=chooseLessDistortedCellCount(columns,idealColumns)}return{columns,rows}}function getPngDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<24||buffer[0]!==137||buffer[1]!==80||buffer[2]!==78||buffer[3]!==71)return null;let width=buffer.readUInt32BE(16),height=buffer.readUInt32BE(20);return{widthPx:width,heightPx:height}}catch{return null}}function getJpegDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<2||buffer[0]!==255||buffer[1]!==216)return null;let offset=2;for(;offset<buffer.length-9;){if(buffer[offset]!==255){offset++;continue}let marker=buffer[offset+1];if(marker>=192&&marker<=194){let height=buffer.readUInt16BE(offset+5);return{widthPx:buffer.readUInt16BE(offset+7),heightPx:height}}if(offset+3>=buffer.length)return null;let length=buffer.readUInt16BE(offset+2);if(length<2)return null;offset+=2+length}return null}catch{return null}}function getGifDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<10)return null;let sig=buffer.subarray(0,6).toString("ascii");if(sig!=="GIF87a"&&sig!=="GIF89a")return null;let width=buffer.readUInt16LE(6),height=buffer.readUInt16LE(8);return{widthPx:width,heightPx:height}}catch{return null}}function getWebpDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<30)return null;let riff=buffer.subarray(0,4).toString("ascii"),webp=buffer.subarray(8,12).toString("ascii");if(riff!=="RIFF"||webp!=="WEBP")return null;let chunk=buffer.subarray(12,16).toString("ascii");if(chunk==="VP8 "){if(buffer.length<30)return null;let width=buffer.readUInt16LE(26)&16383,height=buffer.readUInt16LE(28)&16383;return{widthPx:width,heightPx:height}}else if(chunk==="VP8L"){if(buffer.length<25)return null;let bits=buffer.readUInt32LE(21),width=(bits&16383)+1,height=(bits>>14&16383)+1;return{widthPx:width,heightPx:height}}else if(chunk==="VP8X"){if(buffer.length<30)return null;let width=(buffer[24]|buffer[25]<<8|buffer[26]<<16)+1,height=(buffer[27]|buffer[28]<<8|buffer[29]<<16)+1;return{widthPx:width,heightPx:height}}return null}catch{return null}}function getImageDimensions(base64Data,mimeType){return mimeType==="image/png"?getPngDimensions(base64Data):mimeType==="image/jpeg"?getJpegDimensions(base64Data):mimeType==="image/gif"?getGifDimensions(base64Data):mimeType==="image/webp"?getWebpDimensions(base64Data):null}function renderImage(base64Data,imageDimensions,options={}){let caps=getCapabilities();if(!caps.images)return null;let maxWidth=options.maxWidthCells??80,size=calculateImageCellSize(imageDimensions,maxWidth,options.maxHeightCells,getCellDimensions(),caps.images==="kitty");if(caps.images==="kitty"&&caps.kittyUnicodePlaceholders){let imageId=options.imageId??allocateImageId(),columns=Math.min(size.columns,KITTY_PLACEHOLDER_MAX),rows=Math.min(size.rows,KITTY_PLACEHOLDER_MAX),sequence=encodeKitty(base64Data,{columns,rows,imageId,virtual:!0}),lines=[];for(let row=0;row<rows;row++){let placeholderRow=buildKittyPlaceholderRow(imageId,row,columns);lines.push(row===0?sequence+placeholderRow:placeholderRow)}return{sequence,columns,rows,imageId,lines}}return caps.images==="kitty"?(options.imageId!==void 0&®isterKittyImageMetadata({imageId:options.imageId,columns:size.columns,rows:size.rows,widthPx:imageDimensions.widthPx,heightPx:imageDimensions.heightPx}),{sequence:encodeKitty(base64Data,{columns:size.columns,rows:size.rows,imageId:options.imageId,moveCursor:options.moveCursor}),columns:size.columns,rows:size.rows,imageId:options.imageId}):caps.images==="iterm2"?{sequence:encodeITerm2(base64Data,{width:size.columns,height:"auto",preserveAspectRatio:options.preserveAspectRatio??!0}),columns:size.columns,rows:size.rows}:null}function hyperlink(text,url){return`\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`}function imageFallback(mimeType,dimensions,filename){let parts=[];if(filename){let sanitized=sanitizeTerminalLabel(filename),display=shortenImagePath(sanitized);parts.push(getCapabilities().hyperlinks&&isAbsolute(sanitized)?hyperlink(display,pathToFileURL(sanitized).href):display)}parts.push(`[${sanitizeTerminalLabel(mimeType)}]`),dimensions&&parts.push(`${dimensions.widthPx}x${dimensions.heightPx}`);let hint=getCapabilities().imageHint;return hint?`[Image: ${parts.join(" ")}] (${hint})`:`[Image: ${parts.join(" ")}]`}var _kittyProtocolActive=!1;function setKittyProtocolActive(active){_kittyProtocolActive=active}function isKittyProtocolActive(){return _kittyProtocolActive}var Key={escape:"escape",esc:"esc",enter:"enter",return:"return",tab:"tab",space:"space",backspace:"backspace",delete:"delete",insert:"insert",clear:"clear",home:"home",end:"end",pageUp:"pageUp",pageDown:"pageDown",up:"up",down:"down",left:"left",right:"right",f1:"f1",f2:"f2",f3:"f3",f4:"f4",f5:"f5",f6:"f6",f7:"f7",f8:"f8",f9:"f9",f10:"f10",f11:"f11",f12:"f12",backtick:"`",hyphen:"-",equals:"=",leftbracket:"[",rightbracket:"]",backslash:"\\",semicolon:";",quote:"'",comma:",",period:".",slash:"/",exclamation:"!",at:"@",hash:"#",dollar:"$",percent:"%",caret:"^",ampersand:"&",asterisk:"*",leftparen:"(",rightparen:")",underscore:"_",plus:"+",pipe:"|",tilde:"~",leftbrace:"{",rightbrace:"}",colon:":",lessthan:"<",greaterthan:">",question:"?",ctrl:key=>`ctrl+${key}`,shift:key=>`shift+${key}`,alt:key=>`alt+${key}`,super:key=>`super+${key}`,ctrlShift:key=>`ctrl+shift+${key}`,shiftCtrl:key=>`shift+ctrl+${key}`,ctrlAlt:key=>`ctrl+alt+${key}`,altCtrl:key=>`alt+ctrl+${key}`,shiftAlt:key=>`shift+alt+${key}`,altShift:key=>`alt+shift+${key}`,ctrlSuper:key=>`ctrl+super+${key}`,superCtrl:key=>`super+ctrl+${key}`,shiftSuper:key=>`shift+super+${key}`,superShift:key=>`super+shift+${key}`,altSuper:key=>`alt+super+${key}`,superAlt:key=>`super+alt+${key}`,ctrlShiftAlt:key=>`ctrl+shift+alt+${key}`,ctrlShiftSuper:key=>`ctrl+shift+super+${key}`},SYMBOL_KEYS=new Set(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),MODIFIERS={shift:1,alt:2,ctrl:4,super:8},LOCK_MASK=192,CODEPOINTS={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},ARROW_CODEPOINTS={up:-1,down:-2,right:-3,left:-4},FUNCTIONAL_CODEPOINTS={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15},KITTY_FUNCTIONAL_KEY_EQUIVALENTS=new Map([[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],[57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,ARROW_CODEPOINTS.left],[57418,ARROW_CODEPOINTS.right],[57419,ARROW_CODEPOINTS.up],[57420,ARROW_CODEPOINTS.down],[57421,FUNCTIONAL_CODEPOINTS.pageUp],[57422,FUNCTIONAL_CODEPOINTS.pageDown],[57423,FUNCTIONAL_CODEPOINTS.home],[57424,FUNCTIONAL_CODEPOINTS.end],[57425,FUNCTIONAL_CODEPOINTS.insert],[57426,FUNCTIONAL_CODEPOINTS.delete]]);function normalizeKittyFunctionalCodepoint(codepoint){return KITTY_FUNCTIONAL_KEY_EQUIVALENTS.get(codepoint)??codepoint}function normalizeShiftedLetterIdentityCodepoint(codepoint,modifier){return(modifier&~LOCK_MASK&MODIFIERS.shift)!==0&&codepoint>=65&&codepoint<=90?codepoint+32:codepoint}var LEGACY_KEY_SEQUENCES={up:["\x1B[A","\x1BOA"],down:["\x1B[B","\x1BOB"],right:["\x1B[C","\x1BOC"],left:["\x1B[D","\x1BOD"],home:["\x1B[H","\x1BOH","\x1B[1~","\x1B[7~"],end:["\x1B[F","\x1BOF","\x1B[4~","\x1B[8~"],insert:["\x1B[2~"],delete:["\x1B[3~"],pageUp:["\x1B[5~","\x1B[[5~"],pageDown:["\x1B[6~","\x1B[[6~"],clear:["\x1B[E","\x1BOE"],f1:["\x1BOP","\x1B[11~","\x1B[[A"],f2:["\x1BOQ","\x1B[12~","\x1B[[B"],f3:["\x1BOR","\x1B[13~","\x1B[[C"],f4:["\x1BOS","\x1B[14~","\x1B[[D"],f5:["\x1B[15~","\x1B[[E"],f6:["\x1B[17~"],f7:["\x1B[18~"],f8:["\x1B[19~"],f9:["\x1B[20~"],f10:["\x1B[21~"],f11:["\x1B[23~"],f12:["\x1B[24~"]},LEGACY_SHIFT_SEQUENCES={up:["\x1B[a"],down:["\x1B[b"],right:["\x1B[c"],left:["\x1B[d"],clear:["\x1B[e"],insert:["\x1B[2$"],delete:["\x1B[3$"],pageUp:["\x1B[5$"],pageDown:["\x1B[6$"],home:["\x1B[7$"],end:["\x1B[8$"]},LEGACY_CTRL_SEQUENCES={up:["\x1BOa"],down:["\x1BOb"],right:["\x1BOc"],left:["\x1BOd"],clear:["\x1BOe"],insert:["\x1B[2^"],delete:["\x1B[3^"],pageUp:["\x1B[5^"],pageDown:["\x1B[6^"],home:["\x1B[7^"],end:["\x1B[8^"]},LEGACY_SEQUENCE_KEY_IDS={"\x1BOA":"up","\x1BOB":"down","\x1BOC":"right","\x1BOD":"left","\x1BOH":"home","\x1BOF":"end","\x1B[E":"clear","\x1BOE":"clear","\x1BOe":"ctrl+clear","\x1B[e":"shift+clear","\x1B[2~":"insert","\x1B[2$":"shift+insert","\x1B[2^":"ctrl+insert","\x1B[3$":"shift+delete","\x1B[3^":"ctrl+delete","\x1B[[5~":"pageUp","\x1B[[6~":"pageDown","\x1B[a":"shift+up","\x1B[b":"shift+down","\x1B[c":"shift+right","\x1B[d":"shift+left","\x1BOa":"ctrl+up","\x1BOb":"ctrl+down","\x1BOc":"ctrl+right","\x1BOd":"ctrl+left","\x1B[5$":"shift+pageUp","\x1B[6$":"shift+pageDown","\x1B[7$":"shift+home","\x1B[8$":"shift+end","\x1B[5^":"ctrl+pageUp","\x1B[6^":"ctrl+pageDown","\x1B[7^":"ctrl+home","\x1B[8^":"ctrl+end","\x1BOP":"f1","\x1BOQ":"f2","\x1BOR":"f3","\x1BOS":"f4","\x1B[11~":"f1","\x1B[12~":"f2","\x1B[13~":"f3","\x1B[14~":"f4","\x1B[[A":"f1","\x1B[[B":"f2","\x1B[[C":"f3","\x1B[[D":"f4","\x1B[[E":"f5","\x1B[15~":"f5","\x1B[17~":"f6","\x1B[18~":"f7","\x1B[19~":"f8","\x1B[20~":"f9","\x1B[21~":"f10","\x1B[23~":"f11","\x1B[24~":"f12","\x1Bb":"alt+left","\x1Bf":"alt+right","\x1Bp":"alt+up","\x1Bn":"alt+down"},matchesLegacySequence=(data,sequences)=>sequences.includes(data),matchesLegacyModifierSequence=(data,key,modifier)=>modifier===MODIFIERS.shift?matchesLegacySequence(data,LEGACY_SHIFT_SEQUENCES[key]):modifier===MODIFIERS.ctrl?matchesLegacySequence(data,LEGACY_CTRL_SEQUENCES[key]):!1,_lastEventType="press";function isKeyRelease(data){return data.includes("\x1B[200~")?!1:!!(data.includes(":3u")||data.includes(":3~")||data.includes(":3A")||data.includes(":3B")||data.includes(":3C")||data.includes(":3D")||data.includes(":3H")||data.includes(":3F"))}function isKeyRepeat(data){return data.includes("\x1B[200~")?!1:!!(data.includes(":2u")||data.includes(":2~")||data.includes(":2A")||data.includes(":2B")||data.includes(":2C")||data.includes(":2D")||data.includes(":2H")||data.includes(":2F"))}function parseEventType(eventTypeStr){if(!eventTypeStr)return"press";let eventType=parseInt(eventTypeStr,10);return eventType===2?"repeat":eventType===3?"release":"press"}function parseKittySequence(data){let csiUMatch=data.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(csiUMatch){let codepoint=parseInt(csiUMatch[1],10),shiftedKey=csiUMatch[2]&&csiUMatch[2].length>0?parseInt(csiUMatch[2],10):void 0,baseLayoutKey=csiUMatch[3]?parseInt(csiUMatch[3],10):void 0,modValue=csiUMatch[4]?parseInt(csiUMatch[4],10):1,eventType=parseEventType(csiUMatch[5]);return _lastEventType=eventType,{codepoint,shiftedKey,baseLayoutKey,modifier:modValue-1,eventType}}let arrowMatch=data.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(arrowMatch){let modValue=parseInt(arrowMatch[1],10),eventType=parseEventType(arrowMatch[2]),arrowCodes={A:-1,B:-2,C:-3,D:-4};return _lastEventType=eventType,{codepoint:arrowCodes[arrowMatch[3]],modifier:modValue-1,eventType}}let funcMatch=data.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(funcMatch){let keyNum=parseInt(funcMatch[1],10),modValue=funcMatch[2]?parseInt(funcMatch[2],10):1,eventType=parseEventType(funcMatch[3]),codepoint={2:FUNCTIONAL_CODEPOINTS.insert,3:FUNCTIONAL_CODEPOINTS.delete,5:FUNCTIONAL_CODEPOINTS.pageUp,6:FUNCTIONAL_CODEPOINTS.pageDown,7:FUNCTIONAL_CODEPOINTS.home,8:FUNCTIONAL_CODEPOINTS.end}[keyNum];if(codepoint!==void 0)return _lastEventType=eventType,{codepoint,modifier:modValue-1,eventType}}let homeEndMatch=data.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(homeEndMatch){let modValue=parseInt(homeEndMatch[1],10),eventType=parseEventType(homeEndMatch[2]),codepoint=homeEndMatch[3]==="H"?FUNCTIONAL_CODEPOINTS.home:FUNCTIONAL_CODEPOINTS.end;return _lastEventType=eventType,{codepoint,modifier:modValue-1,eventType}}return null}function matchesKittySequence(data,expectedCodepoint,expectedModifier){let parsed=parseKittySequence(data);if(!parsed)return!1;let actualMod=parsed.modifier&~LOCK_MASK,expectedMod=expectedModifier&~LOCK_MASK;if(actualMod!==expectedMod)return!1;let normalizedCodepoint=normalizeShiftedLetterIdentityCodepoint(normalizeKittyFunctionalCodepoint(parsed.codepoint),parsed.modifier),normalizedExpectedCodepoint=normalizeShiftedLetterIdentityCodepoint(normalizeKittyFunctionalCodepoint(expectedCodepoint),expectedModifier);if(normalizedCodepoint===normalizedExpectedCodepoint)return!0;if(parsed.baseLayoutKey!==void 0&&parsed.baseLayoutKey===expectedCodepoint){let cp=normalizedCodepoint,isLatinLetter=cp>=97&&cp<=122,isKnownSymbol=SYMBOL_KEYS.has(String.fromCharCode(cp));if(!isLatinLetter&&!isKnownSymbol)return!0}return!1}function parseModifyOtherKeysSequence(data){let match=data.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!match)return null;let modValue=parseInt(match[1],10);return{codepoint:parseInt(match[2],10),modifier:modValue-1}}function matchesModifyOtherKeys(data,expectedKeycode,expectedModifier){let parsed=parseModifyOtherKeysSequence(data);return parsed?parsed.codepoint===expectedKeycode&&parsed.modifier===expectedModifier:!1}function isWindowsTerminalSession(){return!!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.env.SSH_TTY}function matchesRawBackspace(data,expectedModifier){return data==="\x7F"?expectedModifier===0:data!=="\b"?!1:isWindowsTerminalSession()?expectedModifier===MODIFIERS.ctrl:expectedModifier===0}function rawCtrlChar(key){let char=key.toLowerCase(),code=char.charCodeAt(0);return code>=97&&code<=122||char==="["||char==="\\"||char==="]"||char==="_"?String.fromCharCode(code&31):char==="-"?"":null}function isDigitKey(key){return key>="0"&&key<="9"}function matchesPrintableModifyOtherKeys(data,expectedKeycode,expectedModifier){if(expectedModifier===0)return!1;let parsed=parseModifyOtherKeysSequence(data);return!parsed||parsed.modifier!==expectedModifier?!1:normalizeShiftedLetterIdentityCodepoint(parsed.codepoint,parsed.modifier)===normalizeShiftedLetterIdentityCodepoint(expectedKeycode,expectedModifier)}function formatKeyNameWithModifiers(keyName,modifier){let mods=[],effectiveMod=modifier&~LOCK_MASK,supportedModifierMask=MODIFIERS.shift|MODIFIERS.ctrl|MODIFIERS.alt|MODIFIERS.super;if((effectiveMod&~supportedModifierMask)===0)return effectiveMod&MODIFIERS.shift&&mods.push("shift"),effectiveMod&MODIFIERS.ctrl&&mods.push("ctrl"),effectiveMod&MODIFIERS.alt&&mods.push("alt"),effectiveMod&MODIFIERS.super&&mods.push("super"),mods.length>0?`${mods.join("+")}+${keyName}`:keyName}function parseKeyId(keyId){let parts=keyId.toLowerCase().split("+"),key=parts[parts.length-1];return key?{key,ctrl:parts.includes("ctrl"),shift:parts.includes("shift"),alt:parts.includes("alt"),super:parts.includes("super")}:null}function matchesKey(data,keyId){let parsed=parseKeyId(keyId);if(!parsed)return!1;let{key,ctrl,shift,alt,super:superModifier}=parsed,modifier=0;switch(shift&&(modifier|=MODIFIERS.shift),alt&&(modifier|=MODIFIERS.alt),ctrl&&(modifier|=MODIFIERS.ctrl),superModifier&&(modifier|=MODIFIERS.super),key){case"escape":case"esc":return modifier!==0?!1:data==="\x1B"||matchesKittySequence(data,CODEPOINTS.escape,0)||matchesModifyOtherKeys(data,CODEPOINTS.escape,0);case"space":return!_kittyProtocolActive&&(modifier===MODIFIERS.ctrl&&data==="\0"||modifier===MODIFIERS.alt&&data==="\x1B ")?!0:modifier===0?data===" "||matchesKittySequence(data,CODEPOINTS.space,0)||matchesModifyOtherKeys(data,CODEPOINTS.space,0):matchesKittySequence(data,CODEPOINTS.space,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.space,modifier);case"tab":return modifier===MODIFIERS.shift?data==="\x1B[Z"||matchesKittySequence(data,CODEPOINTS.tab,MODIFIERS.shift)||matchesModifyOtherKeys(data,CODEPOINTS.tab,MODIFIERS.shift):modifier===0?data===" "||matchesKittySequence(data,CODEPOINTS.tab,0):matchesKittySequence(data,CODEPOINTS.tab,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.tab,modifier);case"enter":case"return":return modifier===MODIFIERS.shift?matchesKittySequence(data,CODEPOINTS.enter,MODIFIERS.shift)||matchesKittySequence(data,CODEPOINTS.kpEnter,MODIFIERS.shift)||matchesModifyOtherKeys(data,CODEPOINTS.enter,MODIFIERS.shift)?!0:_kittyProtocolActive?data==="\x1B\r"||data===`
`:!1:modifier===MODIFIERS.alt?matchesKittySequence(data,CODEPOINTS.enter,MODIFIERS.alt)||matchesKittySequence(data,CODEPOINTS.kpEnter,MODIFIERS.alt)||matchesModifyOtherKeys(data,CODEPOINTS.enter,MODIFIERS.alt)?!0:_kittyProtocolActive?!1:data==="\x1B\r":modifier===0?data==="\r"||!_kittyProtocolActive&&data===`
`||data==="\x1BOM"||matchesKittySequence(data,CODEPOINTS.enter,0)||matchesKittySequence(data,CODEPOINTS.kpEnter,0):matchesKittySequence(data,CODEPOINTS.enter,modifier)||matchesKittySequence(data,CODEPOINTS.kpEnter,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.enter,modifier);case"backspace":return modifier===MODIFIERS.alt?data==="\x1B\x7F"||data==="\x1B\b"?!0:matchesKittySequence(data,CODEPOINTS.backspace,MODIFIERS.alt)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,MODIFIERS.alt):modifier===MODIFIERS.ctrl?matchesRawBackspace(data,MODIFIERS.ctrl)?!0:matchesKittySequence(data,CODEPOINTS.backspace,MODIFIERS.ctrl)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,MODIFIERS.ctrl):modifier===0?matchesRawBackspace(data,0)||matchesKittySequence(data,CODEPOINTS.backspace,0)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,0):matchesKittySequence(data,CODEPOINTS.backspace,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,modifier);case"insert":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.insert)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.insert,0):matchesLegacyModifierSequence(data,"insert",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.insert,modifier);case"delete":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.delete)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.delete,0):matchesLegacyModifierSequence(data,"delete",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.delete,modifier);case"clear":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.clear):matchesLegacyModifierSequence(data,"clear",modifier);case"home":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.home)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.home,0):matchesLegacyModifierSequence(data,"home",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.home,modifier);case"end":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.end)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.end,0):matchesLegacyModifierSequence(data,"end",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.end,modifier);case"pageup":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.pageUp)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageUp,0):matchesLegacyModifierSequence(data,"pageUp",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageUp,modifier);case"pagedown":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.pageDown)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageDown,0):matchesLegacyModifierSequence(data,"pageDown",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageDown,modifier);case"up":return modifier===MODIFIERS.alt?data==="\x1Bp"||matchesKittySequence(data,ARROW_CODEPOINTS.up,MODIFIERS.alt):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.up)||matchesKittySequence(data,ARROW_CODEPOINTS.up,0):matchesLegacyModifierSequence(data,"up",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.up,modifier);case"down":return modifier===MODIFIERS.alt?data==="\x1Bn"||matchesKittySequence(data,ARROW_CODEPOINTS.down,MODIFIERS.alt):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.down)||matchesKittySequence(data,ARROW_CODEPOINTS.down,0):matchesLegacyModifierSequence(data,"down",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.down,modifier);case"left":return modifier===MODIFIERS.alt?data==="\x1B[1;3D"||!_kittyProtocolActive&&data==="\x1BB"||data==="\x1Bb"||matchesKittySequence(data,ARROW_CODEPOINTS.left,MODIFIERS.alt):modifier===MODIFIERS.ctrl?data==="\x1B[1;5D"||matchesLegacyModifierSequence(data,"left",MODIFIERS.ctrl)||matchesKittySequence(data,ARROW_CODEPOINTS.left,MODIFIERS.ctrl):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.left)||matchesKittySequence(data,ARROW_CODEPOINTS.left,0):matchesLegacyModifierSequence(data,"left",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.left,modifier);case"right":return modifier===MODIFIERS.alt?data==="\x1B[1;3C"||!_kittyProtocolActive&&data==="\x1BF"||data==="\x1Bf"||matchesKittySequence(data,ARROW_CODEPOINTS.right,MODIFIERS.alt):modifier===MODIFIERS.ctrl?data==="\x1B[1;5C"||matchesLegacyModifierSequence(data,"right",MODIFIERS.ctrl)||matchesKittySequence(data,ARROW_CODEPOINTS.right,MODIFIERS.ctrl):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.right)||matchesKittySequence(data,ARROW_CODEPOINTS.right,0):matchesLegacyModifierSequence(data,"right",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.right,modifier);case"f1":case"f2":case"f3":case"f4":case"f5":case"f6":case"f7":case"f8":case"f9":case"f10":case"f11":case"f12":return modifier!==0?!1:matchesLegacySequence(data,LEGACY_KEY_SEQUENCES[key])}if(key.length===1&&(key>="a"&&key<="z"||isDigitKey(key)||SYMBOL_KEYS.has(key))){let codepoint=key.charCodeAt(0),rawCtrl=rawCtrlChar(key),isLetter=key>="a"&&key<="z",isDigit=isDigitKey(key);return modifier===MODIFIERS.ctrl+MODIFIERS.alt&&!_kittyProtocolActive&&rawCtrl&&data===`\x1B${rawCtrl}`||modifier===MODIFIERS.alt&&(isLetter||isDigit||SYMBOL_KEYS.has(key))&&data===`\x1B${key}`?!0:modifier===MODIFIERS.ctrl?rawCtrl&&data===rawCtrl?!0:matchesKittySequence(data,codepoint,MODIFIERS.ctrl)||matchesPrintableModifyOtherKeys(data,codepoint,MODIFIERS.ctrl):modifier===MODIFIERS.shift+MODIFIERS.ctrl?matchesKittySequence(data,codepoint,MODIFIERS.shift+MODIFIERS.ctrl)||matchesPrintableModifyOtherKeys(data,codepoint,MODIFIERS.shift+MODIFIERS.ctrl):modifier===MODIFIERS.shift?isLetter&&data===key.toUpperCase()?!0:matchesKittySequence(data,codepoint,MODIFIERS.shift)||matchesPrintableModifyOtherKeys(data,codepoint,MODIFIERS.shift):modifier!==0?matchesKittySequence(data,codepoint,modifier)||matchesPrintableModifyOtherKeys(data,codepoint,modifier):data===key||matchesKittySequence(data,codepoint,0)}return!1}function formatParsedKey(codepoint,modifier,baseLayoutKey){let normalizedCodepoint=normalizeKittyFunctionalCodepoint(codepoint),identityCodepoint=normalizeShiftedLetterIdentityCodepoint(normalizedCodepoint,modifier),isLatinLetter=identityCodepoint>=97&&identityCodepoint<=122,isDigit=identityCodepoint>=48&&identityCodepoint<=57,isKnownSymbol=SYMBOL_KEYS.has(String.fromCharCode(identityCodepoint)),effectiveCodepoint=isLatinLetter||isDigit||isKnownSymbol?identityCodepoint:baseLayoutKey??identityCodepoint,keyName;if(effectiveCodepoint===CODEPOINTS.escape?keyName="escape":effectiveCodepoint===CODEPOINTS.tab?keyName="tab":effectiveCodepoint===CODEPOINTS.enter||effectiveCodepoint===CODEPOINTS.kpEnter?keyName="enter":effectiveCodepoint===CODEPOINTS.space?keyName="space":effectiveCodepoint===CODEPOINTS.backspace?keyName="backspace":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.delete?keyName="delete":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.insert?keyName="insert":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.home?keyName="home":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.end?keyName="end":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.pageUp?keyName="pageUp":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.pageDown?keyName="pageDown":effectiveCodepoint===ARROW_CODEPOINTS.up?keyName="up":effectiveCodepoint===ARROW_CODEPOINTS.down?keyName="down":effectiveCodepoint===ARROW_CODEPOINTS.left?keyName="left":effectiveCodepoint===ARROW_CODEPOINTS.right?keyName="right":(effectiveCodepoint>=48&&effectiveCodepoint<=57||effectiveCodepoint>=97&&effectiveCodepoint<=122||SYMBOL_KEYS.has(String.fromCharCode(effectiveCodepoint)))&&(keyName=String.fromCharCode(effectiveCodepoint)),!!keyName)return formatKeyNameWithModifiers(keyName,modifier)}function parseKey(data){let kitty=parseKittySequence(data);if(kitty)return formatParsedKey(kitty.codepoint,kitty.modifier,kitty.baseLayoutKey);let modifyOtherKeys=parseModifyOtherKeysSequence(data);if(modifyOtherKeys)return formatParsedKey(modifyOtherKeys.codepoint,modifyOtherKeys.modifier);if(_kittyProtocolActive&&(data==="\x1B\r"||data===`
`))return"shift+enter";let legacySequenceKeyId=LEGACY_SEQUENCE_KEY_IDS[data];if(legacySequenceKeyId)return legacySequenceKeyId;if(data==="\x1B")return"escape";if(data==="")return"ctrl+\\";if(data==="")return"ctrl+]";if(data==="")return"ctrl+-";if(data==="\x1B\x1B")return"ctrl+alt+[";if(data==="\x1B")return"ctrl+alt+\\";if(data==="\x1B")return"ctrl+alt+]";if(data==="\x1B")return"ctrl+alt+-";if(data===" ")return"tab";if(data==="\r"||!_kittyProtocolActive&&data===`
`||data==="\x1BOM")return"enter";if(data==="\0")return"ctrl+space";if(data===" ")return"space";if(data==="\x7F")return"backspace";if(data==="\b")return isWindowsTerminalSession()?"ctrl+backspace":"backspace";if(data==="\x1B[Z")return"shift+tab";if(!_kittyProtocolActive&&data==="\x1B\r")return"alt+enter";if(!_kittyProtocolActive&&data==="\x1B ")return"alt+space";if(data==="\x1B\x7F"||data==="\x1B\b")return"alt+backspace";if(!_kittyProtocolActive&&data==="\x1BB")return"alt+left";if(!_kittyProtocolActive&&data==="\x1BF")return"alt+right";if(data.length===2&&data[0]==="\x1B"){let code=data.charCodeAt(1);if(!_kittyProtocolActive&&code>=1&&code<=26)return`ctrl+alt+${String.fromCharCode(code+96)}`;let key=String.fromCharCode(code);if(code>=97&&code<=122||code>=48&&code<=57||SYMBOL_KEYS.has(key))return`alt+${key}`}if(data==="\x1B[A")return"up";if(data==="\x1B[B")return"down";if(data==="\x1B[C")return"right";if(data==="\x1B[D")return"left";if(data==="\x1B[H"||data==="\x1BOH")return"home";if(data==="\x1B[F"||data==="\x1BOF")return"end";if(data==="\x1B[3~")return"delete";if(data==="\x1B[5~")return"pageUp";if(data==="\x1B[6~")return"pageDown";if(data.length===1){let code=data.charCodeAt(0);if(code>=1&&code<=26)return`ctrl+${String.fromCharCode(code+96)}`;if(code>=32&&code<=126)return data}}var KITTY_CSI_U_REGEX=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/,KITTY_PRINTABLE_ALLOWED_MODIFIERS=MODIFIERS.shift|LOCK_MASK;function decodeKittyPrintable(data){let match=data.match(KITTY_CSI_U_REGEX);if(!match)return;let codepoint=Number.parseInt(match[1]??"",10);if(!Number.isFinite(codepoint))return;let shiftedKey=match[2]&&match[2].length>0?Number.parseInt(match[2],10):void 0,modValue=match[4]?Number.parseInt(match[4],10):1,modifier=Number.isFinite(modValue)?modValue-1:0;if((modifier&~KITTY_PRINTABLE_ALLOWED_MODIFIERS)!==0||modifier&(MODIFIERS.alt|MODIFIERS.ctrl))return;let effectiveCodepoint=codepoint;if(modifier&MODIFIERS.shift&&typeof shiftedKey=="number"&&(effectiveCodepoint=shiftedKey),effectiveCodepoint=normalizeKittyFunctionalCodepoint(effectiveCodepoint),!(!Number.isFinite(effectiveCodepoint)||effectiveCodepoint<32))try{return String.fromCodePoint(effectiveCodepoint)}catch{return}}function decodeModifyOtherKeysPrintable(data){let parsed=parseModifyOtherKeysSequence(data);if(!(!parsed||(parsed.modifier&~LOCK_MASK&~MODIFIERS.shift)!==0)&&!(!Number.isFinite(parsed.codepoint)||parsed.codepoint<32))try{return String.fromCodePoint(parsed.codepoint)}catch{return}}function decodePrintableKey(data){return decodeKittyPrintable(data)??decodeModifyOtherKeysPrintable(data)}var TUI_KEYBINDINGS={"tui.editor.cursorUp":{defaultKeys:"up",description:"Move cursor up"},"tui.editor.cursorDown":{defaultKeys:"down",description:"Move cursor down"},"tui.editor.historyPrevious":{defaultKeys:[],description:"Select previous prompt history entry"},"tui.editor.historyNext":{defaultKeys:[],description:"Select next prompt history entry"},"tui.editor.cursorLeft":{defaultKeys:["left","ctrl+b"],description:"Move cursor left"},"tui.editor.cursorRight":{defaultKeys:["right","ctrl+f"],description:"Move cursor right"},"tui.editor.cursorWordLeft":{defaultKeys:["alt+left","ctrl+left","alt+b"],description:"Move cursor word left"},"tui.editor.cursorWordRight":{defaultKeys:["alt+right","ctrl+right","alt+f"],description:"Move cursor word right"},"tui.editor.cursorLineStart":{defaultKeys:["home","ctrl+home","ctrl+a"],description:"Move to line start"},"tui.editor.cursorLineEnd":{defaultKeys:["end","ctrl+end","ctrl+e"],description:"Move to line end"},"tui.editor.jumpForward":{defaultKeys:"ctrl+]",description:"Jump forward to character"},"tui.editor.jumpBackward":{defaultKeys:"ctrl+alt+]",description:"Jump backward to character"},"tui.editor.pageUp":{defaultKeys:["pageUp","ctrl+pageUp"],description:"Page up"},"tui.editor.pageDown":{defaultKeys:["pageDown","ctrl+pageDown"],description:"Page down"},"tui.editor.deleteCharBackward":{defaultKeys:"backspace",description:"Delete character backward"},"tui.editor.deleteCharForward":{defaultKeys:["delete","ctrl+d"],description:"Delete character forward"},"tui.editor.deleteWordBackward":{defaultKeys:["ctrl+w","alt+backspace"],description:"Delete word backward"},"tui.editor.deleteWordForward":{defaultKeys:["alt+d","alt+delete"],description:"Delete word forward"},"tui.editor.deleteToLineStart":{defaultKeys:"ctrl+u",description:"Delete to line start"},"tui.editor.deleteToLineEnd":{defaultKeys:"ctrl+k",description:"Delete to line end"},"tui.editor.yank":{defaultKeys:"ctrl+y",description:"Yank"},"tui.editor.yankPop":{defaultKeys:"alt+y",description:"Yank pop"},"tui.editor.undo":{defaultKeys:"ctrl+-",description:"Undo"},"tui.input.newLine":{defaultKeys:["shift+enter","ctrl+j"],description:"Insert newline"},"tui.input.submit":{defaultKeys:"enter",description:"Submit input"},"tui.input.tab":{defaultKeys:"tab",description:"Tab / autocomplete"},"tui.input.copy":{defaultKeys:"ctrl+c",description:"Copy selection"},"tui.select.up":{defaultKeys:"up",description:"Move selection up"},"tui.select.down":{defaultKeys:"down",description:"Move selection down"},"tui.select.pageUp":{defaultKeys:"pageUp",description:"Selection page up"},"tui.select.pageDown":{defaultKeys:"pageDown",description:"Selection page down"},"tui.select.confirm":{defaultKeys:"enter",description:"Confirm selection"},"tui.select.cancel":{defaultKeys:["escape","ctrl+c"],description:"Cancel selection"},"tui.altScreen.pageUp":{defaultKeys:"pageUp",description:"Scroll viewport up one page"},"tui.altScreen.pageDown":{defaultKeys:"pageDown",description:"Scroll viewport down one page"},"tui.altScreen.halfPageUp":{defaultKeys:[],description:"Scroll viewport up half a page"},"tui.altScreen.halfPageDown":{defaultKeys:[],description:"Scroll viewport down half a page"},"tui.altScreen.lineUp":{defaultKeys:[],description:"Scroll viewport up one line"},"tui.altScreen.lineDown":{defaultKeys:[],description:"Scroll viewport down one line"},"tui.altScreen.previousPrompt":{defaultKeys:["ctrl+shift+up","ctrl+up"],description:"Jump to previous semantic prompt"},"tui.altScreen.nextPrompt":{defaultKeys:["ctrl+shift+down","ctrl+down"],description:"Jump to next semantic prompt"},"tui.altScreen.search":{defaultKeys:"ctrl+shift+f",description:"Search the primary scroll view"},"tui.altScreen.searchNext":{defaultKeys:["enter","ctrl+g"],description:"Select the next search match"},"tui.altScreen.searchPrevious":{defaultKeys:["shift+enter","ctrl+shift+g"],description:"Select the previous search match"},"tui.altScreen.searchClose":{defaultKeys:"escape",description:"Close transcript search"},"tui.altScreen.top":{defaultKeys:"home",description:"Scroll viewport to top"},"tui.altScreen.bottom":{defaultKeys:"end",description:"Scroll viewport to bottom"}};function normalizeKeys(keys){if(keys===void 0)return[];let keyList=Array.isArray(keys)?keys:[keys],seen=new Set,result=[];for(let key of keyList)seen.has(key)||(seen.add(key),result.push(key));return result}var KeybindingsManager=class{constructor(definitions,userBindings={}){this.keysById=new Map,this.conflicts=[],this.definitions=definitions,this.userBindings=userBindings,this.rebuild()}rebuild(){this.keysById.clear(),this.conflicts=[];let userClaims=new Map;for(let[keybinding,keys]of Object.entries(this.userBindings))if(keybinding in this.definitions)for(let key of normalizeKeys(keys)){let claimants=userClaims.get(key)??new Set;claimants.add(keybinding),userClaims.set(key,claimants)}for(let[key,keybindings]of userClaims)keybindings.size>1&&this.conflicts.push({key,keybindings:[...keybindings]});for(let[id,definition]of Object.entries(this.definitions)){let userKeys=this.userBindings[id],keys=normalizeKeys(userKeys===void 0?definition.defaultKeys:userKeys);this.keysById.set(id,keys)}}matches(data,keybinding){let keys=this.keysById.get(keybinding)??[];for(let key of keys)if(matchesKey(data,key))return!0;return!1}getKeys(keybinding){return[...this.keysById.get(keybinding)??[]]}getDefinition(keybinding){return this.definitions[keybinding]}getConflicts(){return this.conflicts.map(conflict=>({...conflict,keybindings:[...conflict.keybindings]}))}setUserBindings(userBindings){this.userBindings=userBindings,this.rebuild()}getUserBindings(){return{...this.userBindings}}getResolvedBindings(){let resolved={};for(let id of Object.keys(this.definitions)){let keys=this.keysById.get(id)??[];resolved[id]=keys.length===1?keys[0]:[...keys]}return resolved}},globalKeybindings=null;function setKeybindings(keybindings){globalKeybindings=keybindings}function getKeybindings(){return globalKeybindings||(globalKeybindings=new KeybindingsManager(TUI_KEYBINDINGS)),globalKeybindings}var ambiguousRanges=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],fullwidthMinimalCodePoint=12288,fullwidthMaximumCodePoint=65510,fullwidthRanges=[12288,12288,65281,65376,65504,65510];var wideMinimalCodePoint=4352,wideMaximumCodePoint=262141,wideRanges=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101594,101631,101664,101760,101874,101888,102801,102816,102866,110576,110579,110581,110587,110589,110590,110592,110888,110898,110898,110928,110930,110933,110933,110948,110952,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127406,127406,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128729,128732,128735,128747,128748,128756,128764,128986,128986,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129734,129736,129736,129740,129757,129759,129771,129775,129786,131072,196605,196608,262141];var isInRange=(ranges,codePoint)=>{let low=0,high=Math.floor(ranges.length/2)-1;for(;low<=high;){let mid=Math.floor((low+high)/2),i=mid*2;if(codePoint<ranges[i])high=mid-1;else if(codePoint>ranges[i+1])low=mid+1;else return!0}return!1};var commonCjkCodePoint=19968,[wideFastPathStart,wideFastPathEnd]=findWideFastPathRange(wideRanges);function findWideFastPathRange(ranges){let fastPathStart=ranges[0],fastPathEnd=ranges[1];for(let index=0;index<ranges.length;index+=2){let start=ranges[index],end=ranges[index+1];if(commonCjkCodePoint>=start&&commonCjkCodePoint<=end)return[start,end];end-start>fastPathEnd-fastPathStart&&(fastPathStart=start,fastPathEnd=end)}return[fastPathStart,fastPathEnd]}var isAmbiguous=codePoint=>codePoint<161||codePoint>1114109?!1:isInRange(ambiguousRanges,codePoint),isFullwidth=codePoint=>codePoint<fullwidthMinimalCodePoint||codePoint>fullwidthMaximumCodePoint?!1:isInRange(fullwidthRanges,codePoint);var isWide=codePoint=>codePoint>=wideFastPathStart&&codePoint<=wideFastPathEnd?!0:codePoint<wideMinimalCodePoint||codePoint>wideMaximumCodePoint?!1:isInRange(wideRanges,codePoint);function validate(codePoint){if(!Number.isSafeInteger(codePoint))throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`)}function eastAsianWidth(codePoint,{ambiguousAsWide=!1}={}){return validate(codePoint),isFullwidth(codePoint)||isWide(codePoint)||ambiguousAsWide&&isAmbiguous(codePoint)?2:1}var graphemeSegmenter=new Intl.Segmenter(void 0,{granularity:"grapheme"}),wordSegmenter=new Intl.Segmenter(void 0,{granularity:"word"});function getGraphemeSegmenter(){return graphemeSegmenter}function getWordSegmenter(){return wordSegmenter}function couldBeEmoji(segment){let cp=segment.codePointAt(0);return cp>=126976&&cp<=130047||cp>=8960&&cp<=9215||cp>=9728&&cp<=10175||cp>=11088&&cp<=11093||segment.includes("\uFE0F")||segment.length>2}var zeroWidthRegex=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$","v"),leadingNonPrintingRegex=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),nonPrintingCharRegex=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})$","v"),markCharRegex=new RegExp("^\\p{Mark}$","v"),terminalSpacingMarkRegex=new RegExp("^(?:[\\p{Spacing_Mark}--[\\u1734\\u302E\\u302F]]|[\\u065F\\u0F7F\\u102B\\u102C\\u1031\\u1033-\\u1035\\u1038\\u103A-\\u103E])+$","v"),rgiEmojiRegex=new RegExp("^\\p{RGI_Emoji}$","v"),WIDTH_CACHE_GENERATION_SIZE=2048,widthCacheCurrent=new Map,widthCachePrevious=new Map,widthCacheHits=0,widthCacheMisses=0;function rotateWidthCacheIfNeeded(){widthCacheCurrent.size>=WIDTH_CACHE_GENERATION_SIZE&&(widthCachePrevious=widthCacheCurrent,widthCacheCurrent=new Map)}function setWidthCache(str,width){widthCacheCurrent.set(str,width),rotateWidthCacheIfNeeded()}var cjkBreakRegex=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u,cjkPunctuationRegex=new RegExp(`(?:(?=\\p{Punctuation})${cjkBreakRegex.source}|[\uFF0C\uFF0E\uFF1A\uFF1B\uFF01\uFF1F\uFF08\uFF09\uFF3B\uFF3D\uFF5B\uFF5D\u201C\u201D\u2018\u2019\u2026\u2014])`,"u"),autocompleteSeparatorRegex=new RegExp(`(?:\\s|${cjkPunctuationRegex.source})`,"u"),autocompleteBoundaryRegex=new RegExp(`(?:^|${autocompleteSeparatorRegex.source})`,"u");function isPrintableAscii(str){for(let i=0;i<str.length;i++){let code=str.charCodeAt(i);if(code<32||code>126)return!1}return!0}function truncateFragmentToWidth(text,maxWidth){if(maxWidth<=0||text.length===0)return{text:"",width:0};if(isPrintableAscii(text)){let clipped=text.slice(0,maxWidth);return{text:clipped,width:clipped.length}}let hasAnsi=text.includes("\x1B"),hasTabs=text.includes(" ");if(!hasAnsi&&!hasTabs){let result2="",width2=0;for(let{segment}of graphemeSegmenter.segment(text)){let w=graphemeWidth(segment);if(width2+w>maxWidth)break;result2+=segment,width2+=w}return{text:result2,width:width2}}let result="",width=0,i=0,pendingAnsi="";for(;i<text.length;){let ansi=extractAnsiCode(text,i);if(ansi){pendingAnsi+=ansi.code,i+=ansi.length;continue}if(text[i]===" "){if(width+3>maxWidth)break;pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=" ",width+=3,i++;continue}let end=i;for(;end<text.length&&text[end]!==" "&&!extractAnsiCode(text,end);)end++;for(let{segment}of graphemeSegmenter.segment(text.slice(i,end))){let w=graphemeWidth(segment);if(width+w>maxWidth)return{text:result,width};pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=segment,width+=w}i=end}return{text:result,width}}function finalizeTruncatedResult(prefix,prefixWidth,ellipsis,ellipsisWidth,maxWidth,pad){let reset="\x1B[0m",hyperlinkClose=getActiveOsc8Close(prefix),visibleWidth2=prefixWidth+ellipsisWidth,result;return ellipsis.length>0?result=`${prefix}${hyperlinkClose}${reset}${ellipsis}${reset}`:result=`${prefix}${hyperlinkClose}${reset}`,pad?result+" ".repeat(Math.max(0,maxWidth-visibleWidth2)):result}function graphemeWidth(segment){if(segment.length===1){let code=segment.charCodeAt(0);if(code>=32&&code<=126)return 1;if(code===9)return 3}if(terminalSpacingMarkRegex.test(segment))return[...segment].length;if(zeroWidthRegex.test(segment))return 0;if(couldBeEmoji(segment)&&rgiEmojiRegex.test(segment))return 2;let base=segment.replace(leadingNonPrintingRegex,""),cp=base.codePointAt(0);if(cp===void 0)return 0;if(cp>=127462&&cp<=127487)return 2;let width=eastAsianWidth(cp),followsMark=!1,chars=[...base];for(let char of chars.slice(1))if(terminalSpacingMarkRegex.test(char))width+=1,followsMark=!1;else if(markCharRegex.test(char))followsMark=!0;else if(!nonPrintingCharRegex.test(char)){let c=char.codePointAt(0);followsMark||c>=65280&&c<=65519?width+=eastAsianWidth(c):(c===3635||c===3763)&&(width+=1),followsMark=!1}return width}function visibleWidth(str){if(str.length===0)return 0;let asciiWidth=asciiVisibleWidth(str);if(asciiWidth!==-1)return asciiWidth;let cachedCurrent=widthCacheCurrent.get(str);if(cachedCurrent!==void 0)return widthCacheHits++,cachedCurrent;let cachedPrevious=widthCachePrevious.get(str);if(cachedPrevious!==void 0)return widthCacheHits++,setWidthCache(str,cachedPrevious),cachedPrevious;widthCacheMisses++;let clean=str;str.includes(" ")&&(clean=clean.replace(/\t/g," "));let escapeIndex=clean.indexOf("\x1B");if(escapeIndex!==-1){let stripped="",copyFrom=0;for(;escapeIndex!==-1;){let length=ansiCodeLength(clean,escapeIndex);length>0?(stripped+=clean.slice(copyFrom,escapeIndex),escapeIndex+=length,copyFrom=escapeIndex):escapeIndex++,escapeIndex=clean.indexOf("\x1B",escapeIndex)}clean=stripped+clean.slice(copyFrom)}let width=0;for(let{segment}of graphemeSegmenter.segment(clean))width+=graphemeWidth(segment);return setWidthCache(str,width),width}function stripTerminalSequences(str){if(!str.includes("\x1B"))return str;let result="",i=0;for(;i<str.length;){let ansi=extractAnsiCode(str,i);if(ansi){i+=ansi.length;continue}result+=str[i],i++}return result}function getGraphemeCellRange(line,column){let currentCol=0,i=0;for(;i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let width=graphemeWidth(segment);if(width>0&&column>=currentCol&&column<currentCol+width)return{start:currentCol,end:currentCol+width};currentCol+=width}i=textEnd}}function getOsc8LinkAtColumn(line,column){let activeUrl,currentCol=0,i=0;for(;i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){let hyperlink2=/^\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)$/.exec(ansi.code);hyperlink2&&(activeUrl=hyperlink2[1]||void 0),i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let width=segment===" "?3:graphemeWidth(segment);if(column>=currentCol&&column<currentCol+width)return activeUrl;currentCol+=width}i=textEnd}}var THAI_LAO_AM_REGEX=/[\u0e33\u0eb3]/,THAI_LAO_AM_GLOBAL_REGEX=/[\u0e33\u0eb3]/g;function normalizeTerminalOutput(str){let normalized=str;if(THAI_LAO_AM_REGEX.test(normalized)&&(normalized=normalized.replace(THAI_LAO_AM_GLOBAL_REGEX,char=>char==="\u0E33"?"\u0E4D\u0E32":"\u0ECD\u0EB2")),!normalized.includes(" "))return normalized;let result="",i=0;for(;i<normalized.length;){let ansi=extractAnsiCode(normalized,i);if(ansi){result+=ansi.code,i+=ansi.length;continue}result+=normalized[i]===" "?" ":normalized[i],i++}return result}function extractAnsiCode(str,pos){let length=ansiCodeLength(str,pos);return length>0?{code:str.substring(pos,pos+length),length}:null}function asciiVisibleWidth(str){let width=0,i=0;for(;i<str.length;){let code=str.charCodeAt(i);if(code>=32&&code<=126)width++,i++;else if(code===9)width+=3,i++;else if(code===27){let length=ansiCodeLength(str,i);if(length===0)return-1;i+=length}else return-1}return width}function ansiCodeLength(str,pos){if(pos>=str.length||str.charCodeAt(pos)!==27)return 0;let next=str[pos+1];if(next==="["){for(let j=pos+2;j<str.length;j++){let c=str.charCodeAt(j);if(c===109||c===71||c===75||c===72||c===74)return j+1-pos}return 0}if(next==="P"){let j=pos+2;for(;j<str.length;){if(str.charCodeAt(j)===27){if(str[j+1]==="\\")return j+2-pos;if(str.charCodeAt(j+1)===27){j+=2;continue}}j++}return 0}if(next==="]"||next==="_"){for(let j=pos+2;j<str.length;j++){let c=str.charCodeAt(j);if(c===7)return j+1-pos;if(c===27&&str[j+1]==="\\")return j+2-pos}return 0}return 0}function parseOsc8Hyperlink(ansiCode){if(!ansiCode.startsWith("\x1B]8;"))return;let terminator=ansiCode.endsWith("\x07")?"\x07":"\x1B\\",body=ansiCode.slice(4,terminator==="\x07"?-1:-2),separatorIndex=body.indexOf(";");if(separatorIndex===-1)return;let params=body.slice(0,separatorIndex),url=body.slice(separatorIndex+1);return url?{params,url,terminator}:null}function formatOsc8Hyperlink(hyperlink2){return`\x1B]8;${hyperlink2.params};${hyperlink2.url}${hyperlink2.terminator}`}function formatOsc8Close(terminator){return`\x1B]8;;${terminator}`}function getActiveOsc8Close(prefix){if(!prefix.includes("\x1B]8;"))return"";let activeHyperlink=null,i=0;for(;i<prefix.length;){let ansi=extractAnsiCode(prefix,i);if(ansi){let hyperlink2=parseOsc8Hyperlink(ansi.code);hyperlink2!==void 0&&(activeHyperlink=hyperlink2),i+=ansi.length}else i++}return activeHyperlink?formatOsc8Close(activeHyperlink.terminator):""}var AnsiCodeTracker=class{constructor(){this.bold=!1,this.dim=!1,this.italic=!1,this.underline=!1,this.blink=!1,this.inverse=!1,this.hidden=!1,this.strikethrough=!1,this.fgColor=null,this.bgColor=null,this.activeHyperlink=null}process(ansiCode){let hyperlink2=parseOsc8Hyperlink(ansiCode);if(hyperlink2!==void 0){this.activeHyperlink=hyperlink2;return}if(!ansiCode.endsWith("m"))return;let match=ansiCode.match(/\x1b\[([\d;]*)m/);if(!match)return;let params=match[1];if(params===""||params==="0"){this.reset();return}let parts=params.split(";"),i=0;for(;i<parts.length;){let code=Number.parseInt(parts[i],10);if(code===38||code===48){if(parts[i+1]==="5"&&parts[i+2]!==void 0){let colorCode=`${parts[i]};${parts[i+1]};${parts[i+2]}`;code===38?this.fgColor=colorCode:this.bgColor=colorCode,i+=3;continue}else if(parts[i+1]==="2"&&parts[i+4]!==void 0){let colorCode=`${parts[i]};${parts[i+1]};${parts[i+2]};${parts[i+3]};${parts[i+4]}`;code===38?this.fgColor=colorCode:this.bgColor=colorCode,i+=5;continue}}switch(code){case 0:this.reset();break;case 1:this.bold=!0;break;case 2:this.dim=!0;break;case 3:this.italic=!0;break;case 4:this.underline=!0;break;case 5:this.blink=!0;break;case 7:this.inverse=!0;break;case 8:this.hidden=!0;break;case 9:this.strikethrough=!0;break;case 21:this.bold=!1;break;case 22:this.bold=!1,this.dim=!1;break;case 23:this.italic=!1;break;case 24:this.underline=!1;break;case 25:this.blink=!1;break;case 27:this.inverse=!1;break;case 28:this.hidden=!1;break;case 29:this.strikethrough=!1;break;case 39:this.fgColor=null;break;case 49:this.bgColor=null;break;default:code>=30&&code<=37||code>=90&&code<=97?this.fgColor=String(code):(code>=40&&code<=47||code>=100&&code<=107)&&(this.bgColor=String(code));break}i++}}reset(){this.bold=!1,this.dim=!1,this.italic=!1,this.underline=!1,this.blink=!1,this.inverse=!1,this.hidden=!1,this.strikethrough=!1,this.fgColor=null,this.bgColor=null}clear(){this.reset(),this.activeHyperlink=null}getActiveCodes(){let codes=[];this.bold&&codes.push("1"),this.dim&&codes.push("2"),this.italic&&codes.push("3"),this.underline&&codes.push("4"),this.blink&&codes.push("5"),this.inverse&&codes.push("7"),this.hidden&&codes.push("8"),this.strikethrough&&codes.push("9"),this.fgColor&&codes.push(this.fgColor),this.bgColor&&codes.push(this.bgColor);let result=codes.length>0?`\x1B[${codes.join(";")}m`:"";return this.activeHyperlink&&(result+=formatOsc8Hyperlink(this.activeHyperlink)),result}getActiveBackgroundCode(){return this.bgColor?`\x1B[${this.bgColor}m`:""}hasActiveCodes(){return this.bold||this.dim||this.italic||this.underline||this.blink||this.inverse||this.hidden||this.strikethrough||this.fgColor!==null||this.bgColor!==null||this.activeHyperlink!==null}getLineEndReset(){let result="";return this.underline&&(result+="\x1B[24m"),this.activeHyperlink&&(result+=formatOsc8Close(this.activeHyperlink.terminator)),result}};function updateTrackerFromText(text,tracker){let i=text.indexOf("\x1B");for(;i!==-1;){let length=ansiCodeLength(text,i);length>0?(tracker.process(text.substring(i,i+length)),i+=length):i++,i=text.indexOf("\x1B",i)}}function getActiveBackgroundAnsi(text){let tracker=new AnsiCodeTracker;return updateTrackerFromText(text,tracker),tracker.getActiveBackgroundCode()}function*graphemeSegments(text){for(let{segment}of graphemeSegmenter.segment(text))yield segment}function splitIntoTokensWithAnsi(text){let tokens=[],current="",pendingAnsi="",currentKind=null,i=0,flushCurrent=()=>{current&&(tokens.push(current),current="",currentKind=null)};for(;i<text.length;){let ansiResult=extractAnsiCode(text,i);if(ansiResult){pendingAnsi+=ansiResult.code,i+=ansiResult.length;continue}let end=text.indexOf("\x1B",i+1);for(;end!==-1&&ansiCodeLength(text,end)===0;)end=text.indexOf("\x1B",end+1);end===-1&&(end=text.length);let chunk=text.slice(i,end),ascii=isPrintableAscii(chunk);for(let segment of ascii?chunk:graphemeSegments(chunk)){let segmentIsSpace=segment===" ";if(!ascii&&!segmentIsSpace&&cjkBreakRegex.test(segment)){flushCurrent();let token=pendingAnsi+segment;pendingAnsi="",tokens.push(token);continue}let segmentKind=segmentIsSpace?"space":"word";current&¤tKind!==segmentKind&&flushCurrent(),pendingAnsi&&(current+=pendingAnsi,pendingAnsi=""),currentKind=segmentKind,current+=segment}i=end}return pendingAnsi&&(current?current+=pendingAnsi:tokens.length>0?tokens[tokens.length-1]+=pendingAnsi:current=pendingAnsi),current&&tokens.push(current),tokens}function flattenLines(lines){for(let line of lines)Number(line)}function wrapTextWithAnsi(text,width,onLine){if(!text)return onLine?.(0,0),[""];let inputLines=text.split(/\r\n|\r|\n/),result=[],tracker=new AnsiCodeTracker,sourceOffset=0,separators=onLine?text.match(/\r\n|\r|\n/g)??[]:[];for(let index=0;index<inputLines.length;index++){let inputLine=inputLines[index],prefix=result.length>0?tracker.getActiveCodes():"",wrappedLines=wrapSingleLine(prefix+inputLine,width,onLine&&((start,end)=>onLine(sourceOffset+start,sourceOffset+end)));for(let wrappedLine of wrappedLines)result.push(wrappedLine);updateTrackerFromText(inputLine,tracker),onLine&&(sourceOffset+=stripTerminalSequences(inputLine).length+(separators[index]?.length??0))}return result.length>0?result:[""]}function wrapSingleLine(line,width,onLine){if(!line)return onLine?.(0,0),[""];if(visibleWidth(line)<=width)return onLine?.(0,stripTerminalSequences(line).length),[line];let wrapped=[],tracker=new AnsiCodeTracker,tokens=splitIntoTokensWithAnsi(line),currentLine="",currentVisibleLength=0,sourceOffset=0,lineStart=0,emit=text=>{onLine?.(lineStart,lineStart+stripTerminalSequences(text.trimEnd()).length)};for(let token of tokens){let tokenStart=sourceOffset;onLine&&(sourceOffset+=stripTerminalSequences(token).length);let tokenVisibleLength=visibleWidth(token),isWhitespace=token.trim()==="";if(tokenVisibleLength>width&&!isWhitespace){if(currentLine){let lineEndReset=tracker.getLineEndReset();lineEndReset&&(currentLine+=lineEndReset),wrapped.push(currentLine),emit(currentLine),currentLine="",currentVisibleLength=0}let broken=breakLongWord(token,width,tracker,onLine&&((start,end)=>{onLine(tokenStart+start,tokenStart+end)}));onLine&&(lineStart=sourceOffset-stripTerminalSequences(broken[broken.length-1]).length);for(let i=0;i<broken.length-1;i++)wrapped.push(broken[i]);currentLine=broken[broken.length-1],currentVisibleLength=visibleWidth(currentLine);continue}if(currentVisibleLength+tokenVisibleLength>width&¤tVisibleLength>0){let lineToWrap=currentLine.trimEnd(),lineEndReset=tracker.getLineEndReset();lineEndReset&&(lineToWrap+=lineEndReset),wrapped.push(lineToWrap),emit(lineToWrap),isWhitespace?(currentLine=tracker.getActiveCodes(),currentVisibleLength=0,lineStart=sourceOffset):(currentLine=tracker.getActiveCodes()+token,currentVisibleLength=tokenVisibleLength,lineStart=tokenStart)}else currentLine+=token,currentVisibleLength+=tokenVisibleLength;updateTrackerFromText(token,tracker)}return currentLine&&(wrapped.push(currentLine),emit(currentLine)),wrapped.length>0?wrapped.map(line2=>line2.trimEnd()):[""]}var PUNCTUATION_REGEX=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function isWhitespaceChar(char){return/\s/.test(char)}function breakLongWord(word,width,tracker,onLine){let lines=[],currentLine=tracker.getActiveCodes(),currentWidth=0,sourceOffset=0,lineStart=0,i=0,segments=[];for(;i<word.length;){let ansiResult=extractAnsiCode(word,i);if(ansiResult)segments.push({type:"ansi",value:ansiResult.code}),i+=ansiResult.length;else{let end=i;for(;end<word.length&&!extractAnsiCode(word,end);)end++;let textPortion=word.slice(i,end);for(let seg of graphemeSegmenter.segment(textPortion))segments.push({type:"grapheme",value:seg.segment});i=end}}for(let seg of segments){if(seg.type==="ansi"){currentLine+=seg.value,tracker.process(seg.value);continue}let grapheme=seg.value;if(!grapheme)continue;let graphemeWidth2=visibleWidth(grapheme);if(currentWidth+graphemeWidth2>width){let lineEndReset=tracker.getLineEndReset();lineEndReset&&(currentLine+=lineEndReset),lines.push(currentLine),onLine?.(lineStart,sourceOffset),lineStart=sourceOffset,currentLine=tracker.getActiveCodes(),currentWidth=0}currentLine+=grapheme,currentWidth+=graphemeWidth2,sourceOffset+=grapheme.length}return currentLine&&lines.push(currentLine),lines.length>0?lines:[""]}function sgrLeavesDefaultBackground(params){if(params==="")return!0;let parts=params.split(";"),backgroundIsDefault=!1,index=0;for(;index<parts.length;){let part=parts[index]??"",code=part===""?0:Number.parseInt(part,10);if(Number.isNaN(code)){index++;continue}if(code===0||code===49){backgroundIsDefault=!0,index++;continue}if((code===38||code===48)&&parts[index+1]==="5"&&parts[index+2]!==void 0){code===48&&(backgroundIsDefault=!1),index+=3;continue}if((code===38||code===48)&&parts[index+1]==="2"&&parts[index+4]!==void 0){code===48&&(backgroundIsDefault=!1),index+=5;continue}(code>=40&&code<=47||code>=100&&code<=107)&&(backgroundIsDefault=!1),index++}return backgroundIsDefault}function applyBackgroundToLine(line,width,bgFn){let visibleLen=visibleWidth(line),paddingNeeded=Math.max(0,width-visibleLen),padding=" ".repeat(paddingNeeded),withPadding=line+padding,marker="pi-bg-marker",wrappedMarker=bgFn(marker),markerIndex=wrappedMarker.indexOf(marker);if(markerIndex===-1)return bgFn(withPadding);let bgStart=wrappedMarker.slice(0,markerIndex),bgEnd=wrappedMarker.slice(markerIndex+marker.length),restoredLine=line.replace(/\x1b\[([0-9;]*)m/g,(sequence,params)=>sgrLeavesDefaultBackground(params)?`${sequence}${bgStart}`:sequence),tracker=new AnsiCodeTracker;updateTrackerFromText(line,tracker);let restored=paddingNeeded>0&&tracker.hasActiveCodes()?`${restoredLine}\x1B[0m${tracker.getLineEndReset()}${bgStart}${padding}`:restoredLine+padding;return`${bgStart}${restored}${bgEnd}`}function truncateToWidth(text,maxWidth,ellipsis="...",pad=!1){if(maxWidth<=0)return"";if(text.length===0)return pad?" ".repeat(maxWidth):"";let ellipsisWidth=visibleWidth(ellipsis);if(ellipsisWidth>=maxWidth){let textWidth=visibleWidth(text);if(textWidth<=maxWidth)return pad?text+" ".repeat(maxWidth-textWidth):text;let clippedEllipsis=truncateFragmentToWidth(ellipsis,maxWidth);return clippedEllipsis.width===0?pad?" ".repeat(maxWidth):"":finalizeTruncatedResult("",0,clippedEllipsis.text,clippedEllipsis.width,maxWidth,pad)}if(isPrintableAscii(text)){if(text.length<=maxWidth)return pad?text+" ".repeat(maxWidth-text.length):text;let targetWidth2=maxWidth-ellipsisWidth;return finalizeTruncatedResult(text.slice(0,targetWidth2),targetWidth2,ellipsis,ellipsisWidth,maxWidth,pad)}let targetWidth=maxWidth-ellipsisWidth,result="",pendingAnsi="",visibleSoFar=0,keptWidth=0,keepContiguousPrefix=!0,overflowed=!1,exhaustedInput=!1,hasAnsi=text.includes("\x1B"),hasTabs=text.includes(" ");if(!hasAnsi&&!hasTabs){for(let{segment}of graphemeSegmenter.segment(text)){let width=graphemeWidth(segment);if(keepContiguousPrefix&&keptWidth+width<=targetWidth?(result+=segment,keptWidth+=width):keepContiguousPrefix=!1,visibleSoFar+=width,visibleSoFar>maxWidth){overflowed=!0;break}}exhaustedInput=!overflowed}else{let i=0;for(;i<text.length;){let ansi=extractAnsiCode(text,i);if(ansi){pendingAnsi+=ansi.code,i+=ansi.length;continue}if(text[i]===" "){if(keepContiguousPrefix&&keptWidth+3<=targetWidth?(pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=" ",keptWidth+=3):(keepContiguousPrefix=!1,pendingAnsi=""),visibleSoFar+=3,visibleSoFar>maxWidth){overflowed=!0;break}i++;continue}let end=i;for(;end<text.length&&text[end]!==" "&&!extractAnsiCode(text,end);)end++;for(let{segment}of graphemeSegmenter.segment(text.slice(i,end))){let width=graphemeWidth(segment);if(keepContiguousPrefix&&keptWidth+width<=targetWidth?(pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=segment,keptWidth+=width):(keepContiguousPrefix=!1,pendingAnsi=""),visibleSoFar+=width,visibleSoFar>maxWidth){overflowed=!0;break}}if(overflowed)break;i=end}exhaustedInput=i>=text.length}return!overflowed&&exhaustedInput?pad?text+" ".repeat(Math.max(0,maxWidth-visibleSoFar)):text:finalizeTruncatedResult(result,keptWidth,ellipsis,ellipsisWidth,maxWidth,pad)}function sliceByColumn(line,startCol,length,strict=!1){return sliceWithWidth(line,startCol,length,strict).text}function sliceWithWidth(line,startCol,length,strict=!1){if(length<=0)return{text:"",width:0};let endCol=startCol+length,result="",resultWidth=0,currentCol=0,i=0,pendingAnsi="";for(;i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){currentCol>=startCol&¤tCol<endCol?(result+=pendingAnsi+ansi.code,pendingAnsi=""):currentCol<startCol&&(pendingAnsi+=ansi.code),i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let w=graphemeWidth(segment),inRange=currentCol>=startCol&¤tCol<endCol,fits=!strict||currentCol+w<=endCol;if(inRange&&fits&&(pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=segment,resultWidth+=w),currentCol+=w,currentCol>=endCol)break}if(i=textEnd,currentCol>=endCol)break}return{text:result,width:resultWidth}}var pooledStyleTracker=new AnsiCodeTracker;function extractSegments(line,beforeEnd,afterStart,afterLen,strictAfter=!1){let before="",beforeWidth=0,after="",afterWidth=0,currentCol=0,i=0,pendingAnsiBefore="",afterStarted=!1,afterEnd=afterStart+afterLen;for(pooledStyleTracker.clear();i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){pooledStyleTracker.process(ansi.code),currentCol<beforeEnd?pendingAnsiBefore+=ansi.code:currentCol>=afterStart&¤tCol<afterEnd&&afterStarted&&(after+=ansi.code),i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of graphemeSegmenter.segment(line.slice(i,textEnd))){let w=graphemeWidth(segment);if(currentCol<beforeEnd&¤tCol+w<=beforeEnd?(pendingAnsiBefore&&(before+=pendingAnsiBefore,pendingAnsiBefore=""),before+=segment,beforeWidth+=w):currentCol>=afterStart&¤tCol<afterEnd&&(!strictAfter||currentCol+w<=afterEnd)&&(afterStarted||(after+=pooledStyleTracker.getActiveCodes(),afterStarted=!0),after+=segment,afterWidth+=w),currentCol+=w,afterLen<=0?currentCol>=beforeEnd:currentCol>=afterEnd)break}if(i=textEnd,afterLen<=0?currentCol>=beforeEnd:currentCol>=afterEnd)break}return{before,beforeWidth,after,afterWidth}}import{execFile}from"node:child_process";import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";import{performance as performance2}from"node:perf_hooks";function buildKittyGraphicsQuery(imageId){return`\x1B_Gi=${imageId},s=1,v=1,a=q,t=d,f=24;AAAA\x1B\\`}function parseKittyGraphicsProbeResponse(data,imageId){if(!data.startsWith("\x1B_G")||!data.endsWith("\x1B\\"))return null;let body=data.slice(3,-2),separator=body.indexOf(";");if(separator===-1)return null;let keys=body.slice(0,separator),message=body.slice(separator+1),idMatch=/(?:^|,)i=(\d+)(?:,|$)/.exec(keys);return!idMatch||Number.parseInt(idMatch[1]??"",10)!==imageId?null:message.startsWith("OK")?"ok":"err"}function isMultiplexerSession(env=process.env){return!!(env.TMUX||env.TMUX_PANE||env.STY||env.ZELLIJ)}function useLegacyMuxRender(){return process.env.PI_TUI_LEGACY_MUX_RENDER==="1"}function viewportRenderEnabled(){return process.env.PI_TUI_VIEWPORT_RENDER!=="0"}var emptyRanges={length:0,spans:[]},LinearRanges=class{constructor(start,length){this.start=start,this.length=length}get spans(){return[{offset:0,length:this.length,source:{start:this.start,end:this.start+this.length},linear:!0}]}};function linearRanges(start,length){return length?new LinearRanges(start,length):emptyRanges}function repeatedRange(source,length){return length?{length,spans:source===void 0?[]:[{offset:0,length,source,linear:!1}]}:emptyRanges}function firstSpan(ranges,offset){let low=0,high=ranges.spans.length;for(;low<high;){let middle=low+high>>>1,span=ranges.spans[middle];span.offset+span.length<=offset?low=middle+1:high=middle}return low}function rangeAt(ranges,offset){if(ranges instanceof LinearRanges){if(offset<0||offset>=ranges.length)return;let start2=ranges.start+offset;return{start:start2,end:start2+1}}let span=ranges.spans[firstSpan(ranges,offset)];if(!span||offset<span.offset)return;if(!span.linear||!span.source)return span.source;let start=span.source.start+offset-span.offset;return{start,end:start+1}}function sliceRanges(ranges,from,to=ranges.length){let start=Math.max(0,Math.min(ranges.length,from<0?ranges.length+from:from)),end=Math.max(start,Math.min(ranges.length,to<0?ranges.length+to:to));if(start===0&&end===ranges.length)return ranges;if(ranges instanceof LinearRanges)return linearRanges(ranges.start+start,end-start);let spans=[];for(let index=firstSpan(ranges,start);index<ranges.spans.length;index++){let span=ranges.spans[index];if(span.offset>=end)break;let left=Math.max(start,span.offset),right=Math.min(end,span.offset+span.length);spans.push({offset:left-start,length:right-left,source:span.linear&&span.source?{start:span.source.start+left-span.offset,end:span.source.start+right-span.offset}:span.source,linear:span.linear})}return compactRanges(end-start,spans)}function concatRanges(parts){if(parts.length===1)return parts[0];let spans=[],length=0;for(let part of parts){for(let span of part.spans){let offset=length+span.offset,previous=spans.at(-1);previous&&previous.offset+previous.length===offset&&previous.linear===span.linear&&(previous.linear?previous.source&&span.source&&previous.source.end===span.source.start:previous.source?.start===span.source?.start&&previous.source?.end===span.source?.end)?spans[spans.length-1]={...previous,length:previous.length+span.length,source:previous.linear&&previous.source&&span.source?{start:previous.source.start,end:span.source.end}:previous.source}:spans.push(length?{...span,offset}:span)}length+=part.length}return compactRanges(length,spans)}function compactRanges(length,spans){if(!length)return emptyRanges;let span=spans[0];return spans.length===1&&span.offset===0&&span.length===length&&span.linear&&span.source?linearRanges(span.source.start,length):{length,spans}}var sources=new WeakMap;function setLineSources(lines,mapping){sources.set(lines,[...mapping])}function setLineSource(lines,row,source){let mapping=sources.get(lines)??[];mapping[row]=source,sources.set(lines,mapping)}function getLineSources(lines){return sources.get(lines)}function copyLineSources(from,to,rowOffset=0,columnOffset=0){let mapping=sources.get(from);if(mapping){let result=sources.get(to)??[];for(let row=0;row<mapping.length&&row+rowOffset<to.length;row++){let line=mapping[row];result[row+rowOffset]=line&&columnOffset?line.sourceRow===void 0?{...line,ranges:concatRanges([repeatedRange(void 0,columnOffset),line.ranges])}:{...line,columnOffset:(line.columnOffset??0)+columnOffset}:line}sources.set(to,result)}return to}function resolveSourceSelection(lines,rows){let mapping=sources.get(lines);if(!mapping)return;let resolvedDocuments=new Map;for(let selection of rows){let document=mapping[selection.row]?.document;if(!document?.resolveLines||resolvedDocuments.has(document))continue;let resolved=document.resolveLines();resolvedDocuments.set(document,{lines:resolved,document:{...resolved?.find(line=>line)?.document??document}})}let resolveLine=line=>{if(!line)return;if(line.sourceRow===void 0)return line;let resolved=resolvedDocuments.get(line.document);if(!resolved)return;if(!resolved.lines)return{document:resolved.document,ranges:emptyRanges,unavailable:!0};let original=resolved.lines[line.sourceRow];if(original)return{...original,document:resolved.document,ranges:line.columnOffset?concatRanges([repeatedRange(void 0,line.columnOffset),original.ranges]):original.ranges}},documentLines=new Map;for(let source of mapping){let line=resolveLine(source);if(!line)continue;let group=documentLines.get(line.document);group?group.push(line):documentLines.set(line.document,[line])}let pieces=[],active,usedSource=!1,unavailable=!1,renderedFallback=!1,flush=()=>{if(!active)return;let{start,end}=active,covered=[];for(let range of active.selected.sort((left,right)=>left.start-right.start)){let previous=covered.at(-1);previous&&previous.end>=range.start?previous.end=Math.max(previous.end,range.end):covered.push({...range})}for(let line of documentLines.get(active.document)??[])for(let span of line.ranges.spans){let range=span.source;if(!range)continue;let left=span.linear?Math.max(start,range.start):range.start,right=span.linear?Math.min(end,range.end):range.end;if(left<start||right>end||left>=right)continue;let low=0,high=covered.length;for(;low<high;){let middle=low+high>>>1;covered[middle].start<=left?low=middle+1:high=middle}(low===0||covered[low-1].end<right)&&(unavailable=!0)}for(let enclosure of active.document.enclosures)start<=enclosure.content.start&&end>=enclosure.content.end&&(start=Math.min(start,enclosure.start),end=Math.max(end,enclosure.end));pieces.push(active.document.text.slice(start,end)),active=void 0};for(let selection of rows){let source=mapping[selection.row];if(source===null)continue;let line=resolveLine(source),text=stripTerminalSequences(lines[selection.row]??"");if(!line){if(source&&!text.trim())continue;flush();let column2=0,selected="";for(let{segment}of getGraphemeSegmenter().segment(text)){let width=visibleWidth(segment);column2<selection.end&&column2+width>selection.start&&(selected+=segment),column2+=width}pieces.push(selected.trimEnd());continue}usedSource=!0,active&&active.document!==line.document&&flush();let column=0,unitStart=text.length,unitEnd=0;for(let{segment,index}of getGraphemeSegmenter().segment(text)){let width=visibleWidth(segment);if(column<selection.end&&column+width>selection.start){if(line.unavailable&&segment.trim())return{unavailable:!0};line.renderedFallback&&segment.trim()&&(renderedFallback=!0),unitStart=Math.min(unitStart,index),unitEnd=index+segment.length}column+=width}for(let span of sliceRanges(line.ranges,unitStart,unitEnd).spans){let range=span.source;if(range===null)return{unavailable:!0};active?(active.start=Math.min(active.start,range.start),active.end=Math.max(active.end,range.end)):active={document:line.document,...range,selected:[]},active.selected.push(range)}}return flush(),unavailable?{unavailable:!0}:renderedFallback?{renderedFallback:!0}:usedSource?{text:pieces.join(`
`)}:void 0}function hexToRgb(hex){let normalized=hex.startsWith("#")?hex.slice(1):hex,r=parseInt(normalized.slice(0,2),16),g=parseInt(normalized.slice(2,4),16),b2=parseInt(normalized.slice(4,6),16);return{r,g,b:b2}}function parseOscHexChannel(channel){if(!/^[0-9a-f]+$/i.test(channel))return;let max=16**channel.length-1;if(!(max<=0))return Math.round(parseInt(channel,16)/max*255)}var OSC_COLOR_RESPONSE_PATTERN=/^\x1b\](?:(1[01])|4;(\d{1,3}));([^\x07\x1b]*)(?:\x07|\x1b\\)$/i,COLOR_SCHEME_REPORT_PATTERN=/^(?:\x1b\[\?997;(1|2)n)+$/;function parseOscColorResponse(data){let match=data.match(OSC_COLOR_RESPONSE_PATTERN);return match?{target:match[1]==="10"?"foreground":match[1]==="11"?"background":Number.parseInt(match[2],10),rgb:parseOscColorValue(match[3])}:void 0}function parseOscColorValue(rawValue){let value=rawValue.trim();if(value.startsWith("#")){let hex=value.slice(1);if(/^[0-9a-f]{6}$/i.test(hex))return hexToRgb(value);if(/^[0-9a-f]{12}$/i.test(hex)){let r2=parseOscHexChannel(hex.slice(0,4)),g2=parseOscHexChannel(hex.slice(4,8)),b3=parseOscHexChannel(hex.slice(8,12));return r2!==void 0&&g2!==void 0&&b3!==void 0?{r:r2,g:g2,b:b3}:void 0}return}let rgbValue=value.replace(/^rgba?:/i,""),[red,green,blue]=rgbValue.split("/");if(red===void 0||green===void 0||blue===void 0)return;let r=parseOscHexChannel(red),g=parseOscHexChannel(green),b2=parseOscHexChannel(blue);return r!==void 0&&g!==void 0&&b2!==void 0?{r,g,b:b2}:void 0}function parseTerminalColorSchemeReport(data){let match=data.match(COLOR_SCHEME_REPORT_PATTERN);if(match)return match[1]==="2"?"light":"dark"}var ENABLE_FOCUS_REPORTING="\x1B[?1004h",DISABLE_FOCUS_REPORTING="\x1B[?1004l";function consumeTmuxFocusEvent(data){let focusIn=data.indexOf("\x1B[I"),focusOut=data.indexOf("\x1B[O"),index=focusIn===-1?focusOut:focusOut===-1?focusIn:Math.min(focusIn,focusOut);return index===-1?{event:null,data}:{event:index===focusIn?"in":"out",data:data.slice(0,index)+data.slice(index+3)}}function shiftedBlockMoved(previousLines,newLines,prevViewportTop,shift,height){if(shift<=0||shift>prevViewportTop)return!1;for(let row=prevViewportTop;row<prevViewportTop+shift;row++){let scrolled=previousLines[row-shift];if(scrolled===void 0||scrolled!==newLines[row])return!1}let scanFloor=Math.max(shift,prevViewportTop-2*height);for(let row=prevViewportTop+shift-1;row>=scanFloor;row--){let line=newLines[row];if(line!==previousLines[row-shift])return!1;if(line!==previousLines[row])return!0}return!1}function insertedAboveViewport(previousLines,newLines,prevViewportTop,height,lineCountDelta){if(lineCountDelta<=0)return 0;let visibleMatchesAt=shift=>{let matches=0;for(let row=0;row<height;row++){let previous=previousLines[prevViewportTop+row];previous!==void 0&&previous===newLines[prevViewportTop+shift+row]&&(matches+=1)}return matches},best=0,bestMatches=visibleMatchesAt(0);for(let shift=1;shift<=Math.min(lineCountDelta,prevViewportTop);shift++){if(!shiftedBlockMoved(previousLines,newLines,prevViewportTop,shift,height))continue;let matches=visibleMatchesAt(shift);matches>bestMatches&&(best=shift,bestMatches=matches)}return bestMatches*2>height?best:0}var MAX_SCROLL_DIFF_ROWS=4;function viewportRows(lines,viewportTop,height){return Array.from({length:height},(_2,row)=>lines[viewportTop+row]??"")}function planViewportInsertScroll(previousLines,newLines,prevViewportTop,height,lineCountDelta){if(lineCountDelta<=0||lineCountDelta>=height)return;let maxViewportTop=Math.max(0,newLines.length-height),viewportTop=Math.min(maxViewportTop,prevViewportTop+lineCountDelta);if(viewportTop<=prevViewportTop)return;let previousVisible=viewportRows(previousLines,prevViewportTop,height),nextVisible=viewportRows(newLines,viewportTop,height);if(previousVisible.some(isImageLine)||nextVisible.some(isImageLine))return;let scrolledOut=viewportTop-prevViewportTop;for(let row=0;row<scrolledOut;row++)if(previousVisible[row]!==newLines[prevViewportTop+row])return;if(shiftedBlockMoved(previousLines,newLines,prevViewportTop,scrolledOut,height))return;let stableSuffixRows=0;for(;stableSuffixRows<height&&previousVisible[height-stableSuffixRows-1]===nextVisible[height-stableSuffixRows-1];)stableSuffixRows+=1;let regionHeight=height-stableSuffixRows;if(regionHeight<=0||regionHeight<lineCountDelta)return;let mutatedRows=[];for(let row=0;row<regionHeight-lineCountDelta;row++)if(previousVisible[row+lineCountDelta]!==nextVisible[row]&&(mutatedRows.push({screenRow:row,content:nextVisible[row]??""}),mutatedRows.length>MAX_SCROLL_DIFF_ROWS))return;return{viewportTop,regionBottom:regionHeight-1,insertedRows:nextVisible.slice(regionHeight-lineCountDelta,regionHeight),mutatedRows}}var KITTY_SEQUENCE_PREFIX="\x1B_G",MAX_RENDER_WRITE_CHARS=1024*1024;function writeBounded(terminal,data){for(let offset=0;offset<data.length;offset+=MAX_RENDER_WRITE_CHARS){let end=Math.min(data.length,offset+MAX_RENDER_WRITE_CHARS);end<data.length&&data.charCodeAt(end-1)>=55296&&data.charCodeAt(end-1)<=56319&&data.charCodeAt(end)>=56320&&data.charCodeAt(end)<=57343&&end--,end===offset&&end++,terminal.write(data.slice(offset,end))}}function parseKittyImageHeader(line){let sequenceStart=line.indexOf(KITTY_SEQUENCE_PREFIX);if(sequenceStart===-1)return;let paramsStart=sequenceStart+KITTY_SEQUENCE_PREFIX.length,paramsEnd=line.indexOf(";",paramsStart);if(paramsEnd===-1)return;let ids=[],rows=1;for(let param of line.slice(paramsStart,paramsEnd).split(",")){let[key,value]=param.split("=",2);if(value===void 0)continue;let numberValue=Number(value);!Number.isInteger(numberValue)||numberValue<=0||numberValue>4294967295||(key==="i"?ids.push(numberValue):key==="r"&&(rows=numberValue))}return{ids,rows}}function extractKittyImageIds(line){return parseKittyImageHeader(line)?.ids??[]}function extractKittyImageRows(line){return parseKittyImageHeader(line)?.rows??1}function isTermuxSession(){return!!process.env.TERMUX_VERSION}function dispatchMouseEvent(component,event){let result=component.handleMouse?.(event);if(result){if("target"in result){let forwarded=result;return forwarded.focus&&component.handleInput?{...forwarded,focusTarget:component}:forwarded}if(!(!result.handled&&!result.capture&&!result.focus))return{...result,handled:!0,...result.focus?{focusTarget:component}:{},target:{component,originX:event.screenX-event.x,originY:event.screenY-event.y,width:event.width,height:event.height}}}}function retargetMouseEvent(event,target){return{...event,x:event.screenX-target.originX,y:event.screenY-target.originY,width:target.width,height:target.height}}var TERMINAL_PALETTE_SIZE=16,TERMINAL_COLOR_REPLY_COUNT=2+TERMINAL_PALETTE_SIZE,TERMINAL_COLOR_QUERY=`\x1B]10;?\x07\x1B]11;?\x07${Array.from({length:TERMINAL_PALETTE_SIZE},(_2,index)=>`\x1B]4;${index};?\x07`).join("")}\x1B[c`,DEVICE_ATTRIBUTES_RESPONSE_PATTERN=/^\x1b\[\?[\d;]*c$/;function isFocusable(component){return component!==null&&"focused"in component}function canReceiveKeys(component){return component!==null&&typeof component.handleInput=="function"}var CURSOR_MARKER="\x1B_pi:c\x07",FAKE_CURSOR_START="\x1B[7m",FAKE_CURSOR_END="\x1B[27m",FAKE_CURSOR_RESET="\x1B[0m";var renderErrorLoggedClasses=new Set,renderErrorLogWrites=0,renderDiagnosticLineScans=0,DIAGNOSTIC_LOG_MODE=384;function defaultDiagnosticLogDirectory(){return path.join(os.homedir(),".senpi","agent")}var renderErrorLogDirectory,VIEWPORT_RENDER_OVERSCAN=16,viewportRenderStats={lastNormalizedLines:0,lastKittyImageScannedLines:0,totalNormalizedLines:0,totalKittyImageScannedLines:0,boundedFrames:0,escapedFrames:0,fullFrames:0};function recordViewportRenderStats(normalizedLines,mode){viewportRenderStats.lastNormalizedLines=normalizedLines,viewportRenderStats.totalNormalizedLines+=normalizedLines,mode==="bounded"?viewportRenderStats.boundedFrames+=1:mode==="escaped"?viewportRenderStats.escapedFrames+=1:viewportRenderStats.fullFrames+=1}function recordKittyImageScanStats(scannedLines){viewportRenderStats.lastKittyImageScannedLines=scannedLines,viewportRenderStats.totalKittyImageScannedLines+=scannedLines}function componentRenderErrorName(component){return component.constructor.name||"AnonymousComponent"}function logRenderErrorOnce(component,error){let componentName=componentRenderErrorName(component);if(renderErrorLoggedClasses.has(componentName))return;renderErrorLoggedClasses.add(componentName),renderErrorLogWrites+=1;let errorText=error instanceof Error?`${error.name}: ${error.message}`:String(error),logPath=path.join(renderErrorLogDirectory??defaultDiagnosticLogDirectory(),"senpi-debug.log"),msg=`[${new Date().toISOString()}] render error: ${componentName}: ${errorText}
`;appendRenderErrorLogBestEffort(logPath,msg)}function appendRenderErrorLogBestEffort(logPath,msg){try{fs.mkdirSync(path.dirname(logPath),{recursive:!0}),fs.appendFileSync(logPath,msg,{encoding:"utf8",mode:DIAGNOSTIC_LOG_MODE}),chmodDiagnosticLogBestEffort(logPath)}catch(error){if(error instanceof Error)return;throw error}}function writeRenderDiagnosticBestEffort(logPath,data){try{return fs.mkdirSync(path.dirname(logPath),{recursive:!0}),fs.writeFileSync(logPath,data,{encoding:"utf8",mode:DIAGNOSTIC_LOG_MODE}),chmodDiagnosticLogBestEffort(logPath),!0}catch(error){if(error instanceof Error)return!1;throw error}}function formatOverWideRenderDiagnostic(lines,terminalWidth,lineIndex,lineWidth){return renderDiagnosticLineScans+=lines.length,[`Crash at ${new Date().toISOString()}`,`Terminal width: ${terminalWidth}`,`Line ${lineIndex} visible width: ${lineWidth}`,"","=== All rendered lines ===",...lines.map((line,index)=>`[${index}] (w=${visibleWidth(line)}) ${line}`),""].join(`
`)}function chmodDiagnosticLogBestEffort(logPath){try{fs.chmodSync(logPath,DIAGNOSTIC_LOG_MODE)}catch(error){if(error instanceof Error)return;throw error}}function parseSizeValue(value,referenceSize){if(value===void 0)return;if(typeof value=="number")return value;let match=value.match(/^(\d+(?:\.\d+)?)%$/);if(match)return Math.floor(referenceSize*parseFloat(match[1])/100)}var renderFrame={scrollbackRows:0,offset:0,next:void 0,mode:void 0,rows:0};function frameMode(){return renderFrame.mode}var DEFAULT_HISTORY_LINES=2e3,MAX_HISTORY_LINES=5e3,terminalScrollbackLines,scrollbackLookupGeneration=0;function readTerminalScrollbackLines(){let override=Number(process.env.PI_TUI_HISTORY_LINES);if(Number.isFinite(override)&&override>0)return Math.floor(override);if(!process.env.TMUX)return null;let generation=scrollbackLookupGeneration;try{execFile("tmux",["display-message","-p","#{history_limit}"],{encoding:"utf8",timeout:500},(error,stdout)=>{if(generation!==scrollbackLookupGeneration)return;let limit=Number(stdout.trim());!error&&Number.isFinite(limit)&&limit>0&&(terminalScrollbackLines=limit)})}catch{}return null}function mainScreenHistoryLines(rows=renderFrame.rows){terminalScrollbackLines===void 0&&(terminalScrollbackLines=readTerminalScrollbackLines());let preferred=Math.min(MAX_HISTORY_LINES,terminalScrollbackLines??DEFAULT_HISTORY_LINES);return Math.min(MAX_HISTORY_LINES,Math.max(2*Math.max(1,rows),preferred))}function resetMainScreenHistoryLines(){terminalScrollbackLines=void 0,scrollbackLookupGeneration+=1}function frameScrollbackRows(){return renderFrame.scrollbackRows}function claimFrameRow(component){if(renderFrame.next===component)return renderFrame.next=void 0,renderFrame.offset}function renderAtFrameRow(child,width,row){if(row===void 0)return child.render(width);let previousOffset=renderFrame.offset,previousNext=renderFrame.next;renderFrame.offset=row,renderFrame.next=child;try{return child.render(width)}finally{renderFrame.offset=previousOffset,renderFrame.next=previousNext}}var renderRevisionClock=0;function nextRenderRevision(){return renderRevisionClock+=1,renderRevisionClock}function currentRenderRevision(){return renderRevisionClock}var FRAME_LINE_BYTES_KEY=Symbol.for("senpi.tui.frame-line-bytes");function frameLineBytesState(){let existing=Reflect.get(globalThis,FRAME_LINE_BYTES_KEY);if(typeof existing=="object"&&existing!==null&&typeof Reflect.get(existing,"bytes")=="number")return existing;let created={bytes:0};return Reflect.set(globalThis,FRAME_LINE_BYTES_KEY,created),created}function frameLineBytesTotals(){return{previousLinesBytes:frameLineBytesState().bytes}}var CompositeRevision=class{constructor(){this.revision=nextRenderRevision(),this.children=[],this.childRevisions=[],this.checkedAt=-1}bump(){this.revision=nextRenderRevision()}read(children){let replaced=children.length!==this.children.length;for(let index=0;!replaced&&index<children.length;index++)children[index]!==this.children[index]&&(replaced=!0);if(!replaced&&this.checkedAt===renderRevisionClock)return this.revision;let revisions=[];for(let child of children){let revision=child.getRenderRevision?.();if(revision===void 0){this.children=[],this.childRevisions=[],this.checkedAt=-1;return}revisions.push(revision)}return(replaced||revisions.some((revision,index)=>revision!==this.childRevisions[index]))&&(this.revision=nextRenderRevision(),this.children=[...children]),this.childRevisions=revisions,this.checkedAt=renderRevisionClock,this.revision}},Container=class _Container{constructor(){this.children=[],this.disposed=!1,this.composite=new CompositeRevision}addChild(component){this.children.push(component),this.composite.bump()}removeChild(component){let index=this.children.indexOf(component);index!==-1&&(this.children.splice(index,1),this.composite.bump(),component.dispose?.())}detachChild(component){let index=this.children.indexOf(component);index!==-1&&(this.children.splice(index,1),this.composite.bump())}clear(){for(let child of this.children)child.dispose?.();this.children=[],this.composite.bump()}detachAll(){this.children=[],this.composite.bump()}dispose(){if(!this.disposed){this.disposed=!0;for(let child of this.children)child.dispose?.()}}invalidate(){this.composite.bump();for(let child of this.children)child.invalidate?.()}getRenderRevision(){return Object.getPrototypeOf(this)===_Container.prototype?this.childRenderRevision():void 0}childRenderRevision(){return this.composite.read(this.children)}bumpRenderRevision(){this.composite.bump()}handleMouse(event){if(event.y<0||event.y>=event.height)return;let mouseChildren=this.mouseLayout?.width===event.width?this.mouseLayout.children:this.children.map(component=>({component,height:component.render(event.width).length})),childY=0;for(let{component:child,height:childHeight}of mouseChildren){if(event.y>=childY&&event.y<childY+childHeight){let result=dispatchMouseEvent(child,{...event,y:event.y-childY,height:childHeight});return result?.focus&&this.handleInput?{...result,focusTarget:this}:result}childY+=childHeight}}render(width){let chunks=[],mouseChildren=[],row=claimFrameRow(this);for(let child of this.children){let childLines;try{childLines=renderAtFrameRow(child,width,row)}catch(error){logRenderErrorOnce(child,error),childLines=[`[render error: ${componentRenderErrorName(child)}]`]}mouseChildren.push({component:child,height:childLines.length}),chunks.push(childLines),row!==void 0&&(row+=childLines.length)}return this.mouseLayout={width,children:mouseChildren},joinLineArrays(chunks)}},JOIN_BATCH=1024;function joinLineArrays(chunks){if(chunks.length<=JOIN_BATCH){let result=[].concat(...chunks),offset=0;for(let chunk of chunks)copyLineSources(chunk,result,offset),offset+=chunk.length;return result}let batches=[];for(let start=0;start<chunks.length;start+=JOIN_BATCH)batches.push(joinLineArrays(chunks.slice(start,start+JOIN_BATCH)));return joinLineArrays(batches)}var SEGMENT_RESET="\x1B[0m\x1B]8;;\x07";function compositeTuiLine(baseLine,overlayLine,startCol,overlayWidth,totalWidth){if(isImageLine(baseLine)&&visibleWidth(baseLine)===0)return baseLine;let placeholderIndex=baseLine.indexOf("\u{10EEEE}"),protocolEnd=placeholderIndex===-1?-1:baseLine.lastIndexOf("\x1B\\",placeholderIndex),protocolPrefix=protocolEnd===-1?"":baseLine.slice(0,protocolEnd+2),afterStart=startCol+overlayWidth,base=extractSegments(baseLine,startCol,afterStart,totalWidth-afterStart,!0),overlay=sliceWithWidth(overlayLine,0,overlayWidth,!0),beforePad=Math.max(0,startCol-base.beforeWidth),overlayPad=Math.max(0,overlayWidth-overlay.width),actualBeforeWidth=Math.max(startCol,base.beforeWidth),actualOverlayWidth=Math.max(overlayWidth,overlay.width),afterTarget=Math.max(0,totalWidth-actualBeforeWidth-actualOverlayWidth),afterPad=Math.max(0,afterTarget-base.afterWidth),result=base.before+" ".repeat(beforePad)+SEGMENT_RESET+overlay.text+" ".repeat(overlayPad)+SEGMENT_RESET+base.after+" ".repeat(afterPad),composited=visibleWidth(result)<=totalWidth?result:sliceByColumn(result,0,totalWidth,!0);return protocolPrefix+composited}var VIEWPORT_TUI=Symbol.for("@earendil-works/pi-tui/viewport");function isViewportTUI(tui){return tui[VIEWPORT_TUI]===!0}var TuiBase=class extends Container{#muxViewportRepaintPending;#minRenderIntervalMs;#lastCursorVisibility;#holdScrollbackReplay;#releaseHoldOnInput;#scrollbackStale;#scrollbackCatchUpPending;get hasOverlayEntries(){return this.overlayStack.length>0}#muxDetector;constructor(terminal,options,logDirectory){super(),this.previousLines=[],this.previousRawLines=[],this.normalizeMemo=new Map,this.previousKittyImageIds=new Set,this.#muxViewportRepaintPending=!1,this.previousWidth=0,this.previousHeight=0,this.focusedComponent=null,this.inputListeners=new Set,this.renderRequested=!1,this.lastRenderAt=0,this.#minRenderIntervalMs=16,this.inputRenderPending=!1,this.cursorRow=0,this.hardwareCursorRow=0,this.showHardwareCursor=process.env.PI_HARDWARE_CURSOR==="1",this.clearOnShrink=process.env.PI_CLEAR_ON_SHRINK==="1",this.maxLinesRendered=0,this.previousViewportTop=0,this.fullRedrawCount=0,this.muxViewportRepaintCount=0,this.overWideCrashDumpWritten=!1,this.stopped=!1,this.pendingTerminalColorQueries=[],this.terminalColorSchemeListeners=new Set,this.terminalColorSchemeNotificationsEnabled=!1,this.#holdScrollbackReplay=!1,this.#releaseHoldOnInput=!1,this.#scrollbackStale=!1,this.#scrollbackCatchUpPending=!1,this.focusOrderCounter=0,this.overlayStack=[],this.renderedOverlayLayouts=[],this.overlayFocusRestore={status:"inactive"},this.mouseLeases=new Map,this.mouseBlockers=new Set,this.placementEpoch=0,this.anchor={kind:"unknown",epoch:0,rows:0,columns:0},this.mouseCommittedLineCount=0,this.mouseAnchorPending=!1,this.mouseExternalWritePending=!1,this.frameLineBytes=0,this.terminal=terminal;let normalizedOptions=typeof options=="boolean"?{showHardwareCursor:options}:options??{};this.#muxDetector=normalizedOptions.muxDetector??isMultiplexerSession,this.logDirectory=logDirectory??defaultDiagnosticLogDirectory(),renderErrorLogDirectory=this.logDirectory,normalizedOptions.showHardwareCursor!==void 0&&(this.showHardwareCursor=normalizedOptions.showHardwareCursor)}acquireMouseCapture(reason){let token=Symbol(reason),first=this.mouseLeases.size===0;return this.mouseLeases.set(token,reason),first&&(this.mouseWriteUnsubscribe??=this.terminal.observeExternalWrites?.(()=>{this.placementEpoch++,this.mouseExternalWritePending=!0}),this.applyMouseTracking(this.mouseCaptureEnabled),this.calibrateMouseAnchor()),()=>{this.mouseLeases.delete(token)&&this.mouseLeases.size===0&&this.applyMouseTracking(!1)}}resetMouseCaptureState(){this.mouseLeases.clear(),this.mouseBlockers.clear(),this.mouseWriteUnsubscribe?.(),this.mouseWriteUnsubscribe=void 0,this.placementEpoch++}get mouseCaptureEnabled(){return this.mouseLeases.size>0&&this.mouseBlockers.size===0}mouseCaptureState(){return this.mouseCaptureEnabled?"armed":"off"}applyMouseTracking(_enabled){}getMouseLayoutRoots(){return[...this.getMountedRoots(),...this.renderedOverlayLayouts.map(layout=>layout.entry.component)]}setMouseBlocker(name,on){this.mouseBlockers.has(name)!==on&&(on?this.mouseBlockers.add(name):this.mouseBlockers.delete(name),this.placementEpoch++,this.applyMouseTracking(this.mouseCaptureEnabled))}noteFullRender(clear){this.placementEpoch++,this.anchor={kind:clear?"cleared":"unknown",frameTopScreenRow:clear?0:void 0,epoch:this.placementEpoch,rows:this.terminal.rows,columns:this.terminal.columns},this.mouseCommittedLineCount=this.previousLines.length,this.noteCommittedMouseFrame(),this.calibrateMouseAnchor()}noteCommittedMouseFrame(){if(this.mouseCommittedLineCount!==this.previousLines.length&&this.placementEpoch++,this.mouseCommittedLineCount=this.previousLines.length,this.previousLinesHaveImage()){this.placementEpoch++,this.anchor.kind="unknown";return}this.previousLines.length>=this.terminal.rows?this.anchor={kind:"viewport",epoch:this.placementEpoch,rows:this.terminal.rows,columns:this.terminal.columns}:(this.anchor.epoch!==this.placementEpoch||this.anchor.rows!==this.terminal.rows||this.anchor.columns!==this.terminal.columns)&&(this.anchor={kind:"unknown",epoch:this.placementEpoch,rows:this.terminal.rows,columns:this.terminal.columns})}calibrateMouseAnchor(){if(!this.mouseCaptureEnabled||this.stopped||this.mouseAnchorPending||this.mouseExternalWritePending||!this.terminal.queryCursorPosition||this.previousLines.length===0||this.previousLinesHaveImage()||this.anchor.kind!=="unknown"&&this.anchor.epoch===this.placementEpoch&&this.anchor.rows===this.terminal.rows&&this.anchor.columns===this.terminal.columns)return;let epoch=this.placementEpoch,rows=this.terminal.rows,columns=this.terminal.columns,hardwareCursorRow=this.hardwareCursorRow,lineCount=this.previousLines.length;this.mouseAnchorPending=!0,this.terminal.queryCursorPosition().then(position=>{if(this.mouseAnchorPending=!1,!position||this.stopped||!this.mouseCaptureEnabled||epoch!==this.placementEpoch||rows!==this.terminal.rows||columns!==this.terminal.columns||hardwareCursorRow!==this.hardwareCursorRow||lineCount!==this.previousLines.length)return;let top=position.row-1-hardwareCursorRow;!Number.isSafeInteger(top)||top<0||top+lineCount>rows||!Number.isSafeInteger(position.column)||position.column<1||position.column>columns+1||position.page!==void 0&&position.page!==1||(this.anchor={kind:"cpr",frameTopScreenRow:top,epoch,rows,columns})})}resolveFrameLine(screenRow){let anchor=this.anchor;if(anchor.kind==="unknown"||anchor.epoch!==this.placementEpoch||anchor.rows!==this.terminal.rows||anchor.columns!==this.terminal.columns||screenRow<1||screenRow>anchor.rows)return;let line=anchor.kind==="viewport"?this.previousViewportTop+screenRow-1:screenRow-1-(anchor.frameTopScreenRow??0);return line>=0&&line<this.previousLines.length?line:void 0}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(_options){}afterTerminalStop(_options){}get fullRedraws(){return this.fullRedrawCount}get muxViewportRepaints(){return this.muxViewportRepaintCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(enabled){this.showHardwareCursor!==enabled&&(this.showHardwareCursor=enabled,this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(enabled){this.clearOnShrink=enabled}getFocusedComponent(){return this.focusedComponent}setFocus(component){this.setFocusInternal({component,overlayFocusRestore:"clear"})}setFocusInternal({component,overlayFocusRestore}){let previousFocus=this.focusedComponent,nextFocus=component,previousFocusedOverlay=previousFocus?this.overlayStack.find(entry=>entry.component===previousFocus&&this.isOverlayVisible(entry)):void 0,nextFocusIsOverlay=nextFocus?this.overlayStack.some(entry=>entry.component===nextFocus):!1,restoreState=this.getVisibleOverlayFocusRestore();nextFocus&&!nextFocusIsOverlay?restoreState.status==="blocked"&&restoreState.blockedBy===previousFocus?restoreState.resume.status==="focus-target"||!this.isComponentMounted(restoreState.blockedBy)?nextFocus=this.resolveBlockedOverlayFocusResume(restoreState):this.overlayFocusRestore={status:"blocked",overlay:restoreState.overlay,blockedBy:nextFocus,resume:restoreState.resume}:previousFocusedOverlay&&restoreState.status!=="inactive"&&restoreState.overlay===previousFocusedOverlay&&!this.isOverlayFocusAncestor(previousFocusedOverlay,nextFocus)&&(this.overlayFocusRestore={status:"blocked",overlay:previousFocusedOverlay,blockedBy:nextFocus,resume:{status:"restore-overlay"}}):nextFocus===null&&(restoreState.status==="blocked"&&restoreState.blockedBy===previousFocus?nextFocus=this.resolveBlockedOverlayFocusResume(restoreState):overlayFocusRestore==="clear"&&this.clearOverlayFocusRestore()),isFocusable(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=nextFocus,isFocusable(nextFocus)&&(nextFocus.focused=!0);let focusedOverlay=nextFocus?this.overlayStack.find(entry=>entry.component===nextFocus&&this.isOverlayVisible(entry)):void 0;focusedOverlay&&(this.overlayFocusRestore={status:"eligible",overlay:focusedOverlay})}clearOverlayFocusRestore(){this.overlayFocusRestore={status:"inactive"}}clearOverlayFocusRestoreFor(overlay){this.overlayFocusRestore.status!=="inactive"&&this.overlayFocusRestore.overlay===overlay&&this.clearOverlayFocusRestore()}resolveBlockedOverlayFocusResume(restoreState){return restoreState.resume.status==="restore-overlay"?restoreState.overlay.component:(this.clearOverlayFocusRestore(),restoreState.resume.target)}getVisibleOverlayFocusRestore(){let restoreState=this.overlayFocusRestore;return restoreState.status==="inactive"?restoreState:!this.overlayStack.includes(restoreState.overlay)||!this.isOverlayVisible(restoreState.overlay)?{status:"inactive"}:restoreState}isOverlayFocusAncestor(entry,component){let visited=new Set,current=entry.preFocus;for(;current&&!visited.has(current);){if(visited.add(current),current===component)return!0;current=this.overlayStack.find(overlay=>overlay.component===current)?.preFocus??null}return!1}retargetOverlayPreFocus(removed){for(let overlay of this.overlayStack)overlay!==removed&&overlay.preFocus===removed.component&&(overlay.preFocus=removed.preFocus)}getMountedRoots(){return this.children}isComponentMounted(component){return this.getMountedRoots().some(child=>this.containsComponent(child,component))}containsComponent(root,target){return root===target?!0:root instanceof Container?root.children.some(child=>this.containsComponent(child,target)):!1}showOverlay(component,options){let entry={component,...options===void 0?{}:{options},preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(entry),!options?.nonCapturing&&this.isOverlayVisible(entry)&&this.setFocus(component),this.#setCursorVisibility(!1),this.requestRender(),{hide:()=>{let index=this.overlayStack.indexOf(entry);if(index!==-1){if(this.clearOverlayFocusRestoreFor(entry),this.retargetOverlayPreFocus(entry),this.overlayStack.splice(index,1),this.focusedComponent===component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??entry.preFocus)}this.overlayStack.length===0&&this.#setCursorVisibility(!1),this.requestRender()}},setHidden:hidden=>{if(entry.hidden!==hidden){if(entry.hidden=hidden,hidden){if(this.clearOverlayFocusRestoreFor(entry),this.focusedComponent===component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??entry.preFocus)}}else!options?.nonCapturing&&this.isOverlayVisible(entry)&&(entry.focusOrder=++this.focusOrderCounter,this.setFocus(component));this.requestRender()}},isHidden:()=>entry.hidden,focus:()=>{!this.overlayStack.includes(entry)||!this.isOverlayVisible(entry)||(entry.focusOrder=++this.focusOrderCounter,this.setFocus(component),this.requestRender())},unfocus:unfocusOptions=>{let isFocused=this.focusedComponent===component,restoreState=this.overlayFocusRestore,hasPendingRestore=restoreState.status!=="inactive"&&restoreState.overlay===entry;if(!(!isFocused&&!hasPendingRestore)){if(restoreState.status==="blocked"&&restoreState.overlay===entry&&this.focusedComponent===restoreState.blockedBy){unfocusOptions?this.overlayFocusRestore={status:"blocked",overlay:entry,blockedBy:restoreState.blockedBy,resume:{status:"focus-target",target:unfocusOptions.target}}:this.clearOverlayFocusRestore(),this.requestRender();return}if(this.clearOverlayFocusRestoreFor(entry),isFocused||unfocusOptions){let topVisible=this.getTopmostVisibleOverlay(),fallbackTarget=topVisible&&topVisible!==entry?topVisible.component:entry.preFocus;this.setFocus(unfocusOptions?unfocusOptions.target:fallbackTarget)}this.requestRender()}},isFocused:()=>this.focusedComponent===component,getBounds:()=>{if(!(!this.overlayStack.includes(entry)||!this.isOverlayVisible(entry)||!entry.bounds))return{...entry.bounds}}}}hideOverlay(){let overlay=this.overlayStack[this.overlayStack.length-1];if(overlay){if(this.clearOverlayFocusRestoreFor(overlay),this.retargetOverlayPreFocus(overlay),this.overlayStack.pop(),this.focusedComponent===overlay.component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??overlay.preFocus)}this.overlayStack.length===0&&this.#setCursorVisibility(!1),this.requestRender()}}hasOverlay(){return this.overlayStack.some(o=>this.isOverlayVisible(o))}isOverlayFocused(){return this.overlayStack.some(entry=>entry.component===this.focusedComponent&&this.isOverlayVisible(entry))}resolveMouseFocusTarget(component){for(let index=this.overlayStack.length-1;index>=0;index--){let overlay=this.overlayStack[index];if(this.isOverlayVisible(overlay)&&this.containsComponent(overlay.component,component))return overlay.component}return canReceiveKeys(component)?component:this.findKeyFocusOwner(component)}findKeyFocusOwner(target){let path4=[],walk=node=>{if(path4.push(node),node===target)return!0;if(node instanceof Container){for(let child of node.children)if(walk(child))return!0}return path4.pop(),!1};for(let root of this.getMouseLayoutRoots())if(path4.length=0,!!walk(root)){for(let index=path4.length-2;index>=0;index--){let candidate=path4[index];if(canReceiveKeys(candidate))return candidate}return null}return null}dispatchMouseToOverlay(event){for(let index=this.renderedOverlayLayouts.length-1;index>=0;index--){let layout=this.renderedOverlayLayouts[index];if(event.screenX<layout.col||event.screenX>=layout.col+layout.width||event.screenY<layout.row||event.screenY>=layout.row+layout.height)continue;let result=dispatchMouseEvent(layout.entry.component,{...event,x:event.screenX-layout.col,y:event.screenY-layout.row,width:layout.width,height:layout.height});return result?{hit:!0,result:result.focus?{...result,focusTarget:layout.entry.component}:result}:{hit:!0}}return{hit:!1}}isOverlayVisible(entry){return entry.hidden?!1:entry.options?.visible?entry.options.visible(this.terminal.columns,this.terminal.rows):!0}getTopmostVisibleOverlay(){let topmost;for(let overlay of this.overlayStack)overlay.options?.nonCapturing||!this.isOverlayVisible(overlay)||(!topmost||overlay.focusOrder>topmost.focusOrder)&&(topmost=overlay);return topmost}invalidate(){for(let root of this.getMountedRoots())root.invalidate();for(let overlay of this.overlayStack)overlay.component.invalidate()}start(){this.stopped=!1,this.renderRequested=!1,this.inputRenderPending=!1,this.#lastCursorVisibility=void 0,this.beforeTerminalStart(),this.terminal.start(data=>this.handleTerminalInput(data),()=>this.requestRender()),this.afterTerminalStart(),process.env.TMUX&&this.terminal.write(ENABLE_FOCUS_REPORTING),this.#setCursorVisibility(!1),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031h"),this.queryCellSize(),this.probeKittyGraphics(),this.requestRender()}addInputListener(listener){return this.inputListeners.add(listener),()=>{this.inputListeners.delete(listener)}}removeInputListener(listener){this.inputListeners.delete(listener)}onTerminalColorSchemeChange(listener){return this.terminalColorSchemeListeners.add(listener),()=>{this.terminalColorSchemeListeners.delete(listener)}}setTerminalColorSchemeNotifications(enabled){this.terminalColorSchemeNotificationsEnabled!==enabled&&(this.terminalColorSchemeNotificationsEnabled=enabled,this.stopped||this.terminal.write(enabled?"\x1B[?2031h":"\x1B[?2031l"))}queryCellSize(){getCapabilities().images&&this.terminal.write("\x1B[16t")}probeKittyGraphics(){if(this.pendingKittyGraphicsProbe||getCapabilities().imageProbe!=="kitty")return;let imageId=allocateImageId(),timer=setTimeout(()=>this.resolveKittyGraphicsProbe(!1),500);this.pendingKittyGraphicsProbe={imageId,timer},this.terminal.write(buildKittyGraphicsQuery(imageId))}consumeKittyGraphicsProbeResponse(data){let probe=this.pendingKittyGraphicsProbe;if(!probe)return!1;let outcome=parseKittyGraphicsProbeResponse(data,probe.imageId);return outcome===null?!1:(this.resolveKittyGraphicsProbe(outcome==="ok"),!0)}resolveKittyGraphicsProbe(supported){let probe=this.pendingKittyGraphicsProbe;probe&&(this.pendingKittyGraphicsProbe=void 0,clearTimeout(probe.timer),setProbedImageProtocol(supported?"kitty":null),!this.stopped&&(supported&&this.queryCellSize(),this.invalidate(),this.requestRender()))}stop(options={}){if(this.stopped=!0,this.#scrollbackStale=!1,this.#scrollbackCatchUpPending=!1,this.#muxViewportRepaintPending=!1,this.renderRequested=!1,this.inputRenderPending=!1,this.cancelRenderTimer(),this.pendingKittyGraphicsProbe&&(clearTimeout(this.pendingKittyGraphicsProbe.timer),this.pendingKittyGraphicsProbe=void 0),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031l"),this.beforeTerminalStop(options),this.resetMouseCaptureState(),!options.preserveScreen&&this.previousLines.length>0){this.#lastCursorVisibility===!1&&this.terminal.write(" ");let lineDiff=this.previousLines.length-this.hardwareCursorRow;lineDiff>0?this.terminal.write(`\x1B[${lineDiff}B`):lineDiff<0&&this.terminal.write(`\x1B[${-lineDiff}A`),this.terminal.write(`\r
`)}this.#lastCursorVisibility=void 0,this.#setCursorVisibility(!0),process.env.TMUX&&this.terminal.write(DISABLE_FOCUS_REPORTING),this.terminal.stop(),this.afterTerminalStop(options),this.resetRenderState(),this.#lastCursorVisibility=void 0,this.dropPreviousLines(),this.previousKittyImageIds.clear(),this.previousWidth=0,this.previousHeight=0,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0}setScrollbackReplayHold(hold){this.#holdScrollbackReplay=hold!==!1,this.#releaseHoldOnInput=hold==="until-input"}catchUpScrollback(){this.#scrollbackStale&&(this.#scrollbackStale=!1,this.#scrollbackCatchUpPending=!0,this.requestRender())}renderNow(force=!1){force&&this.resetForcedRenderState(),this.renderRequested=!1,this.inputRenderPending=!1,this.cancelRenderTimer(),this.lastRenderAt=performance2.now(),this.doRender()}#setCursorVisibility(visible){!visible&&this.stopped||this.#lastCursorVisibility!==visible&&(visible?this.terminal.showCursor():this.terminal.hideCursor(),this.#lastCursorVisibility=visible)}requestRender(force=!1,source="unknown"){if(force){this.inputRenderPending=!1,this.resetForcedRenderState(),this.cancelRenderTimer(),this.renderRequested=!0,process.nextTick(()=>{this.stopped||!this.renderRequested||(this.renderRequested=!1,this.lastRenderAt=performance2.now(),this.doRender())});return}if(source==="input"||source==="editor.input"){this.inputRenderPending||(this.inputRenderPending=!0,this.renderRequested=!0,process.nextTick(()=>this.commitExpeditedRender()));return}this.renderRequested||(this.renderRequested=!0,process.nextTick(()=>this.scheduleRender()))}setMaxRenderFps(fps){let clamped=Math.min(120,Math.max(30,Math.round(fps)));this.#minRenderIntervalMs=Math.floor(1e3/clamped)}resetForcedRenderState(){this.#scrollbackCatchUpPending=!1,this.resetRenderState(),this.dropPreviousLines(),this.previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0}cancelRenderTimer(){this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0)}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let elapsed=performance2.now()-this.lastRenderAt,delay=Math.max(0,this.#minRenderIntervalMs-elapsed);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=!1,this.lastRenderAt=performance2.now(),this.doRender(),this.renderRequested&&this.scheduleRender())},delay)}commitExpeditedRender(){this.inputRenderPending&&(this.inputRenderPending=!1,!(this.stopped||!this.renderRequested)&&(this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0),this.renderRequested=!1,this.lastRenderAt=performance2.now(),this.doRender()))}handleTerminalInput(data){if(this.mode!=="fullscreen"){let focus=consumeTmuxFocusEvent(data);if(focus.event!==null){if(this.shouldPreserveMuxScrollback()?focus.event==="in"&&(resetCapabilitiesCache(),this.invalidate(),this.#muxViewportRepaintPending=!0,this.requestRender()):(resetCapabilitiesCache(),this.invalidate(),this.requestRender(!0)),focus.data.length===0)return;data=focus.data}}if(this.consumeTerminalColorResponse(data)||this.consumeTerminalColorSchemeReport(data)||this.consumeKittyGraphicsProbeResponse(data))return;if(isTerminalReport(data)||(this.#releaseHoldOnInput&&(this.#releaseHoldOnInput=!1,this.#holdScrollbackReplay=!1),this.catchUpScrollback()),this.inputListeners.size>0){let current=data;for(let listener of this.inputListeners){let result=listener(current);if(result?.consume)return;result?.data!==void 0&&(current=result.data)}if(current.length===0)return;data=current}if(this.consumeCellSizeResponse(data))return;if(matchesKey(data,"shift+ctrl+d")&&this.onDebug){this.onDebug();return}let focusedOverlay=this.overlayStack.find(o=>o.component===this.focusedComponent);if(focusedOverlay&&!this.isOverlayVisible(focusedOverlay)){let topVisible=this.getTopmostVisibleOverlay();topVisible?this.setFocus(topVisible.component):this.setFocusInternal({component:focusedOverlay.preFocus,overlayFocusRestore:"preserve"})}if(!this.overlayStack.some(o=>o.component===this.focusedComponent)){let restoreState=this.getVisibleOverlayFocusRestore();restoreState.status==="eligible"?this.setFocus(restoreState.overlay.component):restoreState.status==="blocked"&&restoreState.blockedBy!==this.focusedComponent&&(restoreState.resume.status==="restore-overlay"?this.setFocus(restoreState.overlay.component):(this.clearOverlayFocusRestore(),this.setFocus(restoreState.resume.target)))}if(this.focusedComponent?.handleInput){if(isKeyRelease(data)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(data),this.requestRender(!1,"input")}}consumeTerminalColorResponse(data){let query=this.pendingTerminalColorQueries[0];if(!query)return!1;if(DEVICE_ATTRIBUTES_RESPONSE_PATTERN.test(data))return this.pendingTerminalColorQueries.shift(),this.completeTerminalColorQuery(query),!0;let response=parseOscColorResponse(data);if(!response)return!1;let{target,rgb}=response,key=String(target);return!query.deliver||query.replied.has(key)||(query.replied.add(key),target==="foreground"?query.foreground=rgb:target==="background"?query.background=rgb:target<TERMINAL_PALETTE_SIZE&&(query.palette[target]=rgb),query.replied.size===TERMINAL_COLOR_REPLY_COUNT&&this.completeTerminalColorQuery(query)),!0}terminalColorQueryResult(query){let palette=query.palette.every(color=>color!==void 0)?query.palette:void 0;return{foreground:query.foreground,background:query.background,palette}}completeTerminalColorQuery(query){let deliver=query.deliver;query.deliver=void 0,clearTimeout(query.timer),deliver?.(this.terminalColorQueryResult(query))}consumeTerminalColorSchemeReport(data){let scheme=parseTerminalColorSchemeReport(data);if(!scheme)return!1;for(let listener of this.terminalColorSchemeListeners)listener(scheme);return!0}consumeCellSizeResponse(data){let match=data.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!match)return!1;let heightPx=parseInt(match[1],10),widthPx=parseInt(match[2],10);return heightPx<=0||widthPx<=0||(setCellDimensions({widthPx,heightPx}),this.invalidate(),this.requestRender()),!0}resolveOverlayLayout(options,overlayHeight,termWidth,termHeight){let opt=options??{},margin=typeof opt.margin=="number"?{top:opt.margin,right:opt.margin,bottom:opt.margin,left:opt.margin}:opt.margin??{},marginTop=Math.max(0,margin.top??0),marginRight=Math.max(0,margin.right??0),marginBottom=Math.max(0,margin.bottom??0),marginLeft=Math.max(0,margin.left??0),availWidth=Math.max(1,termWidth-marginLeft-marginRight),availHeight=Math.max(1,termHeight-marginTop-marginBottom),width=parseSizeValue(opt.width,termWidth)??Math.min(80,availWidth);opt.minWidth!==void 0&&(width=Math.max(width,opt.minWidth)),width=Math.max(1,Math.min(width,availWidth));let maxHeight=parseSizeValue(opt.maxHeight,termHeight);maxHeight!==void 0&&(maxHeight=Math.max(1,Math.min(maxHeight,availHeight)));let effectiveHeight=maxHeight!==void 0?Math.min(overlayHeight,maxHeight):overlayHeight,row,col;if(opt.row!==void 0)if(typeof opt.row=="string"){let match=opt.row.match(/^(\d+(?:\.\d+)?)%$/);if(match){let maxRow=Math.max(0,availHeight-effectiveHeight),percent=parseFloat(match[1])/100;row=marginTop+Math.floor(maxRow*percent)}else row=this.resolveAnchorRow("center",effectiveHeight,availHeight,marginTop)}else row=opt.row;else{let anchor=opt.anchor??"center";row=this.resolveAnchorRow(anchor,effectiveHeight,availHeight,marginTop)}if(opt.col!==void 0)if(typeof opt.col=="string"){let match=opt.col.match(/^(\d+(?:\.\d+)?)%$/);if(match){let maxCol=Math.max(0,availWidth-width),percent=parseFloat(match[1])/100;col=marginLeft+Math.floor(maxCol*percent)}else col=this.resolveAnchorCol("center",width,availWidth,marginLeft)}else col=opt.col;else{let anchor=opt.anchor??"center";col=this.resolveAnchorCol(anchor,width,availWidth,marginLeft)}return opt.offsetY!==void 0&&(row+=opt.offsetY),opt.offsetX!==void 0&&(col+=opt.offsetX),row=Math.max(marginTop,Math.min(row,termHeight-marginBottom-effectiveHeight)),col=Math.max(marginLeft,Math.min(col,termWidth-marginRight-width)),{width,row,col,maxHeight}}resolveAnchorRow(anchor,height,availHeight,marginTop){switch(anchor){case"top-left":case"top-center":case"top-right":return marginTop;case"bottom-left":case"bottom-center":case"bottom-right":return marginTop+availHeight-height;case"left-center":case"center":case"right-center":return marginTop+Math.floor((availHeight-height)/2)}}resolveAnchorCol(anchor,width,availWidth,marginLeft){switch(anchor){case"top-left":case"left-center":case"bottom-left":return marginLeft;case"top-right":case"right-center":case"bottom-right":return marginLeft+availWidth-width;case"top-center":case"center":case"bottom-center":return marginLeft+Math.floor((availWidth-width)/2)}}compositeOverlays(lines,termWidth,termHeight){if(this.overlayStack.length===0)return this.renderedOverlayLayouts=[],lines;let result=[...lines];for(let entry of this.overlayStack)entry.bounds=void 0;let rendered=[],minLinesNeeded=result.length,visibleEntries=this.overlayStack.filter(e=>this.isOverlayVisible(e));visibleEntries.sort((a,b2)=>a.focusOrder-b2.focusOrder);for(let entry of visibleEntries){let{component,options}=entry,{width,maxHeight}=this.resolveOverlayLayout(options,0,termWidth,termHeight),overlayLines=component.render(width);maxHeight!==void 0&&overlayLines.length>maxHeight&&(overlayLines=overlayLines.slice(0,maxHeight));let{row,col}=this.resolveOverlayLayout(options,overlayLines.length,termWidth,termHeight);entry.bounds={row,col,width,height:overlayLines.length},rendered.push({entry,overlayLines,row,col,w:width}),minLinesNeeded=Math.max(minLinesNeeded,row+overlayLines.length)}this.renderedOverlayLayouts=rendered.map(({entry,row,col,w,overlayLines})=>({entry,row,col,width:w,height:overlayLines.length}));let workingHeight=Math.max(result.length,termHeight,minLinesNeeded);for(;result.length<workingHeight;)result.push("");let viewportStart=Math.max(0,workingHeight-termHeight);for(let{overlayLines,row,col,w}of rendered)for(let i=0;i<overlayLines.length;i++){let idx=viewportStart+row+i;if(idx>=0&&idx<result.length){let truncatedOverlayLine=visibleWidth(overlayLines[i])>w?sliceByColumn(overlayLines[i],0,w,!0):overlayLines[i];result[idx]=this.compositeLineAt(result[idx],truncatedOverlayLine,col,w,termWidth)}}return result}static{this.SEGMENT_RESET="\x1B[0m\x1B]8;;\x07"}static{this.NORMALIZE_MEMO_MIN=4096}static{this.FRAME_BEGIN="\x1B[?2026h\x1B[?7l"}static{this.FRAME_END="\x1B[?7h\x1B[?2026l"}setPreviousLines(lines,rawLines){let state=frameLineBytesState();state.bytes-=this.frameLineBytes;let bytes=lines.length*8;for(let line of lines)bytes+=line.length*2;this.frameLineBytes=bytes,state.bytes+=bytes,this.previousLines=lines,this.previousRawLines=rawLines}dropPreviousLines(){this.previousLines.length===0&&this.previousRawLines.length===0&&this.frameLineBytes===0||this.setPreviousLines([],[])}previousLinesHaveImage(){let lines=this.previousLines;if(this.previousImageScan?.lines!==lines){let hint=this.normalizedImageHint?.lines===lines?this.normalizedImageHint.hasImage:void 0;this.previousImageScan={lines,hasImage:hint??lines.some(isImageLine)}}return this.previousImageScan.hasImage}hintNormalizedImages(lines,hasImage){this.normalizedImageHint=hasImage===void 0?void 0:{lines,hasImage}}normalizeLine(line){if(isImageLine(line))return{line,normalized:!1};let cached=this.normalizeMemo.get(line);if(cached!==void 0)return{line:cached,normalized:!1};let normalized=normalizeTerminalOutput(line)+TUI.SEGMENT_RESET;if(this.normalizeMemo.size>=Math.max(TUI.NORMALIZE_MEMO_MIN,this.previousRawLines.length*2)){let drop=this.normalizeMemo.size>>1;for(let key of this.normalizeMemo.keys()){if(drop--<=0)break;this.normalizeMemo.delete(key)}}return this.normalizeMemo.set(line,normalized),{line:normalized,normalized:!0}}applyLineResets(lines){return this.applyLineResetResult(lines).lines}applyLineResetResult(lines,mode="full"){let previousMemo=this.normalizeMemo,nextMemo=new Map,normalizedLines=[],normalizedCount=0,hasImage=!1;for(let i=0;i<lines.length;i++){let line=lines[i];if(isImageLine(line)){hasImage=!0,normalizedLines.push(line);continue}let normalized=nextMemo.get(line)??previousMemo.get(line);normalized===void 0&&(normalized=normalizeTerminalOutput(line)+TUI.SEGMENT_RESET,normalizedCount+=1),nextMemo.set(line,normalized),normalizedLines.push(normalized)}return this.normalizeMemo=nextMemo,this.hintNormalizedImages(normalizedLines,hasImage),recordViewportRenderStats(normalizedCount,mode),{lines:normalizedLines,firstRawChanged:0,compareEndExclusive:normalizedLines.length,bounded:!1}}applyViewportLineResets(rawLines,viewportTop,height,stableDimensions){if(!viewportRenderEnabled()||!stableDimensions||this.previousLines.length===0||this.previousRawLines.length!==this.previousLines.length)return this.applyLineResetResult(rawLines);if(this.previousRawLines.length!==rawLines.length)return this.applyResizedLineResets(rawLines);let windowStart=Math.max(0,viewportTop-VIEWPORT_RENDER_OVERSCAN),windowEnd=Math.min(rawLines.length,viewportTop+height+VIEWPORT_RENDER_OVERSCAN),firstRawChanged=-1;for(let i=0;i<rawLines.length;i++)if(rawLines[i]!==this.previousRawLines[i]&&(firstRawChanged===-1&&(firstRawChanged=i),i<windowStart||i>=windowEnd))return this.applyLineResetResult(rawLines,"escaped");let previousHadImage=this.previousLinesHaveImage(),lines=this.previousLines.slice(),normalizedCount=0,changedImage=!1;if(firstRawChanged!==-1)for(let i=windowStart;i<windowEnd;i++){if(rawLines[i]===this.previousRawLines[i])continue;let raw=rawLines[i]??"";isImageLine(raw)&&(changedImage=!0);let normalized=this.normalizeLine(raw);lines[i]=normalized.line,normalized.normalized&&(normalizedCount+=1)}return this.hintNormalizedImages(lines,previousHadImage?void 0:changedImage),recordViewportRenderStats(normalizedCount,"bounded"),{lines,firstRawChanged,compareEndExclusive:windowEnd,bounded:!0}}applyResizedLineResets(rawLines){let previousRaw=this.previousRawLines,sharedLength=Math.min(rawLines.length,previousRaw.length),firstRawChanged=0;for(;firstRawChanged<sharedLength&&rawLines[firstRawChanged]===previousRaw[firstRawChanged];)firstRawChanged++;let previousHadImage=this.previousLinesHaveImage(),lines=this.previousLines.slice(0,firstRawChanged),normalizedCount=0,tailImage=!1;for(let i=firstRawChanged;i<rawLines.length;i++){let line=rawLines[i]??"";if(isImageLine(line)){tailImage=!0,lines.push(line);continue}let normalized=this.normalizeMemo.get(line);normalized===void 0&&(normalized=normalizeTerminalOutput(line)+TUI.SEGMENT_RESET,normalizedCount+=1),lines.push(normalized)}return this.hintNormalizedImages(lines,previousHadImage?void 0:tailImage),recordViewportRenderStats(normalizedCount,"bounded"),{lines,firstRawChanged,compareEndExclusive:Math.max(rawLines.length,this.previousLines.length),bounded:!0}}collectKittyImageIds(lines){recordKittyImageScanStats(lines.length);let ids=new Set;for(let line of lines)for(let id of extractKittyImageIds(line))ids.add(id);return ids}deleteKittyImages(ids){let buffer="";for(let id of ids)buffer+=deleteKittyImage(id);return buffer}getKittyImageReservedRows(lines,index,maxIndex=lines.length-1){let rows=extractKittyImageRows(lines[index]??"");if(rows<=1)return 1;let maxRows=Math.min(rows,maxIndex-index+1,lines.length-index),reservedRows=1;for(;reservedRows<maxRows;){let line=lines[index+reservedRows]??"";if(isImageLine(line)||visibleWidth(line)>0)break;reservedRows++}return reservedRows}expandChangedRangeForKittyImages(firstChanged,lastChanged,newLines){let expandedFirstChanged=firstChanged,expandedLastChanged=lastChanged,expandForLines=lines=>{for(let i=0;i<lines.length;i++){if(extractKittyImageIds(lines[i]).length===0)continue;let blockEnd=i+this.getKittyImageReservedRows(lines,i)-1;(i>=firstChanged||i<=lastChanged&&blockEnd>=firstChanged)&&(expandedFirstChanged=Math.min(expandedFirstChanged,i),expandedLastChanged=Math.max(expandedLastChanged,blockEnd))}};return expandForLines(this.previousLines),expandForLines(newLines),{firstChanged:expandedFirstChanged,lastChanged:expandedLastChanged}}changedRangeNeedsKittyImageExpansion(lines,firstChanged,lastChanged){if(this.previousKittyImageIds.size>0)return!0;let start=Math.max(0,firstChanged),end=Math.min(lines.length-1,lastChanged),scannedLines=0;for(let i=start;i<=end;i++){scannedLines+=1;let line=lines[i]??"";if(isImageLine(line)||extractKittyImageIds(line).length>0)return recordKittyImageScanStats(scannedLines),!0}return recordKittyImageScanStats(scannedLines),!1}deleteChangedKittyImages(firstChanged,lastChanged){if(firstChanged<0||lastChanged<firstChanged)return"";let ids=new Set,maxLine=Math.min(lastChanged,this.previousLines.length-1);for(let i=firstChanged;i<=maxLine;i++)for(let id of extractKittyImageIds(this.previousLines[i]??""))ids.add(id);return this.deleteKittyImages(ids)}getViewportRows(lines,viewportTop,height){return Array.from({length:height},(_2,row)=>lines[viewportTop+row]??"")}shouldPreserveMuxScrollback(){return this.#muxDetector()&&!useLegacyMuxRender()}renderViewportInsertScroll(plan,newLines,rawLines,cursorPos,width,height){let buffer=TUI.FRAME_BEGIN,regionTop=0,regionBottom=plan.regionBottom;buffer+=`\x1B[${regionTop+1};${regionBottom+1}r`,buffer+=`\x1B[${regionBottom+1};1H`,buffer+=`
`.repeat(plan.insertedRows.length),buffer+="\x1B[r";let firstInsertedScreenRow=regionBottom-plan.insertedRows.length+1,finalPaintedScreenRow=firstInsertedScreenRow+plan.insertedRows.length-1;for(let index=0;index<plan.insertedRows.length;index++){let screenRow=firstInsertedScreenRow+index;buffer+=`\x1B[${screenRow+1};1H\x1B[2K${TUI.SEGMENT_RESET}`,buffer+=plan.insertedRows[index]??""}for(let row of plan.mutatedRows)buffer+=`\x1B[${row.screenRow+1};1H\x1B[2K${TUI.SEGMENT_RESET}`,buffer+=row.content,finalPaintedScreenRow=row.screenRow;let finalCursorRow=plan.viewportTop+finalPaintedScreenRow;buffer=this.finishFrame(buffer,cursorPos,newLines.length,finalCursorRow),writeBounded(this.terminal,buffer),this.cursorRow=Math.max(0,newLines.length-1),this.maxLinesRendered=Math.max(this.maxLinesRendered,newLines.length),this.previousViewportTop=plan.viewportTop,this.setPreviousLines(newLines,rawLines),this.previousKittyImageIds=this.collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height,this.placementEpoch++}renderScrollbackReplay(newLines,rawLines,cursorPos,width,height,prevViewportTop,hardwareCursorRow){this.#scrollbackStale=!1;let buffer=TUI.FRAME_BEGIN;buffer+=this.deleteKittyImages(this.previousKittyImageIds),this.shouldPreserveMuxScrollback()||(buffer+="\x1B[3J");let currentScreenRow=Math.max(0,Math.min(height-1,hardwareCursorRow-prevViewportTop));currentScreenRow>0&&(buffer+=`\x1B[${currentScreenRow}A`);let bufferLength=Math.max(height,newLines.length);for(let row=0;row<bufferLength;row++)row>0&&(buffer+=`\r
`),buffer+=`\r\x1B[2K${TUI.SEGMENT_RESET}`,buffer+=newLines[row]??"";buffer=this.finishFrame(buffer,cursorPos,newLines.length,bufferLength-1),writeBounded(this.terminal,buffer),this.cursorRow=Math.max(0,newLines.length-1),this.maxLinesRendered=newLines.length,this.previousViewportTop=Math.max(0,bufferLength-height),this.setPreviousLines(newLines,rawLines),this.previousKittyImageIds=this.collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height,this.placementEpoch++}renderHeldRepaint(newLines,rawLines,cursorPos,width,height,prevViewportTop,hardwareCursorRow){let shift=insertedAboveViewport(this.previousLines,newLines,prevViewportTop,height,newLines.length-this.previousLines.length),start=Math.min(prevViewportTop+shift,Math.max(0,newLines.length-height)),rowCount=Math.max(height,newLines.length-start),rows=Array.from({length:rowCount},(_2,index)=>newLines[start+index]??""),previousVisible=this.getViewportRows(this.previousLines,prevViewportTop,height);if(rows.some(isImageLine)||previousVisible.some(isImageLine))return!1;let buffer=TUI.FRAME_BEGIN,currentScreenRow=Math.max(0,Math.min(height-1,hardwareCursorRow-prevViewportTop));currentScreenRow>0&&(buffer+=`\x1B[${currentScreenRow}A`);for(let row=0;row<rows.length;row++)row>0&&(buffer+=`\r
`),buffer+=`\r\x1B[2K${TUI.SEGMENT_RESET}`,buffer+=rows[row];let lastRow=start+rows.length-1;return buffer=this.finishFrame(buffer,cursorPos,newLines.length,lastRow),writeBounded(this.terminal,buffer),this.#scrollbackStale=!0,this.cursorRow=Math.max(0,newLines.length-1),this.maxLinesRendered=newLines.length,this.previousViewportTop=Math.max(0,lastRow+1-height),this.setPreviousLines(newLines,rawLines),this.previousKittyImageIds=this.collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height,this.placementEpoch++,!0}renderMuxViewportRepaint(newLines,rawLines,cursorPos,width,height,viewportTop=Math.max(0,newLines.length-height),home="relative"){let previousVisible=this.getViewportRows(this.previousLines,this.previousViewportTop,height),nextVisible=this.getViewportRows(newLines,viewportTop,height);if(previousVisible.some(isImageLine)||nextVisible.some(isImageLine))return!1;let buffer=TUI.FRAME_BEGIN;if(home==="absolute")buffer+="\x1B[H";else{let currentScreenRow=Math.max(0,Math.min(height-1,this.hardwareCursorRow-this.previousViewportTop));currentScreenRow>0&&(buffer+=`\x1B[${currentScreenRow}A`)}for(let row=0;row<height;row++)row>0&&(buffer+=`\r
`),buffer+=`\r\x1B[2K${TUI.SEGMENT_RESET}`,buffer+=newLines[viewportTop+row]??"";let finalCursorRow=viewportTop+Math.max(0,height-1);return buffer=this.finishFrame(buffer,cursorPos,newLines.length,finalCursorRow),writeBounded(this.terminal,buffer),this.muxViewportRepaintCount+=1,this.cursorRow=Math.max(0,newLines.length-1),this.maxLinesRendered=newLines.length,this.previousViewportTop=viewportTop,this.setPreviousLines(newLines,rawLines),this.previousKittyImageIds=this.collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height,this.placementEpoch++,!0}compositeLineAt(baseLine,overlayLine,startCol,overlayWidth,totalWidth){if(isImageLine(baseLine)&&visibleWidth(baseLine)===0)return baseLine;let placeholderIndex=baseLine.indexOf("\u{10EEEE}"),protocolEnd=placeholderIndex===-1?-1:baseLine.lastIndexOf("\x1B\\",placeholderIndex),protocolPrefix=protocolEnd===-1?"":baseLine.slice(0,protocolEnd+2),afterStart=startCol+overlayWidth,base=extractSegments(baseLine,startCol,afterStart,totalWidth-afterStart,!0),overlay=sliceWithWidth(overlayLine,0,overlayWidth,!0),beforePad=Math.max(0,startCol-base.beforeWidth),overlayPad=Math.max(0,overlayWidth-overlay.width),actualBeforeWidth=Math.max(startCol,base.beforeWidth),actualOverlayWidth=Math.max(overlayWidth,overlay.width),afterTarget=Math.max(0,totalWidth-actualBeforeWidth-actualOverlayWidth),afterPad=Math.max(0,afterTarget-base.afterWidth),r=TUI.SEGMENT_RESET,result=base.before+" ".repeat(beforePad)+r+overlay.text+" ".repeat(overlayPad)+r+base.after+" ".repeat(afterPad);return visibleWidth(result)<=totalWidth?protocolPrefix+result:protocolPrefix+sliceByColumn(result,0,totalWidth,!0)}extractCursorPosition(lines,height){let viewportTop=Math.max(0,lines.length-height);for(let row=lines.length-1;row>=viewportTop;row--){let line=lines[row],markerIndex=line.indexOf(CURSOR_MARKER);if(markerIndex!==-1){let beforeMarker=line.slice(0,markerIndex),col=visibleWidth(beforeMarker),afterMarker=line.slice(markerIndex+CURSOR_MARKER.length);if(this.showHardwareCursor&&afterMarker.startsWith(FAKE_CURSOR_START)){let fakeCursorEnd=afterMarker.indexOf(FAKE_CURSOR_END,FAKE_CURSOR_START.length),fakeCursorReset=afterMarker.indexOf(FAKE_CURSOR_RESET,FAKE_CURSOR_START.length);fakeCursorReset!==-1&&(fakeCursorEnd===-1||fakeCursorReset<fakeCursorEnd)?afterMarker=afterMarker.slice(FAKE_CURSOR_START.length):fakeCursorEnd!==-1&&(afterMarker=afterMarker.slice(FAKE_CURSOR_START.length,fakeCursorEnd)+afterMarker.slice(fakeCursorEnd+FAKE_CURSOR_END.length))}return lines[row]=beforeMarker+afterMarker,{row,col}}}return null}doRender(){if(this.stopped)return;let width=this.terminal.columns,height=this.terminal.rows,widthChanged=this.previousWidth!==0&&this.previousWidth!==width,heightChanged=this.previousHeight!==0&&this.previousHeight!==height;(widthChanged||heightChanged)&&this.placementEpoch++;let previousBufferLength=this.previousHeight>0?this.previousViewportTop+this.previousHeight:height,prevViewportTop=heightChanged?Math.max(0,previousBufferLength-height):this.previousViewportTop,viewportTop=prevViewportTop,hardwareCursorRow=this.hardwareCursorRow,computeLineDiff=targetRow=>{let currentScreenRow=hardwareCursorRow-prevViewportTop;return targetRow-viewportTop-currentScreenRow};renderFrame.scrollbackRows=this.mode==="regular"&&!widthChanged&&!heightChanged&&this.previousLines.length>0?prevViewportTop:0,renderFrame.mode=this.mode,renderFrame.rows=height;let newLines;try{newLines=renderAtFrameRow(this,width,0)}finally{renderFrame.scrollbackRows=0,renderFrame.mode=void 0}this.overlayStack.length>0&&(newLines=this.compositeOverlays(newLines,width,height));let cursorPos=this.extractCursorPosition(newLines,height),rawLines=newLines,normalizedLines=this.applyViewportLineResets(rawLines,prevViewportTop,height,!widthChanged&&!heightChanged);newLines=normalizedLines.lines;let preserveMuxScrollback=this.shouldPreserveMuxScrollback();if(this.#scrollbackCatchUpPending){if(this.#scrollbackCatchUpPending=!1,!preserveMuxScrollback&&!widthChanged&&!heightChanged){this.renderScrollbackReplay(newLines,rawLines,cursorPos,width,height,prevViewportTop,hardwareCursorRow);return}preserveMuxScrollback||(this.#scrollbackStale=!0)}let fullRender=(clear,clearScrollback=clear)=>{this.fullRedrawCount+=1;let buffer2=TUI.FRAME_BEGIN;clear?(clearScrollback&&(this.#scrollbackStale=!1),buffer2+=this.deleteKittyImages(this.previousKittyImageIds),buffer2+="\x1B[2J\x1B[H",clearScrollback&&!preserveMuxScrollback&&process.platform!=="win32"&&(buffer2+="\x1B[3J")):buffer2+=`\r\x1B[2K${TUI.SEGMENT_RESET}`;for(let i=0;i<newLines.length;i++){i>0&&(buffer2+=`\r
`);let line=newLines[i],imageReservedRows=isImageLine(line)?this.getKittyImageReservedRows(newLines,i):1;if(imageReservedRows>1&&imageReservedRows<=height){for(let row=1;row<imageReservedRows;row++)buffer2+=`\r
`;buffer2+=`\x1B[${imageReservedRows-1}A`,buffer2+=line,buffer2+=`\x1B[${imageReservedRows-1}B`,i+=imageReservedRows-1;continue}buffer2+=line}let finalCursorRow2=Math.max(0,newLines.length-1);buffer2=this.finishFrame(buffer2,cursorPos,newLines.length,finalCursorRow2),writeBounded(this.terminal,buffer2),this.cursorRow=Math.max(0,newLines.length-1),clear?this.maxLinesRendered=newLines.length:this.maxLinesRendered=Math.max(this.maxLinesRendered,newLines.length);let bufferLength=Math.max(height,newLines.length);this.previousViewportTop=Math.max(0,bufferLength-height),this.setPreviousLines(newLines,rawLines),this.previousKittyImageIds=this.collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height,this.noteFullRender(clear)},debugRedraw=process.env.PI_DEBUG_REDRAW==="1",logRedraw=reason=>{if(!debugRedraw)return;let logPath=path.join(this.logDirectory,"pi-debug.log"),msg=`[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})
`;fs.mkdirSync(path.dirname(logPath),{recursive:!0}),fs.appendFileSync(logPath,msg,{encoding:"utf8",mode:DIAGNOSTIC_LOG_MODE}),chmodDiagnosticLogBestEffort(logPath)};if(this.previousLines.length===0&&!widthChanged&&!heightChanged){logRedraw("first render"),fullRender(!1);return}if(widthChanged){if(this.#muxViewportRepaintPending=!1,logRedraw(`terminal width changed (${this.previousWidth} -> ${width})`),preserveMuxScrollback&&this.previousWidth>0&&this.renderMuxViewportRepaint(newLines,rawLines,cursorPos,width,height,void 0,"absolute"))return;fullRender(!0,!preserveMuxScrollback);return}if(this.#muxViewportRepaintPending&&(this.#muxViewportRepaintPending=!1,preserveMuxScrollback&&!heightChanged)){logRedraw("multiplexer pane focus regained");let focusViewportTop=newLines.length>prevViewportTop?Math.max(prevViewportTop,newLines.length-height):Math.max(0,newLines.length-height);this.renderMuxViewportRepaint(newLines,rawLines,cursorPos,width,height,focusViewportTop)||fullRender(!0,!1);return}if(heightChanged&&!isTermuxSession()){logRedraw(`terminal height changed (${this.previousHeight} -> ${height})`),preserveMuxScrollback?this.renderMuxViewportRepaint(newLines,rawLines,cursorPos,width,height)||fullRender(!0,!1):fullRender(!0);return}if(this.clearOnShrink&&newLines.length<this.maxLinesRendered&&this.overlayStack.length===0){logRedraw(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`),fullRender(!0,!preserveMuxScrollback);return}let firstChanged=-1,lastChanged=-1,maxLines=Math.max(newLines.length,this.previousLines.length),diffScanStart=normalizedLines.bounded&&normalizedLines.firstRawChanged!==-1?normalizedLines.firstRawChanged:0,diffScanEndExclusive=normalizedLines.bounded?normalizedLines.compareEndExclusive:maxLines;for(let i=diffScanStart;i<diffScanEndExclusive;i++){let oldLine=i<this.previousLines.length?this.previousLines[i]:"",newLine=i<newLines.length?newLines[i]:"";oldLine!==newLine&&(firstChanged===-1&&(firstChanged=i),lastChanged=i)}let appendedLines=newLines.length>this.previousLines.length,lineCountDelta=newLines.length-this.previousLines.length;appendedLines&&(firstChanged===-1&&(firstChanged=this.previousLines.length),lastChanged=newLines.length-1);let needsKittyImageExpansion=firstChanged!==-1&&this.changedRangeNeedsKittyImageExpansion(newLines,firstChanged,lastChanged);if(needsKittyImageExpansion){let expandedRange=this.expandChangedRangeForKittyImages(firstChanged,lastChanged,newLines);firstChanged=expandedRange.firstChanged,lastChanged=expandedRange.lastChanged}let appendStart=appendedLines&&firstChanged===this.previousLines.length&&firstChanged>0,insertScrollPlan=this.overlayStack.length>0?void 0:planViewportInsertScroll(this.previousLines,newLines,prevViewportTop,height,lineCountDelta);if(firstChanged===-1){this.positionHardwareCursor(cursorPos,newLines.length),this.previousViewportTop=prevViewportTop,this.previousHeight=height;return}if(insertScrollPlan){this.renderViewportInsertScroll(insertScrollPlan,newLines,rawLines,cursorPos,width,height);return}if(firstChanged>=newLines.length){if(this.previousLines.length>newLines.length){let buffer2=TUI.FRAME_BEGIN;buffer2+=this.deleteChangedKittyImages(firstChanged,lastChanged);let targetRow=Math.max(0,newLines.length-1);if(targetRow<prevViewportTop){logRedraw(`deleted lines moved viewport up (${targetRow} < ${prevViewportTop})`),fullRender(!0,!preserveMuxScrollback);return}let lineDiff2=computeLineDiff(targetRow);lineDiff2>0?buffer2+=`\x1B[${lineDiff2}B`:lineDiff2<0&&(buffer2+=`\x1B[${-lineDiff2}A`),buffer2+="\r";let extraLines=this.previousLines.length-newLines.length;if(extraLines>height){logRedraw(`extraLines > height (${extraLines} > ${height})`),fullRender(!0,!preserveMuxScrollback);return}let clearStartOffset=newLines.length===0?0:1;extraLines>0&&clearStartOffset>0&&(buffer2+=`\x1B[${clearStartOffset}B`);for(let i=0;i<extraLines;i++)buffer2+=`\r\x1B[2K${TUI.SEGMENT_RESET}`,i<extraLines-1&&(buffer2+="\x1B[1B");let moveBack=Math.max(0,extraLines-1+clearStartOffset);moveBack>0&&(buffer2+=`\x1B[${moveBack}A`),buffer2=this.finishFrame(buffer2,cursorPos,newLines.length,targetRow),writeBounded(this.terminal,buffer2),this.cursorRow=targetRow}else this.positionHardwareCursor(cursorPos,newLines.length);this.setPreviousLines(newLines,rawLines),this.previousKittyImageIds=this.collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height,this.previousViewportTop=prevViewportTop;return}if(firstChanged<prevViewportTop){if(newLines.length<this.previousLines.length&&(viewportTop=Math.max(0,newLines.length-height)),newLines.length>this.previousLines.length){let maxViewportTop=Math.max(0,newLines.length-height);viewportTop=Math.min(maxViewportTop,prevViewportTop+lineCountDelta)}let firstVisibleChanged=-1,lastVisibleChanged=-1;for(let row=0;row<height;row++){let previousLine=this.previousLines[prevViewportTop+row]??"",nextLine=newLines[viewportTop+row]??"";previousLine!==nextLine&&(firstVisibleChanged===-1&&(firstVisibleChanged=row),lastVisibleChanged=row)}if(firstVisibleChanged===-1){if(lineCountDelta!==0){preserveMuxScrollback?this.renderMuxViewportRepaint(newLines,rawLines,cursorPos,width,height,viewportTop)||fullRender(!0,!1):this.#holdScrollbackReplay&&this.renderHeldRepaint(newLines,rawLines,cursorPos,width,height,prevViewportTop,hardwareCursorRow)||this.renderScrollbackReplay(newLines,rawLines,cursorPos,width,height,prevViewportTop,hardwareCursorRow);return}this.cursorRow=Math.max(0,newLines.length-1),this.maxLinesRendered=Math.max(this.maxLinesRendered,newLines.length),this.setPreviousLines(newLines,rawLines),this.previousWidth=width,this.previousHeight=height,this.previousViewportTop=viewportTop;return}if(viewportTop!==prevViewportTop){if(lineCountDelta!==0){preserveMuxScrollback?this.renderMuxViewportRepaint(newLines,rawLines,cursorPos,width,height,viewportTop)||fullRender(!0,!1):this.#holdScrollbackReplay&&this.renderHeldRepaint(newLines,rawLines,cursorPos,width,height,prevViewportTop,hardwareCursorRow)||this.renderScrollbackReplay(newLines,rawLines,cursorPos,width,height,prevViewportTop,hardwareCursorRow);return}let previousViewportBottom=Math.min(this.previousLines.length-1,prevViewportTop+height-1),buffer2=TUI.FRAME_BEGIN;buffer2+=this.deleteChangedKittyImages(prevViewportTop,previousViewportBottom);let currentScreenRow=Math.max(0,Math.min(height-1,hardwareCursorRow-prevViewportTop));currentScreenRow>0&&(buffer2+=`\x1B[${currentScreenRow}A`);for(let row=0;row<height;row++)row>0&&(buffer2+=`\r
`),buffer2+=`\r\x1B[2K${TUI.SEGMENT_RESET}`,buffer2+=newLines[viewportTop+row]??"";let finalCursorRow2=viewportTop+Math.max(0,height-1);buffer2=this.finishFrame(buffer2,cursorPos,newLines.length,finalCursorRow2),writeBounded(this.terminal,buffer2),this.cursorRow=Math.max(0,newLines.length-1),this.maxLinesRendered=Math.max(this.maxLinesRendered,newLines.length),this.previousViewportTop=viewportTop,this.setPreviousLines(newLines,rawLines),this.previousKittyImageIds=this.collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height;return}firstChanged=viewportTop+firstVisibleChanged,lastChanged=Math.min(newLines.length-1,viewportTop+lastVisibleChanged)}let buffer=TUI.FRAME_BEGIN;buffer+=this.deleteChangedKittyImages(firstChanged,lastChanged);let prevViewportBottom=prevViewportTop+height-1,moveTargetRow=appendStart?firstChanged-1:firstChanged;if(moveTargetRow>prevViewportBottom){let currentScreenRow=Math.max(0,Math.min(height-1,hardwareCursorRow-prevViewportTop)),moveToBottom=height-1-currentScreenRow;moveToBottom>0&&(buffer+=`\x1B[${moveToBottom}B`);let scroll=moveTargetRow-prevViewportBottom;buffer+=`\r
`.repeat(scroll),prevViewportTop+=scroll,viewportTop+=scroll,hardwareCursorRow=moveTargetRow}let lineDiff=computeLineDiff(moveTargetRow);lineDiff>0?buffer+=`\x1B[${lineDiff}B`:lineDiff<0&&(buffer+=`\x1B[${-lineDiff}A`),buffer+=appendStart?`\r
`:"\r";let renderEnd=Math.min(lastChanged,newLines.length-1);for(let i=firstChanged;i<=renderEnd;i++){i>firstChanged&&(buffer+=`\r
`);let line=newLines[i],isImage=isImageLine(line),imageReservedRows=isImage?this.getKittyImageReservedRows(newLines,i,renderEnd):1;if(imageReservedRows>1){let imageStartScreenRow=i-viewportTop;if(imageStartScreenRow<0||imageReservedRows>height){logRedraw(`kitty image cannot be placed in place (start row ${imageStartScreenRow}, ${imageReservedRows} rows, height ${height})`),fullRender(!0,!preserveMuxScrollback);return}buffer+=`\x1B[2K${TUI.SEGMENT_RESET}`;for(let row=1;row<imageReservedRows;row++)buffer+=`\r
\x1B[2K${TUI.SEGMENT_RESET}`;buffer+=`\x1B[${imageReservedRows-1}A`,buffer+=line,buffer+=`\x1B[${imageReservedRows-1}B`,i+=imageReservedRows-1;continue}buffer+=`\x1B[2K${TUI.SEGMENT_RESET}`;let lineWidth=visibleWidth(line);if(!isImage&&lineWidth>width){let crashLogPath=path.join(os.homedir(),".senpi","agent","senpi-crash.log"),strictRender=process.env.PI_TUI_STRICT_RENDER==="1";if(strictRender||!this.overWideCrashDumpWritten){let crashData=formatOverWideRenderDiagnostic(newLines,width,i,lineWidth);if(!strictRender)writeRenderDiagnosticBestEffort(crashLogPath,crashData),this.overWideCrashDumpWritten=!0;else{let crashDumpWritten=writeRenderDiagnosticBestEffort(crashLogPath,crashData);this.stop();let errorMsg=[`Rendered line ${i} exceeds terminal width (${lineWidth} > ${width}).`,"","This is likely caused by a custom TUI component not truncating its output.","Use visibleWidth() to measure and truncateToWidth() to truncate lines.","",crashDumpWritten?`Debug log written to: ${crashLogPath}`:`Debug log could not be written to: ${crashLogPath}`].join(`
`);throw new Error(errorMsg)}}let truncatedLine=sliceByColumn(line,0,width,!0)+TUI.SEGMENT_RESET;newLines[i]=truncatedLine,buffer+=truncatedLine;continue}buffer+=line}let finalCursorRow=renderEnd;if(this.previousLines.length>newLines.length){if(renderEnd<newLines.length-1){let moveDown=newLines.length-1-renderEnd;buffer+=`\x1B[${moveDown}B`,finalCursorRow=newLines.length-1}let extraLines=this.previousLines.length-newLines.length;for(let i=newLines.length;i<this.previousLines.length;i++)buffer+=`\r
\x1B[2K${TUI.SEGMENT_RESET}`;buffer+=`\x1B[${extraLines}A`}if(buffer=this.finishFrame(buffer,cursorPos,newLines.length,finalCursorRow),process.env.PI_TUI_DEBUG==="1"){let debugDir=path.join(os.tmpdir(),"tui");fs.mkdirSync(debugDir,{recursive:!0});let debugPath=path.join(debugDir,`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),debugData=[`firstChanged: ${firstChanged}`,`viewportTop: ${viewportTop}`,`cursorRow: ${this.cursorRow}`,`height: ${height}`,`lineDiff: ${lineDiff}`,`hardwareCursorRow: ${hardwareCursorRow}`,`renderEnd: ${renderEnd}`,`finalCursorRow: ${finalCursorRow}`,`cursorPos: ${JSON.stringify(cursorPos)}`,`newLines.length: ${newLines.length}`,`previousLines.length: ${this.previousLines.length}`,"","=== newLines ===",JSON.stringify(newLines,null,2),"","=== previousLines ===",JSON.stringify(this.previousLines,null,2),"","=== buffer ===",JSON.stringify(buffer)].join(`
`);fs.writeFileSync(debugPath,debugData,{encoding:"utf8",mode:DIAGNOSTIC_LOG_MODE}),chmodDiagnosticLogBestEffort(debugPath)}writeBounded(this.terminal,buffer),this.cursorRow=Math.max(0,newLines.length-1),this.maxLinesRendered=Math.max(this.maxLinesRendered,newLines.length),this.previousViewportTop=Math.max(prevViewportTop,finalCursorRow-height+1),this.setPreviousLines(newLines,rawLines),needsKittyImageExpansion&&(this.previousKittyImageIds=this.collectKittyImageIds(newLines)),this.previousWidth=width,this.previousHeight=height}buildHardwareCursorSequence(cursorPos,totalLines){let buffer="";if(!cursorPos||totalLines<=0)this.#lastCursorVisibility!==!1&&(buffer+="\x1B[?25l",this.#lastCursorVisibility=!1);else{let targetRow=Math.max(0,Math.min(cursorPos.row,totalLines-1)),targetCol=Math.max(0,cursorPos.col),rowDelta=targetRow-this.hardwareCursorRow;rowDelta>0?buffer+=`\x1B[${rowDelta}B`:rowDelta<0&&(buffer+=`\x1B[${-rowDelta}A`),buffer+=`\x1B[${targetCol+1}G`,this.hardwareCursorRow=targetRow,this.#lastCursorVisibility!==this.showHardwareCursor&&(buffer+=this.showHardwareCursor?"\x1B[?25h":"\x1B[?25l",this.#lastCursorVisibility=this.showHardwareCursor)}return buffer}finishFrame(buffer,cursorPos,totalLines,hardwareCursorRow){return this.hardwareCursorRow=hardwareCursorRow,buffer+this.buildHardwareCursorSequence(cursorPos,totalLines)+TUI.FRAME_END}positionHardwareCursor(cursorPos,totalLines){let buffer=this.buildHardwareCursorSequence(cursorPos,totalLines);buffer&&this.terminal.write(TUI.FRAME_BEGIN+buffer+TUI.FRAME_END)}queryTerminalColors({timeoutMs,onLateReply}){return new Promise(resolve=>{let query={palette:Array.from({length:TERMINAL_PALETTE_SIZE},()=>{}),replied:new Set,deliver:resolve,timer:void 0};query.timer=setTimeout(()=>{query.deliver=onLateReply,resolve(this.terminalColorQueryResult(query))},timeoutMs),this.pendingTerminalColorQueries.push(query),this.terminal.write(TERMINAL_COLOR_QUERY)})}};function isTerminalReport(data){return data.startsWith("\x1B[<")||data.startsWith("\x1B[M")||data.length>2&&(data.startsWith("\x1B]")||data.startsWith("\x1BP")||data.startsWith("\x1B_"))||data.startsWith("\x1B[?")||/^\x1b\[\d+(;\d+)*t$/.test(data)}var TUI=class extends TuiBase{constructor(){super(...arguments),this.mode="regular"}};function isAsciiLetter(char){if(!char)return!1;let code=char.charCodeAt(0);return code>=97&&code<=122}function isAsciiDigit(char){if(!char)return!1;let code=char.charCodeAt(0);return code>=48&&code<=57}function isWordBoundaryPrefix(char){switch(char){case" ":case" ":case`
`:case"\r":case"-":case"_":case".":case"/":case":":return!0;default:return!1}}function scoreMatch(queryLower,textLower){if(queryLower.length===0)return{matches:!0,score:0};if(queryLower.length>textLower.length)return{matches:!1,score:0};let queryIndex=0,score=0,lastMatchIndex=-1,consecutiveMatches=0;for(;queryIndex<queryLower.length;){let i=textLower.indexOf(queryLower[queryIndex],lastMatchIndex+1);if(i===-1)break;let isWordBoundary=i===0||isWordBoundaryPrefix(textLower[i-1]);lastMatchIndex===i-1?(consecutiveMatches++,score-=consecutiveMatches*5):(consecutiveMatches=0,lastMatchIndex>=0&&(score+=(i-lastMatchIndex-1)*2)),isWordBoundary&&(score-=10),score+=i*.1,lastMatchIndex=i,queryIndex++}return queryIndex<queryLower.length?{matches:!1,score:0}:(queryLower===textLower&&(score-=100),{matches:!0,score})}function addWholeTokenSwap(variants,queryLower){let splitIndex=0;for(;splitIndex<queryLower.length&&isAsciiLetter(queryLower[splitIndex]);)splitIndex++;if(splitIndex>0&&splitIndex<queryLower.length){let digitEnd=splitIndex;for(;digitEnd<queryLower.length&&isAsciiDigit(queryLower[digitEnd]);)digitEnd++;digitEnd===queryLower.length&&variants.add(queryLower.slice(splitIndex)+queryLower.slice(0,splitIndex))}for(splitIndex=0;splitIndex<queryLower.length&&isAsciiDigit(queryLower[splitIndex]);)splitIndex++;if(splitIndex>0&&splitIndex<queryLower.length){let letterEnd=splitIndex;for(;letterEnd<queryLower.length&&isAsciiLetter(queryLower[letterEnd]);)letterEnd++;letterEnd===queryLower.length&&variants.add(queryLower.slice(splitIndex)+queryLower.slice(0,splitIndex))}}function buildAlphanumericSwapQueries(queryLower){let variants=new Set;addWholeTokenSwap(variants,queryLower);for(let i=0;i<queryLower.length-1;i++){let current=queryLower[i],next=queryLower[i+1];(isAsciiLetter(current)&&isAsciiDigit(next)||isAsciiDigit(current)&&isAsciiLetter(next))&&variants.add(queryLower.slice(0,i)+next+current+queryLower.slice(i+2))}return[...variants]}function fuzzyMatch(query,text){return fuzzyMatchLower(query.toLowerCase(),text.toLowerCase())}function fuzzyMatchLower(queryLower,textLower){let direct=scoreMatch(queryLower,textLower);if(direct.matches)return direct;let bestSwap=null;for(let variant of buildAlphanumericSwapQueries(queryLower)){let match=scoreMatch(variant,textLower);if(!match.matches)continue;let score=match.score+5;(!bestSwap||score<bestSwap.score)&&(bestSwap={matches:!0,score})}return bestSwap??direct}function fuzzyFilter(items,query,getText){if(!query.trim())return items;let tokens=query.trim().split(/[\s/]+/).filter(t=>t.length>0);if(tokens.length===0)return items;let results=[];for(let item of items){let text=getText(item),totalScore=0,allMatch=!0;for(let token of tokens){let match=fuzzyMatch(token,text);if(match.matches)totalScore+=match.score;else{allMatch=!1;break}}allMatch&&results.push({item,totalScore})}return results.sort((a,b2)=>a.totalScore-b2.totalScore),results.map(r=>r.item)}import{spawn}from"child_process";import{readdirSync,statSync}from"fs";import{homedir as homedir3}from"os";import{basename,dirname as dirname2,join as join2}from"path";var SKILL_COMMAND_PREFIX="skill:",DOLLAR_QUERY_PATTERN=/^\$([a-zA-Z0-9:_-]*)$/,DOLLAR_MENTION_PATTERN=/(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s|$)/g,COMMON_SHELL_VARIABLES=new Set(["CI","EDITOR","HOME","LANG","LC_ALL","NODE_ENV","OLDPWD","PATH","PWD","SHELL","SHLVL","TERM","TMPDIR","USER","VISUAL"]);function isDollarQueryCompletable(query){return query===""?!0:query.startsWith("-")||query.startsWith("_")||/^\d/.test(query)?!1:!COMMON_SHELL_VARIABLES.has(query)}function commandName(command){return"name"in command?command.name:command.value}function skillName(name){return name.startsWith(SKILL_COMMAND_PREFIX)&&name.slice(SKILL_COMMAND_PREFIX.length)||null}function commandDescription(command){let hint="argumentHint"in command&&command.argumentHint?command.argumentHint:void 0,description=command.description??"";return hint?description?`${hint} - ${description}`:hint:description||void 0}function findDollarSkillMentions(line,knownSkills){if(knownSkills.size===0)return[];let mentions=[];for(let match of line.matchAll(DOLLAR_MENTION_PATTERN)){let token=match[2]??"",name=token.startsWith(SKILL_COMMAND_PREFIX)?token.slice(SKILL_COMMAND_PREFIX.length):token;if(!knownSkills.has(name))continue;let start=match.index+(match[1]??"").length;mentions.push({start,end:start+token.length+1,name})}return mentions}function knownSkillNames(commands){return new Set(commands.flatMap(command=>{let name=skillName(commandName(command));return name?[name]:[]}))}function getDollarInvocationContext(textBeforeCursor,_cursorLine,commands){let tokenStart=textBeforeCursor.search(/\S+$/),token=tokenStart===-1?"":textBeforeCursor.slice(tokenStart),match=DOLLAR_QUERY_PATTERN.exec(token);if(!match)return null;let rawQuery=match[1]??"";if(!isDollarQueryCompletable(rawQuery))return null;let explicitSkillNamespace=rawQuery.startsWith(SKILL_COMMAND_PREFIX),query=explicitSkillNamespace?rawQuery.slice(SKILL_COMMAND_PREFIX.length):rawQuery;if(knownSkillNames(commands).has(query))return null;let isFirstToken=textBeforeCursor.slice(0,tokenStart).trim()==="";return{prefix:`$${rawQuery}`,query,skillsOnly:explicitSkillNamespace||!isFirstToken}}function getDollarInvocationSuggestions(commands,query,skillsOnly){let items=commands.flatMap(command=>{let name=commandName(command),skill=skillName(name);return skill?[{kind:"skill",value:`$${skill}`,label:`$${skill}`,searchText:skill,description:commandDescription(command)}]:skillsOnly?[]:[{kind:"command",value:`/${name}`,label:`/${name}`,searchText:name,description:commandDescription(command)}]});return fuzzyFilter(items,query,item=>item.searchText).map((item,index)=>({...item,index})).sort((left,right)=>left.kind!==right.kind?left.kind==="command"?-1:1:left.index-right.index).map(({index:_index,kind:_kind,searchText:_searchText,...item})=>item)}var SKILL_COMMAND_PREFIX2="skill:";function isSlashNamespaceItem(value){return value.endsWith(":")}function compareSlashCommandSuggestion(prefix,left,right){let leftExact=left.value===prefix,rightExact=right.value===prefix;if(leftExact!==rightExact)return leftExact?-1:1;let leftPrefix=left.value.startsWith(prefix),rightPrefix=right.value.startsWith(prefix);return leftPrefix!==rightPrefix?leftPrefix?-1:1:leftPrefix&&rightPrefix&&left.value.length!==right.value.length?right.value.length-left.value.length:left.index-right.index}function getSlashCommandSuggestions(commands,prefix){let normalizedPrefix=prefix.toLowerCase(),explicitSkillNamespace=normalizedPrefix.startsWith(SKILL_COMMAND_PREFIX2),hasSkillCommands=commands.some(cmd=>("name"in cmd?cmd.name:cmd.value).startsWith(SKILL_COMMAND_PREFIX2)),commandItems=commands.flatMap(cmd=>{let name="name"in cmd?cmd.name:cmd.value,isSkill=name.startsWith(SKILL_COMMAND_PREFIX2),skillName2=isSkill?name.slice(SKILL_COMMAND_PREFIX2.length):"";if(isSkill&&!explicitSkillNamespace&&(normalizedPrefix.length===0||!skillName2.toLowerCase().startsWith(normalizedPrefix)))return[];let hint="argumentHint"in cmd&&cmd.argumentHint?cmd.argumentHint:void 0,requiresArguments=("requiresArguments"in cmd?cmd.requiresArguments:void 0)??hint!==void 0,desc=cmd.description??"",fullDesc=hint?desc?`${hint} - ${desc}`:hint:desc;return[{name,label:name,description:fullDesc||void 0,searchText:isSkill&&!explicitSkillNamespace?skillName2:name,awaitsArguments:requiresArguments||"awaitsArguments"in cmd&&cmd.awaitsArguments===!0}]});return hasSkillCommands&&!explicitSkillNamespace&&normalizedPrefix.length>0&&SKILL_COMMAND_PREFIX2.startsWith(normalizedPrefix)&&commandItems.push({name:SKILL_COMMAND_PREFIX2,label:SKILL_COMMAND_PREFIX2,description:"Browse available skills",searchText:SKILL_COMMAND_PREFIX2,awaitsArguments:!1}),fuzzyFilter(commandItems,prefix,item=>item.searchText).map((item,index)=>({value:item.name,label:item.label,...item.description&&{description:item.description},...item.awaitsArguments&&{awaitsArguments:!0},index})).sort((left,right)=>compareSlashCommandSuggestion(normalizedPrefix,left,right)).map(({index:_index,...item})=>item)}var PATH_DELIMITERS=new Set([" "," ",'"',"'","="]),tokenStartRegex=new RegExp(`${autocompleteBoundaryRegex.source}$`,"u"),PATH_WRAPPERS={"(":")","[":"]","{":"}","<":">","`":"`"};function toDisplayPath(value){return value.replace(/\\/g,"/")}function escapeRegex(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function buildFdPathQuery(query){let normalized=toDisplayPath(query);if(!normalized.includes("/"))return normalized;let hasTrailingSeparator=normalized.endsWith("/"),trimmed=normalized.replace(/^\/+|\/+$/g,"");if(!trimmed)return normalized;let separatorPattern="[\\\\/]",segments=trimmed.split("/").filter(Boolean).map(segment=>escapeRegex(segment));if(segments.length===0)return normalized;let pattern=segments.join(separatorPattern);return hasTrailingSeparator&&(pattern+=separatorPattern),pattern}function findLastDelimiter(text){let lastDelimiter=-1,index=0;for(let character of text)index+=character.length,(PATH_DELIMITERS.has(character)||autocompleteSeparatorRegex.test(character))&&(lastDelimiter=index-1);return lastDelimiter}function stripLeadingWrappers(token){let result=token;for(;result.length>0;){let closer=PATH_WRAPPERS[result[0]];if(!closer||result.includes(closer,1))break;result=result.slice(1)}return result}function findUnclosedQuoteStart(text){let inQuotes=!1,quoteStart=-1;for(let i=0;i<text.length;i+=1)text[i]==='"'&&(inQuotes=!inQuotes,inQuotes&&(quoteStart=i));return inQuotes?quoteStart:null}function isTokenStart(text,index){let start=index;for(;start>0&&PATH_WRAPPERS[text[start-1]];)start-=1;return PATH_DELIMITERS.has(text[start-1]??"")||tokenStartRegex.test(text.slice(0,start))}function extractQuotedPrefix(text){let quoteStart=findUnclosedQuoteStart(text);return quoteStart===null?null:quoteStart>0&&text[quoteStart-1]==="@"?isTokenStart(text,quoteStart-1)?text.slice(quoteStart-1):null:isTokenStart(text,quoteStart)?text.slice(quoteStart):null}function parsePathPrefix(prefix){return prefix.startsWith('@"')?{rawPrefix:prefix.slice(2),isAtPrefix:!0,isQuotedPrefix:!0}:prefix.startsWith('"')?{rawPrefix:prefix.slice(1),isAtPrefix:!1,isQuotedPrefix:!0}:prefix.startsWith("@")?{rawPrefix:prefix.slice(1),isAtPrefix:!0,isQuotedPrefix:!1}:{rawPrefix:prefix,isAtPrefix:!1,isQuotedPrefix:!1}}function buildCompletionValue(path4,options){let needsQuotes=options.isQuotedPrefix||autocompleteSeparatorRegex.test(path4),prefix=options.isAtPrefix?"@":"";return needsQuotes?`${`${prefix}"`}${path4}"`:`${prefix}${path4}`}async function walkDirectoryWithFd(baseDir,fdPath,query,maxResults,signal,maxDepth){let args=["--base-directory",baseDir,"--max-results",String(maxResults),"--type","f","--type","d","--follow","--hidden","--exclude",".git","--exclude",".git/*","--exclude",".git/**"];return maxDepth!==void 0&&args.push("--max-depth",String(maxDepth)),toDisplayPath(query).includes("/")&&args.push("--full-path"),query&&args.push(buildFdPathQuery(query)),await new Promise(resolve=>{if(signal.aborted){resolve([]);return}let child=spawn(fdPath,args,{stdio:["ignore","pipe","pipe"]}),stdout="",resolved=!1,finish=results=>{resolved||(resolved=!0,signal.removeEventListener("abort",onAbort),resolve(results))},onAbort=()=>{child.pid!==void 0&&child.exitCode===null&&child.kill("SIGKILL")};signal.addEventListener("abort",onAbort,{once:!0}),child.stdout.setEncoding("utf-8"),child.stdout.on("data",chunk=>{stdout+=chunk}),child.on("error",()=>{finish([])}),child.on("close",code=>{if(signal.aborted||code!==0||!stdout){finish([]);return}let lines=stdout.trim().split(`
`).filter(Boolean),results=[];for(let line of lines){let displayLine=toDisplayPath(line),hasTrailingSeparator=displayLine.endsWith("/"),normalizedPath=hasTrailingSeparator?displayLine.slice(0,-1):displayLine;normalizedPath===".git"||normalizedPath.startsWith(".git/")||normalizedPath.includes("/.git/")||results.push({path:displayLine,isDirectory:hasTrailingSeparator})}finish(results)})})}var CombinedAutocompleteProvider=class{constructor(commands=[],basePath,fdPath=null){this.commands=commands,this.basePath=basePath,this.fdPath=fdPath}getMentionRanges(line){return findDollarSkillMentions(line,knownSkillNames(this.commands)).map(({start,end})=>({start,end}))}async getSuggestions(lines,cursorLine,cursorCol,options){let textBeforeCursor=(lines[cursorLine]||"").slice(0,cursorCol),atPrefix=this.extractAtPrefix(textBeforeCursor);if(atPrefix){let{rawPrefix,isQuotedPrefix}=parsePathPrefix(atPrefix),suggestions2=await this.getFuzzyFileSuggestions(rawPrefix,{isQuotedPrefix,signal:options.signal});return suggestions2.length===0?null:{items:suggestions2,prefix:atPrefix}}let dollarContext=getDollarInvocationContext(textBeforeCursor,cursorLine,this.commands);if(dollarContext){let suggestions2=getDollarInvocationSuggestions(this.commands,dollarContext.query,dollarContext.skillsOnly);return suggestions2.length===0?null:{items:suggestions2,prefix:dollarContext.prefix}}let commandText=textBeforeCursor.trimStart();if(!options.force&&commandText.startsWith("/")){let spaceIndex=commandText.indexOf(" ");if(spaceIndex===-1){let prefix=commandText.slice(1),filtered=getSlashCommandSuggestions(this.commands,prefix);return filtered.length===0?null:{items:filtered,prefix:commandText}}let tokenStart=textBeforeCursor.search(/\S+$/),currentToken=tokenStart===-1?"":textBeforeCursor.slice(tokenStart);if(currentToken.startsWith("/skill:")&&this.isLeadingKnownSkillCommandRun(textBeforeCursor.slice(0,tokenStart))){let skillCommands=this.commands.filter(command2=>("name"in command2?command2.name:command2.value).startsWith("skill:")),filtered=getSlashCommandSuggestions(skillCommands,currentToken.slice(1));return filtered.length===0?null:{items:filtered,prefix:currentToken}}let commandName2=commandText.slice(1,spaceIndex),argumentText=commandText.slice(spaceIndex+1),command=this.commands.find(cmd=>("name"in cmd?cmd.name:cmd.value)===commandName2);if(!command||!("getArgumentCompletions"in command)||!command.getArgumentCompletions)return null;let argumentSuggestions=await command.getArgumentCompletions(argumentText);return!Array.isArray(argumentSuggestions)||argumentSuggestions.length===0?null:{items:argumentSuggestions,prefix:argumentText}}let pathMatch=this.extractPathPrefix(textBeforeCursor,options.force??!1);if(pathMatch===null)return null;let suggestions=this.getFileSuggestions(pathMatch);return suggestions.length===0?null:{items:suggestions,prefix:pathMatch}}applyCompletion(lines,cursorLine,cursorCol,item,prefix){let currentLine=lines[cursorLine]||"",beforePrefix=currentLine.slice(0,cursorCol-prefix.length),afterCursor=currentLine.slice(cursorCol),isQuotedPrefix=prefix.startsWith('"')||prefix.startsWith('@"'),hasLeadingQuoteAfterCursor=afterCursor.startsWith('"'),hasTrailingQuoteInItem=item.value.endsWith('"'),adjustedAfterCursor=isQuotedPrefix&&hasTrailingQuoteInItem&&hasLeadingQuoteAfterCursor?afterCursor.slice(1):afterCursor;if(prefix.startsWith("$")&&(item.value.startsWith("/")||item.value.startsWith("$"))){let newLine2=`${beforePrefix}${item.value} ${adjustedAfterCursor}`,newLines2=[...lines];return newLines2[cursorLine]=newLine2,{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+item.value.length+1}}if(prefix.startsWith("/")&&!prefix.slice(1).includes("/")&&(beforePrefix.trim()===""||prefix.startsWith("/skill:")&&this.isLeadingKnownSkillCommandRun(beforePrefix))){let separator=isSlashNamespaceItem(item.value)?"":" ",newLine2=`${beforePrefix}/${item.value}${separator}${adjustedAfterCursor}`,newLines2=[...lines];return newLines2[cursorLine]=newLine2,{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+1+item.value.length+separator.length}}if(prefix.startsWith("@")){let isDirectory2=item.label.endsWith("/"),suffix=isDirectory2?"":" ",newLine2=`${beforePrefix+item.value}${suffix}${adjustedAfterCursor}`,newLines2=[...lines];newLines2[cursorLine]=newLine2;let hasTrailingQuote2=item.value.endsWith('"'),cursorOffset2=isDirectory2&&hasTrailingQuote2?item.value.length-1:item.value.length;return{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+cursorOffset2+suffix.length}}let textBeforeCursor=currentLine.slice(0,cursorCol);if(textBeforeCursor.includes("/")&&textBeforeCursor.includes(" ")){let newLine2=beforePrefix+item.value+adjustedAfterCursor,newLines2=[...lines];newLines2[cursorLine]=newLine2;let isDirectory2=item.label.endsWith("/"),hasTrailingQuote2=item.value.endsWith('"'),cursorOffset2=isDirectory2&&hasTrailingQuote2?item.value.length-1:item.value.length;return{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+cursorOffset2}}let newLine=beforePrefix+item.value+adjustedAfterCursor,newLines=[...lines];newLines[cursorLine]=newLine;let isDirectory=item.label.endsWith("/"),hasTrailingQuote=item.value.endsWith('"'),cursorOffset=isDirectory&&hasTrailingQuote?item.value.length-1:item.value.length;return{lines:newLines,cursorLine,cursorCol:beforePrefix.length+cursorOffset}}isLeadingKnownSkillCommandRun(text){let tokens=text.trim().split(/\s+/);return tokens.length>0&&tokens.every(token=>{if(!token.startsWith("/skill:"))return!1;let commandName2=token.slice(1);return this.commands.some(command=>("name"in command?command.name:command.value)===commandName2)})}extractAtPrefix(text){let quotedPrefix=extractQuotedPrefix(text);if(quotedPrefix?.startsWith('@"'))return quotedPrefix;let lastDelimiterIndex=findLastDelimiter(text),token=stripLeadingWrappers(lastDelimiterIndex===-1?text:text.slice(lastDelimiterIndex+1));return token.startsWith("@")?token:null}extractPathPrefix(text,forceExtract=!1){let quotedPrefix=extractQuotedPrefix(text);if(quotedPrefix)return quotedPrefix;let lastDelimiterIndex=findLastDelimiter(text),pathPrefix=stripLeadingWrappers(lastDelimiterIndex===-1?text:text.slice(lastDelimiterIndex+1));return forceExtract||pathPrefix.includes("/")||pathPrefix.startsWith(".")||pathPrefix.startsWith("~/")||pathPrefix===""&&text!==""&&tokenStartRegex.test(text)?pathPrefix:null}expandHomePath(path4){if(path4.startsWith("~/")){let expandedPath=join2(homedir3(),path4.slice(2));return path4.endsWith("/")&&!expandedPath.endsWith("/")?`${expandedPath}/`:expandedPath}else if(path4==="~")return homedir3();return path4}resolveScopedFuzzyQuery(rawQuery){let normalizedQuery=toDisplayPath(rawQuery),slashIndex=normalizedQuery.lastIndexOf("/");if(slashIndex===-1)return null;let displayBase=normalizedQuery.slice(0,slashIndex+1),query=normalizedQuery.slice(slashIndex+1),baseDir;displayBase.startsWith("~/")?baseDir=this.expandHomePath(displayBase):displayBase.startsWith("/")?baseDir=displayBase:baseDir=join2(this.basePath,displayBase);try{if(!statSync(baseDir).isDirectory())return null}catch{return null}return{baseDir,query,displayBase}}scopedPathForDisplay(displayBase,relativePath){let normalizedRelativePath=toDisplayPath(relativePath);return displayBase==="/"?`/${normalizedRelativePath}`:`${toDisplayPath(displayBase)}${normalizedRelativePath}`}getFileSuggestions(prefix){try{let searchDir,searchPrefix,{rawPrefix,isAtPrefix,isQuotedPrefix}=parsePathPrefix(prefix),expandedPrefix=rawPrefix;if(expandedPrefix.startsWith("~")&&(expandedPrefix=this.expandHomePath(expandedPrefix)),rawPrefix===""||rawPrefix==="./"||rawPrefix==="../"||rawPrefix==="~"||rawPrefix==="~/"||rawPrefix==="/"||isAtPrefix&&rawPrefix==="")rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join2(this.basePath,expandedPrefix),searchPrefix="";else if(rawPrefix.endsWith("/"))rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join2(this.basePath,expandedPrefix),searchPrefix="";else{let dir=dirname2(expandedPrefix),file=basename(expandedPrefix);rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=dir:searchDir=join2(this.basePath,dir),searchPrefix=file}let entries=readdirSync(searchDir,{withFileTypes:!0}),suggestions=[];for(let entry of entries){if(!entry.name.toLowerCase().startsWith(searchPrefix.toLowerCase()))continue;let isDirectory=entry.isDirectory();if(!isDirectory&&entry.isSymbolicLink())try{let fullPath=join2(searchDir,entry.name);isDirectory=statSync(fullPath).isDirectory()}catch{}let relativePath,name=entry.name,displayPrefix=rawPrefix;if(displayPrefix.endsWith("/"))relativePath=displayPrefix+name;else if(displayPrefix.includes("/")||displayPrefix.includes("\\"))if(displayPrefix.startsWith("~/")){let homeRelativeDir=displayPrefix.slice(2),dir=dirname2(homeRelativeDir);relativePath=`~/${dir==="."?name:join2(dir,name)}`}else if(displayPrefix.startsWith("/")){let dir=dirname2(displayPrefix);dir==="/"?relativePath=`/${name}`:relativePath=`${dir}/${name}`}else relativePath=join2(dirname2(displayPrefix),name),displayPrefix.startsWith("./")&&!relativePath.startsWith("./")&&(relativePath=`./${relativePath}`);else displayPrefix.startsWith("~")?relativePath=`~/${name}`:relativePath=name;relativePath=toDisplayPath(relativePath);let pathValue=isDirectory?`${relativePath}/`:relativePath,value=buildCompletionValue(pathValue,{isDirectory,isAtPrefix,isQuotedPrefix});suggestions.push({value,label:name+(isDirectory?"/":"")})}return suggestions.sort((a,b2)=>{let aIsDir=a.label.endsWith("/"),bIsDir=b2.label.endsWith("/");return aIsDir&&!bIsDir?-1:!aIsDir&&bIsDir?1:a.label.localeCompare(b2.label)}),suggestions}catch{return[]}}scoreEntry(filePath,query,isDirectory){let lowerFileName=basename(filePath).toLowerCase(),lowerQuery=query.toLowerCase(),score=0;return lowerFileName===lowerQuery?score=100:lowerFileName.startsWith(lowerQuery)?score=80:lowerFileName.includes(lowerQuery)?score=50:filePath.toLowerCase().includes(lowerQuery)&&(score=30),isDirectory&&score>0&&(score+=10),score}async getBaseDirSuggestions(baseDir,query,signal){return!this.fdPath||signal.aborted?[]:await walkDirectoryWithFd(baseDir,this.fdPath,query,100,signal,1)}async getFuzzyFileSuggestions(query,options){if(!this.fdPath||options.signal.aborted)return[];try{let scopedQuery=this.resolveScopedFuzzyQuery(query),fdBaseDir=scopedQuery?.baseDir??this.basePath,fdQuery=scopedQuery?.query??query,baseDirEntries=await this.getBaseDirSuggestions(fdBaseDir,fdQuery,options.signal),recursiveEntries=await walkDirectoryWithFd(fdBaseDir,this.fdPath,fdQuery,100,options.signal),seenPaths=new Set(baseDirEntries.map(entry=>entry.path)),entries=[...baseDirEntries,...recursiveEntries.filter(entry=>seenPaths.has(entry.path)?!1:(seenPaths.add(entry.path),!0))];if(options.signal.aborted)return[];let scoredEntries=entries.map(entry=>({...entry,score:fdQuery?this.scoreEntry(entry.path,fdQuery,entry.isDirectory):1})).filter(entry=>entry.score>0);scoredEntries.sort((a,b2)=>{let scoreDiff=b2.score-a.score;if(scoreDiff!==0)return scoreDiff;let aDepth=toDisplayPath(a.path).split("/").filter(Boolean).length,bDepth=toDisplayPath(b2.path).split("/").filter(Boolean).length,depthDiff=aDepth-bDepth;if(depthDiff!==0)return depthDiff;let lengthDiff=a.path.length-b2.path.length;return lengthDiff!==0?lengthDiff:a.path.localeCompare(b2.path)});let topEntries=scoredEntries.slice(0,20),suggestions=[];for(let{path:entryPath,isDirectory}of topEntries){let pathWithoutSlash=isDirectory?entryPath.slice(0,-1):entryPath,displayPath=scopedQuery?this.scopedPathForDisplay(scopedQuery.displayBase,pathWithoutSlash):pathWithoutSlash,entryName=basename(pathWithoutSlash),completionPath=isDirectory?`${displayPath}/`:displayPath,value=buildCompletionValue(completionPath,{isDirectory,isAtPrefix:!0,isQuotedPrefix:options.isQuotedPrefix});suggestions.push({value,label:entryName+(isDirectory?"/":""),description:displayPath})}return suggestions}catch{return[]}}shouldTriggerFileCompletion(lines,cursorLine,cursorCol){let textBeforeCursor=(lines[cursorLine]||"").slice(0,cursorCol);return!(textBeforeCursor.trim().startsWith("/")&&!textBeforeCursor.trim().includes(" "))}};var Text=class _Text{constructor(text="",paddingX=1,paddingY=1,customBgFn){this.revision=nextRenderRevision(),this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.customBgFn=customBgFn}setText(text){text!==this.text&&this.markRevision(),this.text=text,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setCustomBgFn(customBgFn){this.customBgFn=customBgFn,this.markRevision(),this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0,this.markRevision()}markRevision(){this.revision=this.getRenderRevision()===void 0?this.revision+1:nextRenderRevision()}getRenderRevision(){return Object.getPrototypeOf(this)===_Text.prototype?this.revision:void 0}textRenderRevision(){return this.revision}render(width){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width)return this.cachedLines;if(!this.text||this.text.trim()===""){let result2=[];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result2,result2}let normalizedText2=this.text.replace(/\t/g," "),paddingX=Math.min(this.paddingX,Math.max(0,Math.floor((width-1)/2))),contentWidth=Math.max(1,width-paddingX*2),wrappedLines=wrapTextWithAnsi(normalizedText2,contentWidth),leftMargin=" ".repeat(paddingX),rightMargin=" ".repeat(paddingX),contentLines=[];for(let line of wrappedLines){let lineWithMargins=leftMargin+line+rightMargin;if(this.customBgFn)contentLines.push(applyBackgroundToLine(lineWithMargins,width,this.customBgFn));else{let visibleLen=visibleWidth(lineWithMargins),paddingNeeded=Math.max(0,width-visibleLen);contentLines.push(lineWithMargins+" ".repeat(paddingNeeded))}}let emptyLine=" ".repeat(width),emptyLines=[];for(let i=0;i<this.paddingY;i++){let line=this.customBgFn?applyBackgroundToLine(emptyLine,width,this.customBgFn):emptyLine;emptyLines.push(line)}let result=[...emptyLines,...contentLines,...emptyLines];for(let row=0;row<emptyLines.length;row++)setLineSource(result,row,null),setLineSource(result,result.length-row-1,null);return flattenLines(result),this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}};var DEFAULT_PRIMARY_COLUMN_WIDTH=32,PRIMARY_COLUMN_GAP=2,MIN_DESCRIPTION_WIDTH=10,normalizeToSingleLine=text=>text.replace(/[\r\n]+/g," ").trim(),clamp=(value,min,max)=>Math.max(min,Math.min(value,max)),SelectList=class{constructor(items,maxVisible,theme,layout={}){this.items=[],this.filteredItems=[],this.selectedIndex=0,this.maxVisible=5,this.items=items,this.filteredItems=items,this.maxVisible=maxVisible,this.theme=theme,this.layout=layout}setFilter(filter){this.filteredItems=this.items.filter(item=>item.value.toLowerCase().startsWith(filter.toLowerCase())),this.selectedIndex=0}setSelectedIndex(index){this.selectedIndex=Math.max(0,Math.min(index,this.filteredItems.length-1))}invalidate(){}render(width){let lines=[];if(this.filteredItems.length===0)return lines.push(this.theme.noMatch(" No matching commands")),lines;let primaryColumnWidth=this.getPrimaryColumnWidth(),{startIndex,endIndex}=this.getVisibleRange();for(let i=startIndex;i<endIndex;i++){let item=this.filteredItems[i];if(!item)continue;let isSelected=i===this.selectedIndex,descriptionSingleLine=item.description?normalizeToSingleLine(item.description):void 0;lines.push(this.renderItem(item,isSelected,width,descriptionSingleLine,primaryColumnWidth))}if(startIndex>0||endIndex<this.filteredItems.length){let scrollText=` (${this.selectedIndex+1}/${this.filteredItems.length})`;lines.push(this.theme.scrollInfo(truncateToWidth(scrollText,width-2,"")))}return lines}handleMouse(event){if(this.filteredItems.length===0)return;if(event.type==="wheel"&&event.wheelDelta){let delta=event.wheelDelta<0?-1:1,previousIndex=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(this.filteredItems.length-1,this.selectedIndex+delta)),this.selectedIndex!==previousIndex&&this.notifySelectionChange(),{handled:!0,render:this.selectedIndex!==previousIndex}}if(event.button!=="left"||event.type!=="press"&&event.type!=="click")return;let{startIndex,endIndex}=this.getVisibleRange(),itemIndex=startIndex+event.y;if(!(itemIndex<startIndex||itemIndex>=endIndex)){if(event.type==="press")return this.mousePressedIndex=itemIndex,this.selectedIndex!==itemIndex&&(this.selectedIndex=itemIndex,this.notifySelectionChange()),{handled:!0,focus:!0};if(event.type==="click"){let clickedIndex=this.mousePressedIndex??itemIndex;this.mousePressedIndex=void 0;let changed=this.selectedIndex!==clickedIndex;this.selectedIndex=clickedIndex,changed&&this.notifySelectionChange();let selectedItem=this.filteredItems[this.selectedIndex];return selectedItem&&this.onSelect?.(selectedItem),{handled:!0}}}}handleInput(keyData){let kb=getKeybindings();if(kb.matches(keyData,"tui.select.up"))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(kb.matches(keyData,"tui.select.down"))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(kb.matches(keyData,"tui.select.confirm")){let selectedItem=this.filteredItems[this.selectedIndex];selectedItem&&this.onSelect&&this.onSelect(selectedItem)}else kb.matches(keyData,"tui.select.cancel")&&this.onCancel&&this.onCancel()}getVisibleRange(){let startIndex=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible));return{startIndex,endIndex:Math.min(startIndex+this.maxVisible,this.filteredItems.length)}}renderItem(item,isSelected,width,descriptionSingleLine,primaryColumnWidth){let prefix=isSelected?"\u2192 ":" ",prefixWidth=visibleWidth(prefix);if(descriptionSingleLine&&width>40){let effectivePrimaryColumnWidth=Math.max(1,Math.min(primaryColumnWidth,width-prefixWidth-4)),maxPrimaryWidth=Math.max(1,effectivePrimaryColumnWidth-PRIMARY_COLUMN_GAP),truncatedValue2=this.truncatePrimary(item,isSelected,maxPrimaryWidth,effectivePrimaryColumnWidth),truncatedValueWidth=visibleWidth(truncatedValue2),spacing=" ".repeat(Math.max(1,effectivePrimaryColumnWidth-truncatedValueWidth)),descriptionStart=prefixWidth+truncatedValueWidth+spacing.length,remainingWidth=width-descriptionStart-2;if(remainingWidth>MIN_DESCRIPTION_WIDTH){let truncatedDesc=truncateToWidth(descriptionSingleLine,remainingWidth,"");return this.composeRow(prefix,truncatedValue2,spacing+truncatedDesc,isSelected)}}let maxWidth=width-prefixWidth-2,truncatedValue=this.truncatePrimary(item,isSelected,maxWidth,maxWidth);return this.composeRow(prefix,truncatedValue,void 0,isSelected)}composeRow(prefix,primary,description,isSelected){return this.theme.renderRow?this.theme.renderRow({prefix:isSelected?this.theme.selectedPrefix(prefix):prefix,primary,description,isSelected}):isSelected?this.theme.selectedText(`${prefix}${primary}${description??""}`):prefix+primary+(description!==void 0?this.theme.description(description):"")}getPrimaryColumnWidth(){let{min,max}=this.getPrimaryColumnBounds(),widestPrimary=this.filteredItems.reduce((widest,item)=>Math.max(widest,visibleWidth(this.getDisplayValue(item))+PRIMARY_COLUMN_GAP),0);return clamp(widestPrimary,min,max)}getPrimaryColumnBounds(){let rawMin=this.layout.minPrimaryColumnWidth??this.layout.maxPrimaryColumnWidth??DEFAULT_PRIMARY_COLUMN_WIDTH,rawMax=this.layout.maxPrimaryColumnWidth??this.layout.minPrimaryColumnWidth??DEFAULT_PRIMARY_COLUMN_WIDTH;return{min:Math.max(1,Math.min(rawMin,rawMax)),max:Math.max(1,Math.max(rawMin,rawMax))}}truncatePrimary(item,isSelected,maxWidth,columnWidth){let displayValue=this.getDisplayValue(item),truncatedValue=this.layout.truncatePrimary?this.layout.truncatePrimary({text:displayValue,maxWidth,columnWidth,item,isSelected}):truncateToWidth(displayValue,maxWidth,"");return truncateToWidth(truncatedValue,maxWidth,"")}getDisplayValue(item){return item.label||item.value}notifySelectionChange(){let selectedItem=this.filteredItems[this.selectedIndex];selectedItem&&this.onSelectionChange&&this.onSelectionChange(selectedItem)}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}};function A(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var T=A();function U(l3){T=l3}var E={exec:()=>null};function I(l3){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),i=e[n];return i||(i=l3(n),e[n]=i),i}}function d(l3,e=""){let t=typeof l3=="string"?l3:l3.source,n={replace:(i,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(m.caret,"$1"),t=t.replace(i,o),n},getRegex:()=>new RegExp(t,e)};return n}var we=((l3="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+l3)}catch{return!1}})(),m={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l3=>new RegExp(`^( {0,3}${l3})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:I(l3=>new RegExp(`^ {0,${l3}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:I(l3=>new RegExp(`^ {0,${l3}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}(?:\`\`\`|~~~)`)),headingBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}#`)),htmlBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}(?:</?(?:${H})(?: +|$|/?>)|<(?:script|pre|style|textarea|!--))`,"i")),blockquoteBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}>`))},ye=/^(?:[ \t]*(?:\n|$))+/,Pe=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Se=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,v=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,_e=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,K=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,le=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ue=d(le).replace(/bull/g,K).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),$e=d(le).replace(/bull/g,K).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),W=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Le=/^[^\n]+/,X=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ze=d(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",X).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ee=d(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,K).getRegex(),H="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",J=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Me=d("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][a-z0-9-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",J).replace("tag",H).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),pe=l3=>d(W).replace("hr",v).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",l3).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex(),Ae=pe(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Ie=pe(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Ce=d(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ie).getRegex(),V={blockquote:Ce,code:Pe,def:ze,fences:Se,heading:_e,hr:v,html:Me,lheading:ue,list:Ee,newline:ye,paragraph:Ae,table:E,text:Le},ie=d("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",v).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex(),Be={...V,lheading:$e,table:ie,paragraph:d(W).replace("hr",v).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",ie).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex()},De={...V,html:d(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",J).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:E,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:d(W).replace("hr",v).replace("heading",` *#{1,6} *[^
]`).replace("lheading",ue).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},qe=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ve=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ce=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,He=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,_=/[\p{P}\p{S}]/u,C=/[\s\p{P}\p{S}]/u,Z=/[^\s\p{P}\p{S}]/u,Ze=d(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,C).getRegex(),Ge=/[\p{Pi}\p{Ps}"']/u,he=/(?!~)[\p{P}\p{S}]/u,Qe=/(?!~)[\s\p{P}\p{S}]/u,Ne=/(?:[^\s\p{P}\p{S}]|~)/u,je=d(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",we?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),de=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Ue=d(de,"u").replace(/punct/g,_).getRegex(),Fe=d(de,"u").replace(/punct/g,he).getRegex(),Ke=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,We=d(Ke,"u").replace(/openQuote/g,Ge).replace(/punct/g,_).getRegex(),ke="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Xe=d(ke,"gu").replace(/notPunctSpace/g,Z).replace(/punctSpace/g,C).replace(/punct/g,_).getRegex(),Je=d(ke,"gu").replace(/notPunctSpace/g,Ne).replace(/punctSpace/g,Qe).replace(/punct/g,he).getRegex(),Ve="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",Ye=d(Ve,"gu").replace(/notPunctSpace/g,Z).replace(/punctSpace/g,C).replace(/punct/g,_).getRegex(),et=d("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Z).replace(/punctSpace/g,C).replace(/punct/g,_).getRegex(),tt="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",nt=d(tt,"gu").replace(/notPunctSpace/g,Z).replace(/punctSpace/g,C).replace(/punct/g,_).getRegex(),rt=d(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,_).getRegex(),st="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",it=d(st,"gu").replace(/notPunctSpace/g,Z).replace(/punctSpace/g,C).replace(/punct/g,_).getRegex(),ot=d(/\\(punct)/,"gu").replace(/punct/g,_).getRegex(),at=d(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),lt=d(J).replace("(?:-->|$)","-->").getRegex(),ut=d("^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\s*>|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",lt).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ge=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,N=d(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",ge).getRegex(),pt=d(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",N).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ct=d(/^!?\[(label)\]\[(ref)\]/).replace("label",N).replace("ref",X).getRegex(),ht=d(/^!?\[(ref)\](?:\[\])?/).replace("ref",X).getRegex(),oe=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,dt=d(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace("brackets",ge).getRegex(),kt=d("reflink|nolink(?!\\()","g").replace("reflink",d(/^!?\[(label)\]\[(ref)\]/).replace("label",dt).replace("ref",oe).getRegex()).replace("nolink",d(/^!?\[(ref)\](?:\[\])?/).replace("ref",oe).getRegex()).getRegex(),ae=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Y={_backpedal:E,anyPunctuation:ot,autolink:at,blockSkip:je,br:ce,code:ve,del:E,delLDelim:E,delRDelim:E,emStrongLDelim:Ue,emStrongRDelimAst:Xe,emStrongRDelimUnd:et,escape:qe,link:pt,nolink:ht,punctuation:Ze,reflink:ct,reflinkSearch:kt,tag:ut,text:He,url:E},gt={...Y,emStrongLDelim:We,emStrongRDelimAst:Ye,emStrongRDelimUnd:nt,link:d(/^!?\[(label)\]\((.*?)\)/).replace("label",N).getRegex(),reflink:d(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",N).getRegex()},F={...Y,emStrongRDelimAst:Je,emStrongLDelim:Fe,delLDelim:rt,delRDelim:it,url:d(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",ae).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:d(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",ae).getRegex()},ft={...F,br:d(ce).replace("{2,}","*").getRegex(),text:d(F.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},G={normal:V,gfm:Be,pedantic:De},B={normal:Y,gfm:F,breaks:ft,pedantic:gt},mt={"&":"&","<":"<",">":">",'"':""","'":"'"},fe=l3=>mt[l3];function R(l3,e){if(e){if(m.escapeTest.test(l3))return l3.replace(m.escapeReplace,fe)}else if(m.escapeTestNoEncode.test(l3))return l3.replace(m.escapeReplaceNoEncode,fe);return l3}function ee(l3){try{l3=encodeURI(l3).replace(m.percentDecode,"%")}catch{return null}return l3}function te(l3,e){let t=l3.replace(m.findPipe,(r,o,s)=>{let u=!1,a=o;for(;--a>=0&&s[a]==="\\";)u=!u;return u?"|":" |"}),n=t.split(m.splitPipe),i=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;i<n.length;i++)n[i]=n[i].trim().replace(m.slashPipe,"|");return n}function $(l3,e,t){let n=l3.length;if(n===0)return"";let i=0;for(;i<n;){let r=l3.charAt(n-i-1);if(r===e&&!t)i++;else if(r!==e&&t)i++;else break}return l3.slice(0,n-i)}function ne(l3){let e=l3.split(`
`),t=e.length-1;for(;t>=0&&m.blankLine.test(e[t]);)t--;return e.length-t<=2?l3:e.slice(0,t+1).join(`
`)}function D(l3){return l3.toLowerCase().toUpperCase().toLowerCase()}function me(l3,e){if(l3.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<l3.length;n++)if(l3[n]==="\\")n++;else if(l3[n]===e[0])t++;else if(l3[n]===e[1]&&(t--,t<0))return n;return t>0?-2:-1}function xe(l3,e=0){let t=e,n="";for(let i of l3)if(i===" "){let r=4-t%4;n+=" ".repeat(r),t+=r}else n+=i,t++;return n}function be(l3,e,t,n,i){let r=e.href,o=e.title||null,s=l3[1].replace(i.other.outputLinkReplace,"$1"),u=l3[0].charAt(0)==="!";n.state.inLink=!0;let a=n.state.linkEmitted,p=n.state.inRawBlock;n.state.linkEmitted=!1;let c=n.inlineTokens(s),h=n.state.linkEmitted;if(n.state.linkEmitted=a,n.state.inLink=!1,!u){if(h){n.state.inRawBlock=p;return}n.state.linkEmitted=!0}return{type:u?"image":"link",raw:t,href:r,title:o,text:s,tokens:c}}function xt(l3,e,t){let n=l3.match(t.other.indentCodeCompensation);if(n===null)return e;let i=n[1];return e.split(`
`).map(r=>{let o=r.match(t.other.beginningSpace);if(o===null)return r;let[s]=o;return r.slice(Math.min(s.length,i.length))}).join(`
`)}function Re(l3,e,t,n){if(!e.includes("<"))return!1;for(let i=0;i<e.length;i++){if(e[i]==="\\"){i++;continue}if(e[i]==="`"){let s=n.inline.code.exec(e.slice(i));if(s){i+=s[0].length-1;continue}}if(e[i]!=="<")continue;let r=l3.slice(t+i),o=n.inline.tag.exec(r)||n.inline.autolink.exec(r);if(o){if(o[0].length>e.length-i)return!0;i+=o[0].length-1}}return!1}var y=class{options;rules;lexer;constructor(e){this.options=e||T}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:ne(t[0]),i=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:i}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],i=xt(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:i}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let i=$(n,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceTabChar.test(i))&&(n=i.trim())}return{type:"heading",raw:$(t[0],`
`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:$(t[0],`
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=$(t[0],`
`).split(`
`),i="",r="",o=[];for(;n.length>0;){let s=!1,u=[],a;for(a=0;a<n.length;a++)if(this.rules.other.blockquoteStart.test(n[a]))u.push(n[a]),s=!0;else if(!s)u.push(n[a]);else break;n=n.slice(a);let p=u.join(`
`),c=p.replace(this.rules.other.blockquoteSetextReplace,`
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
${p}`:p,r=r?`${r}
${c}`:c;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(c,o,!0),this.lexer.state.top=h,n.length===0)break;let k=o.at(-1);if(k?.type==="code")break;if(k?.type==="blockquote"){let O=k,g=n.join(`
`),w=O.raw+`
`+g.replace(this.rules.other.blockquoteSetextReplace2,""),z=this.blockquote(w);o[o.length-1]=z,i=`${i}
${g}`,r=r.substring(0,r.length-O.text.length)+z.text;break}else if(k?.type==="list"){let O=k,g=O.raw+`
`+n.join(`
`),w=this.list(g);o[o.length-1]=w,i=i.substring(0,i.length-k.raw.length)+w.raw,r=r.substring(0,r.length-O.raw.length)+w.raw,n=g.substring(o.at(-1).raw.length).split(`
`);continue}}return{type:"blockquote",raw:i,tokens:o,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),i=n.length>1,r={type:"list",raw:"",ordered:i,start:i?+n.slice(0,-1):"",loose:!1,items:[]};n=i?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=i?n:"[*+-]");let o=this.rules.other.listItemRegex(n),s=!1;for(;e;){let a=!1,p="",c="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=xe(t[2].split(`
`,1)[0],t[1].length),k=e.split(`
`,1)[0],O=!h.trim(),g=0;if(this.options.pedantic?(g=2,c=h.trimStart()):O?g=t[1].length+1:(g=h.search(this.rules.other.nonSpaceChar),g=g>4?1:g,c=h.slice(g),g+=t[1].length),O&&this.rules.other.blankLine.test(k)&&(p+=k+`
`,e=e.substring(k.length+1),a=!0),!a){let w=this.rules.other.nextBulletRegex(g),z=this.rules.other.hrRegex(g),re=this.rules.other.fencesBeginRegex(g),se=this.rules.other.headingBeginRegex(g),Te=this.rules.other.htmlBeginRegex(g),Oe=this.rules.other.blockquoteBeginRegex(g);for(;e;){let j=e.split(`
`,1)[0],q;if(k=j,this.options.pedantic?(k=k.replace(this.rules.other.listReplaceNesting," "),q=k):q=k.replace(this.rules.other.tabCharGlobal," "),re.test(k)||se.test(k)||Te.test(k)||Oe.test(k)||w.test(k)||z.test(k))break;if(q.search(this.rules.other.nonSpaceChar)>=g||!k.trim())c+=`
`+q.slice(g);else{if(O||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||re.test(h)||se.test(h)||z.test(h))break;c+=`
`+k}O=!k.trim(),p+=j+`
`,e=e.substring(j.length+1),h=q.slice(g)}}r.loose||(s?r.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(s=!0)),r.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(c),loose:!1,text:c,tokens:[]}),r.raw+=p}let u=r.items.at(-1);if(u)u.raw=u.raw.trimEnd(),u.text=u.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let a of r.items)if(this.lexer.state.top=!1,a.tokens=this.lexer.blockTokens(a.text,[]),!r.loose){let p=a.tokens.filter(h=>h.type==="space"),c=p.length>0&&p.some(h=>this.rules.other.anyLine.test(h.raw));r.loose=c}for(let a of r.items){let p=a.tokens[0];if(a.task&&(p?.type==="text"||p?.type==="paragraph")){a.text=a.text.replace(this.rules.other.listReplaceTask,""),p.raw=p.raw.replace(this.rules.other.listReplaceTask,""),p.text=p.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let c=this.rules.other.listTaskCheckbox.exec(a.raw);if(c){let h={type:"checkbox",raw:c[0]+" ",checked:c[0]!=="[ ]"};a.checked=h.checked,r.loose?a.tokens[0]&&["paragraph","text"].includes(a.tokens[0].type)&&"tokens"in a.tokens[0]&&a.tokens[0].tokens?(a.tokens[0].raw=h.raw+a.tokens[0].raw,a.tokens[0].text=h.raw+a.tokens[0].text,a.tokens[0].tokens.unshift(h)):a.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):a.tokens.unshift(h)}}else a.task&&(a.task=!1)}if(r.loose)for(let a of r.items){a.loose=!0;for(let p of a.tokens)p.type==="text"&&(p.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=ne(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=D(t[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:$(t[0],`
`),href:i,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=te(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
`):[],o={type:"table",raw:$(t[0],`
`),header:[],align:[],rows:[]};if(n.length===i.length){for(let s of i)this.rules.other.tableAlignRight.test(s)?o.align.push("right"):this.rules.other.tableAlignCenter.test(s)?o.align.push("center"):this.rules.other.tableAlignLeft.test(s)?o.align.push("left"):o.align.push(null);for(let s=0;s<n.length;s++)o.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:o.align[s]});for(let s of r)o.rows.push(te(s,o.header.length).map((u,a)=>({text:u,tokens:this.lexer.inline(u),header:!1,align:o.align[a]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:$(t[0],`
`),depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&Re(e,t[1],n,this.rules))return;let i=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(i)){if(!this.rules.other.endAngleBracket.test(i))return;let s=$(i.slice(0,-1),"\\");if((i.length-s.length)%2===0)return}else{let s=me(t[2],"()");if(s===-2)return;if(s>-1){let a=(t[0].indexOf("!")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,a).trim(),t[3]=""}}let r=t[2],o="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(r);s&&(r=s[1],o=s[3])}else o=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(i)?r=r.slice(1):r=r.slice(1,-1)),be(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let i=n[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&Re(e,n[1],i,this.rules))return;let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=t[D(r)];if(!o){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return be(n,o,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let i=this.rules.inline.emStrongLDelim.exec(e);if(!(!i||!i[1]&&!i[2]&&!i[3]&&!i[4]||i[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[3])||!n||this.rules.inline.punctuation.exec(n))){let o=[...i[0]].length-1,s,u,a=o,p=0,c=i[0][0],h=n===c,k=c==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(k.lastIndex=0,t=t.slice(-1*e.length+o);(i=k.exec(t))!==null;){if(s=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!s)continue;if(u=[...s].length,i[3]||i[4]){a+=u;continue}else if(i[5]||i[6]){if(o%3&&!((o+u)%3)){p+=u;continue}if(h)break}if(a-=u,a>0)continue;u=Math.min(u,u+a+p);let O=[...i[0]][0].length,g=e.slice(0,o+i.index+O+u);if(Math.min(o,u)%2){let z=g.slice(1,-1);return{type:"em",raw:g,text:z,tokens:this.lexer.inlineTokens(z)}}let w=g.slice(2,-2);return{type:"strong",raw:g,text:w,tokens:this.lexer.inlineTokens(w)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return i&&r&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let i=this.rules.inline.delLDelim.exec(e);if(i&&(!i[1]||!n||this.rules.inline.punctuation.exec(n))){let o=[...i[0]].length-1,s,u,a=o,p=this.rules.inline.delRDelim;for(p.lastIndex=0,t=t.slice(-1*e.length+o);(i=p.exec(t))!==null;){if(s=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!s||(u=[...s].length,u!==o))continue;if(i[3]||i[4]){a+=u;continue}if(a-=u,a>0)continue;u=Math.min(u,u+a);let c=[...i[0]][0].length,h=e.slice(0,o+i.index+c+u),k=h.slice(o,-o);return{type:"del",raw:h,text:k,tokens:this.lexer.inlineTokens(k)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,i;return t[2]==="@"?(n=t[1],i="mailto:"+n):(n=t[1],i=n),{type:"link",raw:t[0],text:n,href:i,autolink:!0,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,i;if(t[2]==="@")n=t[0],i="mailto:"+n;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==t[0]);n=t[0],t[1]==="www."?i="http://"+t[0]:i=t[0]}return{type:"link",raw:t[0],text:n,href:i,autolink:!0,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},x=class l{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||T,this.options.tokenizer=this.options.tokenizer||new y,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let t={other:m,block:G.normal,inline:B.normal};this.options.pedantic?(t.block=G.pedantic,t.inline=B.pedantic):this.options.gfm&&(t.block=G.gfm,this.options.breaks?t.inline=B.breaks:t.inline=B.gfm),this.tokenizer.rules=t}static get rules(){return{block:G,inline:B}}static lex(e,t){return new l(t).lex(e)}static lexInline(e,t){return new l(t).inlineTokens(e)}lex(e){e=e.replace(m.carriageReturn,`
`),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let n=this.inlineQueue[t];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(m.tabCharGlobal," ").replace(m.spaceLine,""));let i=1/0;for(;e;){if(e.length<i)i=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let r;if(this.options.extensions?.block?.some(s=>(r=s.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let s=t.at(-1);r.raw.length===1&&s!==void 0?s.raw+=`
`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
`)?"":`
`)+r.raw,s.text+=`
`+r.text,this.inlineQueue.at(-1).src=s.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
`)?"":`
`)+r.raw,s.text+=`
`+r.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let o=e;if(this.options.extensions?.startBlock){let s=1/0,u=e.slice(1),a;this.options.extensions.startBlock.forEach(p=>{a=p.call({lexer:this},u),typeof a=="number"&&a>=0&&(s=Math.min(s,a))}),s<1/0&&s>=0&&(o=e.substring(0,s+1))}if(this.state.top&&(r=this.tokenizer.paragraph(o))){let s=t.at(-1);n&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(`
`)?"":`
`)+r.raw,s.text+=`
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):t.push(r),n=o.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(`
`)?"":`
`)+r.raw,s.text+=`
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}linkInText(e){if(!e.includes("["))return!1;let t=this.tokenizer.rules.inline.link;for(let n of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(t.test(n[0])&&e.charAt(n.index-1)!=="!")return!0;for(let n of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let i=n[0],r=i.lastIndexOf("[");if(!(i.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,D(i.slice(r+1,-1))))&&!(r>1&&this.linkInText(i.slice(1,r-1))))return!0}return!1}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e;if(this.tokens.links&&e.includes("[")){let s=this.tokenizer.rules.inline.reflinkSearch,u=a=>{let p=a.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,D(a.slice(p+1,-1))))return a;if(p>1&&a.charAt(0)!=="!"){let c=a.slice(1,p-1);if(this.linkInText(c))return"["+c.replace(s,u)+"]["+"a".repeat(a.length-p-2)+"]"}return"["+"a".repeat(a.length-2)+"]"};n=n.replace(s,u)}n=n.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),n=n.replace(this.tokenizer.rules.inline.blockSkip,(s,u,a)=>{let p=a?a.length:0;return s.slice(0,p)+"["+"a".repeat(s.length-p-2)+"]"}),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let i=!1,r="",o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}i||(r=""),i=!1;let s;if(this.options.extensions?.inline?.some(a=>(s=a.call({lexer:this},e,t))?(e=e.substring(s.raw.length),t.push(s),!0):!1))continue;if(s=this.tokenizer.escape(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.tag(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.link(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(s.raw.length);let a=t.at(-1);s.type==="text"&&a?.type==="text"?(a.raw+=s.raw,a.text+=s.text):t.push(s);continue}if(s=this.tokenizer.emStrong(e,n,r)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.codespan(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.br(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.del(e,n,r)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.autolink(e)){e=e.substring(s.raw.length),t.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(e))){e=e.substring(s.raw.length),t.push(s);continue}let u=e;if(this.options.extensions?.startInline){let a=1/0,p=e.slice(1),c;this.options.extensions.startInline.forEach(h=>{c=h.call({lexer:this},p),typeof c=="number"&&c>=0&&(a=Math.min(a,c))}),a<1/0&&a>=0&&(u=e.substring(0,a+1))}if(s=this.tokenizer.inlineText(u)){e=e.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(r=s.raw.slice(-1)),i=!0;let a=t.at(-1);a?.type==="text"?(a.raw+=s.raw,a.text+=s.text):t.push(s);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}},P=class{options;parser;constructor(e){this.options=e||T}space(e){return""}code({text:e,lang:t,escaped:n}){let i=(t||"").match(m.notSpaceStart)?.[0],r=e?e.replace(m.endingNewline,"")+`
`:"";return i?'<pre><code class="language-'+R(i)+'">'+(n?r:R(r,!0))+`</code></pre>
`:"<pre><code>"+(n?r:R(r,!0))+`</code></pre>
`}blockquote({tokens:e}){return`<blockquote>
${this.parser.parse(e)}</blockquote>
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
`}hr(e){return`<hr>
`}list(e){let t=e.ordered,n=e.start,i="";for(let s=0;s<e.items.length;s++){let u=e.items[s];i+=this.listitem(u)}let r=t?"ol":"ul",o=t&&n!==1?' start="'+n+'"':"";return"<"+r+o+`>
`+i+"</"+r+`>
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
`}table(e){let t="",n="";for(let r=0;r<e.header.length;r++)n+=this.tablecell(e.header[r]);t+=this.tablerow({text:n});let i="";for(let r=0;r<e.rows.length;r++){let o=e.rows[r];n="";for(let s=0;s<o.length;s++)n+=this.tablecell(o[s]);i+=this.tablerow({text:n})}return i&&(i=`<tbody>${i}</tbody>`),`<table>
<thead>
`+t+`</thead>
`+i+`</table>
`}tablerow({text:e}){return`<tr>
${e}</tr>
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${R(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,text:n,tokens:i,autolink:r}){let o=r?R(n,!0):this.parser.parseInline(i),s=ee(e);if(s===null)return o;e=R(s,r);let u='<a href="'+e+'"';return t&&(u+=' title="'+R(t)+'"'),u+=">"+o+"</a>",u}image({href:e,title:t,text:n,tokens:i}){i&&(n=this.parser.parseInline(i,this.parser.textRenderer));let r=ee(e);if(r===null)return R(n);e=r;let o=`<img src="${R(e)}" alt="${R(n)}"`;return t&&(o+=` title="${R(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:R(e.text)}},L=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},b=class l2{options;renderer;textRenderer;constructor(e){this.options=e||T,this.options.renderer=this.options.renderer||new P,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new L}static parse(e,t){return new l2(t).parse(e)}static parseInline(e,t){return new l2(t).parseInline(e)}parse(e){this.renderer.parser=this;let t="";for(let n=0;n<e.length;n++){let i=e[n];if(this.options.extensions?.renderers?.[i.type]){let o=i,s=this.options.extensions.renderers[o.type].call({parser:this},o);if(s!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){t+=s||"";continue}}let r=i;switch(r.type){case"space":{t+=this.renderer.space(r);break}case"hr":{t+=this.renderer.hr(r);break}case"heading":{t+=this.renderer.heading(r);break}case"code":{t+=this.renderer.code(r);break}case"table":{t+=this.renderer.table(r);break}case"blockquote":{t+=this.renderer.blockquote(r);break}case"list":{t+=this.renderer.list(r);break}case"checkbox":{t+=this.renderer.checkbox(r);break}case"html":{t+=this.renderer.html(r);break}case"def":{t+=this.renderer.def(r);break}case"paragraph":{t+=this.renderer.paragraph(r);break}case"text":{t+=this.renderer.text(r);break}default:{let o='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n="";for(let i=0;i<e.length;i++){let r=e[i];if(this.options.extensions?.renderers?.[r.type]){let s=this.options.extensions.renderers[r.type].call({parser:this},r);if(s!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(r.type)){n+=s||"";continue}}let o=r;switch(o.type){case"escape":{n+=t.text(o);break}case"html":{n+=t.html(o);break}case"link":{n+=t.link(o);break}case"image":{n+=t.image(o);break}case"checkbox":{n+=t.checkbox(o);break}case"strong":{n+=t.strong(o);break}case"em":{n+=t.em(o);break}case"codespan":{n+=t.codespan(o);break}case"br":{n+=t.br(o);break}case"del":{n+=t.del(o);break}case"text":{n+=t.text(o);break}default:{let s='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}},S=class{options;block;constructor(e){this.options=e||T}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?x.lex:x.lexInline}provideParser(e=this.block){return e?b.parse:b.parseInline}},Q=class{defaults=A();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=b;Renderer=P;TextRenderer=L;Lexer=x;Tokenizer=y;Hooks=S;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let i of e)switch(n=n.concat(t.call(this,i)),i.type){case"table":{let r=i;for(let o of r.header)n=n.concat(this.walkTokens(o.tokens,t));for(let o of r.rows)for(let s of o)n=n.concat(this.walkTokens(s.tokens,t));break}case"list":{let r=i;n=n.concat(this.walkTokens(r.items,t));break}default:{let r=i;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(o=>{let s=r[o].flat(1/0);n=n.concat(this.walkTokens(s,t))}):r.tokens&&(n=n.concat(this.walkTokens(r.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let i={...n};if(i.async=this.defaults.async||i.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let o=t.renderers[r.name];o?t.renderers[r.name]=function(...s){let u=r.renderer.apply(this,s);return u===!1&&(u=o.apply(this,s)),u}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[r.level];o?o.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),i.extensions=t),n.renderer){let r=this.defaults.renderer||new P(this.defaults);for(let o in n.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let s=o,u=n.renderer[s],a=r[s];r[s]=(...p)=>{let c=u.apply(r,p);return c===!1&&(c=a.apply(r,p)),c||""}}i.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new y(this.defaults);for(let o in n.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let s=o,u=n.tokenizer[s],a=r[s];r[s]=(...p)=>{let c=u.apply(r,p);return c===!1&&(c=a.apply(r,p)),c}}i.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new S;for(let o in n.hooks){if(!(o in r))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let s=o,u=n.hooks[s],a=r[s];S.passThroughHooks.has(o)?r[s]=p=>{if(this.defaults.async&&S.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await u.call(r,p);return a.call(r,h)})();let c=u.call(r,p);return a.call(r,c)}:r[s]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await u.apply(r,p);return h===!1&&(h=await a.apply(r,p)),h})();let c=u.apply(r,p);return c===!1&&(c=a.apply(r,p)),c}}i.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,o=n.walkTokens;i.walkTokens=function(s){let u=[];return u.push(o.call(this,s)),r&&(u=u.concat(r.call(this,s))),u}}this.defaults={...this.defaults,...i}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(n,i)=>{let r={...i},o={...this.defaults,...r},s=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&r.async===!1)return s(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return s(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return s(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let u=o.hooks?await o.hooks.preprocess(n):n,p=await(o.hooks?await o.hooks.provideLexer(e):e?x.lex:x.lexInline)(u,o),c=o.hooks?await o.hooks.processAllTokens(p):p;o.walkTokens&&await Promise.all(this.walkTokens(c,o.walkTokens));let k=await(o.hooks?await o.hooks.provideParser(e):e?b.parse:b.parseInline)(c,o);return o.hooks?await o.hooks.postprocess(k):k})().catch(s);try{o.hooks&&(n=o.hooks.preprocess(n));let a=(o.hooks?o.hooks.provideLexer(e):e?x.lex:x.lexInline)(n,o);o.hooks&&(a=o.hooks.processAllTokens(a)),o.walkTokens&&this.walkTokens(a,o.walkTokens);let c=(o.hooks?o.hooks.provideParser(e):e?b.parse:b.parseInline)(a,o);return o.hooks&&(c=o.hooks.postprocess(c)),c}catch(u){return s(u)}}}onError(e,t){return n=>{if(n.message+=`
Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+R(n.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(n);throw n}}},M=new Q;function f(l3,e){return M.parse(l3,e)}f.options=f.setOptions=function(l3){return M.setOptions(l3),f.defaults=M.defaults,U(f.defaults),f};f.getDefaults=A;f.defaults=T;function bt(...l3){return M.use(...l3),f.defaults=M.defaults,U(f.defaults),f}f.use=bt;f.walkTokens=function(l3,e){return M.walkTokens(l3,e)};f.parseInline=M.parseInline;f.Parser=b;f.parser=b.parse;f.Renderer=P;f.TextRenderer=L;f.Lexer=x;f.lexer=x.lex;f.Tokenizer=y;f.Hooks=S;f.parse=f;var un=f.options,pn=f.setOptions,cn=f.walkTokens,hn=f.parseInline;var kn=b.parse,gn=x.lex;var SYMBOLS={"\\aleph":"\u2135","\\alpha":"\u03B1","\\approx":"\u2248","\\beta":"\u03B2","\\bowtie":"\u22C8","\\cdot":"\xB7","\\chi":"\u03C7","\\Delta":"\u0394","\\delta":"\u03B4","\\div":"\xF7","\\epsilon":"\u03F5","\\equiv":"\u2261","\\eta":"\u03B7","\\exists":"\u2203","\\forall":"\u2200","\\fullouterjoin":"\u27D7","\\Gamma":"\u0393","\\gamma":"\u03B3","\\ge":"\u2265","\\geq":"\u2265","\\in":"\u2208","\\infty":"\u221E","\\int":"\u222B","\\iota":"\u03B9","\\Join":"\u22C8","\\kappa":"\u03BA","\\Lambda":"\u039B","\\lambda":"\u03BB","\\le":"\u2264","\\leftarrow":"\u2190","\\leftouterjoin":"\u27D5","\\leftrightarrow":"\u2194","\\leq":"\u2264","\\ltimes":"\u22C9","\\mu":"\u03BC","\\nabla":"\u2207","\\ne":"\u2260","\\neq":"\u2260","\\ni":"\u220B","\\notin":"\u2209","\\nu":"\u03BD","\\Omega":"\u03A9","\\omega":"\u03C9","\\otimes":"\u2297","\\partial":"\u2202","\\Phi":"\u03A6","\\phi":"\u03D5","\\Pi":"\u03A0","\\pi":"\u03C0","\\pm":"\xB1","\\prod":"\u220F","\\Psi":"\u03A8","\\psi":"\u03C8","\\rho":"\u03C1","\\rightarrow":"\u2192","\\rightouterjoin":"\u27D6","\\rtimes":"\u22CA","\\Sigma":"\u03A3","\\sigma":"\u03C3","\\sim":"\u223C","\\subset":"\u2282","\\subseteq":"\u2286","\\sum":"\u2211","\\supset":"\u2283","\\supseteq":"\u2287","\\tau":"\u03C4","\\Theta":"\u0398","\\theta":"\u03B8","\\times":"\xD7","\\to":"\u2192","\\Upsilon":"\u03A5","\\upsilon":"\u03C5","\\varepsilon":"\u03B5","\\varphi":"\u03C6","\\vartheta":"\u03D1","\\xi":"\u03BE","\\zeta":"\u03B6"},SUPERSCRIPTS={0:"\u2070",1:"\xB9",2:"\xB2",3:"\xB3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",i:"\u2071",n:"\u207F"},SUBSCRIPTS={0:"\u2080",1:"\u2081",2:"\u2082",3:"\u2083",4:"\u2084",5:"\u2085",6:"\u2086",7:"\u2087",8:"\u2088",9:"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"},MAX_FORMULA_LENGTH=4096,MAX_NESTING_DEPTH=64,LEADING_COMBINING_MARK_REGEX=new RegExp("^\\p{Mark}","u"),STYLE_COMMANDS=new Set(["\\mathrm","\\mathbf","\\mathit","\\text","\\operatorname"]),FONT_SWITCH_COMMANDS=new Set(["\\bf","\\cal","\\it","\\rm","\\sf","\\sl","\\tt"]),scriptText=(text,alphabet)=>{let output="";for(let character of text){let replacement=alphabet[character];if(replacement===void 0)return;output+=replacement}return output},LatexParser=class{constructor(input){this.index=0,this.input=input}parse(){let output=this.parseSequence(0,!1);return output!==void 0&&this.index===this.input.length?output:void 0}parseSequence(depth,stopAtBrace){if(depth>MAX_NESTING_DEPTH)return;let output=[];for(;this.index<this.input.length;){let character=this.input[this.index];if(character==="}"&&stopAtBrace)return output.join("");if(character==="\\"){let command=this.parseCommand(depth);if(command===void 0)return;output.push(command);continue}if(character==="^"||character==="_"){let script=this.parseScript(character,depth);if(script===void 0)return;output.push(script);continue}if(character==="{"){let group=this.parseGroup(depth);if(group===void 0)return;output.push(group);continue}output.push(character??""),this.index+=1}return stopAtBrace?void 0:output.join("")}parseGroup(depth){if(this.input[this.index]!=="{")return;this.index+=1;let body=this.parseSequence(depth+1,!0);if(!(body===void 0||this.input[this.index]!=="}"))return this.index+=1,body}parseCommand(depth){this.index+=1;let first=this.input[this.index];if(first===void 0)return"\\";if(!/[A-Za-z]/.test(first))return this.index+=1,"_^{}[]()$%&#".includes(first)?first:first==="!"?"":",;:".includes(first)?" ":`\\${first}`;let start=this.index;for(;/[A-Za-z]/.test(this.input[this.index]??"");)this.index+=1;let command=`\\${this.input.slice(start,this.index)}`,symbol=SYMBOLS[command];if(symbol!==void 0)return symbol;if(FONT_SWITCH_COMMANDS.has(command))return this.skipSpaces(),"";if(STYLE_COMMANDS.has(command))return this.skipSpaces(),this.input[this.index]==="{"?this.parseGroup(depth):command;if(command==="\\sqrt"){this.skipSpaces();let body=this.parseGroup(depth);return body===void 0?void 0:`\u221A(${body})`}if(command==="\\frac"){this.skipSpaces();let numerator=this.parseGroup(depth);this.skipSpaces();let denominator=numerator===void 0?void 0:this.parseGroup(depth);return numerator===void 0||denominator===void 0?void 0:`(${numerator})\u2044(${denominator})`}if(command==="\\left"||command==="\\right"){this.skipSpaces();let delimiter=this.input[this.index];if(delimiter===".")return this.index+=1,"";let escapedDelimiter=delimiter==="\\"?this.input[this.index+1]:void 0;if(escapedDelimiter!==void 0&&"{}".includes(escapedDelimiter))return this.index+=2,escapedDelimiter;if(delimiter!==void 0&&"()[]{}|".includes(delimiter))return this.index+=1,delimiter}if(command==="\\quad")return" ";let fallback=command,argumentStart=this.index;for(this.skipSpaces(),this.input[this.index]!=="{"&&(this.index=argumentStart);this.input[this.index]==="{";){let group=this.parseGroup(depth);if(group===void 0)return;fallback+=`{${group}}`}return fallback}parseScript(marker,depth){this.index+=1;let alphabet=marker==="^"?SUPERSCRIPTS:SUBSCRIPTS;if(this.input[this.index]==="{"){let body2=this.parseGroup(depth);return body2===void 0?void 0:scriptText(body2,alphabet)??`${marker}{${body2}}`}if(this.input[this.index]==="\\"){let body2=this.parseCommand(depth);return body2===void 0?void 0:scriptText(body2,alphabet)??`${marker}${body2}`}let codePoint=this.input.codePointAt(this.index);if(codePoint===void 0)return marker;let body=String.fromCodePoint(codePoint);return this.index+=body.length,alphabet[body]??`${marker}${body}`}skipSpaces(){for(;this.input[this.index]===" ";)this.index+=1}},latexToUnicode=formula=>{let trimmed=formula.trim(),rendered=trimmed;if(trimmed.length<=MAX_FORMULA_LENGTH){let normalized=trimmed.replace(/\s+/g," ");rendered=new LatexParser(normalized).parse()??trimmed}return LEADING_COMBINING_MARK_REGEX.test(rendered)?`\u25CC${rendered}`:rendered};var locations=new WeakMap,tokenSources=new WeakMap,SourceLexer=class extends x{record(remaining,tokens){let frame=this.frame;if(!frame)return;let offset=frame.text.length-remaining.length,last=tokens.at(-1);if(last&&(tokens.length!==frame.count||last.raw!==frame.lastRaw)){let previous=locations.get(last);locations.set(last,{frame,start:previous?.frame===frame?previous.start:frame.offset,end:offset})}frame.offset=offset,frame.count=tokens.length,frame.lastRaw=last?.raw}blockTokens(src,tokens=[],clipped=!1){let outer=this.frame;this.frame={text:src,offset:0,count:tokens.length,lastRaw:tokens.at(-1)?.raw};try{let result=super.blockTokens(src,tokens,clipped);return this.record("",result),result}finally{this.frame=outer}}inlineTokens(src,tokens=[]){let outer=this.frame;this.frame={text:src,offset:0,count:tokens.length,lastRaw:tokens.at(-1)?.raw};try{let result=super.inlineTokens(src,tokens);return this.record("",result),result}finally{this.frame=outer}}},sourceExtensions=["block","inline"].map(level=>({name:`source_${level}`,level:level==="block"?"block":"inline",tokenizer(src,tokens=[]){this.lexer instanceof SourceLexer&&this.lexer.record(src,tokens)}}));function sliceSource(source,start,end=source.text.length){return{document:source.document,text:source.text.slice(start,end),ranges:sliceRanges(source.ranges,start,end)}}function joinSource(parts,document){return{document,text:parts.map(part=>part.text).join(""),ranges:concatRanges(parts.map(part=>part.ranges))}}function replaceSource(source,pattern,replacement){let parts=[],offset=0;for(let match of source.text.matchAll(pattern))parts.push(sliceSource(source,offset,match.index),replacement(match)),offset=match.index+match[0].length;return parts.push(sliceSource(source,offset)),joinSource(parts,source.document)}function remove(source,pattern){return replaceSource(source,pattern,match=>sliceSource(source,match.index,match.index))}function trim(source){return sliceSource(source,source.text.length-source.text.trimStart().length,source.text.trimEnd().length)}function normalizedText(token,raw){switch(token.type){case"paragraph":case"text":case"html":case"latex_literal":return sliceSource(raw,0,token.text.length);case"latex_inline":case"latex_block":{let formula=trim(raw),delimiter=token.type==="latex_block"||formula.text.startsWith("\\")?2:1;return trim(sliceSource(formula,delimiter,-delimiter))}case"heading":{if(/^ {0,3}#{1,6}(?:\s|$)/.test(raw.text)){let prefix=/^ {0,3}#{1,6}(?:\s+|$)/.exec(raw.text)?.[0].length??0;return sliceSource(raw,prefix,prefix+token.text.length)}return trim(remove(raw,/\n {0,3}(?:=+|-+)[ \t]*(?:\n|$)/g))}case"strong":case"em":case"del":{let size=token.type==="em"?1:2;return sliceSource(raw,size,raw.text.length-size)}case"escape":return sliceSource(raw,1);case"codespan":{let size=/^`+/.exec(raw.text)?.[0].length??0,text=sliceSource(raw,size,raw.text.length-size);return text=replaceSource(text,/\n/g,match=>({...sliceSource(text,match.index,match.index+1),text:" "})),/^ .* $/.test(text.text)&&/[^ ]/.test(text.text)&&(text=sliceSource(text,1,-1)),text}case"link":case"image":{let prefix=raw.text.startsWith("![")?2:raw.text.startsWith("[")||raw.text.startsWith("<")?1:0;if(token.type==="link"&&token.autolink)return sliceSource(raw,prefix,prefix+token.text.length);let text=remove(sliceSource(raw,prefix),/\\(?=[[\]])/g);return sliceSource(text,0,token.text.length)}case"code":{if(token.codeBlockStyle==="indented")return sliceSource(remove(raw,/^(?: {0,3}\t| {1,4})/gm),0,token.text.length);let fence=new RegExp(x.rules.block.gfm.fences.source,"d").exec(raw.text);if(!fence)return;let capture=fence.indices?.[3],text=capture?sliceSource(raw,capture[0],capture[1]):sliceSource(raw,0,0),indent=/^(\s+)(?:```)/.exec(raw.text)?.[1].length??0;return indent&&(text=remove(text,new RegExp(`^[^\\S\\n]{1,${indent}}`,"gm"))),sliceSource(text,0,token.text.length)}default:return}}function mapTokens(tokens,input){for(let token of tokens){let location=locations.get(token);if(!location||location.frame.text!==input.text)continue;locations.delete(token);let raw=sliceSource(input,location.start,location.end),checkbox=/^\[[ xX]\][ \t]+/.exec(raw.text);checkbox&&(token.type==="paragraph"||token.type==="text")&&!/^\[[ xX]\]/.test(token.raw)&&(raw=sliceSource(raw,checkbox[0].length));let text=normalizedText(token,raw),validText=text&&"text"in token&&text.text===token.text?text:void 0,href;if(token.type==="link"){let capture=new RegExp(x.rules.inline.gfm.link.source,"d").exec(raw.text)?.indices?.[2];capture&&(href=trim(sliceSource(raw,capture[0],capture[1])),href.text.startsWith("<")&&(href=sliceSource(href,1,-1)),href=remove(href,/\\(?=[!"#$%&'()*+,\-./:;<=>?@[\]\\^_`{|}~])/g),href.text!==token.href&&(href=void 0))}if(tokenSources.set(token,{raw,text:validText,href}),token.type==="list"){let offset=0;for(let item of token.items){let itemRaw=sliceSource(raw,offset,offset+item.raw.length);offset+=item.raw.length,tokenSources.set(item,{raw:itemRaw});let marker=/^( {0,3}(?:[*+-]|\d{1,9}[.)]))( *)([^\n]*)/.exec(itemRaw.text);if(!marker)continue;let padding=marker[2].length>4?1:marker[2].length,indent=marker[1].length+padding,contents=sliceSource(itemRaw,indent);contents=remove(contents,new RegExp(`(?<=\\n)(?: {${indent}}| {1,${indent}}(?=\\n|$))`,"g")),contents.text.endsWith(`
`)&&(contents=sliceSource(contents,0,-1)),item===token.items.at(-1)&&(contents=sliceSource(contents,0,contents.text.trimEnd().length)),mapTokens(item.tokens,contents)}}else if(token.type==="blockquote"){let quote=remove(raw,/^ {0,3}>[ \t]?/gm);mapTokens(token.tokens??[],sliceSource(quote,0,quote.text.replace(/\n+$/,"").length))}else if(token.type==="table"){let rows=[...raw.text.matchAll(/[^\n]+/g)],cells=[token.header,...token.rows];for(let row=0;row<cells.length;row++){let line=rows[row===0?0:row+1];if(!line)continue;let start=/^\s*\|/.exec(line[0])?.[0].length??0,cell=0;for(let cursor=start;cursor<=line[0].length;cursor++){if(line[0][cursor]==="\\"){cursor++;continue}if(cursor<line[0].length&&line[0][cursor]!=="|")continue;let target=cells[row][cell++];if(!target)break;let mapped=remove(trim(sliceSource(raw,line.index+start,line.index+cursor)),/\\(?=\|)/g);mapTokens(target.tokens,mapped),start=cursor+1}}}else if(validText&&"tokens"in token&&token.tokens){let childText=token.tokens[0]?.type==="checkbox"?remove(validText,/^\[[ xX]\][ \t]+/g):validText;mapTokens(token.tokens,childText)}}}function lexWithSources(text,options){let document={text,enclosures:[]},source={document,text,ranges:linearRanges(0,text.length)};source=replaceSource(source,/\t|\r\n|\r/g,match=>{let range={start:match.index,end:match.index+match[0].length},replacement=match[0]===" "?" ":`
`;return{document,text:replacement,ranges:repeatedRange(range,replacement.length)}});let tokens=new SourceLexer(options).lex(source.text);return mapTokens(tokens,source),tokens}function tokenSource(token){return tokenSources.get(token)}var STRICT_STRIKETHROUGH_REGEX=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,StrictStrikethroughTokenizer=class extends y{del(src){let match=STRICT_STRIKETHROUGH_REGEX.exec(src);if(!match)return;let text=match[2];return{type:"del",raw:match[0],text,tokens:this.lexer.inlineTokens(text)}}},MAX_LATEX_FORMULA_LENGTH=4096,WORD_CHARACTER_REGEX=/[\p{L}\p{M}\p{N}_]/u,inlineCodePrefixStates=new WeakMap;function createLatexToken(type,raw,text){return{raw,text,type}}function isLatexToken(token){return(token.type==="latex_block"||token.type==="latex_inline"||token.type==="latex_literal")&&"text"in token&&typeof token.text=="string"}function formulaRanges(token,rendered){let source=tokenSource(token);if(!source)return repeatedRange(null,rendered.length);let{raw,text}=source,end=raw.text.trimEnd().length;if(raw.text===rendered)return raw.ranges;if(raw.text.trim()===rendered)return sliceRanges(raw.ranges,raw.text.length-raw.text.trimStart().length,end);if(text?.text===rendered)return text.ranges;let first=rangeAt(raw.ranges,0),last=rangeAt(raw.ranges,end-1);return repeatedRange(first&&last?{start:first.start,end:last.end}:null,rendered.length)}function previousRawCharacter(tokens){let raw=tokens[tokens.length-1]?.raw;return raw?Array.from(raw).at(-1):void 0}function firstCharacter(value){let codePoint=value.codePointAt(0);return codePoint===void 0?void 0:String.fromCodePoint(codePoint)}function followsUnclosedCodeSpan(tokens){let state=inlineCodePrefixStates.get(tokens),previousProcessedToken=state?tokens[state.processedTokenCount-1]:void 0;(!state||previousProcessedToken?.raw!==state.lastProcessedRaw)&&(state={hasUnclosedCodeSpan:!1,processedTokenCount:0},inlineCodePrefixStates.set(tokens,state));for(let index=state.processedTokenCount;index<tokens.length;index+=1){let token=tokens[index];token?.type==="text"&&token.raw.includes("`")&&(state.hasUnclosedCodeSpan=!0)}return state.processedTokenCount=tokens.length,state.lastProcessedRaw=tokens.at(-1)?.raw,state.hasUnclosedCodeSpan}function findInlineMath(src,open,close){if(!src.startsWith(open))return;let bodyStart=open.length,scanEnd=Math.min(src.length,bodyStart+MAX_LATEX_FORMULA_LENGTH+1);for(let index=bodyStart;index<scanEnd;index+=1){if(src[index]===`
`||src[index]==="`")return;if(src.startsWith(close,index)){let text=src.slice(bodyStart,index),normalizedText2=open===close?text:text.trim();return!normalizedText2||open===close&&/^\s|\s$/.test(text)?void 0:{raw:src.slice(0,index+close.length),text:normalizedText2}}if(open!==close&&src.startsWith(open,index))return;if(src[index]==="\\"){if(src[index+1]===`
`||src[index+1]==="\r")return;index+=1}}}function findMalformedInlineSpan(src,open,close){if(!src.startsWith(open))return;let scanEnd=Math.min(src.length,open.length+MAX_LATEX_FORMULA_LENGTH+1),competingOpener=!1,closers=[close];for(let index=open.length;index<scanEnd;index+=1){if(src[index]===`
`||src[index]==="`")return competingOpener?src.slice(0,index):void 0;let nestedOpen=src.startsWith("\\(",index)?"\\(":src.startsWith("\\[",index)?"\\[":void 0;if(nestedOpen!==void 0){competingOpener=!0,closers.push(nestedOpen==="\\("?"\\)":"\\]"),index+=nestedOpen.length-1;continue}let expectedClose=closers.at(-1);if(expectedClose!==void 0&&src.startsWith(expectedClose,index)){if(closers.pop(),closers.length===0)return competingOpener?src.slice(0,index+expectedClose.length):void 0;index+=expectedClose.length-1;continue}if(src[index]==="\\"){if(src[index+1]===`
`||src[index+1]==="\r")return competingOpener?src.slice(0,index):void 0;index+=1}}return competingOpener?src.slice(0,scanEnd):void 0}function isLikelyLiteralDollarBody(text){return text.startsWith("{")||/^\([^)\r\n]*\)[/\\]$/.test(text)||/^[!#$?@*-][/\\]$/.test(text)||/^[A-Za-z_][A-Za-z0-9_]*[./\\:-]$/.test(text)||/^\d[\d,.]*(?:[-–—]|[/\\])$/.test(text)}function findBlockMath(src,open,close){if(!src.startsWith(open))return;let bodyStart=open.length,scanEnd=Math.min(src.length,bodyStart+MAX_LATEX_FORMULA_LENGTH+1),lineValidationEnd=Math.min(src.length,scanEnd+close.length+256);for(let index=bodyStart;index<scanEnd;index+=1){if(src[index]==="`"||open!==close&&src.startsWith(open,index))return;if(!src.startsWith(close,index))continue;let rawLineEnd=index+close.length;for(;rawLineEnd<lineValidationEnd&&src[rawLineEnd]!==`
`&&/[ \t]/.test(src[rawLineEnd]??"");)rawLineEnd+=1;if(rawLineEnd<src.length&&src[rawLineEnd]!==`
`)return;let text=src.slice(bodyStart,index).trim();if(!text)return;let rawEnd=rawLineEnd;for(;rawEnd<lineValidationEnd&&src[rawEnd]===`
`;)rawEnd+=1;return{raw:src.slice(0,rawEnd),text}}}function repeatedMalformedOpeners(src,opener){let end=opener.length;for(;src.startsWith(opener,end);)end+=opener.length;return end>opener.length?src.slice(0,end):void 0}var blockMathTokenizer={name:"latex_block",level:"block",tokenizer(src){let leadingSpaces=/^ {0,3}/.exec(src)?.[0]??"",candidate=src.slice(leadingSpaces.length),match=findBlockMath(candidate,"$$","$$")??findBlockMath(candidate,"\\[","\\]");if(match)return createLatexToken("latex_block",`${leadingSpaces}${match.raw}`,match.text)}},inlineMathTokenizer={name:"latex_inline",level:"inline",start(src){let index=src.search(/\$|\\[()[\]]/);return index>=0?index:void 0},tokenizer(src,tokens){let codeSpanLiteral=/^(?:\${1,2}|\\\(|\\\)|\\\[|\\\])/.exec(src)?.[0];if(codeSpanLiteral&&followsUnclosedCodeSpan(tokens))return createLatexToken("latex_literal",codeSpanLiteral,codeSpanLiteral);if(src.startsWith("$")){if(src.startsWith("$$"))return createLatexToken("latex_literal","$$","$$");let match=findInlineMath(src,"$","$");if(match&&isLikelyLiteralDollarBody(match.text))return createLatexToken("latex_literal",match.raw,match.raw);let previous2=previousRawCharacter(tokens),next=match?firstCharacter(src.slice(match.raw.length)):void 0;return match&&(previous2===void 0||!WORD_CHARACTER_REGEX.test(previous2))&&(next===void 0||!WORD_CHARACTER_REGEX.test(next))?createLatexToken("latex_inline",match.raw,match.text):createLatexToken("latex_literal","$","$")}let malformedParens=findMalformedInlineSpan(src,"\\(","\\)");if(malformedParens)return createLatexToken("latex_literal",malformedParens,malformedParens);let malformedBrackets=findMalformedInlineSpan(src,"\\[","\\]");if(malformedBrackets)return createLatexToken("latex_literal",malformedBrackets,malformedBrackets);let repeatedParens=repeatedMalformedOpeners(src,"\\(");if(repeatedParens)return createLatexToken("latex_literal",repeatedParens,repeatedParens);let repeatedBrackets=repeatedMalformedOpeners(src,"\\[");if(repeatedBrackets)return createLatexToken("latex_literal",repeatedBrackets,repeatedBrackets);let parens=findInlineMath(src,"\\(","\\)");if(parens){let previous2=previousRawCharacter(tokens),next=firstCharacter(src.slice(parens.raw.length));return(previous2===void 0||!WORD_CHARACTER_REGEX.test(previous2))&&(next===void 0||!WORD_CHARACTER_REGEX.test(next))?createLatexToken("latex_inline",parens.raw,parens.text):void 0}let brackets=findInlineMath(src,"\\[","\\]");if(brackets){let previous2=previousRawCharacter(tokens),next=firstCharacter(src.slice(brackets.raw.length));return(previous2===void 0||!WORD_CHARACTER_REGEX.test(previous2))&&(next===void 0||!WORD_CHARACTER_REGEX.test(next))?createLatexToken("latex_inline",brackets.raw,brackets.text):void 0}let literal=/^(?:\\\(|\\\)|\\\[|\\\])/.exec(src);if(!literal)return;let previous=previousRawCharacter(tokens);return previous!==void 0&&WORD_CHARACTER_REGEX.test(previous)?void 0:createLatexToken("latex_literal",literal[0],literal[0])}};function trimPartialClosingFences(tokens){let token=tokens[tokens.length-1];if(token?.type==="list"){trimPartialClosingFences(token.items[token.items.length-1]?.tokens??[]);return}if(token?.type==="blockquote"){trimPartialClosingFences(token.tokens??[]);return}if(token?.type!=="code")return;let marker=/^(`{3,}|~{3,})/.exec(token.raw)?.[1],lastLine=token.raw.split(`
`).pop();!marker||!lastLine||lastLine.length>=marker.length||lastLine!==marker[0]?.repeat(lastLine.length)||(token.text=token.text.slice(0,-lastLine.length).replace(/\n$/,""))}var markdownParser=new Q;markdownParser.use({extensions:[blockMathTokenizer,inlineMathTokenizer]});markdownParser.use({extensions:sourceExtensions});markdownParser.setOptions({tokenizer:new StrictStrikethroughTokenizer});var RENDER_CACHE_MAX=256,PARSE_CACHE_MAX=128,SOURCE_CACHE_MAX=8,CONTENT_KEY_CACHE_MAX=128,HIGHLIGHT_CACHE_MAX=512,MAX_HIGHLIGHT_BYTES=2e5,MAX_HIGHLIGHT_LINES=2e3,renderCache=new Map,parseCache=new Map,sourceRenderCache=new Map,sourceParseCache=new Map,contentKeyCache=new Map,highlightCache=new Map,objectIds=new WeakMap,enclosedTokens=new WeakSet,nextObjectId=0,markdownHighlightCallCount=0;function objectId(value){let cached=objectIds.get(value);if(cached!==void 0)return cached;let id=nextObjectId++;return objectIds.set(value,id),id}function cacheSet(cache,key,value,maxSize){if(cache.has(key)&&cache.delete(key),cache.set(key,value),cache.size>maxSize){let oldest=cache.keys().next().value;oldest!==void 0&&cache.delete(oldest)}}function contentKey(text){let cached=contentKeyCache.get(text);if(cached!==void 0)return cacheSet(contentKeyCache,text,cached,CONTENT_KEY_CACHE_MAX),cached;let hash=2166136261;for(let i=0;i<text.length;i++)hash^=text.charCodeAt(i),hash=Math.imul(hash,16777619);let key=`${text.length}:${(hash>>>0).toString(36)}`;return cacheSet(contentKeyCache,text,key,CONTENT_KEY_CACHE_MAX),key}function clearRenderCache(){renderCache.clear(),parseCache.clear(),sourceRenderCache.clear(),sourceParseCache.clear(),contentKeyCache.clear(),highlightCache.clear()}function getMarkdownHighlightCallCount(){return markdownHighlightCallCount}function resetMarkdownHighlightCallCount(){markdownHighlightCallCount=0}var Markdown=class _Markdown{constructor(text,paddingX,paddingY,theme,defaultTextStyle,options){this.collectSources=!1,this.revision=nextRenderRevision(),this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.theme=theme,this.defaultTextStyle=defaultTextStyle,this.options=options?{...options}:{}}setText(text){this.text=text,this.invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0,this.activeSourceDocument=void 0,this.markRevision()}markRevision(){this.revision=this.getRenderRevision()===void 0?this.revision+1:nextRenderRevision()}getRenderRevision(){return Object.getPrototypeOf(this)===_Markdown.prototype?this.revision:void 0}render(width){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width)return this.cachedLines;let contentWidth=Math.max(1,width-this.paddingX*2),text=this.options.transform?.(this.text,contentWidth)??this.text;if(!text||text.trim()===""){let result2=[];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result2,result2}let styleKey=this.defaultTextStyle?objectId(this.defaultTextStyle):-1,renderKey=[contentKey(this.text),contentKey(text),width,contentWidth,this.paddingX,this.paddingY,this.theme.codeBlockIndent??" ",(this.options.preserveOrderedListMarkers?1:0)|(this.options.preserveBackslashEscapes?2:0)|(this.options.renderLatex===!1?4:0),objectId(this.theme),styleKey,getCapabilities().images??"",getCapabilities().hyperlinks?1:0].join("\0"),selectedRenderCache=this.collectSources?sourceRenderCache:renderCache,cachedRender=selectedRenderCache.get(renderKey);if(cachedRender?.source===this.text&&cachedRender.transformed===text)return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=this.ownSources(cachedRender.lines),this.cachedLines;let parseKey2=contentKey(text),selectedParseCache=this.collectSources?sourceParseCache:parseCache,cachedParse=selectedParseCache.get(parseKey2),tokens;cachedParse?.source===text?tokens=cachedParse.tokens:(tokens=this.collectSources?lexWithSources(text,markdownParser.defaults):markdownParser.lexer(text.replace(/\t/g," ")),trimPartialClosingFences(tokens),cacheSet(selectedParseCache,parseKey2,{source:text,tokens},this.collectSources?SOURCE_CACHE_MAX:PARSE_CACHE_MAX)),this.activeSourceDocument=this.collectSources?tokens.map(token=>tokenSource(token)?.raw.document).find(document2=>document2)??{text,enclosures:[]}:void 0;let renderedLines=[];for(let i=0;i<tokens.length;i++){let token=tokens[i],nextToken=tokens[i+1],tokenLines=this.renderToken(token,contentWidth,nextToken?.type),offset=renderedLines.length;for(let tokenLine of tokenLines)renderedLines.push(tokenLine);copyLineSources(tokenLines,renderedLines,offset)}let wrappedLines=[];for(let row=0;row<renderedLines.length;row++){let line=renderedLines[row],mapping=getLineSources(renderedLines)?.[row],offset=wrappedLines.length;if(isImageLine(line))wrappedLines.push(line);else{let fragments=this.wrapSource(line,contentWidth,mapping);for(let wrappedLine of fragments)wrappedLines.push(wrappedLine);copyLineSources(fragments,wrappedLines,offset)}}let leftMargin=" ".repeat(this.paddingX),rightMargin=" ".repeat(this.paddingX),bgFn=this.defaultTextStyle?.bgColor,contentLines=[];for(let line of wrappedLines){if(isImageLine(line)){contentLines.push(line);continue}let lineWithMargins=leftMargin+line+rightMargin;if(bgFn)contentLines.push(applyBackgroundToLine(lineWithMargins,width,bgFn));else{let visibleLen=visibleWidth(lineWithMargins),paddingNeeded=Math.max(0,width-visibleLen);contentLines.push(lineWithMargins+" ".repeat(paddingNeeded))}}copyLineSources(wrappedLines,contentLines,0,this.paddingX);let emptyLine=" ".repeat(width),emptyLines=[];for(let i=0;i<this.paddingY;i++){let line=bgFn?applyBackgroundToLine(emptyLine,width,bgFn):emptyLine;emptyLines.push(line)}let result=emptyLines.concat(contentLines,emptyLines);copyLineSources(contentLines,result,this.paddingY);let mapped=getLineSources(result),document=mapped?.find(line=>line)?.document;if(document&&setLineSources(result,result.map((_2,row)=>mapped?.[row]??{document,ranges:emptyRanges})),text!==this.text){let transformedDocument={text:this.text,enclosures:[]};setLineSources(result,result.map(()=>({document:transformedDocument,ranges:emptyRanges,renderedFallback:!0})))}else if(!this.collectSources){let sourceText=this.text,{paddingX,paddingY,theme,defaultTextStyle}=this,options={...this.options,transform:void 0},deferred={text:sourceText,enclosures:[],resolveLines:()=>{let markdown=new _Markdown(sourceText,paddingX,paddingY,theme,defaultTextStyle,options);markdown.collectSources=!0;let sourceLines=markdown.render(width);if(!(sourceLines.length!==result.length||sourceLines.some((line,row)=>line!==result[row])))return getLineSources(sourceLines)}};setLineSources(result,result.map((_2,sourceRow)=>({document:deferred,ranges:emptyRanges,sourceRow})))}return flattenLines(result),this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=this.ownSources(result),cacheSet(selectedRenderCache,renderKey,{source:this.text,transformed:text,lines:result},this.collectSources?SOURCE_CACHE_MAX:RENDER_CACHE_MAX),this.cachedLines.length>0?this.cachedLines:[""]}ownSources(lines){let mapping=getLineSources(lines);if(!mapping)return lines;let original=mapping.find(line=>line)?.document;if(!original)return lines;let document={...original},result=[...lines];return setLineSources(result,mapping.map(line=>line&&{...line,document})),result}wrapSource(text,width,source){let mapping=[],lines=wrapTextWithAnsi(text,width,source?(start,end)=>{mapping.push({...source,ranges:sliceRanges(source.ranges,start,end)})}:void 0);return source===null?setLineSources(lines,lines.map(()=>null)):source&&setLineSources(lines,mapping),lines}enclose(token,ranges){if(!["heading","strong","em","del","codespan","code","link","image","escape","latex_inline","latex_block","table","blockquote"].includes(token.type)||enclosedTokens.has(token))return;let source=tokenSource(token)?.raw;if(!source)return;let rawEnd=token.type==="latex_block"?source.text.trimEnd().length:source.text.replace(/\n+$/,"").length,start=rangeAt(source.ranges,0)?.start,end=rangeAt(source.ranges,rawEnd-1)?.end;if(start===void 0||end===void 0)return;let contentStart=1/0,contentEnd=0;for(let{source:range}of ranges.spans)range&&(contentStart=Math.min(contentStart,range.start),contentEnd=Math.max(contentEnd,range.end));contentStart!==1/0&&(enclosedTokens.add(token),source.document.enclosures.push({start,end,content:{start:contentStart,end:contentEnd}}))}applyDefaultStyle(text){if(!this.defaultTextStyle)return text;let styled=text;return this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.bold(styled)),this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=this.theme.strikethrough(styled)),this.defaultTextStyle.underline&&(styled=this.theme.underline(styled)),styled}getDefaultStylePrefix(){if(!this.defaultTextStyle)return"";if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let sentinel="\0",styled=sentinel;this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.bold(styled)),this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=this.theme.strikethrough(styled)),this.defaultTextStyle.underline&&(styled=this.theme.underline(styled));let sentinelIndex=styled.indexOf(sentinel);return this.defaultStylePrefix=sentinelIndex>=0?styled.slice(0,sentinelIndex):"",this.defaultStylePrefix}getStylePrefix(styleFn){let styled=styleFn("\0"),sentinelIndex=styled.indexOf("\0");return sentinelIndex>=0?styled.slice(0,sentinelIndex):""}getDefaultInlineStyleContext(){return{applyText:text=>this.applyDefaultStyle(text),stylePrefix:this.getDefaultStylePrefix()}}exceedsHighlightCap(code){let newlineCount=0;for(let i=0;i<code.length;i++)if(code.charCodeAt(i)===10&&(newlineCount+=1),newlineCount+1>MAX_HIGHLIGHT_LINES)return!0;return new TextEncoder().encode(code).byteLength>MAX_HIGHLIGHT_BYTES}highlightCodeBlock(code,lang){if(!this.theme.highlightCode||this.exceedsHighlightCap(code))return null;let key=`${objectId(this.theme)}\0${lang??""}\0${code}`,cached=highlightCache.get(key);if(cached)return cacheSet(highlightCache,key,cached,HIGHLIGHT_CACHE_MAX),cached;markdownHighlightCallCount+=1;let highlighted=this.theme.highlightCode(code,lang);return cacheSet(highlightCache,key,highlighted,HIGHLIGHT_CACHE_MAX),highlighted}renderCodeBlock(lines,code,lang,indent){lines.push(this.theme.codeBlockBorder(`\`\`\`${lang||""}`));let highlightedLines=this.highlightCodeBlock(code,lang);if(highlightedLines)for(let hlLine of highlightedLines)lines.push(`${indent}${hlLine}`);else{this.theme.highlightCode&&this.exceedsHighlightCap(code)&&lines.push(`${indent}${this.theme.codeBlock("[syntax highlighting skipped: code block too large]")}`);for(let codeLine of code.split(`
`))lines.push(`${indent}${this.theme.codeBlock(codeLine)}`)}lines.push(this.theme.codeBlockBorder("```"))}renderToken(token,width,nextTokenType,styleContext){let lines=[],inlineRanges=this.collectSources?[]:void 0,source=tokenSource(token);switch(token.type){case"heading":{let headingLevel=token.depth,headingPrefix=`${"#".repeat(headingLevel)} `,headingStyleFn;headingLevel===1?headingStyleFn=text=>this.theme.heading(this.theme.bold(this.theme.underline(text))):headingStyleFn=text=>this.theme.heading(this.theme.bold(text));let headingStyleContext={applyText:headingStyleFn,stylePrefix:this.getStylePrefix(headingStyleFn)},headingText=this.renderInlineTokens(token.tokens||[],headingStyleContext,inlineRanges),styledHeading=headingLevel>=3?headingStyleFn(headingPrefix)+headingText:headingText;if(headingLevel>=3&&inlineRanges){let prefix=/^( {0,3})(#{3,6})([ \t]*)/.exec(source?.raw.text??"");if(source&&prefix){let start=prefix[1].length,end=start+prefix[2].length,separatorStart=rangeAt(source.raw.ranges,end),separatorEnd=rangeAt(source.raw.ranges,end+prefix[3].length-1);inlineRanges.unshift(concatRanges([sliceRanges(source.raw.ranges,start,end),repeatedRange(prefix[3].length&&separatorStart&&separatorEnd?{start:separatorStart.start,end:separatorEnd.end}:void 0,1)]))}else inlineRanges.unshift(repeatedRange(void 0,headingPrefix.length))}lines.push(styledHeading),nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"paragraph":{let paragraphText=this.renderInlineTokens(token.tokens||[],styleContext,inlineRanges);lines.push(paragraphText),nextTokenType&&nextTokenType!=="list"&&nextTokenType!=="space"&&lines.push("");break}case"latex_block":if(isLatexToken(token)){let formula=this.options.renderLatex===!1?token.raw.trim():latexToUnicode(token.text);lines.push(styleContext?styleContext.applyText(formula):this.applyDefaultStyle(formula)),inlineRanges&&inlineRanges.push(formulaRanges(token,stripTerminalSequences(lines[0]))),nextTokenType&&nextTokenType!=="space"&&lines.push("")}break;case"text":lines.push(this.renderInlineTokens([token],styleContext,inlineRanges));break;case"code":{let indent=this.theme.codeBlockIndent??" ";if(this.renderCodeBlock(lines,token.text,token.lang,indent),source?.text){let ranges=[],offset=0,openingLength=/^[^\n]*/.exec(source.raw.text)?.[0].length??0,openingStart=rangeAt(source.raw.ranges,0),openingEnd=rangeAt(source.raw.ranges,openingLength-1),open=token.codeBlockStyle!=="indented"&&openingStart&&openingEnd?{start:openingStart.start,end:openingEnd.end}:void 0;ranges.push({document:source.raw.document,ranges:repeatedRange(open,stripTerminalSequences(lines[0]).length)});let codeLines=token.text.split(`
`);for(let row=1;row<lines.length-1;row++){let codeLine=codeLines[row-1]??"",rendered=stripTerminalSequences(lines[row]).slice(indent.length);ranges.push({document:source.raw.document,ranges:concatRanges([repeatedRange(void 0,indent.length),rendered===codeLine?sliceRanges(source.text.ranges,offset,offset+codeLine.length):repeatedRange(null,rendered.length)])}),offset+=codeLine.length+1}let marker=/^ {0,3}(`{3,}|~{3,})/.exec(source.raw.text)?.[1],closing=marker?new RegExp(`\\n( {0,3}${marker[0]}{${marker.length},}[ \\t]*)\\n?$`).exec(source.raw.text):null,closeRanges=closing?sliceRanges(source.raw.ranges,closing.index+(closing[0].startsWith(`
`)?1:0),source.raw.text.trimEnd().length):emptyRanges,closingStart=rangeAt(closeRanges,0),closingEnd=rangeAt(closeRanges,closeRanges.length-1),close=closingStart&&closingEnd?{start:closingStart.start,end:closingEnd.end}:void 0;ranges.push({document:source.raw.document,ranges:repeatedRange(close,stripTerminalSequences(lines[lines.length-1]).length)}),setLineSources(lines,ranges),this.enclose(token,concatRanges(ranges.map(line=>line.ranges)))}nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"list":{let listLines=this.renderList(token,0,width,styleContext);lines.push(...listLines),copyLineSources(listLines,lines);break}case"table":{let tableLines=this.renderTable(token,width,nextTokenType,styleContext);lines.push(...tableLines),copyLineSources(tableLines,lines);break}case"blockquote":{let quoteStyle=text=>this.theme.quote(this.theme.italic(text)),quoteStylePrefix=this.getStylePrefix(quoteStyle),applyQuoteStyle=line=>{if(!quoteStylePrefix)return quoteStyle(line);let lineWithReappliedStyle=line.replace(/\x1b\[0m/g,`\x1B[0m${quoteStylePrefix}`);return quoteStyle(lineWithReappliedStyle)},quoteContentWidth=Math.max(1,width-2),quoteInlineStyleContext={applyText:text=>text,stylePrefix:quoteStylePrefix},quoteTokens=token.tokens||[],renderedQuoteLines=[];for(let i=0;i<quoteTokens.length;i++){let quoteToken=quoteTokens[i],nextQuoteToken=quoteTokens[i+1],childLines=this.renderToken(quoteToken,quoteContentWidth,nextQuoteToken?.type,quoteInlineStyleContext),offset=renderedQuoteLines.length;renderedQuoteLines.push(...childLines),copyLineSources(childLines,renderedQuoteLines,offset)}for(;renderedQuoteLines.length>0&&renderedQuoteLines[renderedQuoteLines.length-1]==="";)renderedQuoteLines.pop();for(let row=0;row<renderedQuoteLines.length;row++){let quoteLine=renderedQuoteLines[row],styledLine=applyQuoteStyle(quoteLine),wrappedLines=this.wrapSource(styledLine,quoteContentWidth,getLineSources(renderedQuoteLines)?.[row]),offset=lines.length;for(let wrappedLine of wrappedLines)lines.push(this.theme.quoteBorder("\u2502 ")+wrappedLine);copyLineSources(wrappedLines,lines,offset,2)}nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"hr":if(lines.push(this.theme.hr("\u2500".repeat(Math.min(width,80)))),inlineRanges&&source){let first=rangeAt(source.raw.ranges,0),last=rangeAt(source.raw.ranges,source.raw.text.trimEnd().length-1);inlineRanges.push(repeatedRange(first&&last?{start:first.start,end:last.end}:null,stripTerminalSequences(lines[0]).length))}nextTokenType&&nextTokenType!=="space"&&lines.push("");break;case"html":"raw"in token&&typeof token.raw=="string"&&lines.push(this.applyDefaultStyle(token.raw.trim()));break;case"space":lines.push("");break;default:"text"in token&&typeof token.text=="string"&&lines.push(token.text)}if(source&&!getLineSources(lines)){let ranges=inlineRanges?.length?concatRanges(inlineRanges):source.text?.text===stripTerminalSequences(lines[0]??"")?source.text.ranges:source.raw.text.trim()===stripTerminalSequences(lines[0]??"")?sliceRanges(source.raw.ranges,source.raw.text.length-source.raw.text.trimStart().length,source.raw.text.trimEnd().length):repeatedRange(null,stripTerminalSequences(lines[0]??"").length);setLineSources(lines,lines.map((_2,row)=>({document:source.raw.document,ranges:row===0?ranges:emptyRanges}))),this.enclose(token,ranges)}if(!source&&this.activeSourceDocument){let document=this.activeSourceDocument;setLineSources(lines,lines.map(()=>({document,ranges:emptyRanges,unavailable:!0})))}else token.type==="blockquote"&&this.enclose(token,concatRanges((getLineSources(lines)??[]).map(line=>line?.ranges??emptyRanges)));return lines}renderEmphasisHook(tokens,styleContext,styleFn,ranges){let innerStyleContext={applyText:text=>styleContext.applyText(styleFn(text)),stylePrefix:styleContext.stylePrefix+this.getStylePrefix(styleFn)};return styleFn(this.renderInlineTokens(tokens,innerStyleContext,ranges))+styleContext.stylePrefix}renderInlineTokens(tokens,styleContext,ranges){let result="",resolvedStyleContext=styleContext??this.getDefaultInlineStyleContext(),{applyText,stylePrefix}=resolvedStyleContext,applyTextWithNewlines=text=>text.split(`
`).map(segment=>applyText(segment)).join(`
`);for(let token of tokens){let start=result.length,childRanges=ranges?[]:void 0;switch(token.type){case"escape":result+=applyTextWithNewlines(this.options.preserveBackslashEscapes?token.raw:token.text);break;case"text":token.tokens&&token.tokens.length>0?result+=this.renderInlineTokens(token.tokens,resolvedStyleContext,childRanges):result+=applyTextWithNewlines(token.text);break;case"paragraph":result+=this.renderInlineTokens(token.tokens||[],resolvedStyleContext,childRanges);break;case"strong":{if(this.theme.strong){result+=this.renderEmphasisHook(token.tokens||[],resolvedStyleContext,this.theme.strong,childRanges);break}let boldContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext,childRanges);result+=this.theme.bold(boldContent)+stylePrefix;break}case"em":{if(this.theme.emphasis){result+=this.renderEmphasisHook(token.tokens||[],resolvedStyleContext,this.theme.emphasis,childRanges);break}let italicContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext,childRanges);result+=this.theme.italic(italicContent)+stylePrefix;break}case"codespan":result+=this.theme.code(token.text)+stylePrefix;break;case"latex_inline":isLatexToken(token)&&(result+=applyTextWithNewlines(this.options.renderLatex===!1?token.raw:latexToUnicode(token.text)));break;case"latex_literal":isLatexToken(token)&&(result+=applyTextWithNewlines(token.text));break;case"link":{let linkText=this.renderInlineTokens(token.tokens||[],resolvedStyleContext,token.autolink?void 0:childRanges),styledLink=this.theme.link(this.theme.underline(linkText));if(getCapabilities().hyperlinks)result+=hyperlink(styledLink,token.href)+stylePrefix;else{let hrefForComparison=token.href.startsWith("mailto:")?token.href.slice(7):token.href;token.text===token.href||token.text===hrefForComparison?result+=styledLink+stylePrefix:result+=styledLink+this.theme.linkUrl(` (${token.href})`)+stylePrefix}break}case"br":result+=`
`;break;case"del":{if(this.theme.deleted){result+=this.renderEmphasisHook(token.tokens||[],resolvedStyleContext,this.theme.deleted,childRanges);break}let delContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext,childRanges);result+=this.theme.strikethrough(delContent)+stylePrefix;break}case"html":"raw"in token&&typeof token.raw=="string"&&(result+=applyTextWithNewlines(token.raw));break;default:"text"in token&&typeof token.text=="string"&&(result+=applyTextWithNewlines(token.text))}if(!ranges)continue;let rendered=stripTerminalSequences(result.slice(start)),source=tokenSource(token),mapped=childRanges?.length?concatRanges(childRanges):source?.text?.text===rendered?source.text.ranges:source?.raw.text===rendered?source.raw.ranges:repeatedRange(null,rendered.length);if(token.type==="latex_inline"&&isLatexToken(token))mapped=formulaRanges(token,rendered);else if(token.type==="link"&&token.autolink&&source?.text&&rendered.startsWith(source.text.text))mapped=concatRanges([source.text.ranges,repeatedRange(void 0,rendered.length-source.text.ranges.length)]);else if(token.type==="link"&&mapped.length<rendered.length&&source?.href)mapped=concatRanges([mapped,repeatedRange(void 0,2),source.href.ranges,repeatedRange(void 0,1)]);else if(token.type==="link"&&mapped.length<rendered.length&&source){let first=rangeAt(source.raw.ranges,0),last=rangeAt(source.raw.ranges,source.raw.ranges.length-1);mapped=concatRanges([mapped,repeatedRange(first&&last?{start:first.start,end:last.end}:null,rendered.length-mapped.length)])}mapped.length<rendered.length&&(mapped=concatRanges([mapped,repeatedRange(null,rendered.length-mapped.length)])),ranges.push(mapped),this.enclose(token,token.type==="link"?source?.text?.ranges??mapped:mapped)}for(;stylePrefix&&result.endsWith(stylePrefix);)result=result.slice(0,-stylePrefix.length);return result}getOrderedListMarker(item){let match=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(item.raw);return match?`${match[1]} `:void 0}getUnorderedListMarker(item){let match=/^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(item.raw);return match?`${match[1]} `:void 0}renderList(token,depth,width,styleContext){let lines=[],indent=" ".repeat(depth),startNumber=typeof token.start=="number"?token.start:1;for(let i=0;i<token.items.length;i++){let item=token.items[i],isLastItem=i===token.items.length-1,bullet=token.ordered?this.options.preserveOrderedListMarkers?this.getOrderedListMarker(item)??`${startNumber+i}. `:`${startNumber+i}. `:this.options.preserveOrderedListMarkers?this.getUnorderedListMarker(item)??"- ":"- ",taskMarker=item.task?`[${item.checked?"x":" "}] `:"",marker=bullet+taskMarker,firstPrefix=indent+this.theme.listBullet(marker),continuationPrefix=indent+" ".repeat(visibleWidth(marker)),itemWidth=Math.max(1,width-visibleWidth(firstPrefix)),renderedAnyLine=!1;for(let itemToken of item.tokens){if(itemToken.type==="list"){let childLines=this.renderList(itemToken,depth+1,width,styleContext),offset=lines.length;lines.push(...childLines),copyLineSources(childLines,lines,offset),renderedAnyLine=!0;continue}let itemLines=this.renderToken(itemToken,itemWidth,void 0,styleContext);for(let row=0;row<itemLines.length;row++){let line=itemLines[row],fragments=this.wrapSource(line,itemWidth,getLineSources(itemLines)?.[row]);for(let part=0;part<fragments.length;part++){let wrappedLine=fragments[part],linePrefix=renderedAnyLine?continuationPrefix:firstPrefix;lines.push(linePrefix+wrappedLine);let source=getLineSources(fragments)?.[part];if(source){let markerRange;if(!renderedAnyLine){let raw=tokenSource(item)?.raw,prefix=/^(?: {0,3})(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)(?:\[[ xX]\][ \t]+)?/.exec(raw?.text??"");if(raw&&prefix?.[0].length){let start=rangeAt(raw.ranges,0)?.start,end=rangeAt(raw.ranges,prefix[0].length-1)?.end;start!==void 0&&end!==void 0&&(markerRange={start,end})}}setLineSource(lines,lines.length-1,{...source,ranges:concatRanges([repeatedRange(void 0,indent.length),repeatedRange(markerRange,visibleWidth(linePrefix)-indent.length),source.ranges])})}renderedAnyLine=!0}}}if(!renderedAnyLine){lines.push(firstPrefix);let raw=tokenSource(item)?.raw,start=raw&&rangeAt(raw.ranges,0)?.start,end=raw&&rangeAt(raw.ranges,raw.ranges.length-1)?.end;raw&&start!==void 0&&end!==void 0&&setLineSource(lines,lines.length-1,{document:raw.document,ranges:repeatedRange({start,end},visibleWidth(firstPrefix))})}token.loose&&!isLastItem&&lines.push("")}let document=tokenSource(token)?.raw.document;if(document){let mapping=getLineSources(lines);setLineSources(lines,lines.map((_2,row)=>mapping?.[row]??{document,ranges:emptyRanges}))}return lines}getLongestWordWidth(text,maxWidth){let words=text.split(/\s+/).filter(word=>word.length>0),longest=0;for(let word of words)longest=Math.max(longest,visibleWidth(word));return maxWidth===void 0?longest:Math.min(longest,maxWidth)}wrapCellText(text,maxWidth,stylePrefix="",source){let lines=this.wrapSource(text,Math.max(1,maxWidth),source);return copyLineSources(lines,lines.map((line,index)=>{let styleReset=index<lines.length-1?"\x1B[22;23;24;25;27;28;29;39m":"";return`${line}${styleReset}${stylePrefix}`}))}renderTable(token,availableWidth,nextTokenType,styleContext){let lines=[],source=tokenSource(token)?.raw,numCols=token.header.length;if(numCols===0)return lines;let borderOverhead=3*numCols+1,availableForCells=availableWidth-borderOverhead;if(availableForCells<numCols){let fallbackLines=token.raw?this.wrapSource(token.raw,availableWidth,source&&{document:source.document,ranges:sliceRanges(source.ranges,0,token.raw.length)}):[];return nextTokenType&&nextTokenType!=="space"&&fallbackLines.push(""),fallbackLines}let maxUnbrokenWordWidth=30,naturalWidths=[],minWordWidths=[];for(let i=0;i<numCols;i++){let headerText=this.renderInlineTokens(token.header[i].tokens||[],styleContext);naturalWidths[i]=visibleWidth(headerText),minWordWidths[i]=Math.max(1,this.getLongestWordWidth(headerText,maxUnbrokenWordWidth))}for(let row of token.rows)for(let i=0;i<row.length;i++){let cellText=this.renderInlineTokens(row[i].tokens||[],styleContext);naturalWidths[i]=Math.max(naturalWidths[i]||0,visibleWidth(cellText)),minWordWidths[i]=Math.max(minWordWidths[i]||1,this.getLongestWordWidth(cellText,maxUnbrokenWordWidth))}let minColumnWidths=minWordWidths,minCellsWidth=minColumnWidths.reduce((a,b2)=>a+b2,0);if(minCellsWidth>availableForCells){minColumnWidths=new Array(numCols).fill(1);let remaining=availableForCells-numCols;if(remaining>0){let totalWeight=minWordWidths.reduce((total,width)=>total+Math.max(0,width-1),0),growth=minWordWidths.map(width=>{let weight=Math.max(0,width-1);return totalWeight>0?Math.floor(weight/totalWeight*remaining):0});for(let i=0;i<numCols;i++)minColumnWidths[i]+=growth[i]??0;let allocated=growth.reduce((total,width)=>total+width,0),leftover=remaining-allocated;for(let i=0;leftover>0&&i<numCols;i++)minColumnWidths[i]++,leftover--}minCellsWidth=minColumnWidths.reduce((a,b2)=>a+b2,0)}let totalNaturalWidth=naturalWidths.reduce((a,b2)=>a+b2,0)+borderOverhead,columnWidths;if(totalNaturalWidth<=availableWidth)columnWidths=naturalWidths.map((width,index)=>Math.max(width,minColumnWidths[index]));else{let totalGrowPotential=naturalWidths.reduce((total,width,index)=>total+Math.max(0,width-minColumnWidths[index]),0),extraWidth=Math.max(0,availableForCells-minCellsWidth);columnWidths=minColumnWidths.map((minWidth,index)=>{let naturalWidth=naturalWidths[index],minWidthDelta=Math.max(0,naturalWidth-minWidth),grow=0;return totalGrowPotential>0&&(grow=Math.floor(minWidthDelta/totalGrowPotential*extraWidth)),minWidth+grow});let allocated=columnWidths.reduce((a,b2)=>a+b2,0),remaining=availableForCells-allocated;for(;remaining>0;){let grew=!1;for(let i=0;i<numCols&&remaining>0;i++)columnWidths[i]<naturalWidths[i]&&(columnWidths[i]++,remaining--,grew=!0);if(!grew)break}}let topBorderCells=columnWidths.map(w=>"\u2500".repeat(w));lines.push(`\u250C\u2500${topBorderCells.join("\u2500\u252C\u2500")}\u2500\u2510`);let headerCellLines=token.header.map((cell,i)=>{let ranges=this.collectSources?[]:void 0,text=this.renderInlineTokens(cell.tokens||[],styleContext,ranges);return this.wrapCellText(text,columnWidths[i],styleContext?.stylePrefix,source&&{document:source.document,ranges:concatRanges(ranges??[])})}),headerLineCount=Math.max(...headerCellLines.map(c=>c.length));for(let lineIdx=0;lineIdx<headerLineCount;lineIdx++){let rowParts=headerCellLines.map((cellLines,colIdx)=>{let text=cellLines[lineIdx]||"",padded=text+" ".repeat(Math.max(0,columnWidths[colIdx]-visibleWidth(text)));return this.theme.bold(padded)});lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`),source&&this.mapTableRow(lines,headerCellLines,lineIdx,columnWidths,source.document)}let separatorLine=`\u251C\u2500${columnWidths.map(w=>"\u2500".repeat(w)).join("\u2500\u253C\u2500")}\u2500\u2524`;lines.push(separatorLine);for(let rowIndex=0;rowIndex<token.rows.length;rowIndex++){let rowCellLines=token.rows[rowIndex].map((cell,i)=>{let ranges=this.collectSources?[]:void 0,text=this.renderInlineTokens(cell.tokens||[],styleContext,ranges);return this.wrapCellText(text,columnWidths[i],styleContext?.stylePrefix,source&&{document:source.document,ranges:concatRanges(ranges??[])})}),rowLineCount=Math.max(...rowCellLines.map(c=>c.length));for(let lineIdx=0;lineIdx<rowLineCount;lineIdx++){let rowParts=rowCellLines.map((cellLines,colIdx)=>{let text=cellLines[lineIdx]||"";return text+" ".repeat(Math.max(0,columnWidths[colIdx]-visibleWidth(text)))});lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`),source&&this.mapTableRow(lines,rowCellLines,lineIdx,columnWidths,source.document)}rowIndex<token.rows.length-1&&lines.push(separatorLine)}let bottomBorderCells=columnWidths.map(w=>"\u2500".repeat(w));if(lines.push(`\u2514\u2500${bottomBorderCells.join("\u2500\u2534\u2500")}\u2500\u2518`),nextTokenType&&nextTokenType!=="space"&&lines.push(""),source){let mapping=getLineSources(lines);setLineSources(lines,lines.map((_2,row)=>mapping?.[row]??{document:source.document,ranges:emptyRanges})),this.enclose(token,concatRanges((getLineSources(lines)??[]).map(line=>line?.ranges??emptyRanges)))}return lines}mapTableRow(lines,cells,row,widths,document){let ranges=[repeatedRange(void 0,2)];for(let col=0;col<cells.length;col++){let text=cells[col][row]??"",cell=getLineSources(cells[col])?.[row];ranges.push(cell?.ranges??emptyRanges),ranges.push(repeatedRange(void 0,Math.max(0,widths[col]-visibleWidth(text))+3))}setLineSource(lines,lines.length-1,{document,ranges:concatRanges(ranges)})}};var Spacer=class _Spacer{constructor(lines=1){this.revision=nextRenderRevision(),this.lines=lines}setLines(lines){this.lines=lines,this.markRevision()}invalidate(){this.markRevision()}markRevision(){this.revision=this.getRenderRevision()===void 0?this.revision+1:nextRenderRevision()}getRenderRevision(){return Object.getPrototypeOf(this)===_Spacer.prototype?this.revision:void 0}render(_width){let result=[];for(let i=0;i<this.lines;i++)result.push(""),setLineSource(result,i,null);return result}};var TruncatedText=class{constructor(text,paddingX=0,paddingY=0){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY}invalidate(){}render(width){let result=[],emptyLine=" ".repeat(width);for(let i=0;i<this.paddingY;i++)result.push(emptyLine);let availableWidth=Math.max(1,width-this.paddingX*2),singleLineText=this.text,newlineIndex=this.text.indexOf(`
`);newlineIndex!==-1&&(singleLineText=this.text.substring(0,newlineIndex));let displayText=truncateToWidth(singleLineText,availableWidth),leftPadding=" ".repeat(this.paddingX),rightPadding=" ".repeat(this.paddingX),lineWithPadding=leftPadding+displayText+rightPadding,lineVisibleWidth=visibleWidth(lineWithPadding),paddingNeeded=Math.max(0,width-lineVisibleWidth),finalLine=lineWithPadding+" ".repeat(paddingNeeded);result.push(finalLine);for(let i=0;i<this.paddingY;i++)result.push(emptyLine);return result}};var APP_PATTERN=/^[A-Za-z0-9_.+-]{1,32}$/,CONTROL_PATTERN=/[\u0000-\u001f\u007f-\u009f]+/g,INVISIBLE_FORMATTING_PATTERN=/[\u00ad\u061c\u180e\u200b\u200e\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/g;function sanitizeMessage(message){return message.replace(INVISIBLE_FORMATTING_PATTERN,"").replace(CONTROL_PATTERN," ").replace(/\s+/g," ").trim()}function truncateUtf8(text,maxBytes){if(Buffer.byteLength(text,"utf8")<=maxBytes)return text;let bytes=0,result="";for(let char of text){if(bytes+=Buffer.byteLength(char,"utf8"),bytes>maxBytes)break;result+=char}return result}function encodeProgramStatus(status,app){if(status===void 0)return"\x1B]7501;state=clear\x1B\\";let pairs=[`state=${status.state}`];status.state==="blocked"&&status.kind!==void 0&&pairs.push(`kind=${status.kind}`),app!==void 0&&APP_PATTERN.test(app)&&pairs.push(`app=${app}`);let message=status.message===void 0?"":truncateUtf8(sanitizeMessage(status.message),2048);return message.length>0&&pairs.push(`msg=${Buffer.from(message,"utf8").toString("base64")}`),`\x1B]7501;${pairs.join(":")}\x1B\\`}var KillRing=class{constructor(){this.ring=[]}push(text,opts){if(text)if(opts.accumulate&&this.ring.length>0){let last=this.ring.pop();this.ring.push(opts.prepend?text+last:last+text)}else this.ring.push(text)}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let last=this.ring.pop();this.ring.unshift(last)}}get length(){return this.ring.length}};var UndoStack=class{constructor(){this.stack=[]}push(state){this.stack.push(structuredClone(state))}pop(){return this.stack.pop()}clear(){this.stack.length=0}get length(){return this.stack.length}};var wordSegmenter2=getWordSegmenter();function findWordBackward(text,cursor,options){if(cursor<=0)return 0;let textBeforeCursor=text.slice(0,cursor),segmentFn=options?.segment,isAtomic=options?.isAtomicSegment,segments=segmentFn?[...segmentFn(textBeforeCursor)]:[...wordSegmenter2.segment(textBeforeCursor)],newCursor=cursor;for(;segments.length>0&&!isAtomic?.(segments[segments.length-1]?.segment||"")&&isWhitespaceChar(segments[segments.length-1]?.segment||"");)newCursor-=segments.pop()?.segment.length||0;if(segments.length===0)return newCursor;let last=segments[segments.length-1];if(isAtomic?.(last.segment))newCursor-=last.segment.length;else if(last.isWordLike){let segment=last.segment,matches=[...segment.matchAll(new RegExp(PUNCTUATION_REGEX,"g"))];if(matches.length<=0)newCursor-=segment.length;else{let lastMatch=matches[matches.length-1];newCursor-=segment.length-(lastMatch.index+lastMatch[0].length)}}else for(;segments.length>0&&!isAtomic?.(segments[segments.length-1]?.segment||"")&&!segments[segments.length-1]?.isWordLike&&!isWhitespaceChar(segments[segments.length-1]?.segment||"");)newCursor-=segments.pop()?.segment.length||0;return newCursor}function findWordForward(text,cursor,options){if(cursor>=text.length)return text.length;let textAfterCursor=text.slice(cursor),segmentFn=options?.segment,isAtomic=options?.isAtomicSegment,iterator=(segmentFn?segmentFn(textAfterCursor):wordSegmenter2.segment(textAfterCursor))[Symbol.iterator](),next=iterator.next(),newCursor=cursor;for(;!next.done&&!isAtomic?.(next.value.segment)&&isWhitespaceChar(next.value.segment);)newCursor+=next.value.segment.length,next=iterator.next();if(next.done)return newCursor;if(isAtomic?.(next.value.segment))newCursor+=next.value.segment.length;else if(next.value.isWordLike)newCursor+=PUNCTUATION_REGEX.exec(next.value.segment)?.index??next.value.segment.length;else for(;!next.done&&!isAtomic?.(next.value.segment)&&!next.value.isWordLike&&!isWhitespaceChar(next.value.segment);)newCursor+=next.value.segment.length,next=iterator.next();return newCursor}var segmenter=getGraphemeSegmenter(),Input=class{constructor(options={}){this.value="",this.cursor=0,this.renderedStartColumn=0,this.focused=!1,this.pasteBuffer="",this.isInPaste=!1,this.killRing=new KillRing,this.lastAction=null,this.undoStack=new UndoStack,this.secret=options.secret===!0,this.onInvalidInput=options.onInvalidInput,this.prompt=options.prompt??"> ",this.placeholder=options.placeholder??"",this.placeholderStyle=options.placeholderStyle??(text=>text)}getValue(){return this.value}setValue(value){if(this.secret&&/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(value)){this.onInvalidInput?.();return}this.value=value,this.cursor=Math.min(this.cursor,value.length)}handleInput(data){if(data.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",data=data.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=data;let endIndex=this.pasteBuffer.indexOf("\x1B[201~");if(endIndex!==-1){let pasteContent=this.pasteBuffer.substring(0,endIndex);this.handlePaste(pasteContent),this.isInPaste=!1;let remaining=this.pasteBuffer.substring(endIndex+6);this.pasteBuffer="",remaining&&this.handleInput(remaining)}return}let kb=getKeybindings();if(kb.matches(data,"tui.select.cancel")){this.onEscape&&this.onEscape();return}if(kb.matches(data,"tui.editor.undo")){this.undo();return}if(kb.matches(data,"tui.input.submit")||data===`
`){this.onSubmit&&this.onSubmit(this.value);return}if(kb.matches(data,"tui.editor.deleteCharBackward")){this.handleBackspace();return}if(kb.matches(data,"tui.editor.deleteCharForward")){this.handleForwardDelete();return}if(kb.matches(data,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(kb.matches(data,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(kb.matches(data,"tui.editor.deleteToLineStart")){this.deleteToLineStart();return}if(kb.matches(data,"tui.editor.deleteToLineEnd")){this.deleteToLineEnd();return}if(kb.matches(data,"tui.editor.yank")){this.yank();return}if(kb.matches(data,"tui.editor.yankPop")){this.yankPop();return}if(kb.matches(data,"tui.editor.cursorLeft")){if(this.lastAction=null,this.cursor>0){let beforeCursor=this.value.slice(0,this.cursor),graphemes=[...segmenter.segment(beforeCursor)],lastGrapheme=graphemes[graphemes.length-1];this.cursor-=lastGrapheme?lastGrapheme.segment.length:1}return}if(kb.matches(data,"tui.editor.cursorRight")){if(this.lastAction=null,this.cursor<this.value.length){let afterCursor=this.value.slice(this.cursor),firstGrapheme=[...segmenter.segment(afterCursor)][0];this.cursor+=firstGrapheme?firstGrapheme.segment.length:1}return}if(kb.matches(data,"tui.editor.cursorLineStart")){this.lastAction=null,this.cursor=0;return}if(kb.matches(data,"tui.editor.cursorLineEnd")){this.lastAction=null,this.cursor=this.value.length;return}if(kb.matches(data,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(kb.matches(data,"tui.editor.cursorWordRight")){this.moveWordForwards();return}let kittyPrintable=decodeKittyPrintable(data);if(kittyPrintable!==void 0){this.insertCharacter(kittyPrintable);return}[...data].some(ch=>{let code=ch.charCodeAt(0);return code<32||code===127||code>=128&&code<=159})?this.secret&&!data.startsWith("\x1B")&&this.onInvalidInput?.():this.insertCharacter(data)}handleMouse(event){if(event.type!=="press"||event.button!=="left"||event.y!==0)return;let visibleColumn=Math.max(0,event.x-2),targetColumn=this.renderedStartColumn+visibleColumn,currentColumn=0;this.cursor=this.value.length;for(let grapheme of segmenter.segment(this.value)){let nextColumn=currentColumn+(this.secret?1:visibleWidth(grapheme.segment));if(targetColumn<nextColumn){this.cursor=grapheme.index;break}currentColumn=nextColumn}return this.lastAction=null,{handled:!0,focus:!0}}insertCharacter(char){if(this.secret&&/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(char)){this.onInvalidInput?.();return}(isWhitespaceChar(char)||this.lastAction!=="type-word")&&this.pushUndo(),this.lastAction="type-word",this.value=this.value.slice(0,this.cursor)+char+this.value.slice(this.cursor),this.cursor+=char.length}handleBackspace(){if(this.lastAction=null,this.cursor>0){this.pushUndo();let beforeCursor=this.value.slice(0,this.cursor),graphemes=[...segmenter.segment(beforeCursor)],lastGrapheme=graphemes[graphemes.length-1],graphemeLength=lastGrapheme?lastGrapheme.segment.length:1;this.value=this.value.slice(0,this.cursor-graphemeLength)+this.value.slice(this.cursor),this.cursor-=graphemeLength}}handleForwardDelete(){if(this.lastAction=null,this.cursor<this.value.length){this.pushUndo();let afterCursor=this.value.slice(this.cursor),firstGrapheme=[...segmenter.segment(afterCursor)][0],graphemeLength=firstGrapheme?firstGrapheme.segment.length:1;this.value=this.value.slice(0,this.cursor)+this.value.slice(this.cursor+graphemeLength)}}deleteToLineStart(){if(this.cursor===0)return;this.pushUndo();let deletedText=this.value.slice(0,this.cursor);this.killRing.push(deletedText,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(this.cursor),this.cursor=0}deleteToLineEnd(){if(this.cursor>=this.value.length)return;this.pushUndo();let deletedText=this.value.slice(this.cursor);this.killRing.push(deletedText,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)}deleteWordBackwards(){if(this.cursor===0)return;let wasKill=this.lastAction==="kill";this.pushUndo();let oldCursor=this.cursor;this.moveWordBackwards();let deleteFrom=this.cursor;this.cursor=oldCursor;let deletedText=this.value.slice(deleteFrom,this.cursor);this.killRing.push(deletedText,{prepend:!0,accumulate:wasKill}),this.lastAction="kill",this.value=this.value.slice(0,deleteFrom)+this.value.slice(this.cursor),this.cursor=deleteFrom}deleteWordForward(){if(this.cursor>=this.value.length)return;let wasKill=this.lastAction==="kill";this.pushUndo();let oldCursor=this.cursor;this.moveWordForwards();let deleteTo=this.cursor;this.cursor=oldCursor;let deletedText=this.value.slice(this.cursor,deleteTo);this.killRing.push(deletedText,{prepend:!1,accumulate:wasKill}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)+this.value.slice(deleteTo)}yank(){let text=this.killRing.peek();text&&(this.pushUndo(),this.value=this.value.slice(0,this.cursor)+text+this.value.slice(this.cursor),this.cursor+=text.length,this.lastAction="yank")}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndo();let prevText=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor-prevText.length)+this.value.slice(this.cursor),this.cursor-=prevText.length,this.killRing.rotate();let text=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor)+text+this.value.slice(this.cursor),this.cursor+=text.length,this.lastAction="yank"}pushUndo(){this.undoStack.push({value:this.value,cursor:this.cursor})}undo(){let snapshot=this.undoStack.pop();snapshot&&(this.value=snapshot.value,this.cursor=snapshot.cursor,this.lastAction=null)}moveWordBackwards(){this.cursor!==0&&(this.lastAction=null,this.cursor=findWordBackward(this.value,this.cursor))}moveWordForwards(){this.cursor>=this.value.length||(this.lastAction=null,this.cursor=findWordForward(this.value,this.cursor))}handlePaste(pastedText){if(this.secret){this.insertCharacter(pastedText);return}this.lastAction=null,this.pushUndo();let cleanText=pastedText.replace(/\r\n/g,"").replace(/\r/g,"").replace(/\n/g,"").replace(/\t/g," ");this.value=this.value.slice(0,this.cursor)+cleanText+this.value.slice(this.cursor),this.cursor+=cleanText.length}invalidate(){}dispose(){this.secret&&(this.value="",this.cursor=0,this.pasteBuffer="",this.isInPaste=!1,this.killRing=new KillRing,this.undoStack.clear(),this.lastAction=null,this.onSubmit=void 0,this.onEscape=void 0)}render(width){let availableWidth=width-visibleWidth(this.prompt);if(availableWidth<=0)return[truncateToWidth(this.prompt,width,"")];if(this.secret){let length=[...segmenter.segment(this.value)].length,cursor=[...segmenter.segment(this.value.slice(0,this.cursor))].length,start=Math.max(0,cursor-availableWidth+1);this.renderedStartColumn=start;let shown="*".repeat(Math.min(length-start,availableWidth)),offset=cursor-start,marker2=this.focused?CURSOR_MARKER:"",rendered=shown.slice(0,offset)+marker2+"\x1B[7m"+(shown[offset]??" ")+"\x1B[27m"+shown.slice(offset+1);return[this.prompt+rendered+" ".repeat(Math.max(0,availableWidth-visibleWidth(rendered)))]}if(this.value.length===0&&this.placeholder){let placeholder=truncateToWidth(this.placeholder,availableWidth,""),atCursor2=[...segmenter.segment(placeholder)][0]?.segment??" ",afterCursor2=placeholder.slice(atCursor2.length),marker2=this.focused?CURSOR_MARKER:"",cursorChar2=`\x1B[7m${this.placeholderStyle(atCursor2)}\x1B[27m`,textWithCursor2=marker2+cursorChar2+this.placeholderStyle(afterCursor2),padding2=" ".repeat(Math.max(0,availableWidth-visibleWidth(textWithCursor2)));return[this.prompt+textWithCursor2+padding2]}let visibleText="",cursorDisplay=this.cursor;this.renderedStartColumn=0;let totalWidth=visibleWidth(this.value);if(totalWidth<availableWidth)visibleText=this.value;else{let scrollWidth=this.cursor===this.value.length?availableWidth-1:availableWidth,cursorCol=visibleWidth(this.value.slice(0,this.cursor));if(scrollWidth>0){let halfWidth=Math.floor(scrollWidth/2),startCol=0;cursorCol<halfWidth?startCol=0:cursorCol>totalWidth-halfWidth?startCol=Math.max(0,totalWidth-scrollWidth):startCol=Math.max(0,cursorCol-halfWidth),this.renderedStartColumn=startCol,visibleText=sliceByColumn(this.value,startCol,scrollWidth,!0),cursorDisplay=sliceByColumn(this.value,startCol,Math.max(0,cursorCol-startCol),!0).length}else visibleText="",cursorDisplay=0}let cursorGrapheme=[...segmenter.segment(visibleText.slice(cursorDisplay))][0],beforeCursor=visibleText.slice(0,cursorDisplay),atCursor=cursorGrapheme?.segment??" ",afterCursor=visibleText.slice(cursorDisplay+atCursor.length),marker=this.focused?CURSOR_MARKER:"",cursorChar=`\x1B[7m${atCursor}\x1B[27m`,textWithCursor=beforeCursor+marker+cursorChar+afterCursor,visualLength=visibleWidth(textWithCursor),padding=" ".repeat(Math.max(0,availableWidth-visualLength));return[this.prompt+textWithCursor+padding]}};var segmenter2=getGraphemeSegmenter(),PRINTABLE_ASCII=/^[\x20-\x7e]*$/;function buildSearchCorpus(lines){let chunks=[],spans=[],textLength=0,pendingSeparator=!1,appendSeparator=()=>{pendingSeparator&&(chunks.push(" "),textLength+=1,pendingSeparator=!1)};for(let row=0;row<lines.length;row++){let line=stripTerminalSequences(lines[row]??""),column=0;if(PRINTABLE_ASCII.test(line)){let index=0;for(;index<line.length;){if(line.charCodeAt(index)===32){textLength>0&&(pendingSeparator=!0),column+=1,index+=1;continue}let end=index+1;for(;end<line.length&&line.charCodeAt(end)!==32;)end+=1;appendSeparator();let text=line.slice(index,end);chunks.push(text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,endCol:column+text.length,linearColumns:!0}),textLength+=text.length,column+=text.length,index=end}}else for(let grapheme of segmenter2.segment(line)){let text=grapheme.segment,width=visibleWidth(text);if(/^\s+$/u.test(text)){textLength>0&&(pendingSeparator=!0),column+=width;continue}appendSeparator(),chunks.push(text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,endCol:column+width,linearColumns:!1}),textLength+=text.length,column+=width}textLength>0&&(pendingSeparator=!0)}return{text:chunks.join(""),spans}}function normalizeQuery(query){return query.replace(/\s+/gu," ").trim()}function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function findSearchCorpusMatches(corpus,normalizedQuery){if(!normalizedQuery)return[];let expression=new RegExp(escapeRegExp(normalizedQuery),"giu"),matches=[],spanIndex=0;for(let match of corpus.text.matchAll(expression)){let start=match.index,end=start+match[0].length;for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=start;)spanIndex+=1;let segments=[];for(let index=spanIndex;index<corpus.spans.length;index++){let span=corpus.spans[index];if(span.textStart>=end)break;if(span.textEnd<=start)continue;let startCol=span.linearColumns?span.startCol+Math.max(start,span.textStart)-span.textStart:span.startCol,endCol=span.linearColumns?span.startCol+Math.min(end,span.textEnd)-span.textStart:span.endCol,previous=segments[segments.length-1];previous&&previous.row===span.row&&startCol<=previous.endCol?previous.endCol=Math.max(previous.endCol,endCol):segments.push({row:span.row,startCol,endCol})}for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=end;)spanIndex+=1;segments.length>0&&matches.push({segments})}return matches}var AltScreenSearchIndex=class{constructor(){this.matches=[]}search(lines,query){let sourceChanged=this.sourceLines?.length!==lines.length;if(!sourceChanged&&this.sourceLines){for(let index=0;index<lines.length;index++)if(this.sourceLines[index]!==lines[index]){sourceChanged=!0;break}}(sourceChanged||!this.corpus)&&(this.sourceLines=Array.from(lines),this.corpus=buildSearchCorpus(lines));let normalizedQuery=normalizeQuery(query),changed=sourceChanged||normalizedQuery!==this.normalizedQuery;return changed&&(this.normalizedQuery=normalizedQuery,this.matches=findSearchCorpusMatches(this.corpus,normalizedQuery)),{matches:this.matches,changed}}};function findAltScreenSearchMatches(lines,query){let normalizedQuery=normalizeQuery(query);return normalizedQuery?findSearchCorpusMatches(buildSearchCorpus(lines),normalizedQuery):[]}function getAltScreenSearchMatchKey(match){let first=match.segments[0],last=match.segments[match.segments.length-1];return first&&last?`${first.row}:${first.startCol}:${last.row}:${last.endCol}`:""}var AltScreenSearchComponent=class{constructor(onQueryChange,navigationButtonStyle=text=>text){this.input=new Input({prompt:" ",placeholder:"Find in transcript",placeholderStyle:text=>`\x1B[2m${text}\x1B[22m`}),this.resultCount=0,this.resultIndex=-1,this.previousButtonStart=-1,this.previousButtonEnd=-1,this.nextButtonStart=-1,this.nextButtonEnd=-1,this._focused=!1,this.onQueryChange=onQueryChange,this.navigationButtonStyle=navigationButtonStyle}get focused(){return this._focused}set focused(value){this._focused=value,this.input.focused=value}setResult(index,count){this.resultIndex=index,this.resultCount=count}getNavigationDirectionAt(row,column){if(row===2){if(column>=this.previousButtonStart&&column<this.previousButtonEnd)return-1;if(column>=this.nextButtonStart&&column<this.nextButtonEnd)return 1}}setHoveredNavigationDirection(direction){return direction===this.hoveredNavigationDirection?!1:(this.hoveredNavigationDirection=direction,!0)}handleInput(data){let previous=this.input.getValue();this.input.handleInput(data);let query=this.input.getValue();query!==previous&&this.onQueryChange(query)}invalidate(){this.input.invalidate()}render(width){let safeWidth=Math.max(1,width),innerWidth=Math.max(0,safeWidth-2),formatKey=key=>key?key.split("+").map(part=>process.platform==="darwin"&&part.toLowerCase()==="alt"?"Option":part.charAt(0).toUpperCase()+part.slice(1)).join("+"):"Unbound",keybindings=getKeybindings(),previousKey=formatKey(keybindings.getKeys("tui.altScreen.searchPrevious")[0]),nextKey=formatKey(keybindings.getKeys("tui.altScreen.searchNext")[0]),result=this.input.getValue()?this.resultCount===0?"No matches":`${this.resultIndex+1}/${this.resultCount}`:"",resultSpace=Math.max(0,innerWidth-3),visibleResult=truncateToWidth(result,resultSpace,""),resultText=visibleResult?`\x1B[2m ${visibleResult} \x1B[22m`:"",inputWidth=Math.max(0,innerWidth-visibleWidth(resultText)),inputLine=truncateToWidth(this.input.render(Math.max(1,inputWidth))[0]??"",inputWidth,""),inputPadding=" ".repeat(Math.max(0,inputWidth-visibleWidth(inputLine))),content=`${inputLine}${inputPadding}${resultText}`,previousButton=`\u2191 ${previousKey}`,nextButton=`\u2193 ${nextKey}`,separator=" \xB7 ",outerGapWidth=1,availableControlsWidth=Math.max(0,innerWidth-outerGapWidth*2-1),controlsWidth=visibleWidth(previousButton)+visibleWidth(separator)+visibleWidth(nextButton);controlsWidth>availableControlsWidth&&(previousButton="\u2191",nextButton="\u2193",separator=" ",controlsWidth=visibleWidth(previousButton)+visibleWidth(separator)+visibleWidth(nextButton));let showButtons=controlsWidth<=availableControlsWidth,renderedButtons=showButtons?this.navigationButtonStyle(previousButton,this.hoveredNavigationDirection===-1)+separator+this.navigationButtonStyle(nextButton,this.hoveredNavigationDirection===1):"",outerGapsWidth=showButtons?outerGapWidth*2:0,rightRuleWidth=renderedButtons&&innerWidth>controlsWidth+outerGapsWidth?1:0,leftRuleWidth=Math.max(0,innerWidth-(showButtons?controlsWidth:0)-outerGapsWidth-rightRuleWidth),previousStart=1+leftRuleWidth+outerGapWidth;return this.previousButtonStart=showButtons?previousStart:-1,this.previousButtonEnd=showButtons?previousStart+visibleWidth(previousButton):-1,this.nextButtonStart=showButtons?this.previousButtonEnd+visibleWidth(separator):-1,this.nextButtonEnd=showButtons?this.nextButtonStart+visibleWidth(nextButton):-1,safeWidth===1?["\u250C","\u2502","\u2514"]:[`\u250C${"\u2500".repeat(innerWidth)}\u2510`,`\u2502${content}\u2502`,`\u2514${"\u2500".repeat(leftRuleWidth)}${renderedButtons?" ":""}${renderedButtons}${renderedButtons?" ":""}${"\u2500".repeat(rightRuleWidth)}\u2518`]}};var DEFAULT_DURATION_MS=1e3,AltScreenFlashContainer=class{constructor(requestRender){this.entries=[],this.nextId=0,this.requestRender=requestRender}flash(message,durationMs=DEFAULT_DURATION_MS){let id=this.nextId++,timer=setTimeout(()=>{let index=this.entries.findIndex(entry=>entry.id===id);index!==-1&&(this.entries.splice(index,1),this.requestRender())},Math.max(0,durationMs));timer.unref(),this.entries.push({id,message,timer}),this.requestRender()}dispose(){for(let entry of this.entries)clearTimeout(entry.timer);this.entries.length=0}invalidate(){}render(width){return this.entries.map(entry=>`\x1B[7m${truncateToWidth(` ${entry.message} `,width,"")}\x1B[27m`)}};var LAYOUT_NODE=Symbol.for("@earendil-works/pi-tui/layout-node");function getLayoutNode(component){let candidate=component;return typeof candidate[LAYOUT_NODE]=="function"?candidate[LAYOUT_NODE]():void 0}var ScrollView=class extends Container{constructor(component,options={}){if(super(),this.currentScrollTop=0,this.contentHeight=0,this.currentViewportHeight=0,this.followSuppressedAtEnd=!1,this.transientScrollbarVisible=!1,this.scrollbarActive=!1,options.axis!==void 0&&options.axis!=="vertical")throw new Error(`Unsupported ScrollView axis: ${options.axis}`);this.child=component,this.children.push(component),this.followEnd=(options.follow??"none")==="end",this.followingEnd=this.followEnd,this.primary=options.primary??!1,this.overscroll=options.overscroll??"chain",this.currentScrollbar=options.scrollbar??"hidden",this.scrollbarTrackStyle=options.scrollbarTrackStyle??(text=>`\x1B[90m${text}\x1B[39m`),this.scrollbarThumbStyle=options.scrollbarThumbStyle??(text=>`\x1B[37m${text}\x1B[39m`),this.scrollbarHideDelayMs=Math.max(0,Math.floor(options.scrollbarHideDelayMs??1e3))}get scrollTop(){return this.currentScrollTop}get isFollowingEnd(){return this.followingEnd}get viewportHeight(){return this.currentViewportHeight}get scrollbar(){return this.currentScrollbar}get isScrollbarVisible(){return this.scrollbar==="always"?this.currentViewportHeight>0:this.scrollbar==="auto"&&this.contentHeight>this.currentViewportHeight&&this.transientScrollbarVisible}get isScrollbarActive(){return this.scrollbarActive}setScrollbar(scrollbar){scrollbar!==this.currentScrollbar&&(this.currentScrollbar=scrollbar,scrollbar!=="auto"?this.hideTransientScrollbar():this.scrollbarActive&&this.markScrollbarActivity(),this.requestRenderCallback?.())}getContentWidth(width){return this.scrollbar==="always"&&width>1?width-1:width}markScrollbarActivity(){this.scrollbar!=="auto"||this.contentHeight<=this.currentViewportHeight||(this.transientScrollbarVisible=!0,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0),!this.scrollbarActive&&(this.scrollbarHideTimer=setTimeout(()=>{this.scrollbarHideTimer=void 0,this.transientScrollbarVisible=!1,this.requestRenderCallback?.()},this.scrollbarHideDelayMs),this.scrollbarHideTimer.unref()))}hideTransientScrollbar(){this.transientScrollbarVisible=!1,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0)}setScrollbarActive(active){active!==this.scrollbarActive&&(this.scrollbarActive=active,this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollTo(scrollTop,options={}){let requested=Number.isFinite(scrollTop)?Math.trunc(scrollTop):this.currentScrollTop,maxScrollTop=Math.max(0,this.contentHeight-this.currentViewportHeight),next=Math.max(0,Math.min(maxScrollTop,requested)),nextFollowSuppressedAtEnd=options.disableFollow===!0&&next===maxScrollTop,nextFollowingEnd=!nextFollowSuppressedAtEnd&&this.followEnd&&next===maxScrollTop;if(next===this.currentScrollTop&&nextFollowingEnd===this.followingEnd&&nextFollowSuppressedAtEnd===this.followSuppressedAtEnd)return;let moved=next!==this.currentScrollTop;this.currentScrollTop=next,this.followingEnd=nextFollowingEnd,this.followSuppressedAtEnd=nextFollowSuppressedAtEnd,moved&&this.markScrollbarActivity(),this.requestRenderCallback?.()}scrollBy(lines){let requested=Number.isFinite(lines)?Math.trunc(lines):0;if(requested===0)return 0;let maxScrollTop=Math.max(0,this.contentHeight-this.currentViewportHeight),start=this.followingEnd?maxScrollTop:this.currentScrollTop,next=Math.max(0,Math.min(maxScrollTop,start+requested)),moved=next-start,wasFollowingEnd=this.followingEnd;return this.currentScrollTop=next,this.followingEnd=this.followEnd&&next===maxScrollTop,this.followSuppressedAtEnd=!1,moved!==0&&this.markScrollbarActivity(),(moved!==0||this.followingEnd!==wasFollowingEnd)&&this.requestRenderCallback?.(),requested-moved}scrollToStart(){let changed=this.currentScrollTop!==0||this.followingEnd!==(this.followEnd&&this.contentHeight<=this.currentViewportHeight);this.currentScrollTop=0,this.followingEnd=this.followEnd&&this.contentHeight<=this.currentViewportHeight,this.followSuppressedAtEnd=!1,changed&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollToEnd(){let next=Math.max(0,this.contentHeight-this.currentViewportHeight),changed=this.currentScrollTop!==next||this.followingEnd!==this.followEnd;this.currentScrollTop=next,this.followingEnd=this.followEnd,this.followSuppressedAtEnd=!1,changed&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}updateLayout(contentHeight,viewportHeight,requestRender){this.contentHeight=Math.max(0,Math.floor(contentHeight)),this.currentViewportHeight=Math.max(0,Math.floor(viewportHeight)),this.requestRenderCallback=requestRender;let maxScrollTop=Math.max(0,this.contentHeight-this.currentViewportHeight);this.followingEnd?this.currentScrollTop=maxScrollTop:this.currentScrollTop=Math.max(0,Math.min(this.currentScrollTop,maxScrollTop)),this.currentScrollTop<maxScrollTop&&(this.followSuppressedAtEnd=!1),this.followEnd&&this.currentScrollTop===maxScrollTop&&!this.followSuppressedAtEnd&&(this.followingEnd=!0),this.contentHeight<=this.currentViewportHeight&&this.hideTransientScrollbar()}addChild(_component){throw new Error("ScrollView has exactly one child")}removeChild(_component){throw new Error("ScrollView child cannot be removed")}clear(){throw new Error("ScrollView child cannot be cleared")}render(width){let contentWidth=this.getContentWidth(width),lines=this.child.render(contentWidth);return contentWidth===width?lines:copyLineSources(lines,lines.map(line=>`${line} `))}[LAYOUT_NODE](){return{type:"scroll",component:this.child,state:this}}};function isStackEntry(child){return!("render"in child)}function normalizeSize(value,fallback){return value===void 0||!Number.isFinite(value)?fallback:Math.max(0,Math.floor(value))}var Stack=class extends Container{constructor(children=[],options={}){super(),this.entries=[],this.gap=normalizeSize(options.gap,0),this.align=options.align??"stretch";for(let child of children)isStackEntry(child)?this.addChild(child.component,child):this.addChild(child)}addChild(component,options={}){super.addChild(component),this.entries.push({component,...options.basis===void 0?{}:{basis:options.basis},...options.grow===void 0?{}:{grow:normalizeSize(options.grow,0)},...options.shrink===void 0?{}:{shrink:normalizeSize(options.shrink,1)},...options.minSize===void 0?{}:{minSize:normalizeSize(options.minSize,0)},...options.maxSize===void 0?{}:{maxSize:normalizeSize(options.maxSize,Number.MAX_SAFE_INTEGER)},...options.visible===void 0?{}:{visible:options.visible}})}removeChild(component){super.removeChild(component);let index=this.entries.findIndex(entry=>entry.component===component);index!==-1&&this.entries.splice(index,1)}clear(){super.clear(),this.entries.length=0}[LAYOUT_NODE](){return{type:this.layoutType,entries:this.entries,gap:this.gap,align:this.align}}};function visibleStackEntries(entries,viewport){return entries.filter(entry=>entry.visible?.(viewport)??!0)}function clampSize(size,entry){let min=Math.max(0,Math.floor(entry.minSize??0)),max=Math.max(min,Math.floor(entry.maxSize??Number.MAX_SAFE_INTEGER));return Math.max(min,Math.min(max,Math.max(0,Math.floor(size))))}function distribute(sizes,entries,amount,mode){let remaining=amount;for(;remaining>0;){let candidates=entries.map((entry,index)=>({entry,index})).filter(({entry,index})=>mode==="grow"?(entry.grow??0)>0&&sizes[index]<(entry.maxSize??Number.MAX_SAFE_INTEGER):(entry.shrink??1)>0&&sizes[index]>(entry.minSize??0));if(candidates.length===0)return;let totalWeight=candidates.reduce((sum,{entry,index})=>sum+(mode==="grow"?entry.grow??0:(entry.shrink??1)*Math.max(1,sizes[index])),0),distributed=0;for(let{entry,index}of candidates){if(remaining<=0)break;let weight=mode==="grow"?entry.grow??0:(entry.shrink??1)*Math.max(1,sizes[index]),proposed=Math.max(1,Math.floor(remaining*weight/totalWeight)),capacity=mode==="grow"?(entry.maxSize??Number.MAX_SAFE_INTEGER)-sizes[index]:sizes[index]-(entry.minSize??0),delta=Math.min(remaining,proposed,capacity);delta<=0||(sizes[index]=sizes[index]+(mode==="grow"?delta:-delta),remaining-=delta,distributed+=delta)}if(distributed===0)return}}function allocateStackSizes(entries,intrinsicSizes,availableSize,gap){let sizes=entries.map((entry,index)=>clampSize(entry.basis===void 0||entry.basis==="auto"?intrinsicSizes[index]??0:entry.basis,entry));if(availableSize===void 0)return sizes;let contentSize=Math.max(0,Math.floor(availableSize)-Math.max(0,entries.length-1)*gap),total=sizes.reduce((sum,size)=>sum+size,0);return total<contentSize?distribute(sizes,entries,contentSize-total,"grow"):total>contentSize&&distribute(sizes,entries,total-contentSize,"shrink"),sizes}var OSC133_ZONE_PREFIX=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function intersect(a,b2){let x2=Math.max(a.x,b2.x),y2=Math.max(a.y,b2.y),right=Math.min(a.x+a.width,b2.x+b2.width),bottom=Math.min(a.y+a.height,b2.y+b2.height);return{x:x2,y:y2,width:Math.max(0,right-x2),height:Math.max(0,bottom-y2)}}function renderCached(context,component,width){let safeWidth=Math.max(1,Math.floor(width)),widths=context.renderCache.get(component);widths||(widths=new Map,context.renderCache.set(component,widths));let lines=widths.get(safeWidth);return lines||(lines=component.render(safeWidth),widths.set(safeWidth,lines)),lines}function measureHeight(context,component,width){return renderCached(context,component,width).length}function measureWidth(context,component,width){return renderCached(context,component,width).reduce((max,line)=>Math.max(max,visibleWidth(line)),0)}function withParent(box,parent){return box.parent=parent,box}function translateBox(box,deltaY){box.rect.y+=deltaY;for(let child of box.children)translateBox(child,deltaY)}function updateClips(box,parentClip){box.clip=intersect(parentClip,box.rect);for(let child of box.children)updateClips(child,box.clip)}function layoutComponent(context,component,x2,y2,width,height,clip){let safeWidth=Math.max(1,Math.floor(width)),node=getLayoutNode(component);if(!node){let lines=renderCached(context,component,safeWidth),allocatedHeight2=height===void 0?lines.length:Math.max(0,Math.floor(height)),lineOffset=0;if(lines.length>allocatedHeight2&&allocatedHeight2>0){let cursorLine=lines.findIndex(line=>line.includes(CURSOR_MARKER));cursorLine>=allocatedHeight2&&(lineOffset=cursorLine-allocatedHeight2+1)}return{component,rect:{x:x2,y:y2,width:safeWidth,height:allocatedHeight2},clip:intersect(clip,{x:x2,y:y2,width:safeWidth,height:allocatedHeight2}),children:[],lines,lineOffset,layer:0}}if(node.type==="scroll"){let previousScrollTop=node.state.scrollTop,contentWidth=node.state.getContentWidth(safeWidth),childBox=layoutComponent(context,node.component,x2,y2-previousScrollTop,contentWidth,void 0,clip),contentHeight=childBox.rect.height,viewportHeight=height===void 0?contentHeight:Math.max(0,Math.floor(height));node.state.updateLayout(contentHeight,viewportHeight,context.requestRender),translateBox(childBox,previousScrollTop-node.state.scrollTop);let scrollView=node.state;(node.state.primary||!context.primaryScrollView)&&(context.primaryScrollView=scrollView);let rect2={x:x2,y:y2,width:safeWidth,height:viewportHeight},childClip=intersect(clip,rect2),box2={component,rect:rect2,clip:childClip,children:[childBox],scrollView,scrollContentLines:renderCached(context,node.component,contentWidth),layer:0};return childBox.parent=box2,updateClips(childBox,childClip),box2}let entries=visibleStackEntries(node.entries,context.viewport),gapTotal=Math.max(0,entries.length-1)*node.gap;if(node.type==="vstack"){let intrinsicHeights2=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureHeight(context,entry.component,safeWidth)),sizes=allocateStackSizes(entries,intrinsicHeights2,height,node.gap),naturalHeight=sizes.reduce((sum,size)=>sum+size,0)+gapTotal,allocatedHeight2=height===void 0?naturalHeight:Math.max(0,Math.floor(height)),rect2={x:x2,y:y2,width:safeWidth,height:allocatedHeight2},box2={component,rect:rect2,clip:intersect(clip,rect2),children:[],layer:0},childY=y2;for(let index=0;index<entries.length;index++)box2.children.push(withParent(layoutComponent(context,entries[index].component,x2,childY,safeWidth,sizes[index],box2.clip),box2)),childY+=sizes[index]+node.gap;return box2}let intrinsicWidths=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureWidth(context,entry.component,safeWidth)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,node.gap),intrinsicHeights=entries.map((entry,index)=>measureHeight(context,entry.component,Math.max(1,widths[index]))),allocatedHeight=height===void 0?intrinsicHeights.reduce((max,childHeight)=>Math.max(max,childHeight),0):Math.max(0,height),rect={x:x2,y:y2,width:safeWidth,height:allocatedHeight},box={component,rect,clip:intersect(clip,rect),children:[],layer:0},childX=x2;for(let index=0;index<entries.length;index++){let naturalChildHeight=intrinsicHeights[index],childHeight=node.align==="stretch"?allocatedHeight:Math.min(allocatedHeight,naturalChildHeight),childY=y2;node.align==="center"?childY+=Math.floor((allocatedHeight-childHeight)/2):node.align==="end"&&(childY+=allocatedHeight-childHeight);let childWidth=widths[index];childWidth===0?box.children.push({component:entries[index].component,rect:{x:childX,y:childY,width:0,height:childHeight},clip:{x:childX,y:childY,width:0,height:0},children:[],parent:box,layer:0}):box.children.push(withParent(layoutComponent(context,entries[index].component,childX,childY,childWidth,childHeight,box.clip),box)),childX+=childWidth+node.gap}return box}function replaceScrollbarCell(line,column,totalWidth,replacement,preserveTargetBackground){if(isImageLine(line))return line;let graphemeRange=getGraphemeCellRange(line,column),start=graphemeRange?.start??column,end=graphemeRange?.end??column+1,before=sliceByColumn(line,0,start,!0),target=sliceByColumn(line,start,end-start,!0),after=sliceByColumn(line,end,Math.max(0,totalWidth-end),!0),targetPrefix="",targetIndex=0;for(;targetIndex<target.length;){let ansi=extractAnsiCode(target,targetIndex);if(!ansi)break;targetPrefix+=ansi.code,targetIndex+=ansi.length}let beforePadding=" ".repeat(Math.max(0,start-visibleWidth(before))),cellPaddingBefore=" ".repeat(Math.max(0,column-start)),cellPaddingAfter=" ".repeat(Math.max(0,end-column-1)),targetStyle=`\x1B[0m\x1B]8;;\x07${preserveTargetBackground?getActiveBackgroundAnsi(targetPrefix):""}`;return`${before}${beforePadding}${targetStyle}${cellPaddingBefore}${replacement}${cellPaddingAfter}${after}`}function getScrollbarGeometry(box,includeHiddenAuto=!1){if(!box.scrollView||box.rect.width<=0||box.rect.height<=0)return;let contentHeight=box.children[0]?.rect.height??box.scrollContentLines?.length??0,trackHeight=box.rect.height,canRevealHiddenAuto=includeHiddenAuto&&box.scrollView.scrollbar==="auto"&&contentHeight>trackHeight;if(!box.scrollView.isScrollbarVisible&&!canRevealHiddenAuto)return;let minThumbHeight=Math.min(2,trackHeight),thumbHeight=Math.max(minThumbHeight,Math.min(trackHeight,Math.round(trackHeight*trackHeight/contentHeight))),maxScrollTop=Math.max(0,contentHeight-trackHeight),maxThumbTop=trackHeight-thumbHeight,thumbOffset=maxScrollTop===0?0:Math.round(box.scrollView.scrollTop/maxScrollTop*maxThumbTop),column=box.rect.x+box.rect.width-1;if(!(column<box.clip.x||column>=box.clip.x+box.clip.width))return{column,trackTop:box.rect.y,trackHeight,thumbTop:box.rect.y+thumbOffset,thumbHeight,maxScrollTop}}function paintScrollbar(box,screen,totalWidth){let geometry=getScrollbarGeometry(box);if(!(!geometry||!box.scrollView))for(let offset=0;offset<geometry.trackHeight;offset++){let row=geometry.trackTop+offset;if(row<box.clip.y||row>=box.clip.y+box.clip.height||row<0||row>=screen.length)continue;let replacement=row>=geometry.thumbTop&&row<geometry.thumbTop+geometry.thumbHeight?box.scrollView.scrollbarThumbStyle(box.scrollView.isScrollbarActive?"\u2588":"\u2503"):box.scrollView.scrollbarTrackStyle("\u2502");screen[row]=replaceScrollbarCell(screen[row]??"",geometry.column,totalWidth,replacement,box.scrollView.scrollbar!=="always")}}function paintBox(box,screen,totalWidth){if(box.lines){let offset=box.lineOffset??0,firstRow=Math.max(box.rect.y,box.clip.y,0),lastRow=Math.min(box.rect.y+box.rect.height,box.clip.y+box.clip.height,screen.length);for(let row=firstRow;row<lastRow;row++){let sourceLine=box.lines[offset+row-box.rect.y];if(sourceLine===void 0)continue;let line=sourceLine.replace(OSC133_ZONE_PREFIX,""),imageMetadata=getKittyImageMetadata(line);if(imageMetadata){let clipBottom=Math.min(screen.length,box.clip.y+box.clip.height),visibleRows=Math.min(imageMetadata.rows,clipBottom-row);visibleRows<imageMetadata.rows&&(line=cropKittyImageLine(line,0,visibleRows))}box.rect.x===0&&box.rect.width>=totalWidth&&(isImageLine(line)||!screen[row])?screen[row]=line:screen[row]=compositeTuiLine(screen[row]??"",line,box.rect.x,box.rect.width,totalWidth)}}for(let child of box.children)paintBox(child,screen,totalWidth);if(box.scrollView&&box.scrollContentLines&&box.scrollView.scrollTop>0&&box.rect.height>0)for(let imageRow=box.scrollView.scrollTop-1;imageRow>=0;imageRow--){let imageLine=box.scrollContentLines[imageRow]??"",metadata=getKittyImageMetadata(imageLine);if(metadata){let hiddenRows=box.scrollView.scrollTop-imageRow;if(hiddenRows<metadata.rows){let visibleRows=Math.min(box.rect.height,metadata.rows-hiddenRows),cropped=cropKittyImageLine(imageLine,hiddenRows,visibleRows);box.rect.x===0&&box.rect.width>=totalWidth&&(screen[box.rect.y]=cropped)}break}if(imageLine!=="")break}paintScrollbar(box,screen,totalWidth)}function renderLayoutFrame(root,width,height,requestRender){let safeWidth=Math.max(1,Math.floor(width)),safeHeight=Math.max(1,Math.floor(height)),context={viewport:{width:safeWidth,height:safeHeight},renderCache:new Map,requestRender,primaryScrollView:void 0},rootBox=layoutComponent(context,root,0,0,safeWidth,safeHeight,{x:0,y:0,width:safeWidth,height:safeHeight}),lines=Array.from({length:safeHeight},()=>"");return paintBox(rootBox,lines,safeWidth),{root:rootBox,width:safeWidth,height:safeHeight,lines,...context.primaryScrollView===void 0?{}:{primaryScrollView:context.primaryScrollView}}}function containsPoint(rect,x2,y2){return x2>=rect.x&&x2<rect.x+rect.width&&y2>=rect.y&&y2<rect.y+rect.height}function getLayoutBoxesAt(frame,x2,y2){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y2)){result.push({box,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a,b2)=>b2.box.layer-a.box.layer||b2.depth-a.depth),result.map(({box})=>box)}function getScrollViewBox(frame,scrollView){let visit=box=>{if(box.scrollView===scrollView)return box;for(let child of box.children){let match=visit(child);if(match)return match}};return visit(frame.root)}function getScrollViewsAt(frame,x2,y2){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y2)){box.scrollView&&containsPoint(box.rect,x2,y2)&&result.push({scrollView:box.scrollView,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a,b2)=>b2.depth-a.depth),result.map(entry=>entry.scrollView)}var MOUSE_TRACKING={buttonMotion:"\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",allMotion:"\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",inline:"\x1B[?1006h\x1B[?1000h",disable:"\x1B[?1000l\x1B[?1002l\x1B[?1003l\x1B[?1006l"};function parseSgrMouseEvent(data){let match=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);if(!match)return;let button=Number(match[1]),x2=Number(match[2])-1,y2=Number(match[3])-1;if(!(button>255||!Number.isSafeInteger(x2)||!Number.isSafeInteger(y2)||x2<0||y2<0))return{button,x:x2,y:y2,release:match[4]==="m"}}function parseWheelEvent(data){let raw=parseSgrMouseEvent(data)??(data.length===6&&data.startsWith("\x1B[M")?{button:data.charCodeAt(3)-32,x:data.charCodeAt(4)-33,y:data.charCodeAt(5)-33}:void 0);if(!raw||raw.button<0||raw.button>255||(raw.button&64)===0)return;let direction=raw.button&3;if(!(direction!==0&&direction!==1))return{direction:direction===0?-1:1,x:raw.x,y:raw.y,button:raw.button}}function isMouseSequence(data){return data.startsWith("\x1B[<")||data.startsWith("\x1B[M")}function decodeMouseButton(button){switch(button&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}function toTuiMouseEvent(type,raw,size,extra={}){return{type,button:type==="wheel"?"none":decodeMouseButton(raw.button),x:raw.x,y:raw.y,screenX:raw.x,screenY:raw.y,width:Math.max(1,size.columns),height:Math.max(1,size.rows),shift:(raw.button&4)!==0,alt:(raw.button&8)!==0,ctrl:(raw.button&16)!==0,...extra}}var MouseClickSynthesizer=class{press(raw,target,epoch,now=Date.now()){this.pressed={x:raw.x,y:raw.y,target,epoch,time:now}}release(raw,target,epoch,now=Date.now()){let press=this.pressed;if(this.pressed=void 0,!press||press.x!==raw.x||press.y!==raw.y||press.target!==target||press.epoch!==epoch||now-press.time>500||now<press.time){this.last=void 0;return}let last=this.last,count=last&&last.x===raw.x&&last.y===raw.y&&last.target===target&&last.epoch===epoch&&now-last.time<=500?last.count%3+1:1;return this.last={...press,time:now,count},count}cancel(){this.pressed=void 0,this.last=void 0}};function terminalAcceleratesWheel(){let env=process.env;return process.platform==="darwin"&&env.SSH_CONNECTION===void 0&&env.SSH_CLIENT===void 0&&env.SSH_TTY===void 0}var WheelScrollAccelerator=class{constructor(lines="auto",accelerate=!terminalAcceleratesWheel()){this.lastTime=Number.NEGATIVE_INFINITY,this.lastDirection=0,this.carry=0,this.lines=lines,this.accelerate=accelerate}setLines(lines){this.lines=lines,this.reset()}next(direction,now){if(this.lines!=="auto")return Number.isFinite(this.lines)?Math.max(1,Math.floor(this.lines)):1;if(!this.accelerate)return 1;let gap=now-this.lastTime,sameGesture=direction===this.lastDirection&&gap<=200;if(this.lastTime=now,this.lastDirection=direction,!sameGesture)return this.averageGap=void 0,this.carry=0,1;if(gap<5)return 1;this.averageGap=this.averageGap===void 0?gap:(this.averageGap+gap)/2;let lines=Math.min(6,Math.max(1,100/this.averageGap))+this.carry,whole=Math.floor(lines);return this.carry=lines-whole,whole}reset(){this.lastTime=Number.NEGATIVE_INFINITY,this.lastDirection=0,this.averageGap=void 0,this.carry=0}};var _a,ENTER_ALT_SCREEN="\x1B[?1049h",EXIT_ALT_SCREEN="\x1B[?1049l",DISABLE_AUTOWRAP="\x1B[?7l",ENABLE_AUTOWRAP="\x1B[?7h",ENABLE_BUTTON_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",ENABLE_ALL_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",DISABLE_MOUSE="\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l",FOCUS_IN="\x1B[I",FOCUS_OUT="\x1B[O",BEGIN_SYNCHRONIZED_OUTPUT="\x1B[?2026h",END_SYNCHRONIZED_OUTPUT="\x1B[?2026l",OSC133_ZONE_PREFIX2=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,OSC133_PROMPT_START=/^\x1b\]133;A(?:\x07|\x1b\\)/,PAGE_SCROLL_OVERLAP=4,ALT_WHEEL_SCROLL_MULTIPLIER=5,MAX_CACHED_OFFSCREEN_KITTY_IMAGES=16,MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES=32*1024*1024,MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES=64*1024*1024,DOUBLE_CLICK_INTERVAL_MS=500,COPY_ERROR_FLASH_DURATION_MS=5e3,TERMINAL_WORD_SELECTION_JOINERS=new Set(["/","-"]),wordSegmenter3=getWordSegmenter(),TuiAltScreen=class extends TuiBase{static{_a=VIEWPORT_TUI}constructor(terminal,showHardwareCursor,logDirectory,options={}){super(terminal,showHardwareCursor,logDirectory),this.mode="fullscreen",this[_a]=!0,this.previousScreen=[],this.lastDocument=[],this.previousScreenWidth=0,this.previousScreenHeight=0,this.altScreenActive=!1,this.imageProtocol=null,this.uploadedKittyImages=new Map,this.selectionGranularity="character",this.selectionAutoScrollDirection=0,this.selectionPressActive=!1,this.selectionDragged=!1,this.mousePressMoved=!1,this.selectionSourceUnavailable=!1,this.implicitDocument={render:width=>super.render(width),handleMouse:event=>super.handleMouse(event),invalidate:()=>{for(let child of this.children)child.invalidate()}},this.implicitScrollView=new ScrollView(this.implicitDocument,{follow:"end",primary:!0}),this.flashes=new AltScreenFlashContainer(()=>this.requestRender()),this.wheelScroll=new WheelScrollAccelerator(options.wheelScrollLines??1),this.mouseEnabled=options.mouse??!0,this.searchMatchStyle=options.searchMatchStyle??(text=>`\x1B[4m${text}\x1B[24m`),this.searchCurrentMatchStyle=options.searchCurrentMatchStyle??(text=>`\x1B[1;7m${text}\x1B[22;27m`),this.searchNavigationButtonStyle=options.searchNavigationButtonStyle??(text=>text),this.scrollToEndIndicator=options.scrollToEndIndicator,this.openUrl=options.openUrl,this.onRightClickPaste=options.onRightClickPaste,this.copyOnSelect=options.copyOnSelect??!0,this.copySelection=options.copySelection,this.addInputListener(data=>this.handleViewportInput(data))}get viewportTop(){return this.getPrimaryScrollView().scrollTop}get isFollowingOutput(){return this.getPrimaryScrollView().isFollowingEnd}setWheelScrollLines(lines){this.wheelScroll.setLines(lines)}getCopyOnSelect(){return this.copyOnSelect}setCopyOnSelect(enabled){this.copyOnSelect=enabled}hasActiveSelection(){return this.getActiveSelectionText()!==void 0||this.selectionSourceUnavailable}async copyActiveSelectionToClipboard(){return this.copySelectionToClipboard()}getScreenLines(){return[...this.previousScreen]}setLayoutRoot(component){this.layoutRoot!==component&&(this.layoutRoot=component,this.currentLayout=void 0,this.requestRender())}render(width){return this.layoutRoot?.render(width)??super.render(width)}getMountedRoots(){return this.layoutRoot?[this.layoutRoot]:this.children}getPrimaryScrollView(){return this.currentLayout?.primaryScrollView??this.implicitScrollView}beforeTerminalStart(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.flashes.dispose(),this.altScreenActive=!0;let capabilities=getCapabilities();this.imageProtocol=capabilities.images,this.uploadedKittyImages.clear(),capabilities.images==="iterm2"&&(this.savedCapabilities=capabilities,setCapabilities({...capabilities,images:null}),this.invalidate()),this.lastDocument=[],this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,this.resetRenderState();let term=process.env.TERM?.toLowerCase()??"",mouseSequence=process.env.TMUX!==void 0||process.env.ZELLIJ!==void 0||process.env.STY!==void 0||term.startsWith("tmux")||term.startsWith("screen")?ENABLE_BUTTON_MOTION_MOUSE:ENABLE_ALL_MOTION_MOUSE;this.terminal.write(`${ENTER_ALT_SCREEN}${DISABLE_AUTOWRAP}${this.mouseEnabled?mouseSequence:""}\x1B[2J\x1B[H\x1B[?25l`)}beforeTerminalStop(_options){this.closeSearch(),this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.clearComponentMouseGesture(),this.flashes.dispose(),this.altScreenActive&&(this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${this.deleteAltScreenKittyImages()}${this.mouseEnabled?DISABLE_MOUSE:""}${ENABLE_AUTOWRAP}${END_SYNCHRONIZED_OUTPUT}`),this.uploadedKittyImages.clear())}afterTerminalStop(options){if(this.altScreenActive){if(this.altScreenActive=!1,options.preserveScreen)this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}\x1B[?25h${END_SYNCHRONIZED_OUTPUT}`);else{let width=Math.max(1,this.terminal.columns),documentLines=this.render(width).map(line=>line.replace(OSC133_ZONE_PREFIX2,""));this.lastDocument=this.applyLineResets(documentLines.map(line=>line.replaceAll(CURSOR_MARKER,""))).map(line=>isImageLine(line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));let buffer=`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}${DISABLE_AUTOWRAP}`;for(let row=0;row<this.lastDocument.length;row++)row>0&&(buffer+=`\r
`),buffer+=`\r\x1B[2K${this.lastDocument[row]??""}`;buffer+=`\x1B[0m${ENABLE_AUTOWRAP}\r
\x1B[?25h${END_SYNCHRONIZED_OUTPUT}`,this.terminal.write(buffer)}this.savedCapabilities&&(setCapabilities(this.savedCapabilities),this.savedCapabilities=void 0)}}deleteAltScreenKittyImages(){return this.imageProtocol==="kitty"?deleteAllKittyImages():""}prepareKittyScreen(screen){let visibleImageIds=new Set,lines=screen.map(line=>{let placement=getKittyImagePlacement(line);if(!placement)return line;visibleImageIds.add(placement.imageId);let cachedImage=this.uploadedKittyImages.get(placement.imageId),nextCachedImage={transmissionGeneration:placement.transmissionGeneration,transmissionBytes:placement.transmissionBytes,estimatedDecodedBytes:placement.estimatedDecodedBytes};return cachedImage&&this.uploadedKittyImages.delete(placement.imageId),this.uploadedKittyImages.set(placement.imageId,nextCachedImage),cachedImage?.transmissionGeneration===placement.transmissionGeneration?placement.replacementLine:line}),cachedOffscreenImageCount=0,cachedOffscreenTransmissionBytes=0,cachedOffscreenDecodedBytes=0;for(let[imageId,cachedImage]of this.uploadedKittyImages)visibleImageIds.has(imageId)||(cachedOffscreenImageCount+=1,cachedOffscreenTransmissionBytes+=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes+=cachedImage.estimatedDecodedBytes);let evictedImageDeletion="";for(let[imageId,cachedImage]of this.uploadedKittyImages){if(cachedOffscreenImageCount<=MAX_CACHED_OFFSCREEN_KITTY_IMAGES&&cachedOffscreenTransmissionBytes<=MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES&&cachedOffscreenDecodedBytes<=MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES)break;visibleImageIds.has(imageId)||(evictedImageDeletion+=deleteKittyImage(imageId),this.uploadedKittyImages.delete(imageId),cachedOffscreenImageCount-=1,cachedOffscreenTransmissionBytes-=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes-=cachedImage.estimatedDecodedBytes)}return{lines,evictedImageDeletion}}resetRenderState(){this.previousScreen=[],this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0}scrollBy(lines){this.getPrimaryScrollView().scrollBy(lines),this.requestRender()}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestRender()}scrollToBottom(){this.getPrimaryScrollView().scrollToEnd(),this.requestRender()}scrollToPrompt(direction){if(!this.currentLayout)return;let scrollView=this.getPrimaryScrollView(),lines=getScrollViewBox(this.currentLayout,scrollView)?.scrollContentLines;if(lines){for(let row=scrollView.scrollTop+direction;row>=0&&row<lines.length;row+=direction)if(OSC133_PROMPT_START.test(lines[row]??"")){scrollView.scrollTo(row),this.requestRender();return}}}toggleSearch(){if(this.activeSearch){this.closeSearch();return}let component=new AltScreenSearchComponent(query=>this.updateSearchQuery(query),this.searchNavigationButtonStyle),search={component,index:new AltScreenSearchIndex,query:"",matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:"query"};this.activeSearch=search,search.overlay=this.showOverlay(component,{anchor:"top-right",width:"40%",minWidth:32,margin:1})}closeSearch(){let search=this.activeSearch;search&&(this.activeSearch=void 0,search.overlay?.hide(),this.requestRender())}updateSearchQuery(query){let search=this.activeSearch;if(!search||query===search.query)return;let selected=search.matches[search.selectedIndex];search.anchorRow=selected?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,search.query=query,search.selectionMode="query",search.component.setResult(-1,0),this.requestRender()}navigateSearch(direction){let search=this.activeSearch;search?.query&&(search.selectionMode=direction<0?"previous":"next",this.requestRender())}getSearchNavigationDirectionAt(x2,y2){let search=this.activeSearch,bounds=search?.overlay?.getBounds();if(!(!search||!bounds)&&!(x2<bounds.col||x2>=bounds.col+bounds.width||y2<bounds.row||y2>=bounds.row+bounds.height))return search.component.getNavigationDirectionAt(y2-bounds.row,x2-bounds.col)}handleSearchMouseEvent(event){let search=this.activeSearch;if(!search)return!1;let direction=this.getSearchNavigationDirectionAt(event.x,event.y);return search.component.setHoveredNavigationDirection(direction)&&this.requestRender(),direction===void 0||event.release||(event.button&32)!==0||(event.button&3)!==0?!1:(this.navigateSearch(direction),!0)}refreshSearch(layout){let search=this.activeSearch;if(!search)return!1;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView),lines=box?.scrollContentLines;if(!lines||!search.query.trim())return search.matches=[],search.selectedIndex=-1,search.selectedKey=void 0,search.selectionMode="retain",search.component.setResult(-1,0),!1;let shouldRevealSelection=search.selectionMode!=="retain",result=search.index.search(lines,search.query),matches=result.matches;if(search.matches=matches,!result.changed&&search.selectionMode==="retain")return!1;let exactIndex=result.changed?search.selectedKey?matches.findIndex(match=>getAltScreenSearchMatchKey(match)===search.selectedKey):-1:search.selectedIndex,selectedIndex=-1;if(matches.length>0)if(search.selectionMode==="query"){let low=0,high=matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2);(matches[middle].segments[0]?.row??0)<search.anchorRow?low=middle+1:high=middle}selectedIndex=low<matches.length?low:0}else if(search.selectionMode==="next"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?0:(baseIndex+1)%matches.length}else if(search.selectionMode==="previous"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?matches.length-1:(baseIndex-1+matches.length)%matches.length}else selectedIndex=exactIndex>=0?exactIndex:Math.min(Math.max(0,search.selectedIndex),matches.length-1);if(search.selectedIndex=selectedIndex,search.selectedKey=selectedIndex>=0?getAltScreenSearchMatchKey(matches[selectedIndex]):void 0,search.selectionMode="retain",search.component.setResult(selectedIndex,matches.length),!shouldRevealSelection)return!1;let selected=matches[selectedIndex],firstSegment=selected?.segments[0],lastSegment=selected?.segments[selected.segments.length-1];if(!box||!firstSegment||!lastSegment||scrollView.viewportHeight<=0)return!1;let before=scrollView.scrollTop,visibleBottom=before+scrollView.viewportHeight-1,target=before;return(firstSegment.row<before||lastSegment.row>visibleBottom)&&(target=firstSegment.row-Math.floor(scrollView.viewportHeight/3)),scrollView.scrollTo(target,{disableFollow:!0}),scrollView.scrollTop!==before}flash(message,durationMs){this.flashes.flash(message,durationMs)}shouldDeferViewportInputToOverlay(){return this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(data){if(data===FOCUS_OUT){let hadActiveSelection=this.selectionPressActive,hadNonEmptyActiveSelection=hadActiveSelection&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=!1,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,hadActiveSelection&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,hadNonEmptyActiveSelection&&this.requestRender()),this.lastClick=void 0,{consume:!0}}if(data===FOCUS_IN)return{consume:!0};let wheelEvent=this.parseWheelEvent(data);if(wheelEvent){let lines=this.wheelScroll.next(wheelEvent.direction,performance.now()),wheelDelta=wheelEvent.direction*((wheelEvent.button&8)!==0?lines*ALT_WHEEL_SCROLL_MULTIPLIER:lines),event=this.createMouseEvent("wheel",wheelEvent.button,wheelEvent.x,wheelEvent.y,{wheelDelta}),overlay=this.dispatchMouseToOverlay(event),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));return result?(this.applyMouseDispatchResult(event,result)&&this.requestRender(),{consume:!0}):this.shouldDeferViewportInputToOverlay()?void 0:(this.routeWheel(wheelEvent,wheelDelta),{consume:!0})}let mouseEvent=this.parseSgrMouseEvent(data);if(mouseEvent)return this.handleMouseEvent(mouseEvent),{consume:!0};if(this.isMouseSequence(data))return{consume:!0};let keybindings=getKeybindings(),isRelease=isKeyRelease(data);if(keybindings.matches(data,"tui.altScreen.search"))return isRelease||this.toggleSearch(),{consume:!0};if(this.activeSearch?.overlay?.isFocused()){if(keybindings.matches(data,"tui.altScreen.searchNext"))return isRelease||this.navigateSearch(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchPrevious"))return isRelease||this.navigateSearch(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchClose"))return isRelease||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInputToOverlay()){if(keybindings.matches(data,"tui.altScreen.pageUp"))return isRelease||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.pageDown"))return isRelease||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageUp"))return isRelease||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageDown"))return isRelease||this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineUp"))return isRelease||this.scrollBy(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineDown"))return isRelease||this.scrollBy(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.previousPrompt"))return isRelease||this.scrollToPrompt(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.nextPrompt"))return isRelease||this.scrollToPrompt(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.top"))return isRelease||this.scrollToTop(),{consume:!0};if(keybindings.matches(data,"tui.altScreen.bottom"))return isRelease||this.scrollToBottom(),{consume:!0}}}decodeMouseButton(button){return decodeMouseButton(button)}createMouseEvent(type,button,x2,y2,extra={}){return{type,button:type==="wheel"?"none":this.decodeMouseButton(button),x:x2,y:y2,screenX:x2,screenY:y2,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(button&4)!==0,alt:(button&8)!==0,ctrl:(button&16)!==0,...extra.wheelDelta===void 0?{}:{wheelDelta:extra.wheelDelta},...extra.clickCount===void 0?{}:{clickCount:extra.clickCount}}}dispatchMouseToLayout(event){if(!this.currentLayout)return;let visited=new Set,boxes=getLayoutBoxesAt(this.currentLayout,event.screenX,event.screenY);for(let box of boxes){if(visited.has(box.component)||getLayoutNode(box.component)&&box.component.handleMouse===Container.prototype.handleMouse)continue;visited.add(box.component);let result=dispatchMouseEvent(box.component,{...event,x:event.screenX-box.rect.x,y:event.screenY-box.rect.y,width:box.rect.width,height:box.rect.height});if(result)return result}}applyMouseDispatchResult(event,result,applyFocus=!0){let focusTarget=applyFocus&&result.focus?this.resolveMouseFocusTarget(result.focusTarget??result.target.component):null,focusChanged=focusTarget!==null&&this.getFocusedComponent()!==focusTarget;return focusTarget&&this.setFocus(focusTarget),result.capture&&(this.mouseCapture=result.target),result.render??(focusChanged||event.type==="press"||event.type==="click"||event.type==="drag"||event.type==="wheel")}dispatchMouseToTarget(event,target){return dispatchMouseEvent(target.component,retargetMouseEvent(event,target))}getComponentClickCount(target,x2,y2){let now=Date.now(),previous=this.lastComponentClick,count=previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.component===target.component&&previous.x===x2&&previous.y===y2?previous.count%3+1:1;return this.lastComponentClick={timestamp:now,count,component:target.component,x:x2,y:y2},count}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(raw){let isMotion=(raw.button&32)!==0,type=raw.release?"release":isMotion?this.decodeMouseButton(raw.button)==="none"?"move":"drag":"press",event=this.createMouseEvent(type,raw.button,raw.x,raw.y);if(this.mouseCapture||this.mousePressTarget){let target=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(raw.x!==this.mousePressPoint.x||raw.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let render=!1,targetResult=this.dispatchMouseToTarget(event,target);if(targetResult&&(render=this.applyMouseDispatchResult(event,targetResult)),raw.release){if(!this.mousePressMoved&&this.mousePressPoint?.x===raw.x&&this.mousePressPoint.y===raw.y){let clickEvent=this.createMouseEvent("click",raw.button,raw.x,raw.y,{clickCount:this.getComponentClickCount(target,raw.x,raw.y)}),focusBeforeClick=this.getFocusedComponent(),clickResult=this.dispatchMouseToTarget(clickEvent,target);if(clickResult){let keepHandlerFocus=this.getFocusedComponent()!==focusBeforeClick;render=this.applyMouseDispatchResult(clickEvent,clickResult,!keepHandlerFocus)||render}}this.clearComponentMouseGesture()}render&&this.requestRender();return}if(this.handleSearchMouseEvent(raw))return;let overlay=this.dispatchMouseToOverlay(event);if(overlay.hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(raw))return;let scrollbarHandled=this.handleScrollbarMouseEvent(raw);if(this.scrollbarDrag||this.updateScrollbarHover(raw.x,raw.y),scrollbarHandled)return}let result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));if(result){let render=this.applyMouseDispatchResult(event,result);type==="press"&&(this.clearTextSelection(),this.mousePressTarget=result.target,this.mousePressPoint={x:raw.x,y:raw.y},this.mousePressMoved=!1),render&&this.requestRender();return}this.handleRightClickPaste(raw)||this.handleSelectionMouseEvent(raw)}parseWheelEvent(data){return parseWheelEvent(data)}routeWheel(event,delta){let remaining=delta,seen=new Set;for(let scrollView of this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y):[])if(seen.add(scrollView),remaining=scrollView.scrollBy(remaining),remaining===0||scrollView.overscroll==="contain")break;let primary=this.getPrimaryScrollView();remaining!==0&&!seen.has(primary)&&primary.scrollBy(remaining),this.updateScrollbarHover(event.x,event.y),this.requestRender()}parseSgrMouseEvent(data){return parseSgrMouseEvent(data)}handleRightClickPaste(event){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.TERM_PROGRAM?.toLowerCase()==="vscode"||event.release||event.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(event){let rect=this.scrollToEndIndicatorRect;return!rect||event.release||(event.button&32)!==0||(event.button&3)!==0||event.y!==rect.row||event.x<rect.column||event.x>=rect.column+rect.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(x2,y2,includeHiddenAuto=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let scrollView of getScrollViewsAt(this.currentLayout,x2,y2)){let box=getScrollViewBox(this.currentLayout,scrollView),geometry=box?getScrollbarGeometry(box,includeHiddenAuto):void 0;if(geometry&&x2===geometry.column&&y2>=geometry.trackTop&&y2<geometry.trackTop+geometry.trackHeight)return{scrollView,geometry}}}setScrollbarHover(scrollView){scrollView!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=scrollView,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(x2,y2){this.setScrollbarHover(this.getScrollbarTargetAt(x2,y2,!0)?.scrollView)}stopScrollbarHover(){this.setScrollbarHover(void 0)}scrollScrollbarToPointer(scrollView,geometry,pointerY,grabOffset){let maxThumbOffset=geometry.trackHeight-geometry.thumbHeight,thumbOffset=Math.max(0,Math.min(maxThumbOffset,pointerY-geometry.trackTop-grabOffset)),scrollTop=maxThumbOffset===0?0:Math.round(thumbOffset/maxThumbOffset*geometry.maxScrollTop);scrollView.scrollTo(scrollTop)}handleScrollbarMouseEvent(event){if(this.scrollbarDrag){if(event.release)return this.stopScrollbarDrag(),!0;let box=this.currentLayout?getScrollViewBox(this.currentLayout,this.scrollbarDrag.scrollView):void 0,geometry=box?getScrollbarGeometry(box):void 0;return geometry&&this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView,geometry,event.y,this.scrollbarDrag.grabOffset),!0}if(event.release||(event.button&32)!==0||(event.button&3)!==0)return!1;let target=this.getScrollbarTargetAt(event.x,event.y);if(!target)return!1;this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.setScrollbarHover(target.scrollView);let onThumb=event.y>=target.geometry.thumbTop&&event.y<target.geometry.thumbTop+target.geometry.thumbHeight,grabOffset=onThumb?event.y-target.geometry.thumbTop:Math.floor(target.geometry.thumbHeight/2);return onThumb||this.scrollScrollbarToPointer(target.scrollView,target.geometry,event.y,grabOffset),this.scrollbarDrag={scrollView:target.scrollView,grabOffset},!0}stopScrollbarDrag(){this.scrollbarDrag=void 0}getScrollSelectionPoint(scrollView,x2,y2){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0)return;let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(visibleBottom<visibleTop)return;let pointerRow=Math.max(visibleTop,Math.min(visibleBottom,y2)),maxContentRow=Math.max(0,(box.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(maxContentRow,scrollView.scrollTop+pointerRow-box.rect.y)),col:Math.max(0,Math.min(box.rect.width-1,x2-box.rect.x)),scrollView}}getSelectionPoint(event,scrollView){if(scrollView){let point=this.getScrollSelectionPoint(scrollView,event.x,event.y);if(point)return point}return{row:Math.max(0,Math.min(this.terminal.rows-1,event.y)),col:Math.max(0,Math.min(this.terminal.columns-1,event.x))}}getSelectionSourceLine(point){if(point.scrollView&&this.currentLayout){let lines=getScrollViewBox(this.currentLayout,point.scrollView)?.scrollContentLines;if(lines)return lines[point.row]??""}return this.previousScreen[point.row]??""}getWordSelection(point){let line=stripTerminalSequences(this.getSelectionSourceLine(point)),segments=[],start=0;for(let segment of wordSegmenter3.segment(line)){let end=start+visibleWidth(segment.segment),joiner=TERMINAL_WORD_SELECTION_JOINERS.has(segment.segment);segments.push({start,end,selectable:segment.isWordLike===!0||joiner,joiner}),start=end}let clickedSegmentIndex=segments.findIndex(segment=>point.col>=segment.start&&point.col<segment.end);if(clickedSegmentIndex<0)return;let canJoin=(left,right)=>left.selectable&&right.selectable&&(left.joiner||right.joiner),selectionStart=segments[clickedSegmentIndex].start,selectionEnd=segments[clickedSegmentIndex].end;for(let index=clickedSegmentIndex;index>0&&canJoin(segments[index-1],segments[index]);index--)selectionStart=segments[index-1].start;for(let index=clickedSegmentIndex;index<segments.length-1&&canJoin(segments[index],segments[index+1]);index++)selectionEnd=segments[index+1].end;return{start:{...point,col:selectionStart},end:{...point,col:selectionEnd,boundary:!0}}}getLineSelection(point){return{start:{...point,col:0},end:{...point,col:visibleWidth(this.getSelectionSourceLine(point)),boundary:!0}}}updateSelectionFocus(point){if(this.selectionGranularity==="character"||!this.selectionInitialRange){this.selectionFocus=point;return}let range=this.selectionGranularity==="word"?this.getWordSelection(point):this.getLineSelection(point);if(!range)return;let initial=this.selectionInitialRange;range.start.row<initial.start.row||range.start.row===initial.start.row&&range.start.col<initial.start.col?(this.selectionAnchor=initial.end,this.selectionFocus=range.start):(this.selectionAnchor=initial.start,this.selectionFocus=range.end)}getClickCount(point,word){let now=Date.now(),previous=this.lastClick,count=word&&previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.row===point.row&&previous.scrollView===point.scrollView&&previous.wordStart===word.start.col&&previous.wordEnd===word.end.col?previous.count%3+1:1;return this.lastClick=word?{timestamp:now,count,row:point.row,scrollView:point.scrollView,wordStart:word.start.col,wordEnd:word.end.col}:void 0,count}updateSelectionAutoScroll(event){let scrollView=this.selectionAnchor?.scrollView;if(!scrollView||!this.currentLayout){this.stopSelectionAutoScroll();return}let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0){this.stopSelectionAutoScroll();return}let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(this.selectionDragPointer={x:event.x,y:event.y},this.selectionAutoScrollDirection=event.y<=visibleTop?-1:event.y>=visibleBottom?1:0,this.selectionAutoScrollDirection===0){this.stopSelectionAutoScroll();return}this.selectionAutoScrollTimer||(this.selectionAutoScrollTimer=setInterval(()=>this.autoScrollSelection(),50),this.selectionAutoScrollTimer.unref())}autoScrollSelection(){let scrollView=this.selectionAnchor?.scrollView,pointer=this.selectionDragPointer,direction=this.selectionAutoScrollDirection;if(!scrollView||!pointer||direction===0){this.stopSelectionAutoScroll();return}if(scrollView.scrollBy(direction)===direction){this.stopSelectionAutoScroll();return}let point=this.getScrollSelectionPoint(scrollView,pointer.x,pointer.y);point&&this.updateSelectionFocus(point),this.requestRender()}stopSelectionAutoScroll(){this.selectionAutoScrollTimer&&(clearInterval(this.selectionAutoScrollTimer),this.selectionAutoScrollTimer=void 0),this.selectionAutoScrollDirection=0,this.selectionDragPointer=void 0}handleSelectionMouseEvent(event){let button=event.button&3;if(button!==0&&!(event.release&&button===3))return;let anchorScrollView=this.selectionAnchor?.scrollView,point=this.getSelectionPoint(event,anchorScrollView);if(event.release){if(!this.selectionPressActive||(this.selectionPressActive=!1,this.stopSelectionAutoScroll(),!this.selectionAnchor))return;this.updateSelectionFocus(point);let isClick=!this.selectionDragged&&this.selectionAnchor.scrollView===point.scrollView&&this.selectionAnchor.row===point.row&&this.selectionAnchor.col===point.col,clickedUrl=isClick?this.pressedUrl:void 0;if(this.pressedUrl=void 0,clickedUrl&&this.openUrl){this.selectionAnchor=void 0,this.selectionFocus=void 0;try{this.openUrl(clickedUrl)}catch{}this.requestRender();return}if(isClick){let clickEvent=this.createMouseEvent("click",event.button,event.x,event.y,{clickCount:this.lastClick?.count??1}),overlay=this.dispatchMouseToOverlay(clickEvent),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(clickEvent));if(result){let render=this.applyMouseDispatchResult(clickEvent,result);this.clearTextSelection(),render&&this.requestRender();return}}this.copyOnSelect&&this.copySelectionToClipboard(),this.requestRender();return}if((event.button&32)!==0){if(!this.selectionPressActive||!this.selectionAnchor)return;this.selectionDragged=!0,this.lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(point),this.updateSelectionAutoScroll(event),this.requestRender();return}this.stopSelectionAutoScroll(),this.selectionPressActive=!0;let scrollView=!this.hasOverlay()&&this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y)[0]:void 0,anchor=this.getSelectionPoint(event,scrollView),word=this.getWordSelection(anchor),clickCount=this.getClickCount(anchor,word),range=clickCount===2?word:clickCount===3?this.getLineSelection(anchor):void 0;this.selectionGranularity=range?clickCount===2?"word":"line":"character",this.selectionInitialRange=range,this.selectionAnchor=range?.start??anchor,this.selectionFocus=range?.end??anchor,this.selectionDragged=!1,this.pressedUrl=range?void 0:getOsc8LinkAtColumn(this.previousScreen[Math.max(0,Math.min(this.terminal.rows-1,event.y))]??"",Math.max(0,Math.min(this.terminal.columns-1,event.x))),this.requestRender()}getSelectionBounds(){if(!this.selectionAnchor||!this.selectionFocus||this.selectionAnchor.scrollView!==this.selectionFocus.scrollView)return;let anchorBeforeFocus=this.selectionAnchor.row<this.selectionFocus.row||this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col<this.selectionFocus.col;if(!(this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col===this.selectionFocus.col))return anchorBeforeFocus?{start:this.selectionAnchor,end:this.selectionFocus}:{start:this.selectionFocus,end:this.selectionAnchor}}getSelectionColumns(line,row,selection,minColumn=0,maxColumn=visibleWidth(line)){let lineWidth=visibleWidth(line),start=Math.max(0,minColumn),end=Math.min(lineWidth,maxColumn);return row===selection.start.row&&(start=getGraphemeCellRange(line,selection.start.col)?.start??Math.min(selection.start.col,lineWidth)),row===selection.end.row&&(end=selection.end.boundary?Math.min(selection.end.col,lineWidth):getGraphemeCellRange(line,selection.end.col)?.end??Math.min(selection.end.col+1,lineWidth)),{start:Math.max(minColumn,start),end:Math.min(maxColumn,end)}}getActiveSelectionText(){this.selectionSourceUnavailable=!1;let selection=this.getSelectionBounds();if(!selection)return;let sourceLines=this.previousScreen;if(selection.start.scrollView){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,selection.start.scrollView);if(!box?.scrollContentLines)return;sourceLines=box.scrollContentLines}let rows=[];for(let row=selection.start.row;row<=selection.end.row;row++)rows.push({row,...this.getSelectionColumns(sourceLines[row]??"",row,selection)});let original=resolveSourceSelection(sourceLines,rows);if(original&&"unavailable"in original){this.selectionSourceUnavailable=!0;return}if(original&&"text"in original)return original.text||void 0;let lines=[];for(let row=selection.start.row;row<=selection.end.row;row++){let line=sourceLines[row]??"",columns=this.getSelectionColumns(line,row,selection);lines.push(stripTerminalSequences(sliceByColumn(line,columns.start,Math.max(0,columns.end-columns.start),!0)).trimEnd())}let text=lines.join(`
`);return text.length===0?void 0:text}async copySelectionToClipboard(){let text=this.getActiveSelectionText();return this.selectionSourceUnavailable?(this.flash("Original source unavailable for this selection",COPY_ERROR_FLASH_DURATION_MS),!1):text?this.copyTextToClipboard(text):!1}async copyTextToClipboard(text){if(this.copySelection){let result=await this.copySelection(text),ok=result===!0;return this.flash(ok?"Copied!":typeof result=="string"?result:"Copy failed",ok?void 0:COPY_ERROR_FLASH_DURATION_MS),ok}return this.terminal.write(`\x1B]52;c;${Buffer.from(text).toString("base64")}\x07`),this.flash("Copied!"),!0}applySearchTextHighlight(text,current){let style=current?this.searchCurrentMatchStyle:this.searchMatchStyle,result="",plainStart=0,index=0;for(;index<text.length;){let ansi=extractAnsiCode(text,index);if(!ansi){index+=1;continue}index>plainStart&&(result+=style(text.slice(plainStart,index))),result+=ansi.code,index+=ansi.length,plainStart=index}return plainStart<text.length&&(result+=style(text.slice(plainStart))),result}applySearchHighlights(screen,layout){let search=this.activeSearch;if(!search||search.selectedIndex<0||search.matches.length===0)return screen;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView);if(!box)return screen;let rangesByRow=new Map,scrollbarColumn=getScrollbarGeometry(box)?.column,minRow=Math.max(0,box.rect.y,box.clip.y),maxRow=Math.min(screen.length,box.rect.y+box.rect.height,box.clip.y+box.clip.height),minColumn=Math.max(0,box.rect.x,box.clip.x),maxColumn=Math.min(this.terminal.columns,box.rect.x+box.rect.width,box.clip.x+box.clip.width,scrollbarColumn??Number.POSITIVE_INFINITY),minContentRow=scrollView.scrollTop+minRow-box.rect.y,maxContentRow=scrollView.scrollTop+maxRow-box.rect.y-1,low=0,high=search.matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2),match=search.matches[middle];(match.segments[match.segments.length-1]?.row??-1)<minContentRow?low=middle+1:high=middle}for(let matchIndex=low;matchIndex<search.matches.length;matchIndex++){let match=search.matches[matchIndex];if((match.segments[0]?.row??0)>maxContentRow)break;for(let segment of match.segments){let row=box.rect.y+segment.row-scrollView.scrollTop;if(row<minRow||row>=maxRow)continue;let startCol=Math.max(minColumn,box.rect.x+segment.startCol),endCol=Math.min(maxColumn,box.rect.x+segment.endCol);if(endCol<=startCol)continue;let ranges=rangesByRow.get(row)??[];ranges.push({startCol,endCol,current:matchIndex===search.selectedIndex}),rangesByRow.set(row,ranges)}}let result=[...screen];for(let[row,ranges]of rangesByRow){let line=result[row]??"";if(isImageLine(line))continue;let lineWidth=visibleWidth(line);for(let range of ranges.sort((a,b2)=>b2.startCol-a.startCol)){let startCol=Math.min(range.startCol,lineWidth),endCol=Math.min(range.endCol,lineWidth);if(endCol<=startCol)continue;let before=sliceByColumn(line,0,startCol,!0),highlighted=sliceByColumn(line,startCol,endCol-startCol,!0),after=sliceByColumn(line,endCol,Math.max(0,lineWidth-endCol),!0);line=`${before}${this.applySearchTextHighlight(highlighted,range.current)}${after}`}result[row]=line}return result}applySelectionHighlight(text){let result="\x1B[7m",index=0;for(;index<text.length;){let ansi=extractAnsiCode(text,index);if(!ansi){result+=text[index],index+=1;continue}result+=ansi.code,ansi.code.endsWith("m")&&(result+="\x1B[7m"),index+=ansi.length}return`${result}\x1B[27m`}applySelection(screen,layout=this.currentLayout){let selection=this.getSelectionBounds();if(!selection)return screen;let screenSelection=selection,minRow=0,maxRow=screen.length-1,minColumn=0,maxColumn=this.terminal.columns;if(selection.start.scrollView){if(!layout)return screen;let box=getScrollViewBox(layout,selection.start.scrollView);if(!box)return screen;minRow=Math.max(0,box.rect.y,box.clip.y),maxRow=Math.min(screen.length-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1),minColumn=Math.max(0,box.rect.x,box.clip.x),maxColumn=Math.min(this.terminal.columns,box.rect.x+box.rect.width,box.clip.x+box.clip.width),screenSelection={start:{...selection.start,row:box.rect.y+selection.start.row-selection.start.scrollView.scrollTop,col:box.rect.x+selection.start.col},end:{...selection.end,row:box.rect.y+selection.end.row-selection.start.scrollView.scrollTop,col:box.rect.x+selection.end.col}}}return screen.map((line,row)=>{if(row<minRow||row>maxRow||row<screenSelection.start.row||row>screenSelection.end.row||isImageLine(line))return line;let lineWidth=visibleWidth(line),columns=this.getSelectionColumns(line,row,screenSelection,minColumn,maxColumn);if(columns.end<=columns.start)return line;let before=sliceByColumn(line,0,columns.start,!0),selected=sliceByColumn(line,columns.start,columns.end-columns.start,!0),after=sliceByColumn(line,columns.end,Math.max(0,lineWidth-columns.end),!0);return`${before}${this.applySelectionHighlight(selected)}${after}`})}isMouseSequence(data){return isMouseSequence(data)}compositeScrollToEndIndicator(screen,layout,width){this.scrollToEndIndicatorRect=void 0;let scrollView=layout.primaryScrollView??this.implicitScrollView;if(!this.scrollToEndIndicator||!scrollView.followEnd||scrollView.isFollowingEnd)return screen;let box=getScrollViewBox(layout,scrollView),clip=box?.clip;if(!clip||clip.width<=0||clip.height<=0)return screen;let row=clip.y+clip.height-1;if(row>=screen.length||isImageLine(screen[row]??""))return screen;let scrollbarColumn=box?getScrollbarGeometry(box)?.column:void 0,label=truncateToWidth(this.scrollToEndIndicator(),clip.width,""),labelWidth=visibleWidth(label),column=clip.x+Math.floor((clip.width-labelWidth)/2),rightEdge=scrollbarColumn??clip.x+clip.width,availableWidth=Math.max(0,rightEdge-column),text=truncateToWidth(label,availableWidth,""),textWidth=visibleWidth(text);if(textWidth===0)return screen;let result=[...screen];return result[row]=compositeTuiLine(result[row]??"",text,column,textWidth,width),this.scrollToEndIndicatorRect={row,column,width:textWidth},result}compositeFlashes(screen,width,height){let flashLines=this.flashes.render(width).slice(-height);if(flashLines.length===0)return screen;let result=[...screen];for(;result.length<height;)result.push("");for(let row=0;row<flashLines.length;row++){let line=flashLines[row],flashWidth=visibleWidth(line);flashWidth!==0&&(result[row]=compositeTuiLine(result[row]??"",line,width-flashWidth,flashWidth,width))}return result}doRender(){if(this.stopped||!this.altScreenActive)return;let width=Math.max(1,this.terminal.columns),height=Math.max(1,this.terminal.rows),root=this.layoutRoot??this.implicitScrollView,nextLayout=renderLayoutFrame(root,width,height,()=>this.requestRender());this.refreshSearch(nextLayout)&&(nextLayout=renderLayoutFrame(root,width,height,()=>this.requestRender()));let screen=nextLayout.lines.map(line=>line.replace(OSC133_ZONE_PREFIX2,""));screen=this.applySearchHighlights(screen,nextLayout),screen=this.compositeScrollToEndIndicator(screen,nextLayout,width),screen=this.compositeOverlays(screen,width,height),screen.length>height&&(screen=screen.slice(screen.length-height)),screen=this.applySelection(screen,nextLayout),screen=this.compositeFlashes(screen,width,height);let cursorPos=this.extractCursorPosition(screen,height);screen=this.applyLineResets(screen).map(line=>isImageLine(line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));let fullRedraw=this.previousScreen.length===0||this.previousScreenWidth!==width||this.previousScreenHeight!==height,imagesNeedRedraw=screen.some((line,row)=>line!==this.previousScreen[row]&&(isImageLine(line)||isImageLine(this.previousScreen[row]??""))),redrawImages=fullRedraw||imagesNeedRedraw,hadUploadedKittyImages=this.uploadedKittyImages.size>0,preparedKittyScreen=redrawImages&&this.imageProtocol==="kitty"?this.prepareKittyScreen(screen):{lines:screen,evictedImageDeletion:""},buffer=BEGIN_SYNCHRONIZED_OUTPUT;if(fullRedraw){this.fullRedrawCount+=1;let clearImages=this.imageProtocol==="kitty"&&hadUploadedKittyImages?deleteAllKittyPlacements():this.deleteAltScreenKittyImages();buffer+=`${clearImages}\x1B[2J`}else imagesNeedRedraw&&(this.imageProtocol==="iterm2"?buffer+="\x1B[2J":this.imageProtocol==="kitty"&&(buffer+=deleteAllKittyPlacements()));buffer+=preparedKittyScreen.evictedImageDeletion;let clearRowsBeforeKittyImages=redrawImages&&this.imageProtocol==="kitty"&&screen.some(isImageLine)&&(!!process.env.WEZTERM_PANE||process.env.TERM_PROGRAM?.toLowerCase()==="wezterm");if(clearRowsBeforeKittyImages)for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H\x1B[2K`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H${clearRowsBeforeKittyImages?"":"\x1B[2K"}${preparedKittyScreen.lines[row]??""}`);cursorPos?(buffer+=`\x1B[${cursorPos.row+1};${Math.min(width,cursorPos.col)+1}H`,buffer+=this.getShowHardwareCursor()?"\x1B[?25h":"\x1B[?25l"):buffer+="\x1B[?25l",buffer+=END_SYNCHRONIZED_OUTPUT,this.terminal.write(buffer),this.previousScreen=screen,this.previousScreenWidth=width,this.previousScreenHeight=height,this.currentLayout=nextLayout}};var TuiMainScreen=class extends TuiBase{constructor(...args){super(...args),this.mode="regular",this.trackingEnabled=!1,this.yielded=!1,this.clicks=new MouseClickSynthesizer,this.addInputListener(data=>this.handleMouseInput(data))}mouseCaptureState(){return this.yielded?"yielded":this.trackingEnabled?"armed":"off"}applyMouseTracking(enabled){this.yielded=!1;let supported=!!process.stdout.isTTY&&!process.env.TERMUX_VERSION&&(process.platform!=="win32"||!!process.env.WT_SESSION),next=enabled&&supported&&!this.stopped;this.clicks.cancel(),this.mousePress=void 0,this.trackingEnabled!==next&&(this.trackingEnabled=next,this.terminal.write(next?MOUSE_TRACKING.inline:MOUSE_TRACKING.disable))}beforeTerminalStop(){this.terminal.write(MOUSE_TRACKING.disable),this.trackingEnabled=!1,this.yielded=!1,this.clicks.cancel(),this.mousePress=void 0}doRender(){this.stopped||(this.mouseExternalWritePending&&(this.mouseExternalWritePending=!1,this.terminal.write(`\r
`),this.restoreRenderState({previousLines:[],previousWidth:0,previousHeight:0,cursorRow:0,hardwareCursorRow:0,maxLinesRendered:0,previousViewportTop:0})),super.doRender(),this.noteCommittedMouseFrame(),this.calibrateMouseAnchor())}collectMouseComponents(){let components=[],visit=component=>{if(components.push(component),component instanceof Container)for(let child of component.children)visit(child)};for(let root of this.getMouseLayoutRoots())visit(root);return components}pressLayoutUnchanged(press){let lines=this.previousLines;if(press.frame!==lines){if(press.frame.length!==lines.length)return!1;for(let index=0;index<lines.length;index++)if(press.frame[index]!==lines[index])return!1}let components=this.collectMouseComponents();return components.length===press.components.length&&components.every((component,index)=>component===press.components[index])}applyMouseResult(result){if(!result?.focus)return;let target=this.resolveMouseFocusTarget(result.focusTarget??result.target.component);target&&this.setFocus(target)}handleMouseInput(data){if(!isMouseSequence(data))return this.yielded&&!isTerminalReport(data)&&!isKeyRelease(data)&&this.rearmAfterYield(),{consume:!1};let raw=parseSgrMouseEvent(data);if(this.trackingEnabled&&raw&&(raw.button&64)!==0)return this.yieldToTerminal(),{consume:!0};if(!this.trackingEnabled||!raw||raw.button!==0)return this.clicks.cancel(),this.mousePress=void 0,{consume:!0};let frameLine=this.resolveFrameLine(raw.y+1);if(frameLine===void 0||raw.x>=this.terminal.columns)return this.clicks.cancel(),this.mousePress=void 0,{consume:!0};let event=toTuiMouseEvent(raw.release?"release":"press",raw,this.terminal);if(raw.release){let press=this.mousePress;if(this.mousePress=void 0,!press||press.epoch!==this.placementEpoch||!this.pressLayoutUnchanged(press)||press.x!==raw.x||press.y!==raw.y)return this.clicks.cancel(),{consume:!0};let count=this.clicks.release(raw,press.target.component,this.placementEpoch);if(count!==void 0){let click={...event,type:"click",clickCount:count},focusBeforeClick=this.getFocusedComponent(),clickResult=dispatchMouseEvent(press.target.component,retargetMouseEvent(click,press.target));this.getFocusedComponent()===focusBeforeClick&&this.applyMouseResult(clickResult),this.requestRender()}}else{let overlay=this.dispatchMouseToOverlay(event),result=overlay.result??(overlay.hit?void 0:dispatchMouseEvent(this,{...event,y:frameLine,height:this.previousLines.length}));this.mousePress=void 0,result?(this.applyMouseResult(result),this.mousePress={target:result.target,epoch:this.placementEpoch,frame:this.previousLines,components:this.collectMouseComponents(),x:raw.x,y:raw.y},this.clicks.press(raw,result.target.component,this.placementEpoch)):this.clicks.cancel(),this.requestRender()}return{consume:!0}}yieldToTerminal(){this.terminal.write(MOUSE_TRACKING.disable),this.trackingEnabled=!1,this.yielded=!0,this.clicks.cancel(),this.mousePress=void 0,this.requestRender()}rearmAfterYield(){if(!this.mouseCaptureEnabled){this.yielded=!1;return}this.applyMouseTracking(!0),this.requestRender()}captureRenderState(){return{previousLines:[...this.previousLines],previousWidth:this.previousWidth,previousHeight:this.previousHeight,cursorRow:this.cursorRow,hardwareCursorRow:this.hardwareCursorRow,maxLinesRendered:this.maxLinesRendered,previousViewportTop:this.previousViewportTop}}restoreRenderState(state){this.previousLines=state.previousLines.map(line=>isImageLine(line)?"":line),this.previousKittyImageIds=new Set,this.previousWidth=state.previousWidth,this.previousHeight=state.previousHeight,this.cursorRow=state.cursorRow,this.hardwareCursorRow=state.hardwareCursorRow,this.maxLinesRendered=state.maxLinesRendered,this.previousViewportTop=state.previousViewportTop}};var dist_exports={};__export(dist_exports,{AltScreenSearchComponent:()=>AltScreenSearchComponent,Box:()=>Box,CURSOR_MARKER:()=>CURSOR_MARKER,CancellableLoader:()=>CancellableLoader,CombinedAutocompleteProvider:()=>CombinedAutocompleteProvider,CompositeRevision:()=>CompositeRevision,Container:()=>Container,Editor:()=>Editor,HStack:()=>HStack,IMAGE_MARKER_REGEX:()=>IMAGE_MARKER_REGEX,IMAGE_MARKER_SINGLE:()=>IMAGE_MARKER_SINGLE,Image:()=>Image,ImageMarkerRegistry:()=>ImageMarkerRegistry,Input:()=>Input,KITTY_PLACEHOLDER_MAX:()=>KITTY_PLACEHOLDER_MAX,Key:()=>Key,KeybindingsManager:()=>KeybindingsManager,Loader:()=>Loader,MOUSE_TRACKING:()=>MOUSE_TRACKING,Markdown:()=>Markdown,Marked:()=>Q,MouseClickSynthesizer:()=>MouseClickSynthesizer,MouseRegion:()=>MouseRegion,ProcessTerminal:()=>ProcessTerminal,ScrollView:()=>ScrollView,SelectList:()=>SelectList,SettingsList:()=>SettingsList,Spacer:()=>Spacer,StdinBuffer:()=>StdinBuffer,TUI:()=>TUI,TUI_KEYBINDINGS:()=>TUI_KEYBINDINGS,Text:()=>Text,TruncatedText:()=>TruncatedText,TuiAltScreen:()=>TuiAltScreen,TuiMainScreen:()=>TuiMainScreen,VStack:()=>VStack,allocateImageId:()=>allocateImageId,backgroundAnsi:()=>backgroundAnsi,buildKittyPlaceholderRow:()=>buildKittyPlaceholderRow,calculateImageRows:()=>calculateImageRows,claimFrameRow:()=>claimFrameRow,clearRenderCache:()=>clearRenderCache,colorToHex:()=>colorToHex,colorToOkhsl:()=>colorToOkhsl,colorToOklch:()=>colorToOklch,colorToRgb:()=>colorToRgb,compositeTuiLine:()=>compositeTuiLine,copyLineSources:()=>copyLineSources,currentRenderRevision:()=>currentRenderRevision,decodeKittyPrintable:()=>decodeKittyPrintable,decodeMouseButton:()=>decodeMouseButton,deleteAllKittyImages:()=>deleteAllKittyImages,deleteKittyImage:()=>deleteKittyImage,detectCapabilities:()=>detectCapabilities,dispatchMouseEvent:()=>dispatchMouseEvent,encodeITerm2:()=>encodeITerm2,encodeKitty:()=>encodeKitty,encodeProgramStatus:()=>encodeProgramStatus,expandPasteMarkers:()=>expandPasteMarkers,findAltScreenSearchMatches:()=>findAltScreenSearchMatches,foregroundAnsi:()=>foregroundAnsi,formatImageMarker:()=>formatImageMarker,frameLineBytesTotals:()=>frameLineBytesTotals,frameMode:()=>frameMode,frameScrollbackRows:()=>frameScrollbackRows,fuzzyFilter:()=>fuzzyFilter,fuzzyMatch:()=>fuzzyMatch,fuzzyMatchLower:()=>fuzzyMatchLower,getAltScreenSearchMatchKey:()=>getAltScreenSearchMatchKey,getCapabilities:()=>getCapabilities,getCellDimensions:()=>getCellDimensions,getGifDimensions:()=>getGifDimensions,getGraphemeSegmenter:()=>getGraphemeSegmenter,getImageDimensions:()=>getImageDimensions,getJpegDimensions:()=>getJpegDimensions,getKeybindings:()=>getKeybindings,getMarkdownHighlightCallCount:()=>getMarkdownHighlightCallCount,getNativeClipboard:()=>getNativeClipboard,getOsc8LinkAtColumn:()=>getOsc8LinkAtColumn,getPngDimensions:()=>getPngDimensions,getTerminalColorMode:()=>getTerminalColorMode,getWebpDimensions:()=>getWebpDimensions,getWordSegmenter:()=>getWordSegmenter,hyperlink:()=>hyperlink,imageFallback:()=>imageFallback,imageMarkerId:()=>imageMarkerId,indexedColor:()=>indexedColor,isAppleTerminalSession:()=>isAppleTerminalSession,isFocusable:()=>isFocusable,isImageMarker:()=>isImageMarker,isKeyRelease:()=>isKeyRelease,isKeyRepeat:()=>isKeyRepeat,isKittyProtocolActive:()=>isKittyProtocolActive,isMouseSequence:()=>isMouseSequence,isViewportTUI:()=>isViewportTUI,isWarpWslSession:()=>isWarpWslSession,joinLineArrays:()=>joinLineArrays,mainScreenHistoryLines:()=>mainScreenHistoryLines,matchesKey:()=>matchesKey,mixColors:()=>mixColors,nextRenderRevision:()=>nextRenderRevision,okhslColor:()=>okhslColor,oklabToOkhslLightness:()=>oklabToOkhslLightness,oklchColor:()=>oklchColor,outerKittyGraphicsMode:()=>outerKittyGraphicsMode,parseColor:()=>parseColor,parseKey:()=>parseKey,parseSgrMouseEvent:()=>parseSgrMouseEvent,parseTerminalColorSchemeReport:()=>parseTerminalColorSchemeReport,parseWheelEvent:()=>parseWheelEvent,renderAtFrameRow:()=>renderAtFrameRow,renderImage:()=>renderImage,resetCapabilitiesCache:()=>resetCapabilitiesCache,resetMainScreenHistoryLines:()=>resetMainScreenHistoryLines,resetMarkdownHighlightCallCount:()=>resetMarkdownHighlightCallCount,rgbColor:()=>rgbColor,sanitizeTerminalLabel:()=>sanitizeTerminalLabel,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,setKeybindings:()=>setKeybindings,setKittyProtocolActive:()=>setKittyProtocolActive,shortenImagePath:()=>shortenImagePath,sliceByColumn:()=>sliceByColumn,stripTerminalSequences:()=>stripTerminalSequences,styleText:()=>styleText,styleTextWithAnsi:()=>styleTextWithAnsi,toTuiMouseEvent:()=>toTuiMouseEvent,truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi,wrapTmuxPassthrough:()=>wrapTmuxPassthrough});var multiply=(m2,[x2,y2,z])=>m2.map(row=>row[0]*x2+row[1]*y2+row[2]*z),LINEAR_SRGB_TO_LMS=[[.4122214694707629,.5363325372617349,.0514459932675022],[.2119034958178251,.6806995506452344,.1073969535369405],[.0883024591900564,.2817188391361215,.6299787016738222]],LMS_TO_LAB=[[.210454268309314,.793617774702305,-.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-.8086757549230774]],LAB_TO_LMS=[[1,.3963377773761749,.2158037573099136],[1,-.1055613458156586,-.0638541728258133],[1,-.0894841775298119,-1.2914855480194092]],LMS_TO_LINEAR_SRGB=[[4.076741636075958,-3.307711539258063,.2309699031821043],[-1.2684379732850315,2.609757349287688,-.341319376002657],[-.0041960761386756,-.7034186179359362,1.7076146940746117]],SATURATION_FIT=[[[-1.8817031,-.80936501],[1.19086277,1.76576728,.59662641,.75515197,.56771245]],[[1.8144408,-1.19445267],[.73956515,-.45954404,.08285427,.12541073,-.14503204]],[[.13110758,1.81333971],[1.35733652,-.00915799,-1.1513021,-.50559606,.00692167]]],K1=.206,K2=.03,K3=(1+K1)/(1+K2),oklabToOkhslLightness=x2=>.5*(K3*x2-K1+Math.sqrt((K3*x2-K1)**2+4*K2*K3*x2)),okhslToOklabLightness=x2=>(x2*x2+K1*x2)/(K3*(x2+K2)),linearToSrgb=value=>value>.0031308?1.055*value**(1/2.4)-.055:12.92*value,srgbToLinear=value=>value<=.04045?value/12.92:((value+.055)/1.055)**2.4;function oklabToLinearSrgb(lab){return multiply(LMS_TO_LINEAR_SRGB,multiply(LAB_TO_LMS,lab).map(value=>value**3))}function linearSrgbToOklab(rgb){return multiply(LMS_TO_LAB,multiply(LINEAR_SRGB_TO_LMS,rgb).map(Math.cbrt))}function rgbToOklab({r,g,b:b2}){return linearSrgbToOklab([r/255,g/255,b2/255].map(srgbToLinear))}function linearSrgbToRgb(linear){let[r,g,b2]=linear.map(value=>Math.round(Math.min(1,Math.max(0,linearToSrgb(value)))*255));return{r,g,b:b2}}function lmsSlopes(a,b2){return[LAB_TO_LMS[0],LAB_TO_LMS[1],LAB_TO_LMS[2]].map(row=>row[1]*a+row[2]*b2)}function maxSaturation(a,b2){let channel=SATURATION_FIT.findIndex(([[x2,y2]],index)=>index===2||x2*a+y2*b2>1),[k0,k1,k2,k3,k4]=SATURATION_FIT[channel][1],weights=LMS_TO_LINEAR_SRGB[channel],saturation=k0+k1*a+k2*b2+k3*a*a+k4*a*b2,slopes=lmsSlopes(a,b2),base=slopes.map(k=>1+saturation*k),dot=values=>values.reduce((sum,value,index)=>sum+weights[index]*value,0),f2=dot(base.map(value=>value**3)),f1=dot(base.map((value,index)=>3*slopes[index]*value**2)),f22=dot(base.map((value,index)=>6*slopes[index]**2*value));return saturation-f2*f1/(f1*f1-.5*f2*f22)}function cusp(a,b2){let saturation=maxSaturation(a,b2),lightness=Math.cbrt(1/Math.max(...oklabToLinearSrgb([1,saturation*a,saturation*b2])));return[lightness,lightness*saturation]}function maxChroma(a,b2,lightness,[cuspL,cuspC]){if(lightness<=cuspL)return cuspC*lightness/cuspL;let t=cuspC*(lightness-1)/(cuspL-1),slopes=lmsSlopes(a,b2),lms=slopes.map(k=>lightness+t*k),cubes=lms.map(value=>value**3),first=lms.map((value,index)=>3*slopes[index]*value**2),second=lms.map((value,index)=>6*slopes[index]**2*value),dot=(row,values)=>row[0]*values[0]+row[1]*values[1]+row[2]*values[2],steps=LMS_TO_LINEAR_SRGB.map(row=>{let f2=dot(row,cubes)-1,f1=dot(row,first),f22=dot(row,second),u=f1/(f1*f1-.5*f2*f22);return u>=0?-f2*u:Number.MAX_VALUE});return t+Math.min(...steps)}function chromaStops(L2,a,b2){let peak=cusp(a,b2),cMax=maxChroma(a,b2,L2,peak),k=cMax/Math.min(L2*(peak[1]/peak[0]),(1-L2)*(peak[1]/(1-peak[0]))),midS=.11516993+1/(7.4477897+4.1590124*b2+a*(-2.19557347+1.75198401*b2+a*(-2.13704948-10.02301043*b2+a*(-4.24894561+5.38770819*b2+4.69891013*a)))),midT=.11239642+1/(1.6132032-.68124379*b2+a*(.40370612+.90148123*b2+a*(-.27087943+.6122399*b2+a*(.00299215-.45399568*b2-.14661872*a)))),cMid=.9*k*Math.sqrt(Math.sqrt(1/(1/(L2*midS)**4+1/((1-L2)*midT)**4)));return[Math.sqrt(1/(1/(L2*.4)**2+1/((1-L2)*.8)**2)),cMid,cMax]}function okhslToRgb(hue,saturation,lightness){let L2=okhslToOklabLightness(lightness),lab=[L2,0,0];if(L2>0&&L2<1&&saturation>0){let angle=2*Math.PI*((hue%360+360)%360)/360,a=Math.cos(angle),b2=Math.sin(angle),[c0,cMid,cMax]=chromaStops(L2,a,b2),chroma;if(saturation<.8){let t=1.25*saturation,k1=.8*c0;chroma=t*k1/(1-(1-k1/cMid)*t)}else{let t=5*(saturation-.8),k1=.2*cMid**2*1.25**2/c0;chroma=cMid+t*k1/(1-(1-k1/(cMax-cMid))*t)}lab=[L2,chroma*a,chroma*b2]}return linearSrgbToRgb(oklabToLinearSrgb(lab))}function rgbToOkhsl(rgb){let[L2,labA,labB]=rgbToOklab(rgb),chroma=Math.hypot(labA,labB),lightness=oklabToOkhslLightness(L2);if(chroma<1e-9||lightness<=0||lightness>=1)return{h:0,s:0,l:lightness};let hue=(Math.atan2(labB,labA)*180/Math.PI+360)%360,[c0,cMid,cMax]=chromaStops(L2,labA/chroma,labB/chroma),saturation;if(chroma<cMid){let k1=.8*c0;saturation=.8*(chroma/(k1+(1-k1/cMid)*chroma))}else{let k1=.2*cMid**2*1.5625/c0,offset=chroma-cMid;saturation=.8+.2*(offset/(k1+(1-k1/(cMax-cMid))*offset))}return{h:hue,s:Math.min(1,Math.max(0,saturation)),l:lightness}}function requireFinite(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function indexedColor(index){if(!Number.isInteger(index)||index<0||index>255)throw new Error(`ANSI color index must be an integer from 0 to 255: ${index}`);return Object.freeze({kind:"indexed",index})}function rgbColor(r,g,b2){for(let[name,value]of[["r",r],["g",g],["b",b2]])if(requireFinite(value,name),value<0||value>255)throw new Error(`${name} must be between 0 and 255: ${value}`);return Object.freeze({kind:"rgb",r,g,b:b2})}function oklchColor(l3,c,h){if(requireFinite(l3,"l"),requireFinite(c,"c"),requireFinite(h,"h"),l3<0||l3>1)throw new Error(`l must be between 0 and 1: ${l3}`);if(c<0)throw new Error(`c must not be negative: ${c}`);return Object.freeze({kind:"oklch",l:l3,c,h:(h%360+360)%360})}var NUMBER_PATTERN=String.raw`[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?`,OKLCH_PATTERN=new RegExp(`^oklch\\(\\s*(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})\\s+(${NUMBER_PATTERN})(?:deg)?\\s*\\)$`,"i"),OKHSL_PATTERN=new RegExp(`^okhsl\\(\\s*(${NUMBER_PATTERN})(?:deg)?\\s+(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})(%)?\\s*\\)$`,"i");function okhslColor(h,s,l3){if(requireFinite(h,"h"),requireFinite(s,"s"),requireFinite(l3,"l"),s<0||s>1)throw new Error(`s must be between 0 and 1: ${s}`);if(l3<0||l3>1)throw new Error(`l must be between 0 and 1: ${l3}`);let{r,g,b:b2}=okhslToRgb(h,s,l3);return rgbColor(r,g,b2)}function colorToOkhsl(color){return rgbToOkhsl(colorToRgb(color))}function parseColor(value){if(typeof value=="number")return indexedColor(value);let hex=/^#([\da-f]{3}|[\da-f]{6})$/i.exec(value);if(hex){let digits=hex[1].length===3?[...hex[1]].map(digit=>digit+digit).join(""):hex[1];return rgbColor(Number.parseInt(digits.slice(0,2),16),Number.parseInt(digits.slice(2,4),16),Number.parseInt(digits.slice(4,6),16))}let oklch=OKLCH_PATTERN.exec(value);if(oklch){let lightness=Number.parseFloat(oklch[1])/(oklch[2]?100:1);return oklchColor(lightness,Number.parseFloat(oklch[3]),Number.parseFloat(oklch[4]))}let okhsl=OKHSL_PATTERN.exec(value);if(okhsl){let saturation=Number.parseFloat(okhsl[2])/(okhsl[3]?100:1),lightness=Number.parseFloat(okhsl[4])/(okhsl[5]?100:1);return okhslColor(Number.parseFloat(okhsl[1]),saturation,lightness)}throw new Error(`Invalid color value: ${value}`)}var BASIC_COLORS=[{r:0,g:0,b:0},{r:128,g:0,b:0},{r:0,g:128,b:0},{r:128,g:128,b:0},{r:0,g:0,b:128},{r:128,g:0,b:128},{r:0,g:128,b:128},{r:192,g:192,b:192},{r:128,g:128,b:128},{r:255,g:0,b:0},{r:0,g:255,b:0},{r:255,g:255,b:0},{r:0,g:0,b:255},{r:255,g:0,b:255},{r:0,g:255,b:255},{r:255,g:255,b:255}],CUBE_VALUES=[0,95,135,175,215,255],GRAY_VALUES=Array.from({length:24},(_2,index)=>8+index*10);function indexedToRgb(index){if(index<16)return{...BASIC_COLORS[index]};if(index<232){let cubeIndex=index-16;return{r:CUBE_VALUES[Math.floor(cubeIndex/36)],g:CUBE_VALUES[Math.floor(cubeIndex%36/6)],b:CUBE_VALUES[cubeIndex%6]}}let gray=8+(index-232)*10;return{r:gray,g:gray,b:gray}}function isInSrgbGamut(linear){return linear.every(channel=>channel>=-1e-7&&channel<=1+1e-7)}function oklchToRgb({l:l3,c,h}){let radians=h*Math.PI/180,cos=Math.cos(radians),sin=Math.sin(radians),atChroma=chroma=>oklabToLinearSrgb([l3,chroma*cos,chroma*sin]),direct=atChroma(c);if(isInSrgbGamut(direct))return linearSrgbToRgb(direct);let linear=atChroma(0),low=0,high=c;for(let index=0;index<20;index++){let chroma=(low+high)/2,candidate=atChroma(chroma);isInSrgbGamut(candidate)?(low=chroma,linear=candidate):high=chroma}return linearSrgbToRgb(linear)}function colorToRgb(color){switch(color.kind){case"indexed":return indexedToRgb(color.index);case"rgb":return{r:color.r,g:color.g,b:color.b};case"oklch":return oklchToRgb(color)}}function colorToOklch(color){if(color.kind==="oklch")return{l:color.l,c:color.c,h:color.h};let[l3,a,b2]=rgbToOklab(colorToRgb(color));return{l:l3,c:Math.hypot(a,b2),h:(Math.atan2(b2,a)*180/Math.PI+360)%360}}function colorToHex(color){let{r,g,b:b2}=colorToRgb(color),channel=value=>Math.round(value).toString(16).padStart(2,"0");return`#${channel(r)}${channel(g)}${channel(b2)}`}function mixColors(first,second,amount,space="oklch"){if(requireFinite(amount,"amount"),amount<0||amount>1)throw new Error(`amount must be between 0 and 1: ${amount}`);if(space==="srgb"){let a2=colorToRgb(first),b3=colorToRgb(second);return rgbColor(a2.r+(b3.r-a2.r)*amount,a2.g+(b3.g-a2.g)*amount,a2.b+(b3.b-a2.b)*amount)}let a=colorToOklch(first),b2=colorToOklch(second),firstHue=a.c<1e-7?b2.h:a.h,hueDelta=((b2.c<1e-7?firstHue:b2.h)-firstHue+540)%360-180;return oklchColor(a.l+(b2.l-a.l)*amount,a.c+(b2.c-a.c)*amount,firstHue+hueDelta*amount)}function findClosest(values,target){let closestIndex=0,closestDistance=1/0;for(let index=0;index<values.length;index++){let distance=Math.abs(target-values[index]);distance<closestDistance&&(closestIndex=index,closestDistance=distance)}return closestIndex}function colorDistance(first,second){let dr=first.r-second.r,dg=first.g-second.g,db=first.b-second.b;return dr*dr*.299+dg*dg*.587+db*db*.114}function rgbToAnsi256(color){let rIndex=findClosest(CUBE_VALUES,color.r),gIndex=findClosest(CUBE_VALUES,color.g),bIndex=findClosest(CUBE_VALUES,color.b),cubeColor={r:CUBE_VALUES[rIndex],g:CUBE_VALUES[gIndex],b:CUBE_VALUES[bIndex]},cubeIndex=16+36*rIndex+6*gIndex+bIndex,gray=Math.round(.299*color.r+.587*color.g+.114*color.b),grayOffset=findClosest(GRAY_VALUES,gray),grayValue=GRAY_VALUES[grayOffset];return Math.max(color.r,color.g,color.b)-Math.min(color.r,color.g,color.b)<10&&colorDistance(color,{r:grayValue,g:grayValue,b:grayValue})<colorDistance(color,cubeColor)?232+grayOffset:cubeIndex}function colorAnsi(color,mode,background){if(color.kind==="indexed")return`\x1B[${background?48:38};5;${color.index}m`;let rgb=colorToRgb(color);return mode==="truecolor"?`\x1B[${background?48:38};2;${Math.round(rgb.r)};${Math.round(rgb.g)};${Math.round(rgb.b)}m`:`\x1B[${background?48:38};5;${rgbToAnsi256(rgb)}m`}function foregroundAnsi(color,mode){return colorAnsi(color,mode,!1)}function backgroundAnsi(color,mode){return colorAnsi(color,mode,!0)}function styleText(text,options,mode){return styleTextWithAnsi(text,options.fg&&foregroundAnsi(options.fg,mode),options.bg&&backgroundAnsi(options.bg,mode),options)}function styleTextWithAnsi(text,fgAnsi,bgAnsi,options){let prefix="",suffix="";return fgAnsi&&(prefix+=fgAnsi,suffix="\x1B[39m"),bgAnsi&&(prefix+=bgAnsi,suffix=`\x1B[49m${suffix}`),options.bold&&(prefix+="\x1B[1m"),options.dim&&(prefix+="\x1B[2m"),(options.bold||options.dim)&&(suffix=`\x1B[22m${suffix}`),options.italic&&(prefix+="\x1B[3m",suffix=`\x1B[23m${suffix}`),options.underline&&(prefix+="\x1B[4m",suffix=`\x1B[24m${suffix}`),options.inverse&&(prefix+="\x1B[7m",suffix=`\x1B[27m${suffix}`),options.strikethrough&&(prefix+="\x1B[9m",suffix=`\x1B[29m${suffix}`),`${prefix}${text}${suffix}`}var Box=class _Box{constructor(paddingX=1,paddingY=1,bgFn){this.children=[],this.disposed=!1,this.composite=new CompositeRevision,this.paddingX=paddingX,this.paddingY=paddingY,this.bgFn=bgFn}addChild(component){this.children.push(component),this.invalidateCache()}removeChild(component){let index=this.children.indexOf(component);index!==-1&&(this.children.splice(index,1),this.invalidateCache(),component.dispose?.())}clear(){for(let child of this.children)child.dispose?.();this.children=[],this.invalidateCache()}detachAll(){this.children=[],this.invalidateCache()}dispose(){if(!this.disposed){this.disposed=!0;for(let child of this.children)child.dispose?.();this.invalidateCache()}}setBgFn(bgFn){this.bgFn=bgFn,this.composite.bump()}invalidateCache(){this.cache=void 0,this.composite.bump()}matchCache(width,childLines,bgSample){let cache=this.cache;if(!cache||cache.width!==width||cache.bgSample!==bgSample||cache.childLines.length!==childLines.length)return!1;let cachedSources=getLineSources(cache.childLines),nextSources=getLineSources(childLines);return cache.childLines.every((line,i)=>{if(line!==childLines[i])return!1;let before=cachedSources?.[i],after=nextSources?.[i];return before===after?!0:!before||!after?!1:before.document===after.document&&before.ranges===after.ranges&&before.sourceRow===after.sourceRow&&before.columnOffset===after.columnOffset&&before.unavailable===after.unavailable})}invalidate(){this.invalidateCache(),this.composite.bump();for(let child of this.children)child.invalidate?.()}getRenderRevision(){return Object.getPrototypeOf(this)===_Box.prototype?this.childRenderRevision():void 0}childRenderRevision(){return this.composite.read(this.children)}bumpRenderRevision(){this.composite.bump()}handleMouse(event){let contentWidth=Math.max(1,event.width-this.paddingX*2),contentY=event.y-this.paddingY,contentX=event.x-this.paddingX;if(contentY<0||contentX<0||contentX>=contentWidth)return;let mouseChildren=this.mouseLayout?.width===contentWidth?this.mouseLayout.children:this.children.map(component=>({component,height:component.render(contentWidth).length})),childY=0;for(let{component:child,height:childHeight}of mouseChildren){if(contentY>=childY&&contentY<childY+childHeight)return dispatchMouseEvent(child,{...event,x:contentX,y:contentY-childY,width:contentWidth,height:childHeight});childY+=childHeight}}render(width){if(this.children.length===0)return[];let contentWidth=Math.max(1,width-this.paddingX*2),leftPad=" ".repeat(this.paddingX),childLines=[],mouseChildren=[];for(let child of this.children){let lines=child.render(contentWidth),offset=childLines.length;mouseChildren.push({component:child,height:lines.length});for(let line of lines)childLines.push(line);copyLineSources(lines,childLines,offset)}if(this.mouseLayout={width:contentWidth,children:mouseChildren},childLines.length===0)return[];let bgSample=this.bgFn?this.bgFn("test"):void 0,cache=this.cache;if(cache&&this.matchCache(width,childLines,bgSample))return cache.lines;let result=[];for(let i=0;i<this.paddingY;i++)result.push(this.applyBg("",width)),setLineSource(result,result.length-1,null);for(let line of childLines)result.push(this.applyBg(leftPad+line,width));for(let i=0;i<this.paddingY;i++)result.push(this.applyBg("",width)),setLineSource(result,result.length-1,null);return flattenLines(result),copyLineSources(childLines,result,this.paddingY,this.paddingX),this.cache={childLines,width,bgSample,lines:result},result}applyBg(line,width){let visLen=visibleWidth(line),padNeeded=Math.max(0,width-visLen),padded=line+" ".repeat(padNeeded);return this.bgFn?applyBackgroundToLine(padded,width,this.bgFn):padded}};var DEFAULT_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],DEFAULT_INTERVAL_MS=80,Loader=class extends Text{constructor(ui,spinnerColorFn,messageColorFn,message="Loading...",indicator){super("",1,0),this.frames=[...DEFAULT_FRAMES],this.intervalMs=DEFAULT_INTERVAL_MS,this.currentFrame=0,this.indicatorIntervalId=null,this.messageIntervalId=null,this.indicatorFormatter=void 0,this.messageFormatter=void 0,this.messageIntervalMs=DEFAULT_INTERVAL_MS,this.messageAnimationStartedAt=0,this.ui=null,this.renderIndicatorVerbatim=!1,this.message="Loading...",this.lastDisplayedText=void 0,this.ui=ui,this.spinnerColorFn=spinnerColorFn,this.messageColorFn=messageColorFn,this.message=message,this.setIndicator(indicator)}render(width){return["",...super.render(width)]}start(){this.messageFormatter&&(this.messageAnimationStartedAt=Date.now()),this.updateDisplay(),this.restartAnimation()}stop(){this.indicatorIntervalId&&(clearInterval(this.indicatorIntervalId),this.indicatorIntervalId=null),this.messageIntervalId&&(clearInterval(this.messageIntervalId),this.messageIntervalId=null)}dispose(){this.stop()}setMessage(message){this.message=message,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}setIndicator(indicator){this.renderIndicatorVerbatim=indicator!==void 0,this.frames=indicator?.frames!==void 0?[...indicator.frames]:[...DEFAULT_FRAMES],this.intervalMs=indicator?.intervalMs&&indicator.intervalMs>0?indicator.intervalMs:DEFAULT_INTERVAL_MS,this.indicatorFormatter=indicator?.indicatorFormatter,this.messageFormatter=indicator?.messageFormatter,this.messageIntervalMs=indicator?.messageIntervalMs&&indicator.messageIntervalMs>0?indicator.messageIntervalMs:this.intervalMs,this.currentFrame=0,this.messageAnimationStartedAt=Date.now(),this.start()}restartAnimation(){this.stop(),this.frames.length>1&&(this.indicatorIntervalId=setInterval(()=>{this.currentFrame=(this.currentFrame+1)%this.frames.length,this.updateDisplay()},this.intervalMs),this.indicatorIntervalId.unref?.()),(this.indicatorFormatter||this.messageFormatter)&&(this.messageAnimationStartedAt=Date.now(),this.messageIntervalId=setInterval(()=>{this.updateDisplay()},this.messageIntervalMs),this.messageIntervalId.unref?.())}getRenderedIndicator(animationElapsedMs=this.getAnimationElapsedMs()){let frame=this.frames[this.currentFrame]??"";return frame.length===0?"":this.indicatorFormatter?this.indicatorFormatter(frame,animationElapsedMs):this.renderIndicatorVerbatim?frame:this.spinnerColorFn(frame)}getAnimationElapsedMs(){return Math.max(0,Date.now()-this.messageAnimationStartedAt)}updateDisplay(){let animationElapsedMs=this.getAnimationElapsedMs(),renderedFrame=this.getRenderedIndicator(animationElapsedMs),indicator=renderedFrame.length>0?`${renderedFrame} `:"",renderedMessage=this.messageFormatter?this.messageFormatter(this.message,animationElapsedMs):this.messageColorFn(this.message),displayedText=`${indicator}${renderedMessage}`;displayedText!==this.lastDisplayedText&&(this.lastDisplayedText=displayedText,this.setText(displayedText),this.ui&&this.ui.requestRender())}};var CancellableLoader=class extends Loader{constructor(){super(...arguments),this.abortController=new AbortController}get signal(){return this.abortController.signal}get aborted(){return this.abortController.signal.aborted}handleInput(data){getKeybindings().matches(data,"tui.select.cancel")&&(this.abortController.abort(),this.onAbort?.())}dispose(){this.stop()}};var IMAGE_MARKER_REGEX=/\[Image #([1-9]\d*)\]/g,IMAGE_MARKER_SINGLE=/^\[Image #([1-9]\d*)\]$/;function formatImageMarker(id){return`[Image #${id}]`}function isImageMarker(segment){return segment.length>=10&&IMAGE_MARKER_SINGLE.test(segment)}function imageMarkerId(segment){let match=segment.length>=10?IMAGE_MARKER_SINGLE.exec(segment):null;return match?Number.parseInt(match[1],10):void 0}function countOccurrences(text,marker){let count=0,offset=0;for(;offset<=text.length-marker.length;){let index=text.indexOf(marker,offset);if(index===-1)break;count++,offset=index+marker.length}return count}function replaceSingleOccurrence(text,marker,replacement){let index=text.indexOf(marker);return index===-1||text.indexOf(marker,index+marker.length)!==-1?text:text.slice(0,index)+replacement+text.slice(index+marker.length)}var ImageMarkerRegistry=class{constructor(){this.entries=new Set,this.imageCounter=0}add(){let id=++this.imageCounter;return this.entries.add(id),formatImageMarker(id)}authorizedMarkers(text){let markers=new Set;for(let id of this.entries){let marker=formatImageMarker(id);countOccurrences(text,marker)===1&&markers.add(marker)}return markers}canonicalize(text){let order=this.ids(text);if(order.length===0)return{text,order};let renumbered=new Map;for(let[index,id]of order.entries())renumbered.set(id,index+1);let updatedText=text.replace(IMAGE_MARKER_REGEX,marker=>{let id=imageMarkerId(marker),newId=id===void 0?void 0:renumbered.get(id);return newId===void 0?marker:formatImageMarker(newId)});return this.entries=new Set(order.map((_2,index)=>index+1)),this.imageCounter=this.entries.size,{text:updatedText,order}}clear(){this.entries.clear(),this.imageCounter=0}ids(text){let authorized=this.authorizedMarkers(text),ordered=[];for(let match of text.matchAll(IMAGE_MARKER_REGEX))authorized.has(match[0])&&ordered.push(Number.parseInt(match[1],10));return ordered}install(state,text){this.restore(state),this.prune(text)}prune(text,previousText){for(let id of[...this.entries]){let marker=formatImageMarker(id);(!(previousText===void 0||countOccurrences(previousText,marker)===1)||countOccurrences(text,marker)!==1)&&this.entries.delete(id)}this.imageCounter=Math.max(...this.entries,0)}remove(id,text){if(!this.entries.delete(id))return{text,removed:!1};let updatedText=replaceSingleOccurrence(text,formatImageMarker(id),""),higherIds=[...this.entries].filter(entryId=>entryId>id).sort((a,b2)=>a-b2);for(let oldId of higherIds){this.entries.delete(oldId);let marker=formatImageMarker(oldId);if(countOccurrences(updatedText,marker)!==1)continue;let newId=oldId-1;updatedText=replaceSingleOccurrence(updatedText,marker,formatImageMarker(newId)),this.entries.add(newId)}return this.imageCounter=Math.max(...this.entries,0),{text:updatedText,removed:!0}}restore(state){this.entries=new Set(state.ids),this.imageCounter=Math.max(state.imageCounter,...this.entries,0)}snapshot(){return{ids:[...this.entries].sort((a,b2)=>a-b2),imageCounter:this.imageCounter}}};var PASTE_MARKER_REGEX=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,PASTE_MARKER_SINGLE=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function formatPasteMarker(id,lineCount,charCount){return lineCount>10?`[paste #${id} +${lineCount} lines]`:`[paste #${id} ${charCount} chars]`}function countLines(content){let lineCount=1;for(let index=0;index<content.length;index++)content.charCodeAt(index)===10&&lineCount++;return lineCount}function createEntry(id,content,marker){let charCount=content.length,lineMatch=marker?.match(PASTE_MARKER_SINGLE)?.[3]?.match(/^\+(\d+) lines$/),lineCount=lineMatch?Number.parseInt(lineMatch[1],10):countLines(content),canonical=formatPasteMarker(id,lineCount,charCount);return{content,marker:marker===canonical?marker:canonical,lineCount,charCount}}function countOccurrences2(text,marker){let count=0,offset=0;for(;offset<=text.length-marker.length;){let index=text.indexOf(marker,offset);if(index===-1)break;count++,offset=index+marker.length}return count}function replaceSingleOccurrence2(text,marker,replacement){let index=text.indexOf(marker);return index===-1||text.indexOf(marker,index+marker.length)!==-1?text:text.slice(0,index)+replacement+text.slice(index+marker.length)}function entriesFromState(state){let entries=new Map;for(let[id,content]of state.pastes)entries.set(id,createEntry(id,content,state.markers?.get(id)));return entries}function expandPasteMarkers(text,state){let entries=entriesFromState(state),byMarker=new Map;for(let entry of entries.values())byMarker.set(entry.marker,entry);let matches=[],counts=new Map;for(let match of text.matchAll(PASTE_MARKER_REGEX)){let marker=match[0];byMarker.has(marker)&&(matches.push({start:match.index,end:match.index+marker.length,marker}),counts.set(marker,(counts.get(marker)??0)+1))}if(matches.length===0)return text;let chunks=[],offset=0;for(let match of matches){chunks.push(text.slice(offset,match.start));let entry=byMarker.get(match.marker);chunks.push(counts.get(match.marker)===1?entry.content:match.marker),offset=match.end}return chunks.push(text.slice(offset)),chunks.join("")}function isPasteMarker(segment){return segment.length>=10&&PASTE_MARKER_SINGLE.test(segment)}function pasteMarkerId(segment){let match=segment.length>=10?PASTE_MARKER_SINGLE.exec(segment):null;return match?Number.parseInt(match[1],10):void 0}function segmentWithMarkers(text,baseSegmenter,validMarkers){if(validMarkers.size===0)return baseSegmenter.segment(text);let found=[];for(let marker2 of validMarkers){let start=text.indexOf(marker2);start!==-1&&found.push({start,end:start+marker2.length})}if(found.length===0)return baseSegmenter.segment(text);found.sort((a,b2)=>a.start-b2.start||b2.end-a.end);let markers=[];for(let range of found){let previous=markers[markers.length-1];previous&&range.start<previous.end||markers.push(range)}let result=[],markerIndex=0,marker=markers[0];for(let segment of baseSegmenter.segment(text)){for(;marker&&segment.index>=marker.end;)marker=markers[++markerIndex];!marker||segment.index<marker.start?result.push(segment):segment.index===marker.start&&result.push({segment:text.slice(marker.start,marker.end),index:marker.start,input:text})}return result}var PasteMarkerRegistry=class{constructor(){this.entries=new Map,this.pasteCounter=0,this.metadataBuilds=0}add(content,lineCount,charCount){let id=++this.pasteCounter,marker=formatPasteMarker(id,lineCount,charCount);return this.entries.set(id,{content,marker,lineCount,charCount}),this.metadataBuilds++,marker}authorizedMarkers(text){let markers=new Set;for(let entry of this.entries.values())countOccurrences2(text,entry.marker)===1&&markers.add(entry.marker);return markers}clear(){this.entries.clear(),this.pasteCounter=0}expand(text){return expandPasteMarkers(text,this.snapshot())}get metadataBuildCount(){return this.metadataBuilds}install(state,text){this.entries=entriesFromState(state),this.metadataBuilds+=this.entries.size,this.pasteCounter=Math.max(state.pasteCounter,...this.entries.keys(),0),this.prune(text)}prune(text,previousText){for(let[id,entry]of this.entries)(!(previousText===void 0||countOccurrences2(previousText,entry.marker)===1)||countOccurrences2(text,entry.marker)!==1)&&this.entries.delete(id);this.pasteCounter=Math.max(...this.entries.keys(),0)}remove(id,text){let removedEntry=this.entries.get(id);if(!removedEntry||!this.entries.delete(id))return{text,removed:!1};let updatedText=replaceSingleOccurrence2(text,removedEntry.marker,""),higherIds=[...this.entries.keys()].filter(entryId=>entryId>id).sort((a,b2)=>a-b2);for(let oldId of higherIds){let entry=this.entries.get(oldId);if(this.entries.delete(oldId),countOccurrences2(updatedText,entry.marker)!==1)continue;let newId=oldId-1,renamed=formatPasteMarker(newId,entry.lineCount,entry.charCount);updatedText=replaceSingleOccurrence2(updatedText,entry.marker,renamed),this.entries.set(newId,{...entry,marker:renamed})}return this.pasteCounter=Math.max(...this.entries.keys(),0),{text:updatedText,removed:!0}}snapshot(){let pastes=new Map,markers=new Map;for(let[id,entry]of this.entries)pastes.set(id,entry.content),markers.set(id,entry.marker);return{pastes,markers,pasteCounter:this.pasteCounter}}restore(state){this.entries=entriesFromState(state),this.metadataBuilds+=this.entries.size,this.pasteCounter=Math.max(state.pasteCounter,...this.entries.keys(),0)}};import*as fs2 from"node:fs";import*as path3 from"node:path";import{createRequire as createRequire2}from"node:module";import*as path2 from"node:path";import{createRequire}from"node:module";import{dirname as dirname3,isAbsolute as isAbsolute2,join as join3}from"node:path";import{fileURLToPath}from"node:url";var moduleRequire=createRequire(import.meta.url),TUI_PACKAGE_NAME="@earendil-works/pi-tui";function resolvePackageEntry(resolveOverride){if(resolveOverride)return resolveOverride(TUI_PACKAGE_NAME);try{return fileURLToPath(import.meta.resolve(TUI_PACKAGE_NAME))}catch{}return moduleRequire.resolve(TUI_PACKAGE_NAME)}function getNativeModuleCandidates(nativePath,options={}){let moduleDir=dirname3(fileURLToPath(options.moduleUrl??import.meta.url)),candidates=[];try{let packageEntry=resolvePackageEntry(options.resolvePackage);packageEntry&&isAbsolute2(packageEntry)&&candidates.push(join3(dirname3(packageEntry),"..",nativePath))}catch{}return candidates.push(join3(moduleDir,"..",nativePath),join3(moduleDir,nativePath),join3(dirname3(options.execPath??process.execPath),nativePath)),Array.from(new Set(candidates))}var cjsRequire=createRequire2(import.meta.url),helpers=new Map;function loadNativePlatformHelper(platform,suffix=""){let arch=process.arch;if(arch!=="x64"&&arch!=="arm64")return;let nativePath=path2.join("native",platform,"prebuilds",`${platform}-${arch}`,`${platform}-platform${suffix}.node`);if(helpers.has(nativePath))return helpers.get(nativePath);for(let modulePath of getNativeModuleCandidates(nativePath))try{let helper=cjsRequire(modulePath);if(typeof helper?.getText=="function"&&typeof helper.getImage=="function")return helpers.set(nativePath,helper),helper}catch{}helpers.set(nativePath,void 0)}function getNativePlatformHelper(){if(!(process.platform!=="darwin"&&process.platform!=="win32"))return loadNativePlatformHelper(process.platform)}function getNativeClipboard(){if(process.platform!=="linux")return getNativePlatformHelper();if(process.env.DISPLAY)return loadNativePlatformHelper("linux","-x11")}function isNativeModifierPressed(key){let helper=getNativePlatformHelper();if(!helper?.isModifierPressed)return!1;try{return helper.isModifierPressed(key)===!0}catch{return!1}}function observeProcessStderrWrites(listener){let original=process.stderr.write,observed=function(...args){return listener(),Reflect.apply(original,this,args)};return process.stderr.write=observed,()=>{process.stderr.write===observed&&(process.stderr.write=original)}}import{StringDecoder}from"node:string_decoder";import{EventEmitter}from"events";function isStaleEscape(pending,gapMs,escapeWindowMs){return pending==="\x1B"&&gapMs!==void 0&&gapMs>=escapeWindowMs}var ESC="\x1B",DEFAULT_SEQUENCE_TIMEOUT_MS=50,DEFAULT_ESCAPE_TIMEOUT_MS=50,DEFAULT_BURST_WINDOW_MS=20,BRACKETED_PASTE_START="\x1B[200~",BRACKETED_PASTE_END="\x1B[201~",LINE_BREAK=/\r\n|\r|\n/g,TRAILING_LINE_BREAK_RUN=/(\r\n|\r|\n)+$/,LINE_BREAK_BEFORE_TEXT=/[\r\n][^\r\n]/;function countLineBreaks(text){let matches=text.match(LINE_BREAK);return matches===null?0:matches.length}function isCompleteSequence(data){if(!data.startsWith(ESC))return"not-escape";if(data.length===1)return"incomplete";let afterEsc=data.slice(1);return afterEsc.startsWith("[")?afterEsc.startsWith("[M")?data.length>=6?"complete":"incomplete":isCompleteCsiSequence(data):afterEsc.startsWith("]")?isCompleteOscSequence(data):afterEsc.startsWith("P")?isCompleteDcsSequence(data):afterEsc.startsWith("_")?isCompleteApcSequence(data):afterEsc.startsWith("O")?afterEsc.length>=2?"complete":"incomplete":(afterEsc.length===1,"complete")}function isCompleteCsiSequence(data){if(!data.startsWith(`${ESC}[`))return"complete";if(data.length<3)return"incomplete";let payload=data.slice(2),lastChar=payload[payload.length-1],lastCharCode=lastChar.charCodeAt(0);if(lastCharCode>=64&&lastCharCode<=126){if(payload.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(payload))return"complete";if(lastChar==="M"||lastChar==="m"){let parts=payload.slice(1,-1).split(";");if(parts.length===3&&parts.every(p=>/^\d+$/.test(p)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}function isCompleteOscSequence(data){return!data.startsWith(`${ESC}]`)||data.endsWith(`${ESC}\\`)||data.endsWith("\x07")?"complete":"incomplete"}function isCompleteDcsSequence(data){return!data.startsWith(`${ESC}P`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function isCompleteApcSequence(data){return!data.startsWith(`${ESC}_`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function parseUnmodifiedKittyPrintableCodepoint(sequence){let match=sequence.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!match)return;let codepoint=parseInt(match[1],10);return codepoint>=32?codepoint:void 0}function extractCompleteSequences(buffer){let sequences=[],pos=0;for(;pos<buffer.length;){let remaining=buffer.slice(pos);if(remaining.startsWith(ESC)){let seqEnd=1;for(;seqEnd<=remaining.length;){let candidate=remaining.slice(0,seqEnd),status=isCompleteSequence(candidate);if(status==="complete"){if(candidate==="\x1B\x1B"){let nextChar=remaining[seqEnd];if(nextChar==="["||nextChar==="]"||nextChar==="O"||nextChar==="P"||nextChar==="_"){sequences.push(ESC),pos+=1;break}}sequences.push(candidate),pos+=seqEnd;break}else if(status==="incomplete")seqEnd++;else{sequences.push(candidate),pos+=seqEnd;break}}if(seqEnd>remaining.length)return{sequences,remainder:remaining}}else{let codepoint=remaining.codePointAt(0),character=String.fromCodePoint(codepoint);sequences.push(character),pos+=character.length}}return{sequences,remainder:""}}var StdinBuffer=class extends EventEmitter{constructor(options={}){super(),this.buffer="",this.timeout=null,this.discardingMouseFragment=!1,this.pasteMode=!1,this.pasteBuffer="",this.decoder=new StringDecoder("utf8"),this.heldNewline="",this.heldNewlineKind="keystroke",this.lastBurstPasteUsesCrLineBreaks=!1,this.burstTimer=null,this.timeoutMs=options.timeout??DEFAULT_SEQUENCE_TIMEOUT_MS,this.escapeTimeoutMs=options.escapeTimeout??DEFAULT_ESCAPE_TIMEOUT_MS,this.burstWindowMs=options.burstWindowMs??DEFAULT_BURST_WINDOW_MS,this.clock=options.now??Date.now}process(data){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let str,decodedFromBuffer=!1;if(Buffer.isBuffer(data))if(!((this.decoder.lastNeed??0)>0)&&data.length===1&&data[0]>=128&&data[0]<194){let byte=data[0]-128;str=`\x1B${String.fromCharCode(byte)}`}else str=this.decoder.write(data),decodedFromBuffer=!0;else str=data;if(str.length===0&&this.buffer.length===0){decodedFromBuffer||this.emitDataSequence("");return}if(this.discardingMouseFragment){let terminator=str.search(/[\x40-\x7e]/),escapeIndex=str.indexOf(ESC);if(escapeIndex!==-1&&(terminator===-1||escapeIndex<terminator))str=str.slice(escapeIndex);else{if(terminator===-1)return;str=str.slice(terminator+1)}this.discardingMouseFragment=!1}this.burstTimer&&(clearTimeout(this.burstTimer),this.burstTimer=null);let chunkAt=str.length>0?this.clock():void 0,burstGap=chunkAt!==void 0&&this.lastInputAt!==void 0?chunkAt-this.lastInputAt:void 0;if(chunkAt!==void 0&&(this.lastInputAt=chunkAt),isStaleEscape(this.buffer,burstGap,this.escapeTimeoutMs)&&(this.buffer="",this.emitDataSequence(ESC)),this.buffer+=str,this.heldNewline.length>0&&(burstGap!==void 0&&burstGap>=this.burstWindowMs?this.releaseHeldNewline():this.heldNewlineKind==="enter"&&!this.buffer.startsWith(`
`)?this.releaseHeldNewline():(this.buffer=this.heldNewline+this.buffer,this.heldNewline="",this.heldNewlineKind="keystroke")),this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let startIndex=this.buffer.indexOf(BRACKETED_PASTE_START);if(startIndex!==-1){if(startIndex>0){let beforePaste=this.buffer.slice(0,startIndex),result2=extractCompleteSequences(beforePaste);for(let sequence of result2.sequences)this.emitDataSequence(sequence)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(startIndex+BRACKETED_PASTE_START.length),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}if(this.consumeUnbracketedBurst(burstGap))return;let result=extractCompleteSequences(this.buffer);this.buffer=result.remainder,this.buffer.startsWith("\x1B[<")?(this.mouseFragmentStartedAt??=Date.now(),this.buffer.length>64&&(this.buffer="",this.discardingMouseFragment=!0)):this.mouseFragmentStartedAt=void 0;for(let sequence of result.sequences)this.emitDataSequence(sequence);if(this.buffer.length>0){let timeoutMs=this.buffer===ESC?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let flushed=this.flush();for(let sequence of flushed)this.emitDataSequence(sequence)},timeoutMs)}}consumeUnbracketedBurst(burstGap){let text=this.buffer;if(text.length===0||text.includes(ESC)||text.includes(BRACKETED_PASTE_START))return!1;let breaks=countLineBreaks(text);if(breaks===0)return!1;let trailing=text.match(TRAILING_LINE_BREAK_RUN)?.[0],trailingEndsWithCr=trailing!==void 0&&trailing.endsWith("\r"),crOnlyPasteBurst=trailingEndsWithCr&&!text.includes(`
`)&&/[^\r\n]/.test(text);if((breaks>=2||LINE_BREAK_BEFORE_TEXT.test(text))&&/[^\r\n]/.test(text)){let endsWithEnter=trailingEndsWithCr&&!crOnlyPasteBurst,body=endsWithEnter?text.slice(0,-1):text;return this.buffer="",this.lastBurstPasteAt=this.lastInputAt,this.lastBurstPasteUsesCrLineBreaks=!body.includes(`
`),this.emit("paste",body),endsWithEnter&&this.holdTrailingNewline("\r","enter"),!0}if(trailing===void 0||burstGap===void 0||burstGap>=this.burstWindowMs)return!1;let head=text.slice(0,text.length-trailing.length),endsPaste=this.lastBurstPasteAt!==void 0&&this.lastInputAt!==void 0&&this.lastInputAt-this.lastBurstPasteAt<this.burstWindowMs,crContinuesPaste=endsPaste&&this.lastBurstPasteUsesCrLineBreaks;if(trailingEndsWithCr&&!crContinuesPaste||head.length===0&&!endsPaste)return!1;for(let chunk of head)this.emitDataSequence(chunk);return this.buffer="",this.holdTrailingNewline(trailing,endsPaste?"paste":"keystroke"),!0}holdTrailingNewline(run,kind){this.heldNewline=run,this.heldNewlineKind=kind,this.burstTimer&&clearTimeout(this.burstTimer),this.burstTimer=setTimeout(()=>{this.burstTimer=null,this.releaseHeldNewline()},this.burstWindowMs)}releaseHeldNewline(){if(this.heldNewline.length===0)return;let held=this.heldNewline,kind=this.heldNewlineKind;if(this.heldNewline="",this.heldNewlineKind="keystroke",kind==="paste"){this.emit("paste",held);return}for(let chunk of held)this.emitDataSequence(chunk)}emitDataSequence(sequence){let rawCodepoint=sequence.length===1?sequence.codePointAt(0):void 0;if(rawCodepoint!==void 0&&rawCodepoint===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=parseUnmodifiedKittyPrintableCodepoint(sequence),this.emit("data",sequence)}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.burstTimer&&(clearTimeout(this.burstTimer),this.burstTimer=null),this.releaseHeldNewline(),this.buffer.length===0)return[];if(this.buffer.startsWith("\x1B[<")){let remaining=750-(Date.now()-(this.mouseFragmentStartedAt??Date.now()));return remaining>0&&this.buffer.length<=64?this.timeout=setTimeout(()=>this.flush(),remaining):(this.buffer="",this.mouseFragmentStartedAt=void 0,this.discardingMouseFragment=!0),[]}let sequences=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,sequences}clear(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.burstTimer&&(clearTimeout(this.burstTimer),this.burstTimer=null),this.heldNewline="",this.heldNewlineKind="keystroke",this.lastBurstPasteAt=void 0,this.lastBurstPasteUsesCrLineBreaks=!1,this.buffer="",this.pasteMode=!1,this.pasteBuffer="",this.mouseFragmentStartedAt=void 0,this.discardingMouseFragment=!1,this.pendingKittyPrintableCodepoint=void 0,this.decoder=new StringDecoder("utf8")}getBuffer(){return this.buffer}destroy(){this.clear()}};import{execFileSync as execFileSync2}from"node:child_process";function queryTmuxCursorPosition(pane,deadline,execFile2){let read=()=>{let remaining=deadline-Date.now();if(!(remaining<=0))try{let args=["display-message","-p","-t",pane,"#{cursor_y} #{cursor_x}"],output=execFile2?execFile2("tmux",args):execFileSync2("tmux",args,{encoding:"utf8",timeout:remaining,stdio:["ignore","pipe","ignore"]}),match=/^(\d+) (\d+)$/.exec(output.trim());if(!match||Date.now()>=deadline)return;let row=Number(match[1])+1,column=Number(match[2])+1;return Number.isSafeInteger(row)&&Number.isSafeInteger(column)?{row,column}:void 0}catch{return}},first=read();return!first||deadline-Date.now()<=10?Promise.resolve(void 0):new Promise(resolve=>{setTimeout(()=>{let second=read();resolve(second?.row===first.row&&second.column===first.column?second:void 0)},10)})}import{readFileSync}from"node:fs";var WSL_ENV_MARKERS=["WSL_DISTRO_NAME","WSL_INTEROP","WSLENV"];function isWslSession(env,platform=process.platform,procVersionPath="/proc/version"){if(platform!=="linux")return!1;if(WSL_ENV_MARKERS.some(marker=>!!env[marker]))return!0;try{return/microsoft|wsl/i.test(readFileSync(procVersionPath,"utf-8"))}catch{return!1}}var TERMINAL_PROGRESS_KEEPALIVE_MS=1e3,TERMINAL_PROGRESS_ACTIVE_SEQUENCE="\x1B]9;4;3\x07",TERMINAL_PROGRESS_CLEAR_SEQUENCE="\x1B]9;4;0\x07",NATIVE_SHIFT_ENTER_SEQUENCE="\x1B[13;2u",APPLE_TERMINAL_ESCAPED_RETURN_SEQUENCE="\x1B\r",DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS=7,DEAD_TERMINAL_ERROR_CODES=new Set(["EIO","EPIPE","ENOTCONN"]),EIO_ERRNO=5,EPIPE_ERRNO=32,DEAD_TERMINAL_ERRNOS=new Set([EIO_ERRNO,EPIPE_ERRNO]),ERRNO_IN_MESSAGE_PATTERN=/errno:\s*(\d+)/,KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS=150,KITTY_KEYBOARD_PROTOCOL_QUERY=`\x1B[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1B[?u\x1B[c`;function parseCursorPositionResponse(sequence){let match=/^\x1b\[\?(\d+);(\d+)(?:;(\d+))?R$/.exec(sequence);return match?{row:Number(match[1]),column:Number(match[2]),...match[3]===void 0?{}:{page:Number(match[3])}}:void 0}function parseKeyboardProtocolNegotiationSequence(sequence){let cursorPosition=parseCursorPositionResponse(sequence);if(cursorPosition)return{type:"cursor-position",...cursorPosition};let kittyFlags=sequence.match(/^\x1b\[\?(\d+)u$/);if(kittyFlags)return{type:"kitty-flags",flags:Number.parseInt(kittyFlags[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(sequence))return{type:"device-attributes"}}function isKeyboardProtocolNegotiationSequencePrefix(sequence){return sequence==="\x1B["||/^\x1b\[\?[\d;]*$/.test(sequence)}function isAppleTerminalSession(){return process.platform==="darwin"&&process.env.TERM_PROGRAM==="Apple_Terminal"}function refreshTerminalDimensions(){if(!(process.platform==="win32"||process.pid<=0))try{process.kill(process.pid,"SIGWINCH")}catch{}}function normalizeNativeShiftEnterInput(data,shouldDetectNativeShiftEnter,isShiftPressed){return shouldDetectNativeShiftEnter&&data==="\r"&&isShiftPressed?NATIVE_SHIFT_ENTER_SEQUENCE:data}function normalizeAppleTerminalInput(data,isAppleTerminal,isShiftPressed){return isAppleTerminal&&data===APPLE_TERMINAL_ESCAPED_RETURN_SEQUENCE&&isShiftPressed?NATIVE_SHIFT_ENTER_SEQUENCE:normalizeNativeShiftEnterInput(data,isAppleTerminal,isShiftPressed)}function isWarpWslSession(env=process.env,platform=process.platform,socketExists=socketPath=>{try{return fs2.statSync(socketPath).isSocket()}catch{return!1}}){if(platform!=="linux"||isMultiplexerSession(env)||env.SSH_CONNECTION?.trim()||env.SSH_CLIENT?.trim()||env.SSH_TTY?.trim())return!1;let isWarp=!!(env.WARP_SESSION_ID?.trim()||env.WARP_TERMINAL_SESSION_UUID?.trim()),interopPath=env.WSL_INTEROP?.trim(),isWsl=isWarp&&interopPath!==void 0&&/^\/run\/WSL\/\d+_interop$/.test(interopPath)&&socketExists(interopPath);return isWarp&&isWsl}function normalizeWarpWslShiftEnterInput(data,env=process.env,platform=process.platform,socketExists){return data===`
`&&isWarpWslSession(env,platform,socketExists)?NATIVE_SHIFT_ENTER_SEQUENCE:data}function keyboardEnhancementEnabled(){let value=process.env.PI_TUI_KEYBOARD_PROTOCOL;return value===void 0?!0:!["0","false","no","off"].includes(value.toLowerCase())}function isDeadTerminalError(error){if(!(error instanceof Error))return!1;if("code"in error&&typeof error.code=="string")return DEAD_TERMINAL_ERROR_CODES.has(error.code);if("errno"in error&&error.errno===EIO_ERRNO)return!0;let messageErrno=ERRNO_IN_MESSAGE_PATTERN.exec(error.message);return messageErrno?DEAD_TERMINAL_ERRNOS.has(Number.parseInt(messageErrno[1],10)):!1}var STDIN_ERROR_HANDLER_GRACE_MS=250,stdinErrorSubscribers=new Set;function isTerminalDetachStdinError(err){if(err.code==="EIO")return!0;let errno=err.errno;return errno===EIO_ERRNO||errno===-EIO_ERRNO}var dispatchStdinError=err=>{if(!isTerminalDetachStdinError(err)){if(!process.stdin.listeners("error").some(listener=>listener!==dispatchStdinError))throw err;return}for(let subscriber of stdinErrorSubscribers)subscriber(err)};function subscribeToStdinErrors(subscriber){stdinErrorSubscribers.size===0&&process.stdin.on("error",dispatchStdinError),stdinErrorSubscribers.add(subscriber)}function unsubscribeFromStdinErrors(subscriber){stdinErrorSubscribers.delete(subscriber),stdinErrorSubscribers.size===0&&process.stdin.removeListener("error",dispatchStdinError)}var DEFAULT_ESCAPE_TIMEOUT_MS2=50,DEFAULT_REMOTE_ESCAPE_TIMEOUT_MS=100,DEFAULT_BURST_WINDOW_MS2=20,DEFAULT_SSH_BURST_WINDOW_MS=100;function resolveEscapeTimeoutMs(env=process.env,platform=process.platform){let configured=Number(env.PI_TUI_ESC_TIMEOUT);return Number.isFinite(configured)&&configured>0?configured:env.SSH_CONNECTION||env.SSH_TTY||isWslSession(env,platform)?DEFAULT_REMOTE_ESCAPE_TIMEOUT_MS:DEFAULT_ESCAPE_TIMEOUT_MS2}function resolveBurstWindowMs(env=process.env){let raw=env.PI_TUI_BURST_WINDOW_MS?.trim();if(raw!==void 0&&raw.length>0){let configured=Number(raw);if(Number.isFinite(configured)&&configured>=0)return configured}return env.SSH_CONNECTION||env.SSH_TTY?DEFAULT_SSH_BURST_WINDOW_MS:DEFAULT_BURST_WINDOW_MS2}var ProcessTerminal=class{constructor(options){this.wasRaw=!1,this.externalWriteObservers=new Set,this.keyboardNegotiationSettled=!1,this.cursorQueryTimedOut=!1,this.forwardingExternalWrite=!1,this._kittyProtocolActive=!1,this._modifyOtherKeysActive=!1,this.keyboardProtocolPushed=!1,this.pendingKeyboardProtocolDeviceAttributes=0,this.keyboardProtocolNegotiationBuffer="",this.discardingPrivateResponse=!1,this.writeLogPath=(()=>{let env=process.env.PI_TUI_WRITE_LOG||"";if(!env)return"";try{if(fs2.statSync(env).isDirectory()){let now=new Date,ts=`${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,"0")}-${String(now.getDate()).padStart(2,"0")}_${String(now.getHours()).padStart(2,"0")}-${String(now.getMinutes()).padStart(2,"0")}-${String(now.getSeconds()).padStart(2,"0")}`;return path3.join(env,`tui-${ts}-${process.pid}.log`)}}catch{}return env})(),this.onExternalStdoutWrite=options?.onExternalStdoutWrite,this.observeExternalStderrWrites=options?.observeExternalStderrWrites??observeProcessStderrWrites,this.tmuxExecFile=options?.tmuxExecFile}get kittyProtocolActive(){return this._kittyProtocolActive}queryCursorPosition(){if(this.cursorQuery)return this.cursorQuery.promise;if(!this.inputHandler||this.cursorQueryTimedOut)return Promise.resolve(void 0);let resolve,promise=new Promise(settle=>{resolve=settle}),timer=setTimeout(()=>{this.cursorQueryTimedOut=!0,this.settleCursorQuery(void 0)},750);return this.cursorQuery={promise,resolve,timer,issued:!1,tmuxPane:process.env.TMUX_PANE,deadline:Date.now()+750},this.issueCursorQuery(),promise}issueCursorQuery(){if(!this.keyboardNegotiationSettled||!this.cursorQuery||this.cursorQuery.issued)return;this.cursorQuery.issued=!0,this.rawWrite("\x1B[?6n");let pending=this.cursorQuery;pending?.tmuxPane!==void 0&&queryTmuxCursorPosition(pending.tmuxPane,pending.deadline,this.tmuxExecFile).then(position=>{this.cursorQuery===pending&&(Date.now()>=pending.deadline&&(this.cursorQueryTimedOut=!0),this.settleCursorQuery(this.cursorQueryTimedOut?void 0:position))})}settleCursorQuery(position){let pending=this.cursorQuery;pending&&(this.cursorQuery=void 0,clearTimeout(pending.timer),pending.resolve(position))}observeExternalWrites(listener){return this.externalWriteObservers.add(listener),this.inputHandler&&(this.installExternalStdoutGuard(),this.installExternalStderrObserver()),()=>{this.externalWriteObservers.delete(listener)}}noteExternalWrite(){for(let listener of this.externalWriteObservers)listener()}installExternalStderrObserver(){this.stopExternalStderrObservation||this.externalWriteObservers.size===0||(this.stopExternalStderrObservation=this.observeExternalStderrWrites(()=>this.noteExternalWrite()))}rawWrite(data){if(this.rawStdoutWrite){this.rawStdoutWrite(data);return}process.stdout.write(data)}installExternalStdoutGuard(){let handler=this.onExternalStdoutWrite;if(!handler&&this.externalWriteObservers.size===0||this.originalStdoutWrite)return;this.originalStdoutWrite=process.stdout.write;let rawWrite=process.stdout.write.bind(process.stdout);this.rawStdoutWrite=rawWrite,process.stdout.write=((chunk,encodingOrCallback,callback)=>{let cb=typeof encodingOrCallback=="function"?encodingOrCallback:callback,encoding=typeof encodingOrCallback=="string"?encodingOrCallback:void 0,text=typeof chunk=="string"?chunk:Buffer.from(chunk).toString(encoding);if(/^\x1b]52;c;(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?\x07(?![\s\S])/.test(text))return rawWrite(text,cb);if(!handler||this.forwardingExternalWrite)return this.noteExternalWrite(),rawWrite(text),cb?.(null),!0;this.forwardingExternalWrite=!0;try{handler(text)}catch{this.noteExternalWrite(),rawWrite(text)}finally{this.forwardingExternalWrite=!1}return cb?.(null),!0})}removeExternalStdoutGuard(){this.originalStdoutWrite&&(process.stdout.write=this.originalStdoutWrite,this.originalStdoutWrite=void 0,this.rawStdoutWrite=void 0)}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(onInput,onResize){this.installExternalStdoutGuard(),this.installExternalStderrObserver(),this.keyboardNegotiationSettled=!keyboardEnhancementEnabled(),this.cursorQueryTimedOut=!1,this.discardingPrivateResponse=!1,this.inputHandler=onInput,this.resizeHandler=onResize,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.resume(),this.stdinErrorHandlerCleanupTimer&&(clearTimeout(this.stdinErrorHandlerCleanupTimer),this.stdinErrorHandlerCleanupTimer=void 0),this.stdinErrorHandler||(this.stdinErrorHandler=()=>{},subscribeToStdinErrors(this.stdinErrorHandler)),this.rawWrite("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),refreshTerminalDimensions(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){this.stdinBuffer=new StdinBuffer({escapeTimeout:resolveEscapeTimeoutMs(),burstWindowMs:resolveBurstWindowMs()}),this.stdinBuffer.on("data",sequence=>{if(this.discardingPrivateResponse)if(sequence.startsWith("\x1B"))this.discardingPrivateResponse=!1;else{/[\x40-\x7e]/.test(sequence)&&(this.discardingPrivateResponse=!1);return}let negotiation=this.readKeyboardProtocolNegotiationSequence(sequence);if(negotiation==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}negotiation&&this.handleKeyboardProtocolNegotiationSequence(negotiation.parsed)||this.forwardInputSequence(negotiation?.sequence??sequence)}),this.stdinBuffer.on("paste",content=>{this.inputHandler&&this.inputHandler(`\x1B[200~${content}\x1B[201~`)}),this.stdinDataHandler=data=>{this.stdinBuffer.process(data)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),keyboardEnhancementEnabled()&&((process.env.TMUX!==void 0||process.env.TMUX_PANE!==void 0)&&this.enableModifyOtherKeys(),this.keyboardProtocolPushed=!0,this.pendingKeyboardProtocolDeviceAttributes+=1,this.clearKeyboardProtocolNegotiationBuffer(),this.rawWrite(KITTY_KEYBOARD_PROTOCOL_QUERY))}handleKeyboardProtocolNegotiationSequence(negotiationSequence){if(this.clearKeyboardProtocolNegotiationBuffer(),negotiationSequence.type==="cursor-position"){if(this.cursorQuery?.issued&&this.cursorQuery.tmuxPane===void 0){let{type:_type,...position}=negotiationSequence;this.settleCursorQuery(position)}return!0}if(negotiationSequence.type==="device-attributes"){if(this.pendingKeyboardProtocolDeviceAttributes===0)return!1;this.pendingKeyboardProtocolDeviceAttributes-=1}return this.keyboardNegotiationSettled=!0,this.issueCursorQuery(),negotiationSequence.type==="kitty-flags"?(negotiationSequence.flags!==0?(this.disableModifyOtherKeys(),this._kittyProtocolActive||(this._kittyProtocolActive=!0,setKittyProtocolActive(!0))):this.enableModifyOtherKeys(),!0):(this._kittyProtocolActive||this.enableModifyOtherKeys(),!0)}readKeyboardProtocolNegotiationSequence(sequence){if(this.keyboardProtocolNegotiationBuffer){let bufferedSequence=this.keyboardProtocolNegotiationBuffer+sequence,negotiationSequence2=parseKeyboardProtocolNegotiationSequence(bufferedSequence);if(negotiationSequence2)return this.clearKeyboardProtocolNegotiationBuffer(),{parsed:negotiationSequence2,sequence:bufferedSequence};if(isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence))return this.setKeyboardProtocolNegotiationBuffer(bufferedSequence),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput()}let negotiationSequence=parseKeyboardProtocolNegotiationSequence(sequence);if(negotiationSequence)return{parsed:negotiationSequence,sequence};if(isKeyboardProtocolNegotiationSequencePrefix(sequence))return this.setKeyboardProtocolNegotiationBuffer(sequence),"pending"}setKeyboardProtocolNegotiationBuffer(sequence){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=sequence}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=""}flushKeyboardProtocolNegotiationBufferAsInput(discardTail=!1){if(!this.keyboardProtocolNegotiationBuffer)return;let sequence=this.keyboardProtocolNegotiationBuffer;if(this.clearKeyboardProtocolNegotiationBuffer(),/^\x1b\[\?[\d;]*$/.test(sequence)){this.discardingPrivateResponse=discardTail;return}this.forwardInputSequence(sequence)}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput(!0)},KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS))}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0)}forwardInputSequence(sequence){if(!this.inputHandler)return;let isAppleTerminal=(sequence==="\r"||sequence===APPLE_TERMINAL_ESCAPED_RETURN_SEQUENCE)&&isAppleTerminalSession(),shouldDetectNativeShiftEnter=isAppleTerminal||sequence==="\r"&&process.platform==="win32",isShiftPressed=shouldDetectNativeShiftEnter&&isNativeModifierPressed("shift"),input=isAppleTerminal?normalizeAppleTerminalInput(sequence,!0,isShiftPressed):normalizeNativeShiftEnterInput(sequence,shouldDetectNativeShiftEnter,isShiftPressed);this.inputHandler(input)}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(this.rawWrite("\x1B[>4;2m"),this._modifyOtherKeysActive=!0)}disableModifyOtherKeys(){this._modifyOtherKeysActive&&(this.rawWrite("\x1B[>4;0m"),this._modifyOtherKeysActive=!1)}enableWindowsVTInput(){if(process.platform==="win32")try{getNativePlatformHelper()?.enableVirtualTerminalInput?.()}catch{}}async drainInput(maxMs=1e3,idleMs=50){let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(this.rawWrite("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys();let previousHandler=this.inputHandler;this.inputHandler=void 0;let lastDataTime=Date.now(),onData=()=>{lastDataTime=Date.now()};process.stdin.on("data",onData);let endTime=Date.now()+maxMs;try{for(;;){let now=Date.now(),timeLeft=endTime-now;if(timeLeft<=0||now-lastDataTime>=idleMs)break;await new Promise(resolve=>setTimeout(resolve,Math.min(idleMs,timeLeft)))}}finally{process.stdin.removeListener("data",onData),this.inputHandler=previousHandler}}stop(){this.settleCursorQuery(void 0),this.stopExternalStderrObservation?.(),this.stopExternalStderrObservation=void 0,this.clearProgressInterval()&&this.rawWrite(TERMINAL_PROGRESS_CLEAR_SEQUENCE),this.rawWrite("\x1B[?2004l");let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;if(this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(this.rawWrite("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys(),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode)try{process.stdin.setRawMode(this.wasRaw)}catch(error){if(!isDeadTerminalError(error))throw error}this.removeExternalStdoutGuard(),this.scheduleStdinErrorHandlerCleanup()}scheduleStdinErrorHandlerCleanup(){if(!this.stdinErrorHandler||this.stdinErrorHandlerCleanupTimer)return;let handler=this.stdinErrorHandler;this.stdinErrorHandlerCleanupTimer=setTimeout(()=>{this.stdinErrorHandlerCleanupTimer=void 0,this.stdinErrorHandler===handler&&(this.stdinErrorHandler=void 0,unsubscribeFromStdinErrors(handler))},STDIN_ERROR_HANDLER_GRACE_MS),this.stdinErrorHandlerCleanupTimer.unref()}write(data){if(this.rawWrite(data),this.writeLogPath)try{fs2.appendFileSync(this.writeLogPath,data,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(lines){lines>0?this.rawWrite(`\x1B[${lines}B`):lines<0&&this.rawWrite(`\x1B[${-lines}A`)}hideCursor(){this.rawWrite("\x1B[?25l")}showCursor(){this.rawWrite("\x1B[?25h")}clearLine(){this.rawWrite("\x1B[K")}clearFromCursor(){this.rawWrite("\x1B[J")}clearScreen(){this.rawWrite("\x1B[2J\x1B[H")}setTitle(title){let sanitizedTitle=title.replace(/[\u0000-\u001f\u007f-\u009f]/g,"");this.rawWrite(`\x1B]0;${sanitizedTitle}\x07`)}setProgress(active){active?(this.rawWrite(TERMINAL_PROGRESS_ACTIVE_SEQUENCE),this.progressInterval||(this.progressInterval=setInterval(()=>{this.rawWrite(TERMINAL_PROGRESS_ACTIVE_SEQUENCE)},TERMINAL_PROGRESS_KEEPALIVE_MS))):(this.clearProgressInterval(),this.rawWrite(TERMINAL_PROGRESS_CLEAR_SEQUENCE))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var FAKE_CURSOR_END2="\x1B[7m \x1B[0m";function clampMentions(mentions,length){return mentions.map(range=>({start:Math.max(0,range.start),end:Math.min(length,range.end)})).filter(range=>range.start<range.end)}function keywordRangesByLine(lines,runs){let byLine=new Map,lineStart=0;for(let line=0;line<lines.length;line++){let lineEnd=lineStart+(lines[line]?.length??0);for(let run of runs){let start=Math.max(run.start,lineStart),end=Math.min(run.end,lineEnd);if(start>=end)continue;let pieces=byLine.get(line)??[];pieces.push({start:start-lineStart,end:end-lineStart,runStart:run.start-lineStart,runLength:run.end-run.start}),byLine.set(line,pieces)}lineStart=lineEnd+1}return byLine}function styleKeywordSegment(segment,from,range,style){let out="",offset=from;for(let char of segment)out+=style(char,offset-range.runStart,range.runLength),offset+=char.length;return out}function cutPoints(length,mentions,cursorGlyph){let cuts=new Set([0,length]);for(let range of mentions)cuts.add(range.start),cuts.add(range.end);return cursorGlyph&&(cuts.add(cursorGlyph.start),cuts.add(cursorGlyph.end)),[...cuts].sort((left,right)=>left-right)}function renderEditorLine(input){let{text,cursor}=input,mentions=clampMentions(input.mentions,text.length),keywordStyle=input.keywordStyle,keywords=keywordStyle?(input.keywords??[]).filter(range=>Math.max(0,range.start)<Math.min(text.length,range.end)&&!mentions.some(mention=>range.start<mention.end&&mention.start<range.end)):[],cursorInText=cursor!==void 0&&cursor.pos<text.length,cursorGlyph=cursorInText&&cursor.drawFakeCursor?{start:cursor.pos,end:cursor.pos+input.firstGrapheme(text.slice(cursor.pos)).length}:void 0,points=cutPoints(text.length,[...mentions,...clampMentions(keywords,text.length)],cursorGlyph),out="";for(let index=0;index<points.length-1;index++){let from=points[index]??0,to=points[index+1]??from;cursorInText&&from===cursor.pos&&(out+=cursor.marker);let segment=text.slice(from,to);if(cursorGlyph&&from===cursorGlyph.start)out+=`\x1B[7m${segment}\x1B[0m`;else if(mentions.some(range=>from>=range.start&&to<=range.end))out+=input.mentionStyle(segment);else if(keywordStyle){let keyword=keywords.find(range=>from>=range.start&&to<=range.end);out+=keyword?styleKeywordSegment(segment,from,keyword,keywordStyle):segment}else out+=segment}return cursor!==void 0&&!cursorInText&&(out+=cursor.marker,cursor.drawFakeCursor)?{text:out+FAKE_CURSOR_END2,cursorAppended:!0}:{text:out,cursorAppended:!1}}var graphemeSegmenter2=getGraphemeSegmenter(),wordSegmenter4=getWordSegmenter();function isAtomicMarker(segment){return isPasteMarker(segment)||isImageMarker(segment)}function markerKind(segment){if(isPasteMarker(segment))return"paste";if(isImageMarker(segment))return"image"}function containsMarkerPrefix(text){return text.includes("[paste #")||text.includes("[Image #")}function isPrintableAsciiText(text){for(let i=0;i<text.length;i++){let code=text.charCodeAt(i);if(code<32||code>126)return!1}return!0}function wordWrapAsciiLine(line,maxWidth){if(line.length<=maxWidth)return[{text:line,startIndex:0,endIndex:line.length}];let chunks=[],chunkStart=0;for(;chunkStart<line.length;){let chunkEnd=Math.min(line.length,chunkStart+maxWidth);if(chunkEnd<line.length){let breakAt=-1;for(let i=chunkEnd;i>chunkStart;i--){let code=line.charCodeAt(i-1);if(code===32||code===9){breakAt=i-1;break}}breakAt>chunkStart&&(chunkEnd=breakAt)}let raw=line.slice(chunkStart,chunkEnd),text=raw.trimEnd();for((text||chunks.length===0)&&chunks.push({text,startIndex:chunkStart,endIndex:chunkStart+raw.length}),chunkStart=chunkEnd;chunkStart<line.length;){let code=line.charCodeAt(chunkStart);if(code!==32&&code!==9)break;chunkStart++}}return chunks.length>0?chunks:[{text:"",startIndex:0,endIndex:0}]}function wordWrapLine(line,maxWidth,preSegmented){if(!line||maxWidth<=0)return[{text:"",startIndex:0,endIndex:0}];if(preSegmented===void 0&&!/\s/.test(line)&&!containsMarkerPrefix(line)&&isPrintableAsciiText(line))return wordWrapAsciiLine(line,maxWidth);if(visibleWidth(line)<=maxWidth)return[{text:line,startIndex:0,endIndex:line.length}];let chunks=[],segments=preSegmented??[...graphemeSegmenter2.segment(line)],currentWidth=0,chunkStart=0,wrapOppIndex=-1,wrapOppWidth=0;for(let i=0;i<segments.length;i++){let seg=segments[i],grapheme=seg.segment,gWidth=visibleWidth(grapheme),charIndex=seg.index,isWs=!isAtomicMarker(grapheme)&&isWhitespaceChar(grapheme);if(currentWidth+gWidth>maxWidth&&(wrapOppIndex>=0&¤tWidth-wrapOppWidth+gWidth<=maxWidth?(chunks.push({text:line.slice(chunkStart,wrapOppIndex),startIndex:chunkStart,endIndex:wrapOppIndex}),chunkStart=wrapOppIndex,currentWidth-=wrapOppWidth):chunkStart<charIndex&&(chunks.push({text:line.slice(chunkStart,charIndex),startIndex:chunkStart,endIndex:charIndex}),chunkStart=charIndex,currentWidth=0),wrapOppIndex=-1),gWidth>maxWidth){let subChunks=wordWrapLine(grapheme,maxWidth);for(let j=0;j<subChunks.length-1;j++){let sc=subChunks[j];chunks.push({text:sc.text,startIndex:charIndex+sc.startIndex,endIndex:charIndex+sc.endIndex})}let last=subChunks[subChunks.length-1];chunkStart=charIndex+last.startIndex,currentWidth=visibleWidth(last.text),wrapOppIndex=-1;continue}currentWidth+=gWidth;let next=segments[i+1];if(isWs&&next&&(isAtomicMarker(next.segment)||!isWhitespaceChar(next.segment)))wrapOppIndex=next.index,wrapOppWidth=currentWidth;else if(!isWs&&next&&!isWhitespaceChar(next.segment)){let isCjk=!isAtomicMarker(grapheme)&&cjkBreakRegex.test(grapheme),nextIsCjk=!isAtomicMarker(next.segment)&&cjkBreakRegex.test(next.segment);(isCjk||nextIsCjk)&&(wrapOppIndex=next.index,wrapOppWidth=currentWidth)}}return chunks.push({text:line.slice(chunkStart),startIndex:chunkStart,endIndex:line.length}),chunks}var SLASH_COMMAND_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS=20,DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS=["@","#","$"],unquotedAutocompleteSuffixRegex=new RegExp(`(?:(?!${autocompleteSeparatorRegex.source}).)*`,"u"),autocompleteTokenStartSource=`${autocompleteBoundaryRegex.source}[([{<\`]*`;function escapeCharacterClass(value){return value.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}function buildTriggerPattern(triggerCharacters){return new RegExp(`${autocompleteTokenStartSource}(?:@"[^"]*|[${triggerCharacters.map(escapeCharacterClass).join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function buildDebouncePattern(triggerCharacters){let escapedWithoutAt=triggerCharacters.filter(character=>character!=="@").map(escapeCharacterClass);return new RegExp(`${autocompleteTokenStartSource}(?:@(?:"[^"]*|${unquotedAutocompleteSuffixRegex.source})|[${escapedWithoutAt.join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function createScrollBorder(direction,hiddenLineCount,width){let availableWidth=Math.max(0,width),label=` ${direction} ${hiddenLineCount} more `,labelWidth=visibleWidth(label);if(labelWidth+2<=availableWidth){let leftWidth=Math.floor((availableWidth-labelWidth)/2);return"\u2500".repeat(leftWidth)+label+"\u2500".repeat(availableWidth-leftWidth-labelWidth)}let indicator=`\u2500\u2500\u2500 ${direction} ${hiddenLineCount} more `,remaining=availableWidth-visibleWidth(indicator);if(remaining>=0)return indicator+"\u2500".repeat(remaining);let ellipsis="...".slice(0,availableWidth),indicatorWidth=availableWidth-visibleWidth(ellipsis);return sliceByColumn(indicator,0,indicatorWidth,!0)+ellipsis}var Editor=class{constructor(tui,theme,options={}){this.state={lines:[""],cursorLine:0,cursorCol:0},this.focused=!1,this.paddingX=0,this.lastWidth=80,this.renderedVisibleLineCount=1,this.renderedAutocompleteHeight=0,this.scrollOffset=0,this.autocompleteTriggerCharacters=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS],this.autocompleteTriggerPattern=buildTriggerPattern(this.autocompleteTriggerCharacters),this.autocompleteDebouncePattern=buildDebouncePattern(this.autocompleteTriggerCharacters),this.autocompleteState=null,this.autocompletePrefix="",this.autocompleteItems=[],this.autocompleteMaxVisible=5,this.autocompleteRequestTask=Promise.resolve(),this.autocompleteStartToken=0,this.autocompleteRequestId=0,this.pasteMarkers=new PasteMarkerRegistry,this.imageMarkers=new ImageMarkerRegistry,this.pasteBuffer="",this.isInPaste=!1,this.history=[],this.historyIndex=-1,this.historyDraft=null,this.killRing=new KillRing,this.lastAction=null,this.jumpMode=null,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.undoStack=new UndoStack,this.wrappedLineCache=[],this.disableSubmit=!1,this.tui=tui,this.theme=theme,this.borderColor=theme.borderColor;let paddingX=options.paddingX??0;this.paddingX=Number.isFinite(paddingX)?Math.max(0,Math.floor(paddingX)):0,this.terminalEnvironment=options.terminalEnvironment,this.terminalPlatform=options.terminalPlatform,this.terminalSocketExists=options.terminalSocketExists;let maxVisible=options.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5}segment(text,mode){return segmentWithMarkers(text,mode==="word"?wordSegmenter4:graphemeSegmenter2,this.authorizedMarkers(text))}authorizedMarkers(text){let imageMarkers=this.imageMarkers.authorizedMarkers(text);if(imageMarkers.size===0)return this.pasteMarkers.authorizedMarkers(text);let merged=new Set(this.pasteMarkers.authorizedMarkers(text));for(let marker of imageMarkers)merged.add(marker);return merged}removePasteMarker(id){let removal=this.pasteMarkers.remove(id,this.getText());return removal.removed?(this.state.lines=removal.text.split(`
`),!0):!1}removeImageMarker(id){let survivors=this.imageMarkers.ids(this.getText()).filter(entryId=>entryId!==id),removal=this.imageMarkers.remove(id,this.getText());return removal.removed?(this.state.lines=removal.text.split(`
`),this.onImageMarkersChanged?.(survivors),!0):!1}removeMarkerSegment(segment){switch(markerKind(segment)){case"paste":{let id=pasteMarkerId(segment);return id!==void 0&&this.removePasteMarker(id)}case"image":{let id=imageMarkerId(segment);return id!==void 0&&this.removeImageMarker(id)}default:return!1}}notifyImageMarkersChanged(){this.onImageMarkersChanged?.(this.imageMarkers.ids(this.getText()))}getPaddingX(){return this.paddingX}setPaddingX(padding){let newPadding=Number.isFinite(padding)?Math.max(0,Math.floor(padding)):0;this.paddingX!==newPadding&&(this.paddingX=newPadding,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(maxVisible){let newMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5;this.autocompleteMaxVisible!==newMaxVisible&&(this.autocompleteMaxVisible=newMaxVisible,this.tui.requestRender())}setAutocompleteProvider(provider){this.cancelAutocomplete(),this.autocompleteProvider=provider,this.setAutocompleteTriggerCharacters(provider.triggerCharacters??[])}addToHistory(text){let trimmed=text.trim();trimmed&&(this.history.length>0&&this.history[0]===trimmed||(this.history.unshift(trimmed),this.history.length>100&&this.history.pop()))}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===""}isOnFirstVisualLine(){let visualLines=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(visualLines)===0}isOnLastVisualLine(){let visualLines=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(visualLines)===visualLines.length-1}navigateHistory(direction){if(this.lastAction=null,this.history.length===0)return;let newIndex=this.historyIndex-direction;if(!(newIndex<-1||newIndex>=this.history.length))if(this.historyIndex===-1&&newIndex>=0&&(this.pushUndoSnapshot(),this.historyDraft=structuredClone(this.state)),this.historyIndex=newIndex,this.historyIndex===-1){let draft=this.historyDraft;this.historyDraft=null,draft?(this.state=draft,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.scrollOffset=0,this.onChange&&this.onChange(this.getText())):this.setTextInternal("")}else this.setTextInternal(this.history[this.historyIndex]||"",direction===-1?"start":"end")}exitHistoryBrowsing(){this.historyIndex=-1,this.historyDraft=null}setTextInternal(text,cursorPlacement="end"){let lines=text.split(`
`);this.state.lines=lines.length===0?[""]:lines,this.state.cursorLine=cursorPlacement==="start"?0:this.state.lines.length-1,this.setCursorCol(cursorPlacement==="start"?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){this.wrappedLineCache.length=0}getWrappedLine(lineIndex,contentWidth){let line=this.state.lines[lineIndex]||"",cached=this.wrappedLineCache[lineIndex];if(cached&&cached.lineRef===line&&cached.contentWidth===contentWidth)return cached;let width=isPrintableAsciiText(line)?line.length:visibleWidth(line);if(containsMarkerPrefix(line))return{width,chunks:width<=contentWidth?[{text:line,startIndex:0,endIndex:line.length}]:wordWrapLine(line,contentWidth,[...this.segment(line,"grapheme")])};let wrapped={lineRef:line,contentWidth,width,chunks:width<=contentWidth?[{text:line,startIndex:0,endIndex:line.length}]:wordWrapLine(line,contentWidth)};return this.wrappedLineCache[lineIndex]=wrapped,wrapped}renderTopBorder(width,hiddenLineCount){let border=hiddenLineCount>0?createScrollBorder("\u2191",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}renderBottomBorder(width,hiddenLineCount){let border=hiddenLineCount>0?createScrollBorder("\u2193",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}keywordRangesByLine(highlight){let text=this.state.lines.join(`
`);return this.keywordRunsCache?.text!==text&&(this.keywordRunsCache={text,byLine:keywordRangesByLine(this.state.lines,highlight.find(text))}),this.keywordRunsCache.byLine}render(width){let maxPadding=Math.max(0,Math.floor((width-1)/2)),paddingX=Math.min(this.paddingX,maxPadding),contentWidth=Math.max(1,width-paddingX*2),layoutWidth=Math.max(1,contentWidth-(paddingX?0:1));this.lastWidth=layoutWidth;let layoutLines=this.layoutText(layoutWidth),terminalRows=this.tui.terminal.rows,maxVisibleLines=Math.max(5,Math.floor(terminalRows*.3)),cursorLineIndex=layoutLines.findIndex(line=>line.hasCursor);cursorLineIndex===-1&&(cursorLineIndex=0),cursorLineIndex<this.scrollOffset?this.scrollOffset=cursorLineIndex:cursorLineIndex>=this.scrollOffset+maxVisibleLines&&(this.scrollOffset=cursorLineIndex-maxVisibleLines+1);let maxScrollOffset=Math.max(0,layoutLines.length-maxVisibleLines);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,maxScrollOffset));let visibleLines=layoutLines.slice(this.scrollOffset,this.scrollOffset+maxVisibleLines);this.renderedVisibleLineCount=visibleLines.length;let result=[],leftPadding=" ".repeat(paddingX),rightPadding=leftPadding;result.push(this.renderTopBorder(width,this.scrollOffset));let emitCursorMarker=this.focused,drawFakeCursor=!this.tui.getShowHardwareCursor(),mentionStyle=this.theme.mention,mentionRangesByLine=new Map,mentionRangesFor=layoutLine=>{if(!mentionStyle||!this.autocompleteProvider?.getMentionRanges)return[];let ranges=mentionRangesByLine.get(layoutLine.logicalLine);return ranges===void 0&&(ranges=this.autocompleteProvider.getMentionRanges(this.state.lines[layoutLine.logicalLine]??""),mentionRangesByLine.set(layoutLine.logicalLine,ranges)),ranges.map(range=>({start:range.start-layoutLine.startIndex,end:range.end-layoutLine.startIndex}))},keywordHighlight=this.theme.keywordHighlight,keywordRangesByLine2=keywordHighlight?this.keywordRangesByLine(keywordHighlight):void 0,keywordRangesFor=layoutLine=>(keywordRangesByLine2?.get(layoutLine.logicalLine)??[]).map(range=>({start:range.start-layoutLine.startIndex,end:range.end-layoutLine.startIndex,runStart:range.runStart-layoutLine.startIndex,runLength:range.runLength}));for(let layoutLine of visibleLines){let lineVisibleWidth=visibleWidth(layoutLine.text),cursorInPadding=!1,cursor=layoutLine.hasCursor&&layoutLine.cursorPos!==void 0?{pos:layoutLine.cursorPos,marker:emitCursorMarker?CURSOR_MARKER:"",drawFakeCursor}:void 0,rendered=renderEditorLine({text:layoutLine.text,mentions:mentionRangesFor(layoutLine),mentionStyle:mentionStyle??(text=>text),keywords:keywordRangesFor(layoutLine),keywordStyle:keywordHighlight?.style,cursor,firstGrapheme:text=>[...this.segment(text,"grapheme")][0]?.segment??""}),displayText=rendered.text;rendered.cursorAppended&&(lineVisibleWidth=lineVisibleWidth+1,lineVisibleWidth>contentWidth&&paddingX>0&&(cursorInPadding=!0));let padding=" ".repeat(Math.max(0,contentWidth-lineVisibleWidth)),lineRightPadding=cursorInPadding?rightPadding.slice(1):rightPadding;result.push(`${leftPadding}${displayText}${padding}${lineRightPadding}`)}let linesBelow=layoutLines.length-(this.scrollOffset+visibleLines.length);if(result.push(this.renderBottomBorder(width,linesBelow)),this.renderedAutocompleteHeight=0,this.autocompleteState&&this.autocompleteList){let autocompleteResult=this.autocompleteList.render(contentWidth);this.renderedAutocompleteHeight=autocompleteResult.length;for(let line of autocompleteResult){let lineWidth=visibleWidth(line),linePadding=" ".repeat(Math.max(0,contentWidth-lineWidth));result.push(`${leftPadding}${line}${linePadding}${rightPadding}`)}}return result}handleMouse(event){let autocompleteStartRow=this.renderedVisibleLineCount+2;if(this.autocompleteState&&this.autocompleteList&&event.y>=autocompleteStartRow&&event.y<autocompleteStartRow+this.renderedAutocompleteHeight){let maxPadding2=Math.max(0,Math.floor((event.width-1)/2)),paddingX2=Math.min(this.paddingX,maxPadding2),contentWidth=Math.max(1,event.width-paddingX2*2),result=this.autocompleteList.handleMouse?.({...event,x:event.x-paddingX2,y:event.y-autocompleteStartRow,width:contentWidth,height:this.renderedAutocompleteHeight});return result?{...result,focus:!0}:void 0}if(event.type!=="click"||event.button!=="left")return;if(event.y<=0||event.y>this.renderedVisibleLineCount)return{handled:!0,focus:!0};let visualLines=this.buildVisualLineMap(this.lastWidth),visualLineIndex=this.scrollOffset+event.y-1,visualLine=visualLines[visualLineIndex];if(!visualLine)return{handled:!0,focus:!0};let logicalLine=this.state.lines[visualLine.logicalLine]??"",chunkEnd=visualLine.startCol+visualLine.length,chunk=logicalLine.slice(visualLine.startCol,chunkEnd),maxPadding=Math.max(0,Math.floor((event.width-1)/2)),paddingX=Math.min(this.paddingX,maxPadding),targetColumn=Math.max(0,event.x-paddingX),visibleColumn=0,targetIndex=chunk.length,lastGraphemeIndex=0;for(let grapheme of this.segment(chunk,"grapheme")){let nextColumn=visibleColumn+visibleWidth(grapheme.segment);if(lastGraphemeIndex=grapheme.index,targetColumn<nextColumn){targetIndex=grapheme.index;break}visibleColumn=nextColumn}return!(visualLineIndex===visualLines.length-1||visualLines[visualLineIndex+1]?.logicalLine!==visualLine.logicalLine)&&targetIndex===chunk.length&&chunk.length>0&&(targetIndex=lastGraphemeIndex),this.state.cursorLine=visualLine.logicalLine,this.setCursorCol(visualLine.startCol+targetIndex),this.lastAction=null,this.exitHistoryBrowsing(),this.autocompleteState&&this.updateAutocomplete(),{handled:!0,focus:!0}}handleInput(data){data=normalizeWarpWslShiftEnterInput(data,this.terminalEnvironment,this.terminalPlatform,this.terminalSocketExists);let kb=getKeybindings();if(this.jumpMode!==null){if(kb.matches(data,"tui.editor.jumpForward")||kb.matches(data,"tui.editor.jumpBackward")){this.jumpMode=null;return}let printable2=decodePrintableKey(data)??(data.charCodeAt(0)>=32?data:void 0);if(printable2!==void 0){let direction=this.jumpMode;this.jumpMode=null,this.jumpToChar(printable2,direction);return}this.jumpMode=null}if(data.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",data=data.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=data;let endIndex=this.pasteBuffer.indexOf("\x1B[201~");if(endIndex!==-1){let pasteContent=this.pasteBuffer.substring(0,endIndex);pasteContent.length>0&&this.handlePaste(pasteContent),this.isInPaste=!1;let remaining=this.pasteBuffer.substring(endIndex+6);this.pasteBuffer="",remaining.length>0&&this.handleInput(remaining);return}return}if(kb.matches(data,"tui.input.copy"))return;if(kb.matches(data,"tui.editor.undo")){this.undo();return}if(this.autocompleteState&&this.autocompleteList){if(kb.matches(data,"tui.select.cancel")){this.cancelAutocomplete();return}if(kb.matches(data,"tui.select.up")||kb.matches(data,"tui.select.down")){this.autocompleteList.handleInput(data);return}if(kb.matches(data,"tui.input.tab")){if(this.isAutocompleteListStale()){this.acceptRefreshedAutocomplete();return}let selected=this.autocompleteList.getSelectedItem();if(selected&&this.autocompleteProvider){let drillsIntoNamespace=this.isSlashNamespaceSelection(selected.value);this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText()),drillsIntoNamespace&&this.tryTriggerAutocomplete()}return}if(kb.matches(data,"tui.select.confirm")){if(!this.autocompletePrefix.startsWith("/")&&this.isAutocompleteListStale()){this.acceptRefreshedAutocomplete();return}let selected=this.autocompleteList.getSelectedItem();if(selected&&this.autocompleteProvider){let drillsIntoNamespace=this.isSlashNamespaceSelection(selected.value);this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);if(this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),drillsIntoNamespace){this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText()),this.tryTriggerAutocomplete();return}if(this.autocompletePrefix.startsWith("/")){let awaitsArguments=this.autocompleteItems.some(item=>item===selected&&item.awaitsArguments===!0);if(this.cancelAutocomplete(),awaitsArguments){this.onChange&&this.onChange(this.getText());return}}else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());return}}}}if(kb.matches(data,"tui.input.tab")&&!this.autocompleteState){this.handleTabCompletion();return}if(kb.matches(data,"tui.editor.deleteToLineEnd")){this.deleteToEndOfLine();return}if(kb.matches(data,"tui.editor.deleteToLineStart")){this.deleteToStartOfLine();return}if(kb.matches(data,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(kb.matches(data,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(kb.matches(data,"tui.editor.deleteCharBackward")||matchesKey(data,"shift+backspace")){this.handleBackspace();return}if(kb.matches(data,"tui.editor.deleteCharForward")||matchesKey(data,"shift+delete")){this.handleForwardDelete();return}if(kb.matches(data,"tui.editor.yank")){this.yank();return}if(kb.matches(data,"tui.editor.yankPop")){this.yankPop();return}if(kb.matches(data,"tui.editor.historyPrevious")){this.cancelAutocomplete(),this.navigateHistory(-1);return}if(kb.matches(data,"tui.editor.historyNext")){this.cancelAutocomplete(),this.navigateHistory(1);return}if(kb.matches(data,"tui.editor.cursorLineStart")){this.moveToLineStart();return}if(kb.matches(data,"tui.editor.cursorLineEnd")){this.moveToLineEnd();return}if(kb.matches(data,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(kb.matches(data,"tui.editor.cursorWordRight")){this.moveWordForwards();return}if(kb.matches(data,"tui.input.submit")){if(this.disableSubmit)return;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0&¤tLine[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(kb.matches(data,"tui.input.newLine")||data.charCodeAt(0)===10&&data.length>1||data==="\x1B\r"||data==="\x1B[13;2~"||data.length>1&&data.includes("\x1B")&&data.includes("\r")||data===`
`&&data.length===1){if(this.shouldSubmitOnBackslashEnter(data,kb)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(kb.matches(data,"tui.editor.cursorUp")){this.isOnFirstVisualLine()&&(this.isEditorEmpty()||this.historyIndex>-1||this.state.cursorCol===0)?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0);return}if(kb.matches(data,"tui.editor.cursorDown")){this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0);return}if(kb.matches(data,"tui.editor.cursorRight")){this.moveCursor(0,1);return}if(kb.matches(data,"tui.editor.cursorLeft")){this.moveCursor(0,-1);return}if(kb.matches(data,"tui.editor.pageUp")){this.pageScroll(-1);return}if(kb.matches(data,"tui.editor.pageDown")){this.pageScroll(1);return}if(kb.matches(data,"tui.editor.jumpForward")){this.jumpMode="forward";return}if(kb.matches(data,"tui.editor.jumpBackward")){this.jumpMode="backward";return}if(matchesKey(data,"shift+space")){this.insertCharacter(" ");return}let printable=decodePrintableKey(data);if(printable!==void 0){this.insertCharacter(printable);return}data.charCodeAt(0)>=32&&this.insertCharacter(data)}layoutText(contentWidth){let layoutLines=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]==="")return this.wrappedLineCache.length=this.state.lines.length,layoutLines.push({text:"",hasCursor:!0,cursorPos:0,logicalLine:0,startIndex:0}),layoutLines;for(let i=0;i<this.state.lines.length;i++){let line=this.state.lines[i]||"",isCurrentLine=i===this.state.cursorLine,wrappedLine=this.getWrappedLine(i,contentWidth);if(wrappedLine.width<=contentWidth)isCurrentLine?layoutLines.push({text:line,hasCursor:!0,cursorPos:this.state.cursorCol,logicalLine:i,startIndex:0}):layoutLines.push({text:line,hasCursor:!1,logicalLine:i,startIndex:0});else{let chunks=wrappedLine.chunks;for(let chunkIndex=0;chunkIndex<chunks.length;chunkIndex++){let chunk=chunks[chunkIndex];if(!chunk)continue;let cursorPos=this.state.cursorCol,isLastChunk=chunkIndex===chunks.length-1,hasCursorInChunk=!1,adjustedCursorPos=0;isCurrentLine&&(isLastChunk?(hasCursorInChunk=cursorPos>=chunk.startIndex,adjustedCursorPos=cursorPos-chunk.startIndex):(hasCursorInChunk=cursorPos>=chunk.startIndex&&cursorPos<chunk.endIndex,hasCursorInChunk&&(adjustedCursorPos=cursorPos-chunk.startIndex,adjustedCursorPos>chunk.text.length&&(adjustedCursorPos=chunk.text.length)))),hasCursorInChunk?layoutLines.push({text:chunk.text,hasCursor:!0,cursorPos:adjustedCursorPos,logicalLine:i,startIndex:chunk.startIndex}):layoutLines.push({text:chunk.text,hasCursor:!1,logicalLine:i,startIndex:chunk.startIndex})}}}return this.wrappedLineCache.length=this.state.lines.length,layoutLines}getText(){return this.state.lines.join(`
`)}getExpandedText(){return this.pasteMarkers.expand(this.state.lines.join(`
`))}getLines(){return[...this.state.lines]}getCursor(){return{line:this.state.cursorLine,col:this.state.cursorCol}}setText(text){this.cancelAutocomplete(),this.lastAction=null,this.exitHistoryBrowsing();let normalized=this.normalizeText(text),previousText=this.getText();previousText!==normalized&&this.pushUndoSnapshot(),this.pasteMarkers.prune(normalized,previousText);let previousImageOrder=this.imageMarkers.ids(previousText);this.imageMarkers.prune(normalized,previousText),this.setTextInternal(normalized);let canonicalization=this.imageMarkers.canonicalize(normalized);this.applyCanonicalizedText(canonicalization);let imageOrder=canonicalization.order;(previousImageOrder.length!==imageOrder.length||previousImageOrder.some((id,i)=>id!==imageOrder[i]))&&this.onImageMarkersChanged?.(imageOrder)}getPasteState(){return this.pasteMarkers.snapshot()}setPasteState(state){this.pasteMarkers.install(state,this.getText())}getImageMarkerState(){return this.imageMarkers.snapshot()}setImageMarkerState(state){this.imageMarkers.install(state,this.getText())}insertImageMarker(){this.cancelAutocomplete(),this.pushUndoSnapshot(),this.lastAction=null,this.exitHistoryBrowsing();let marker=this.imageMarkers.add();this.insertTextAtCursorInternal(marker);let canonicalization=this.imageMarkers.canonicalize(this.getText());this.applyCanonicalizedText(canonicalization);let insertionId=imageMarkerId(marker),finalId=canonicalization.order.includes(insertionId)?canonicalization.order.indexOf(insertionId)+1:insertionId;return this.onImageMarkersChanged?.(canonicalization.order),finalId}applyCanonicalizedText(canonicalization){if(canonicalization.text===this.getText())return;let oldLine=this.state.lines[this.state.cursorLine]??"",cursorCol=this.state.cursorCol,renumbered=new Map;for(let[index,id]of canonicalization.order.entries())renumbered.set(id,index+1);let delta=0;for(let match of oldLine.matchAll(IMAGE_MARKER_REGEX)){if((match.index??0)+match[0].length>cursorCol)break;let newId=renumbered.get(Number.parseInt(match[1]??"0",10));newId!==void 0&&(delta+=formatImageMarker(newId).length-match[0].length)}this.state.lines=canonicalization.text.split(`
`),this.setCursorCol(Math.max(0,cursorCol+delta))}insertTextAtCursor(text){text&&(this.cancelAutocomplete(),this.pushUndoSnapshot(),this.lastAction=null,this.exitHistoryBrowsing(),this.insertTextAtCursorInternal(text))}normalizeText(text){return text.replace(/\r\n/g,`
`).replace(/\r/g,`
`).replace(/\t/g," ")}insertTextAtCursorInternal(text){if(!text)return;let normalized=this.normalizeText(text),insertedLines=normalized.split(`
`),currentLine=this.state.lines[this.state.cursorLine]||"",beforeCursor=currentLine.slice(0,this.state.cursorCol),afterCursor=currentLine.slice(this.state.cursorCol);insertedLines.length===1?(this.state.lines[this.state.cursorLine]=beforeCursor+normalized+afterCursor,this.setCursorCol(this.state.cursorCol+normalized.length)):(this.state.lines=[...this.state.lines.slice(0,this.state.cursorLine),beforeCursor+insertedLines[0],...insertedLines.slice(1,-1),insertedLines[insertedLines.length-1]+afterCursor,...this.state.lines.slice(this.state.cursorLine+1)],this.state.cursorLine+=insertedLines.length-1,this.setCursorCol((insertedLines[insertedLines.length-1]||"").length)),this.onChange&&this.onChange(this.getText())}insertCharacter(char,skipUndoCoalescing){this.exitHistoryBrowsing(),skipUndoCoalescing||((isWhitespaceChar(char)||this.lastAction!=="type-word")&&this.pushUndoSnapshot(),this.lastAction="type-word");let line=this.state.lines[this.state.cursorLine]||"",before=line.slice(0,this.state.cursorCol),after=line.slice(this.state.cursorCol);if(this.state.lines[this.state.cursorLine]=before+char+after,this.setCursorCol(this.state.cursorCol+char.length),this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else if(char==="/"&&this.isAtStartOfMessage())this.tryTriggerAutocomplete();else if(this.autocompleteTriggerCharacters.includes(char)){let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}else if(/[a-zA-Z0-9.\-_]/.test(char)||cjkBreakRegex.test(char)){let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}}handlePaste(pastedText){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let decodedText=pastedText.replace(/\x1b\[(\d+);5u/g,(match,code)=>{let cp=Number(code);return cp>=97&&cp<=122?String.fromCharCode(cp-96):cp>=65&&cp<=90?String.fromCharCode(cp-64):match}),filteredText=this.normalizeText(decodedText).split("").filter(char=>char===`
`||char.charCodeAt(0)>=32).join("");if(/^[/~.]/.test(filteredText)){let currentLine=this.state.lines[this.state.cursorLine]||"",charBeforeCursor=this.state.cursorCol>0?currentLine[this.state.cursorCol-1]:"";charBeforeCursor&&/\w/.test(charBeforeCursor)&&(filteredText=` ${filteredText}`)}let pastedLines=filteredText.split(`
`),totalChars=filteredText.length;if(pastedLines.length>10||totalChars>1e3){let marker=this.pasteMarkers.add(filteredText,pastedLines.length,totalChars);this.insertTextAtCursorInternal(marker);return}if(pastedLines.length===1){this.insertTextAtCursorInternal(filteredText);return}this.insertTextAtCursorInternal(filteredText)}addNewLine(){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let currentLine=this.state.lines[this.state.cursorLine]||"",before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before,this.state.lines.splice(this.state.cursorLine+1,0,after),this.state.cursorLine++,this.setCursorCol(0),this.onChange&&this.onChange(this.getText())}shouldSubmitOnBackslashEnter(data,kb){if(this.disableSubmit||!matchesKey(data,"enter"))return!1;let submitKeys=kb.getKeys("tui.input.submit");if(!(submitKeys.includes("shift+enter")||submitKeys.includes("shift+return")))return!1;let currentLine=this.state.lines[this.state.cursorLine]||"";return this.state.cursorCol>0&¤tLine[this.state.cursorCol-1]==="\\"}submitValue(){this.cancelAutocomplete();let rawText=this.pasteMarkers.expand(this.state.lines.join(`
`)),result=rawText.trim();this.state={lines:[""],cursorLine:0,cursorCol:0},this.pasteMarkers.clear(),this.imageMarkers.clear(),this.exitHistoryBrowsing(),this.scrollOffset=0,this.undoStack.clear(),this.lastAction=null,this.onChange&&this.onChange(""),this.onSubmit&&this.onSubmit(result,{rawText})}handleBackspace(){if(this.exitHistoryBrowsing(),this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let line=this.state.lines[this.state.cursorLine]||"",beforeCursor=line.slice(0,this.state.cursorCol),graphemes=[...this.segment(beforeCursor,"grapheme")],lastGrapheme=graphemes[graphemes.length-1],graphemeLength=lastGrapheme?lastGrapheme.segment.length:1;if(this.removeMarkerSegment(lastGrapheme?.segment??""))this.setCursorCol(Math.max(0,this.state.cursorCol-graphemeLength));else{line=this.state.lines[this.state.cursorLine]||"";let before=line.slice(0,this.state.cursorCol-graphemeLength),after=line.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+after,this.setCursorCol(this.state.cursorCol-graphemeLength)}}else if(this.state.cursorLine>0){this.pushUndoSnapshot();let currentLine=this.state.lines[this.state.cursorLine]||"",previousLine=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=previousLine+currentLine,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(previousLine.length)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}}setCursorCol(col){this.state.cursorCol=col,this.preferredVisualCol=null,this.snappedFromCursorCol=null}moveToVisualLine(visualLines,currentVisualLine,targetVisualLine){let currentVL=visualLines[currentVisualLine],targetVL=visualLines[targetVisualLine];if(!(currentVL&&targetVL))return;let currentVisualCol;if(this.snappedFromCursorCol!==null){let vlIndex=this.findVisualLineAt(visualLines,currentVL.logicalLine,this.snappedFromCursorCol);currentVisualCol=this.snappedFromCursorCol-visualLines[vlIndex].startCol}else currentVisualCol=this.state.cursorCol-currentVL.startCol;let sourceMaxVisualCol=currentVisualLine===visualLines.length-1||visualLines[currentVisualLine+1]?.logicalLine!==currentVL.logicalLine?currentVL.length:Math.max(0,currentVL.length-1),targetMaxVisualCol=targetVisualLine===visualLines.length-1||visualLines[targetVisualLine+1]?.logicalLine!==targetVL.logicalLine?targetVL.length:Math.max(0,targetVL.length-1),moveToVisualCol=this.computeVerticalMoveColumn(currentVisualCol,sourceMaxVisualCol,targetMaxVisualCol);this.state.cursorLine=targetVL.logicalLine;let targetCol=targetVL.startCol+moveToVisualCol,logicalLine=this.state.lines[targetVL.logicalLine]||"";this.state.cursorCol=Math.min(targetCol,logicalLine.length);let segments=[...this.segment(logicalLine,"grapheme")];for(let seg of segments){if(seg.index>this.state.cursorCol)break;if(!(seg.segment.length<=1)&&this.state.cursorCol<seg.index+seg.segment.length){let isContinuation=seg.index<targetVL.startCol,isMovingDown=targetVisualLine>currentVisualLine;if(isContinuation&&isMovingDown){let segEnd=seg.index+seg.segment.length,next=targetVisualLine+1;for(;next<visualLines.length&&visualLines[next].logicalLine===targetVL.logicalLine&&visualLines[next].startCol<segEnd;)next++;if(next<visualLines.length){this.moveToVisualLine(visualLines,currentVisualLine,next);return}}this.snappedFromCursorCol=this.state.cursorCol,this.state.cursorCol=seg.index;return}}this.snappedFromCursorCol=null}computeVerticalMoveColumn(currentVisualCol,sourceMaxVisualCol,targetMaxVisualCol){let hasPreferred=this.preferredVisualCol!==null,cursorInMiddle=currentVisualCol<sourceMaxVisualCol,targetTooShort=targetMaxVisualCol<currentVisualCol;if(!hasPreferred||cursorInMiddle)return targetTooShort?(this.preferredVisualCol=currentVisualCol,targetMaxVisualCol):(this.preferredVisualCol=null,currentVisualCol);let targetCantFitPreferred=targetMaxVisualCol<this.preferredVisualCol;if(targetTooShort||targetCantFitPreferred)return targetMaxVisualCol;let result=this.preferredVisualCol;return this.preferredVisualCol=null,result}moveToLineStart(){this.lastAction=null,this.setCursorCol(0)}moveToLineEnd(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(currentLine.length)}deleteToStartOfLine(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0){this.pushUndoSnapshot();let deletedText=currentLine.slice(0,this.state.cursorCol);this.killRing.push(deletedText,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(this.state.cursorCol),this.setCursorCol(0)}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
`,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let previousLine=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=previousLine+currentLine,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(previousLine.length)}this.onChange&&this.onChange(this.getText())}deleteToEndOfLine(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<currentLine.length){this.pushUndoSnapshot();let deletedText=currentLine.slice(this.state.cursorCol);this.killRing.push(deletedText,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(0,this.state.cursorCol)}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
`,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let nextLine=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=currentLine+nextLine,this.state.lines.splice(this.state.cursorLine+1,1)}this.onChange&&this.onChange(this.getText())}deleteWordBackwards(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
`,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let previousLine=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=previousLine+currentLine,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(previousLine.length)}}else{this.pushUndoSnapshot();let wasKill=this.lastAction==="kill",oldCursorCol=this.state.cursorCol;this.moveWordBackwards();let deleteFrom=this.state.cursorCol;this.setCursorCol(oldCursorCol);let deletedText=currentLine.slice(deleteFrom,this.state.cursorCol);this.killRing.push(deletedText,{prepend:!0,accumulate:wasKill}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(0,deleteFrom)+currentLine.slice(this.state.cursorCol),this.setCursorCol(deleteFrom)}this.onChange&&this.onChange(this.getText())}deleteWordForward(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=currentLine.length){if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
`,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let nextLine=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=currentLine+nextLine,this.state.lines.splice(this.state.cursorLine+1,1)}}else{this.pushUndoSnapshot();let wasKill=this.lastAction==="kill",oldCursorCol=this.state.cursorCol;this.moveWordForwards();let deleteTo=this.state.cursorCol;this.setCursorCol(oldCursorCol);let deletedText=currentLine.slice(this.state.cursorCol,deleteTo);this.killRing.push(deletedText,{prepend:!1,accumulate:wasKill}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(0,this.state.cursorCol)+currentLine.slice(deleteTo)}this.onChange&&this.onChange(this.getText())}handleForwardDelete(){this.exitHistoryBrowsing(),this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<currentLine.length){this.pushUndoSnapshot();let afterCursor=currentLine.slice(this.state.cursorCol),firstGrapheme=[...this.segment(afterCursor,"grapheme")][0];if(this.removeMarkerSegment(firstGrapheme?.segment??"")){this.onChange?.(this.getText());return}let graphemeLength=firstGrapheme?firstGrapheme.segment.length:1,before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol+graphemeLength);this.state.lines[this.state.cursorLine]=before+after}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot();let nextLine=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=currentLine+nextLine,this.state.lines.splice(this.state.cursorLine+1,1)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}}buildVisualLineMap(width){let visualLines=[];for(let i=0;i<this.state.lines.length;i++){let line=this.state.lines[i]||"",lineVisWidth=visibleWidth(line);if(line.length===0)visualLines.push({logicalLine:i,startCol:0,length:0});else if(lineVisWidth<=width)visualLines.push({logicalLine:i,startCol:0,length:line.length});else{let chunks=this.getWrappedLine(i,width).chunks;for(let chunk of chunks)visualLines.push({logicalLine:i,startCol:chunk.startIndex,length:chunk.endIndex-chunk.startIndex})}}return visualLines}findVisualLineAt(visualLines,line,col){for(let i=0;i<visualLines.length;i++){let vl=visualLines[i];if(!vl||vl.logicalLine!==line)continue;let offset=col-vl.startCol,isLastSegmentOfLine=i===visualLines.length-1||visualLines[i+1]?.logicalLine!==vl.logicalLine;if(offset>=0&&(offset<vl.length||isLastSegmentOfLine&&offset===vl.length))return i}return visualLines.length-1}findCurrentVisualLine(visualLines){return this.findVisualLineAt(visualLines,this.state.cursorLine,this.state.cursorCol)}moveCursor(deltaLine,deltaCol){this.lastAction=null;let visualLines=this.buildVisualLineMap(this.lastWidth),currentVisualLine=this.findCurrentVisualLine(visualLines);if(deltaLine!==0){let targetVisualLine=currentVisualLine+deltaLine;targetVisualLine>=0&&targetVisualLine<visualLines.length&&this.moveToVisualLine(visualLines,currentVisualLine,targetVisualLine)}if(deltaCol!==0){let currentLine=this.state.lines[this.state.cursorLine]||"";if(deltaCol>0)if(this.state.cursorCol<currentLine.length){let afterCursor=currentLine.slice(this.state.cursorCol),firstGrapheme=[...this.segment(afterCursor,"grapheme")][0];this.setCursorCol(this.state.cursorCol+(firstGrapheme?firstGrapheme.segment.length:1))}else if(this.state.cursorLine<this.state.lines.length-1)this.state.cursorLine++,this.setCursorCol(0);else{let currentVL=visualLines[currentVisualLine];currentVL&&(this.preferredVisualCol=this.state.cursorCol-currentVL.startCol)}else if(this.state.cursorCol>0){let beforeCursor=currentLine.slice(0,this.state.cursorCol),graphemes=[...this.segment(beforeCursor,"grapheme")],lastGrapheme=graphemes[graphemes.length-1];this.setCursorCol(this.state.cursorCol-(lastGrapheme?lastGrapheme.segment.length:1))}else if(this.state.cursorLine>0){this.state.cursorLine--;let prevLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(prevLine.length)}}this.autocompleteState&&this.updateAutocomplete()}pageScroll(direction){this.lastAction=null;let terminalRows=this.tui.terminal.rows,pageSize=Math.max(5,Math.floor(terminalRows*.3)),visualLines=this.buildVisualLineMap(this.lastWidth),currentVisualLine=this.findCurrentVisualLine(visualLines),targetVisualLine=Math.max(0,Math.min(visualLines.length-1,currentVisualLine+direction*pageSize));this.moveToVisualLine(visualLines,currentVisualLine,targetVisualLine)}moveWordBackwards(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.state.cursorLine--;let prevLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(prevLine.length)}return}this.setCursorCol(findWordBackward(currentLine,this.state.cursorCol,{segment:text=>this.segment(text,"word"),isAtomicSegment:isAtomicMarker}))}yank(){if(this.killRing.length===0)return;this.pushUndoSnapshot();let text=this.killRing.peek();this.insertYankedText(text),this.lastAction="yank"}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();let text=this.killRing.peek();this.insertYankedText(text),this.lastAction="yank"}insertYankedText(text){this.exitHistoryBrowsing();let lines=text.split(`
`);if(lines.length===1){let currentLine=this.state.lines[this.state.cursorLine]||"",before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+text+after,this.setCursorCol(this.state.cursorCol+text.length)}else{let currentLine=this.state.lines[this.state.cursorLine]||"",before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+(lines[0]||"");for(let i=1;i<lines.length-1;i++)this.state.lines.splice(this.state.cursorLine+i,0,lines[i]||"");let lastLineIndex=this.state.cursorLine+lines.length-1;this.state.lines.splice(lastLineIndex,0,(lines[lines.length-1]||"")+after),this.state.cursorLine=lastLineIndex,this.setCursorCol((lines[lines.length-1]||"").length)}this.onChange&&this.onChange(this.getText())}deleteYankedText(){let yankedText=this.killRing.peek();if(!yankedText)return;let yankLines=yankedText.split(`
`);if(yankLines.length===1){let currentLine=this.state.lines[this.state.cursorLine]||"",deleteLen=yankedText.length,before=currentLine.slice(0,this.state.cursorCol-deleteLen),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+after,this.setCursorCol(this.state.cursorCol-deleteLen)}else{let startLine=this.state.cursorLine-(yankLines.length-1),startCol=(this.state.lines[startLine]||"").length-(yankLines[0]||"").length,afterCursor=(this.state.lines[this.state.cursorLine]||"").slice(this.state.cursorCol),beforeYank=(this.state.lines[startLine]||"").slice(0,startCol);this.state.lines.splice(startLine,yankLines.length,beforeYank+afterCursor),this.state.cursorLine=startLine,this.setCursorCol(startCol)}this.onChange&&this.onChange(this.getText())}pushUndoSnapshot(){this.undoStack.push({state:this.state,pasteState:this.pasteMarkers.snapshot(),imageState:this.imageMarkers.snapshot(),attachmentState:this.snapshotAttachmentState?.()})}undo(){this.exitHistoryBrowsing();let snapshot=this.undoStack.pop();snapshot&&(Object.assign(this.state,snapshot.state),this.pasteMarkers.restore(snapshot.pasteState),this.imageMarkers.restore(snapshot.imageState),snapshot.attachmentState!==void 0&&this.restoreAttachmentState?.(snapshot.attachmentState),this.lastAction=null,this.preferredVisualCol=null,this.onChange&&this.onChange(this.getText()),this.notifyImageMarkersChanged())}jumpToChar(char,direction){this.lastAction=null;let isForward=direction==="forward",lines=this.state.lines,end=isForward?lines.length:-1,step=isForward?1:-1;for(let lineIdx=this.state.cursorLine;lineIdx!==end;lineIdx+=step){let line=lines[lineIdx]||"",searchFrom=lineIdx===this.state.cursorLine?isForward?this.state.cursorCol+1:this.state.cursorCol-1:void 0,idx=isForward?line.indexOf(char,searchFrom):line.lastIndexOf(char,searchFrom);if(idx!==-1){this.state.cursorLine=lineIdx,this.setCursorCol(idx);return}}}moveWordForwards(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=currentLine.length){this.state.cursorLine<this.state.lines.length-1&&(this.state.cursorLine++,this.setCursorCol(0));return}this.setCursorCol(findWordForward(currentLine,this.state.cursorCol,{segment:text=>this.segment(text,"word"),isAtomicSegment:isAtomicMarker}))}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;let beforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return beforeCursor.trim()===""||beforeCursor.trim()==="/"}isInSlashCommandContext(textBeforeCursor){return this.isSlashMenuAllowed()&&textBeforeCursor.trimStart().startsWith("/")}getBestAutocompleteMatchIndex(items,prefix){if(!prefix)return-1;let firstPrefixIndex=-1;for(let i=0;i<items.length;i++){let value=items[i].value;if(value===prefix)return i;firstPrefixIndex===-1&&value.startsWith(prefix)&&(firstPrefixIndex=i)}return firstPrefixIndex}createAutocompleteList(prefix,items){let layout=prefix.startsWith("/")?SLASH_COMMAND_SELECT_LIST_LAYOUT:void 0,list=new SelectList(items,this.autocompleteMaxVisible,this.theme.selectList,layout);return list.onSelect=selected=>{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText())},list}tryTriggerAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!1,explicitTab})}openAutocomplete(){this.tryTriggerAutocomplete()}isSlashNamespaceSelection(value){return this.autocompletePrefix.startsWith("/")&&isSlashNamespaceItem(value)}handleTabCompletion(){if(!this.autocompleteProvider)return;let beforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(beforeCursor)&&!beforeCursor.trimStart().includes(" ")?this.handleSlashCommandCompletion():this.forceFileAutocomplete(!0)}handleSlashCommandCompletion(){this.requestAutocomplete({force:!1,explicitTab:!0})}forceFileAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!0,explicitTab})}requestAutocomplete(options){if(!this.autocompleteProvider||options.force&&!(!this.autocompleteProvider.shouldTriggerFileCompletion||this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return;this.cancelAutocompleteRequest();let startToken=++this.autocompleteStartToken,debounceMs=this.getAutocompleteDebounceMs(options);if(debounceMs>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(startToken,options)},debounceMs);return}this.startAutocompleteRequest(startToken,options)}async startAutocompleteRequest(startToken,options){let previousTask=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await previousTask,startToken!==this.autocompleteStartToken||!this.autocompleteProvider)return;let controller=new AbortController;this.autocompleteAbort=controller;let requestId=++this.autocompleteRequestId,snapshotText=this.getText(),snapshotLine=this.state.cursorLine,snapshotCol=this.state.cursorCol;await this.runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options)})(),await this.autocompleteRequestTask}setAutocompleteTriggerCharacters(triggerCharacters){let next=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];for(let character of triggerCharacters)character.length!==1||character==="/"||isWhitespaceChar(character)||next.includes(character)||next.push(character);this.autocompleteTriggerCharacters=next,this.autocompleteTriggerPattern=buildTriggerPattern(next),this.autocompleteDebouncePattern=buildDebouncePattern(next)}getAutocompleteDebounceMs(options){if(options.explicitTab||options.force)return 0;let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(textBeforeCursor)?ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS:0}async runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options){if(!this.autocompleteProvider)return;let suggestions=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:controller.signal,force:options.force});if(this.isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol)){if(this.autocompleteAbort=void 0,!suggestions||!Array.isArray(suggestions.items)||suggestions.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(options.acceptSelection){let bestMatchIndex=this.getBestAutocompleteMatchIndex(suggestions.items,suggestions.prefix),item=suggestions.items[Math.max(bestMatchIndex,0)],drillsIntoNamespace=suggestions.prefix.startsWith("/")&&isSlashNamespaceItem(item.value);this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,item,suggestions.prefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.clearAutocompleteUi(),this.onChange&&this.onChange(this.getText()),drillsIntoNamespace&&this.tryTriggerAutocomplete(),this.tui.requestRender();return}if(options.force&&options.explicitTab&&suggestions.items.length===1){let item=suggestions.items[0];this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,item,suggestions.prefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(suggestions,options.force?"force":"regular"),this.tui.requestRender()}}isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol){return!controller.signal.aborted&&requestId===this.autocompleteRequestId&&this.getText()===snapshotText&&this.state.cursorLine===snapshotLine&&this.state.cursorCol===snapshotCol}applyAutocompleteSuggestions(suggestions,state){this.autocompletePrefix=suggestions.prefix,this.autocompleteListSnapshot={text:this.getText(),line:this.state.cursorLine,col:this.state.cursorCol},this.autocompleteItems=suggestions.items,this.autocompleteList=this.createAutocompleteList(suggestions.prefix,suggestions.items);let bestMatchIndex=this.getBestAutocompleteMatchIndex(suggestions.items,suggestions.prefix);bestMatchIndex>=0&&this.autocompleteList.setSelectedIndex(bestMatchIndex),this.autocompleteState=state}cancelAutocompleteRequest(){this.autocompleteStartToken+=1,this.autocompleteDebounceTimer&&(clearTimeout(this.autocompleteDebounceTimer),this.autocompleteDebounceTimer=void 0),this.autocompleteAbort?.abort(),this.autocompleteAbort=void 0}clearAutocompleteUi(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompleteItems=[],this.autocompletePrefix="",this.autocompleteListSnapshot=void 0}isAutocompleteListStale(){let snapshot=this.autocompleteListSnapshot;return snapshot!==void 0&&(snapshot.text!==this.getText()||snapshot.line!==this.state.cursorLine||snapshot.col!==this.state.cursorCol)}acceptRefreshedAutocomplete(){this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:!0,acceptSelection:!0})}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:!1})}};var HStack=class extends Stack{constructor(children=[],options={}){super(children,options),this.layoutType="hstack"}render(width){let safeWidth=Math.max(1,width),viewport={width:safeWidth,height:Number.MAX_SAFE_INTEGER},entries=visibleStackEntries(this.entries,viewport);if(entries.length===0)return[];let intrinsicWidths=entries.map(entry=>entry.component.render(safeWidth).reduce((max,line)=>Math.max(max,visibleWidth(line)),0)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,this.gap),rendered=entries.map((entry,index)=>widths[index]===0?[]:entry.component.render(widths[index])),height=rendered.reduce((max,lines)=>Math.max(max,lines.length),0),result=Array.from({length:height},()=>""),x2=0;for(let index=0;index<rendered.length;index++){let lines=rendered[index],childWidth=widths[index],offset=0;this.align==="center"?offset=Math.floor((height-lines.length)/2):this.align==="end"&&(offset=height-lines.length);for(let row=0;row<lines.length;row++){let target=row+offset;target<0||target>=result.length||(result[target]=compositeTuiLine(result[target],lines[row],x2,childWidth,safeWidth))}x2+=childWidth+this.gap}return result}};var Image=class{constructor(base64Data,mimeType,theme,options={},dimensions){this.base64Data=base64Data,this.mimeType=mimeType,this.theme=theme,this.options=options,this.dimensions=dimensions||getImageDimensions(base64Data,mimeType)||{widthPx:800,heightPx:600},this.imageId=options.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0}render(width){if(this.cachedLines&&this.cachedWidth===width)return this.cachedLines;let maxWidth=Math.max(1,Math.min(width-2,this.options.maxWidthCells??60)),cellDimensions2=getCellDimensions(),defaultMaxHeight=Math.max(1,Math.ceil(maxWidth*cellDimensions2.widthPx/cellDimensions2.heightPx)),maxHeight=this.options.maxHeightCells??defaultMaxHeight,caps=getCapabilities(),lines;if(caps.images){caps.images==="kitty"&&this.imageId===void 0&&(this.imageId=allocateImageId());let result=renderImage(this.base64Data,this.dimensions,{maxWidthCells:maxWidth,maxHeightCells:maxHeight,imageId:this.imageId,moveCursor:!1});if(result)if(result.imageId&&(this.imageId=result.imageId),caps.images==="kitty"&&result.lines)lines=result.lines;else if(caps.images==="kitty"){lines=[result.sequence];for(let i=0;i<result.rows-1;i++)lines.push("")}else{lines=[];for(let i=0;i<result.rows-1;i++)lines.push("");let rowOffset=result.rows-1,moveUp=rowOffset>0?`\x1B[${rowOffset}A`:"";lines.push(moveUp+result.sequence)}else{let fallback=imageFallback(this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}}else{let fallback=imageFallback(this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}return this.cachedLines=lines,this.cachedWidth=width,lines}};var MouseRegion=class _MouseRegion{constructor(child,onMouse){this.child=child,this.onMouse=onMouse}render(width){return this.child.render(width)}getRenderRevision(){return Object.getPrototypeOf(this)===_MouseRegion.prototype?this.child.getRenderRevision?.():void 0}handleMouse(event){return dispatchMouseEvent(this.child,event)??this.onMouse(event)}invalidate(){this.child.invalidate()}};var SettingsList=class{constructor(items,maxVisible,theme,onChange,onCancel,options={}){this.selectedIndex=0,this.submenuComponent=null,this.submenuItemIndex=null,this.navigateAfterClose=null,this.items=items,this.filteredItems=items,this.maxVisible=maxVisible,this.theme=theme,this.onChange=onChange,this.onCancel=onCancel,this.searchEnabled=options.enableSearch??!1,this.searchEnabled&&(this.searchInput=new Input)}updateValue(id,newValue){let item=this.items.find(i=>i.id===id);item&&(item.currentValue=newValue)}selectItem(id){let index=(this.searchEnabled?this.filteredItems:this.items).findIndex(i=>i.id===id);index!==-1&&(this.selectedIndex=index)}invalidate(){this.submenuComponent?.invalidate?.()}render(width){return this.submenuComponent?this.submenuComponent.render(width):this.renderMainList(width)}renderMainList(width){let lines=[];if(this.searchEnabled&&this.searchInput&&(lines.push(...this.searchInput.render(width)),lines.push("")),this.items.length===0)return lines.push(this.theme.hint(" No settings available")),this.searchEnabled&&this.addHintLine(lines,width),lines;let displayItems=this.getDisplayItems();if(displayItems.length===0)return lines.push(truncateToWidth(this.theme.hint(" No matching settings"),width)),this.addHintLine(lines,width),lines;let{startIndex,endIndex}=this.getVisibleRange(displayItems),maxLabelWidth=Math.min(36,Math.max(...this.items.map(item=>visibleWidth(item.label))));for(let i=startIndex;i<endIndex;i++){let item=displayItems[i];if(!item)continue;let isSelected=i===this.selectedIndex,prefix=isSelected?this.theme.cursor:" ",prefixWidth=visibleWidth(prefix),labelPadded=item.label+" ".repeat(Math.max(0,maxLabelWidth-visibleWidth(item.label))),labelText=this.theme.label(labelPadded,isSelected),separator=" ",usedWidth=prefixWidth+maxLabelWidth+visibleWidth(separator),valueMaxWidth=width-usedWidth-2,valueText=this.theme.value(truncateToWidth(item.currentValue,valueMaxWidth,""),isSelected);lines.push(truncateToWidth(prefix+labelText+separator+valueText,width))}if(startIndex>0||endIndex<displayItems.length){let scrollText=` (${this.selectedIndex+1}/${displayItems.length})`;lines.push(this.theme.hint(truncateToWidth(scrollText,width-2,"")))}let selectedItem=displayItems[this.selectedIndex];if(selectedItem?.description){lines.push("");let wrappedDesc=wrapTextWithAnsi(selectedItem.description,width-4);for(let line of wrappedDesc)lines.push(this.theme.description(` ${line}`))}return this.addHintLine(lines,width),lines}handleMouse(event){if(this.submenuComponent){let result=this.submenuComponent.handleMouse?.(event);return result?{...result,focus:!0}:void 0}if(this.searchEnabled&&this.searchInput){if(event.y===0){let result=this.searchInput.handleMouse?.(event);return result?{...result,focus:!0}:void 0}if(event.y===1)return}let displayItems=this.getDisplayItems();if(displayItems.length===0)return;if(event.type==="wheel"&&event.wheelDelta){let delta=event.wheelDelta<0?-1:1,previousIndex=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(displayItems.length-1,this.selectedIndex+delta)),{handled:!0,render:this.selectedIndex!==previousIndex}}if(event.button!=="left"||event.type!=="press"&&event.type!=="click")return;let rowOffset=this.searchEnabled?2:0,{startIndex,endIndex}=this.getVisibleRange(displayItems),itemIndex=startIndex+event.y-rowOffset;if(!(itemIndex<startIndex||itemIndex>=endIndex)){if(event.type==="press")return this.mousePressedIndex=itemIndex,this.selectedIndex=itemIndex,{handled:!0,focus:!0};if(event.type==="click")return this.selectedIndex=this.mousePressedIndex??itemIndex,this.mousePressedIndex=void 0,this.activateItem(),{handled:!0}}}handleInput(data){if(this.submenuComponent){this.submenuComponent.handleInput?.(data);return}let kb=getKeybindings(),displayItems=this.getDisplayItems();if(kb.matches(data,"tui.select.up")){if(displayItems.length===0)return;this.selectedIndex=this.selectedIndex===0?displayItems.length-1:this.selectedIndex-1}else if(kb.matches(data,"tui.select.down")){if(displayItems.length===0)return;this.selectedIndex=this.selectedIndex===displayItems.length-1?0:this.selectedIndex+1}else kb.matches(data,"tui.select.confirm")||data===" "&&(!this.searchEnabled||this.searchInput?.getValue().length===0)?this.activateItem():kb.matches(data,"tui.select.cancel")?this.onCancel():this.searchEnabled&&this.searchInput&&(this.searchInput.handleInput(data),this.applyFilter(this.searchInput.getValue()))}getDisplayItems(){return this.searchEnabled?this.filteredItems:this.items}getVisibleRange(displayItems){let startIndex=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),displayItems.length-this.maxVisible));return{startIndex,endIndex:Math.min(startIndex+this.maxVisible,displayItems.length)}}activateItem(){let item=this.getDisplayItems()[this.selectedIndex];if(item){if(item.submenu)this.submenuItemIndex=this.selectedIndex,this.submenuComponent=item.submenu(item.currentValue,(selectedValue,options)=>{selectedValue!==void 0&&(item.currentValue=selectedValue,this.onChange(item.id,selectedValue)),options?.navigateTo&&(this.navigateAfterClose=options.navigateTo),this.closeSubmenu()});else if(item.values&&item.values.length>0){let nextIndex=(item.values.indexOf(item.currentValue)+1)%item.values.length,newValue=item.values[nextIndex];item.currentValue=newValue,this.onChange(item.id,newValue)}}}closeSubmenu(){if(this.submenuComponent=null,this.navigateAfterClose!==null){let id=this.navigateAfterClose;this.navigateAfterClose=null,this.submenuItemIndex=null,this.selectItem(id),this.activateItem()}else this.submenuItemIndex!==null&&(this.selectedIndex=this.submenuItemIndex,this.submenuItemIndex=null)}applyFilter(query){this.filteredItems=fuzzyFilter(this.items,query,item=>item.label),this.selectedIndex=0}addHintLine(lines,width){lines.push(""),lines.push(truncateToWidth(this.theme.hint(this.searchEnabled?" Type to search \xB7 Enter/Space to change \xB7 Esc to cancel":" Enter/Space to change \xB7 Esc to cancel"),width))}};var VStack=class extends Stack{constructor(children=[],options={}){super(children,options),this.layoutType="vstack"}render(width){let viewport={width:Math.max(1,width),height:Number.MAX_SAFE_INTEGER},entries=visibleStackEntries(this.entries,viewport),rendered=entries.map(entry=>entry.component.render(viewport.width)),sizes=allocateStackSizes(entries,rendered.map(lines2=>lines2.length),void 0,this.gap),lines=[];for(let index=0;index<entries.length;index++){if(index>0)for(let gap=0;gap<this.gap;gap++)lines.push(""),setLineSource(lines,lines.length-1,null);let original=rendered[index],childLines=copyLineSources(original,original.slice(0,sizes[index])),offset=lines.length;lines.push(...childLines),copyLineSources(childLines,lines,offset);for(let padding=childLines.length;padding<sizes[index];padding++)lines.push(""),setLineSource(lines,lines.length-1,null)}return lines}};function calculateImageRows(imageDimensions,targetWidthCells,cellDimensions2={widthPx:9,heightPx:18}){return calculateImageCellSize(imageDimensions,targetWidthCells,void 0,cellDimensions2).rows}export{outerKittyGraphicsMode,sanitizeTerminalLabel,detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,getImageDimensions,hyperlink,imageFallback,Q,Key,isKeyRelease,matchesKey,decodeKittyPrintable,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,getGraphemeSegmenter,visibleWidth,stripTerminalSequences,wrapTextWithAnsi,truncateToWidth,sliceByColumn,copyLineSources,dispatchMouseEvent,CURSOR_MARKER,frameMode,mainScreenHistoryLines,frameScrollbackRows,claimFrameRow,renderAtFrameRow,nextRenderRevision,currentRenderRevision,Container,joinLineArrays,isViewportTUI,TUI,Input,fuzzyMatch,fuzzyMatchLower,fuzzyFilter,CombinedAutocompleteProvider,oklabToOkhslLightness,indexedColor,rgbColor,oklchColor,okhslColor,colorToOkhsl,parseColor,colorToRgb,colorToOklch,colorToHex,mixColors,foregroundAnsi,backgroundAnsi,styleTextWithAnsi,Box,Text,Loader,CancellableLoader,expandPasteMarkers,getNativeClipboard,isWarpWslSession,ProcessTerminal,SelectList,Editor,Image,Markdown,MouseRegion,ScrollView,SettingsList,Spacer,TruncatedText,VStack,encodeProgramStatus,TuiAltScreen,TuiMainScreen,dist_exports};