silvery 0.11.0 → 0.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/runtime.js CHANGED
@@ -4,7 +4,7 @@ import{createRequire}from"node:module";var{defineProperty:__defProp,getOwnProper
4
4
  `))text=text.replace(/\r?\n/g,`${close}$&${open}`);return`${open}${text}${close}`},get(_target,prop){if(typeof prop==="symbol")return;if(prop==="level")return toChalkLevel(ref.level);if(prop==="resolve")return(token)=>resolveToken(token,ref.theme);if(prop==="visible")return createChainWithRef({...state,visible:!0},ref);if(prop==="call"||prop==="apply"||prop==="bind")return Function.prototype[prop].bind(proxyRef.proxy);let level=ref.level;if(prop==="hex"||prop==="bgHex")return(color)=>{if(level===null)return createChainWithRef(state,ref);let rgb=hexToRgb(color);if(!rgb)return createChainWithRef(state,ref);let code=prop==="hex"?fgFromRgb(rgb[0],rgb[1],rgb[2],level):bgFromRgb(rgb[0],rgb[1],rgb[2],level),close=prop==="hex"?"39":"49";return createChainWithRef({opens:[...state.opens,code],closes:[...state.closes,close]},ref)};if(prop==="rgb"||prop==="bgRgb")return(r,g,b)=>{if(level===null)return createChainWithRef(state,ref);let code=prop==="rgb"?fgFromRgb(r,g,b,level):bgFromRgb(r,g,b,level),close=prop==="rgb"?"39":"49";return createChainWithRef({opens:[...state.opens,code],closes:[...state.closes,close]},ref)};if(prop==="ansi256")return(code)=>{if(level===null)return createChainWithRef(state,ref);return createChainWithRef({opens:[...state.opens,`38;5;${code}`],closes:[...state.closes,"39"]},ref)};if(prop==="bgAnsi256")return(code)=>{if(level===null)return createChainWithRef(state,ref);return createChainWithRef({opens:[...state.opens,`48;5;${code}`],closes:[...state.closes,"49"]},ref)};if(prop in MODIFIERS){if(level===null)return createChainWithRef(state,ref);let[open,close]=MODIFIERS[prop];return createChainWithRef({opens:[...state.opens,String(open)],closes:[...state.closes,String(close)]},ref)}if(prop in FG_COLORS){if(level===null)return createChainWithRef(state,ref);return createChainWithRef({opens:[...state.opens,String(FG_COLORS[prop])],closes:[...state.closes,"39"]},ref)}if(prop in BG_COLORS){if(level===null)return createChainWithRef(state,ref);return createChainWithRef({opens:[...state.opens,String(BG_COLORS[prop])],closes:[...state.closes,"49"]},ref)}if(THEME_TOKENS.has(prop)){if(level===null)return createChainWithRef(state,ref);let hex=resolveToken(prop,ref.theme);if(hex){let rgb=hexToRgb(hex);if(rgb){let code=fgFromRgb(rgb[0],rgb[1],rgb[2],level);if(prop==="link")return createChainWithRef({opens:[...state.opens,code,"4"],closes:[...state.closes,"39","24"]},ref);return createChainWithRef({opens:[...state.opens,code],closes:[...state.closes,"39"]},ref)}}let fallback=THEME_TOKEN_DEFAULTS[prop];if(fallback!==void 0){if(prop==="muted")return createChainWithRef({opens:[...state.opens,String(fallback)],closes:[...state.closes,"22"]},ref);if(prop==="link")return createChainWithRef({opens:[...state.opens,String(fallback),"4"],closes:[...state.closes,"39","24"]},ref);return createChainWithRef({opens:[...state.opens,String(fallback)],closes:[...state.closes,"39"]},ref)}}return},set(_target,prop,value){if(prop==="level")return ref.level=fromChalkLevel(value),!0;return!1},has(_target,prop){if(prop==="level")return!0;if(typeof prop==="symbol")return!1;return prop in MODIFIERS||prop in FG_COLORS||prop in BG_COLORS||THEME_TOKENS.has(prop)||KNOWN_METHODS.has(prop)}});return proxyRef.proxy=proxy,proxy}var ESC="\x1B[",KNOWN_METHODS,THEME_TOKENS,style;var init_style=__esm(()=>{init_detection();init_colors();KNOWN_METHODS=new Set(["hex","rgb","bgHex","bgRgb","ansi256","bgAnsi256","resolve"]),THEME_TOKENS=new Set(["primary","secondary","accent","error","warning","success","info","muted","link","border","surface"]);style=createStyle()});function createMixedStyle(style2,extra){return createChainProxy(style2,extra)}function createChainProxy(currentStyle,extra){return new Proxy(function(){},{apply(_target,_thisArg,args){return currentStyle(...args)},get(_target,prop){if(prop in extra){let value=extra[prop];if(typeof value==="function")return value;return value}if(typeof prop==="symbol"){if(prop===Symbol.dispose)return extra[Symbol.dispose];return}if(STYLE_METHODS.has(prop)){let method=currentStyle[prop];if(typeof method==="function")return(...args)=>{let newStyle=method.apply(currentStyle,args);return createChainProxy(newStyle,extra)}}let styleProp=currentStyle[prop];if(styleProp!==void 0){if(typeof styleProp==="function"||typeof styleProp==="object")return createChainProxy(styleProp,extra);return styleProp}return},set(_target,prop,value){return extra[prop]=value,!0},defineProperty(_target,prop,descriptor){return Object.defineProperty(extra,prop,descriptor),!0},has(_target,prop){if(prop in extra)return!0;if(typeof prop==="string"&&prop in currentStyle)return!0;return!1}})}var STYLE_METHODS;var init_mixed_proxy=__esm(()=>{STYLE_METHODS=new Set(["hex","bgHex","rgb","bgRgb","ansi256","bgAnsi256"])});function deriveTheme(palette,mode="truecolor",adjustments){if(mode==="ansi16")return deriveAnsi16Theme(palette);return deriveTruecolorTheme(palette,adjustments)}function deriveTruecolorTheme(p,adjustments){let dark=p.dark??!0,bg=p.background;function ensure(token,color,against,target){let result=ensureContrast(color,against,target);if(adjustments&&result!==color){let before=checkContrast(color,against),after=checkContrast(result,against);adjustments.push({token,from:color,to:result,against,target,ratioBefore:before?.ratio??0,ratioAfter:after?.ratio??0})}return result}let surfacebg=blend(bg,p.foreground,0.05),popoverbg=blend(bg,p.foreground,0.08),fg=ensure("fg",p.foreground,popoverbg,AA),primary=ensure("primary",p.primary??(dark?p.yellow:p.blue),bg,AA),accent=ensure("accent",complement(primary),bg,AA),secondary=ensure("secondary",blend(primary,accent,0.35),bg,AA),error=ensure("error",p.red,bg,AA),warning=ensure("warning",p.yellow,bg,AA),success=ensure("success",p.green,bg,AA),info=ensure("info",blend(fg,accent,0.5),bg,AA),link=ensure("link",dark?p.brightBlue:p.blue,bg,AA),mutedbg=blend(bg,p.foreground,0.04),muted=ensure("muted",blend(fg,bg,0.4),mutedbg,AA),disabledfg=ensure("disabledfg",blend(fg,bg,0.5),bg,DIM),border=ensure("border",blend(bg,p.foreground,0.15),bg,FAINT),inputborder=ensure("inputborder",blend(bg,p.foreground,0.25),bg,CONTROL),selection=ensure("selection",p.selectionForeground,p.selectionBackground,AA),cursor=ensure("cursor",p.cursorText,p.cursorColor,AA);return{name:p.name??(dark?"derived-dark":"derived-light"),bg,fg,muted,mutedbg,surface:fg,surfacebg,popover:fg,popoverbg,inverse:contrastFg(blend(fg,bg,0.1)),inversebg:blend(fg,bg,0.1),cursor,cursorbg:p.cursorColor,selection,selectionbg:p.selectionBackground,primary,primaryfg:contrastFg(primary),secondary,secondaryfg:contrastFg(secondary),accent,accentfg:contrastFg(accent),error,errorfg:contrastFg(error),warning,warningfg:contrastFg(warning),success,successfg:contrastFg(success),info,infofg:contrastFg(info),border,inputborder,focusborder:link,link,disabledfg,palette:[p.black,p.red,p.green,p.yellow,p.blue,p.magenta,p.cyan,p.white,p.brightBlack,p.brightRed,p.brightGreen,p.brightYellow,p.brightBlue,p.brightMagenta,p.brightCyan,p.brightWhite]}}function deriveAnsi16Theme(p){let dark=p.dark??!0,primaryColor=dark?p.yellow:p.blue;return{name:p.name??(dark?"derived-ansi16-dark":"derived-ansi16-light"),bg:p.background,fg:p.foreground,muted:p.white,mutedbg:p.black,surface:p.foreground,surfacebg:p.black,popover:p.foreground,popoverbg:p.black,inverse:p.black,inversebg:p.brightWhite,cursor:p.cursorText,cursorbg:p.cursorColor,selection:p.selectionForeground,selectionbg:p.selectionBackground,primary:primaryColor,primaryfg:p.black,secondary:p.magenta,secondaryfg:p.black,accent:p.cyan,accentfg:p.black,error:dark?p.brightRed:p.red,errorfg:p.black,warning:p.yellow,warningfg:p.black,success:dark?p.brightGreen:p.green,successfg:p.black,info:p.cyan,infofg:p.black,border:p.brightBlack,inputborder:p.brightBlack,focusborder:dark?p.brightBlue:p.blue,link:dark?p.brightBlue:p.blue,disabledfg:p.brightBlack,palette:[p.black,p.red,p.green,p.yellow,p.blue,p.magenta,p.cyan,p.white,p.brightBlack,p.brightRed,p.brightGreen,p.brightYellow,p.brightBlue,p.brightMagenta,p.brightCyan,p.brightWhite]}}var AA=4.5,DIM=3,FAINT=1.5,CONTROL=3;var init_derive=__esm(()=>{init_src();init_src()});var ansi16DarkTheme,ansi16LightTheme;var init_default_palettes=__esm(()=>{ansi16DarkTheme={name:"dark-ansi16",bg:"",fg:"whiteBright",muted:"white",mutedbg:"black",surface:"whiteBright",surfacebg:"black",popover:"whiteBright",popoverbg:"black",inverse:"black",inversebg:"whiteBright",cursor:"black",cursorbg:"yellow",selection:"black",selectionbg:"yellow",primary:"yellow",primaryfg:"black",secondary:"white",secondaryfg:"black",accent:"blueBright",accentfg:"black",error:"redBright",errorfg:"black",warning:"yellow",warningfg:"black",success:"greenBright",successfg:"black",info:"cyan",infofg:"black",border:"gray",inputborder:"gray",focusborder:"blueBright",link:"blueBright",disabledfg:"gray",palette:["black","red","green","yellow","blue","magenta","cyan","white","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"]},ansi16LightTheme={name:"light-ansi16",bg:"",fg:"black",muted:"blackBright",mutedbg:"white",surface:"black",surfacebg:"white",popover:"black",popoverbg:"white",inverse:"whiteBright",inversebg:"black",cursor:"black",cursorbg:"blue",selection:"black",selectionbg:"cyan",primary:"blue",primaryfg:"black",secondary:"blue",secondaryfg:"black",accent:"cyan",accentfg:"black",error:"red",errorfg:"black",warning:"yellow",warningfg:"black",success:"green",successfg:"black",info:"cyan",infofg:"black",border:"gray",inputborder:"gray",focusborder:"blue",link:"blueBright",disabledfg:"gray",palette:["black","red","green","yellow","blue","magenta","cyan","white","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"]}});var init_types=()=>{};function queryPaletteColor(index,write){if(index<0||index>255)throw RangeError(`Palette index must be 0-255, got ${index}`);write(`\x1B]4;${index};?\x07`)}function queryMultiplePaletteColors(indices,write){for(let index of indices)queryPaletteColor(index,write)}function parsePaletteResponse(input){let prefixIdx=input.indexOf(OSC4_PREFIX);if(prefixIdx===-1)return null;let bodyStart=prefixIdx+OSC4_PREFIX.length,bodyEnd=input.indexOf("\x07",bodyStart);if(bodyEnd===-1)bodyEnd=input.indexOf("\x1B\\",bodyStart);if(bodyEnd===-1)return null;let body=input.slice(bodyStart,bodyEnd),match=OSC4_BODY_RE.exec(body);if(!match)return null;let index=Number.parseInt(match[1],10);if(index<0||index>255)return null;let r=normalizeHexChannel(match[2]),g=normalizeHexChannel(match[3]),b=normalizeHexChannel(match[4]);return{index,color:`#${r}${g}${b}`}}function normalizeHexChannel(hex){switch(hex.length){case 1:return hex+hex;case 2:return hex;default:return hex.slice(0,2)}}var OSC4_PREFIX="\x1B]4;",OSC4_BODY_RE;var init_osc_palette=__esm(()=>{OSC4_BODY_RE=/^(\d+);rgb:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})$/});function normalizeHexChannel2(hex){switch(hex.length){case 1:return hex+hex;case 2:return hex;default:return hex.slice(0,2)}}function parseOscColorResponse(input,oscCode){let prefix=`\x1B]${oscCode};`,prefixIdx=input.indexOf(prefix);if(prefixIdx===-1)return null;let bodyStart=prefixIdx+prefix.length,bodyEnd=input.indexOf("\x07",bodyStart);if(bodyEnd===-1)bodyEnd=input.indexOf("\x1B\\",bodyStart);if(bodyEnd===-1)return null;let body=input.slice(bodyStart,bodyEnd),match=RGB_BODY_RE.exec(body);if(!match)return null;return`#${normalizeHexChannel2(match[1])}${normalizeHexChannel2(match[2])}${normalizeHexChannel2(match[3])}`}async function queryOscColor(write,read,oscCode,timeoutMs){write(`\x1B]${oscCode};?\x07`);let data=await read(timeoutMs);if(data==null)return null;return parseOscColorResponse(data,oscCode)}async function queryForegroundColor(write,read,timeoutMs=200){return queryOscColor(write,read,10,timeoutMs)}async function queryBackgroundColor(write,read,timeoutMs=200){return queryOscColor(write,read,11,timeoutMs)}var RGB_BODY_RE;var init_osc_colors=__esm(()=>{RGB_BODY_RE=/rgb:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})/});async function detectTerminalPalette(timeoutMs=150){let{stdin,stdout}=process;if(!stdin.isTTY||!stdout.isTTY)return null;let wasRaw=stdin.isRaw;if(!wasRaw)stdin.setRawMode(!0);let buffer="",onData=(chunk)=>{buffer+=chunk.toString()};stdin.on("data",onData);try{let write=(s)=>{stdout.write(s)},read=(ms)=>new Promise((resolve)=>{if(buffer.length>0){let result=buffer;buffer="",resolve(result);return}let timer=setTimeout(()=>{resolve(buffer.length>0?buffer:null),buffer=""},ms),check=(_chunk)=>{clearTimeout(timer),stdin.removeListener("data",check);let result=buffer;buffer="",resolve(result)};stdin.on("data",check)}),bg=await queryBackgroundColor(write,read,timeoutMs),fg=await queryForegroundColor(write,read,timeoutMs),ansi=Array(16).fill(null);queryMultiplePaletteColors(Array.from({length:16},(_,i)=>i),write),await new Promise((resolve)=>setTimeout(resolve,timeoutMs));let remaining=buffer;if(buffer="",remaining){let pos=0;while(pos<remaining.length){let nextOsc=remaining.indexOf("\x1B]4;",pos);if(nextOsc===-1)break;let end=remaining.indexOf("\x07",nextOsc);if(end===-1)end=remaining.indexOf("\x1B\\",nextOsc);if(end===-1)break;let chunk=remaining.slice(nextOsc,end+1),parsed=parsePaletteResponse(chunk);if(parsed&&parsed.index>=0&&parsed.index<16)ansi[parsed.index]=parsed.color;pos=end+1}}let dark=bg?isDarkColor(bg):!0,palette={dark};if(bg)palette.background=bg;if(fg)palette.foreground=fg;let ansiFields=["black","red","green","yellow","blue","magenta","cyan","white","brightBlack","brightRed","brightGreen","brightYellow","brightBlue","brightMagenta","brightCyan","brightWhite"];for(let i=0;i<16;i++)if(ansi[i])palette[ansiFields[i]]=ansi[i];if(fg)palette.cursorColor=fg,palette.selectionForeground=fg;if(bg)palette.cursorText=bg;if(ansi[4])palette.selectionBackground=ansi[4];return{fg,bg,ansi,dark,palette}}finally{if(stdin.removeListener("data",onData),!wasRaw)stdin.setRawMode(!1)}}function isDarkColor(hex){let r=parseInt(hex.slice(1,3),16)/255,g=parseInt(hex.slice(3,5),16)/255,b=parseInt(hex.slice(5,7),16)/255;return 0.2126*r+0.7152*g+0.0722*b<=0.5}var init_detect=__esm(()=>{init_derive();init_default_palettes();init_osc_palette();init_osc_colors()});var init_color_scheme=()=>{};var init_src2=__esm(()=>{init_constants();init_detection();init_utils();init_color_maps();init_underline_ext();init_hyperlink();init_style();init_mixed_proxy();init_colors();init_derive();init_default_palettes();init_types();init_detect();init_osc_palette();init_osc_colors();init_color_scheme()});var init_sgr_codes=__esm(()=>{init_src2()});var exports_buffer={};__export(exports_buffer,{trimTrailingWhitespacePreservingAnsi:()=>trimTrailingWhitespacePreservingAnsi,styleTransitionCodes:()=>styleTransitionCodes,styleToAnsiCodes:()=>styleToAnsiCodes,styleResetCodes:()=>styleResetCodes,styleEquals:()=>styleEquals,setSelectableFlag:()=>setSelectableFlag,packCell:()=>packCell,numberToAttrs:()=>numberToAttrs,isDefaultBg:()=>isDefaultBg,isCellSelectable:()=>isCellSelectable,hasActiveAttrs:()=>hasActiveAttrs,createTextFrame:()=>createTextFrame,createMutableCell:()=>createMutableCell,createBuffer:()=>createBuffer,colorEquals:()=>colorEquals,clearSelectableFlag:()=>clearSelectableFlag,cellToFrameCell:()=>cellToFrameCell,cellEquals:()=>cellEquals,bufferToText:()=>bufferToText,bufferToStyledText:()=>bufferToStyledText,bufferToHTML:()=>bufferToHTML,attrsToNumber:()=>attrsToNumber,attrsEquals:()=>attrsEquals,VISIBLE_SPACE_ATTR_MASK:()=>VISIBLE_SPACE_ATTR_MASK,TerminalBuffer:()=>TerminalBuffer,SELECTABLE_FLAG:()=>SELECTABLE_FLAG,EMPTY_FRAME_CELL:()=>EMPTY_FRAME_CELL,DEFAULT_BG:()=>DEFAULT_BG});function isDefaultBg(color){return color!==null&&typeof color==="object"&&color.r===-1}function isCellSelectable(packed){return(packed>>>0&SELECTABLE_FLAG)!==0}function setSelectableFlag(packed){return(packed|SELECTABLE_FLAG)>>>0}function clearSelectableFlag(packed){return(packed&~SELECTABLE_FLAG)>>>0}function underlineStyleToNumber(style2){switch(style2){case!1:return 0;case"single":return 1;case"double":return 2;case"curly":return 3;case"dotted":return 4;case"dashed":return 5;default:return 0}}function numberToUnderlineStyle(n){switch(n){case 0:return;case 1:return"single";case 2:return"double";case 3:return"curly";case 4:return"dotted";case 5:return"dashed";default:return}}function attrsToNumber(attrs){let n=0;if(attrs.bold)n|=ATTR_BOLD;if(attrs.dim)n|=ATTR_DIM;if(attrs.italic)n|=ATTR_ITALIC;if(attrs.blink)n|=ATTR_BLINK;if(attrs.inverse)n|=ATTR_INVERSE;if(attrs.hidden)n|=ATTR_HIDDEN;if(attrs.strikethrough)n|=ATTR_STRIKETHROUGH;let ulStyle=attrs.underlineStyle??(attrs.underline?"single":void 0);return n|=underlineStyleToNumber(ulStyle)<<UNDERLINE_STYLE_SHIFT,n}function numberToAttrs(n){let attrs={};if(n&ATTR_BOLD)attrs.bold=!0;if(n&ATTR_DIM)attrs.dim=!0;if(n&ATTR_ITALIC)attrs.italic=!0;if(n&ATTR_BLINK)attrs.blink=!0;if(n&ATTR_INVERSE)attrs.inverse=!0;if(n&ATTR_HIDDEN)attrs.hidden=!0;if(n&ATTR_STRIKETHROUGH)attrs.strikethrough=!0;let ulStyleNum=(n&UNDERLINE_STYLE_MASK)>>UNDERLINE_STYLE_SHIFT,ulStyle=numberToUnderlineStyle(ulStyleNum);if(ulStyle)attrs.underlineStyle=ulStyle,attrs.underline=!0;return attrs}function colorToIndex(color){if(color===null)return 0;if(typeof color==="number")return(color&255)+1;return 0}function isTrueColor(color){return color!==null&&typeof color==="object"}function packCell(cell){let packed=0;if(packed|=colorToIndex(cell.fg)&255,packed|=(colorToIndex(cell.bg)&255)<<8,packed|=attrsToNumber(cell.attrs),cell.wide)packed|=WIDE_FLAG;if(cell.continuation)packed|=CONTINUATION_FLAG;if(isTrueColor(cell.fg))packed|=TRUE_COLOR_FG_FLAG;if(isTrueColor(cell.bg))packed|=TRUE_COLOR_BG_FLAG;return packed}function unpackFgIndex(packed){return packed&255}function unpackBgIndex(packed){return packed>>8&255}function unpackAttrs(packed){return numberToAttrs(packed)}function unpackWide(packed){return(packed&WIDE_FLAG)!==0}function unpackContinuation(packed){return(packed&CONTINUATION_FLAG)!==0}function unpackTrueColorFg(packed){return(packed&TRUE_COLOR_FG_FLAG)!==0}function unpackTrueColorBg(packed){return(packed&TRUE_COLOR_BG_FLAG)!==0}class TerminalBuffer{cells;chars;fgColors;bgColors;underlineColors;hyperlinks;_dirtyRows;_minDirtyRow;_maxDirtyRow;_rowMetadata;_selectableMode=!1;width;height;constructor(width,height){this.width=width,this.height=height;let size=width*height;this.cells=new Uint32Array(size),this.chars=Array(size).fill(" "),this.fgColors=new Map,this.bgColors=new Map,this.underlineColors=new Map,this.hyperlinks=new Map,this._dirtyRows=new Uint8Array(height).fill(1),this._minDirtyRow=0,this._maxDirtyRow=height-1,this._rowMetadata=Array.from({length:height},()=>({softWrapped:!1,lastContentCol:-1}))}index(x,y){return y*this.width+x}inBounds(x,y){return x>=0&&x<this.width&&y>=0&&y<this.height}getCell(x,y){if(!this.inBounds(x,y))return{...EMPTY_CELL};let idx=this.index(x,y),packed=this.cells[idx],char=this.chars[idx],fg=null;if(unpackTrueColorFg(packed))fg=this.fgColors.get(idx)??null;else{let fgIndex=unpackFgIndex(packed);fg=fgIndex>0?fgIndex-1:null}let bg=null;if(unpackTrueColorBg(packed))bg=this.bgColors.get(idx)??null;else{let bgIndex=unpackBgIndex(packed);bg=bgIndex>0?bgIndex-1:null}let hyperlink2=this.hyperlinks.get(idx);return{char,fg,bg,underlineColor:this.underlineColors.get(idx)??null,attrs:unpackAttrs(packed),wide:unpackWide(packed),continuation:unpackContinuation(packed),...hyperlink2!==void 0?{hyperlink:hyperlink2}:{}}}getCellChar(x,y){if(!this.inBounds(x,y))return" ";return this.chars[this.index(x,y)]}getCellBg(x,y){if(!this.inBounds(x,y))return null;let idx=this.index(x,y),packed=this.cells[idx];if(unpackTrueColorBg(packed))return this.bgColors.get(idx)??null;let bgIndex=unpackBgIndex(packed);return bgIndex>0?bgIndex-1:null}getCellFg(x,y){if(!this.inBounds(x,y))return null;let idx=this.index(x,y),packed=this.cells[idx];if(unpackTrueColorFg(packed))return this.fgColors.get(idx)??null;let fgIndex=unpackFgIndex(packed);return fgIndex>0?fgIndex-1:null}getCellAttrs(x,y){if(!this.inBounds(x,y))return 0;return this.cells[this.index(x,y)]}isCellWide(x,y){if(!this.inBounds(x,y))return!1;return unpackWide(this.cells[this.index(x,y)])}isCellContinuation(x,y){if(!this.inBounds(x,y))return!1;return unpackContinuation(this.cells[this.index(x,y)])}isCellSelectable(x,y){if(!this.inBounds(x,y))return!1;return(this.cells[this.index(x,y)]>>>0&SELECTABLE_FLAG)!==0}setRowMeta(row,meta){if(row<0||row>=this.height)return;let existing=this._rowMetadata[row];if(meta.softWrapped!==void 0)existing.softWrapped=meta.softWrapped;if(meta.lastContentCol!==void 0)existing.lastContentCol=meta.lastContentCol}getRowMeta(row){if(row<0||row>=this.height)return{softWrapped:!1,lastContentCol:-1};return this._rowMetadata[row]}getRowMetadataArray(){return this._rowMetadata}setSelectableMode(selectable){this._selectableMode=selectable}getSelectableMode(){return this._selectableMode}readCellInto(x,y,out){if(!this.inBounds(x,y))return out.char=" ",out.fg=null,out.bg=null,out.underlineColor=null,out.attrs=EMPTY_ATTRS,out.wide=!1,out.continuation=!1,out.hyperlink=void 0,out;let idx=this.index(x,y),packed=this.cells[idx];if(out.char=this.chars[idx],unpackTrueColorFg(packed))out.fg=this.fgColors.get(idx)??null;else{let fgIndex=unpackFgIndex(packed);out.fg=fgIndex>0?fgIndex-1:null}if(unpackTrueColorBg(packed))out.bg=this.bgColors.get(idx)??null;else{let bgIndex=unpackBgIndex(packed);out.bg=bgIndex>0?bgIndex-1:null}out.underlineColor=this.underlineColors.get(idx)??null;let attrs=out.attrs===EMPTY_ATTRS?(out.attrs={},out.attrs):out.attrs;attrs.bold=(packed&ATTR_BOLD)!==0?!0:void 0,attrs.dim=(packed&ATTR_DIM)!==0?!0:void 0,attrs.italic=(packed&ATTR_ITALIC)!==0?!0:void 0,attrs.blink=(packed&ATTR_BLINK)!==0?!0:void 0,attrs.inverse=(packed&ATTR_INVERSE)!==0?!0:void 0,attrs.hidden=(packed&ATTR_HIDDEN)!==0?!0:void 0,attrs.strikethrough=(packed&ATTR_STRIKETHROUGH)!==0?!0:void 0;let ulStyleNum=(packed&UNDERLINE_STYLE_MASK)>>UNDERLINE_STYLE_SHIFT,ulStyle=numberToUnderlineStyle(ulStyleNum);if(ulStyle)attrs.underlineStyle=ulStyle,attrs.underline=!0;else attrs.underlineStyle=void 0,attrs.underline=void 0;return out.wide=(packed&WIDE_FLAG)!==0,out.continuation=(packed&CONTINUATION_FLAG)!==0,out.hyperlink=this.hyperlinks.get(idx),out}setCell(x,y,cell){if(!this.inBounds(x,y))return;let trap=globalThis.__silvery_write_trap;if(trap&&x===trap.x&&y===trap.y){let char2=cell.char??" ",stack=Error().stack?.split(`
5
5
  `).slice(1,6).join(`
6
6
  `)??"";trap.log.push(` char="${char2}" fg=${cell.fg??"null"} bg=${cell.bg??"null"} dim=${cell.attrs?.dim} ul=${cell.attrs?.underline}
7
- ${stack}`)}if(this._dirtyRows[y]=1,this._minDirtyRow===-1||y<this._minDirtyRow)this._minDirtyRow=y;if(y>this._maxDirtyRow)this._maxDirtyRow=y;let idx=this.index(x,y);if(!(cell.continuation??!1)){let prevPacked=this.cells[idx];if(prevPacked!==void 0&&(prevPacked&CONTINUATION_FLAG)!==0&&x>0){let prevIdx=idx-1;this.cells[prevIdx]=this.cells[prevIdx]&~WIDE_FLAG,this.chars[prevIdx]=" "}}if(!(cell.wide??!1)){let prevPacked=this.cells[idx];if(prevPacked!==void 0&&(prevPacked&WIDE_FLAG)!==0&&x+1<this.width){let nextIdx=idx+1;this.cells[nextIdx]=this.cells[nextIdx]&~CONTINUATION_FLAG,this.chars[nextIdx]=" "}}let char=cell.char??" ",fg=cell.fg??null,bg=cell.bg??null,underlineColor2=cell.underlineColor??null,attrs=cell.attrs??EMPTY_ATTRS,wide=cell.wide??!1,continuation=cell.continuation??!1;if(this.chars[idx]=char,isTrueColor(fg))this.fgColors.set(idx,fg);else this.fgColors.delete(idx);if(isTrueColor(bg))this.bgColors.set(idx,bg);else this.bgColors.delete(idx);if(underlineColor2!==null)this.underlineColors.set(idx,underlineColor2);else this.underlineColors.delete(idx);let hyperlink2=cell.hyperlink;if(hyperlink2!==void 0&&hyperlink2!=="")this.hyperlinks.set(idx,hyperlink2);else this.hyperlinks.delete(idx);let packed=0;if(packed|=colorToIndex(fg)&255,packed|=(colorToIndex(bg)&255)<<8,packed|=attrsToNumber(attrs),wide)packed|=WIDE_FLAG;if(continuation)packed|=CONTINUATION_FLAG;if(isTrueColor(fg))packed|=TRUE_COLOR_FG_FLAG;if(isTrueColor(bg))packed|=TRUE_COLOR_BG_FLAG;if(this._selectableMode)packed=(packed|SELECTABLE_FLAG)>>>0;this.cells[idx]=packed}fill(x,y,width,height,cell){let endX=Math.min(x+width,this.width),endY=Math.min(y+height,this.height),startX=Math.max(0,x),startY=Math.max(0,y);if(startX>=endX||startY>=endY)return;let char=cell.char??" ",fg=cell.fg??null,bg=cell.bg??null,underlineColor2=cell.underlineColor??null,attrs=cell.attrs??{},wide=cell.wide??!1,continuation=cell.continuation??!1,packed=packCell({char,fg,bg,underlineColor:underlineColor2,attrs,wide,continuation});if(this._selectableMode)packed=(packed|SELECTABLE_FLAG)>>>0;let hasTrueColorFg=isTrueColor(fg),hasTrueColorBg=isTrueColor(bg),trueColorFg=hasTrueColorFg?fg:null,trueColorBg=hasTrueColorBg?bg:null,hasUnderlineColor=underlineColor2!==null,hyperlink2=cell.hyperlink,hasHyperlink=hyperlink2!==void 0&&hyperlink2!=="";for(let cy=startY;cy<endY;cy++)this._dirtyRows[cy]=1;if(startY<endY){if(this._minDirtyRow===-1||startY<this._minDirtyRow)this._minDirtyRow=startY;if(endY-1>this._maxDirtyRow)this._maxDirtyRow=endY-1}let needFgDelete=!hasTrueColorFg&&this.fgColors.size>0,needBgDelete=!hasTrueColorBg&&this.bgColors.size>0,needUlDelete=!hasUnderlineColor&&this.underlineColors.size>0,needHlDelete=!hasHyperlink&&this.hyperlinks.size>0;for(let cy=startY;cy<endY;cy++){let rowBase=cy*this.width;for(let cx=startX;cx<endX;cx++){let idx=rowBase+cx;if(this.cells[idx]=packed,this.chars[idx]=char,hasTrueColorFg)this.fgColors.set(idx,trueColorFg);else if(needFgDelete)this.fgColors.delete(idx);if(hasTrueColorBg)this.bgColors.set(idx,trueColorBg);else if(needBgDelete)this.bgColors.delete(idx);if(hasUnderlineColor)this.underlineColors.set(idx,underlineColor2);else if(needUlDelete)this.underlineColors.delete(idx);if(hasHyperlink)this.hyperlinks.set(idx,hyperlink2);else if(needHlDelete)this.hyperlinks.delete(idx)}}}clear(){this.cells.fill(0),this.chars.fill(" "),this.fgColors.clear(),this.bgColors.clear(),this.underlineColors.clear(),this.hyperlinks.clear(),this._dirtyRows.fill(1),this._minDirtyRow=0,this._maxDirtyRow=this.height-1}copyFrom(source,srcX,srcY,destX,destY,width,height){let cell=createMutableCell();for(let dy=0;dy<height;dy++){let dstY=destY+dy;if(dstY>=0&&dstY<this.height){if(this._dirtyRows[dstY]=1,this._minDirtyRow===-1||dstY<this._minDirtyRow)this._minDirtyRow=dstY;if(dstY>this._maxDirtyRow)this._maxDirtyRow=dstY}for(let dx=0;dx<width;dx++){let sx=srcX+dx,sy=srcY+dy,dX=destX+dx;if(source.inBounds(sx,sy)&&this.inBounds(dX,dstY))source.readCellInto(sx,sy,cell),this.setCell(dX,dstY,cell)}}}scrollRegion(x,y,regionWidth,regionHeight,delta,clearCell={}){if(delta===0||regionHeight<=0||regionWidth<=0)return;let startX=Math.max(0,x),endX=Math.min(x+regionWidth,this.width),startY=Math.max(0,y),endY=Math.min(y+regionHeight,this.height),clampedWidth=endX-startX,clampedHeight=endY-startY;if(clampedWidth<=0||clampedHeight<=0)return;for(let r=startY;r<endY;r++)this._dirtyRows[r]=1;if(this._minDirtyRow===-1||startY<this._minDirtyRow)this._minDirtyRow=startY;if(endY-1>this._maxDirtyRow)this._maxDirtyRow=endY-1;if(Math.abs(delta)>=clampedHeight){this.fill(startX,startY,clampedWidth,clampedHeight,{char:clearCell.char??" ",bg:clearCell.bg??null});return}let absDelta=Math.abs(delta),w=this.width;if(delta>0){for(let row=startY;row<endY-absDelta;row++){let dstBase=row*w,srcBase=(row+absDelta)*w;this.cells.copyWithin(dstBase+startX,srcBase+startX,srcBase+endX);for(let cx=startX;cx<endX;cx++){this.chars[dstBase+cx]=this.chars[srcBase+cx];let srcIdx=srcBase+cx,dstIdx=dstBase+cx,fgc=this.fgColors.get(srcIdx);if(fgc)this.fgColors.set(dstIdx,fgc),this.fgColors.delete(srcIdx);else this.fgColors.delete(dstIdx);let bgc=this.bgColors.get(srcIdx);if(bgc)this.bgColors.set(dstIdx,bgc),this.bgColors.delete(srcIdx);else this.bgColors.delete(dstIdx);let ulc=this.underlineColors.get(srcIdx);if(ulc)this.underlineColors.set(dstIdx,ulc),this.underlineColors.delete(srcIdx);else this.underlineColors.delete(dstIdx);let hl=this.hyperlinks.get(srcIdx);if(hl)this.hyperlinks.set(dstIdx,hl),this.hyperlinks.delete(srcIdx);else this.hyperlinks.delete(dstIdx)}}this.fill(startX,endY-absDelta,clampedWidth,absDelta,{char:clearCell.char??" ",bg:clearCell.bg??null})}else{for(let row=endY-1;row>=startY+absDelta;row--){let dstBase=row*w,srcBase=(row-absDelta)*w;this.cells.copyWithin(dstBase+startX,srcBase+startX,srcBase+endX);for(let cx=startX;cx<endX;cx++){this.chars[dstBase+cx]=this.chars[srcBase+cx];let srcIdx=srcBase+cx,dstIdx=dstBase+cx,fgc=this.fgColors.get(srcIdx);if(fgc)this.fgColors.set(dstIdx,fgc),this.fgColors.delete(srcIdx);else this.fgColors.delete(dstIdx);let bgc=this.bgColors.get(srcIdx);if(bgc)this.bgColors.set(dstIdx,bgc),this.bgColors.delete(srcIdx);else this.bgColors.delete(dstIdx);let ulc=this.underlineColors.get(srcIdx);if(ulc)this.underlineColors.set(dstIdx,ulc),this.underlineColors.delete(srcIdx);else this.underlineColors.delete(dstIdx);let hl=this.hyperlinks.get(srcIdx);if(hl)this.hyperlinks.set(dstIdx,hl),this.hyperlinks.delete(srcIdx);else this.hyperlinks.delete(dstIdx)}}this.fill(startX,startY,clampedWidth,absDelta,{char:clearCell.char??" ",bg:clearCell.bg??null})}}clone(){let copy=new TerminalBuffer(this.width,this.height);return copy.cells.set(this.cells),copy.chars=[...this.chars],copy.fgColors=new Map(this.fgColors),copy.bgColors=new Map(this.bgColors),copy.underlineColors=new Map(this.underlineColors),copy.hyperlinks=new Map(this.hyperlinks),copy._dirtyRows.fill(0),copy._minDirtyRow=-1,copy._maxDirtyRow=-1,copy._rowMetadata=this._rowMetadata.map((m)=>({...m})),copy}isRowDirty(y){if(y<0||y>=this.height)return!1;return this._dirtyRows[y]!==0}get minDirtyRow(){return this._minDirtyRow}get maxDirtyRow(){return this._maxDirtyRow}resetDirtyRows(){this._dirtyRows.fill(0),this._minDirtyRow=-1,this._maxDirtyRow=-1}markAllRowsDirty(){this._dirtyRows.fill(1),this._minDirtyRow=0,this._maxDirtyRow=this.height-1}cellEquals(x,y,other){if(!this.inBounds(x,y)||!other.inBounds(x,y))return!1;let idx=this.index(x,y),otherIdx=other.index(x,y),mask=~SELECTABLE_FLAG;if((this.cells[idx]&mask)!==(other.cells[otherIdx]&mask))return!1;if(this.chars[idx]!==other.chars[otherIdx])return!1;let packed=this.cells[idx];if(unpackTrueColorFg(packed)){let a=this.fgColors.get(idx),b=other.fgColors.get(otherIdx);if(!colorEquals(a,b))return!1}if(unpackTrueColorBg(packed)){let a=this.bgColors.get(idx),b=other.bgColors.get(otherIdx);if(!colorEquals(a,b))return!1}let ulA=this.underlineColors.get(idx)??null,ulB=other.underlineColors.get(otherIdx)??null;if(!colorEquals(ulA,ulB))return!1;let hlA=this.hyperlinks.get(idx),hlB=other.hyperlinks.get(otherIdx);if(hlA!==hlB)return!1;return!0}rowMetadataEquals(y,other){if(y<0||y>=this.height||y>=other.height)return!1;let start=y*this.width,otherStart=y*other.width,w=Math.min(this.width,other.width),mask=~SELECTABLE_FLAG;for(let i=0;i<w;i++)if((this.cells[start+i]&mask)!==(other.cells[otherStart+i]&mask))return!1;return!0}rowCharsEquals(y,other){if(y<0||y>=this.height||y>=other.height)return!1;let start=y*this.width,otherStart=y*other.width,w=Math.min(this.width,other.width);for(let i=0;i<w;i++)if(this.chars[start+i]!==other.chars[otherStart+i])return!1;return!0}rowExtrasEquals(y,other){if(y<0||y>=this.height||y>=other.height)return!1;let start=y*this.width,w=Math.min(this.width,other.width),otherStart=y*other.width;for(let i=0;i<w;i++){let idx=start+i,otherIdx=otherStart+i,packed=this.cells[idx];if((packed&TRUE_COLOR_FG_FLAG)!==0){let a=this.fgColors.get(idx),b=other.fgColors.get(otherIdx);if(!colorEquals(a,b))return!1}if((packed&TRUE_COLOR_BG_FLAG)!==0){let a=this.bgColors.get(idx),b=other.bgColors.get(otherIdx);if(!colorEquals(a,b))return!1}let ulA=this.underlineColors.get(idx)??null,ulB=other.underlineColors.get(otherIdx)??null;if(!colorEquals(ulA,ulB))return!1;let hlA=this.hyperlinks.get(idx),hlB=other.hyperlinks.get(otherIdx);if(hlA!==hlB)return!1}return!0}}function colorEquals(a,b){if(a===b)return!0;if(a===null||a===void 0)return b===null||b===void 0;if(b===null||b===void 0)return!1;if(typeof a==="number")return a===b;if(typeof b==="number")return!1;return a.r===b.r&&a.g===b.g&&a.b===b.b}function cellEquals(a,b){return a.char===b.char&&colorEquals(a.fg,b.fg)&&colorEquals(a.bg,b.bg)&&colorEquals(a.underlineColor,b.underlineColor)&&a.wide===b.wide&&a.continuation===b.continuation&&attrsEquals(a.attrs,b.attrs)&&(a.hyperlink??void 0)===(b.hyperlink??void 0)}function attrsEquals(a,b){return Boolean(a.bold)===Boolean(b.bold)&&Boolean(a.dim)===Boolean(b.dim)&&Boolean(a.italic)===Boolean(b.italic)&&Boolean(a.underline)===Boolean(b.underline)&&(a.underlineStyle??!1)===(b.underlineStyle??!1)&&Boolean(a.blink)===Boolean(b.blink)&&Boolean(a.inverse)===Boolean(b.inverse)&&Boolean(a.hidden)===Boolean(b.hidden)&&Boolean(a.strikethrough)===Boolean(b.strikethrough)}function styleEquals(a,b){if(a===b)return!0;if(!a||!b)return!1;return colorEquals(a.fg,b.fg)&&colorEquals(a.bg,b.bg)&&colorEquals(a.underlineColor,b.underlineColor)&&attrsEquals(a.attrs,b.attrs)&&(a.hyperlink??void 0)===(b.hyperlink??void 0)}function createMutableCell(){return{char:" ",fg:null,bg:null,underlineColor:null,attrs:{},wide:!1,continuation:!1,hyperlink:void 0}}function createBuffer(width,height,char=" "){let buffer=new TerminalBuffer(width,height);if(char!==" ")buffer.fill(0,0,width,height,{char});return buffer}function bufferToText(buffer,options={}){let{trimTrailingWhitespace=!0,trimEmptyLines=!0}=options,lines=[];for(let y=0;y<buffer.height;y++){let line="",strOffset=0,contentEdgeStrOffset=0,contentEdge=trimTrailingWhitespace?getContentEdge(buffer,y):0;for(let x=0;x<buffer.width;x++){if(buffer.isCellContinuation(x,y))continue;if(line+=buffer.getCellChar(x,y),strOffset++,x<contentEdge)contentEdgeStrOffset=strOffset}if(trimTrailingWhitespace){let trimmed=line.trimEnd();line=trimmed.length>=contentEdgeStrOffset?trimmed:line.substring(0,contentEdgeStrOffset)}lines.push(line)}let result=lines.join(`
7
+ ${stack}`)}if(this._dirtyRows[y]=1,this._minDirtyRow===-1||y<this._minDirtyRow)this._minDirtyRow=y;if(y>this._maxDirtyRow)this._maxDirtyRow=y;let idx=this.index(x,y);if(!(cell.continuation??!1)){let prevPacked=this.cells[idx];if(prevPacked!==void 0&&(prevPacked&CONTINUATION_FLAG)!==0&&x>0){let prevIdx=idx-1;this.cells[prevIdx]=this.cells[prevIdx]&~WIDE_FLAG,this.chars[prevIdx]=" "}}if(!(cell.wide??!1)){let prevPacked=this.cells[idx];if(prevPacked!==void 0&&(prevPacked&WIDE_FLAG)!==0&&x+1<this.width){let nextIdx=idx+1;this.cells[nextIdx]=this.cells[nextIdx]&~CONTINUATION_FLAG,this.chars[nextIdx]=" "}}let char=cell.char??" ",fg=cell.fg??null,bg=cell.bg??null,underlineColor2=cell.underlineColor??null,attrs=cell.attrs??EMPTY_ATTRS,wide=cell.wide??!1,continuation=cell.continuation??!1;if(this.chars[idx]=char,isTrueColor(fg))this.fgColors.set(idx,fg);else this.fgColors.delete(idx);if(isTrueColor(bg))this.bgColors.set(idx,bg);else this.bgColors.delete(idx);if(underlineColor2!==null)this.underlineColors.set(idx,underlineColor2);else this.underlineColors.delete(idx);let hyperlink2=cell.hyperlink;if(hyperlink2!==void 0&&hyperlink2!=="")this.hyperlinks.set(idx,hyperlink2);else this.hyperlinks.delete(idx);let packed=0;if(packed|=colorToIndex(fg)&255,packed|=(colorToIndex(bg)&255)<<8,packed|=attrsToNumber(attrs),wide)packed|=WIDE_FLAG;if(continuation)packed|=CONTINUATION_FLAG;if(isTrueColor(fg))packed|=TRUE_COLOR_FG_FLAG;if(isTrueColor(bg))packed|=TRUE_COLOR_BG_FLAG;if(this._selectableMode)packed=(packed|SELECTABLE_FLAG)>>>0;this.cells[idx]=packed}fill(x,y,width,height,cell){let endX=Math.min(x+width,this.width),endY=Math.min(y+height,this.height),startX=Math.max(0,x),startY=Math.max(0,y);if(startX>=endX||startY>=endY)return;let char=cell.char??" ",fg=cell.fg??null,bg=cell.bg??null,underlineColor2=cell.underlineColor??null,attrs=cell.attrs??{},wide=cell.wide??!1,continuation=cell.continuation??!1,packed=packCell({char,fg,bg,underlineColor:underlineColor2,attrs,wide,continuation});if(this._selectableMode)packed=(packed|SELECTABLE_FLAG)>>>0;let hasTrueColorFg=isTrueColor(fg),hasTrueColorBg=isTrueColor(bg),trueColorFg=hasTrueColorFg?fg:null,trueColorBg=hasTrueColorBg?bg:null,hasUnderlineColor=underlineColor2!==null,hyperlink2=cell.hyperlink,hasHyperlink=hyperlink2!==void 0&&hyperlink2!=="";for(let cy=startY;cy<endY;cy++)this._dirtyRows[cy]=1;if(startY<endY){if(this._minDirtyRow===-1||startY<this._minDirtyRow)this._minDirtyRow=startY;if(endY-1>this._maxDirtyRow)this._maxDirtyRow=endY-1}let needFgDelete=!hasTrueColorFg&&this.fgColors.size>0,needBgDelete=!hasTrueColorBg&&this.bgColors.size>0,needUlDelete=!hasUnderlineColor&&this.underlineColors.size>0,needHlDelete=!hasHyperlink&&this.hyperlinks.size>0;for(let cy=startY;cy<endY;cy++){let rowBase=cy*this.width;for(let cx=startX;cx<endX;cx++){let idx=rowBase+cx;if(this.cells[idx]=packed,this.chars[idx]=char,hasTrueColorFg)this.fgColors.set(idx,trueColorFg);else if(needFgDelete)this.fgColors.delete(idx);if(hasTrueColorBg)this.bgColors.set(idx,trueColorBg);else if(needBgDelete)this.bgColors.delete(idx);if(hasUnderlineColor)this.underlineColors.set(idx,underlineColor2);else if(needUlDelete)this.underlineColors.delete(idx);if(hasHyperlink)this.hyperlinks.set(idx,hyperlink2);else if(needHlDelete)this.hyperlinks.delete(idx)}}}restyleRegion(x,y,width,height,style2){let endX=Math.min(x+width,this.width),endY=Math.min(y+height,this.height),startX=Math.max(0,x),startY=Math.max(0,y);if(startX>=endX||startY>=endY)return;let fgIndex=colorToIndex(style2.fg)&255,bgIndex=(colorToIndex(style2.bg)&255)<<8,attrBits=attrsToNumber(style2.attrs),hasTrueColorFg=isTrueColor(style2.fg),hasTrueColorBg=isTrueColor(style2.bg),trueColorFgFlag=hasTrueColorFg?TRUE_COLOR_FG_FLAG:0,trueColorBgFlag=hasTrueColorBg?TRUE_COLOR_BG_FLAG:0,trueColorFg=hasTrueColorFg?style2.fg:null,trueColorBg=hasTrueColorBg?style2.bg:null,underlineColor2=style2.underlineColor??null,hasUnderlineColor=underlineColor2!==null,styleBits=fgIndex|bgIndex|attrBits|trueColorFgFlag|trueColorBgFlag,PRESERVE_MASK=WIDE_FLAG|CONTINUATION_FLAG|SELECTABLE_FLAG,needFgDelete=!hasTrueColorFg&&this.fgColors.size>0,needBgDelete=!hasTrueColorBg&&this.bgColors.size>0,needUlDelete=!hasUnderlineColor&&this.underlineColors.size>0;for(let cy=startY;cy<endY;cy++)this._dirtyRows[cy]=1;if(this._minDirtyRow===-1||startY<this._minDirtyRow)this._minDirtyRow=startY;if(endY-1>this._maxDirtyRow)this._maxDirtyRow=endY-1;for(let cy=startY;cy<endY;cy++){let rowBase=cy*this.width;for(let cx=startX;cx<endX;cx++){let idx=rowBase+cx,oldPacked=this.cells[idx];if(this.cells[idx]=(oldPacked&PRESERVE_MASK)>>>0|styleBits,hasTrueColorFg)this.fgColors.set(idx,trueColorFg);else if(needFgDelete)this.fgColors.delete(idx);if(hasTrueColorBg)this.bgColors.set(idx,trueColorBg);else if(needBgDelete)this.bgColors.delete(idx);if(hasUnderlineColor)this.underlineColors.set(idx,underlineColor2);else if(needUlDelete)this.underlineColors.delete(idx)}}}fillBg(x,y,width,height,bg){let endX=Math.min(x+width,this.width),endY=Math.min(y+height,this.height),startX=Math.max(0,x),startY=Math.max(0,y);if(startX>=endX||startY>=endY)return;let bgIndex=(colorToIndex(bg)&255)<<8,hasTrueColorBg=isTrueColor(bg),trueColorBg=hasTrueColorBg?bg:null,needBgDelete=!hasTrueColorBg&&this.bgColors.size>0,BG_CLEAR_MASK=~(65280|TRUE_COLOR_BG_FLAG),trueColorBgFlag=hasTrueColorBg?TRUE_COLOR_BG_FLAG:0;for(let cy=startY;cy<endY;cy++)this._dirtyRows[cy]=1;if(startY<endY){if(this._minDirtyRow===-1||startY<this._minDirtyRow)this._minDirtyRow=startY;if(endY-1>this._maxDirtyRow)this._maxDirtyRow=endY-1}for(let cy=startY;cy<endY;cy++){let rowBase=cy*this.width;for(let cx=startX;cx<endX;cx++){let idx=rowBase+cx,oldPacked=this.cells[idx];if(this.cells[idx]=(oldPacked&BG_CLEAR_MASK)>>>0|bgIndex|trueColorBgFlag,hasTrueColorBg)this.bgColors.set(idx,trueColorBg);else if(needBgDelete)this.bgColors.delete(idx)}}}clear(){this.cells.fill(0),this.chars.fill(" "),this.fgColors.clear(),this.bgColors.clear(),this.underlineColors.clear(),this.hyperlinks.clear(),this._dirtyRows.fill(1),this._minDirtyRow=0,this._maxDirtyRow=this.height-1}copyFrom(source,srcX,srcY,destX,destY,width,height){let cell=createMutableCell();for(let dy=0;dy<height;dy++){let dstY=destY+dy;if(dstY>=0&&dstY<this.height){if(this._dirtyRows[dstY]=1,this._minDirtyRow===-1||dstY<this._minDirtyRow)this._minDirtyRow=dstY;if(dstY>this._maxDirtyRow)this._maxDirtyRow=dstY}for(let dx=0;dx<width;dx++){let sx=srcX+dx,sy=srcY+dy,dX=destX+dx;if(source.inBounds(sx,sy)&&this.inBounds(dX,dstY))source.readCellInto(sx,sy,cell),this.setCell(dX,dstY,cell)}}}scrollRegion(x,y,regionWidth,regionHeight,delta,clearCell={}){if(delta===0||regionHeight<=0||regionWidth<=0)return;let startX=Math.max(0,x),endX=Math.min(x+regionWidth,this.width),startY=Math.max(0,y),endY=Math.min(y+regionHeight,this.height),clampedWidth=endX-startX,clampedHeight=endY-startY;if(clampedWidth<=0||clampedHeight<=0)return;for(let r=startY;r<endY;r++)this._dirtyRows[r]=1;if(this._minDirtyRow===-1||startY<this._minDirtyRow)this._minDirtyRow=startY;if(endY-1>this._maxDirtyRow)this._maxDirtyRow=endY-1;if(Math.abs(delta)>=clampedHeight){this.fill(startX,startY,clampedWidth,clampedHeight,{char:clearCell.char??" ",bg:clearCell.bg??null});return}let absDelta=Math.abs(delta),w=this.width;if(delta>0){for(let row=startY;row<endY-absDelta;row++){let dstBase=row*w,srcBase=(row+absDelta)*w;this.cells.copyWithin(dstBase+startX,srcBase+startX,srcBase+endX);for(let cx=startX;cx<endX;cx++){this.chars[dstBase+cx]=this.chars[srcBase+cx];let srcIdx=srcBase+cx,dstIdx=dstBase+cx,fgc=this.fgColors.get(srcIdx);if(fgc)this.fgColors.set(dstIdx,fgc),this.fgColors.delete(srcIdx);else this.fgColors.delete(dstIdx);let bgc=this.bgColors.get(srcIdx);if(bgc)this.bgColors.set(dstIdx,bgc),this.bgColors.delete(srcIdx);else this.bgColors.delete(dstIdx);let ulc=this.underlineColors.get(srcIdx);if(ulc)this.underlineColors.set(dstIdx,ulc),this.underlineColors.delete(srcIdx);else this.underlineColors.delete(dstIdx);let hl=this.hyperlinks.get(srcIdx);if(hl)this.hyperlinks.set(dstIdx,hl),this.hyperlinks.delete(srcIdx);else this.hyperlinks.delete(dstIdx)}}this.fill(startX,endY-absDelta,clampedWidth,absDelta,{char:clearCell.char??" ",bg:clearCell.bg??null})}else{for(let row=endY-1;row>=startY+absDelta;row--){let dstBase=row*w,srcBase=(row-absDelta)*w;this.cells.copyWithin(dstBase+startX,srcBase+startX,srcBase+endX);for(let cx=startX;cx<endX;cx++){this.chars[dstBase+cx]=this.chars[srcBase+cx];let srcIdx=srcBase+cx,dstIdx=dstBase+cx,fgc=this.fgColors.get(srcIdx);if(fgc)this.fgColors.set(dstIdx,fgc),this.fgColors.delete(srcIdx);else this.fgColors.delete(dstIdx);let bgc=this.bgColors.get(srcIdx);if(bgc)this.bgColors.set(dstIdx,bgc),this.bgColors.delete(srcIdx);else this.bgColors.delete(dstIdx);let ulc=this.underlineColors.get(srcIdx);if(ulc)this.underlineColors.set(dstIdx,ulc),this.underlineColors.delete(srcIdx);else this.underlineColors.delete(dstIdx);let hl=this.hyperlinks.get(srcIdx);if(hl)this.hyperlinks.set(dstIdx,hl),this.hyperlinks.delete(srcIdx);else this.hyperlinks.delete(dstIdx)}}this.fill(startX,startY,clampedWidth,absDelta,{char:clearCell.char??" ",bg:clearCell.bg??null})}}clone(){let copy=new TerminalBuffer(this.width,this.height);return copy.cells.set(this.cells),copy.chars=[...this.chars],copy.fgColors=new Map(this.fgColors),copy.bgColors=new Map(this.bgColors),copy.underlineColors=new Map(this.underlineColors),copy.hyperlinks=new Map(this.hyperlinks),copy._dirtyRows.fill(0),copy._minDirtyRow=-1,copy._maxDirtyRow=-1,copy._rowMetadata=this._rowMetadata.map((m)=>({...m})),copy}isRowDirty(y){if(y<0||y>=this.height)return!1;return this._dirtyRows[y]!==0}get minDirtyRow(){return this._minDirtyRow}get maxDirtyRow(){return this._maxDirtyRow}resetDirtyRows(){this._dirtyRows.fill(0),this._minDirtyRow=-1,this._maxDirtyRow=-1}markAllRowsDirty(){this._dirtyRows.fill(1),this._minDirtyRow=0,this._maxDirtyRow=this.height-1}cellEquals(x,y,other){if(!this.inBounds(x,y)||!other.inBounds(x,y))return!1;let idx=this.index(x,y),otherIdx=other.index(x,y),mask=~SELECTABLE_FLAG;if((this.cells[idx]&mask)!==(other.cells[otherIdx]&mask))return!1;if(this.chars[idx]!==other.chars[otherIdx])return!1;let packed=this.cells[idx];if(unpackTrueColorFg(packed)){let a=this.fgColors.get(idx),b=other.fgColors.get(otherIdx);if(!colorEquals(a,b))return!1}if(unpackTrueColorBg(packed)){let a=this.bgColors.get(idx),b=other.bgColors.get(otherIdx);if(!colorEquals(a,b))return!1}let ulA=this.underlineColors.get(idx)??null,ulB=other.underlineColors.get(otherIdx)??null;if(!colorEquals(ulA,ulB))return!1;let hlA=this.hyperlinks.get(idx),hlB=other.hyperlinks.get(otherIdx);if(hlA!==hlB)return!1;return!0}rowMetadataEquals(y,other){if(y<0||y>=this.height||y>=other.height)return!1;let start=y*this.width,otherStart=y*other.width,w=Math.min(this.width,other.width),mask=~SELECTABLE_FLAG;for(let i=0;i<w;i++)if((this.cells[start+i]&mask)!==(other.cells[otherStart+i]&mask))return!1;return!0}rowCharsEquals(y,other){if(y<0||y>=this.height||y>=other.height)return!1;let start=y*this.width,otherStart=y*other.width,w=Math.min(this.width,other.width);for(let i=0;i<w;i++)if(this.chars[start+i]!==other.chars[otherStart+i])return!1;return!0}rowExtrasEquals(y,other){if(y<0||y>=this.height||y>=other.height)return!1;let start=y*this.width,w=Math.min(this.width,other.width),otherStart=y*other.width;for(let i=0;i<w;i++){let idx=start+i,otherIdx=otherStart+i,packed=this.cells[idx];if((packed&TRUE_COLOR_FG_FLAG)!==0){let a=this.fgColors.get(idx),b=other.fgColors.get(otherIdx);if(!colorEquals(a,b))return!1}if((packed&TRUE_COLOR_BG_FLAG)!==0){let a=this.bgColors.get(idx),b=other.bgColors.get(otherIdx);if(!colorEquals(a,b))return!1}let ulA=this.underlineColors.get(idx)??null,ulB=other.underlineColors.get(otherIdx)??null;if(!colorEquals(ulA,ulB))return!1;let hlA=this.hyperlinks.get(idx),hlB=other.hyperlinks.get(otherIdx);if(hlA!==hlB)return!1}return!0}}function colorEquals(a,b){if(a===b)return!0;if(a===null||a===void 0)return b===null||b===void 0;if(b===null||b===void 0)return!1;if(typeof a==="number")return a===b;if(typeof b==="number")return!1;return a.r===b.r&&a.g===b.g&&a.b===b.b}function cellEquals(a,b){return a.char===b.char&&colorEquals(a.fg,b.fg)&&colorEquals(a.bg,b.bg)&&colorEquals(a.underlineColor,b.underlineColor)&&a.wide===b.wide&&a.continuation===b.continuation&&attrsEquals(a.attrs,b.attrs)&&(a.hyperlink??void 0)===(b.hyperlink??void 0)}function attrsEquals(a,b){return Boolean(a.bold)===Boolean(b.bold)&&Boolean(a.dim)===Boolean(b.dim)&&Boolean(a.italic)===Boolean(b.italic)&&Boolean(a.underline)===Boolean(b.underline)&&(a.underlineStyle??!1)===(b.underlineStyle??!1)&&Boolean(a.blink)===Boolean(b.blink)&&Boolean(a.inverse)===Boolean(b.inverse)&&Boolean(a.hidden)===Boolean(b.hidden)&&Boolean(a.strikethrough)===Boolean(b.strikethrough)}function styleEquals(a,b){if(a===b)return!0;if(!a||!b)return!1;return colorEquals(a.fg,b.fg)&&colorEquals(a.bg,b.bg)&&colorEquals(a.underlineColor,b.underlineColor)&&attrsEquals(a.attrs,b.attrs)&&(a.hyperlink??void 0)===(b.hyperlink??void 0)}function createMutableCell(){return{char:" ",fg:null,bg:null,underlineColor:null,attrs:{},wide:!1,continuation:!1,hyperlink:void 0}}function createBuffer(width,height,char=" "){let buffer=new TerminalBuffer(width,height);if(char!==" ")buffer.fill(0,0,width,height,{char});return buffer}function bufferToText(buffer,options={}){let{trimTrailingWhitespace=!0,trimEmptyLines=!0}=options,lines=[];for(let y=0;y<buffer.height;y++){let line="",strOffset=0,contentEdgeStrOffset=0,contentEdge=trimTrailingWhitespace?getContentEdge(buffer,y):0;for(let x=0;x<buffer.width;x++){if(buffer.isCellContinuation(x,y))continue;if(line+=buffer.getCellChar(x,y),strOffset++,x<contentEdge)contentEdgeStrOffset=strOffset}if(trimTrailingWhitespace){let trimmed=line.trimEnd();line=trimmed.length>=contentEdgeStrOffset?trimmed:line.substring(0,contentEdgeStrOffset)}lines.push(line)}let result=lines.join(`
8
8
  `);if(trimEmptyLines){while(lines.length>0&&lines[lines.length-1].length===0)lines.pop();result=lines.join(`
9
9
  `)}return result}function getContentEdge(buffer,y){let FLAG_MASK=~(WIDE_FLAG|CONTINUATION_FLAG|SELECTABLE_FLAG);for(let x=buffer.width-1;x>=0;x--){if(buffer.isCellContinuation(x,y))continue;if((buffer.getCellAttrs(x,y)&FLAG_MASK)!==0)return x+1;if(buffer.getCellChar(x,y)!==" ")return x+1}return 0}function bufferToStyledText(buffer,options={}){let{trimTrailingWhitespace=!0,trimEmptyLines=!0}=options,lines=[],currentStyle=null,currentHyperlink;for(let y=0;y<buffer.height;y++){let line="";for(let x=0;x<buffer.width;x++){let cell=buffer.getCell(x,y);if(cell.continuation)continue;let cellHyperlink=cell.hyperlink;if(cellHyperlink!==currentHyperlink){if(currentHyperlink)line+=emitHyperlinkClose(currentHyperlink);if(cellHyperlink)line+=emitHyperlinkOpen(cellHyperlink);currentHyperlink=cellHyperlink}let cellStyle={fg:cell.fg,bg:cell.bg,underlineColor:cell.underlineColor,attrs:cell.attrs};if(!styleEquals(currentStyle,cellStyle))line+=styleTransitionCodes(currentStyle,cellStyle),currentStyle=cellStyle;line+=cell.char}if(currentHyperlink)line+=emitHyperlinkClose(currentHyperlink),currentHyperlink=void 0;if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))line+=styleResetCodes(currentStyle),currentStyle=null;if(trimTrailingWhitespace)line=trimTrailingWhitespacePreservingAnsi(line);lines.push(line)}let result=lines.join(`
10
10
  `);if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))result+=styleResetCodes(currentStyle);if(trimEmptyLines)result=result.replace(/\n+$/,"");return result}function decodeHyperlinkFormat(encoded){if(encoded.charCodeAt(0)===1){let sepIdx=encoded.indexOf("\x02");if(sepIdx>0){let tag=encoded.slice(1,sepIdx),url=encoded.slice(sepIdx+1);if(tag==="c1b")return{url,oscIntro:"",oscClose:"",closeIntro:"",closeTerminator:"\x07"};if(tag==="c1s")return{url,oscIntro:"",oscClose:"",closeIntro:"",closeTerminator:"\x1B\\"};if(tag==="e7b")return{url,oscIntro:"\x1B]",oscClose:"\x1B]",closeIntro:"\x1B]",closeTerminator:"\x07"}}}return{url:encoded,oscIntro:"\x1B]",oscClose:"\x1B]",closeIntro:"\x1B]",closeTerminator:"\x1B\\"}}function emitHyperlinkOpen(encoded){let fmt=decodeHyperlinkFormat(encoded);return`${fmt.oscIntro}8;;${fmt.url}${fmt.closeTerminator}`}function emitHyperlinkClose(encoded){let fmt=decodeHyperlinkFormat(encoded);return`${fmt.closeIntro}8;;${fmt.closeTerminator}`}function colorToCSS(color){if(color===null)return null;if(typeof color==="number")return XTERM_256_PALETTE[color]??null;if(color.r===-1)return null;return`rgb(${color.r},${color.g},${color.b})`}function bufferToHTML(buffer,options={}){let{fontFamily="JetBrains Mono, Menlo, monospace",fontSize=14,theme="dark"}=options,defaultFg=theme==="dark"?"#d4d4d4":"#1e1e1e",defaultBg=theme==="dark"?"#1e1e1e":"#ffffff",htmlLines=[];for(let y=0;y<buffer.height;y++){let lineHTML="",currentStyle=null,spanOpen=!1,linkOpen=!1,currentHyperlink;for(let x=0;x<buffer.width;x++){let cell=buffer.getCell(x,y);if(cell.continuation)continue;let cellHyperlink=cell.hyperlink;if(cellHyperlink!==currentHyperlink){if(linkOpen){if(spanOpen)lineHTML+="</span>",spanOpen=!1;lineHTML+="</a>",linkOpen=!1}if(cellHyperlink)lineHTML+=`<a href="${escapeHTML(cellHyperlink)}">`,linkOpen=!0;currentHyperlink=cellHyperlink}let cellStyle={fg:cell.fg,bg:cell.bg,underlineColor:cell.underlineColor,attrs:cell.attrs};if(!styleEquals(currentStyle,cellStyle)){if(spanOpen)lineHTML+="</span>",spanOpen=!1;let css=styleToCSSProperties(cellStyle,defaultFg,defaultBg);if(css)lineHTML+=`<span style="${css}">`,spanOpen=!0;currentStyle=cellStyle}lineHTML+=escapeHTML(cell.char)}if(spanOpen)lineHTML+="</span>";if(linkOpen)lineHTML+="</a>",currentHyperlink=void 0;htmlLines.push(`<div>${lineHTML}</div>`)}return`<!DOCTYPE html>
@@ -15,30 +15,11 @@ ${htmlLines.join(`
15
15
  `)}
16
16
  </body>
17
17
  </html>`}function styleToCSSProperties(style2,defaultFg,defaultBg){let parts=[],fgColor,bgColor;if(style2.attrs.inverse)fgColor=colorToCSS(style2.bg)??defaultBg,bgColor=colorToCSS(style2.fg)??defaultFg;else fgColor=colorToCSS(style2.fg),bgColor=colorToCSS(style2.bg);if(fgColor)parts.push(`color:${fgColor}`);if(bgColor)parts.push(`background:${bgColor}`);if(style2.attrs.bold)parts.push("font-weight:bold");if(style2.attrs.dim)parts.push("opacity:0.5");if(style2.attrs.italic)parts.push("font-style:italic");if(style2.attrs.hidden)parts.push("visibility:hidden");let decorations=[],underlineStyle=style2.attrs.underlineStyle;if(typeof underlineStyle==="string"){let cssStyleMap={single:"solid",double:"double",curly:"wavy",dotted:"dotted",dashed:"dashed"};decorations.push("underline");let cssStyle=cssStyleMap[underlineStyle];if(cssStyle)parts.push(`text-decoration-style:${cssStyle}`);let ulColor=colorToCSS(style2.underlineColor??null);if(ulColor)parts.push(`text-decoration-color:${ulColor}`)}else if(style2.attrs.underline)decorations.push("underline");if(style2.attrs.strikethrough)decorations.push("line-through");if(decorations.length>0)parts.push(`text-decoration:${decorations.join(" ")}`);return parts.length>0?parts.join(";"):null}function escapeHTML(str){if(str===" "||str.length===0)return str;return str.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}function hasActiveAttrs(attrs){return!!(attrs.bold||attrs.dim||attrs.italic||attrs.underline||attrs.underlineStyle||attrs.blink||attrs.inverse||attrs.hidden||attrs.strikethrough)}function styleToAnsiCodes(style2){let{fg,bg}=style2,result="";if(fg!==null)result+=`\x1B[${fgColorCode(fg)}m`;if(bg!==null&&!isDefaultBg(bg))result+=`\x1B[${bgColorCode(bg)}m`;if(style2.attrs.bold)result+="\x1B[1m";if(style2.attrs.dim)result+="\x1B[2m";if(style2.attrs.italic)result+="\x1B[3m";let underlineStyle=style2.attrs.underlineStyle;if(typeof underlineStyle==="string"){let subparam={single:1,double:2,curly:3,dotted:4,dashed:5}[underlineStyle];if(subparam!==void 0&&subparam!==0)result+=`\x1B[4:${subparam}m`}else if(style2.attrs.underline)result+="\x1B[4m";if(style2.attrs.inverse)result+="\x1B[7m";if(style2.attrs.strikethrough)result+="\x1B[9m";if(style2.underlineColor!==null&&style2.underlineColor!==void 0)if(typeof style2.underlineColor==="number")result+=`\x1B[58;5;${style2.underlineColor}m`;else result+=`\x1B[58;2;${style2.underlineColor.r};${style2.underlineColor.g};${style2.underlineColor.b}m`;return result}function styleTransitionCodes(oldStyle,newStyle){if(!oldStyle)return styleToAnsiCodes(newStyle);if(styleEquals(oldStyle,newStyle))return"";let result="",oa=oldStyle.attrs,na=newStyle.attrs,boldChanged=Boolean(oa.bold)!==Boolean(na.bold),dimChanged=Boolean(oa.dim)!==Boolean(na.dim);if(boldChanged||dimChanged){let boldOff=boldChanged&&!na.bold,dimOff=dimChanged&&!na.dim;if(boldOff||dimOff){if(result+="\x1B[22m",na.bold)result+="\x1B[1m";if(na.dim)result+="\x1B[2m"}else{if(boldChanged&&na.bold)result+="\x1B[1m";if(dimChanged&&na.dim)result+="\x1B[2m"}}if(Boolean(oa.italic)!==Boolean(na.italic))result+=na.italic?"\x1B[3m":"\x1B[23m";let oldUl=Boolean(oa.underline),newUl=Boolean(na.underline),oldUlStyle=oa.underlineStyle??!1,newUlStyle=na.underlineStyle??!1;if(oldUl!==newUl||oldUlStyle!==newUlStyle)if(typeof na.underlineStyle==="string"){let sub={single:1,double:2,curly:3,dotted:4,dashed:5}[na.underlineStyle];if(sub!==void 0&&sub!==0)result+=`\x1B[4:${sub}m`;else if(newUl)result+="\x1B[4m";else result+="\x1B[24m"}else if(newUl)result+="\x1B[4m";else result+="\x1B[24m";if(Boolean(oa.inverse)!==Boolean(na.inverse))result+=na.inverse?"\x1B[7m":"\x1B[27m";if(Boolean(oa.strikethrough)!==Boolean(na.strikethrough))result+=na.strikethrough?"\x1B[9m":"\x1B[29m";if(!colorEquals(oldStyle.fg,newStyle.fg))if(newStyle.fg===null)result+="\x1B[39m";else result+=`\x1B[${fgColorCode(newStyle.fg)}m`;if(!colorEquals(oldStyle.bg,newStyle.bg))if(newStyle.bg===null)result+="\x1B[49m";else result+=`\x1B[${bgColorCode(newStyle.bg)}m`;if(!colorEquals(oldStyle.underlineColor,newStyle.underlineColor))if(newStyle.underlineColor===null||newStyle.underlineColor===void 0)result+="\x1B[59m";else if(typeof newStyle.underlineColor==="number")result+=`\x1B[58;5;${newStyle.underlineColor}m`;else result+=`\x1B[58;2;${newStyle.underlineColor.r};${newStyle.underlineColor.g};${newStyle.underlineColor.b}m`;return result}function styleResetCodes(style2){let result="";if(style2.attrs.underline||style2.attrs.underlineStyle)result+="\x1B[24m";if(style2.attrs.bold||style2.attrs.dim)result+="\x1B[22m";if(style2.attrs.italic)result+="\x1B[23m";if(style2.attrs.strikethrough)result+="\x1B[29m";if(style2.attrs.inverse)result+="\x1B[27m";if(style2.bg!==null&&!isDefaultBg(style2.bg))result+="\x1B[49m";if(style2.fg!==null)result+="\x1B[39m";if(style2.underlineColor!==null&&style2.underlineColor!==void 0)result+="\x1B[59m";return result}function trimTrailingWhitespacePreservingAnsi(str){let lastContentIndex=-1,i=0;while(i<str.length){if(str[i]==="\x1B"){if(str[i+1]==="]"){let end2=-1;for(let j=i+2;j<str.length;j++){if(str[j]==="\x07"){end2=j;break}if(str[j]==="\x1B"&&str[j+1]==="\\"){end2=j+1;break}}if(end2!==-1){lastContentIndex=end2,i=end2+1;continue}}let end=str.indexOf("m",i);if(end!==-1){lastContentIndex=end,i=end+1;continue}}if(str[i]!==" "&&str[i]!=="\t")lastContentIndex=i;i++}return str.slice(0,lastContentIndex+1)}function ansi256ToRgb(idx){if(idx<16){let table=[[0,0,0],[128,0,0],[0,128,0],[128,128,0],[0,0,128],[128,0,128],[0,128,128],[192,192,192],[128,128,128],[255,0,0],[0,255,0],[255,255,0],[0,0,255],[255,0,255],[0,255,255],[255,255,255]],[r,g,b]=table[idx];return{r,g,b}}if(idx<232){let i=idx-16,r=Math.floor(i/36),g=Math.floor(i%36/6),b=i%6;return{r:r?r*40+55:0,g:g?g*40+55:0,b:b?b*40+55:0}}let v=(idx-232)*10+8;return{r:v,g:v,b:v}}function resolveColor(color){if(color===null)return null;if(typeof color==="number")return ansi256ToRgb(color);if(color.r===-1)return null;return color}function cellToFrameCell(c){let ulStyle=c.attrs.underlineStyle??(c.attrs.underline?"single":!1);return{char:c.char,fg:resolveColor(c.fg),bg:resolveColor(c.bg),bold:c.attrs.bold??!1,dim:c.attrs.dim??!1,italic:c.attrs.italic??!1,underline:ulStyle,underlineColor:resolveColor(c.underlineColor??null),strikethrough:c.attrs.strikethrough??!1,inverse:c.attrs.inverse??!1,blink:c.attrs.blink??!1,hidden:c.attrs.hidden??!1,wide:c.wide,continuation:c.continuation,hyperlink:c.hyperlink??null}}function createTextFrame(buffer){let{width,height}=buffer,snapshot=buffer.clone(),cellData=Array(width*height);for(let y=0;y<height;y++)for(let x=0;x<width;x++)cellData[y*width+x]=snapshot.getCell(x,y);let _text,_ansi,_lines,frame={width,height,get text(){if(_text===void 0)_text=bufferToText(snapshot);return _text},get ansi(){if(_ansi===void 0)_ansi=bufferToStyledText(snapshot);return _ansi},get lines(){if(_lines===void 0)_lines=frame.text.split(`
18
- `);return _lines},cell(col,row){if(col<0||col>=width||row<0||row>=height)return EMPTY_FRAME_CELL;return cellToFrameCell(cellData[row*width+col])},containsText(text){return frame.text.includes(text)}};return frame}var DEFAULT_BG,ATTR_BOLD=65536,ATTR_DIM=131072,ATTR_ITALIC=262144,ATTR_BLINK=524288,ATTR_INVERSE=1048576,ATTR_HIDDEN=2097152,ATTR_STRIKETHROUGH=4194304,UNDERLINE_STYLE_SHIFT=24,UNDERLINE_STYLE_MASK,WIDE_FLAG=134217728,CONTINUATION_FLAG=268435456,TRUE_COLOR_FG_FLAG=536870912,TRUE_COLOR_BG_FLAG=1073741824,SELECTABLE_FLAG=2147483648,VISIBLE_SPACE_ATTR_MASK,EMPTY_CELL,EMPTY_ATTRS,XTERM_256_PALETTE,EMPTY_FRAME_CELL;var init_buffer=__esm(()=>{init_sgr_codes();DEFAULT_BG=Object.freeze({r:-1,g:-1,b:-1});UNDERLINE_STYLE_MASK=7<<UNDERLINE_STYLE_SHIFT;VISIBLE_SPACE_ATTR_MASK=ATTR_INVERSE|ATTR_STRIKETHROUGH|UNDERLINE_STYLE_MASK,EMPTY_CELL={char:" ",fg:null,bg:null,underlineColor:null,attrs:{},wide:!1,continuation:!1,hyperlink:void 0},EMPTY_ATTRS=Object.freeze({});XTERM_256_PALETTE=(()=>{let palette=Array(256),standard=["#000000","#cd0000","#00cd00","#cdcd00","#0000ee","#cd00cd","#00cdcd","#e5e5e5"],bright=["#7f7f7f","#ff0000","#00ff00","#ffff00","#5c5cff","#ff00ff","#00ffff","#ffffff"];for(let i=0;i<8;i++)palette[i]=standard[i],palette[i+8]=bright[i];let cubeValues=[0,95,135,175,215,255];for(let i=0;i<216;i++){let r=cubeValues[Math.floor(i/36)],g=cubeValues[Math.floor(i%36/6)],b=cubeValues[i%6];palette[16+i]="#"+r.toString(16).padStart(2,"0")+g.toString(16).padStart(2,"0")+b.toString(16).padStart(2,"0")}for(let i=0;i<24;i++){let hex=(8+i*10).toString(16).padStart(2,"0");palette[232+i]="#"+hex+hex+hex}return palette})();EMPTY_FRAME_CELL=Object.freeze({char:" ",fg:null,bg:null,bold:!1,dim:!1,italic:!1,underline:!1,underlineColor:null,strikethrough:!1,inverse:!1,blink:!1,hidden:!1,wide:!1,continuation:!1,hyperlink:null})});var IncrementalRenderMismatchError;var init_errors=__esm(()=>{IncrementalRenderMismatchError=class IncrementalRenderMismatchError extends Error{renderPhaseStats;mismatchContext;constructor(message,data){super(message);this.name="IncrementalRenderMismatchError",this.renderPhaseStats=data?.renderPhaseStats,this.mismatchContext=data?.mismatchContext}}});function textSized(text,width){return`\x1B]66;w=${width};${text}\x07`}function isPrivateUseArea(cp){return cp>=57344&&cp<=63743||cp>=983040&&cp<=1048573||cp>=1048576&&cp<=1114109}function isTextSizingLikelySupported(){let termProgram=process.env.TERM_PROGRAM?.toLowerCase()??"",termVersion=process.env.TERM_PROGRAM_VERSION??"";if(termProgram==="kitty"){let parts=termVersion.split("."),major=Number(parts[0])||0,minor=Number(parts[1])||0;if(major>0||major===0&&minor>=40)return!0}return!1}function getTerminalFingerprint(){let program=process.env.TERM_PROGRAM??"unknown",version=process.env.TERM_PROGRAM_VERSION??"unknown";return`${program}@${version}`}function getCachedProbeResult(){return probeCache.get(getTerminalFingerprint())}function setCachedProbeResult(result){probeCache.set(getTerminalFingerprint(),result)}async function detectTextSizingSupport(write,read,timeout=1000){let cached=getCachedProbeResult();if(cached!==void 0)return cached;let testSequence="\r"+textSized(" ",2)+"\x1B[6n\r\x1B[K";write(testSequence);try{let match=(await Promise.race([read(),new Promise((_resolve,reject)=>setTimeout(()=>reject(Error("timeout")),timeout))])).match(/\x1b\[(\d+);(\d+)R/);if(match){if(Number(match[2])===3){let result2={supported:!0,widthOnly:!1};return setCachedProbeResult(result2),result2}}let result={supported:!1,widthOnly:!1};return setCachedProbeResult(result),result}catch{let result={supported:!1,widthOnly:!1};return setCachedProbeResult(result),result}}var probeCache;var init_text_sizing=__esm(()=>{probeCache=new Map});import sliceAnsi from"slice-ansi";import stringWidth2 from"string-width";class DisplayWidthCache{cache=new Map;maxSize;constructor(maxSize=1000){this.maxSize=maxSize}get(text){let cached=this.cache.get(text);if(cached!==void 0)this.cache.delete(text),this.cache.set(text,cached);return cached}set(text,width){if(this.cache.size>=this.maxSize){let firstKey=this.cache.keys().next().value;if(firstKey!==void 0)this.cache.delete(firstKey)}this.cache.set(text,width)}clear(){this.cache.clear()}}function runWithMeasurer(measurer,fn){let prev=_scopedMeasurer;_scopedMeasurer=measurer;try{return fn()}finally{_scopedMeasurer=prev}}function isTextSizingEnabled(){if(_scopedMeasurer)return _scopedMeasurer.textSizingEnabled;return DEFAULT_TEXT_SIZING_ENABLED}function stripOsc8ForSlice(text){return text.replace(OSC8_RE,"")}function createWidthMeasurer(caps={}){let textEmojiWide=caps.textEmojiWide??!0,textSizingEnabled=caps.textSizingEnabled??!1,cache=new DisplayWidthCache(1e4);function measuredGraphemeWidth(grapheme){let width=stringWidth2(grapheme);if(width!==1)return width;if(textEmojiWide&&isTextPresentationEmoji(grapheme))return 2;if(textSizingEnabled){let cp=grapheme.codePointAt(0);if(cp!==void 0&&isPrivateUseArea(cp))return 2}return width}function measuredDisplayWidth(text){let cached=cache.get(text);if(cached!==void 0)return cached;let width;if(!(MAY_CONTAIN_TEXT_EMOJI.test(text)||textSizingEnabled&&MAY_CONTAIN_PUA.test(text)))width=stringWidth2(text);else{let stripped=stripAnsi2(text);width=0;for(let grapheme of splitGraphemes(stripped))width+=measuredGraphemeWidth(grapheme)}return cache.set(text,width),width}function measuredDisplayWidthAnsi(text){return measuredDisplayWidth(stripAnsi2(text))}function measuredSliceByWidth(text,maxWidth){if(hasAnsi(text))return sliceAnsi(stripOsc8ForSlice(text),0,maxWidth);let width=0,result="",graphemes=splitGraphemes(text);for(let grapheme of graphemes){let gWidth=measuredGraphemeWidth(grapheme);if(width+gWidth>maxWidth)break;result+=grapheme,width+=gWidth}return result}function measuredSliceByWidthFromEnd(text,maxWidth){if(measuredDisplayWidthAnsi(text)<=maxWidth)return text;if(hasAnsi(text)){let cleaned=stripOsc8ForSlice(text),startIndex=measuredDisplayWidthAnsi(cleaned)-maxWidth;return sliceAnsi(cleaned,startIndex)}let graphemes=splitGraphemes(text),width=0,startIdx=graphemes.length;for(let i=graphemes.length-1;i>=0;i--){let gWidth=measuredGraphemeWidth(graphemes[i]);if(width+gWidth>maxWidth)break;width+=gWidth,startIdx=i}return graphemes.slice(startIdx).join("")}function measuredWrapText(text,width,trim,hard){return wrapTextWithMeasurer(text,width,measurer,trim??!1,hard??!1)}let measurer={textEmojiWide,textSizingEnabled,lineHeight:1,displayWidth:measuredDisplayWidth,displayWidthAnsi:measuredDisplayWidthAnsi,graphemeWidth:measuredGraphemeWidth,wrapText:measuredWrapText,sliceByWidth:measuredSliceByWidth,sliceByWidthFromEnd:measuredSliceByWidthFromEnd};return measurer}function getDefaultMeasurer(){if(!_defaultMeasurer)_defaultMeasurer=createWidthMeasurer();return _defaultMeasurer}function splitGraphemes(text){return[...segmenter.segment(text)].map((s)=>s.segment)}function isTextPresentationEmoji(grapheme){let cp=grapheme.codePointAt(0);if(cp===void 0)return!1;let cached=textPresentationEmojiCache.get(cp);if(cached!==void 0)return cached;if(String.fromCodePoint(cp).length!==grapheme.length)return textPresentationEmojiCache.set(cp,!1),!1;let isExtPict=TEXT_PRESENTATION_EMOJI_REGEX.test(grapheme),isEmojiPres=EMOJI_PRESENTATION_REGEX.test(grapheme);if(!isExtPict||isEmojiPres)return textPresentationEmojiCache.set(cp,!1),!1;let withVs16=grapheme+"️",result=RGI_EMOJI_REGEX.test(withVs16);return textPresentationEmojiCache.set(cp,result),result}function ensureEmojiPresentation(char){if(char.includes("️"))return char;if(isTextPresentationEmoji(char))return char+"️";return char}function displayWidth(text){if(_scopedMeasurer)return _scopedMeasurer.displayWidth(text);let cached=displayWidthCache.get(text);if(cached!==void 0)return cached;let width;if(!(MAY_CONTAIN_TEXT_EMOJI.test(text)||DEFAULT_TEXT_SIZING_ENABLED&&MAY_CONTAIN_PUA.test(text)))width=stringWidth2(text);else{let stripped=stripAnsi2(text);width=0;for(let grapheme of splitGraphemes(stripped))width+=graphemeWidth(grapheme)}return displayWidthCache.set(text,width),width}function graphemeWidth(grapheme){if(_scopedMeasurer)return _scopedMeasurer.graphemeWidth(grapheme);let width=stringWidth2(grapheme);if(width!==1)return width;if(DEFAULT_TEXT_EMOJI_WIDE&&isTextPresentationEmoji(grapheme))return 2;if(DEFAULT_TEXT_SIZING_ENABLED){let cp=grapheme.codePointAt(0);if(cp!==void 0&&isPrivateUseArea(cp))return 2}return width}function isWordBoundary(grapheme){return grapheme===" "||grapheme==="-"||grapheme==="\t"}function isBreakBeforeOperatorWith(graphemes,spaceIndex,gWidthFn){let j=spaceIndex+1;while(j<graphemes.length&&gWidthFn(graphemes[j])===0)j++;if(j>=graphemes.length)return!1;let nextChar=graphemes[j];if(gWidthFn(nextChar)!==1)return!1;if(/^[a-zA-Z0-9\s]$/.test(nextChar))return!1;let k=j+1;while(k<graphemes.length&&gWidthFn(graphemes[k])===0)k++;if(k>=graphemes.length)return!1;return graphemes[k]===" "}function canBreakAnywhere(grapheme){return isCJK(grapheme)}function splitGraphemesAnsiAware(text){if(!hasAnsi(text))return splitGraphemes(text);let result=[],pos=0;while(pos<text.length){if(text[pos]==="\x1B"){let remaining=text.slice(pos),csi=remaining.match(ANSI_CSI_RE);if(csi){result.push(csi[0]),pos+=csi[0].length;continue}let osc=remaining.match(ANSI_OSC_RE);if(osc){result.push(osc[0]),pos+=osc[0].length;continue}let single=remaining.match(ANSI_SINGLE_RE);if(single){result.push(single[0]),pos+=single[0].length;continue}}let nextEsc=text.indexOf("\x1B",pos+1),chunk=nextEsc===-1?text.slice(pos):text.slice(pos,nextEsc);for(let g of splitGraphemes(chunk))result.push(g);pos+=chunk.length}return result}function wrapText(text,width,preserveNewlines=!0,trim=!1){if(_scopedMeasurer?.wrapText)return _scopedMeasurer.wrapText(text,width,trim);return wrapTextWithMeasurer(text,width,_scopedMeasurer??void 0,trim,!1,preserveNewlines)}function getActiveLineHeight(){return _scopedMeasurer?.lineHeight??1}function wrapTextWithMeasurer(text,width,measurer,trim=!1,_hard=!1,preserveNewlines=!0){if(width<=0)return[];let gWidthFn=measurer?measurer.graphemeWidth.bind(measurer):graphemeWidth,lines=[],inputLines=preserveNewlines?text.split(`
19
- `):[text.replace(/\n/g," ")];for(let line of inputLines){if(line===""){lines.push("");continue}let graphemes=splitGraphemesAnsiAware(line),currentLine="",currentWidth=0,isFirstLineOfParagraph=!0,lastBreakIndex=-1,lastBreakWidth=0,lastBreakGraphemeIndex=-1;for(let i=0;i<graphemes.length;i++){let grapheme=graphemes[i],gWidth=gWidthFn(grapheme);if(gWidth===0){currentLine+=grapheme;continue}if(trim&&!isFirstLineOfParagraph&&currentWidth===0&&isWordBoundary(grapheme)&&grapheme!=="-")continue;if(isWordBoundary(grapheme)){if(currentWidth+gWidth<=width){if(currentLine+=grapheme,currentWidth+=gWidth,grapheme!==" "||!isBreakBeforeOperatorWith(graphemes,i,gWidthFn))lastBreakIndex=currentLine.length,lastBreakWidth=currentWidth,lastBreakGraphemeIndex=i+1;continue}if(currentLine){let lineToAdd=currentLine;if(trim)lineToAdd=lineToAdd.trimEnd();lines.push(lineToAdd),isFirstLineOfParagraph=!1}currentLine="",currentWidth=0,lastBreakIndex=-1,lastBreakWidth=0,lastBreakGraphemeIndex=-1;continue}else if(canBreakAnywhere(grapheme))lastBreakIndex=currentLine.length,lastBreakWidth=currentWidth,lastBreakGraphemeIndex=i;if(currentWidth+gWidth>width)if(lastBreakIndex>0){let lineToAdd=currentLine.slice(0,lastBreakIndex);if(trim)lineToAdd=lineToAdd.trimEnd();lines.push(lineToAdd),isFirstLineOfParagraph=!1,currentLine=currentLine.slice(lastBreakIndex),currentWidth=currentWidth-lastBreakWidth,i=lastBreakGraphemeIndex-1,currentLine="",currentWidth=0,lastBreakIndex=-1,lastBreakWidth=0,lastBreakGraphemeIndex=-1}else{if(currentLine){if(trim)currentLine=currentLine.trimEnd();lines.push(currentLine),isFirstLineOfParagraph=!1}currentLine=grapheme,currentWidth=gWidth,lastBreakIndex=-1,lastBreakWidth=0,lastBreakGraphemeIndex=-1}else currentLine+=grapheme,currentWidth+=gWidth}if(currentLine)lines.push(currentLine)}if(text.includes("\x1B]8;;"))fixOsc8AcrossWrappedLines(lines);return lines}function fixOsc8AcrossWrappedLines(lines){let activeHref=null;for(let i=0;i<lines.length;i++){let line=lines[i];if(activeHref!==null)line=`\x1B]8;;${activeHref}\x1B\\`+line;let lineHref=activeHref,osc8Matches=line.matchAll(/\x1b\]8;;([^\x07\x1b]*)(?:\x07|\x1b\\)/g);for(let m of osc8Matches)lineHref=m[1]===""?null:m[1];if(lineHref!==null)line+="\x1B]8;;\x1B\\";lines[i]=line,activeHref=lineHref}}function sliceByWidth(text,maxWidth){return(_scopedMeasurer??getDefaultMeasurer()).sliceByWidth(text,maxWidth)}function sliceByWidthFromEnd(text,maxWidth){return(_scopedMeasurer??getDefaultMeasurer()).sliceByWidthFromEnd(text,maxWidth)}function stripAnsi2(text){return text.replace(/\x1b\[[0-9;:?]*[A-Za-z]/g,"").replace(/\x9b[0-9;:?]*[A-Za-z]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x9d[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c)/g,"").replace(/\x1b[DME78]/g,"").replace(/\x1b\(B/g,"")}function displayWidthAnsi(text){return displayWidth(stripAnsi2(text))}function parseUnderlineStyle(subparam){switch(subparam){case 0:return!1;case 1:return"single";case 2:return"double";case 3:return"curly";case 4:return"dotted";case 5:return"dashed";default:return"single"}}function parseAnsiText(text){let segments=[],sanitizedText=text.replace(/\x1b\[[0-9;:]*[A-LN-Za-ln-z@`]/g,"").replace(/\x9b[0-9;:]*[A-LN-Za-ln-z@`]/g,""),oscPattern=/(?:\x1b\]|\x9d)8;;([^\x07\x1b\x9c]*)(?:\x07|\x1b\\|\x9c)/g,currentHyperlink,hyperlinkRanges=[],rangeStart=-1,cleaned="",oscMatch,oscLastIndex=0;while((oscMatch=oscPattern.exec(sanitizedText))!==null){cleaned+=sanitizedText.slice(oscLastIndex,oscMatch.index);let url=oscMatch[1],matchStr=oscMatch[0],isC1=matchStr.charCodeAt(0)===157,lastChar=matchStr.charCodeAt(matchStr.length-1),isBel=lastChar===7,isSt9c=lastChar===156;if(url===""){if(currentHyperlink&&rangeStart>=0)hyperlinkRanges.push({start:rangeStart,end:cleaned.length,url:currentHyperlink});currentHyperlink=void 0,rangeStart=-1}else{if(currentHyperlink&&rangeStart>=0)hyperlinkRanges.push({start:rangeStart,end:cleaned.length,url:currentHyperlink});let encodedUrl=url;if(isC1&&(isBel||isSt9c))encodedUrl=`\x01c1b\x02${url}`;else if(isC1)encodedUrl=`\x01c1s\x02${url}`;else if(isBel)encodedUrl=`\x01e7b\x02${url}`;currentHyperlink=encodedUrl,rangeStart=cleaned.length}oscLastIndex=oscMatch.index+oscMatch[0].length}if(cleaned+=sanitizedText.slice(oscLastIndex),currentHyperlink&&rangeStart>=0)hyperlinkRanges.push({start:rangeStart,end:cleaned.length,url:currentHyperlink});let processText=hyperlinkRanges.length>0?cleaned:sanitizedText,ansiPattern=/(?:\x1b\[|\x9b)([0-9;:]*)m/g,currentStyle={},lastIndex=0,match;function getHyperlinkAt(pos){for(let range of hyperlinkRanges)if(pos>=range.start&&pos<range.end)return range.url;return}while((match=ansiPattern.exec(processText))!==null){if(match.index>lastIndex){let content=processText.slice(lastIndex,match.index);if(content.length>0)if(hyperlinkRanges.length>0){let segStart=0;for(let ci=0;ci<content.length;ci++){let hl=getHyperlinkAt(lastIndex+ci),prevHl=ci>0?getHyperlinkAt(lastIndex+ci-1):void 0;if(ci>0&&hl!==prevHl){let sub2=content.slice(segStart,ci);if(sub2.length>0){let seg={text:sub2,...currentStyle};if(prevHl)seg.hyperlink=prevHl;segments.push(seg)}segStart=ci}}let sub=content.slice(segStart);if(sub.length>0){let hl=getHyperlinkAt(lastIndex+segStart),seg={text:sub,...currentStyle};if(hl)seg.hyperlink=hl;segments.push(seg)}}else segments.push({text:content,...currentStyle})}let params=match[1].split(";");for(let i=0;i<params.length;i++){let param=params[i];if(param.includes(":")){let subparts=param.split(":").map((s)=>s===""?0:Number(s)),mainCode=subparts[0];if(mainCode===4){let styleCode=subparts[1]??1;currentStyle.underlineStyle=parseUnderlineStyle(styleCode),currentStyle.underline=currentStyle.underlineStyle!==!1}else if(mainCode===58){if(subparts[1]===5&&subparts[2]!==void 0)currentStyle.underlineColor=subparts[2];else if(subparts[1]===2){let r=subparts[3]??subparts[2]??0,g=subparts[4]??subparts[3]??0,b=subparts[5]??subparts[4]??0;currentStyle.underlineColor=16777216|(r&255)<<16|(g&255)<<8|b&255}}else if(mainCode===38){if(subparts[1]===5&&subparts[2]!==void 0)currentStyle.fg=subparts[2],currentStyle.colonFg=!0;else if(subparts[1]===2){let r=subparts[3]??subparts[2]??0,g=subparts[4]??subparts[3]??0,b=subparts[5]??subparts[4]??0;currentStyle.fg=16777216|(r&255)<<16|(g&255)<<8|b&255,currentStyle.colonFg=!0}}else if(mainCode===48){if(subparts[1]===5&&subparts[2]!==void 0)currentStyle.bg=subparts[2],currentStyle.colonBg=!0;else if(subparts[1]===2){let r=subparts[3]??subparts[2]??0,g=subparts[4]??subparts[3]??0,b=subparts[5]??subparts[4]??0;currentStyle.bg=16777216|(r&255)<<16|(g&255)<<8|b&255,currentStyle.colonBg=!0}}continue}let code=Number(param);switch(code){case 0:currentStyle={};break;case 1:currentStyle.bold=!0;break;case 2:currentStyle.dim=!0;break;case 3:currentStyle.italic=!0;break;case 4:currentStyle.underline=!0,currentStyle.underlineStyle="single";break;case 7:currentStyle.inverse=!0;break;case 22:currentStyle.bold=!1,currentStyle.dim=!1;break;case 23:currentStyle.italic=!1;break;case 24:currentStyle.underline=!1,currentStyle.underlineStyle=!1;break;case 27:currentStyle.inverse=!1;break;case 30:case 31:case 32:case 33:case 34:case 35:case 36:case 37:currentStyle.fg=code;break;case 38:{let nextParams=params.slice(i+1).map(Number);if(currentStyle.colonFg=void 0,nextParams[0]===5&&nextParams[1]!==void 0)currentStyle.fg=nextParams[1],i+=2;else if(nextParams[0]===2&&nextParams[3]!==void 0)currentStyle.fg=16777216|(nextParams[1]&255)<<16|(nextParams[2]&255)<<8|nextParams[3]&255,i+=4;break}case 39:currentStyle.fg=null;break;case 40:case 41:case 42:case 43:case 44:case 45:case 46:case 47:currentStyle.bg=code;break;case 48:{let nextParams=params.slice(i+1).map(Number);if(currentStyle.colonBg=void 0,nextParams[0]===5&&nextParams[1]!==void 0)currentStyle.bg=nextParams[1],i+=2;else if(nextParams[0]===2&&nextParams[3]!==void 0)currentStyle.bg=16777216|(nextParams[1]&255)<<16|(nextParams[2]&255)<<8|nextParams[3]&255,i+=4;break}case 49:currentStyle.bg=null;break;case 58:{let nextParams=params.slice(i+1).map(Number);if(nextParams[0]===5&&nextParams[1]!==void 0)currentStyle.underlineColor=nextParams[1],i+=2;else if(nextParams[0]===2&&nextParams[3]!==void 0)currentStyle.underlineColor=16777216|(nextParams[1]&255)<<16|(nextParams[2]&255)<<8|nextParams[3]&255,i+=4;break}case 59:currentStyle.underlineColor=null;break;case 90:case 91:case 92:case 93:case 94:case 95:case 96:case 97:currentStyle.fg=code;break;case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:currentStyle.bg=code;break;case BG_OVERRIDE_CODE:currentStyle.bgOverride=!0;break}}lastIndex=match.index+match[0].length}if(lastIndex<processText.length){let content=processText.slice(lastIndex);if(content.length>0)if(hyperlinkRanges.length>0){let segStart=0;for(let ci=0;ci<content.length;ci++){let hl=getHyperlinkAt(lastIndex+ci),prevHl=ci>0?getHyperlinkAt(lastIndex+ci-1):void 0;if(ci>0&&hl!==prevHl){let sub2=content.slice(segStart,ci);if(sub2.length>0){let seg={text:sub2,...currentStyle};if(prevHl)seg.hyperlink=prevHl;segments.push(seg)}segStart=ci}}let sub=content.slice(segStart);if(sub.length>0){let hl=getHyperlinkAt(lastIndex+segStart),seg={text:sub,...currentStyle};if(hl)seg.hyperlink=hl;segments.push(seg)}}else segments.push({text:content,...currentStyle})}return segments}function hasAnsi(text){return ANSI_TEST_REGEX.test(text)}function getFirstCodePoint(str){return str.codePointAt(0)??0}function isCJK(grapheme){let cp=getFirstCodePoint(grapheme);return CHAR_RANGES.isCJK(cp)||CHAR_RANGES.isJapaneseKana(cp)||CHAR_RANGES.isHangul(cp)}var segmenter,displayWidthCache,DEFAULT_TEXT_EMOJI_WIDE=!0,DEFAULT_TEXT_SIZING_ENABLED=!1,_scopedMeasurer=null,OSC8_RE,_defaultMeasurer,TEXT_PRESENTATION_EMOJI_REGEX,EMOJI_PRESENTATION_REGEX,RGI_EMOJI_REGEX,textPresentationEmojiCache,MAY_CONTAIN_TEXT_EMOJI,MAY_CONTAIN_PUA,ANSI_CSI_RE,ANSI_OSC_RE,ANSI_SINGLE_RE,ANSI_TEST_REGEX,CHAR_RANGES;var init_unicode=__esm(()=>{init_ansi2();init_buffer();init_text_sizing();segmenter=new Intl.Segmenter(void 0,{granularity:"grapheme"});displayWidthCache=new DisplayWidthCache(1e4);OSC8_RE=/\x1b\]8;;[^\x07\x1b]*(?:\x07|\x1b\\)/g;TEXT_PRESENTATION_EMOJI_REGEX=/^\p{Extended_Pictographic}$/u,EMOJI_PRESENTATION_REGEX=/^\p{Emoji_Presentation}$/u,RGI_EMOJI_REGEX=/^\p{RGI_Emoji}$/v,textPresentationEmojiCache=new Map;MAY_CONTAIN_TEXT_EMOJI=/[\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]/,MAY_CONTAIN_PUA=/[\uE000-\uF8FF]/;ANSI_CSI_RE=/^\x1b\[[0-9;:?]*[A-Za-z]/,ANSI_OSC_RE=/^\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/,ANSI_SINGLE_RE=/^\x1b[DME78(B]/;ANSI_TEST_REGEX=/\x1b(?:\[[0-9;:]*[A-Za-z]|\])|\x9b[\x30-\x3f]*[\x40-\x7e]|\x9d/;CHAR_RANGES={isBasicLatin:(cp)=>cp>=32&&cp<=127,isCJK:(cp)=>cp>=19968&&cp<=40959||cp>=13312&&cp<=19903||cp>=131072&&cp<=173791||cp>=63744&&cp<=64255||cp>=194560&&cp<=195103,isJapaneseKana:(cp)=>cp>=12352&&cp<=12447||cp>=12448&&cp<=12543,isHangul:(cp)=>cp>=44032&&cp<=55203||cp>=4352&&cp<=4607,isEmoji:(cp)=>cp>=128512&&cp<=128591||cp>=127744&&cp<=128511||cp>=128640&&cp<=128767||cp>=128768&&cp<=128895||cp>=129280&&cp<=129535||cp>=9728&&cp<=9983||cp>=9984&&cp<=10175}});function createEmptyCellChange(){return{x:0,y:0,cell:{char:" ",fg:null,bg:null,underlineColor:null,attrs:{},wide:!1,continuation:!1,hyperlink:void 0}}}function ensureDiffPoolCapacity(capacity){if(capacity<=diffPoolCapacity)return;for(let i=diffPoolCapacity;i<capacity;i++)diffPool.push(createEmptyCellChange());diffPoolCapacity=capacity}function writeCellChange(change,x,y,buffer){change.x=x,change.y=y,buffer.readCellInto(x,y,change.cell)}function writeEmptyCellChange(change,x,y){change.x=x,change.y=y;let cell=change.cell;cell.char=" ",cell.fg=null,cell.bg=null,cell.underlineColor=null;let attrs=cell.attrs;attrs.bold=void 0,attrs.dim=void 0,attrs.italic=void 0,attrs.underline=void 0,attrs.underlineStyle=void 0,attrs.blink=void 0,attrs.inverse=void 0,attrs.hidden=void 0,attrs.strikethrough=void 0,cell.wide=!1,cell.continuation=!1,cell.hyperlink=void 0}function diffBuffers(prev,next){let cells=Math.max(prev.width,next.width)*Math.max(prev.height,next.height),maxChanges=cells+(cells>>1);ensureDiffPoolCapacity(maxChanges);let changeCount=0,height=Math.min(prev.height,next.height),width=Math.min(prev.width,next.width),startRow=next.minDirtyRow===-1?0:next.minDirtyRow,endRow=next.maxDirtyRow===-1?-1:Math.min(next.maxDirtyRow,height-1);for(let y=startRow;y<=endRow;y++){if(!next.isRowDirty(y))continue;if(next.rowMetadataEquals(y,prev)&&next.rowCharsEquals(y,prev)&&next.rowExtrasEquals(y,prev))continue;for(let x=0;x<width;x++)if(!next.cellEquals(x,y,prev)){if(writeCellChange(diffPool[changeCount],x,y,next),changeCount++,x+1<width&&prev.isCellWide(x,y)&&!next.isCellWide(x,y))writeCellChange(diffPool[changeCount],x+1,y,next),changeCount++}}let widthGrew=next.width>prev.width;if(widthGrew)for(let y=0;y<next.height;y++)for(let x=prev.width;x<next.width;x++)writeCellChange(diffPool[changeCount],x,y,next),changeCount++;if(next.height>prev.height){let xEnd=widthGrew?prev.width:next.width;for(let y=prev.height;y<next.height;y++)for(let x=0;x<xEnd;x++)writeCellChange(diffPool[changeCount],x,y,next),changeCount++}if(prev.width>next.width)for(let y=0;y<height;y++)for(let x=next.width;x<prev.width;x++)writeEmptyCellChange(diffPool[changeCount],x,y),changeCount++;if(prev.height>next.height)for(let y=next.height;y<prev.height;y++)for(let x=0;x<prev.width;x++)writeEmptyCellChange(diffPool[changeCount],x,y),changeCount++;if(changeCount>maxChanges)throw Error(`diffBuffers: changeCount ${changeCount} exceeds pool capacity ${maxChanges} (prev ${prev.width}x${prev.height}, next ${next.width}x${next.height})`);return diffResult.pool=diffPool,diffResult.count=changeCount,diffResult}var diffPool,diffPoolCapacity=0,diffResult;var init_diff_buffers=__esm(()=>{diffPool=[];diffResult={pool:diffPool,count:0}});import{createLogger as createLogger2}from"loggily";function outputGraphemeWidth(g,ctx){return ctx.measurer?ctx.measurer.graphemeWidth(g):graphemeWidth(g)}function outputTextSizingEnabled(ctx){return ctx.measurer?ctx.measurer.textSizingEnabled:isTextSizingEnabled()}function createOutputPhase(caps,measurer){let ctx={caps:{underlineStyles:caps.underlineStyles??!0,underlineColor:caps.underlineColor??!0,colorLevel:caps.colorLevel??"truecolor"},measurer:measurer??null,sgrCache:new Map,transitionCache:new Map,mode:"fullscreen",termRows:void 0},inlineState=createInlineCursorState(),accState={accumulatedAnsi:"",accumulateWidth:0,accumulateHeight:0,accumulateFrameCount:0},tvState=createTerminalVerifyState(),pendingPromotion=null,fn=function(prev,next,mode="fullscreen",scrollbackOffset=0,termRows,cursorPos){if(ctx.mode=mode,ctx.termRows=termRows,pendingPromotion&&mode==="inline"){let promo=pendingPromotion;return pendingPromotion=null,handleScrollbackPromotion(inlineState,promo.frozenContent,promo.frozenLineCount,next,cursorPos,ctx)}return outputPhase(prev,next,mode,scrollbackOffset,termRows,cursorPos,inlineState,ctx,accState,tvState)};return fn.resetInlineState=()=>{Object.assign(inlineState,createInlineCursorState()),inlineState.forceFirstRender=!0,pendingPromotion=null},fn.getInlineCursorRow=()=>inlineState.prevCursorRow,fn.promoteScrollback=(frozenContent,frozenLineCount)=>{if(pendingPromotion)pendingPromotion.frozenContent+=frozenContent,pendingPromotion.frozenLineCount+=frozenLineCount;else pendingPromotion={frozenContent,frozenLineCount}},fn}function handleScrollbackPromotion(state,frozenContent,frozenLineCount,next,cursorPos,ctx){let{termRows}=ctx,output="";if(state.prevCursorRow>0)output+=`\x1B[${state.prevCursorRow}A`;output+="\r",output+=frozenContent;let nextContentLines=findLastContentLine(next)+1,maxOutputLines=termRows!=null?Math.min(nextContentLines,termRows):nextContentLines;output+=bufferToAnsi(next,ctx,maxOutputLines);let totalOnScreen=frozenLineCount+maxOutputLines,oldTotalLines=state.prevOutputLines,nextLastLine=totalOnScreen-1,terminalScroll=termRows!=null?Math.max(0,totalOnScreen-termRows):0,lastOccupied=Math.max(oldTotalLines-1-terminalScroll,0);if(lastOccupied>nextLastLine){for(let y=nextLastLine+1;y<=lastOccupied;y++)output+=`
20
- \r\x1B[K`;let up=lastOccupied-nextLastLine;if(up>0)output+=`\x1B[${up}A`}output+=inlineCursorSuffix(cursorPos??null,next,ctx);let startLine=0;if(termRows!=null&&nextContentLines>termRows)startLine=nextContentLines-termRows;if(state.prevBuffer=next,cursorPos?.visible){let visibleRow=cursorPos.y-startLine;state.prevCursorRow=visibleRow>=0&&visibleRow<maxOutputLines?visibleRow:maxOutputLines-1}else state.prevCursorRow=maxOutputLines-1;return state.prevOutputLines=maxOutputLines,output}function isStrictOutput(){if(typeof process>"u")return!1;let val=process.env.SILVERY_STRICT;return!!val&&val!=="0"&&val!=="false"}function isStrictAccumulate(){if(typeof process>"u")return!1;let val=process.env.SILVERY_STRICT_ACCUMULATE;return!!val&&val!=="0"&&val!=="false"}function strictTerminalBackends(){let val=(typeof process<"u"?process.env.SILVERY_STRICT_TERMINAL??"":"").toLowerCase().trim();if(!val)return[];if(val==="all")return["vt100","xterm","ghostty"];let backends=val.split(",").map((s)=>s.trim()).filter(Boolean),valid=new Set(["vt100","xterm","ghostty"]);for(let b of backends)if(!valid.has(b))log2.warn?.(`SILVERY_STRICT_TERMINAL: unknown backend '${b}', ignoring`);return backends.filter((b)=>valid.has(b))}function createTerminalVerifyState(){let allBackends=strictTerminalBackends();return{terminal:null,ghosttyTerminal:null,width:0,height:0,frameCount:0,backends:allBackends.filter((b)=>b!=="vt100"),hasVt100:allBackends.includes("vt100")}}function createInlineCursorState(){return{prevCursorRow:-1,prevOutputLines:0,prevBuffer:null,forceFirstRender:!1}}function updateInlineCursorRow(state,cursorPos,maxOutputLines,startLine){if(cursorPos?.visible){let visibleRow=cursorPos.y-startLine;state.prevCursorRow=visibleRow>=0&&visibleRow<maxOutputLines?visibleRow:maxOutputLines-1}else state.prevCursorRow=maxOutputLines-1;state.prevOutputLines=maxOutputLines}function wrapTextSizing(char,wide,ctx){if(!wide||!outputTextSizingEnabled(ctx))return char;return textSized(char,2)}function styleToKey(style2){let{fg,bg,attrs}=style2,key="";if(fg===null)key="n";else if(typeof fg==="number")key=`${fg}`;else key=`r${fg.r},${fg.g},${fg.b}`;if(key+="|",bg===null)key+="n";else if(typeof bg==="number")key+=`${bg}`;else key+=`r${bg.r},${bg.g},${bg.b}`;let attrBits=0;if(attrs.bold)attrBits|=1;if(attrs.dim)attrBits|=2;if(attrs.italic)attrBits|=4;if(attrs.underline)attrBits|=8;if(attrs.inverse)attrBits|=16;if(attrs.strikethrough)attrBits|=32;if(attrs.blink)attrBits|=64;if(attrs.hidden)attrBits|=128;if(key+=`|${attrBits}`,attrs.underlineStyle)key+=`|u${attrs.underlineStyle}`;let ul=style2.underlineColor;if(ul!==null&&ul!==void 0)if(typeof ul==="number")key+=`|l${ul}`;else key+=`|lr${ul.r},${ul.g},${ul.b}`;if(style2.hyperlink)key+=`|h${style2.hyperlink}`;return key}function cachedStyleToAnsi(style2,ctx){let key=styleToKey(style2),sgr=ctx.sgrCache.get(key);if(sgr!==void 0)return sgr;if(sgr=styleToAnsi(style2,ctx),ctx.sgrCache.set(key,sgr),ctx.sgrCache.size>1000)ctx.sgrCache.clear();return sgr}function styleTransition(oldStyle,newStyle,ctx){if(!oldStyle)return cachedStyleToAnsi(newStyle,ctx);if(styleEquals(oldStyle,newStyle))return"";let oldKey=styleToKey(oldStyle),newKey=styleToKey(newStyle),cacheKey=`${oldKey}\x00${newKey}`,cached=ctx.transitionCache.get(cacheKey);if(cached!==void 0)return cached;let codes=[],oa=oldStyle.attrs,na=newStyle.attrs,boldChanged=Boolean(oa.bold)!==Boolean(na.bold),dimChanged=Boolean(oa.dim)!==Boolean(na.dim);if(boldChanged||dimChanged){let boldOff=boldChanged&&!na.bold,dimOff=dimChanged&&!na.dim;if(boldOff||dimOff){if(codes.push("22"),na.bold)codes.push("1");if(na.dim)codes.push("2")}else{if(boldChanged&&na.bold)codes.push("1");if(dimChanged&&na.dim)codes.push("2")}}if(Boolean(oa.italic)!==Boolean(na.italic))codes.push(na.italic?"3":"23");let oldUl=Boolean(oa.underline),newUl=Boolean(na.underline),oldUlStyle=oa.underlineStyle??!1,newUlStyle=na.underlineStyle??!1;if(oldUl!==newUl||oldUlStyle!==newUlStyle)if(!ctx.caps.underlineStyles)codes.push(newUl||na.underlineStyle?"4":"24");else{let sgrSub=underlineStyleToSgr(na.underlineStyle);if(sgrSub!==null&&sgrSub!==0)codes.push(`4:${sgrSub}`);else if(newUl)codes.push("4");else codes.push("24")}if(Boolean(oa.inverse)!==Boolean(na.inverse))codes.push(na.inverse?"7":"27");if(Boolean(oa.hidden)!==Boolean(na.hidden))codes.push(na.hidden?"8":"28");if(Boolean(oa.strikethrough)!==Boolean(na.strikethrough))codes.push(na.strikethrough?"9":"29");if(Boolean(oa.blink)!==Boolean(na.blink))codes.push(na.blink?"5":"25");if(!colorEquals(oldStyle.fg,newStyle.fg))if(newStyle.fg===null)codes.push("39");else codes.push(fgColorCode(newStyle.fg));if(!colorEquals(oldStyle.bg,newStyle.bg))if(newStyle.bg===null)codes.push("49");else codes.push(bgColorCode(newStyle.bg));if(ctx.caps.underlineColor&&!colorEquals(oldStyle.underlineColor,newStyle.underlineColor))if(newStyle.underlineColor===null||newStyle.underlineColor===void 0)codes.push("59");else if(typeof newStyle.underlineColor==="number")codes.push(`58;5;${newStyle.underlineColor}`);else codes.push(`58;2;${newStyle.underlineColor.r};${newStyle.underlineColor.g};${newStyle.underlineColor.b}`);let result;if(codes.length===0)result=cachedStyleToAnsi(newStyle,ctx);else result=`\x1B[${codes.join(";")}m`;if(ctx.transitionCache.set(cacheKey,result),ctx.transitionCache.size>1000)ctx.transitionCache.clear();return result}function underlineStyleToSgr(style2){switch(style2){case!1:return 0;case"single":return 1;case"double":return 2;case"curly":return 3;case"dotted":return 4;case"dashed":return 5;default:return null}}function outputPhase(prev,next,mode="fullscreen",scrollbackOffset=0,termRows,cursorPos,_inlineState,_ctx,_accState,_tvState){let inlineState=_inlineState??createInlineCursorState(),ctx=_ctx??defaultContext,accState=_accState??defaultAccState;ctx.mode=mode,ctx.termRows=termRows;let tvState=_tvState??defaultTerminalVerifyState;if(mode==="inline"&&inlineState.forceFirstRender)inlineState.forceFirstRender=!1,prev=null;if(!prev){let fullRenderAcc=globalThis.__silvery_bench_output_detail;if(fullRenderAcc)fullRenderAcc.fullRenderCalls=(fullRenderAcc.fullRenderCalls??0)+1,fullRenderAcc.fullRenderCells=(fullRenderAcc.fullRenderCells??0)+next.width*next.height;if(mode==="inline"&&inlineState.prevBuffer&&inlineState.prevCursorRow>=0){let stored=inlineState.prevBuffer;if(stored.width===next.width&&stored.height===next.height)return inlineState.prevBuffer=next,inlineIncrementalRender(inlineState,stored,next,scrollbackOffset,cursorPos,ctx,tvState)}let tFullStart=performance.now(),firstOutput=bufferToAnsi(next,ctx,termRows),tFullEnd=performance.now();if(fullRenderAcc)fullRenderAcc.fullRenderMs=(fullRenderAcc.fullRenderMs??0)+(tFullEnd-tFullStart),fullRenderAcc.fullRenderBytes=(fullRenderAcc.fullRenderBytes??0)+firstOutput.length;if(mode==="inline"){let firstContentLines=findLastContentLine(next)+1,firstMaxOutput=termRows!=null?Math.min(firstContentLines,termRows):firstContentLines,firstStartLine=0;if(termRows!=null&&firstContentLines>termRows)firstStartLine=firstContentLines-termRows;let prefix="";if(inlineState.prevCursorRow>=0){let clearDistance=termRows??Math.max(inlineState.prevCursorRow,inlineState.prevOutputLines-1);if(clearDistance>0)prefix+=`\x1B[${clearDistance}A`;prefix+="\r\x1B[J"}return inlineState.prevBuffer=next,updateInlineCursorRow(inlineState,cursorPos,firstMaxOutput,firstStartLine),prefix+firstOutput+inlineCursorSuffix(cursorPos??null,next,ctx)}if(isStrictAccumulate())accState.accumulatedAnsi=firstOutput,accState.accumulateWidth=next.width,accState.accumulateHeight=next.height,accState.accumulateFrameCount=0;if(tvState.backends.length>0)initTerminalVerifyState(tvState,next.width,next.height,firstOutput);if(CAPTURE_RAW)try{let fs=__require("fs");_captureRawFrameCount=0,fs.writeFileSync("/tmp/silvery-raw.ansi",firstOutput),fs.writeFileSync("/tmp/silvery-raw-frames.jsonl",JSON.stringify({frame:0,type:"full",bytes:firstOutput.length,width:next.width,height:next.height})+`
21
- `)}catch{}return firstOutput}if(mode==="inline")return inlineState.prevBuffer=next,inlineIncrementalRender(inlineState,prev,next,scrollbackOffset,cursorPos,ctx,tvState);if(FULL_RENDER)return bufferToAnsi(next,ctx,termRows);if(prev.width!==next.width||prev.height!==next.height)return bufferToAnsi(next,ctx,termRows);let tDiff0=performance.now(),{pool,count:rawCount}=diffBuffers(prev,next),tDiff1=performance.now(),count=rawCount;if(termRows!=null){let writeIdx=0;for(let i=0;i<rawCount;i++)if(pool[i].y<termRows)pool[writeIdx++]=pool[i];count=writeIdx}if(DEBUG_OUTPUT){log2.error?.(`diffBuffers: ${count} changes${rawCount!==count?` (${rawCount-count} clamped beyond termRows)`:""}`);let debugLimit=Math.min(count,10);for(let i=0;i<debugLimit;i++){let change=pool[i];log2.error?.(` (${change.x},${change.y}): "${change.cell.char}"`)}if(count>10)log2.error?.(` ... and ${count-10} more`)}if(count===0){let acc=globalThis.__silvery_bench_output_detail;if(acc)acc.diffMs+=tDiff1-tDiff0,acc.calls+=1;return""}let tAnsi0=performance.now(),incrOutput=changesToAnsi(pool,count,ctx,next).output,tAnsi1=performance.now(),outputDetailAcc=globalThis.__silvery_bench_output_detail;if(outputDetailAcc){outputDetailAcc.diffMs+=tDiff1-tDiff0,outputDetailAcc.ansiMs+=tAnsi1-tAnsi0,outputDetailAcc.calls+=1,outputDetailAcc.totalChanges+=count;let dirtyRowCount=0,minRow=next.minDirtyRow,maxRow=next.maxDirtyRow;if(minRow>=0){for(let r=minRow;r<=maxRow;r++)if(next.isRowDirty(r))dirtyRowCount++}outputDetailAcc.dirtyRows+=dirtyRowCount,outputDetailAcc.outputBytes+=incrOutput.length}if(DEBUG_OUTPUT||isStrictAccumulate()){let bytes=Buffer.byteLength(incrOutput);try{__require("fs").appendFileSync("/tmp/silvery-sizes.log",`changesToAnsi: ${count} changes, ${bytes} bytes
22
- `)}catch{}}if(DEBUG_CAPTURE){_debugFrameCount++;try{let fs=__require("fs"),freshOutput=bufferToAnsi(next,ctx),freshPrev=prev?bufferToAnsi(prev,ctx):"",w=Math.max(prev?.width??next.width,next.width),h=Math.max(prev?.height??next.height,next.height),screenIncr=replayAnsiWithStyles(w,h,freshPrev+incrOutput,ctx),screenFresh=replayAnsiWithStyles(w,h,freshOutput,ctx),mismatchInfo="";for(let y=0;y<h&&!mismatchInfo;y++)for(let x=0;x<w&&!mismatchInfo;x++){let ic=screenIncr[y]?.[x],fc=screenFresh[y]?.[x];if(ic&&fc&&(ic.char!==fc.char||!sgrColorEquals(ic.fg,fc.fg)||!sgrColorEquals(ic.bg,fc.bg))){mismatchInfo=`MISMATCH at (${x},${y}): incr='${ic.char}' fresh='${fc.char}' incrFg=${formatColor(ic.fg)} freshFg=${formatColor(fc.fg)} incrBg=${formatColor(ic.bg)} freshBg=${formatColor(fc.bg)}`;let incrRow=screenIncr[y].map((c)=>c.char).join(""),freshRow=screenFresh[y].map((c)=>c.char).join("");mismatchInfo+=`
23
- incr row ${y}: ${incrRow.slice(Math.max(0,x-20),x+40)}
24
- fresh row ${y}: ${freshRow.slice(Math.max(0,x-20),x+40)}`}}let status=mismatchInfo||"MATCH";if(fs.appendFileSync("/tmp/silvery-capture.log",`Frame ${_debugFrameCount}: ${count} changes, ${status}
25
- `),mismatchInfo)fs.writeFileSync(`/tmp/silvery-incr-${_debugFrameCount}.ansi`,freshPrev+incrOutput),fs.writeFileSync(`/tmp/silvery-fresh-${_debugFrameCount}.ansi`,freshOutput),fs.appendFileSync("/tmp/silvery-capture.log",` Saved ANSI files: /tmp/silvery-incr-${_debugFrameCount}.ansi and /tmp/silvery-fresh-${_debugFrameCount}.ansi
26
- `)}catch(e){try{__require("fs").appendFileSync("/tmp/silvery-capture.log",`Frame ${_debugFrameCount}: ERROR ${e}
27
- `)}catch{}}}if(isStrictOutput()||tvState.hasVt100)verifyOutputEquivalence(prev,next,incrOutput,ctx);if(isStrictAccumulate())accState.accumulatedAnsi+=incrOutput,accState.accumulateFrameCount++,verifyAccumulatedOutput(next,ctx,accState);if(tvState.backends.length>0&&(tvState.terminal||tvState.ghosttyTerminal))tvState.frameCount++,verifyTerminalEquivalence(tvState,incrOutput,next,ctx);if(CAPTURE_RAW)try{let fs=__require("fs");_captureRawFrameCount++,fs.appendFileSync("/tmp/silvery-raw.ansi",incrOutput);let freshOutput=bufferToAnsi(next,ctx);fs.writeFileSync(`/tmp/silvery-raw-fresh-${_captureRawFrameCount}.ansi`,freshOutput),fs.appendFileSync("/tmp/silvery-raw-frames.jsonl",JSON.stringify({frame:_captureRawFrameCount,type:"incremental",changes:count,bytes:incrOutput.length,width:next.width,height:next.height})+`
28
- `)}catch{}return incrOutput}function lineHasContent(buffer,y){for(let x=0;x<buffer.width;x++){let ch=buffer.getCellChar(x,y);if(ch!==" "&&ch!=="")return!0;if(buffer.getCellBg(x,y)!==null)return!0;if(buffer.getCellAttrs(x,y)&VISIBLE_SPACE_ATTR_MASK)return!0}return!1}function findLastContentLine(buffer){for(let y=buffer.height-1;y>=0;y--)if(lineHasContent(buffer,y))return y;return 0}function inlineCursorSuffix(cursorPos,buffer,ctx){let{termRows}=ctx;if(!cursorPos?.visible)return"\x1B[?25l";let lastContentLine=findLastContentLine(buffer),maxLine=lastContentLine,startLine=0,maxOutputLines=termRows!=null?Math.min(lastContentLine+1,termRows):lastContentLine+1;if(termRows!=null&&maxLine>=termRows)startLine=maxLine-termRows+1;let visibleRow=cursorPos.y-startLine;if(visibleRow<0||visibleRow>=maxOutputLines)return"\x1B[?25l";let rowDelta=maxOutputLines-1-visibleRow,suffix="";if(rowDelta>0)suffix+=`\x1B[${rowDelta}A`;if(suffix+="\r",cursorPos.x>0)suffix+=`\x1B[${cursorPos.x}C`;return suffix+="\x1B[?25h",suffix}function inlineIncrementalRender(state,prev,next,scrollbackOffset,cursorPos,ctx=defaultContext,tvState){let{termRows}=ctx;if(scrollbackOffset>0||prev.width!==next.width||prev.height!==next.height||state.prevCursorRow<0)return inlineFullRender(state,prev,next,scrollbackOffset,cursorPos,ctx);let nextContentLines=findLastContentLine(next)+1,prevContentLines=findLastContentLine(prev)+1,prevMaxOutputLines=termRows!=null?Math.min(prevContentLines,termRows):prevContentLines,maxOutputLines=termRows!=null?Math.min(nextContentLines,termRows):nextContentLines,prevStartLine=0;if(termRows!=null&&prevContentLines>termRows)prevStartLine=prevContentLines-termRows;let startLine=0;if(termRows!=null&&nextContentLines>termRows)startLine=nextContentLines-termRows;if(startLine!==prevStartLine)return inlineFullRender(state,prev,next,scrollbackOffset,cursorPos,ctx);let{pool,count}=diffBuffers(prev,next);if(count===0&&nextContentLines===prevContentLines){let suffix=inlineCursorSuffix(cursorPos??null,next,ctx);return updateInlineCursorRow(state,cursorPos,maxOutputLines,startLine),suffix}let output="";if(state.prevCursorRow>0)output+=`\x1B[${state.prevCursorRow}A`;output+="\r",output+="\x1B[?25l";let effectiveOutputLines=Math.max(prevMaxOutputLines,maxOutputLines),changes=changesToAnsi(pool,count,ctx,next,startLine,effectiveOutputLines);output+=changes.output;let finalY=changes.finalY,prevBottomRow=prevMaxOutputLines-1,bottomRow=maxOutputLines-1;if(maxOutputLines>prevMaxOutputLines){let fromRow=finalY>=0?finalY:0;if(fromRow>=bottomRow);else if(fromRow>=prevBottomRow){let remainingRows=bottomRow-fromRow;for(let i=0;i<remainingRows;i++)output+=`\r
29
- `}else{if(fromRow<prevBottomRow){let dy=prevBottomRow-fromRow;output+=dy===1?`\r
30
- `:`\r\x1B[${dy}B`}let newRows=bottomRow-prevBottomRow;for(let i=0;i<newRows;i++)output+=`\r
31
- `}}else if(maxOutputLines<prevMaxOutputLines){let fromRow=finalY>=0?finalY:0;if(fromRow<bottomRow){let dy=bottomRow-fromRow;output+=dy===1?`\r
32
- `:`\r\x1B[${dy}B`}else if(fromRow>bottomRow)output+=`\x1B[${fromRow-bottomRow}A`;let orphanCount=prevMaxOutputLines-maxOutputLines;for(let y=0;y<orphanCount;y++)output+=`
33
- \r\x1B[K`;if(orphanCount>0)output+=`\x1B[${orphanCount}A`}else if(finalY>=0&&finalY<bottomRow){let dy=bottomRow-finalY;output+=dy===1?`\r
34
- `:`\r\x1B[${dy}B`}if(output+=inlineCursorSuffix(cursorPos??null,next,ctx),isStrictOutput()||tvState?.hasVt100){let savedMode=ctx.mode;ctx.mode="fullscreen";let fsIncrOutput=changesToAnsi(pool,count,ctx,next).output;verifyOutputEquivalence(prev,next,fsIncrOutput,ctx),ctx.mode=savedMode}return updateInlineCursorRow(state,cursorPos,maxOutputLines,startLine),output}function inlineFullRender(state,prev,next,scrollbackOffset,cursorPos,ctx=defaultContext){let{termRows}=ctx,nextContentLines=findLastContentLine(next)+1,prevOutputLines,cursorRowInRegion;if(state.prevCursorRow>=0)prevOutputLines=state.prevOutputLines,cursorRowInRegion=state.prevCursorRow;else{let prevContentLines=findLastContentLine(prev)+1;prevOutputLines=termRows!=null?Math.min(prevContentLines,termRows):prevContentLines,cursorRowInRegion=prevOutputLines-1}let rawCursorOffset=cursorRowInRegion+scrollbackOffset,cursorOffset=termRows!=null&&!isStrictOutput()?Math.min(rawCursorOffset,termRows-1):rawCursorOffset,maxOutputLines=termRows!=null?Math.min(nextContentLines,termRows):nextContentLines;if(scrollbackOffset===0){let{count}=diffBuffers(prev,next);if(count===0)return""}let prefix="";if(cursorOffset>0)prefix=`\x1B[${cursorOffset}A\r`;let output=prefix+bufferToAnsi(next,ctx,maxOutputLines),terminalScroll=termRows!=null?Math.max(0,rawCursorOffset-(termRows-1)):0,lastOccupiedLine=Math.max(prevOutputLines-1-terminalScroll,0),nextLastLine=maxOutputLines-1;if(lastOccupiedLine>nextLastLine){for(let y=nextLastLine+1;y<=lastOccupiedLine;y++)output+=`
35
- \r\x1B[K`;let up=lastOccupiedLine-nextLastLine;if(up>0)output+=`\x1B[${up}A`}output+=inlineCursorSuffix(cursorPos??null,next,ctx);let startLine=0;if(termRows!=null&&nextContentLines>termRows)startLine=nextContentLines-termRows;return updateInlineCursorRow(state,cursorPos,maxOutputLines,startLine),output}function bufferToAnsi(buffer,ctx=defaultContext,maxRows){let{mode}=ctx,output="",currentStyle=null,currentHyperlink,maxLine=mode==="inline"?findLastContentLine(buffer):buffer.height-1,startLine=0;if(maxRows!=null&&maxLine>=maxRows)if(mode==="fullscreen")maxLine=maxRows-1;else startLine=maxLine-maxRows+1;if(mode==="fullscreen")output+="\x1B[H";else output+="\x1B[?25l";let cell=createMutableCell(),cellStyle={fg:null,bg:null,underlineColor:null,attrs:{}};for(let y=startLine;y<=maxLine;y++){if(mode==="inline")output+="\r";else if(y>startLine)output+=`\x1B[${y+1};1H`;for(let x=0;x<buffer.width;x++){buffer.readCellInto(x,y,cell);let cellHyperlink=cell.hyperlink;if(cellHyperlink!==currentHyperlink){if(currentHyperlink)output+="\x1B]8;;\x1B\\";if(cellHyperlink)output+=`\x1B]8;;${cellHyperlink}\x1B\\`;currentHyperlink=cellHyperlink}if(cellStyle.fg=cell.fg,cellStyle.bg=cell.bg,cellStyle.underlineColor=cell.underlineColor,cellStyle.attrs=cell.attrs,!styleEquals(currentStyle,cellStyle)){let saved={fg:cell.fg,bg:cell.bg,underlineColor:cell.underlineColor,attrs:{...cell.attrs}};output+=styleTransition(currentStyle,saved,ctx),currentStyle=saved}let char=cell.char||" ";if(output+=wrapTextSizing(char,cell.wide,ctx),cell.wide)if(x++,mode==="fullscreen")output+=`\x1B[${y-startLine+1};${x+2}H`;else{if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;let nextCol=x+1;if(output+="\r",nextCol>0)output+=nextCol===1?"\x1B[C":`\x1B[${nextCol}C`}}if(currentHyperlink)output+="\x1B]8;;\x1B\\",currentHyperlink=void 0;if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;if(y<maxLine){if(mode==="inline")output+=`\r
36
- `}}if(currentHyperlink)output+="\x1B]8;;\x1B\\";return output+="\x1B[0m",output}function sortPoolByPosition(pool,count){for(let i=1;i<count;i++){let item=pool[i],iy=item.y,ix=item.x,j=i-1;while(j>=0&&(pool[j].y>iy||pool[j].y===iy&&pool[j].x>ix))pool[j+1]=pool[j],j--;pool[j+1]=item}}function changesToAnsi(pool,count,ctx=defaultContext,buffer,startLine=0,maxOutputLines=1/0){let{mode}=ctx;if(count===0)return{output:"",finalY:-1};sortPoolByPosition(pool,count);let output="",currentStyle=null,currentHyperlink,isInline=mode==="inline",endLine=startLine+maxOutputLines,finalY=-1,cursorX=-1,cursorY=-1,prevY=-1,lastEmittedX=-1,lastEmittedY=-1;for(let i=0;i<count;i++){let change=pool[i],x=change.x,y=change.y,cell=change.cell;if(isInline&&(y<startLine||y>=endLine))continue;if(cell.continuation){if(lastEmittedX===x-1&&lastEmittedY===y)continue;if(buffer&&x>0){if(x=x-1,buffer.readCellInto(x,y,wideCharLookupCell),cell=wideCharLookupCell,cell.continuation||!cell.wide)continue}else continue}let renderY=isInline?y-startLine:y;if(y!==prevY&&currentHyperlink)output+="\x1B]8;;\x1B\\",currentHyperlink=void 0;if(prevY=y,renderY!==cursorY||x!==cursorX)if(cursorY>=0&&renderY===cursorY+1&&x===0){if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;output+=`\r
37
- `}else if(cursorY>=0&&renderY===cursorY&&x>cursorX){if(currentStyle&&currentStyle.bg!==null)output+="\x1B[0m",currentStyle=null;let dx=x-cursorX;output+=dx===1?"\x1B[C":`\x1B[${dx}C`}else if(cursorY>=0&&renderY>cursorY&&x===0){let dy=renderY-cursorY;if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;output+=dy===1?`\r
38
- `:`\r\x1B[${dy}B`}else if(isInline){if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;let fromRow=cursorY>=0?cursorY:0;if(renderY>fromRow)output+=`\x1B[${renderY-fromRow}B\r`;else if(renderY<fromRow)output+=`\x1B[${fromRow-renderY}A\r`;else output+="\r";if(x>0)output+=x===1?"\x1B[C":`\x1B[${x}C`}else output+=`\x1B[${renderY+1};${x+1}H`;let cellHyperlink=cell.hyperlink;if(cellHyperlink!==currentHyperlink){if(currentHyperlink)output+="\x1B]8;;\x1B\\";if(cellHyperlink)output+=`\x1B]8;;${cellHyperlink}\x1B\\`;currentHyperlink=cellHyperlink}if(reusableCellStyle.fg=cell.fg,reusableCellStyle.bg=cell.bg,reusableCellStyle.underlineColor=cell.underlineColor,reusableCellStyle.attrs=cell.attrs,!styleEquals(currentStyle,reusableCellStyle)){let prevStyle=currentStyle;currentStyle={fg:cell.fg,bg:cell.bg,underlineColor:cell.underlineColor,attrs:{...cell.attrs}},output+=styleTransition(prevStyle,currentStyle,ctx)}let char=cell.char||" ";if(output+=wrapTextSizing(char,cell.wide,ctx),cursorX=x+(cell.wide?2:1),cursorY=renderY,lastEmittedX=x,lastEmittedY=y,cell.wide)if(isInline){if(currentStyle&&currentStyle.bg!==null)output+="\x1B[0m",currentStyle=null;if(output+="\r",cursorX>0)output+=cursorX===1?"\x1B[C":`\x1B[${cursorX}C`}else output+=`\x1B[${cursorY+1};${cursorX+1}H`}if(finalY=cursorY,currentHyperlink)output+="\x1B]8;;\x1B\\";if(currentStyle)output+="\x1B[0m";return{output,finalY}}function styleToAnsi(style2,ctx=defaultContext){let{fg,bg}=style2,codes=[];if(fg!==null)codes.push(fgColorCode(fg));if(bg!==null&&!isDefaultBg(bg))codes.push(bgColorCode(bg));if(style2.attrs.bold)codes.push("1");if(style2.attrs.dim)codes.push("2");if(style2.attrs.italic)codes.push("3");if(!ctx.caps.underlineStyles){if(style2.attrs.underline||style2.attrs.underlineStyle)codes.push("4")}else{let underlineStyle=style2.attrs.underlineStyle,sgrSubparam=underlineStyleToSgr(underlineStyle);if(sgrSubparam!==null&&sgrSubparam!==0)codes.push(`4:${sgrSubparam}`);else if(style2.attrs.underline)codes.push("4")}if(style2.attrs.blink)codes.push("5");if(style2.attrs.inverse)codes.push("7");if(style2.attrs.hidden)codes.push("8");if(style2.attrs.strikethrough)codes.push("9");if(ctx.caps.underlineColor&&style2.underlineColor!==null&&style2.underlineColor!==void 0)if(typeof style2.underlineColor==="number")codes.push(`58;5;${style2.underlineColor}`);else codes.push(`58;2;${style2.underlineColor.r};${style2.underlineColor.g};${style2.underlineColor.b}`);if(codes.length===0)return"";return`\x1B[${codes.join(";")}m`}function createDefaultSgr(){return{fg:null,bg:null,bold:!1,dim:!1,italic:!1,underline:!1,blink:!1,inverse:!1,hidden:!1,strikethrough:!1}}function createDefaultStyledCell(){return{char:" ",fg:null,bg:null,bold:!1,dim:!1,italic:!1,underline:!1,blink:!1,inverse:!1,hidden:!1,strikethrough:!1}}function applySgrParams(params,sgr){if(params===""||params==="0"){sgr.fg=null,sgr.bg=null,sgr.bold=!1,sgr.dim=!1,sgr.italic=!1,sgr.underline=!1,sgr.blink=!1,sgr.inverse=!1,sgr.hidden=!1,sgr.strikethrough=!1;return}let parts=params.split(";"),i=0;while(i<parts.length){let code=parts[i],colonIdx=code.indexOf(":");if(colonIdx>=0){if(parseInt(code.substring(0,colonIdx))===4){let sub=parseInt(code.substring(colonIdx+1));sgr.underline=sub>0}i++;continue}let n=parseInt(code);if(n===0)sgr.fg=null,sgr.bg=null,sgr.bold=!1,sgr.dim=!1,sgr.italic=!1,sgr.underline=!1,sgr.blink=!1,sgr.inverse=!1,sgr.hidden=!1,sgr.strikethrough=!1;else if(n===1)sgr.bold=!0;else if(n===2)sgr.dim=!0;else if(n===3)sgr.italic=!0;else if(n===4)sgr.underline=!0;else if(n===5||n===6)sgr.blink=!0;else if(n===7)sgr.inverse=!0;else if(n===8)sgr.hidden=!0;else if(n===9)sgr.strikethrough=!0;else if(n===22)sgr.bold=!1,sgr.dim=!1;else if(n===23)sgr.italic=!1;else if(n===24)sgr.underline=!1;else if(n===25)sgr.blink=!1;else if(n===27)sgr.inverse=!1;else if(n===28)sgr.hidden=!1;else if(n===29)sgr.strikethrough=!1;else if(n>=30&&n<=37)sgr.fg=n-30;else if(n===38){if(i+1<parts.length&&parts[i+1]==="5"&&i+2<parts.length)sgr.fg=parseInt(parts[i+2]),i+=2;else if(i+1<parts.length&&parts[i+1]==="2"&&i+4<parts.length)sgr.fg={r:parseInt(parts[i+2]),g:parseInt(parts[i+3]),b:parseInt(parts[i+4])},i+=4}else if(n===39)sgr.fg=null;else if(n>=40&&n<=47)sgr.bg=n-40;else if(n===48){if(i+1<parts.length&&parts[i+1]==="5"&&i+2<parts.length)sgr.bg=parseInt(parts[i+2]),i+=2;else if(i+1<parts.length&&parts[i+1]==="2"&&i+4<parts.length)sgr.bg={r:parseInt(parts[i+2]),g:parseInt(parts[i+3]),b:parseInt(parts[i+4])},i+=4}else if(n===49)sgr.bg=null;else if(n>=90&&n<=97)sgr.fg=n-90+8;else if(n>=100&&n<=107)sgr.bg=n-100+8;i++}}function replayAnsiWithStyles(width,height,ansi,ctx=defaultContext){let screen=Array.from({length:height},()=>Array.from({length:width},()=>createDefaultStyledCell())),cx=0,cy=0,sgr=createDefaultSgr(),i=0;while(i<ansi.length)if(ansi[i]==="\x1B")if(ansi[i+1]==="["){i+=2;let params="";while(i<ansi.length&&(ansi[i]>="0"&&ansi[i]<="9"||ansi[i]===";"||ansi[i]==="?"||ansi[i]===":"))params+=ansi[i],i++;let cmd=ansi[i];if(i++,cmd==="H")if(params==="")cx=0,cy=0;else{let cmdParts=params.split(";");cy=Math.min(height-1,Math.max(0,(parseInt(cmdParts[0])||1)-1)),cx=Math.min(width-1,Math.max(0,(parseInt(cmdParts[1])||1)-1))}else if(cmd==="K"){if(cy>=height)continue;for(let x=cx;x<width;x++){let cell=screen[cy][x];cell.char=" ",cell.fg=null,cell.bg=sgr.bg,cell.bold=!1,cell.dim=!1,cell.italic=!1,cell.underline=!1,cell.blink=!1,cell.inverse=!1,cell.hidden=!1,cell.strikethrough=!1}}else if(cmd==="A")cy=Math.max(0,cy-(parseInt(params)||1));else if(cmd==="B")cy=Math.min(height-1,cy+(parseInt(params)||1));else if(cmd==="C")cx=Math.min(width-1,cx+(parseInt(params)||1));else if(cmd==="D")cx=Math.max(0,cx-(parseInt(params)||1));else if(cmd==="G")cx=Math.max(0,(parseInt(params)||1)-1);else if(cmd==="J"){if(params==="2")for(let y=0;y<height;y++)for(let x=0;x<width;x++)screen[y][x]=createDefaultStyledCell()}else if(cmd==="m")applySgrParams(params,sgr)}else if(ansi[i+1]==="]"){i+=2;let oscPayload="";while(i<ansi.length){if(ansi[i]==="\x1B"&&ansi[i+1]==="\\"){i+=2;break}if(ansi[i]==="\x07"){i++;break}oscPayload+=ansi[i],i++}if(oscPayload.startsWith("66;")){let semiIdx=oscPayload.indexOf(";",3);if(semiIdx!==-1){let text=oscPayload.slice(semiIdx+1),widthParam=oscPayload.slice(3,semiIdx),declaredWidth=widthParam.startsWith("w=")?parseInt(widthParam.slice(2))||1:1;if(cy<height&&cx<width){let cell=screen[cy][cx];if(cell.char=text,cell.fg=sgr.fg,cell.bg=sgr.bg,cell.bold=sgr.bold,cell.dim=sgr.dim,cell.italic=sgr.italic,cell.underline=sgr.underline,cell.blink=sgr.blink,cell.inverse=sgr.inverse,cell.hidden=sgr.hidden,cell.strikethrough=sgr.strikethrough,declaredWidth>1&&cx+1<width){let cont=screen[cy][cx+1];cont.char=" ",cont.fg=null,cont.bg=sgr.bg,cont.bold=!1,cont.dim=!1,cont.italic=!1,cont.underline=!1,cont.blink=!1,cont.inverse=!1,cont.hidden=!1,cont.strikethrough=!1}cx+=declaredWidth}}}}else if(ansi[i+1]===">"){i+=2;while(i<ansi.length&&ansi[i]!=="\x1B")i++}else i+=2;else if(ansi[i]==="\r")cx=0,i++;else if(ansi[i]===`
39
- `)cy=Math.min(height-1,cy+1),i++;else{let cp=ansi.codePointAt(i),cpLen=cp>65535?2:1,grapheme=String.fromCodePoint(cp),j=i+cpLen,prevWasZwj=!1;while(j<ansi.length){let nextCp=ansi.codePointAt(j);if(!(prevWasZwj||nextCp>=768&&nextCp<=879||nextCp>=8400&&nextCp<=8447||nextCp>=65024&&nextCp<=65039||nextCp===65038||nextCp===65039||nextCp===8205||nextCp>=917760&&nextCp<=917999||nextCp>=127995&&nextCp<=127999||cp>=127462&&cp<=127487&&nextCp>=127462&&nextCp<=127487))break;prevWasZwj=nextCp===8205;let nextLen=nextCp>65535?2:1;grapheme+=String.fromCodePoint(nextCp),j+=nextLen}if(cy<height&&cx<width){let charWidth=outputGraphemeWidth(grapheme,ctx)||1,cell=screen[cy][cx];if(cell.char=grapheme,cell.fg=sgr.fg,cell.bg=sgr.bg,cell.bold=sgr.bold,cell.dim=sgr.dim,cell.italic=sgr.italic,cell.underline=sgr.underline,cell.blink=sgr.blink,cell.inverse=sgr.inverse,cell.hidden=sgr.hidden,cell.strikethrough=sgr.strikethrough,charWidth>1&&cx+1<width){let cont=screen[cy][cx+1];cont.char=" ",cont.fg=null,cont.bg=sgr.bg,cont.bold=!1,cont.dim=!1,cont.italic=!1,cont.underline=!1,cont.blink=!1,cont.inverse=!1,cont.hidden=!1,cont.strikethrough=!1}cx+=charWidth}i=j}return screen}function formatColor(c){if(c===null)return"default";if(typeof c==="number")return`${c}`;return`rgb(${c.r},${c.g},${c.b})`}function captureStrictFailureArtifacts(opts){try{let fs=__require("fs"),path=__require("path"),dir=`/tmp/silvery-strict-failure-${Date.now()}`;fs.mkdirSync(dir,{recursive:!0});let meta={source:opts.source,timestamp:new Date().toISOString(),frameCount:opts.frameCount,prevSize:opts.prev?{width:opts.prev.width,height:opts.prev.height}:null,nextSize:opts.next?{width:opts.next.width,height:opts.next.height}:null,incrOutputLength:opts.incrOutput?.length,freshOutputLength:opts.freshOutput?.length,testName:globalThis.__vitest_worker__?.current?.name};if(fs.writeFileSync(path.join(dir,"meta.json"),JSON.stringify(meta,null,2)),fs.writeFileSync(path.join(dir,"error.txt"),opts.errorMessage),opts.incrOutput)fs.writeFileSync(path.join(dir,"incremental.ansi"),opts.incrOutput);if(opts.freshOutput)fs.writeFileSync(path.join(dir,"fresh.ansi"),opts.freshOutput);if(opts.prev){let rows=[];for(let y=0;y<opts.prev.height;y++){let row="";for(let x=0;x<opts.prev.width;x++){let cell=opts.prev.getCell(x,y);row+=cell.char||" "}rows.push(row.trimEnd())}fs.writeFileSync(path.join(dir,"prev-buffer.txt"),rows.join(`
18
+ `);return _lines},cell(col,row){if(col<0||col>=width||row<0||row>=height)return EMPTY_FRAME_CELL;return cellToFrameCell(cellData[row*width+col])},containsText(text){return frame.text.includes(text)}};return frame}var DEFAULT_BG,ATTR_BOLD=65536,ATTR_DIM=131072,ATTR_ITALIC=262144,ATTR_BLINK=524288,ATTR_INVERSE=1048576,ATTR_HIDDEN=2097152,ATTR_STRIKETHROUGH=4194304,UNDERLINE_STYLE_SHIFT=24,UNDERLINE_STYLE_MASK,WIDE_FLAG=134217728,CONTINUATION_FLAG=268435456,TRUE_COLOR_FG_FLAG=536870912,TRUE_COLOR_BG_FLAG=1073741824,SELECTABLE_FLAG=2147483648,VISIBLE_SPACE_ATTR_MASK,EMPTY_CELL,EMPTY_ATTRS,XTERM_256_PALETTE,EMPTY_FRAME_CELL;var init_buffer=__esm(()=>{init_sgr_codes();DEFAULT_BG=Object.freeze({r:-1,g:-1,b:-1});UNDERLINE_STYLE_MASK=7<<UNDERLINE_STYLE_SHIFT;VISIBLE_SPACE_ATTR_MASK=ATTR_INVERSE|ATTR_STRIKETHROUGH|UNDERLINE_STYLE_MASK,EMPTY_CELL={char:" ",fg:null,bg:null,underlineColor:null,attrs:{},wide:!1,continuation:!1,hyperlink:void 0},EMPTY_ATTRS=Object.freeze({});XTERM_256_PALETTE=(()=>{let palette=Array(256),standard=["#000000","#cd0000","#00cd00","#cdcd00","#0000ee","#cd00cd","#00cdcd","#e5e5e5"],bright=["#7f7f7f","#ff0000","#00ff00","#ffff00","#5c5cff","#ff00ff","#00ffff","#ffffff"];for(let i=0;i<8;i++)palette[i]=standard[i],palette[i+8]=bright[i];let cubeValues=[0,95,135,175,215,255];for(let i=0;i<216;i++){let r=cubeValues[Math.floor(i/36)],g=cubeValues[Math.floor(i%36/6)],b=cubeValues[i%6];palette[16+i]="#"+r.toString(16).padStart(2,"0")+g.toString(16).padStart(2,"0")+b.toString(16).padStart(2,"0")}for(let i=0;i<24;i++){let hex=(8+i*10).toString(16).padStart(2,"0");palette[232+i]="#"+hex+hex+hex}return palette})();EMPTY_FRAME_CELL=Object.freeze({char:" ",fg:null,bg:null,bold:!1,dim:!1,italic:!1,underline:!1,underlineColor:null,strikethrough:!1,inverse:!1,blink:!1,hidden:!1,wide:!1,continuation:!1,hyperlink:null})});function textSized(text,width){return`\x1B]66;w=${width};${text}\x07`}function isPrivateUseArea(cp){return cp>=57344&&cp<=63743||cp>=983040&&cp<=1048573||cp>=1048576&&cp<=1114109}function isTextSizingLikelySupported(){let termProgram=process.env.TERM_PROGRAM?.toLowerCase()??"",termVersion=process.env.TERM_PROGRAM_VERSION??"";if(termProgram==="kitty"){let parts=termVersion.split("."),major=Number(parts[0])||0,minor=Number(parts[1])||0;if(major>0||major===0&&minor>=40)return!0}return!1}function getTerminalFingerprint(){let program=process.env.TERM_PROGRAM??"unknown",version=process.env.TERM_PROGRAM_VERSION??"unknown";return`${program}@${version}`}function getCachedProbeResult(){return probeCache.get(getTerminalFingerprint())}function setCachedProbeResult(result){probeCache.set(getTerminalFingerprint(),result)}async function detectTextSizingSupport(write,read,timeout=1000){let cached=getCachedProbeResult();if(cached!==void 0)return cached;let testSequence="\r"+textSized(" ",2)+"\x1B[6n\r\x1B[K";write(testSequence);try{let match=(await Promise.race([read(),new Promise((_resolve,reject)=>setTimeout(()=>reject(Error("timeout")),timeout))])).match(/\x1b\[(\d+);(\d+)R/);if(match){if(Number(match[2])===3){let result2={supported:!0,widthOnly:!1};return setCachedProbeResult(result2),result2}}let result={supported:!1,widthOnly:!1};return setCachedProbeResult(result),result}catch{let result={supported:!1,widthOnly:!1};return setCachedProbeResult(result),result}}var probeCache;var init_text_sizing=__esm(()=>{probeCache=new Map});import sliceAnsi from"slice-ansi";import stringWidth2 from"string-width";class DisplayWidthCache{cache=new Map;maxSize;constructor(maxSize=1000){this.maxSize=maxSize}get(text){let cached=this.cache.get(text);if(cached!==void 0)this.cache.delete(text),this.cache.set(text,cached);return cached}set(text,width){if(this.cache.size>=this.maxSize){let firstKey=this.cache.keys().next().value;if(firstKey!==void 0)this.cache.delete(firstKey)}this.cache.set(text,width)}clear(){this.cache.clear()}}function runWithMeasurer(measurer,fn){let prev=_scopedMeasurer;_scopedMeasurer=measurer;try{return fn()}finally{_scopedMeasurer=prev}}function isTextSizingEnabled(){if(_scopedMeasurer)return _scopedMeasurer.textSizingEnabled;return DEFAULT_TEXT_SIZING_ENABLED}function stripOsc8ForSlice(text){return text.replace(OSC8_RE,"")}function createWidthMeasurer(caps={}){let textEmojiWide=caps.textEmojiWide??!0,textSizingEnabled=caps.textSizingEnabled??!1,cache=new DisplayWidthCache(1e4);function measuredGraphemeWidth(grapheme){let width=stringWidth2(grapheme);if(width!==1)return width;if(textEmojiWide&&isTextPresentationEmoji(grapheme))return 2;if(textSizingEnabled){let cp=grapheme.codePointAt(0);if(cp!==void 0&&isPrivateUseArea(cp))return 2}return width}function measuredDisplayWidth(text){let cached=cache.get(text);if(cached!==void 0)return cached;let width;if(!(MAY_CONTAIN_TEXT_EMOJI.test(text)||textSizingEnabled&&MAY_CONTAIN_PUA.test(text)))width=stringWidth2(text);else{let stripped=stripAnsi2(text);width=0;for(let grapheme of splitGraphemes(stripped))width+=measuredGraphemeWidth(grapheme)}return cache.set(text,width),width}function measuredDisplayWidthAnsi(text){return measuredDisplayWidth(stripAnsi2(text))}function measuredSliceByWidth(text,maxWidth){if(hasAnsi(text))return sliceAnsi(stripOsc8ForSlice(text),0,maxWidth);let width=0,result="",graphemes=splitGraphemes(text);for(let grapheme of graphemes){let gWidth=measuredGraphemeWidth(grapheme);if(width+gWidth>maxWidth)break;result+=grapheme,width+=gWidth}return result}function measuredSliceByWidthFromEnd(text,maxWidth){if(measuredDisplayWidthAnsi(text)<=maxWidth)return text;if(hasAnsi(text)){let cleaned=stripOsc8ForSlice(text),startIndex=measuredDisplayWidthAnsi(cleaned)-maxWidth;return sliceAnsi(cleaned,startIndex)}let graphemes=splitGraphemes(text),width=0,startIdx=graphemes.length;for(let i=graphemes.length-1;i>=0;i--){let gWidth=measuredGraphemeWidth(graphemes[i]);if(width+gWidth>maxWidth)break;width+=gWidth,startIdx=i}return graphemes.slice(startIdx).join("")}function measuredWrapText(text,width,trim,hard){return wrapTextWithMeasurer(text,width,measurer,trim??!1,hard??!1)}let measurer={textEmojiWide,textSizingEnabled,lineHeight:1,displayWidth:measuredDisplayWidth,displayWidthAnsi:measuredDisplayWidthAnsi,graphemeWidth:measuredGraphemeWidth,wrapText:measuredWrapText,sliceByWidth:measuredSliceByWidth,sliceByWidthFromEnd:measuredSliceByWidthFromEnd};return measurer}function getDefaultMeasurer(){if(!_defaultMeasurer)_defaultMeasurer=createWidthMeasurer();return _defaultMeasurer}function splitGraphemes(text){return[...segmenter.segment(text)].map((s)=>s.segment)}function isTextPresentationEmoji(grapheme){let cp=grapheme.codePointAt(0);if(cp===void 0)return!1;let cached=textPresentationEmojiCache.get(cp);if(cached!==void 0)return cached;if(String.fromCodePoint(cp).length!==grapheme.length)return textPresentationEmojiCache.set(cp,!1),!1;let isExtPict=TEXT_PRESENTATION_EMOJI_REGEX.test(grapheme),isEmojiPres=EMOJI_PRESENTATION_REGEX.test(grapheme);if(!isExtPict||isEmojiPres)return textPresentationEmojiCache.set(cp,!1),!1;let withVs16=grapheme+"️",result=RGI_EMOJI_REGEX.test(withVs16);return textPresentationEmojiCache.set(cp,result),result}function ensureEmojiPresentation(char){if(char.includes("️"))return char;if(isTextPresentationEmoji(char))return char+"️";return char}function displayWidth(text){if(_scopedMeasurer)return _scopedMeasurer.displayWidth(text);let cached=displayWidthCache.get(text);if(cached!==void 0)return cached;let width;if(!(MAY_CONTAIN_TEXT_EMOJI.test(text)||DEFAULT_TEXT_SIZING_ENABLED&&MAY_CONTAIN_PUA.test(text)))width=stringWidth2(text);else{let stripped=stripAnsi2(text);width=0;for(let grapheme of splitGraphemes(stripped))width+=graphemeWidth(grapheme)}return displayWidthCache.set(text,width),width}function graphemeWidth(grapheme){if(_scopedMeasurer)return _scopedMeasurer.graphemeWidth(grapheme);let width=stringWidth2(grapheme);if(width!==1)return width;if(DEFAULT_TEXT_EMOJI_WIDE&&isTextPresentationEmoji(grapheme))return 2;if(DEFAULT_TEXT_SIZING_ENABLED){let cp=grapheme.codePointAt(0);if(cp!==void 0&&isPrivateUseArea(cp))return 2}return width}function isWordBoundary(grapheme){return grapheme===" "||grapheme==="-"||grapheme==="\t"}function isBreakBeforeOperatorWith(graphemes,spaceIndex,gWidthFn){let j=spaceIndex+1;while(j<graphemes.length&&gWidthFn(graphemes[j])===0)j++;if(j>=graphemes.length)return!1;let nextChar=graphemes[j];if(gWidthFn(nextChar)!==1)return!1;if(/^[a-zA-Z0-9\s]$/.test(nextChar))return!1;let k=j+1;while(k<graphemes.length&&gWidthFn(graphemes[k])===0)k++;if(k>=graphemes.length)return!1;return graphemes[k]===" "}function canBreakAnywhere(grapheme){return isCJK(grapheme)}function splitGraphemesAnsiAware(text){if(!hasAnsi(text))return splitGraphemes(text);let result=[],pos=0;while(pos<text.length){if(text[pos]==="\x1B"){let remaining=text.slice(pos),csi=remaining.match(ANSI_CSI_RE);if(csi){result.push(csi[0]),pos+=csi[0].length;continue}let osc=remaining.match(ANSI_OSC_RE);if(osc){result.push(osc[0]),pos+=osc[0].length;continue}let single=remaining.match(ANSI_SINGLE_RE);if(single){result.push(single[0]),pos+=single[0].length;continue}}let nextEsc=text.indexOf("\x1B",pos+1),chunk=nextEsc===-1?text.slice(pos):text.slice(pos,nextEsc);for(let g of splitGraphemes(chunk))result.push(g);pos+=chunk.length}return result}function wrapText(text,width,preserveNewlines=!0,trim=!1){if(_scopedMeasurer?.wrapText)return _scopedMeasurer.wrapText(text,width,trim);return wrapTextWithMeasurer(text,width,_scopedMeasurer??void 0,trim,!1,preserveNewlines)}function getActiveLineHeight(){return _scopedMeasurer?.lineHeight??1}function wrapTextWithMeasurer(text,width,measurer,trim=!1,_hard=!1,preserveNewlines=!0){if(width<=0)return[];let gWidthFn=measurer?measurer.graphemeWidth.bind(measurer):graphemeWidth,lines=[],inputLines=preserveNewlines?text.split(`
19
+ `):[text.replace(/\n/g," ")];for(let line of inputLines){if(line===""){lines.push("");continue}let graphemes=splitGraphemesAnsiAware(line),currentLine="",currentWidth=0,isFirstLineOfParagraph=!0,lastBreakIndex=-1,lastBreakWidth=0,lastBreakGraphemeIndex=-1;for(let i=0;i<graphemes.length;i++){let grapheme=graphemes[i],gWidth=gWidthFn(grapheme);if(gWidth===0){currentLine+=grapheme;continue}if(trim&&!isFirstLineOfParagraph&&currentWidth===0&&isWordBoundary(grapheme)&&grapheme!=="-")continue;if(isWordBoundary(grapheme)){if(currentWidth+gWidth<=width){if(currentLine+=grapheme,currentWidth+=gWidth,grapheme!==" "||!isBreakBeforeOperatorWith(graphemes,i,gWidthFn))lastBreakIndex=currentLine.length,lastBreakWidth=currentWidth,lastBreakGraphemeIndex=i+1;continue}if(currentLine){let lineToAdd=currentLine;if(trim)lineToAdd=lineToAdd.trimEnd();lines.push(lineToAdd),isFirstLineOfParagraph=!1}currentLine="",currentWidth=0,lastBreakIndex=-1,lastBreakWidth=0,lastBreakGraphemeIndex=-1;continue}else if(canBreakAnywhere(grapheme))lastBreakIndex=currentLine.length,lastBreakWidth=currentWidth,lastBreakGraphemeIndex=i;if(currentWidth+gWidth>width)if(lastBreakIndex>0){let lineToAdd=currentLine.slice(0,lastBreakIndex);if(trim)lineToAdd=lineToAdd.trimEnd();lines.push(lineToAdd),isFirstLineOfParagraph=!1,currentLine=currentLine.slice(lastBreakIndex),currentWidth=currentWidth-lastBreakWidth,i=lastBreakGraphemeIndex-1,currentLine="",currentWidth=0,lastBreakIndex=-1,lastBreakWidth=0,lastBreakGraphemeIndex=-1}else{if(currentLine){if(trim)currentLine=currentLine.trimEnd();lines.push(currentLine),isFirstLineOfParagraph=!1}currentLine=grapheme,currentWidth=gWidth,lastBreakIndex=-1,lastBreakWidth=0,lastBreakGraphemeIndex=-1}else currentLine+=grapheme,currentWidth+=gWidth}if(currentLine)lines.push(currentLine)}if(text.includes("\x1B]8;;"))fixOsc8AcrossWrappedLines(lines);return lines}function fixOsc8AcrossWrappedLines(lines){let activeHref=null;for(let i=0;i<lines.length;i++){let line=lines[i];if(activeHref!==null)line=`\x1B]8;;${activeHref}\x1B\\`+line;let lineHref=activeHref,osc8Matches=line.matchAll(/\x1b\]8;;([^\x07\x1b]*)(?:\x07|\x1b\\)/g);for(let m of osc8Matches)lineHref=m[1]===""?null:m[1];if(lineHref!==null)line+="\x1B]8;;\x1B\\";lines[i]=line,activeHref=lineHref}}function sliceByWidth(text,maxWidth){return(_scopedMeasurer??getDefaultMeasurer()).sliceByWidth(text,maxWidth)}function sliceByWidthFromEnd(text,maxWidth){return(_scopedMeasurer??getDefaultMeasurer()).sliceByWidthFromEnd(text,maxWidth)}function stripAnsi2(text){return text.replace(/\x1b\[[0-9;:?]*[A-Za-z]/g,"").replace(/\x9b[0-9;:?]*[A-Za-z]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x9d[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c)/g,"").replace(/\x1b[DME78]/g,"").replace(/\x1b\(B/g,"")}function displayWidthAnsi(text){return displayWidth(stripAnsi2(text))}function parseUnderlineStyle(subparam){switch(subparam){case 0:return!1;case 1:return"single";case 2:return"double";case 3:return"curly";case 4:return"dotted";case 5:return"dashed";default:return"single"}}function parseAnsiText(text){let segments=[],sanitizedText=text.replace(/\x1b\[[0-9;:]*[A-LN-Za-ln-z@`]/g,"").replace(/\x9b[0-9;:]*[A-LN-Za-ln-z@`]/g,""),oscPattern=/(?:\x1b\]|\x9d)8;;([^\x07\x1b\x9c]*)(?:\x07|\x1b\\|\x9c)/g,currentHyperlink,hyperlinkRanges=[],rangeStart=-1,cleaned="",oscMatch,oscLastIndex=0;while((oscMatch=oscPattern.exec(sanitizedText))!==null){cleaned+=sanitizedText.slice(oscLastIndex,oscMatch.index);let url=oscMatch[1],matchStr=oscMatch[0],isC1=matchStr.charCodeAt(0)===157,lastChar=matchStr.charCodeAt(matchStr.length-1),isBel=lastChar===7,isSt9c=lastChar===156;if(url===""){if(currentHyperlink&&rangeStart>=0)hyperlinkRanges.push({start:rangeStart,end:cleaned.length,url:currentHyperlink});currentHyperlink=void 0,rangeStart=-1}else{if(currentHyperlink&&rangeStart>=0)hyperlinkRanges.push({start:rangeStart,end:cleaned.length,url:currentHyperlink});let encodedUrl=url;if(isC1&&(isBel||isSt9c))encodedUrl=`\x01c1b\x02${url}`;else if(isC1)encodedUrl=`\x01c1s\x02${url}`;else if(isBel)encodedUrl=`\x01e7b\x02${url}`;currentHyperlink=encodedUrl,rangeStart=cleaned.length}oscLastIndex=oscMatch.index+oscMatch[0].length}if(cleaned+=sanitizedText.slice(oscLastIndex),currentHyperlink&&rangeStart>=0)hyperlinkRanges.push({start:rangeStart,end:cleaned.length,url:currentHyperlink});let processText=hyperlinkRanges.length>0?cleaned:sanitizedText,ansiPattern=/(?:\x1b\[|\x9b)([0-9;:]*)m/g,currentStyle={},lastIndex=0,match;function getHyperlinkAt(pos){for(let range of hyperlinkRanges)if(pos>=range.start&&pos<range.end)return range.url;return}while((match=ansiPattern.exec(processText))!==null){if(match.index>lastIndex){let content=processText.slice(lastIndex,match.index);if(content.length>0)if(hyperlinkRanges.length>0){let segStart=0;for(let ci=0;ci<content.length;ci++){let hl=getHyperlinkAt(lastIndex+ci),prevHl=ci>0?getHyperlinkAt(lastIndex+ci-1):void 0;if(ci>0&&hl!==prevHl){let sub2=content.slice(segStart,ci);if(sub2.length>0){let seg={text:sub2,...currentStyle};if(prevHl)seg.hyperlink=prevHl;segments.push(seg)}segStart=ci}}let sub=content.slice(segStart);if(sub.length>0){let hl=getHyperlinkAt(lastIndex+segStart),seg={text:sub,...currentStyle};if(hl)seg.hyperlink=hl;segments.push(seg)}}else segments.push({text:content,...currentStyle})}let params=match[1].split(";");for(let i=0;i<params.length;i++){let param=params[i];if(param.includes(":")){let subparts=param.split(":").map((s)=>s===""?0:Number(s)),mainCode=subparts[0];if(mainCode===4){let styleCode=subparts[1]??1;currentStyle.underlineStyle=parseUnderlineStyle(styleCode),currentStyle.underline=currentStyle.underlineStyle!==!1}else if(mainCode===58){if(subparts[1]===5&&subparts[2]!==void 0)currentStyle.underlineColor=subparts[2];else if(subparts[1]===2){let r=subparts[3]??subparts[2]??0,g=subparts[4]??subparts[3]??0,b=subparts[5]??subparts[4]??0;currentStyle.underlineColor=16777216|(r&255)<<16|(g&255)<<8|b&255}}else if(mainCode===38){if(subparts[1]===5&&subparts[2]!==void 0)currentStyle.fg=subparts[2],currentStyle.colonFg=!0;else if(subparts[1]===2){let r=subparts[3]??subparts[2]??0,g=subparts[4]??subparts[3]??0,b=subparts[5]??subparts[4]??0;currentStyle.fg=16777216|(r&255)<<16|(g&255)<<8|b&255,currentStyle.colonFg=!0}}else if(mainCode===48){if(subparts[1]===5&&subparts[2]!==void 0)currentStyle.bg=subparts[2],currentStyle.colonBg=!0;else if(subparts[1]===2){let r=subparts[3]??subparts[2]??0,g=subparts[4]??subparts[3]??0,b=subparts[5]??subparts[4]??0;currentStyle.bg=16777216|(r&255)<<16|(g&255)<<8|b&255,currentStyle.colonBg=!0}}continue}let code=Number(param);switch(code){case 0:currentStyle={};break;case 1:currentStyle.bold=!0;break;case 2:currentStyle.dim=!0;break;case 3:currentStyle.italic=!0;break;case 4:currentStyle.underline=!0,currentStyle.underlineStyle="single";break;case 7:currentStyle.inverse=!0;break;case 22:currentStyle.bold=!1,currentStyle.dim=!1;break;case 23:currentStyle.italic=!1;break;case 24:currentStyle.underline=!1,currentStyle.underlineStyle=!1;break;case 27:currentStyle.inverse=!1;break;case 30:case 31:case 32:case 33:case 34:case 35:case 36:case 37:currentStyle.fg=code;break;case 38:{let nextParams=params.slice(i+1).map(Number);if(currentStyle.colonFg=void 0,nextParams[0]===5&&nextParams[1]!==void 0)currentStyle.fg=nextParams[1],i+=2;else if(nextParams[0]===2&&nextParams[3]!==void 0)currentStyle.fg=16777216|(nextParams[1]&255)<<16|(nextParams[2]&255)<<8|nextParams[3]&255,i+=4;break}case 39:currentStyle.fg=null;break;case 40:case 41:case 42:case 43:case 44:case 45:case 46:case 47:currentStyle.bg=code;break;case 48:{let nextParams=params.slice(i+1).map(Number);if(currentStyle.colonBg=void 0,nextParams[0]===5&&nextParams[1]!==void 0)currentStyle.bg=nextParams[1],i+=2;else if(nextParams[0]===2&&nextParams[3]!==void 0)currentStyle.bg=16777216|(nextParams[1]&255)<<16|(nextParams[2]&255)<<8|nextParams[3]&255,i+=4;break}case 49:currentStyle.bg=null;break;case 58:{let nextParams=params.slice(i+1).map(Number);if(nextParams[0]===5&&nextParams[1]!==void 0)currentStyle.underlineColor=nextParams[1],i+=2;else if(nextParams[0]===2&&nextParams[3]!==void 0)currentStyle.underlineColor=16777216|(nextParams[1]&255)<<16|(nextParams[2]&255)<<8|nextParams[3]&255,i+=4;break}case 59:currentStyle.underlineColor=null;break;case 90:case 91:case 92:case 93:case 94:case 95:case 96:case 97:currentStyle.fg=code;break;case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:currentStyle.bg=code;break;case BG_OVERRIDE_CODE:currentStyle.bgOverride=!0;break}}lastIndex=match.index+match[0].length}if(lastIndex<processText.length){let content=processText.slice(lastIndex);if(content.length>0)if(hyperlinkRanges.length>0){let segStart=0;for(let ci=0;ci<content.length;ci++){let hl=getHyperlinkAt(lastIndex+ci),prevHl=ci>0?getHyperlinkAt(lastIndex+ci-1):void 0;if(ci>0&&hl!==prevHl){let sub2=content.slice(segStart,ci);if(sub2.length>0){let seg={text:sub2,...currentStyle};if(prevHl)seg.hyperlink=prevHl;segments.push(seg)}segStart=ci}}let sub=content.slice(segStart);if(sub.length>0){let hl=getHyperlinkAt(lastIndex+segStart),seg={text:sub,...currentStyle};if(hl)seg.hyperlink=hl;segments.push(seg)}}else segments.push({text:content,...currentStyle})}return segments}function hasAnsi(text){return ANSI_TEST_REGEX.test(text)}function getFirstCodePoint(str){return str.codePointAt(0)??0}function isCJK(grapheme){let cp=getFirstCodePoint(grapheme);return CHAR_RANGES.isCJK(cp)||CHAR_RANGES.isJapaneseKana(cp)||CHAR_RANGES.isHangul(cp)}var segmenter,displayWidthCache,DEFAULT_TEXT_EMOJI_WIDE=!0,DEFAULT_TEXT_SIZING_ENABLED=!1,_scopedMeasurer=null,OSC8_RE,_defaultMeasurer,TEXT_PRESENTATION_EMOJI_REGEX,EMOJI_PRESENTATION_REGEX,RGI_EMOJI_REGEX,textPresentationEmojiCache,MAY_CONTAIN_TEXT_EMOJI,MAY_CONTAIN_PUA,ANSI_CSI_RE,ANSI_OSC_RE,ANSI_SINGLE_RE,ANSI_TEST_REGEX,CHAR_RANGES;var init_unicode=__esm(()=>{init_ansi2();init_buffer();init_text_sizing();segmenter=new Intl.Segmenter(void 0,{granularity:"grapheme"});displayWidthCache=new DisplayWidthCache(1e4);OSC8_RE=/\x1b\]8;;[^\x07\x1b]*(?:\x07|\x1b\\)/g;TEXT_PRESENTATION_EMOJI_REGEX=/^\p{Extended_Pictographic}$/u,EMOJI_PRESENTATION_REGEX=/^\p{Emoji_Presentation}$/u,RGI_EMOJI_REGEX=/^\p{RGI_Emoji}$/v,textPresentationEmojiCache=new Map;MAY_CONTAIN_TEXT_EMOJI=/[\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]/,MAY_CONTAIN_PUA=/[\uE000-\uF8FF]/;ANSI_CSI_RE=/^\x1b\[[0-9;:?]*[A-Za-z]/,ANSI_OSC_RE=/^\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/,ANSI_SINGLE_RE=/^\x1b[DME78(B]/;ANSI_TEST_REGEX=/\x1b(?:\[[0-9;:]*[A-Za-z]|\])|\x9b[\x30-\x3f]*[\x40-\x7e]|\x9d/;CHAR_RANGES={isBasicLatin:(cp)=>cp>=32&&cp<=127,isCJK:(cp)=>cp>=19968&&cp<=40959||cp>=13312&&cp<=19903||cp>=131072&&cp<=173791||cp>=63744&&cp<=64255||cp>=194560&&cp<=195103,isJapaneseKana:(cp)=>cp>=12352&&cp<=12447||cp>=12448&&cp<=12543,isHangul:(cp)=>cp>=44032&&cp<=55203||cp>=4352&&cp<=4607,isEmoji:(cp)=>cp>=128512&&cp<=128591||cp>=127744&&cp<=128511||cp>=128640&&cp<=128767||cp>=128768&&cp<=128895||cp>=129280&&cp<=129535||cp>=9728&&cp<=9983||cp>=9984&&cp<=10175}});var IncrementalRenderMismatchError;var init_errors=__esm(()=>{IncrementalRenderMismatchError=class IncrementalRenderMismatchError extends Error{renderPhaseStats;mismatchContext;constructor(message,data){super(message);this.name="IncrementalRenderMismatchError",this.renderPhaseStats=data?.renderPhaseStats,this.mismatchContext=data?.mismatchContext}}});import{createLogger as createLogger2}from"loggily";function strictTerminalBackends(){let val=(typeof process<"u"?process.env.SILVERY_STRICT_TERMINAL??"":"").toLowerCase().trim();if(!val)return[];if(val==="all")return["vt100","xterm","ghostty"];let backends=val.split(",").map((s)=>s.trim()).filter(Boolean),valid=new Set(["vt100","xterm","ghostty"]);for(let b of backends)if(!valid.has(b))log2.warn?.(`SILVERY_STRICT_TERMINAL: unknown backend '${b}', ignoring`);return backends.filter((b)=>valid.has(b))}function createTerminalVerifyState(){let allBackends=strictTerminalBackends();return{terminal:null,ghosttyTerminal:null,width:0,height:0,frameCount:0,backends:allBackends.filter((b)=>b!=="vt100"),hasVt100:allBackends.includes("vt100")}}function createDefaultSgr(){return{fg:null,bg:null,bold:!1,dim:!1,italic:!1,underline:!1,blink:!1,inverse:!1,hidden:!1,strikethrough:!1}}function createDefaultStyledCell(){return{char:" ",fg:null,bg:null,bold:!1,dim:!1,italic:!1,underline:!1,blink:!1,inverse:!1,hidden:!1,strikethrough:!1}}function applySgrParams(params,sgr){if(params===""||params==="0"){sgr.fg=null,sgr.bg=null,sgr.bold=!1,sgr.dim=!1,sgr.italic=!1,sgr.underline=!1,sgr.blink=!1,sgr.inverse=!1,sgr.hidden=!1,sgr.strikethrough=!1;return}let parts=params.split(";"),i=0;while(i<parts.length){let code=parts[i],colonIdx=code.indexOf(":");if(colonIdx>=0){if(parseInt(code.substring(0,colonIdx))===4){let sub=parseInt(code.substring(colonIdx+1));sgr.underline=sub>0}i++;continue}let n=parseInt(code);if(n===0)sgr.fg=null,sgr.bg=null,sgr.bold=!1,sgr.dim=!1,sgr.italic=!1,sgr.underline=!1,sgr.blink=!1,sgr.inverse=!1,sgr.hidden=!1,sgr.strikethrough=!1;else if(n===1)sgr.bold=!0;else if(n===2)sgr.dim=!0;else if(n===3)sgr.italic=!0;else if(n===4)sgr.underline=!0;else if(n===5||n===6)sgr.blink=!0;else if(n===7)sgr.inverse=!0;else if(n===8)sgr.hidden=!0;else if(n===9)sgr.strikethrough=!0;else if(n===21)sgr.underline=!0;else if(n===22)sgr.bold=!1,sgr.dim=!1;else if(n===23)sgr.italic=!1;else if(n===24)sgr.underline=!1;else if(n===25)sgr.blink=!1;else if(n===27)sgr.inverse=!1;else if(n===28)sgr.hidden=!1;else if(n===29)sgr.strikethrough=!1;else if(n>=30&&n<=37)sgr.fg=n-30;else if(n===38){if(parts[i+1]==="5")sgr.fg=parseInt(parts[i+2]),i+=2;else if(parts[i+1]==="2")sgr.fg={r:parseInt(parts[i+2]),g:parseInt(parts[i+3]),b:parseInt(parts[i+4])},i+=4}else if(n===39)sgr.fg=null;else if(n>=40&&n<=47)sgr.bg=n-40;else if(n===48){if(parts[i+1]==="5")sgr.bg=parseInt(parts[i+2]),i+=2;else if(parts[i+1]==="2")sgr.bg={r:parseInt(parts[i+2]),g:parseInt(parts[i+3]),b:parseInt(parts[i+4])},i+=4}else if(n===49)sgr.bg=null;else if(n>=90&&n<=97)sgr.fg=n-90+8;else if(n>=100&&n<=107)sgr.bg=n-100+8;i++}}function replayAnsiWithStyles(width,height,ansi,ctx=_defaultCtxForReplay){let screen=Array.from({length:height},()=>Array.from({length:width},()=>createDefaultStyledCell())),cx=0,cy=0,pendingWrap=!1,sgr=createDefaultSgr(),i=0;while(i<ansi.length){if(ansi[i]==="\x1B"){if(ansi[i+1]==="["){i+=2;let params="";while(i<ansi.length&&(ansi[i]>="0"&&ansi[i]<="9"||ansi[i]===";"||ansi[i]==="?"||ansi[i]===":"))params+=ansi[i],i++;let cmd=ansi[i];if(i++,cmd==="H")if(pendingWrap=!1,params==="")cx=0,cy=0;else{let cmdParts=params.split(";");cy=Math.min(height-1,Math.max(0,(parseInt(cmdParts[0])||1)-1)),cx=Math.min(width-1,Math.max(0,(parseInt(cmdParts[1])||1)-1))}else if(cmd==="K"){if(cy>=height)continue;for(let x=cx;x<width;x++){let cell=screen[cy][x];cell.char=" ",cell.fg=null,cell.bg=sgr.bg,cell.bold=!1,cell.dim=!1,cell.italic=!1,cell.underline=!1,cell.blink=!1,cell.inverse=!1,cell.hidden=!1,cell.strikethrough=!1}}else if(cmd==="J"){if(cy<height)for(let x=cx;x<width;x++){let cell=screen[cy][x];cell.char=" ",cell.fg=null,cell.bg=sgr.bg,cell.bold=!1,cell.dim=!1,cell.italic=!1,cell.underline=!1,cell.blink=!1,cell.inverse=!1,cell.hidden=!1,cell.strikethrough=!1}for(let y=cy+1;y<height;y++)for(let x=0;x<width;x++){let cell=screen[y][x];cell.char=" ",cell.fg=null,cell.bg=sgr.bg,cell.bold=!1,cell.dim=!1,cell.italic=!1,cell.underline=!1,cell.blink=!1,cell.inverse=!1,cell.hidden=!1,cell.strikethrough=!1}}else if(cmd==="m")applySgrParams(params,sgr);else if(cmd==="C"){pendingWrap=!1;let n=parseInt(params)||1;cx=Math.min(width-1,cx+n)}else if(cmd==="A"){pendingWrap=!1;let n=parseInt(params)||1;cy=Math.max(0,cy-n)}else if(cmd==="B"){pendingWrap=!1;let n=parseInt(params)||1;cy=Math.min(height-1,cy+n)}continue}else if(ansi[i+1]==="]"){i+=2;while(i<ansi.length){if(ansi[i]==="\x07"){i++;break}if(ansi[i]==="\x1B"&&ansi[i+1]==="\\"){i+=2;break}i++}continue}i+=2;continue}if(ansi[i]==="\r"){pendingWrap=!1,cx=0,i++;continue}if(ansi[i]===`
20
+ `){if(pendingWrap=!1,cy++,cy>=height){let first=screen.shift();for(let cell of first)cell.char=" ",cell.fg=null,cell.bg=null,cell.bold=!1,cell.dim=!1,cell.italic=!1,cell.underline=!1,cell.blink=!1,cell.inverse=!1,cell.hidden=!1,cell.strikethrough=!1;screen.push(first),cy=height-1}i++;continue}let grapheme="",advance=0,code0=ansi.charCodeAt(i);if(code0>=55296&&code0<=56319&&i+1<ansi.length){let low=ansi.charCodeAt(i+1);if(low>=56320&&low<=57343)grapheme=ansi[i]+ansi[i+1],advance=2;else grapheme=ansi[i],advance=1}else grapheme=ansi[i],advance=1;{let j=i+advance;while(j<ansi.length){let c=ansi.charCodeAt(j),cp,cpLen;if(c>=55296&&c<=56319&&j+1<ansi.length){let lo=ansi.charCodeAt(j+1);if(lo>=56320&&lo<=57343)cp=(c-55296<<10)+(lo-56320)+65536,cpLen=2;else break}else cp=c,cpLen=1;if(cp===8205||cp===65038||cp===65039||cp>=768&&cp<=879||cp>=8400&&cp<=8447||cp>=6832&&cp<=6911||cp>=65056&&cp<=65071||cp===8419||cp>=127995&&cp<=127999||cp>=127462&&cp<=127487||cp>=917536&&cp<=917631||cp===917505){grapheme+=ansi.slice(j,j+cpLen),advance+=cpLen,j+=cpLen;continue}if((grapheme.length>=2?grapheme.charCodeAt(grapheme.length-2)===8205?8205:grapheme.charCodeAt(grapheme.length-1):grapheme.charCodeAt(grapheme.length-1))===8205&&cp>32){grapheme+=ansi.slice(j,j+cpLen),advance+=cpLen,j+=cpLen;continue}break}}let charWidth=graphemeWidth(grapheme);if(cy<height&&cx<width){if(pendingWrap){if(pendingWrap=!1,cx=0,cy++,cy>=height){let first=screen.shift();for(let cell of first)cell.char=" ",cell.fg=null,cell.bg=null,cell.bold=!1,cell.dim=!1,cell.italic=!1,cell.underline=!1,cell.blink=!1,cell.inverse=!1,cell.hidden=!1,cell.strikethrough=!1;screen.push(first),cy=height-1}}if(cy<height&&cx<width){let cell=screen[cy][cx];if(cell.char=grapheme,cell.fg=sgr.fg,cell.bg=sgr.bg,cell.bold=sgr.bold,cell.dim=sgr.dim,cell.italic=sgr.italic,cell.underline=sgr.underline,cell.blink=sgr.blink,cell.inverse=sgr.inverse,cell.hidden=sgr.hidden,cell.strikethrough=sgr.strikethrough,charWidth===2&&cx+1<width){let cont=screen[cy][cx+1];cont.char=" ",cont.fg=sgr.fg,cont.bg=sgr.bg,cont.bold=sgr.bold,cont.dim=sgr.dim,cont.italic=sgr.italic,cont.underline=sgr.underline,cont.blink=sgr.blink,cont.inverse=sgr.inverse,cont.hidden=sgr.hidden,cont.strikethrough=sgr.strikethrough}if(cx+=charWidth,cx>=width)cx=width-1,pendingWrap=!0}}i+=advance}return screen}function formatColor(c){if(c===null)return"default";if(typeof c==="number")return`${c}`;return`rgb(${c.r},${c.g},${c.b})`}function captureStrictFailureArtifacts(opts){try{let fs=__require("fs"),path=__require("path"),dir=`/tmp/silvery-strict-failure-${Date.now()}`;fs.mkdirSync(dir,{recursive:!0});let meta={source:opts.source,timestamp:new Date().toISOString(),frameCount:opts.frameCount,prevSize:opts.prev?{width:opts.prev.width,height:opts.prev.height}:null,nextSize:opts.next?{width:opts.next.width,height:opts.next.height}:null,incrOutputLength:opts.incrOutput?.length,freshOutputLength:opts.freshOutput?.length,testName:globalThis.__vitest_worker__?.current?.name};if(fs.writeFileSync(path.join(dir,"meta.json"),JSON.stringify(meta,null,2)),fs.writeFileSync(path.join(dir,"error.txt"),opts.errorMessage),opts.incrOutput)fs.writeFileSync(path.join(dir,"incremental.ansi"),opts.incrOutput);if(opts.freshOutput)fs.writeFileSync(path.join(dir,"fresh.ansi"),opts.freshOutput);if(opts.prev){let rows=[];for(let y=0;y<opts.prev.height;y++){let row="";for(let x=0;x<opts.prev.width;x++){let cell=opts.prev.getCell(x,y);row+=cell.char||" "}rows.push(row.trimEnd())}fs.writeFileSync(path.join(dir,"prev-buffer.txt"),rows.join(`
40
21
  `))}if(opts.next){let rows=[];for(let y=0;y<opts.next.height;y++){let row="";for(let x=0;x<opts.next.width;x++){let cell=opts.next.getCell(x,y);row+=cell.char||" "}rows.push(row.trimEnd())}fs.writeFileSync(path.join(dir,"next-buffer.txt"),rows.join(`
41
- `))}if(opts.prev&&opts.ctx){let freshPrev=bufferToAnsi(opts.prev,opts.ctx);fs.writeFileSync(path.join(dir,"fresh-prev.ansi"),freshPrev)}return dir}catch{return"(artifact capture failed)"}}function verifyOutputEquivalence(prev,next,incrOutput,ctx=defaultContext){let{mode}=ctx,w=Math.max(prev.width,next.width),vtHeight=Math.max(prev.height,next.height),compareHeight=next.height;if(DEBUG_OUTPUT)log2.error?.(`[VERIFY] prev=${prev.width}x${prev.height} next=${next.width}x${next.height} vtSize=${w}x${vtHeight}`);let freshPrev=bufferToAnsi(prev,ctx);if(DEBUG_OUTPUT){log2.error?.(`[VERIFY] freshPrev len=${freshPrev.length} incrOutput len=${incrOutput.length}`);let escaped=incrOutput.replace(/\x1b/g,"\\e").replace(/\r/g,"\\r").replace(/\n/g,"\\n");log2.error?.(`[VERIFY] incrOutput: ${escaped.slice(0,500)}`)}let screenIncr=replayAnsiWithStyles(w,vtHeight,freshPrev+incrOutput,ctx),freshNext=bufferToAnsi(next,ctx),screenFresh=replayAnsiWithStyles(w,vtHeight,freshNext,ctx),_dumpRowWideCells=(buf,row)=>{let parts=[];for(let cx=0;cx<buf.width;cx++){let c=buf.getCell(cx,row),cp=c.char?[...c.char].map((ch)=>"U+"+(ch.codePointAt(0)??0).toString(16).toUpperCase().padStart(4,"0")).join(","):"empty";if(c.wide)parts.push(`W@${cx}:${cp}(gw=${outputGraphemeWidth(c.char,ctx)})`);if(c.continuation)parts.push(`C@${cx}`);let charToWrite=c.char||" ",vtWidth=outputGraphemeWidth(charToWrite,ctx),bufWidth=c.wide?2:1;if(!c.continuation&&vtWidth!==bufWidth)parts.push(`MISMATCH@${cx}:${cp}(vtW=${vtWidth},bufW=${bufWidth},tse=${outputTextSizingEnabled(ctx)})`)}return parts.join(" ")};for(let y=0;y<vtHeight;y++)for(let x=0;x<w;x++){let incr=screenIncr[y][x],fresh=screenFresh[y][x];if(incr.char!==fresh.char){let incrRow=screenIncr[y].map((c)=>c.char).join(""),freshRow=screenFresh[y].map((c)=>c.char).join(""),prevRow=screenIncr[y].map((_,cx)=>{return prev.getCell(cx,y).char}).join(""),nextCell=next.getCell(x,y),prevCell=prev.getCell(x,y),contextStart=Math.max(0,x-5),contextEnd=Math.min(w,x+10),colDetails=[];for(let cx=contextStart;cx<contextEnd;cx++){let ic=screenIncr[y][cx],fc=screenFresh[y][cx],pc=prev.getCell(cx,y),nc=next.getCell(cx,y),marker=cx===x?" <<<":ic.char!==fc.char?" !!!":"";colDetails.push(` col ${cx}: prev='${pc.char}'(w=${pc.wide},c=${pc.continuation}) next='${nc.char}' incr='${ic.char}' fresh='${fc.char}' wide=${nc.wide} cont=${nc.continuation}${marker}`)}let msg=`STRICT_OUTPUT char mismatch at (${x},${y}): incremental='${incr.char}' fresh='${fresh.char}'
22
+ `))}if(opts.prev&&opts.ctx&&opts.renderFull){let freshPrev=opts.renderFull(opts.prev,opts.ctx);fs.writeFileSync(path.join(dir,"fresh-prev.ansi"),freshPrev)}return dir}catch{return"(artifact capture failed)"}}function verifyOutputEquivalence(prev,next,incrOutput,ctx,renderFull,graphemeWidthFn,textSizingEnabledFn){let w=Math.max(prev.width,next.width),vtHeight=Math.max(prev.height,next.height);if(DEBUG_OUTPUT)log2.error?.(`[VERIFY] prev=${prev.width}x${prev.height} next=${next.width}x${next.height} vtSize=${w}x${vtHeight}`);let freshPrev=renderFull(prev,ctx);if(DEBUG_OUTPUT){log2.error?.(`[VERIFY] freshPrev len=${freshPrev.length} incrOutput len=${incrOutput.length}`);let escaped=incrOutput.replace(/\x1b/g,"\\e").replace(/\r/g,"\\r").replace(/\n/g,"\\n");log2.error?.(`[VERIFY] incrOutput: ${escaped.slice(0,500)}`)}let screenIncr=replayAnsiWithStyles(w,vtHeight,freshPrev+incrOutput,ctx),freshNext=renderFull(next,ctx),screenFresh=replayAnsiWithStyles(w,vtHeight,freshNext,ctx),_dumpRowWideCells=(buf,row)=>{let parts=[];for(let cx=0;cx<buf.width;cx++){let c=buf.getCell(cx,row),cp=c.char?[...c.char].map((ch)=>"U+"+(ch.codePointAt(0)??0).toString(16).toUpperCase().padStart(4,"0")).join(","):"empty";if(c.wide)parts.push(`W@${cx}:${cp}(gw=${graphemeWidthFn(c.char,ctx)})`);if(c.continuation)parts.push(`C@${cx}`);let charToWrite=c.char||" ",vtWidth=graphemeWidthFn(charToWrite,ctx),bufWidth=c.wide?2:1;if(!c.continuation&&vtWidth!==bufWidth)parts.push(`MISMATCH@${cx}:${cp}(vtW=${vtWidth},bufW=${bufWidth},tse=${textSizingEnabledFn(ctx)})`)}return parts.join(" ")};for(let y=0;y<vtHeight;y++)for(let x=0;x<w;x++){let incr=screenIncr[y][x],fresh=screenFresh[y][x];if(incr.char!==fresh.char){let incrRow=screenIncr[y].map((c)=>c.char).join(""),freshRow=screenFresh[y].map((c)=>c.char).join(""),prevRow=screenIncr[y].map((_,cx)=>{return prev.getCell(cx,y).char}).join(""),nextCell=next.getCell(x,y),prevCell=prev.getCell(x,y),contextStart=Math.max(0,x-5),contextEnd=Math.min(w,x+10),colDetails=[];for(let cx=contextStart;cx<contextEnd;cx++){let ic=screenIncr[y][cx],fc=screenFresh[y][cx],pc=prev.getCell(cx,y),nc=next.getCell(cx,y),marker=cx===x?" <<<":ic.char!==fc.char?" !!!":"";colDetails.push(` col ${cx}: prev='${pc.char}'(w=${pc.wide},c=${pc.continuation}) next='${nc.char}' incr='${ic.char}' fresh='${fc.char}' wide=${nc.wide} cont=${nc.continuation}${marker}`)}let msg=`STRICT_OUTPUT char mismatch at (${x},${y}): incremental='${incr.char}' fresh='${fresh.char}'
42
23
  prev buffer cell: char='${prevCell.char}' bg=${prevCell.bg} wide=${prevCell.wide} cont=${prevCell.continuation}
43
24
  next buffer cell: char='${nextCell.char}' bg=${nextCell.bg} wide=${nextCell.wide} cont=${nextCell.continuation}
44
25
  incr row: ${incrRow}
@@ -48,36 +29,60 @@ Wide/cont cells on row ${y} (next buffer): ${_dumpRowWideCells(next,y)}
48
29
  Wide/cont cells on row ${y} (prev buffer): ${_dumpRowWideCells(prev,y)}
49
30
  Column detail around mismatch:
50
31
  ${colDetails.join(`
51
- `)}`,artifactDir=captureStrictFailureArtifacts({source:"STRICT_OUTPUT",errorMessage:msg,prev,next,incrOutput,freshOutput:freshNext,ctx}),fullMsg=`${msg}
32
+ `)}`,artifactDir=captureStrictFailureArtifacts({source:"STRICT_OUTPUT",errorMessage:msg,prev,next,incrOutput,freshOutput:freshNext,ctx,renderFull}),fullMsg=`${msg}
52
33
  Artifacts: ${artifactDir}`;throw log2.error?.(fullMsg),new IncrementalRenderMismatchError(fullMsg)}let diffs=[];if(!sgrColorEquals(incr.fg,fresh.fg))diffs.push(`fg: ${formatColor(incr.fg)} vs ${formatColor(fresh.fg)}`);if(!sgrColorEquals(incr.bg,fresh.bg))diffs.push(`bg: ${formatColor(incr.bg)} vs ${formatColor(fresh.bg)}`);if(incr.bold!==fresh.bold)diffs.push(`bold: ${incr.bold} vs ${fresh.bold}`);if(incr.dim!==fresh.dim)diffs.push(`dim: ${incr.dim} vs ${fresh.dim}`);if(incr.italic!==fresh.italic)diffs.push(`italic: ${incr.italic} vs ${fresh.italic}`);if(incr.underline!==fresh.underline)diffs.push(`underline: ${incr.underline} vs ${fresh.underline}`);if(incr.inverse!==fresh.inverse)diffs.push(`inverse: ${incr.inverse} vs ${fresh.inverse}`);if(incr.strikethrough!==fresh.strikethrough)diffs.push(`strikethrough: ${incr.strikethrough} vs ${fresh.strikethrough}`);if(diffs.length>0){let msg=`STRICT_OUTPUT style mismatch at (${x},${y}) char='${incr.char}': `+diffs.join(", ")+`
53
34
  incremental: fg=${formatColor(incr.fg)} bg=${formatColor(incr.bg)} bold=${incr.bold} dim=${incr.dim}
54
- fresh: fg=${formatColor(fresh.fg)} bg=${formatColor(fresh.bg)} bold=${fresh.bold} dim=${fresh.dim}`,artifactDir2=captureStrictFailureArtifacts({source:"STRICT_OUTPUT",errorMessage:msg,prev,next,incrOutput,freshOutput:freshNext,ctx});throw new IncrementalRenderMismatchError(`${msg}
55
- Artifacts: ${artifactDir2}`)}}}function verifyAccumulatedOutput(currentBuffer,ctx=defaultContext,accState=defaultAccState){let{mode}=ctx,w=accState.accumulateWidth,h=accState.accumulateHeight,screenAccumulated=replayAnsiWithStyles(w,h,accState.accumulatedAnsi,ctx),freshOutput=bufferToAnsi(currentBuffer,ctx),screenFresh=replayAnsiWithStyles(w,h,freshOutput,ctx);for(let y=0;y<h;y++)for(let x=0;x<w;x++){let accum=screenAccumulated[y][x],fresh=screenFresh[y][x];if(accum.char!==fresh.char){let msg=`SILVERY_STRICT_ACCUMULATE char mismatch at (${x},${y}) after ${accState.accumulateFrameCount} frames: accumulated='${accum.char}' fresh='${fresh.char}'`,dir=captureStrictFailureArtifacts({source:"STRICT_ACCUMULATE",errorMessage:msg,next:currentBuffer,incrOutput:accState.accumulatedAnsi,freshOutput,ctx,frameCount:accState.accumulateFrameCount});throw log2.error?.(`${msg}
35
+ fresh: fg=${formatColor(fresh.fg)} bg=${formatColor(fresh.bg)} bold=${fresh.bold} dim=${fresh.dim}`,artifactDir2=captureStrictFailureArtifacts({source:"STRICT_OUTPUT",errorMessage:msg,prev,next,incrOutput,freshOutput:freshNext,ctx,renderFull});throw new IncrementalRenderMismatchError(`${msg}
36
+ Artifacts: ${artifactDir2}`)}}}function verifyAccumulatedOutput(currentBuffer,ctx,accState,renderFull){let{accumulateWidth:w,accumulateHeight:h}=accState,screenAccumulated=replayAnsiWithStyles(w,h,accState.accumulatedAnsi,ctx),freshOutput=renderFull(currentBuffer,ctx),screenFresh=replayAnsiWithStyles(w,h,freshOutput,ctx);for(let y=0;y<h;y++)for(let x=0;x<w;x++){let accum=screenAccumulated[y][x],fresh=screenFresh[y][x];if(accum.char!==fresh.char){let msg=`SILVERY_STRICT_ACCUMULATE char mismatch at (${x},${y}) after ${accState.accumulateFrameCount} frames: accumulated='${accum.char}' fresh='${fresh.char}'`,dir=captureStrictFailureArtifacts({source:"STRICT_ACCUMULATE",errorMessage:msg,next:currentBuffer,incrOutput:accState.accumulatedAnsi,freshOutput,ctx,frameCount:accState.accumulateFrameCount,renderFull});throw log2.error?.(`${msg}
56
37
  Artifacts: ${dir}`),new IncrementalRenderMismatchError(`${msg}
57
- Artifacts: ${dir}`)}let diffs=[];if(!sgrColorEquals(accum.fg,fresh.fg))diffs.push(`fg: ${formatColor(accum.fg)} vs ${formatColor(fresh.fg)}`);if(!sgrColorEquals(accum.bg,fresh.bg))diffs.push(`bg: ${formatColor(accum.bg)} vs ${formatColor(fresh.bg)}`);if(accum.bold!==fresh.bold)diffs.push(`bold: ${accum.bold} vs ${fresh.bold}`);if(accum.dim!==fresh.dim)diffs.push(`dim: ${accum.dim} vs ${fresh.dim}`);if(accum.italic!==fresh.italic)diffs.push(`italic: ${accum.italic} vs ${fresh.italic}`);if(accum.underline!==fresh.underline)diffs.push(`underline: ${accum.underline} vs ${fresh.underline}`);if(accum.inverse!==fresh.inverse)diffs.push(`inverse: ${accum.inverse} vs ${fresh.inverse}`);if(accum.strikethrough!==fresh.strikethrough)diffs.push(`strikethrough: ${accum.strikethrough} vs ${fresh.strikethrough}`);if(diffs.length>0){let msg=`SILVERY_STRICT_ACCUMULATE style mismatch at (${x},${y}) char='${accum.char}' after ${accState.accumulateFrameCount} frames: `+diffs.join(", "),dir2=captureStrictFailureArtifacts({source:"STRICT_ACCUMULATE",errorMessage:msg,next:currentBuffer,freshOutput,ctx,frameCount:accState.accumulateFrameCount});throw log2.error?.(`${msg}
38
+ Artifacts: ${dir}`)}let diffs=[];if(!sgrColorEquals(accum.fg,fresh.fg))diffs.push(`fg: ${formatColor(accum.fg)} vs ${formatColor(fresh.fg)}`);if(!sgrColorEquals(accum.bg,fresh.bg))diffs.push(`bg: ${formatColor(accum.bg)} vs ${formatColor(fresh.bg)}`);if(accum.bold!==fresh.bold)diffs.push(`bold: ${accum.bold} vs ${fresh.bold}`);if(accum.dim!==fresh.dim)diffs.push(`dim: ${accum.dim} vs ${fresh.dim}`);if(accum.italic!==fresh.italic)diffs.push(`italic: ${accum.italic} vs ${fresh.italic}`);if(accum.underline!==fresh.underline)diffs.push(`underline: ${accum.underline} vs ${fresh.underline}`);if(accum.inverse!==fresh.inverse)diffs.push(`inverse: ${accum.inverse} vs ${fresh.inverse}`);if(accum.strikethrough!==fresh.strikethrough)diffs.push(`strikethrough: ${accum.strikethrough} vs ${fresh.strikethrough}`);if(diffs.length>0){let msg=`SILVERY_STRICT_ACCUMULATE style mismatch at (${x},${y}) char='${accum.char}' after ${accState.accumulateFrameCount} frames: `+diffs.join(", "),dir2=captureStrictFailureArtifacts({source:"STRICT_ACCUMULATE",errorMessage:msg,next:currentBuffer,freshOutput,ctx,frameCount:accState.accumulateFrameCount,renderFull});throw log2.error?.(`${msg}
58
39
  Artifacts: ${dir2}`),new IncrementalRenderMismatchError(`${msg}
59
- Artifacts: ${dir2}`)}}}function loadTermless(){if(!_createTerminal||!_createXtermBackend)_createTerminal=__require("@termless/core").createTerminal,_createXtermBackend=__require("@termless/xtermjs").createXtermBackend;return{createTerminal:_createTerminal,createXtermBackend:_createXtermBackend}}function loadGhosttyBackend(){if(!_createGhosttyBackend){let mod=__require("@termless/ghostty");if(_createGhosttyBackend=mod.createGhosttyBackend,!_ghosttyInitPromise)_ghosttyInitPromise=mod.initGhostty()}return _createGhosttyBackend}function initTerminalVerifyState(state,width,height,initialAnsi){if(state.terminal)state.terminal.close();if(state.ghosttyTerminal)state.ghosttyTerminal.close();if(state.backends.includes("xterm")){let{createTerminal,createXtermBackend}=loadTermless();state.terminal=createTerminal({backend:createXtermBackend(),cols:width,rows:height}),state.terminal.feed(initialAnsi)}else state.terminal=null;if(state.backends.includes("ghostty")){let{createTerminal}=loadTermless(),createGhostty=loadGhosttyBackend();state.ghosttyTerminal=createTerminal({backend:createGhostty(),cols:width,rows:height}),state.ghosttyTerminal.feed(initialAnsi)}else state.ghosttyTerminal=null;state.width=width,state.height=height,state.frameCount=0}function verifyTerminalEquivalence(state,incrOutput,nextBuffer,ctx){if(nextBuffer.width!==state.width||nextBuffer.height!==state.height){let freshAnsi2=bufferToAnsi(nextBuffer,ctx);initTerminalVerifyState(state,nextBuffer.width,nextBuffer.height,freshAnsi2),state.frameCount++;return}let freshAnsi=bufferToAnsi(nextBuffer,ctx);if(state.terminal){state.terminal.feed(incrOutput);let{createTerminal,createXtermBackend}=loadTermless(),freshTerm=createTerminal({backend:createXtermBackend(),cols:state.width,rows:state.height});freshTerm.feed(freshAnsi);try{compareTerminals(state.terminal,freshTerm,state,"xterm")}catch(e){if(e instanceof IncrementalRenderMismatchError){let dir=captureStrictFailureArtifacts({source:"STRICT_TERMINAL[xterm]",errorMessage:e.message,next:nextBuffer,incrOutput,freshOutput:freshAnsi,ctx,frameCount:state.frameCount});throw new IncrementalRenderMismatchError(`${e.message}
60
- Artifacts: ${dir}`)}throw e}finally{freshTerm.close()}}if(state.ghosttyTerminal){state.ghosttyTerminal.feed(incrOutput);let{createTerminal}=loadTermless(),createGhostty=loadGhosttyBackend(),freshTerm=createTerminal({backend:createGhostty(),cols:state.width,rows:state.height});freshTerm.feed(freshAnsi);try{compareTerminals(state.ghosttyTerminal,freshTerm,state,"ghostty")}catch(e){if(e instanceof IncrementalRenderMismatchError){let dir=captureStrictFailureArtifacts({source:"STRICT_TERMINAL[ghostty]",errorMessage:e.message,next:nextBuffer,incrOutput,freshOutput:freshAnsi,ctx,frameCount:state.frameCount});throw new IncrementalRenderMismatchError(`${e.message}
40
+ Artifacts: ${dir2}`)}}}function loadTermless(){if(!_createTerminal||!_createXtermBackend)_createTerminal=__require("@termless/core").createTerminal,_createXtermBackend=__require("@termless/xtermjs").createXtermBackend;return{createTerminal:_createTerminal,createXtermBackend:_createXtermBackend}}function loadGhosttyBackend(){if(!_createGhosttyBackend){let mod=__require("@termless/ghostty");if(_createGhosttyBackend=mod.createGhosttyBackend,!_ghosttyInitPromise)_ghosttyInitPromise=mod.initGhostty()}return _createGhosttyBackend}function initTerminalVerifyState(state,width,height,initialAnsi){if(state.terminal)state.terminal.close();if(state.ghosttyTerminal)state.ghosttyTerminal.close();if(state.backends.includes("xterm")){let{createTerminal,createXtermBackend}=loadTermless();state.terminal=createTerminal({backend:createXtermBackend(),cols:width,rows:height}),state.terminal.feed(initialAnsi)}else state.terminal=null;if(state.backends.includes("ghostty")){let{createTerminal}=loadTermless(),createGhostty=loadGhosttyBackend();state.ghosttyTerminal=createTerminal({backend:createGhostty(),cols:width,rows:height}),state.ghosttyTerminal.feed(initialAnsi)}else state.ghosttyTerminal=null;state.width=width,state.height=height,state.frameCount=0}function verifyTerminalEquivalence(state,incrOutput,nextBuffer,ctx,renderFull){if(nextBuffer.width!==state.width||nextBuffer.height!==state.height){let freshAnsi2=renderFull(nextBuffer,ctx);initTerminalVerifyState(state,nextBuffer.width,nextBuffer.height,freshAnsi2),state.frameCount++;return}let freshAnsi=renderFull(nextBuffer,ctx);if(state.terminal){state.terminal.feed(incrOutput);let{createTerminal,createXtermBackend}=loadTermless(),freshTerm=createTerminal({backend:createXtermBackend(),cols:state.width,rows:state.height});freshTerm.feed(freshAnsi);try{compareTerminals(state.terminal,freshTerm,state,"xterm")}catch(e){if(e instanceof IncrementalRenderMismatchError){let dir=captureStrictFailureArtifacts({source:"STRICT_TERMINAL[xterm]",errorMessage:e.message,next:nextBuffer,incrOutput,freshOutput:freshAnsi,ctx,frameCount:state.frameCount,renderFull});throw new IncrementalRenderMismatchError(`${e.message}
41
+ Artifacts: ${dir}`)}throw e}finally{freshTerm.close()}}if(state.ghosttyTerminal){state.ghosttyTerminal.feed(incrOutput);let{createTerminal}=loadTermless(),createGhostty=loadGhosttyBackend(),freshTerm=createTerminal({backend:createGhostty(),cols:state.width,rows:state.height});freshTerm.feed(freshAnsi);try{compareTerminals(state.ghosttyTerminal,freshTerm,state,"ghostty")}catch(e){if(e instanceof IncrementalRenderMismatchError){let dir=captureStrictFailureArtifacts({source:"STRICT_TERMINAL[ghostty]",errorMessage:e.message,next:nextBuffer,incrOutput,freshOutput:freshAnsi,ctx,frameCount:state.frameCount,renderFull});throw new IncrementalRenderMismatchError(`${e.message}
61
42
  Artifacts: ${dir}`)}throw e}finally{freshTerm.close()}}}function compareTerminals(incrTerm,freshTerm,state,backendName){let{width:w,height:h}=state,prefix=`SILVERY_STRICT_TERMINAL[${backendName}]`;for(let y=0;y<h;y++)for(let x=0;x<w;x++){let incrCell=incrTerm.getCell(y,x),freshCell=freshTerm.getCell(y,x),incrChar=incrCell.char||" ",freshChar=freshCell.char||" ";if(incrChar!==freshChar){let incrRow=Array.from({length:w},(_,cx)=>incrTerm.getCell(y,cx).char||" ").join(""),freshRow=Array.from({length:w},(_,cx)=>freshTerm.getCell(y,cx).char||" ").join(""),msg=`${prefix} char mismatch at (${x},${y}) frame ${state.frameCount}: incremental='${incrChar}' fresh='${freshChar}'
62
43
  incr row: ${incrRow.trimEnd()}
63
- fresh row: ${freshRow.trimEnd()}`;throw log2.error?.(msg),new IncrementalRenderMismatchError(msg)}if(!rgbEquals(incrCell.fg,freshCell.fg)){let msg=`${prefix} fg color mismatch at (${x},${y}) char='${incrChar}' frame ${state.frameCount}: incremental=${formatRgb(incrCell.fg)} fresh=${formatRgb(freshCell.fg)}`;throw log2.error?.(msg),new IncrementalRenderMismatchError(msg)}if(!rgbEquals(incrCell.bg,freshCell.bg)){let msg=`${prefix} bg color mismatch at (${x},${y}) char='${incrChar}' frame ${state.frameCount}: incremental=${formatRgb(incrCell.bg)} fresh=${formatRgb(freshCell.bg)}`;throw log2.error?.(msg),new IncrementalRenderMismatchError(msg)}let attrDiffs=[];if(incrCell.bold!==freshCell.bold)attrDiffs.push(`bold: ${incrCell.bold} vs ${freshCell.bold}`);if(incrCell.dim!==freshCell.dim)attrDiffs.push(`dim: ${incrCell.dim} vs ${freshCell.dim}`);if(incrCell.italic!==freshCell.italic)attrDiffs.push(`italic: ${incrCell.italic} vs ${freshCell.italic}`);if(incrCell.inverse!==freshCell.inverse)attrDiffs.push(`inverse: ${incrCell.inverse} vs ${freshCell.inverse}`);if(incrCell.strikethrough!==freshCell.strikethrough)attrDiffs.push(`strikethrough: ${incrCell.strikethrough} vs ${freshCell.strikethrough}`);if(attrDiffs.length>0){let msg=`${prefix} attr mismatch at (${x},${y}) char='${incrChar}' frame ${state.frameCount}: `+attrDiffs.join(", ");throw log2.error?.(msg),new IncrementalRenderMismatchError(msg)}}}function rgbEquals(a,b){if(a===b)return!0;if(a===null||b===null)return!1;return a.r===b.r&&a.g===b.g&&a.b===b.b}function formatRgb(c){if(c===null)return"null";return`rgb(${c.r},${c.g},${c.b})`}function sgrColorEquals(a,b){if(a===b)return!0;if(a===null||b===null)return!1;if(typeof a==="number"||typeof b==="number")return a===b;return a.r===b.r&&a.g===b.g&&a.b===b.b}var log2,_env,DEBUG_OUTPUT,FULL_RENDER,DEBUG_CAPTURE,CAPTURE_RAW,_debugFrameCount=0,_captureRawFrameCount=0,defaultContext,defaultAccState,defaultTerminalVerifyState,reusableCellStyle,wideCharLookupCell,_createTerminal=null,_createXtermBackend=null,_createGhosttyBackend=null,_ghosttyInitPromise=null;var init_output_phase=__esm(()=>{init_buffer();init_sgr_codes();init_errors();init_text_sizing();init_unicode();init_diff_buffers();log2=createLogger2("silvery:output"),_env=typeof process<"u"?process.env:{},DEBUG_OUTPUT=!!_env.SILVERY_DEBUG_OUTPUT,FULL_RENDER=!!_env.SILVERY_FULL_RENDER,DEBUG_CAPTURE=!!_env.SILVERY_DEBUG_CAPTURE,CAPTURE_RAW=!!_env.SILVERY_CAPTURE_RAW,defaultContext={caps:{underlineStyles:!0,underlineColor:!0,colorLevel:"truecolor"},measurer:null,sgrCache:new Map,transitionCache:new Map,mode:"fullscreen",termRows:void 0};defaultAccState={accumulatedAnsi:"",accumulateWidth:0,accumulateHeight:0,accumulateFrameCount:0};defaultTerminalVerifyState=createTerminalVerifyState();reusableCellStyle={fg:null,bg:null,underlineColor:null,attrs:{}},wideCharLookupCell=createMutableCell()});var init_detection2=__esm(()=>{init_src2();init_src2()});function stripAnsi3(text){return text.replace(ANSI_REGEX2,"")}function parseInputEvents(data){let events=[],pasteResult=parseBracketedPaste(data);if(pasteResult)events.push({type:"paste",data:{text:pasteResult.content}});else for(let raw of splitRawInput(data)){let focusEvent=parseFocusEvent(raw);if(focusEvent){events.push({type:"focus",data:{focused:focusEvent.type==="focus-in"}});continue}if(isMouseSequence(raw)){let parsed=parseMouseSequence(raw);if(parsed)events.push({type:"mouse",data:parsed});continue}let[input,key]=parseKey(raw);events.push({type:"key",data:{input,key}})}return events}function createEventQueue(controller){let queue=[],resolve=null,disposed=!1;function push(...events2){if(queue.push(...events2),resolve){let r=resolve;resolve=null,r()}}async function*events(){if(disposed)return;while(!disposed&&!controller.signal.aborted){if(queue.length===0)await new Promise((r)=>{resolve=r,controller.signal.addEventListener("abort",()=>r(),{once:!0})});if(disposed||controller.signal.aborted)break;while(queue.length>0)yield queue.shift()}}return{push,events,dispose(){disposed=!0}}}function createEmulatorStdout(feed,cols,rows){let resizeListeners=new Set,stdout={write:(data)=>{return feed(typeof data==="string"?data:new TextDecoder().decode(data)),!0},on:(event,handler)=>{if(event==="resize")resizeListeners.add(handler)},off:(event,handler)=>{if(event==="resize")resizeListeners.delete(handler)},isTTY:!0,columns:cols,rows};return{stdout,resizeListeners,updateDims(c,r){stdout.columns=c,stdout.rows=r}}}function finalizeTerm(style2,termBase,frame,opts){if(Object.defineProperty(termBase,"frame",{get:frame.get,enumerable:!0}),opts?.defineProperties)Object.defineProperties(termBase,opts.defineProperties);if(opts?.delegateFrom)for(let key of Object.keys(opts.delegateFrom)){if(key in termBase)continue;let val=opts.delegateFrom[key];Object.defineProperty(termBase,key,typeof val==="function"?{value:(...args)=>opts.delegateFrom[key](...args)}:{get:()=>opts.delegateFrom[key]})}return createMixedStyle(style2,termBase)}function createTerm(first,second){if(second&&first&&isTermBackend(first)){let{createTerminal}=__require("@termless/core"),emulator=createTerminal({backend:first,...second});return createBackendTerm(emulator)}if(first&&isTermEmulator(first))return createBackendTerm(first);if(first&&isHeadlessDims(first))return createHeadlessTerm(first);return createNodeTerm(first??{})}function isTermEmulator(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;return typeof o.feed==="function"&&typeof o.screen==="object"&&o.screen!==null}function isTermBackend(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;return typeof o.init==="function"&&typeof o.name==="string"&&typeof o.destroy==="function"}function isHeadlessDims(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;return typeof o.cols==="number"&&typeof o.rows==="number"&&!("stdout"in o)&&!("stdin"in o)}function createNodeTerm(options){let stdout=options.stdout??process.stdout,stdin=options.stdin??process.stdin,cachedCursor=options.cursor??detectCursor(stdout),cachedInput=detectInput(stdin),cachedColor=options.color!==void 0?options.color:detectColor(stdout),cachedUnicode=options.unicode??detectUnicode(),detectedCaps=options.caps?{...defaultCaps(),...options.caps}:stdin.isTTY?detectTerminalCaps():void 0,styleInstance=createStyle({level:cachedColor}),provider=null,getProvider=()=>{if(!provider)provider=createTermProvider(stdin,stdout,{cols:stdout.columns||80,rows:stdout.rows||24});return provider},_frame,termBase={hasCursor:()=>cachedCursor,hasInput:()=>cachedInput,hasColor:()=>cachedColor,hasUnicode:()=>cachedUnicode,caps:detectedCaps,stdout,stdin,write:(str)=>{stdout.write(str)},writeLine:(str)=>{stdout.write(str+`
44
+ fresh row: ${freshRow.trimEnd()}`;throw log2.error?.(msg),new IncrementalRenderMismatchError(msg)}if(!rgbEquals(incrCell.fg,freshCell.fg)){let msg=`${prefix} fg color mismatch at (${x},${y}) char='${incrChar}' frame ${state.frameCount}: incremental=${formatRgb(incrCell.fg)} fresh=${formatRgb(freshCell.fg)}`;throw log2.error?.(msg),new IncrementalRenderMismatchError(msg)}if(!rgbEquals(incrCell.bg,freshCell.bg)){let msg=`${prefix} bg color mismatch at (${x},${y}) char='${incrChar}' frame ${state.frameCount}: incremental=${formatRgb(incrCell.bg)} fresh=${formatRgb(freshCell.bg)}`;throw log2.error?.(msg),new IncrementalRenderMismatchError(msg)}let attrDiffs=[];if(incrCell.bold!==freshCell.bold)attrDiffs.push(`bold: ${incrCell.bold} vs ${freshCell.bold}`);if(incrCell.dim!==freshCell.dim)attrDiffs.push(`dim: ${incrCell.dim} vs ${freshCell.dim}`);if(incrCell.italic!==freshCell.italic)attrDiffs.push(`italic: ${incrCell.italic} vs ${freshCell.italic}`);if(incrCell.inverse!==freshCell.inverse)attrDiffs.push(`inverse: ${incrCell.inverse} vs ${freshCell.inverse}`);if(incrCell.strikethrough!==freshCell.strikethrough)attrDiffs.push(`strikethrough: ${incrCell.strikethrough} vs ${freshCell.strikethrough}`);if(attrDiffs.length>0){let msg=`${prefix} attr mismatch at (${x},${y}) char='${incrChar}' frame ${state.frameCount}: `+attrDiffs.join(", ");throw log2.error?.(msg),new IncrementalRenderMismatchError(msg)}}}function rgbEquals(a,b){if(a===b)return!0;if(a===null||b===null)return!1;return a.r===b.r&&a.g===b.g&&a.b===b.b}function formatRgb(c){if(c===null)return"null";return`rgb(${c.r},${c.g},${c.b})`}function sgrColorEquals(a,b){if(a===b)return!0;if(a===null||b===null)return!1;if(typeof a==="number"||typeof b==="number")return a===b;return a.r===b.r&&a.g===b.g&&a.b===b.b}var log2,_env,DEBUG_OUTPUT,_defaultCtxForReplay,_createTerminal=null,_createXtermBackend=null,_createGhosttyBackend=null,_ghosttyInitPromise=null;var init_output_verify=__esm(()=>{init_errors();init_unicode();log2=createLogger2("silvery:output"),_env=typeof process<"u"?process.env:{},DEBUG_OUTPUT=!!_env.SILVERY_DEBUG_OUTPUT;_defaultCtxForReplay={caps:{underlineStyles:!0,underlineColor:!0,colorLevel:"truecolor"},measurer:null,sgrCache:new Map,transitionCache:new Map,mode:"fullscreen",termRows:void 0}});function createEmptyCellChange(){return{x:0,y:0,cell:{char:" ",fg:null,bg:null,underlineColor:null,attrs:{},wide:!1,continuation:!1,hyperlink:void 0}}}function ensureDiffPoolCapacity(capacity){if(capacity<=diffPoolCapacity)return;for(let i=diffPoolCapacity;i<capacity;i++)diffPool.push(createEmptyCellChange());diffPoolCapacity=capacity}function writeCellChange(change,x,y,buffer){change.x=x,change.y=y,buffer.readCellInto(x,y,change.cell)}function writeEmptyCellChange(change,x,y){change.x=x,change.y=y;let cell=change.cell;cell.char=" ",cell.fg=null,cell.bg=null,cell.underlineColor=null;let attrs=cell.attrs;attrs.bold=void 0,attrs.dim=void 0,attrs.italic=void 0,attrs.underline=void 0,attrs.underlineStyle=void 0,attrs.blink=void 0,attrs.inverse=void 0,attrs.hidden=void 0,attrs.strikethrough=void 0,cell.wide=!1,cell.continuation=!1,cell.hyperlink=void 0}function diffBuffers(prev,next){let cells=Math.max(prev.width,next.width)*Math.max(prev.height,next.height),maxChanges=cells+(cells>>1);ensureDiffPoolCapacity(maxChanges);let changeCount=0,height=Math.min(prev.height,next.height),width=Math.min(prev.width,next.width),startRow=next.minDirtyRow===-1?0:next.minDirtyRow,endRow=next.maxDirtyRow===-1?-1:Math.min(next.maxDirtyRow,height-1);for(let y=startRow;y<=endRow;y++){if(!next.isRowDirty(y))continue;if(next.rowMetadataEquals(y,prev)&&next.rowCharsEquals(y,prev)&&next.rowExtrasEquals(y,prev))continue;for(let x=0;x<width;x++)if(!next.cellEquals(x,y,prev)){if(writeCellChange(diffPool[changeCount],x,y,next),changeCount++,x+1<width&&prev.isCellWide(x,y)&&!next.isCellWide(x,y))writeCellChange(diffPool[changeCount],x+1,y,next),changeCount++}}let widthGrew=next.width>prev.width;if(widthGrew)for(let y=0;y<next.height;y++)for(let x=prev.width;x<next.width;x++)writeCellChange(diffPool[changeCount],x,y,next),changeCount++;if(next.height>prev.height){let xEnd=widthGrew?prev.width:next.width;for(let y=prev.height;y<next.height;y++)for(let x=0;x<xEnd;x++)writeCellChange(diffPool[changeCount],x,y,next),changeCount++}if(prev.width>next.width)for(let y=0;y<height;y++)for(let x=next.width;x<prev.width;x++)writeEmptyCellChange(diffPool[changeCount],x,y),changeCount++;if(prev.height>next.height)for(let y=next.height;y<prev.height;y++)for(let x=0;x<prev.width;x++)writeEmptyCellChange(diffPool[changeCount],x,y),changeCount++;if(changeCount>maxChanges)throw Error(`diffBuffers: changeCount ${changeCount} exceeds pool capacity ${maxChanges} (prev ${prev.width}x${prev.height}, next ${next.width}x${next.height})`);return diffResult.pool=diffPool,diffResult.count=changeCount,diffResult}var diffPool,diffPoolCapacity=0,diffResult;var init_diff_buffers=__esm(()=>{diffPool=[];diffResult={pool:diffPool,count:0}});import{createLogger as createLogger3}from"loggily";function outputGraphemeWidth(g,ctx){return ctx.measurer?ctx.measurer.graphemeWidth(g):graphemeWidth(g)}function outputTextSizingEnabled(ctx){return ctx.measurer?ctx.measurer.textSizingEnabled:isTextSizingEnabled()}function createOutputPhase(caps,measurer){let ctx={caps:{underlineStyles:caps.underlineStyles??!0,underlineColor:caps.underlineColor??!0,colorLevel:caps.colorLevel??"truecolor"},measurer:measurer??null,sgrCache:new Map,transitionCache:new Map,mode:"fullscreen",termRows:void 0},inlineState=createInlineCursorState(),accState={accumulatedAnsi:"",accumulateWidth:0,accumulateHeight:0,accumulateFrameCount:0},tvState=createTerminalVerifyState(),pendingPromotion=null,fn=function(prev,next,mode="fullscreen",scrollbackOffset=0,termRows,cursorPos){if(ctx.mode=mode,ctx.termRows=termRows,pendingPromotion&&mode==="inline"){let promo=pendingPromotion;return pendingPromotion=null,handleScrollbackPromotion(inlineState,promo.frozenContent,promo.frozenLineCount,next,cursorPos,ctx)}return outputPhase(prev,next,mode,scrollbackOffset,termRows,cursorPos,inlineState,ctx,accState,tvState)};return fn.resetInlineState=()=>{Object.assign(inlineState,createInlineCursorState()),inlineState.forceFirstRender=!0,pendingPromotion=null},fn.getInlineCursorRow=()=>inlineState.prevCursorRow,fn.promoteScrollback=(frozenContent,frozenLineCount)=>{if(pendingPromotion)pendingPromotion.frozenContent+=frozenContent,pendingPromotion.frozenLineCount+=frozenLineCount;else pendingPromotion={frozenContent,frozenLineCount}},fn}function handleScrollbackPromotion(state,frozenContent,frozenLineCount,next,cursorPos,ctx){let{termRows}=ctx,output="";if(state.prevCursorRow>0)output+=`\x1B[${state.prevCursorRow}A`;output+="\r",output+=frozenContent;let nextContentLines=findLastContentLine(next)+1,maxOutputLines=termRows!=null?Math.min(nextContentLines,termRows):nextContentLines;output+=bufferToAnsi(next,ctx,maxOutputLines);let totalOnScreen=frozenLineCount+maxOutputLines,oldTotalLines=state.prevOutputLines,nextLastLine=totalOnScreen-1,terminalScroll=termRows!=null?Math.max(0,totalOnScreen-termRows):0,lastOccupied=Math.max(oldTotalLines-1-terminalScroll,0);if(lastOccupied>nextLastLine){for(let y=nextLastLine+1;y<=lastOccupied;y++)output+=`
45
+ \r\x1B[K`;let up=lastOccupied-nextLastLine;if(up>0)output+=`\x1B[${up}A`}output+=inlineCursorSuffix(cursorPos??null,next,ctx);let startLine=0;if(termRows!=null&&nextContentLines>termRows)startLine=nextContentLines-termRows;if(state.prevBuffer=next,cursorPos?.visible){let visibleRow=cursorPos.y-startLine;state.prevCursorRow=visibleRow>=0&&visibleRow<maxOutputLines?visibleRow:maxOutputLines-1}else state.prevCursorRow=maxOutputLines-1;return state.prevOutputLines=maxOutputLines,output}function isStrictOutput(){if(typeof process>"u")return!1;let val=process.env.SILVERY_STRICT;return!!val&&val!=="0"&&val!=="false"}function isStrictAccumulate(){if(typeof process>"u")return!1;let val=process.env.SILVERY_STRICT_ACCUMULATE;return!!val&&val!=="0"&&val!=="false"}function createInlineCursorState(){return{prevCursorRow:-1,prevOutputLines:0,prevBuffer:null,forceFirstRender:!1}}function updateInlineCursorRow(state,cursorPos,maxOutputLines,startLine){if(cursorPos?.visible){let visibleRow=cursorPos.y-startLine;state.prevCursorRow=visibleRow>=0&&visibleRow<maxOutputLines?visibleRow:maxOutputLines-1}else state.prevCursorRow=maxOutputLines-1;state.prevOutputLines=maxOutputLines}function wrapTextSizing(char,wide,ctx){if(!wide||!outputTextSizingEnabled(ctx))return char;return textSized(char,2)}function styleToKey(style2){let{fg,bg,attrs}=style2,key="";if(fg===null)key="n";else if(typeof fg==="number")key=`${fg}`;else key=`r${fg.r},${fg.g},${fg.b}`;if(key+="|",bg===null)key+="n";else if(typeof bg==="number")key+=`${bg}`;else key+=`r${bg.r},${bg.g},${bg.b}`;let attrBits=0;if(attrs.bold)attrBits|=1;if(attrs.dim)attrBits|=2;if(attrs.italic)attrBits|=4;if(attrs.underline)attrBits|=8;if(attrs.inverse)attrBits|=16;if(attrs.strikethrough)attrBits|=32;if(attrs.blink)attrBits|=64;if(attrs.hidden)attrBits|=128;if(key+=`|${attrBits}`,attrs.underlineStyle)key+=`|u${attrs.underlineStyle}`;let ul=style2.underlineColor;if(ul!==null&&ul!==void 0)if(typeof ul==="number")key+=`|l${ul}`;else key+=`|lr${ul.r},${ul.g},${ul.b}`;if(style2.hyperlink)key+=`|h${style2.hyperlink}`;return key}function cachedStyleToAnsi(style2,ctx){let key=styleToKey(style2),sgr=ctx.sgrCache.get(key);if(sgr!==void 0)return sgr;if(sgr=styleToAnsi(style2,ctx),ctx.sgrCache.set(key,sgr),ctx.sgrCache.size>1000)ctx.sgrCache.clear();return sgr}function styleTransition(oldStyle,newStyle,ctx){if(!oldStyle)return cachedStyleToAnsi(newStyle,ctx);if(styleEquals(oldStyle,newStyle))return"";let oldKey=styleToKey(oldStyle),newKey=styleToKey(newStyle),cacheKey=`${oldKey}\x00${newKey}`,cached=ctx.transitionCache.get(cacheKey);if(cached!==void 0)return cached;let codes=[],oa=oldStyle.attrs,na=newStyle.attrs,boldChanged=Boolean(oa.bold)!==Boolean(na.bold),dimChanged=Boolean(oa.dim)!==Boolean(na.dim);if(boldChanged||dimChanged){let boldOff=boldChanged&&!na.bold,dimOff=dimChanged&&!na.dim;if(boldOff||dimOff){if(codes.push("22"),na.bold)codes.push("1");if(na.dim)codes.push("2")}else{if(boldChanged&&na.bold)codes.push("1");if(dimChanged&&na.dim)codes.push("2")}}if(Boolean(oa.italic)!==Boolean(na.italic))codes.push(na.italic?"3":"23");let oldUl=Boolean(oa.underline),newUl=Boolean(na.underline),oldUlStyle=oa.underlineStyle??!1,newUlStyle=na.underlineStyle??!1;if(oldUl!==newUl||oldUlStyle!==newUlStyle)if(!ctx.caps.underlineStyles)codes.push(newUl||na.underlineStyle?"4":"24");else{let sgrSub=underlineStyleToSgr(na.underlineStyle);if(sgrSub!==null&&sgrSub!==0)codes.push(`4:${sgrSub}`);else if(newUl)codes.push("4");else codes.push("24")}if(Boolean(oa.inverse)!==Boolean(na.inverse))codes.push(na.inverse?"7":"27");if(Boolean(oa.hidden)!==Boolean(na.hidden))codes.push(na.hidden?"8":"28");if(Boolean(oa.strikethrough)!==Boolean(na.strikethrough))codes.push(na.strikethrough?"9":"29");if(Boolean(oa.blink)!==Boolean(na.blink))codes.push(na.blink?"5":"25");if(!colorEquals(oldStyle.fg,newStyle.fg))if(newStyle.fg===null)codes.push("39");else codes.push(fgColorCode(newStyle.fg));if(!colorEquals(oldStyle.bg,newStyle.bg))if(newStyle.bg===null)codes.push("49");else codes.push(bgColorCode(newStyle.bg));if(ctx.caps.underlineColor&&!colorEquals(oldStyle.underlineColor,newStyle.underlineColor))if(newStyle.underlineColor===null||newStyle.underlineColor===void 0)codes.push("59");else if(typeof newStyle.underlineColor==="number")codes.push(`58;5;${newStyle.underlineColor}`);else codes.push(`58;2;${newStyle.underlineColor.r};${newStyle.underlineColor.g};${newStyle.underlineColor.b}`);let result;if(codes.length===0)result=cachedStyleToAnsi(newStyle,ctx);else result=`\x1B[${codes.join(";")}m`;if(ctx.transitionCache.set(cacheKey,result),ctx.transitionCache.size>1000)ctx.transitionCache.clear();return result}function underlineStyleToSgr(style2){switch(style2){case!1:return 0;case"single":return 1;case"double":return 2;case"curly":return 3;case"dotted":return 4;case"dashed":return 5;default:return null}}function outputPhase(prev,next,mode="fullscreen",scrollbackOffset=0,termRows,cursorPos,_inlineState,_ctx,_accState,_tvState){let inlineState=_inlineState??createInlineCursorState(),ctx=_ctx??defaultContext,accState=_accState??defaultAccState;ctx.mode=mode,ctx.termRows=termRows;let tvState=_tvState??defaultTerminalVerifyState;if(mode==="inline"&&inlineState.forceFirstRender)inlineState.forceFirstRender=!1,prev=null;if(!prev){let fullRenderAcc=globalThis.__silvery_bench_output_detail;if(fullRenderAcc)fullRenderAcc.fullRenderCalls=(fullRenderAcc.fullRenderCalls??0)+1,fullRenderAcc.fullRenderCells=(fullRenderAcc.fullRenderCells??0)+next.width*next.height;if(mode==="inline"&&inlineState.prevBuffer&&inlineState.prevCursorRow>=0){let stored=inlineState.prevBuffer;if(stored.width===next.width&&stored.height===next.height)return inlineState.prevBuffer=next,inlineIncrementalRender(inlineState,stored,next,scrollbackOffset,cursorPos,ctx,tvState)}let tFullStart=performance.now(),firstOutput=bufferToAnsi(next,ctx,termRows),tFullEnd=performance.now();if(fullRenderAcc)fullRenderAcc.fullRenderMs=(fullRenderAcc.fullRenderMs??0)+(tFullEnd-tFullStart),fullRenderAcc.fullRenderBytes=(fullRenderAcc.fullRenderBytes??0)+firstOutput.length;if(mode==="inline"){let firstContentLines=findLastContentLine(next)+1,firstMaxOutput=termRows!=null?Math.min(firstContentLines,termRows):firstContentLines,firstStartLine=0;if(termRows!=null&&firstContentLines>termRows)firstStartLine=firstContentLines-termRows;let prefix="";if(inlineState.prevCursorRow>=0){let clearDistance=termRows??Math.max(inlineState.prevCursorRow,inlineState.prevOutputLines-1);if(clearDistance>0)prefix+=`\x1B[${clearDistance}A`;prefix+="\r\x1B[J"}return inlineState.prevBuffer=next,updateInlineCursorRow(inlineState,cursorPos,firstMaxOutput,firstStartLine),prefix+firstOutput+inlineCursorSuffix(cursorPos??null,next,ctx)}if(isStrictAccumulate())accState.accumulatedAnsi=firstOutput,accState.accumulateWidth=next.width,accState.accumulateHeight=next.height,accState.accumulateFrameCount=0;if(tvState.backends.length>0)initTerminalVerifyState(tvState,next.width,next.height,firstOutput);if(CAPTURE_RAW)try{let fs=__require("fs");_captureRawFrameCount=0,fs.writeFileSync("/tmp/silvery-raw.ansi",firstOutput),fs.writeFileSync("/tmp/silvery-raw-frames.jsonl",JSON.stringify({frame:0,type:"full",bytes:firstOutput.length,width:next.width,height:next.height})+`
46
+ `)}catch{}return firstOutput}if(mode==="inline")return inlineState.prevBuffer=next,inlineIncrementalRender(inlineState,prev,next,scrollbackOffset,cursorPos,ctx,tvState);if(FULL_RENDER)return bufferToAnsi(next,ctx,termRows);if(prev.width!==next.width||prev.height!==next.height)return bufferToAnsi(next,ctx,termRows);let tDiff0=performance.now(),{pool,count:rawCount}=diffBuffers(prev,next),tDiff1=performance.now(),count=rawCount;if(termRows!=null){let writeIdx=0;for(let i=0;i<rawCount;i++)if(pool[i].y<termRows)pool[writeIdx++]=pool[i];count=writeIdx}if(DEBUG_OUTPUT2){log3.error?.(`diffBuffers: ${count} changes${rawCount!==count?` (${rawCount-count} clamped beyond termRows)`:""}`);let debugLimit=Math.min(count,10);for(let i=0;i<debugLimit;i++){let change=pool[i];log3.error?.(` (${change.x},${change.y}): "${change.cell.char}"`)}if(count>10)log3.error?.(` ... and ${count-10} more`)}if(count===0){let acc=globalThis.__silvery_bench_output_detail;if(acc)acc.diffMs+=tDiff1-tDiff0,acc.calls+=1;return""}let tAnsi0=performance.now(),incrOutput=changesToAnsi(pool,count,ctx,next).output,tAnsi1=performance.now(),outputDetailAcc=globalThis.__silvery_bench_output_detail;if(outputDetailAcc){outputDetailAcc.diffMs+=tDiff1-tDiff0,outputDetailAcc.ansiMs+=tAnsi1-tAnsi0,outputDetailAcc.calls+=1,outputDetailAcc.totalChanges+=count;let dirtyRowCount=0,minRow=next.minDirtyRow,maxRow=next.maxDirtyRow;if(minRow>=0){for(let r=minRow;r<=maxRow;r++)if(next.isRowDirty(r))dirtyRowCount++}outputDetailAcc.dirtyRows+=dirtyRowCount,outputDetailAcc.outputBytes+=incrOutput.length}if(DEBUG_OUTPUT2||isStrictAccumulate()){let bytes=Buffer.byteLength(incrOutput);try{__require("fs").appendFileSync("/tmp/silvery-sizes.log",`changesToAnsi: ${count} changes, ${bytes} bytes
47
+ `)}catch{}}if(DEBUG_CAPTURE){_debugFrameCount++;try{let fs=__require("fs"),freshOutput=bufferToAnsi(next,ctx),freshPrev=prev?bufferToAnsi(prev,ctx):"",w=Math.max(prev?.width??next.width,next.width),h=Math.max(prev?.height??next.height,next.height),screenIncr=replayAnsiWithStyles(w,h,freshPrev+incrOutput,ctx),screenFresh=replayAnsiWithStyles(w,h,freshOutput,ctx),mismatchInfo="";for(let y=0;y<h&&!mismatchInfo;y++)for(let x=0;x<w&&!mismatchInfo;x++){let ic=screenIncr[y]?.[x],fc=screenFresh[y]?.[x];if(ic&&fc&&(ic.char!==fc.char||!sgrColorEquals(ic.fg,fc.fg)||!sgrColorEquals(ic.bg,fc.bg))){mismatchInfo=`MISMATCH at (${x},${y}): incr='${ic.char}' fresh='${fc.char}' incrFg=${formatColor(ic.fg)} freshFg=${formatColor(fc.fg)} incrBg=${formatColor(ic.bg)} freshBg=${formatColor(fc.bg)}`;let incrRow=screenIncr[y].map((c)=>c.char).join(""),freshRow=screenFresh[y].map((c)=>c.char).join("");mismatchInfo+=`
48
+ incr row ${y}: ${incrRow.slice(Math.max(0,x-20),x+40)}
49
+ fresh row ${y}: ${freshRow.slice(Math.max(0,x-20),x+40)}`}}let status=mismatchInfo||"MATCH";if(fs.appendFileSync("/tmp/silvery-capture.log",`Frame ${_debugFrameCount}: ${count} changes, ${status}
50
+ `),mismatchInfo)fs.writeFileSync(`/tmp/silvery-incr-${_debugFrameCount}.ansi`,freshPrev+incrOutput),fs.writeFileSync(`/tmp/silvery-fresh-${_debugFrameCount}.ansi`,freshOutput),fs.appendFileSync("/tmp/silvery-capture.log",` Saved ANSI files: /tmp/silvery-incr-${_debugFrameCount}.ansi and /tmp/silvery-fresh-${_debugFrameCount}.ansi
51
+ `)}catch(e){try{__require("fs").appendFileSync("/tmp/silvery-capture.log",`Frame ${_debugFrameCount}: ERROR ${e}
52
+ `)}catch{}}}if(isStrictOutput()||tvState.hasVt100)verifyOutputEquivalence(prev,next,incrOutput,ctx,bufferToAnsi,outputGraphemeWidth,outputTextSizingEnabled);if(isStrictAccumulate())accState.accumulatedAnsi+=incrOutput,accState.accumulateFrameCount++,verifyAccumulatedOutput(next,ctx,accState,bufferToAnsi);if(tvState.backends.length>0&&(tvState.terminal||tvState.ghosttyTerminal))tvState.frameCount++,verifyTerminalEquivalence(tvState,incrOutput,next,ctx,bufferToAnsi);if(CAPTURE_RAW)try{let fs=__require("fs");_captureRawFrameCount++,fs.appendFileSync("/tmp/silvery-raw.ansi",incrOutput);let freshOutput=bufferToAnsi(next,ctx);fs.writeFileSync(`/tmp/silvery-raw-fresh-${_captureRawFrameCount}.ansi`,freshOutput),fs.appendFileSync("/tmp/silvery-raw-frames.jsonl",JSON.stringify({frame:_captureRawFrameCount,type:"incremental",changes:count,bytes:incrOutput.length,width:next.width,height:next.height})+`
53
+ `)}catch{}return incrOutput}function lineHasContent(buffer,y){for(let x=0;x<buffer.width;x++){let ch=buffer.getCellChar(x,y);if(ch!==" "&&ch!=="")return!0;if(buffer.getCellBg(x,y)!==null)return!0;if(buffer.getCellAttrs(x,y)&VISIBLE_SPACE_ATTR_MASK)return!0}return!1}function findLastContentLine(buffer){for(let y=buffer.height-1;y>=0;y--)if(lineHasContent(buffer,y))return y;return 0}function inlineCursorSuffix(cursorPos,buffer,ctx){let{termRows}=ctx;if(!cursorPos?.visible)return"\x1B[?25l";let lastContentLine=findLastContentLine(buffer),maxLine=lastContentLine,startLine=0,maxOutputLines=termRows!=null?Math.min(lastContentLine+1,termRows):lastContentLine+1;if(termRows!=null&&maxLine>=termRows)startLine=maxLine-termRows+1;let visibleRow=cursorPos.y-startLine;if(visibleRow<0||visibleRow>=maxOutputLines)return"\x1B[?25l";let rowDelta=maxOutputLines-1-visibleRow,suffix="";if(rowDelta>0)suffix+=`\x1B[${rowDelta}A`;if(suffix+="\r",cursorPos.x>0)suffix+=`\x1B[${cursorPos.x}C`;return suffix+="\x1B[?25h",suffix}function inlineIncrementalRender(state,prev,next,scrollbackOffset,cursorPos,ctx=defaultContext,tvState){let{termRows}=ctx;if(scrollbackOffset>0||prev.width!==next.width||prev.height!==next.height||state.prevCursorRow<0)return inlineFullRender(state,prev,next,scrollbackOffset,cursorPos,ctx);let nextContentLines=findLastContentLine(next)+1,prevContentLines=findLastContentLine(prev)+1,prevMaxOutputLines=termRows!=null?Math.min(prevContentLines,termRows):prevContentLines,maxOutputLines=termRows!=null?Math.min(nextContentLines,termRows):nextContentLines,prevStartLine=0;if(termRows!=null&&prevContentLines>termRows)prevStartLine=prevContentLines-termRows;let startLine=0;if(termRows!=null&&nextContentLines>termRows)startLine=nextContentLines-termRows;if(startLine!==prevStartLine)return inlineFullRender(state,prev,next,scrollbackOffset,cursorPos,ctx);let{pool,count}=diffBuffers(prev,next);if(count===0&&nextContentLines===prevContentLines){let suffix=inlineCursorSuffix(cursorPos??null,next,ctx);return updateInlineCursorRow(state,cursorPos,maxOutputLines,startLine),suffix}let output="";if(state.prevCursorRow>0)output+=`\x1B[${state.prevCursorRow}A`;output+="\r",output+="\x1B[?25l";let effectiveOutputLines=Math.max(prevMaxOutputLines,maxOutputLines),changes=changesToAnsi(pool,count,ctx,next,startLine,effectiveOutputLines);output+=changes.output;let finalY=changes.finalY,prevBottomRow=prevMaxOutputLines-1,bottomRow=maxOutputLines-1;if(maxOutputLines>prevMaxOutputLines){let fromRow=finalY>=0?finalY:0;if(fromRow>=bottomRow);else if(fromRow>=prevBottomRow){let remainingRows=bottomRow-fromRow;for(let i=0;i<remainingRows;i++)output+=`\r
54
+ `}else{if(fromRow<prevBottomRow){let dy=prevBottomRow-fromRow;output+=dy===1?`\r
55
+ `:`\r\x1B[${dy}B`}let newRows=bottomRow-prevBottomRow;for(let i=0;i<newRows;i++)output+=`\r
56
+ `}}else if(maxOutputLines<prevMaxOutputLines){let fromRow=finalY>=0?finalY:0;if(fromRow<bottomRow){let dy=bottomRow-fromRow;output+=dy===1?`\r
57
+ `:`\r\x1B[${dy}B`}else if(fromRow>bottomRow)output+=`\x1B[${fromRow-bottomRow}A`;let orphanCount=prevMaxOutputLines-maxOutputLines;for(let y=0;y<orphanCount;y++)output+=`
58
+ \r\x1B[K`;if(orphanCount>0)output+=`\x1B[${orphanCount}A`}else if(finalY>=0&&finalY<bottomRow){let dy=bottomRow-finalY;output+=dy===1?`\r
59
+ `:`\r\x1B[${dy}B`}if(output+=inlineCursorSuffix(cursorPos??null,next,ctx),isStrictOutput()||tvState?.hasVt100){let savedMode=ctx.mode;ctx.mode="fullscreen";let fsIncrOutput=changesToAnsi(pool,count,ctx,next).output;verifyOutputEquivalence(prev,next,fsIncrOutput,ctx,bufferToAnsi,outputGraphemeWidth,outputTextSizingEnabled),ctx.mode=savedMode}return updateInlineCursorRow(state,cursorPos,maxOutputLines,startLine),output}function inlineFullRender(state,prev,next,scrollbackOffset,cursorPos,ctx=defaultContext){let{termRows}=ctx,nextContentLines=findLastContentLine(next)+1,prevOutputLines,cursorRowInRegion;if(state.prevCursorRow>=0)prevOutputLines=state.prevOutputLines,cursorRowInRegion=state.prevCursorRow;else{let prevContentLines=findLastContentLine(prev)+1;prevOutputLines=termRows!=null?Math.min(prevContentLines,termRows):prevContentLines,cursorRowInRegion=prevOutputLines-1}let rawCursorOffset=cursorRowInRegion+scrollbackOffset,cursorOffset=termRows!=null&&!isStrictOutput()?Math.min(rawCursorOffset,termRows-1):rawCursorOffset,maxOutputLines=termRows!=null?Math.min(nextContentLines,termRows):nextContentLines;if(scrollbackOffset===0){let{count}=diffBuffers(prev,next);if(count===0)return""}let prefix="";if(cursorOffset>0)prefix=`\x1B[${cursorOffset}A\r`;let output=prefix+bufferToAnsi(next,ctx,maxOutputLines),terminalScroll=termRows!=null?Math.max(0,rawCursorOffset-(termRows-1)):0,lastOccupiedLine=Math.max(prevOutputLines-1-terminalScroll,0),nextLastLine=maxOutputLines-1;if(lastOccupiedLine>nextLastLine){for(let y=nextLastLine+1;y<=lastOccupiedLine;y++)output+=`
60
+ \r\x1B[K`;let up=lastOccupiedLine-nextLastLine;if(up>0)output+=`\x1B[${up}A`}output+=inlineCursorSuffix(cursorPos??null,next,ctx);let startLine=0;if(termRows!=null&&nextContentLines>termRows)startLine=nextContentLines-termRows;return updateInlineCursorRow(state,cursorPos,maxOutputLines,startLine),output}function bufferToAnsi(buffer,ctx=defaultContext,maxRows){let{mode}=ctx,output="",currentStyle=null,currentHyperlink,maxLine=mode==="inline"?findLastContentLine(buffer):buffer.height-1,startLine=0;if(maxRows!=null&&maxLine>=maxRows)if(mode==="fullscreen")maxLine=maxRows-1;else startLine=maxLine-maxRows+1;if(mode==="fullscreen")output+="\x1B[H";else output+="\x1B[?25l";let cell=createMutableCell(),cellStyle={fg:null,bg:null,underlineColor:null,attrs:{}};for(let y=startLine;y<=maxLine;y++){if(mode==="inline")output+="\r";else if(y>startLine)output+=`\x1B[${y+1};1H`;for(let x=0;x<buffer.width;x++){buffer.readCellInto(x,y,cell);let cellHyperlink=cell.hyperlink;if(cellHyperlink!==currentHyperlink){if(currentHyperlink)output+="\x1B]8;;\x1B\\";if(cellHyperlink)output+=`\x1B]8;;${cellHyperlink}\x1B\\`;currentHyperlink=cellHyperlink}if(cellStyle.fg=cell.fg,cellStyle.bg=cell.bg,cellStyle.underlineColor=cell.underlineColor,cellStyle.attrs=cell.attrs,!styleEquals(currentStyle,cellStyle)){let saved={fg:cell.fg,bg:cell.bg,underlineColor:cell.underlineColor,attrs:{...cell.attrs}};output+=styleTransition(currentStyle,saved,ctx),currentStyle=saved}let char=cell.char||" ";if(output+=wrapTextSizing(char,cell.wide,ctx),cell.wide)if(x++,mode==="fullscreen")output+=`\x1B[${y-startLine+1};${x+2}H`;else{if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;let nextCol=x+1;if(output+="\r",nextCol>0)output+=nextCol===1?"\x1B[C":`\x1B[${nextCol}C`}}if(currentHyperlink)output+="\x1B]8;;\x1B\\",currentHyperlink=void 0;if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;if(y<maxLine){if(mode==="inline")output+=`\r
61
+ `}}if(currentHyperlink)output+="\x1B]8;;\x1B\\";return output+="\x1B[0m",output}function sortPoolByPosition(pool,count){for(let i=1;i<count;i++){let item=pool[i],iy=item.y,ix=item.x,j=i-1;while(j>=0&&(pool[j].y>iy||pool[j].y===iy&&pool[j].x>ix))pool[j+1]=pool[j],j--;pool[j+1]=item}}function changesToAnsi(pool,count,ctx=defaultContext,buffer,startLine=0,maxOutputLines=1/0){let{mode}=ctx;if(count===0)return{output:"",finalY:-1};sortPoolByPosition(pool,count);let denseRows=new Set,bufWidth=buffer?.width??0,densityThreshold=bufWidth>0?bufWidth*0.5:1/0;if(buffer&&bufWidth>0){let rowStart=0;while(rowStart<count){let rowY=pool[rowStart].y,rowEnd=rowStart+1;while(rowEnd<count&&pool[rowEnd].y===rowY)rowEnd++;if(rowEnd-rowStart>=densityThreshold)denseRows.add(rowY);rowStart=rowEnd}}let output="",currentStyle=null,currentHyperlink,isInline=mode==="inline",endLine=startLine+maxOutputLines,finalY=-1,cursorX=-1,cursorY=-1,prevY=-1,lastEmittedX=-1,lastEmittedY=-1,denseRowCell=createMutableCell();for(let i=0;i<count;i++){let change=pool[i],x=change.x,y=change.y,cell=change.cell;if(isInline&&(y<startLine||y>=endLine))continue;if(buffer&&denseRows.has(y)){while(i+1<count&&pool[i+1].y===y)i++;let renderY2=isInline?y-startLine:y;if(y!==prevY&&currentHyperlink)output+="\x1B]8;;\x1B\\",currentHyperlink=void 0;if(prevY=y,renderY2!==cursorY||cursorX!==0){if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;if(cursorY>=0&&renderY2===cursorY+1)output+=`\r
62
+ `;else if(cursorY>=0&&renderY2>cursorY){let dy=renderY2-cursorY;output+=dy===1?`\r
63
+ `:`\r\x1B[${dy}B`}else if(isInline){let fromRow=cursorY>=0?cursorY:0;if(renderY2>fromRow)output+=`\x1B[${renderY2-fromRow}B\r`;else if(renderY2<fromRow)output+=`\x1B[${fromRow-renderY2}A\r`;else output+="\r"}else output+=`\x1B[${renderY2+1};1H`}for(let bx=0;bx<bufWidth;bx++){buffer.readCellInto(bx,y,denseRowCell);let cellHyperlink2=denseRowCell.hyperlink;if(cellHyperlink2!==currentHyperlink){if(currentHyperlink)output+="\x1B]8;;\x1B\\";if(cellHyperlink2)output+=`\x1B]8;;${cellHyperlink2}\x1B\\`;currentHyperlink=cellHyperlink2}if(reusableCellStyle.fg=denseRowCell.fg,reusableCellStyle.bg=denseRowCell.bg,reusableCellStyle.underlineColor=denseRowCell.underlineColor,reusableCellStyle.attrs=denseRowCell.attrs,!styleEquals(currentStyle,reusableCellStyle)){let prevStyle=currentStyle;currentStyle={fg:denseRowCell.fg,bg:denseRowCell.bg,underlineColor:denseRowCell.underlineColor,attrs:{...denseRowCell.attrs}},output+=styleTransition(prevStyle,currentStyle,ctx)}let char2=denseRowCell.char||" ";if(output+=wrapTextSizing(char2,denseRowCell.wide,ctx),denseRowCell.wide)if(bx++,isInline){if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;let nextCol=bx+1;if(output+="\r",nextCol>0)output+=nextCol===1?"\x1B[C":`\x1B[${nextCol}C`}else output+=`\x1B[${renderY2+1};${bx+2}H`}if(currentHyperlink)output+="\x1B]8;;\x1B\\",currentHyperlink=void 0;if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;cursorX=bufWidth,cursorY=renderY2,lastEmittedX=bufWidth-1,lastEmittedY=y;continue}if(cell.continuation){if(lastEmittedX===x-1&&lastEmittedY===y)continue;if(buffer&&x>0){if(x=x-1,buffer.readCellInto(x,y,wideCharLookupCell),cell=wideCharLookupCell,cell.continuation||!cell.wide)continue}else continue}let renderY=isInline?y-startLine:y;if(y!==prevY&&currentHyperlink)output+="\x1B]8;;\x1B\\",currentHyperlink=void 0;if(prevY=y,renderY!==cursorY||x!==cursorX)if(cursorY>=0&&renderY===cursorY+1&&x===0){if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;output+=`\r
64
+ `}else if(cursorY>=0&&renderY===cursorY&&x>cursorX){if(currentStyle&&currentStyle.bg!==null)output+="\x1B[0m",currentStyle=null;let dx=x-cursorX;output+=dx===1?"\x1B[C":`\x1B[${dx}C`}else if(cursorY>=0&&renderY>cursorY&&x===0){let dy=renderY-cursorY;if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;output+=dy===1?`\r
65
+ `:`\r\x1B[${dy}B`}else if(isInline){if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;let fromRow=cursorY>=0?cursorY:0;if(renderY>fromRow)output+=`\x1B[${renderY-fromRow}B\r`;else if(renderY<fromRow)output+=`\x1B[${fromRow-renderY}A\r`;else output+="\r";if(x>0)output+=x===1?"\x1B[C":`\x1B[${x}C`}else output+=`\x1B[${renderY+1};${x+1}H`;let cellHyperlink=cell.hyperlink;if(cellHyperlink!==currentHyperlink){if(currentHyperlink)output+="\x1B]8;;\x1B\\";if(cellHyperlink)output+=`\x1B]8;;${cellHyperlink}\x1B\\`;currentHyperlink=cellHyperlink}if(reusableCellStyle.fg=cell.fg,reusableCellStyle.bg=cell.bg,reusableCellStyle.underlineColor=cell.underlineColor,reusableCellStyle.attrs=cell.attrs,!styleEquals(currentStyle,reusableCellStyle)){let prevStyle=currentStyle;currentStyle={fg:cell.fg,bg:cell.bg,underlineColor:cell.underlineColor,attrs:{...cell.attrs}},output+=styleTransition(prevStyle,currentStyle,ctx)}let char=cell.char||" ";if(output+=wrapTextSizing(char,cell.wide,ctx),cursorX=x+(cell.wide?2:1),cursorY=renderY,lastEmittedX=x,lastEmittedY=y,cell.wide)if(isInline){if(currentStyle&&currentStyle.bg!==null)output+="\x1B[0m",currentStyle=null;if(output+="\r",cursorX>0)output+=cursorX===1?"\x1B[C":`\x1B[${cursorX}C`}else output+=`\x1B[${cursorY+1};${cursorX+1}H`}if(finalY=cursorY,currentHyperlink)output+="\x1B]8;;\x1B\\";if(currentStyle)output+="\x1B[0m";return{output,finalY}}function styleToAnsi(style2,ctx=defaultContext){let{fg,bg}=style2,codes=[];if(fg!==null)codes.push(fgColorCode(fg));if(bg!==null&&!isDefaultBg(bg))codes.push(bgColorCode(bg));if(style2.attrs.bold)codes.push("1");if(style2.attrs.dim)codes.push("2");if(style2.attrs.italic)codes.push("3");if(!ctx.caps.underlineStyles){if(style2.attrs.underline||style2.attrs.underlineStyle)codes.push("4")}else{let underlineStyle=style2.attrs.underlineStyle,sgrSubparam=underlineStyleToSgr(underlineStyle);if(sgrSubparam!==null&&sgrSubparam!==0)codes.push(`4:${sgrSubparam}`);else if(style2.attrs.underline)codes.push("4")}if(style2.attrs.blink)codes.push("5");if(style2.attrs.inverse)codes.push("7");if(style2.attrs.hidden)codes.push("8");if(style2.attrs.strikethrough)codes.push("9");if(ctx.caps.underlineColor&&style2.underlineColor!==null&&style2.underlineColor!==void 0)if(typeof style2.underlineColor==="number")codes.push(`58;5;${style2.underlineColor}`);else codes.push(`58;2;${style2.underlineColor.r};${style2.underlineColor.g};${style2.underlineColor.b}`);if(codes.length===0)return"";return`\x1B[${codes.join(";")}m`}var log3,_env2,DEBUG_OUTPUT2,FULL_RENDER,DEBUG_CAPTURE,CAPTURE_RAW,_debugFrameCount=0,_captureRawFrameCount=0,defaultContext,defaultAccState,defaultTerminalVerifyState,reusableCellStyle,wideCharLookupCell;var init_output_phase=__esm(()=>{init_buffer();init_sgr_codes();init_text_sizing();init_unicode();init_output_verify();init_output_verify();init_diff_buffers();log3=createLogger3("silvery:output"),_env2=typeof process<"u"?process.env:{},DEBUG_OUTPUT2=!!_env2.SILVERY_DEBUG_OUTPUT,FULL_RENDER=!!_env2.SILVERY_FULL_RENDER,DEBUG_CAPTURE=!!_env2.SILVERY_DEBUG_CAPTURE,CAPTURE_RAW=!!_env2.SILVERY_CAPTURE_RAW,defaultContext={caps:{underlineStyles:!0,underlineColor:!0,colorLevel:"truecolor"},measurer:null,sgrCache:new Map,transitionCache:new Map,mode:"fullscreen",termRows:void 0};defaultAccState={accumulatedAnsi:"",accumulateWidth:0,accumulateHeight:0,accumulateFrameCount:0},defaultTerminalVerifyState=createTerminalVerifyState();reusableCellStyle={fg:null,bg:null,underlineColor:null,attrs:{}},wideCharLookupCell=createMutableCell()});var init_detection2=__esm(()=>{init_src2();init_src2()});function stripAnsi3(text){return text.replace(ANSI_REGEX2,"")}function parseInputEvents(data){let events=[],pasteResult=parseBracketedPaste(data);if(pasteResult)events.push({type:"paste",data:{text:pasteResult.content}});else for(let raw of splitRawInput(data)){let focusEvent=parseFocusEvent(raw);if(focusEvent){events.push({type:"focus",data:{focused:focusEvent.type==="focus-in"}});continue}if(isMouseSequence(raw)){let parsed=parseMouseSequence(raw);if(parsed)events.push({type:"mouse",data:parsed});continue}let[input,key]=parseKey(raw);events.push({type:"key",data:{input,key}})}return events}function createEventQueue(controller){let queue=[],resolve=null,disposed=!1;function push(...events2){if(queue.push(...events2),resolve){let r=resolve;resolve=null,r()}}async function*events(){if(disposed)return;while(!disposed&&!controller.signal.aborted){if(queue.length===0)await new Promise((r)=>{resolve=r,controller.signal.addEventListener("abort",()=>r(),{once:!0})});if(disposed||controller.signal.aborted)break;while(queue.length>0)yield queue.shift()}}return{push,events,dispose(){disposed=!0}}}function createEmulatorStdout(feed,cols,rows){let resizeListeners=new Set,stdout={write:(data)=>{return feed(typeof data==="string"?data:new TextDecoder().decode(data)),!0},on:(event,handler)=>{if(event==="resize")resizeListeners.add(handler)},off:(event,handler)=>{if(event==="resize")resizeListeners.delete(handler)},isTTY:!0,columns:cols,rows};return{stdout,resizeListeners,updateDims(c,r){stdout.columns=c,stdout.rows=r}}}function finalizeTerm(style2,termBase,frame,opts){if(Object.defineProperty(termBase,"frame",{get:frame.get,enumerable:!0}),opts?.defineProperties)Object.defineProperties(termBase,opts.defineProperties);if(opts?.delegateFrom)for(let key of Object.keys(opts.delegateFrom)){if(key in termBase)continue;let val=opts.delegateFrom[key];Object.defineProperty(termBase,key,typeof val==="function"?{value:(...args)=>opts.delegateFrom[key](...args)}:{get:()=>opts.delegateFrom[key]})}return createMixedStyle(style2,termBase)}function createTerm(first,second){if(second&&first&&isTermBackend(first)){let{createTerminal}=__require("@termless/core"),emulator=createTerminal({backend:first,...second});return createBackendTerm(emulator)}if(first&&isTermEmulator(first))return createBackendTerm(first);if(first&&isHeadlessDims(first))return createHeadlessTerm(first);return createNodeTerm(first??{})}function isTermEmulator(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;return typeof o.feed==="function"&&typeof o.screen==="object"&&o.screen!==null}function isTermBackend(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;return typeof o.init==="function"&&typeof o.name==="string"&&typeof o.destroy==="function"}function isHeadlessDims(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;return typeof o.cols==="number"&&typeof o.rows==="number"&&!("stdout"in o)&&!("stdin"in o)}function createNodeTerm(options){let stdout=options.stdout??process.stdout,stdin=options.stdin??process.stdin,cachedCursor=options.cursor??detectCursor(stdout),cachedInput=detectInput(stdin),cachedColor=options.color!==void 0?options.color:detectColor(stdout),cachedUnicode=options.unicode??detectUnicode(),detectedCaps=options.caps?{...defaultCaps(),...options.caps}:stdin.isTTY?detectTerminalCaps():void 0,styleInstance=createStyle({level:cachedColor}),provider=null,getProvider=()=>{if(!provider)provider=createTermProvider(stdin,stdout,{cols:stdout.columns||80,rows:stdout.rows||24});return provider},_frame,termBase={hasCursor:()=>cachedCursor,hasInput:()=>cachedInput,hasColor:()=>cachedColor,hasUnicode:()=>cachedUnicode,caps:detectedCaps,stdout,stdin,write:(str)=>{stdout.write(str)},writeLine:(str)=>{stdout.write(str+`
64
66
  `)},getState:()=>getProvider().getState(),subscribe:(listener)=>getProvider().subscribe(listener),events:()=>getProvider().events(),stripAnsi:stripAnsi3,paint:(buffer,prev)=>{let output=outputPhase(prev,buffer);return _frame=createTextFrame(buffer),output},[Symbol.dispose]:()=>{if(provider)provider[Symbol.dispose]()}};return finalizeTerm(styleInstance,termBase,{get:()=>_frame},{defineProperties:{cols:{get:()=>stdout.isTTY?stdout.columns:void 0,enumerable:!0},rows:{get:()=>stdout.isTTY?stdout.rows:void 0,enumerable:!0}}})}function createHeadlessTerm(dims){let disposed=!1,controller=new AbortController,_frame,termBase={hasCursor:()=>!1,hasInput:()=>!1,hasColor:()=>null,hasUnicode:()=>!1,caps:void 0,stdout:process.stdout,stdin:process.stdin,write:()=>{},writeLine:()=>{},getState:()=>dims,subscribe:()=>()=>{},async*events(){if(disposed)return;await new Promise((r)=>controller.signal.addEventListener("abort",()=>r(),{once:!0}))},stripAnsi:stripAnsi3,paint:(_buffer,_prev)=>{return _frame=createTextFrame(_buffer),""},[Symbol.dispose]:()=>{if(disposed)return;disposed=!0,controller.abort()}};return finalizeTerm(createStyle({level:null}),termBase,{get:()=>_frame},{defineProperties:{cols:{get:()=>dims.cols,enumerable:!0},rows:{get:()=>dims.rows,enumerable:!0}}})}function createBackendTerm(emulator){let controller=new AbortController,eq=createEventQueue(controller),{stdout,resizeListeners,updateDims}=createEmulatorStdout((s)=>emulator.feed(s),emulator.cols,emulator.rows),subscribers=new Set,_frame,termBase={hasCursor:()=>!0,hasInput:()=>!0,hasColor:()=>"truecolor",hasUnicode:()=>!0,caps:void 0,stdout,stdin:process.stdin,write:(str)=>emulator.feed(str),writeLine:(str)=>emulator.feed(str+`
65
- `),getState:()=>({cols:emulator.cols,rows:emulator.rows}),subscribe:(listener)=>{return subscribers.add(listener),()=>subscribers.delete(listener)},events:()=>eq.events(),resize:(cols,rows)=>{emulator.resize(cols,rows),subscribers.forEach((l)=>l({cols,rows})),eq.push({type:"resize",data:{cols,rows}}),updateDims(cols,rows),resizeListeners.forEach((l)=>l())},sendInput:(data)=>eq.push(...parseInputEvents(data)),stripAnsi:stripAnsi3,paint:(buffer,prev)=>{let output=outputPhase(prev,buffer);if(output)emulator.feed(output);return _frame=createTextFrame(buffer),output},_emulator:emulator,[Symbol.dispose]:()=>{eq.dispose(),controller.abort(),subscribers.clear(),emulator.close().catch(()=>{})}};return finalizeTerm(createStyle({level:"truecolor"}),termBase,{get:()=>_frame},{defineProperties:{cols:{get:()=>emulator.cols,enumerable:!0},rows:{get:()=>emulator.rows,enumerable:!0},screen:{get:()=>emulator.screen,enumerable:!0},scrollback:{get:()=>emulator.scrollback,enumerable:!0}},delegateFrom:emulator})}var ANSI_REGEX2;var init_term=__esm(()=>{init_src2();init_buffer();init_output_phase();init_detection2();init_term_provider();init_keys();init_mouse();ANSI_REGEX2=/\x1b\[[0-9;:]*m|\x9b[0-9;:]*m|\x1b\]8;;[^\x07\x1b]*(?:\x07|\x1b\\)|\x9d8;;[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c)/g});var init_patch_console=()=>{};import{openSync,writeSync,closeSync}from"node:fs";import{createLogger as createLogger3}from"loggily";function createOutputGuard(options){let savedStdoutWrite=process.stdout.write,savedStderrWrite=process.stderr.write,origStdoutWrite=savedStdoutWrite.bind(process.stdout),origStderrWrite=savedStderrWrite.bind(process.stderr),silveryWriting=!1,disposed=!1,suppressedCount=0,redirectedCount=0,stderrLog=options?.stderrLog??process.env.DEBUG_LOG,stderrFd=null,stderrBuffer=[];if(stderrLog)try{stderrFd=openSync(stderrLog,"a")}catch{}process.stdout.write=function(chunk,...args){if(silveryWriting)return origStdoutWrite(chunk,...args);suppressedCount++;let preview=typeof chunk==="string"?chunk.slice(0,60):"<binary>";return log3?.debug?.(`suppressed stdout write (${suppressedCount}): ${JSON.stringify(preview)}`),!0},process.stderr.write=function(chunk,..._args){let str=typeof chunk==="string"?chunk:chunk.toString();if(redirectedCount++,stderrFd!==null){try{writeSync(stderrFd,str)}catch{}return!0}if(options?.bufferStderr)return stderrBuffer.push(str),!0;return!0};let{log:savedConsoleLog,info:savedConsoleInfo,warn:savedConsoleWarn,error:savedConsoleError,debug:savedConsoleDebug}=console;function redirectConsole(...args){let str=args.map((a)=>typeof a==="string"?a:String(a)).join(" ")+`
66
- `;if(redirectedCount++,stderrFd!==null){try{writeSync(stderrFd,str)}catch{}return}if(options?.bufferStderr){stderrBuffer.push(str);return}}console.log=redirectConsole,console.info=redirectConsole,console.warn=redirectConsole,console.error=redirectConsole,console.debug=redirectConsole,log3?.info?.("activated"+(stderrLog?` (stderr -> ${stderrLog})`:" (stderr suppressed)"));function dispose(){if(disposed)return;disposed=!0,process.stdout.write=savedStdoutWrite,process.stderr.write=savedStderrWrite,console.log=savedConsoleLog,console.info=savedConsoleInfo,console.warn=savedConsoleWarn,console.error=savedConsoleError,console.debug=savedConsoleDebug,log3?.info?.(`deactivated (suppressed ${suppressedCount} stdout, redirected ${redirectedCount} stderr)`);for(let line of stderrBuffer)origStderrWrite(line);if(stderrFd!==null){try{closeSync(stderrFd)}catch{}stderrFd=null}}return{writeStdout(data){silveryWriting=!0;try{return origStdoutWrite(data)}finally{silveryWriting=!1}},get active(){return!disposed},get suppressedCount(){return suppressedCount},get redirectedCount(){return redirectedCount},dispose,[Symbol.dispose]:dispose}}var log3;var init_output_guard=__esm(()=>{log3=createLogger3("silvery:guard")});var init_utils2=__esm(()=>{init_src2()});var init_underline=__esm(()=>{init_src2()});var init_hyperlink2=__esm(()=>{init_src2()});var init_ansi=__esm(()=>{init_src2()});var _lazyTerm,term,BG_OVERRIDE_CODE=9999;var init_ansi2=__esm(()=>{init_term();init_term();init_patch_console();init_output_guard();init_detection2();init_utils2();init_underline();init_hyperlink2();init_ansi();term=new Proxy({},{get(_target,prop,receiver){if(!_lazyTerm)_lazyTerm=createTerm();return Reflect.get(_lazyTerm,prop,receiver)},apply(_target,thisArg,args){if(!_lazyTerm)_lazyTerm=createTerm();return Reflect.apply(_lazyTerm,thisArg,args)},has(_target,prop){if(!_lazyTerm)_lazyTerm=createTerm();return Reflect.has(_lazyTerm,prop)}})});var YGEnums,ALIGN_AUTO,ALIGN_FLEX_START,ALIGN_CENTER,ALIGN_FLEX_END,ALIGN_STRETCH,ALIGN_BASELINE,ALIGN_SPACE_BETWEEN,ALIGN_SPACE_AROUND,DIMENSION_WIDTH,DIMENSION_HEIGHT,DIRECTION_INHERIT,DIRECTION_LTR,DIRECTION_RTL,DISPLAY_FLEX,DISPLAY_NONE,EDGE_LEFT,EDGE_TOP,EDGE_RIGHT,EDGE_BOTTOM,EDGE_START,EDGE_END,EDGE_HORIZONTAL,EDGE_VERTICAL,EDGE_ALL,EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS,EXPERIMENTAL_FEATURE_ABSOLUTE_PERCENTAGE_AGAINST_PADDING_EDGE,EXPERIMENTAL_FEATURE_FIX_ABSOLUTE_TRAILING_COLUMN_MARGIN,FLEX_DIRECTION_COLUMN,FLEX_DIRECTION_COLUMN_REVERSE,FLEX_DIRECTION_ROW,FLEX_DIRECTION_ROW_REVERSE,GUTTER_COLUMN,GUTTER_ROW,GUTTER_ALL,JUSTIFY_FLEX_START,JUSTIFY_CENTER,JUSTIFY_FLEX_END,JUSTIFY_SPACE_BETWEEN,JUSTIFY_SPACE_AROUND,JUSTIFY_SPACE_EVENLY,LOG_LEVEL_ERROR,LOG_LEVEL_WARN,LOG_LEVEL_INFO,LOG_LEVEL_DEBUG,LOG_LEVEL_VERBOSE,LOG_LEVEL_FATAL,MEASURE_MODE_UNDEFINED,MEASURE_MODE_EXACTLY,MEASURE_MODE_AT_MOST,NODE_TYPE_DEFAULT,NODE_TYPE_TEXT,OVERFLOW_VISIBLE,OVERFLOW_HIDDEN,OVERFLOW_SCROLL,POSITION_TYPE_STATIC,POSITION_TYPE_RELATIVE,POSITION_TYPE_ABSOLUTE,PRINT_OPTIONS_LAYOUT,PRINT_OPTIONS_STYLE,PRINT_OPTIONS_CHILDREN,UNIT_UNDEFINED,UNIT_POINT,UNIT_PERCENT,UNIT_AUTO,WRAP_NO_WRAP,WRAP_WRAP,WRAP_WRAP_REVERSE,wrapAsm=(E)=>{function _(E2,_2,T2){let N2=E2[_2];E2[_2]=function(...E3){return T2.call(this,N2,...E3)}}for(let T2 of["setPosition","setMargin","setFlexBasis","setWidth","setHeight","setMinWidth","setMinHeight","setMaxWidth","setMaxHeight","setPadding"]){let N2={[YGEnums.UNIT_POINT]:E.Node.prototype[T2],[YGEnums.UNIT_PERCENT]:E.Node.prototype[`${T2}Percent`],[YGEnums.UNIT_AUTO]:E.Node.prototype[`${T2}Auto`]};_(E.Node.prototype,T2,function(E2,..._2){let I,L,O=_2.pop();if(O==="auto")I=YGEnums.UNIT_AUTO,L=void 0;else if(typeof O=="object")I=O.unit,L=O.valueOf();else if(I=typeof O=="string"&&O.endsWith("%")?YGEnums.UNIT_PERCENT:YGEnums.UNIT_POINT,L=parseFloat(O),!Number.isNaN(O)&&Number.isNaN(L))throw Error(`Invalid value ${O} for ${T2}`);if(!N2[I])throw Error(`Failed to execute "${T2}": Unsupported unit '${O}'`);return L!==void 0?N2[I].call(this,..._2,L):N2[I].call(this,..._2)})}function T(_2){return E.MeasureCallback.implement({measure:(...E2)=>{let{width:T2,height:N2}=_2(...E2);return{width:T2??NaN,height:N2??NaN}}})}function N(_2){return E.DirtiedCallback.implement({dirtied:_2})}return _(E.Node.prototype,"setMeasureFunc",function(E2,_2){return _2?E2.call(this,T(_2)):this.unsetMeasureFunc()}),_(E.Node.prototype,"setDirtiedFunc",function(E2,_2){E2.call(this,N(_2))}),_(E.Config.prototype,"free",function(){E.Config.destroy(this)}),_(E.Node,"create",(_2,T2)=>T2?E.Node.createWithConfig(T2):E.Node.createDefault()),_(E.Node.prototype,"free",function(){E.Node.destroy(this)}),_(E.Node.prototype,"freeRecursive",function(){for(let E2=0,_2=this.getChildCount();E2<_2;++E2)this.getChild(0).freeRecursive();this.free()}),_(E.Node.prototype,"calculateLayout",function(E2,_2=NaN,T2=NaN,N2=YGEnums.DIRECTION_LTR){return E2.call(this,_2,T2,N2)}),{Config:E.Config,Node:E.Node,...YGEnums}};var init_wrapAsm_f766f97f=__esm(()=>{YGEnums={},ALIGN_AUTO=YGEnums.ALIGN_AUTO=0,ALIGN_FLEX_START=YGEnums.ALIGN_FLEX_START=1,ALIGN_CENTER=YGEnums.ALIGN_CENTER=2,ALIGN_FLEX_END=YGEnums.ALIGN_FLEX_END=3,ALIGN_STRETCH=YGEnums.ALIGN_STRETCH=4,ALIGN_BASELINE=YGEnums.ALIGN_BASELINE=5,ALIGN_SPACE_BETWEEN=YGEnums.ALIGN_SPACE_BETWEEN=6,ALIGN_SPACE_AROUND=YGEnums.ALIGN_SPACE_AROUND=7,DIMENSION_WIDTH=YGEnums.DIMENSION_WIDTH=0,DIMENSION_HEIGHT=YGEnums.DIMENSION_HEIGHT=1,DIRECTION_INHERIT=YGEnums.DIRECTION_INHERIT=0,DIRECTION_LTR=YGEnums.DIRECTION_LTR=1,DIRECTION_RTL=YGEnums.DIRECTION_RTL=2,DISPLAY_FLEX=YGEnums.DISPLAY_FLEX=0,DISPLAY_NONE=YGEnums.DISPLAY_NONE=1,EDGE_LEFT=YGEnums.EDGE_LEFT=0,EDGE_TOP=YGEnums.EDGE_TOP=1,EDGE_RIGHT=YGEnums.EDGE_RIGHT=2,EDGE_BOTTOM=YGEnums.EDGE_BOTTOM=3,EDGE_START=YGEnums.EDGE_START=4,EDGE_END=YGEnums.EDGE_END=5,EDGE_HORIZONTAL=YGEnums.EDGE_HORIZONTAL=6,EDGE_VERTICAL=YGEnums.EDGE_VERTICAL=7,EDGE_ALL=YGEnums.EDGE_ALL=8,EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS=YGEnums.EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS=0,EXPERIMENTAL_FEATURE_ABSOLUTE_PERCENTAGE_AGAINST_PADDING_EDGE=YGEnums.EXPERIMENTAL_FEATURE_ABSOLUTE_PERCENTAGE_AGAINST_PADDING_EDGE=1,EXPERIMENTAL_FEATURE_FIX_ABSOLUTE_TRAILING_COLUMN_MARGIN=YGEnums.EXPERIMENTAL_FEATURE_FIX_ABSOLUTE_TRAILING_COLUMN_MARGIN=2,FLEX_DIRECTION_COLUMN=YGEnums.FLEX_DIRECTION_COLUMN=0,FLEX_DIRECTION_COLUMN_REVERSE=YGEnums.FLEX_DIRECTION_COLUMN_REVERSE=1,FLEX_DIRECTION_ROW=YGEnums.FLEX_DIRECTION_ROW=2,FLEX_DIRECTION_ROW_REVERSE=YGEnums.FLEX_DIRECTION_ROW_REVERSE=3,GUTTER_COLUMN=YGEnums.GUTTER_COLUMN=0,GUTTER_ROW=YGEnums.GUTTER_ROW=1,GUTTER_ALL=YGEnums.GUTTER_ALL=2,JUSTIFY_FLEX_START=YGEnums.JUSTIFY_FLEX_START=0,JUSTIFY_CENTER=YGEnums.JUSTIFY_CENTER=1,JUSTIFY_FLEX_END=YGEnums.JUSTIFY_FLEX_END=2,JUSTIFY_SPACE_BETWEEN=YGEnums.JUSTIFY_SPACE_BETWEEN=3,JUSTIFY_SPACE_AROUND=YGEnums.JUSTIFY_SPACE_AROUND=4,JUSTIFY_SPACE_EVENLY=YGEnums.JUSTIFY_SPACE_EVENLY=5,LOG_LEVEL_ERROR=YGEnums.LOG_LEVEL_ERROR=0,LOG_LEVEL_WARN=YGEnums.LOG_LEVEL_WARN=1,LOG_LEVEL_INFO=YGEnums.LOG_LEVEL_INFO=2,LOG_LEVEL_DEBUG=YGEnums.LOG_LEVEL_DEBUG=3,LOG_LEVEL_VERBOSE=YGEnums.LOG_LEVEL_VERBOSE=4,LOG_LEVEL_FATAL=YGEnums.LOG_LEVEL_FATAL=5,MEASURE_MODE_UNDEFINED=YGEnums.MEASURE_MODE_UNDEFINED=0,MEASURE_MODE_EXACTLY=YGEnums.MEASURE_MODE_EXACTLY=1,MEASURE_MODE_AT_MOST=YGEnums.MEASURE_MODE_AT_MOST=2,NODE_TYPE_DEFAULT=YGEnums.NODE_TYPE_DEFAULT=0,NODE_TYPE_TEXT=YGEnums.NODE_TYPE_TEXT=1,OVERFLOW_VISIBLE=YGEnums.OVERFLOW_VISIBLE=0,OVERFLOW_HIDDEN=YGEnums.OVERFLOW_HIDDEN=1,OVERFLOW_SCROLL=YGEnums.OVERFLOW_SCROLL=2,POSITION_TYPE_STATIC=YGEnums.POSITION_TYPE_STATIC=0,POSITION_TYPE_RELATIVE=YGEnums.POSITION_TYPE_RELATIVE=1,POSITION_TYPE_ABSOLUTE=YGEnums.POSITION_TYPE_ABSOLUTE=2,PRINT_OPTIONS_LAYOUT=YGEnums.PRINT_OPTIONS_LAYOUT=1,PRINT_OPTIONS_STYLE=YGEnums.PRINT_OPTIONS_STYLE=2,PRINT_OPTIONS_CHILDREN=YGEnums.PRINT_OPTIONS_CHILDREN=4,UNIT_UNDEFINED=YGEnums.UNIT_UNDEFINED=0,UNIT_POINT=YGEnums.UNIT_POINT=1,UNIT_PERCENT=YGEnums.UNIT_PERCENT=2,UNIT_AUTO=YGEnums.UNIT_AUTO=3,WRAP_NO_WRAP=YGEnums.WRAP_NO_WRAP=0,WRAP_WRAP=YGEnums.WRAP_WRAP=1,WRAP_WRAP_REVERSE=YGEnums.WRAP_WRAP_REVERSE=2});async function initYoga(t){let r=await yoga({instantiateWasm(n,r2){WebAssembly.instantiate(t,n).then((n2)=>{n2 instanceof WebAssembly.Instance?r2(n2):r2(n2.instance)})}});return wrapAsm(r)}var yoga;var init_dist=__esm(()=>{init_wrapAsm_f766f97f();init_wrapAsm_f766f97f();yoga=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(t={}){u||(u=t!==void 0?t:{}),u.ready=new Promise(function(n2,t2){c=n2,f=t2});var r,e,a=Object.assign({},u),i="";typeof document<"u"&&document.currentScript&&(i=document.currentScript.src),n&&(i=n),i=i.indexOf("blob:")!==0?i.substr(0,i.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var o=console.log.bind(console),s=console.warn.bind(console);Object.assign(u,a),a=null,typeof WebAssembly!="object"&&w("no native wasm support detected");var u,c,f,l,h=!1;function p(n2,t2,r2){r2=t2+r2;for(var e2="";!(t2>=r2);){var a2=n2[t2++];if(!a2)break;if(128&a2){var i2=63&n2[t2++];if((224&a2)==192)e2+=String.fromCharCode((31&a2)<<6|i2);else{var o2=63&n2[t2++];65536>(a2=(240&a2)==224?(15&a2)<<12|i2<<6|o2:(7&a2)<<18|i2<<12|o2<<6|63&n2[t2++])?e2+=String.fromCharCode(a2):(a2-=65536,e2+=String.fromCharCode(55296|a2>>10,56320|1023&a2))}}else e2+=String.fromCharCode(a2)}return e2}function v(){var n2=l.buffer;u.HEAP8=d=new Int8Array(n2),u.HEAP16=m=new Int16Array(n2),u.HEAP32=g=new Int32Array(n2),u.HEAPU8=y=new Uint8Array(n2),u.HEAPU16=E=new Uint16Array(n2),u.HEAPU32=_=new Uint32Array(n2),u.HEAPF32=T=new Float32Array(n2),u.HEAPF64=L=new Float64Array(n2)}var d,y,m,E,g,_,T,L,A,O=[],P=[],b=[],N=0,I=null;function w(n2){throw s(n2="Aborted("+n2+")"),h=!0,f(n2=new WebAssembly.RuntimeError(n2+". Build with -sASSERTIONS for more info.")),n2}function S(){return r.startsWith("data:application/octet-stream;base64,")}function R(){try{throw"both async and sync fetching of the wasm failed"}catch(n2){w(n2)}}function C(n2){for(;0<n2.length;)n2.shift()(u)}function W(n2){if(n2===void 0)return"_unknown";var t2=(n2=n2.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return 48<=t2&&57>=t2?"_"+n2:n2}function U(n2,t2){return n2=W(n2),function(){return t2.apply(this,arguments)}}r="yoga.wasm",S()||(r=i+r);var M=[{},{value:void 0},{value:null},{value:!0},{value:!1}],F=[];function D(n2){var t2=Error,r2=U(n2,function(t3){this.name=n2,this.message=t3,(t3=Error(t3).stack)!==void 0&&(this.stack=this.toString()+`
67
- `+t3.replace(/^Error(:[^\n]*)?\n/,""))});return r2.prototype=Object.create(t2.prototype),r2.prototype.constructor=r2,r2.prototype.toString=function(){return this.message===void 0?this.name:this.name+": "+this.message},r2}var k=void 0;function V(n2){throw new k(n2)}var j=(n2)=>(n2||V("Cannot use deleted val. handle = "+n2),M[n2].value),G=(n2)=>{switch(n2){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:var t2=F.length?F.pop():M.length;return M[t2]={fa:1,value:n2},t2}},Y=void 0,X=void 0;function B(n2){for(var t2="";y[n2];)t2+=X[y[n2++]];return t2}var H=[];function x(){for(;H.length;){var n2=H.pop();n2.L.Z=!1,n2.delete()}}var z=void 0,$={};function Z(n2,t2){for(t2===void 0&&V("ptr should not be undefined");n2.P;)t2=n2.aa(t2),n2=n2.P;return t2}var J={};function q(n2){var t2=B(n2=nz(n2));return nZ(n2),t2}function K(n2,t2){var r2=J[n2];return r2===void 0&&V(t2+" has unknown type "+q(n2)),r2}function Q(){}var nn=!1;function nt(n2){--n2.count.value,n2.count.value===0&&(n2.S?n2.T.V(n2.S):n2.O.M.V(n2.N))}var nr={},ne=void 0;function na(n2){throw new ne(n2)}function ni(n2,t2){return t2.O&&t2.N||na("makeClassHandle requires ptr and ptrType"),!!t2.T!=!!t2.S&&na("Both smartPtrType and smartPtr must be specified"),t2.count={value:1},no(Object.create(n2,{L:{value:t2}}))}function no(n2){return typeof FinalizationRegistry>"u"?(no=(n3)=>n3,n2):(nn=new FinalizationRegistry((n3)=>{nt(n3.L)}),no=(n3)=>{var t2=n3.L;return t2.S&&nn.register(n3,{L:t2},n3),n3},Q=(n3)=>{nn.unregister(n3)},no(n2))}var ns={};function nu(n2){for(;n2.length;){var t2=n2.pop();n2.pop()(t2)}}function nc(n2){return this.fromWireType(g[n2>>2])}var nf={},nl={};function nh(n2,t2,r2){function e2(t3){(t3=r2(t3)).length!==n2.length&&na("Mismatched type converter count");for(var e3=0;e3<n2.length;++e3)nv(n2[e3],t3[e3])}n2.forEach(function(n3){nl[n3]=t2});var a2=Array(t2.length),i2=[],o2=0;t2.forEach((n3,t3)=>{J.hasOwnProperty(n3)?a2[t3]=J[n3]:(i2.push(n3),nf.hasOwnProperty(n3)||(nf[n3]=[]),nf[n3].push(()=>{a2[t3]=J[n3],++o2===i2.length&&e2(a2)}))}),i2.length===0&&e2(a2)}function np(n2){switch(n2){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw TypeError("Unknown type size: "+n2)}}function nv(n2,t2,r2={}){if(!("argPackAdvance"in t2))throw TypeError("registerType registeredInstance requires argPackAdvance");var e2=t2.name;if(n2||V('type "'+e2+'" must have a positive integer typeid pointer'),J.hasOwnProperty(n2)){if(r2.ta)return;V("Cannot register type '"+e2+"' twice")}J[n2]=t2,delete nl[n2],nf.hasOwnProperty(n2)&&(t2=nf[n2],delete nf[n2],t2.forEach((n3)=>n3()))}function nd(n2){V(n2.L.O.M.name+" instance already deleted")}function ny(){}function nm(n2,t2,r2){if(n2[t2].R===void 0){var e2=n2[t2];n2[t2]=function(){return n2[t2].R.hasOwnProperty(arguments.length)||V("Function '"+r2+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+n2[t2].R+")!"),n2[t2].R[arguments.length].apply(this,arguments)},n2[t2].R=[],n2[t2].R[e2.Y]=e2}}function nE(n2,t2,r2,e2,a2,i2,o2,s2){this.name=n2,this.constructor=t2,this.W=r2,this.V=e2,this.P=a2,this.oa=i2,this.aa=o2,this.ma=s2,this.ia=[]}function ng(n2,t2,r2){for(;t2!==r2;)t2.aa||V("Expected null or instance of "+r2.name+", got an instance of "+t2.name),n2=t2.aa(n2),t2=t2.P;return n2}function n_(n2,t2){return t2===null?(this.da&&V("null is not a valid "+this.name),0):(t2.L||V('Cannot pass "'+nC(t2)+'" as a '+this.name),t2.L.N||V("Cannot pass deleted object as a pointer of type "+this.name),ng(t2.L.N,t2.L.O.M,this.M))}function nT(n2,t2){if(t2===null){if(this.da&&V("null is not a valid "+this.name),this.ca){var r2=this.ea();return n2!==null&&n2.push(this.V,r2),r2}return 0}if(t2.L||V('Cannot pass "'+nC(t2)+'" as a '+this.name),t2.L.N||V("Cannot pass deleted object as a pointer of type "+this.name),!this.ba&&t2.L.O.ba&&V("Cannot convert argument of type "+(t2.L.T?t2.L.T.name:t2.L.O.name)+" to parameter type "+this.name),r2=ng(t2.L.N,t2.L.O.M,this.M),this.ca)switch(t2.L.S===void 0&&V("Passing raw pointer to smart pointer is illegal"),this.Aa){case 0:t2.L.T===this?r2=t2.L.S:V("Cannot convert argument of type "+(t2.L.T?t2.L.T.name:t2.L.O.name)+" to parameter type "+this.name);break;case 1:r2=t2.L.S;break;case 2:if(t2.L.T===this)r2=t2.L.S;else{var e2=t2.clone();r2=this.wa(r2,G(function(){e2.delete()})),n2!==null&&n2.push(this.V,r2)}break;default:V("Unsupporting sharing policy")}return r2}function nL(n2,t2){return t2===null?(this.da&&V("null is not a valid "+this.name),0):(t2.L||V('Cannot pass "'+nC(t2)+'" as a '+this.name),t2.L.N||V("Cannot pass deleted object as a pointer of type "+this.name),t2.L.O.ba&&V("Cannot convert argument of type "+t2.L.O.name+" to parameter type "+this.name),ng(t2.L.N,t2.L.O.M,this.M))}function nA(n2,t2,r2,e2){this.name=n2,this.M=t2,this.da=r2,this.ba=e2,this.ca=!1,this.V=this.wa=this.ea=this.ja=this.Aa=this.va=void 0,t2.P!==void 0?this.toWireType=nT:(this.toWireType=e2?n_:nL,this.U=null)}var nO=[];function nP(n2){var t2=nO[n2];return t2||(n2>=nO.length&&(nO.length=n2+1),nO[n2]=t2=A.get(n2)),t2}function nb(n2,t2){var r2,e2,a2=(n2=B(n2)).includes("j")?(r2=n2,e2=[],function(){if(e2.length=0,Object.assign(e2,arguments),r2.includes("j")){var n3=u["dynCall_"+r2];n3=e2&&e2.length?n3.apply(null,[t2].concat(e2)):n3.call(null,t2)}else n3=nP(t2).apply(null,e2);return n3}):nP(t2);return typeof a2!="function"&&V("unknown function pointer with signature "+n2+": "+t2),a2}var nN=void 0;function nI(n2,t2){var r2=[],e2={};throw t2.forEach(function n3(t3){e2[t3]||J[t3]||(nl[t3]?nl[t3].forEach(n3):(r2.push(t3),e2[t3]=!0))}),new nN(n2+": "+r2.map(q).join([", "]))}function nw(n2,t2,r2,e2,a2){var i2=t2.length;2>i2&&V("argTypes array size mismatch! Must at least get return value and 'this' types!");var o2=t2[1]!==null&&r2!==null,s2=!1;for(r2=1;r2<t2.length;++r2)if(t2[r2]!==null&&t2[r2].U===void 0){s2=!0;break}var u2=t2[0].name!=="void",c2=i2-2,f2=Array(c2),l2=[],h2=[];return function(){if(arguments.length!==c2&&V("function "+n2+" called with "+arguments.length+" arguments, expected "+c2+" args!"),h2.length=0,l2.length=o2?2:1,l2[0]=a2,o2){var r3=t2[1].toWireType(h2,this);l2[1]=r3}for(var i3=0;i3<c2;++i3)f2[i3]=t2[i3+2].toWireType(h2,arguments[i3]),l2.push(f2[i3]);if(i3=e2.apply(null,l2),s2)nu(h2);else for(var p2=o2?1:2;p2<t2.length;p2++){var v2=p2===1?r3:f2[p2-2];t2[p2].U!==null&&t2[p2].U(v2)}return u2?t2[0].fromWireType(i3):void 0}}function nS(n2,t2){for(var r2=[],e2=0;e2<n2;e2++)r2.push(_[t2+4*e2>>2]);return r2}function nR(n2){4<n2&&--M[n2].fa==0&&(M[n2]=void 0,F.push(n2))}function nC(n2){if(n2===null)return"null";var t2=typeof n2;return t2==="object"||t2==="array"||t2==="function"?n2.toString():""+n2}function nW(n2,t2){for(var r2="",e2=0;!(e2>=t2/2);++e2){var a2=m[n2+2*e2>>1];if(a2==0)break;r2+=String.fromCharCode(a2)}return r2}function nU(n2,t2,r2){if(r2===void 0&&(r2=2147483647),2>r2)return 0;r2-=2;var e2=t2;r2=r2<2*n2.length?r2/2:n2.length;for(var a2=0;a2<r2;++a2)m[t2>>1]=n2.charCodeAt(a2),t2+=2;return m[t2>>1]=0,t2-e2}function nM(n2){return 2*n2.length}function nF(n2,t2){for(var r2=0,e2="";!(r2>=t2/4);){var a2=g[n2+4*r2>>2];if(a2==0)break;++r2,65536<=a2?(a2-=65536,e2+=String.fromCharCode(55296|a2>>10,56320|1023&a2)):e2+=String.fromCharCode(a2)}return e2}function nD(n2,t2,r2){if(r2===void 0&&(r2=2147483647),4>r2)return 0;var e2=t2;r2=e2+r2-4;for(var a2=0;a2<n2.length;++a2){var i2=n2.charCodeAt(a2);if(55296<=i2&&57343>=i2&&(i2=65536+((1023&i2)<<10)|1023&n2.charCodeAt(++a2)),g[t2>>2]=i2,(t2+=4)+4>r2)break}return g[t2>>2]=0,t2-e2}function nk(n2){for(var t2=0,r2=0;r2<n2.length;++r2){var e2=n2.charCodeAt(r2);55296<=e2&&57343>=e2&&++r2,t2+=4}return t2}var nV={};function nj(n2){var t2=nV[n2];return t2===void 0?B(n2):t2}var nG=[],nY=[],nX=[null,[],[]];k=u.BindingError=D("BindingError"),u.count_emval_handles=function(){for(var n2=0,t2=5;t2<M.length;++t2)M[t2]!==void 0&&++n2;return n2},u.get_first_emval=function(){for(var n2=5;n2<M.length;++n2)if(M[n2]!==void 0)return M[n2];return null},Y=u.PureVirtualError=D("PureVirtualError");for(var nB=Array(256),nH=0;256>nH;++nH)nB[nH]=String.fromCharCode(nH);X=nB,u.getInheritedInstanceCount=function(){return Object.keys($).length},u.getLiveInheritedInstances=function(){var n2,t2=[];for(n2 in $)$.hasOwnProperty(n2)&&t2.push($[n2]);return t2},u.flushPendingDeletes=x,u.setDelayFunction=function(n2){z=n2,H.length&&z&&z(x)},ne=u.InternalError=D("InternalError"),ny.prototype.isAliasOf=function(n2){if(!(this instanceof ny&&n2 instanceof ny))return!1;var t2=this.L.O.M,r2=this.L.N,e2=n2.L.O.M;for(n2=n2.L.N;t2.P;)r2=t2.aa(r2),t2=t2.P;for(;e2.P;)n2=e2.aa(n2),e2=e2.P;return t2===e2&&r2===n2},ny.prototype.clone=function(){if(this.L.N||nd(this),this.L.$)return this.L.count.value+=1,this;var n2=no,t2=Object,r2=t2.create,e2=Object.getPrototypeOf(this),a2=this.L;return n2=n2(r2.call(t2,e2,{L:{value:{count:a2.count,Z:a2.Z,$:a2.$,N:a2.N,O:a2.O,S:a2.S,T:a2.T}}})),n2.L.count.value+=1,n2.L.Z=!1,n2},ny.prototype.delete=function(){this.L.N||nd(this),this.L.Z&&!this.L.$&&V("Object already scheduled for deletion"),Q(this),nt(this.L),this.L.$||(this.L.S=void 0,this.L.N=void 0)},ny.prototype.isDeleted=function(){return!this.L.N},ny.prototype.deleteLater=function(){return this.L.N||nd(this),this.L.Z&&!this.L.$&&V("Object already scheduled for deletion"),H.push(this),H.length===1&&z&&z(x),this.L.Z=!0,this},nA.prototype.pa=function(n2){return this.ja&&(n2=this.ja(n2)),n2},nA.prototype.ga=function(n2){this.V&&this.V(n2)},nA.prototype.argPackAdvance=8,nA.prototype.readValueFromPointer=nc,nA.prototype.deleteObject=function(n2){n2!==null&&n2.delete()},nA.prototype.fromWireType=function(n2){function t2(){return this.ca?ni(this.M.W,{O:this.va,N:e2,T:this,S:n2}):ni(this.M.W,{O:this,N:n2})}var r2,e2=this.pa(n2);if(!e2)return this.ga(n2),null;var a2=$[Z(this.M,e2)];if(a2!==void 0)return a2.L.count.value===0?(a2.L.N=e2,a2.L.S=n2,a2.clone()):(a2=a2.clone(),this.ga(n2),a2);if(!(a2=nr[a2=this.M.oa(e2)]))return t2.call(this);a2=this.ba?a2.ka:a2.pointerType;var i2=function n3(t3,r3,e3){return r3===e3?t3:e3.P===void 0?null:(t3=n3(t3,r3,e3.P))===null?null:e3.ma(t3)}(e2,this.M,a2.M);return i2===null?t2.call(this):this.ca?ni(a2.M.W,{O:a2,N:i2,T:this,S:n2}):ni(a2.M.W,{O:a2,N:i2})},nN=u.UnboundTypeError=D("UnboundTypeError");var nx={q:function(n2,t2,r2){n2=B(n2),t2=K(t2,"wrapper"),r2=j(r2);var e2=[].slice,a2=t2.M,i2=a2.W,o2=a2.P.W,s2=a2.P.constructor;for(var u2 in n2=U(n2,function(){a2.P.ia.forEach(function(n3){if(this[n3]===o2[n3])throw new Y("Pure virtual function "+n3+" must be implemented in JavaScript")}.bind(this)),Object.defineProperty(this,"__parent",{value:i2}),this.__construct.apply(this,e2.call(arguments))}),i2.__construct=function(){this===i2&&V("Pass correct 'this' to __construct");var n3=s2.implement.apply(void 0,[this].concat(e2.call(arguments)));Q(n3);var t3=n3.L;n3.notifyOnDestruction(),t3.$=!0,Object.defineProperties(this,{L:{value:t3}}),no(this),n3=Z(a2,n3=t3.N),$.hasOwnProperty(n3)?V("Tried to register registered instance: "+n3):$[n3]=this},i2.__destruct=function(){this===i2&&V("Pass correct 'this' to __destruct"),Q(this);var n3=this.L.N;n3=Z(a2,n3),$.hasOwnProperty(n3)?delete $[n3]:V("Tried to unregister unregistered instance: "+n3)},n2.prototype=Object.create(i2),r2)n2.prototype[u2]=r2[u2];return G(n2)},l:function(n2){var t2=ns[n2];delete ns[n2];var{ea:r2,V:e2,ha:a2}=t2;nh([n2],a2.map((n3)=>n3.sa).concat(a2.map((n3)=>n3.ya)),(n3)=>{var i2={};return a2.forEach((t3,r3)=>{var e3=n3[r3],o2=t3.qa,s2=t3.ra,u2=n3[r3+a2.length],c2=t3.xa,f2=t3.za;i2[t3.na]={read:(n4)=>e3.fromWireType(o2(s2,n4)),write:(n4,t4)=>{var r4=[];c2(f2,n4,u2.toWireType(r4,t4)),nu(r4)}}}),[{name:t2.name,fromWireType:function(n4){var t3,r3={};for(t3 in i2)r3[t3]=i2[t3].read(n4);return e2(n4),r3},toWireType:function(n4,t3){for(var a3 in i2)if(!(a3 in t3))throw TypeError('Missing field: "'+a3+'"');var o2=r2();for(a3 in i2)i2[a3].write(o2,t3[a3]);return n4!==null&&n4.push(e2,o2),o2},argPackAdvance:8,readValueFromPointer:nc,U:e2}]})},v:function(){},B:function(n2,t2,r2,e2,a2){var i2=np(r2);nv(n2,{name:t2=B(t2),fromWireType:function(n3){return!!n3},toWireType:function(n3,t3){return t3?e2:a2},argPackAdvance:8,readValueFromPointer:function(n3){if(r2===1)var e3=d;else if(r2===2)e3=m;else if(r2===4)e3=g;else throw TypeError("Unknown boolean type size: "+t2);return this.fromWireType(e3[n3>>i2])},U:null})},h:function(n2,t2,r2,e2,a2,i2,o2,s2,c2,f2,l2,h2,p2){l2=B(l2),i2=nb(a2,i2),s2&&(s2=nb(o2,s2)),f2&&(f2=nb(c2,f2)),p2=nb(h2,p2);var v2,d2=W(l2);v2=function(){nI("Cannot construct "+l2+" due to unbound types",[e2])},u.hasOwnProperty(d2)?(V("Cannot register public name '"+d2+"' twice"),nm(u,d2,d2),u.hasOwnProperty(void 0)&&V("Cannot register multiple overloads of a function with the same number of arguments (undefined)!"),u[d2].R[void 0]=v2):u[d2]=v2,nh([n2,t2,r2],e2?[e2]:[],function(t3){if(t3=t3[0],e2)var r3,a3=t3.M,o3=a3.W;else o3=ny.prototype;t3=U(d2,function(){if(Object.getPrototypeOf(this)!==c3)throw new k("Use 'new' to construct "+l2);if(h3.X===void 0)throw new k(l2+" has no accessible constructor");var n3=h3.X[arguments.length];if(n3===void 0)throw new k("Tried to invoke ctor of "+l2+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(h3.X).toString()+") parameters instead!");return n3.apply(this,arguments)});var c3=Object.create(o3,{constructor:{value:t3}});t3.prototype=c3;var h3=new nE(l2,t3,c3,p2,a3,i2,s2,f2);a3=new nA(l2,h3,!0,!1),o3=new nA(l2+"*",h3,!1,!1);var v3=new nA(l2+" const*",h3,!1,!0);return nr[n2]={pointerType:o3,ka:v3},r3=t3,u.hasOwnProperty(d2)||na("Replacing nonexistant public symbol"),u[d2]=r3,u[d2].Y=void 0,[a3,o3,v3]})},d:function(n2,t2,r2,e2,a2,i2,o2){var s2=nS(r2,e2);t2=B(t2),i2=nb(a2,i2),nh([],[n2],function(n3){function e3(){nI("Cannot call "+a3+" due to unbound types",s2)}var a3=(n3=n3[0]).name+"."+t2;t2.startsWith("@@")&&(t2=Symbol[t2.substring(2)]);var u2=n3.M.constructor;return u2[t2]===void 0?(e3.Y=r2-1,u2[t2]=e3):(nm(u2,t2,a3),u2[t2].R[r2-1]=e3),nh([],s2,function(n4){return n4=nw(a3,[n4[0],null].concat(n4.slice(1)),null,i2,o2),u2[t2].R===void 0?(n4.Y=r2-1,u2[t2]=n4):u2[t2].R[r2-1]=n4,[]}),[]})},p:function(n2,t2,r2,e2,a2,i2){0<t2||w();var o2=nS(t2,r2);a2=nb(e2,a2),nh([],[n2],function(n3){var r3="constructor "+(n3=n3[0]).name;if(n3.M.X===void 0&&(n3.M.X=[]),n3.M.X[t2-1]!==void 0)throw new k("Cannot register multiple constructors with identical number of parameters ("+(t2-1)+") for class '"+n3.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return n3.M.X[t2-1]=()=>{nI("Cannot construct "+n3.name+" due to unbound types",o2)},nh([],o2,function(e3){return e3.splice(1,0,null),n3.M.X[t2-1]=nw(r3,e3,null,a2,i2),[]}),[]})},a:function(n2,t2,r2,e2,a2,i2,o2,s2){var u2=nS(r2,e2);t2=B(t2),i2=nb(a2,i2),nh([],[n2],function(n3){function e3(){nI("Cannot call "+a3+" due to unbound types",u2)}var a3=(n3=n3[0]).name+"."+t2;t2.startsWith("@@")&&(t2=Symbol[t2.substring(2)]),s2&&n3.M.ia.push(t2);var c2=n3.M.W,f2=c2[t2];return f2===void 0||f2.R===void 0&&f2.className!==n3.name&&f2.Y===r2-2?(e3.Y=r2-2,e3.className=n3.name,c2[t2]=e3):(nm(c2,t2,a3),c2[t2].R[r2-2]=e3),nh([],u2,function(e4){return e4=nw(a3,e4,n3,i2,o2),c2[t2].R===void 0?(e4.Y=r2-2,c2[t2]=e4):c2[t2].R[r2-2]=e4,[]}),[]})},A:function(n2,t2){nv(n2,{name:t2=B(t2),fromWireType:function(n3){var t3=j(n3);return nR(n3),t3},toWireType:function(n3,t3){return G(t3)},argPackAdvance:8,readValueFromPointer:nc,U:null})},n:function(n2,t2,r2){r2=np(r2),nv(n2,{name:t2=B(t2),fromWireType:function(n3){return n3},toWireType:function(n3,t3){return t3},argPackAdvance:8,readValueFromPointer:function(n3,t3){switch(t3){case 2:return function(n4){return this.fromWireType(T[n4>>2])};case 3:return function(n4){return this.fromWireType(L[n4>>3])};default:throw TypeError("Unknown float type: "+n3)}}(t2,r2),U:null})},e:function(n2,t2,r2,e2,a2){t2=B(t2),a2===-1&&(a2=4294967295),a2=np(r2);var i2=(n3)=>n3;if(e2===0){var o2=32-8*r2;i2=(n3)=>n3<<o2>>>o2}r2=t2.includes("unsigned")?function(n3,t3){return t3>>>0}:function(n3,t3){return t3},nv(n2,{name:t2,fromWireType:i2,toWireType:r2,argPackAdvance:8,readValueFromPointer:function(n3,t3,r3){switch(t3){case 0:return r3?function(n4){return d[n4]}:function(n4){return y[n4]};case 1:return r3?function(n4){return m[n4>>1]}:function(n4){return E[n4>>1]};case 2:return r3?function(n4){return g[n4>>2]}:function(n4){return _[n4>>2]};default:throw TypeError("Unknown integer type: "+n3)}}(t2,a2,e2!==0),U:null})},b:function(n2,t2,r2){function e2(n3){n3>>=2;var t3=_;return new a2(t3.buffer,t3[n3+1],t3[n3])}var a2=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][t2];nv(n2,{name:r2=B(r2),fromWireType:e2,argPackAdvance:8,readValueFromPointer:e2},{ta:!0})},o:function(n2,t2){var r2=(t2=B(t2))==="std::string";nv(n2,{name:t2,fromWireType:function(n3){var t3=_[n3>>2],e2=n3+4;if(r2)for(var a2=e2,i2=0;i2<=t3;++i2){var o2=e2+i2;if(i2==t3||y[o2]==0){if(a2=a2?p(y,a2,o2-a2):"",s2===void 0)var s2=a2;else s2+="\x00"+a2;a2=o2+1}}else{for(i2=0,s2=Array(t3);i2<t3;++i2)s2[i2]=String.fromCharCode(y[e2+i2]);s2=s2.join("")}return nZ(n3),s2},toWireType:function(n3,t3){t3 instanceof ArrayBuffer&&(t3=new Uint8Array(t3));var e2,a2=typeof t3=="string";if(a2||t3 instanceof Uint8Array||t3 instanceof Uint8ClampedArray||t3 instanceof Int8Array||V("Cannot pass non-string to std::string"),r2&&a2){var i2=0;for(e2=0;e2<t3.length;++e2){var o2=t3.charCodeAt(e2);127>=o2?i2++:2047>=o2?i2+=2:55296<=o2&&57343>=o2?(i2+=4,++e2):i2+=3}e2=i2}else e2=t3.length;if(o2=(i2=n$(4+e2+1))+4,_[i2>>2]=e2,r2&&a2){if(a2=o2,o2=e2+1,e2=y,0<o2){o2=a2+o2-1;for(var s2=0;s2<t3.length;++s2){var u2=t3.charCodeAt(s2);if(55296<=u2&&57343>=u2&&(u2=65536+((1023&u2)<<10)|1023&t3.charCodeAt(++s2)),127>=u2){if(a2>=o2)break;e2[a2++]=u2}else{if(2047>=u2){if(a2+1>=o2)break;e2[a2++]=192|u2>>6}else{if(65535>=u2){if(a2+2>=o2)break;e2[a2++]=224|u2>>12}else{if(a2+3>=o2)break;e2[a2++]=240|u2>>18,e2[a2++]=128|u2>>12&63}e2[a2++]=128|u2>>6&63}e2[a2++]=128|63&u2}}e2[a2]=0}}else if(a2)for(a2=0;a2<e2;++a2)255<(s2=t3.charCodeAt(a2))&&(nZ(o2),V("String has UTF-16 code units that do not fit in 8 bits")),y[o2+a2]=s2;else for(a2=0;a2<e2;++a2)y[o2+a2]=t3[a2];return n3!==null&&n3.push(nZ,i2),i2},argPackAdvance:8,readValueFromPointer:nc,U:function(n3){nZ(n3)}})},k:function(n2,t2,r2){if(r2=B(r2),t2===2)var e2=nW,a2=nU,i2=nM,o2=()=>E,s2=1;else t2===4&&(e2=nF,a2=nD,i2=nk,o2=()=>_,s2=2);nv(n2,{name:r2,fromWireType:function(n3){for(var r3,a3=_[n3>>2],i3=o2(),u2=n3+4,c2=0;c2<=a3;++c2){var f2=n3+4+c2*t2;(c2==a3||i3[f2>>s2]==0)&&(u2=e2(u2,f2-u2),r3===void 0?r3=u2:r3+="\x00"+u2,u2=f2+t2)}return nZ(n3),r3},toWireType:function(n3,e3){typeof e3!="string"&&V("Cannot pass non-string to C++ string type "+r2);var o3=i2(e3),u2=n$(4+o3+t2);return _[u2>>2]=o3>>s2,a2(e3,u2+4,o3+t2),n3!==null&&n3.push(nZ,u2),u2},argPackAdvance:8,readValueFromPointer:nc,U:function(n3){nZ(n3)}})},m:function(n2,t2,r2,e2,a2,i2){ns[n2]={name:B(t2),ea:nb(r2,e2),V:nb(a2,i2),ha:[]}},c:function(n2,t2,r2,e2,a2,i2,o2,s2,u2,c2){ns[n2].ha.push({na:B(t2),sa:r2,qa:nb(e2,a2),ra:i2,ya:o2,xa:nb(s2,u2),za:c2})},C:function(n2,t2){nv(n2,{ua:!0,name:t2=B(t2),argPackAdvance:0,fromWireType:function(){},toWireType:function(){}})},t:function(n2,t2,r2,e2,a2){n2=nG[n2],t2=j(t2),r2=nj(r2);var i2=[];return _[e2>>2]=G(i2),n2(t2,r2,i2,a2)},j:function(n2,t2,r2,e2){n2=nG[n2],n2(t2=j(t2),r2=nj(r2),null,e2)},f:nR,g:function(n2,t2){var r2,e2,a2=function(n3,t3){for(var r3=Array(n3),e3=0;e3<n3;++e3)r3[e3]=K(_[t3+4*e3>>2],"parameter "+e3);return r3}(n2,t2),i2=a2[0],o2=nY[t2=i2.name+"_$"+a2.slice(1).map(function(n3){return n3.name}).join("_")+"$"];if(o2!==void 0)return o2;var s2=Array(n2-1);return r2=(t3,r3,e3,o3)=>{for(var u2=0,c2=0;c2<n2-1;++c2)s2[c2]=a2[c2+1].readValueFromPointer(o3+u2),u2+=a2[c2+1].argPackAdvance;for(c2=0,t3=t3[r3].apply(t3,s2);c2<n2-1;++c2)a2[c2+1].la&&a2[c2+1].la(s2[c2]);if(!i2.ua)return i2.toWireType(e3,t3)},e2=nG.length,nG.push(r2),o2=e2,nY[t2]=o2},r:function(n2){4<n2&&(M[n2].fa+=1)},s:function(n2){nu(j(n2)),nR(n2)},i:function(){w("")},x:function(n2,t2,r2){y.copyWithin(n2,t2,t2+r2)},w:function(n2){var t2=y.length;if(2147483648<(n2>>>=0))return!1;for(var r2=1;4>=r2;r2*=2){var e2=t2*(1+0.2/r2);e2=Math.min(e2,n2+100663296);var a2=Math,i2=a2.min;e2=Math.max(n2,e2),e2+=(65536-e2%65536)%65536;n:{var o2=l.buffer;try{l.grow(i2.call(a2,2147483648,e2)-o2.byteLength+65535>>>16),v();var s2=1;break n}catch(n3){}s2=void 0}if(s2)return!0}return!1},z:function(){return 52},u:function(){return 70},y:function(n2,t2,r2,e2){for(var a2=0,i2=0;i2<r2;i2++){var u2=_[t2>>2],c2=_[t2+4>>2];t2+=8;for(var f2=0;f2<c2;f2++){var l2=y[u2+f2],h2=nX[n2];l2===0||l2===10?((n2===1?o:s)(p(h2,0)),h2.length=0):h2.push(l2)}a2+=c2}return _[e2>>2]=a2,0}};(function(){function n2(n3){u.asm=n3.exports,l=u.asm.D,v(),A=u.asm.I,P.unshift(u.asm.E),--N==0&&I&&(n3=I,I=null,n3())}function t2(t3){n2(t3.instance)}function e2(n3){return(typeof fetch=="function"?fetch(r,{credentials:"same-origin"}).then(function(n4){if(!n4.ok)throw"failed to load wasm binary file at '"+r+"'";return n4.arrayBuffer()}).catch(function(){return R()}):Promise.resolve().then(function(){return R()})).then(function(n4){return WebAssembly.instantiate(n4,a2)}).then(function(n4){return n4}).then(n3,function(n4){s("failed to asynchronously prepare wasm: "+n4),w(n4)})}var a2={a:nx};if(N++,u.instantiateWasm)try{return u.instantiateWasm(a2,n2)}catch(n3){s("Module.instantiateWasm callback failed with error: "+n3),f(n3)}(typeof WebAssembly.instantiateStreaming!="function"||S()||typeof fetch!="function"?e2(t2):fetch(r,{credentials:"same-origin"}).then(function(n3){return WebAssembly.instantiateStreaming(n3,a2).then(t2,function(n4){return s("wasm streaming compile failed: "+n4),s("falling back to ArrayBuffer instantiation"),e2(t2)})})).catch(f)})();var nz=u.___getTypeName=function(){return(nz=u.___getTypeName=u.asm.F).apply(null,arguments)};function n$(){return(n$=u.asm.H).apply(null,arguments)}function nZ(){return(nZ=u.asm.J).apply(null,arguments)}function nJ(){0<N||(C(O),0<N||e||(e=!0,u.calledRun=!0,h||(C(P),c(u),C(b))))}return u.__embind_initialize_bindings=function(){return(u.__embind_initialize_bindings=u.asm.G).apply(null,arguments)},u.dynCall_jiji=function(){return(u.dynCall_jiji=u.asm.K).apply(null,arguments)},I=function n2(){e||nJ(),e||(I=n2)},nJ(),t.ready}})()});var exports_node={};__export(exports_node,{default:()=>Yoga,WRAP_WRAP_REVERSE:()=>WRAP_WRAP_REVERSE,WRAP_WRAP:()=>WRAP_WRAP,WRAP_NO_WRAP:()=>WRAP_NO_WRAP,UNIT_UNDEFINED:()=>UNIT_UNDEFINED,UNIT_POINT:()=>UNIT_POINT,UNIT_PERCENT:()=>UNIT_PERCENT,UNIT_AUTO:()=>UNIT_AUTO,PRINT_OPTIONS_STYLE:()=>PRINT_OPTIONS_STYLE,PRINT_OPTIONS_LAYOUT:()=>PRINT_OPTIONS_LAYOUT,PRINT_OPTIONS_CHILDREN:()=>PRINT_OPTIONS_CHILDREN,POSITION_TYPE_STATIC:()=>POSITION_TYPE_STATIC,POSITION_TYPE_RELATIVE:()=>POSITION_TYPE_RELATIVE,POSITION_TYPE_ABSOLUTE:()=>POSITION_TYPE_ABSOLUTE,OVERFLOW_VISIBLE:()=>OVERFLOW_VISIBLE,OVERFLOW_SCROLL:()=>OVERFLOW_SCROLL,OVERFLOW_HIDDEN:()=>OVERFLOW_HIDDEN,NODE_TYPE_TEXT:()=>NODE_TYPE_TEXT,NODE_TYPE_DEFAULT:()=>NODE_TYPE_DEFAULT,MEASURE_MODE_UNDEFINED:()=>MEASURE_MODE_UNDEFINED,MEASURE_MODE_EXACTLY:()=>MEASURE_MODE_EXACTLY,MEASURE_MODE_AT_MOST:()=>MEASURE_MODE_AT_MOST,LOG_LEVEL_WARN:()=>LOG_LEVEL_WARN,LOG_LEVEL_VERBOSE:()=>LOG_LEVEL_VERBOSE,LOG_LEVEL_INFO:()=>LOG_LEVEL_INFO,LOG_LEVEL_FATAL:()=>LOG_LEVEL_FATAL,LOG_LEVEL_ERROR:()=>LOG_LEVEL_ERROR,LOG_LEVEL_DEBUG:()=>LOG_LEVEL_DEBUG,JUSTIFY_SPACE_EVENLY:()=>JUSTIFY_SPACE_EVENLY,JUSTIFY_SPACE_BETWEEN:()=>JUSTIFY_SPACE_BETWEEN,JUSTIFY_SPACE_AROUND:()=>JUSTIFY_SPACE_AROUND,JUSTIFY_FLEX_START:()=>JUSTIFY_FLEX_START,JUSTIFY_FLEX_END:()=>JUSTIFY_FLEX_END,JUSTIFY_CENTER:()=>JUSTIFY_CENTER,GUTTER_ROW:()=>GUTTER_ROW,GUTTER_COLUMN:()=>GUTTER_COLUMN,GUTTER_ALL:()=>GUTTER_ALL,FLEX_DIRECTION_ROW_REVERSE:()=>FLEX_DIRECTION_ROW_REVERSE,FLEX_DIRECTION_ROW:()=>FLEX_DIRECTION_ROW,FLEX_DIRECTION_COLUMN_REVERSE:()=>FLEX_DIRECTION_COLUMN_REVERSE,FLEX_DIRECTION_COLUMN:()=>FLEX_DIRECTION_COLUMN,EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS:()=>EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS,EXPERIMENTAL_FEATURE_FIX_ABSOLUTE_TRAILING_COLUMN_MARGIN:()=>EXPERIMENTAL_FEATURE_FIX_ABSOLUTE_TRAILING_COLUMN_MARGIN,EXPERIMENTAL_FEATURE_ABSOLUTE_PERCENTAGE_AGAINST_PADDING_EDGE:()=>EXPERIMENTAL_FEATURE_ABSOLUTE_PERCENTAGE_AGAINST_PADDING_EDGE,EDGE_VERTICAL:()=>EDGE_VERTICAL,EDGE_TOP:()=>EDGE_TOP,EDGE_START:()=>EDGE_START,EDGE_RIGHT:()=>EDGE_RIGHT,EDGE_LEFT:()=>EDGE_LEFT,EDGE_HORIZONTAL:()=>EDGE_HORIZONTAL,EDGE_END:()=>EDGE_END,EDGE_BOTTOM:()=>EDGE_BOTTOM,EDGE_ALL:()=>EDGE_ALL,DISPLAY_NONE:()=>DISPLAY_NONE,DISPLAY_FLEX:()=>DISPLAY_FLEX,DIRECTION_RTL:()=>DIRECTION_RTL,DIRECTION_LTR:()=>DIRECTION_LTR,DIRECTION_INHERIT:()=>DIRECTION_INHERIT,DIMENSION_WIDTH:()=>DIMENSION_WIDTH,DIMENSION_HEIGHT:()=>DIMENSION_HEIGHT,ALIGN_STRETCH:()=>ALIGN_STRETCH,ALIGN_SPACE_BETWEEN:()=>ALIGN_SPACE_BETWEEN,ALIGN_SPACE_AROUND:()=>ALIGN_SPACE_AROUND,ALIGN_FLEX_START:()=>ALIGN_FLEX_START,ALIGN_FLEX_END:()=>ALIGN_FLEX_END,ALIGN_CENTER:()=>ALIGN_CENTER,ALIGN_BASELINE:()=>ALIGN_BASELINE,ALIGN_AUTO:()=>ALIGN_AUTO});import{readFile as E}from"node:fs/promises";import{createRequire as _}from"node:module";var Yoga;var init_node=__esm(async()=>{init_dist();init_wrapAsm_f766f97f();Yoga=await initYoga(await E(_(import.meta.url).resolve("./yoga.wasm")))});var exports_yoga_adapter={};__export(exports_yoga_adapter,{initYogaEngine:()=>initYogaEngine,createYogaEngine:()=>createYogaEngine,YogaLayoutEngine:()=>YogaLayoutEngine});class YogaNodeAdapter{node;yoga;hasMeasureFunc=!1;constructor(node,yoga2){this.node=node,this.yoga=yoga2}getYogaNode(){return this.node}insertChild(child,index){let yogaChild=child.getYogaNode();this.node.insertChild(yogaChild,index)}removeChild(child){let yogaChild=child.getYogaNode();this.node.removeChild(yogaChild)}free(){this.node.free()}setMeasureFunc(measureFunc){this.hasMeasureFunc=!0,this.node.setMeasureFunc((width,widthMode,height,heightMode)=>{let widthModeStr=this.measureModeToString(widthMode),heightModeStr=this.measureModeToString(heightMode);return measureFunc(width,widthModeStr,height,heightModeStr)})}markDirty(){if(this.hasMeasureFunc)this.node.markDirty()}measureModeToString(mode){if(mode===this.yoga.MEASURE_MODE_EXACTLY)return"exactly";if(mode===this.yoga.MEASURE_MODE_AT_MOST)return"at-most";return"undefined"}setWidth(value){this.node.setWidth(value)}setWidthPercent(value){this.node.setWidthPercent(value)}setWidthAuto(){this.node.setWidthAuto()}setHeight(value){this.node.setHeight(value)}setHeightPercent(value){this.node.setHeightPercent(value)}setHeightAuto(){this.node.setHeightAuto()}setMinWidth(value){this.node.setMinWidth(value)}setMinWidthPercent(value){this.node.setMinWidthPercent(value)}setMinHeight(value){this.node.setMinHeight(value)}setMinHeightPercent(value){this.node.setMinHeightPercent(value)}setMaxWidth(value){this.node.setMaxWidth(value)}setMaxWidthPercent(value){this.node.setMaxWidthPercent(value)}setMaxHeight(value){this.node.setMaxHeight(value)}setMaxHeightPercent(value){this.node.setMaxHeightPercent(value)}setFlexGrow(value){this.node.setFlexGrow(value)}setFlexShrink(value){this.node.setFlexShrink(value)}setFlexBasis(value){this.node.setFlexBasis(value)}setFlexBasisPercent(value){this.node.setFlexBasisPercent(value)}setFlexBasisAuto(){this.node.setFlexBasisAuto()}setFlexDirection(direction){this.node.setFlexDirection(direction)}setFlexWrap(wrap){this.node.setFlexWrap(wrap)}setAlignItems(align){this.node.setAlignItems(align)}setAlignSelf(align){this.node.setAlignSelf(align)}setAlignContent(align){this.node.setAlignContent(align)}setJustifyContent(justify){this.node.setJustifyContent(justify)}setPadding(edge,value){this.node.setPadding(edge,value)}setMargin(edge,value){this.node.setMargin(edge,value)}setBorder(edge,value){this.node.setBorder(edge,value)}setGap(gutter,value){this.node.setGap(gutter,value)}setDisplay(display){this.node.setDisplay(display)}setPositionType(positionType){this.node.setPositionType(positionType)}setPosition(edge,value){this.node.setPosition(edge,value)}setPositionPercent(edge,value){this.node.setPositionPercent(edge,value)}setOverflow(overflow){this.node.setOverflow(overflow)}setAspectRatio(value){this.node.setAspectRatio(value)}calculateLayout(width,height,direction){this.node.calculateLayout(width,height,direction??this.yoga.DIRECTION_LTR)}getComputedLeft(){return this.node.getComputedLeft()}getComputedTop(){return this.node.getComputedTop()}getComputedWidth(){return this.node.getComputedWidth()}getComputedHeight(){return this.node.getComputedHeight()}}class YogaLayoutEngine{yoga;_constants;constructor(yoga2){this.yoga=yoga2,this._constants={FLEX_DIRECTION_COLUMN:yoga2.FLEX_DIRECTION_COLUMN,FLEX_DIRECTION_COLUMN_REVERSE:yoga2.FLEX_DIRECTION_COLUMN_REVERSE,FLEX_DIRECTION_ROW:yoga2.FLEX_DIRECTION_ROW,FLEX_DIRECTION_ROW_REVERSE:yoga2.FLEX_DIRECTION_ROW_REVERSE,WRAP_NO_WRAP:yoga2.WRAP_NO_WRAP,WRAP_WRAP:yoga2.WRAP_WRAP,WRAP_WRAP_REVERSE:yoga2.WRAP_WRAP_REVERSE,ALIGN_AUTO:yoga2.ALIGN_AUTO,ALIGN_FLEX_START:yoga2.ALIGN_FLEX_START,ALIGN_CENTER:yoga2.ALIGN_CENTER,ALIGN_FLEX_END:yoga2.ALIGN_FLEX_END,ALIGN_STRETCH:yoga2.ALIGN_STRETCH,ALIGN_BASELINE:yoga2.ALIGN_BASELINE,ALIGN_SPACE_BETWEEN:yoga2.ALIGN_SPACE_BETWEEN,ALIGN_SPACE_AROUND:yoga2.ALIGN_SPACE_AROUND,ALIGN_SPACE_EVENLY:yoga2.ALIGN_SPACE_EVENLY,JUSTIFY_FLEX_START:yoga2.JUSTIFY_FLEX_START,JUSTIFY_CENTER:yoga2.JUSTIFY_CENTER,JUSTIFY_FLEX_END:yoga2.JUSTIFY_FLEX_END,JUSTIFY_SPACE_BETWEEN:yoga2.JUSTIFY_SPACE_BETWEEN,JUSTIFY_SPACE_AROUND:yoga2.JUSTIFY_SPACE_AROUND,JUSTIFY_SPACE_EVENLY:yoga2.JUSTIFY_SPACE_EVENLY,EDGE_LEFT:yoga2.EDGE_LEFT,EDGE_TOP:yoga2.EDGE_TOP,EDGE_RIGHT:yoga2.EDGE_RIGHT,EDGE_BOTTOM:yoga2.EDGE_BOTTOM,EDGE_HORIZONTAL:yoga2.EDGE_HORIZONTAL,EDGE_VERTICAL:yoga2.EDGE_VERTICAL,EDGE_ALL:yoga2.EDGE_ALL,GUTTER_COLUMN:yoga2.GUTTER_COLUMN,GUTTER_ROW:yoga2.GUTTER_ROW,GUTTER_ALL:yoga2.GUTTER_ALL,DISPLAY_FLEX:yoga2.DISPLAY_FLEX,DISPLAY_NONE:yoga2.DISPLAY_NONE,POSITION_TYPE_STATIC:yoga2.POSITION_TYPE_STATIC,POSITION_TYPE_RELATIVE:yoga2.POSITION_TYPE_RELATIVE,POSITION_TYPE_ABSOLUTE:yoga2.POSITION_TYPE_ABSOLUTE,OVERFLOW_VISIBLE:yoga2.OVERFLOW_VISIBLE,OVERFLOW_HIDDEN:yoga2.OVERFLOW_HIDDEN,OVERFLOW_SCROLL:yoga2.OVERFLOW_SCROLL,DIRECTION_LTR:yoga2.DIRECTION_LTR,MEASURE_MODE_UNDEFINED:yoga2.MEASURE_MODE_UNDEFINED,MEASURE_MODE_EXACTLY:yoga2.MEASURE_MODE_EXACTLY,MEASURE_MODE_AT_MOST:yoga2.MEASURE_MODE_AT_MOST}}createNode(){return new YogaNodeAdapter(this.yoga.Node.create(),this.yoga)}get constants(){return this._constants}get name(){return"yoga"}}function createYogaEngine(yoga2){return new YogaLayoutEngine(yoga2)}async function initYogaEngine(){let{default:yoga2}=await init_node().then(() => exports_node);return new YogaLayoutEngine(yoga2)}var exports_flexily_zero_adapter={};__export(exports_flexily_zero_adapter,{createFlexilyZeroEngine:()=>createFlexilyZeroEngine,FlexilyZeroLayoutEngine:()=>FlexilyZeroLayoutEngine});import{ALIGN_AUTO as ALIGN_AUTO2,ALIGN_BASELINE as ALIGN_BASELINE2,ALIGN_CENTER as ALIGN_CENTER2,ALIGN_FLEX_END as ALIGN_FLEX_END2,ALIGN_FLEX_START as ALIGN_FLEX_START2,ALIGN_SPACE_AROUND as ALIGN_SPACE_AROUND2,ALIGN_SPACE_BETWEEN as ALIGN_SPACE_BETWEEN2,ALIGN_SPACE_EVENLY,ALIGN_STRETCH as ALIGN_STRETCH2,DIRECTION_LTR as DIRECTION_LTR2,DISPLAY_FLEX as DISPLAY_FLEX2,DISPLAY_NONE as DISPLAY_NONE2,EDGE_ALL as EDGE_ALL2,EDGE_BOTTOM as EDGE_BOTTOM2,EDGE_HORIZONTAL as EDGE_HORIZONTAL2,EDGE_LEFT as EDGE_LEFT2,EDGE_RIGHT as EDGE_RIGHT2,EDGE_TOP as EDGE_TOP2,EDGE_VERTICAL as EDGE_VERTICAL2,FLEX_DIRECTION_COLUMN as FLEX_DIRECTION_COLUMN2,FLEX_DIRECTION_COLUMN_REVERSE as FLEX_DIRECTION_COLUMN_REVERSE2,FLEX_DIRECTION_ROW as FLEX_DIRECTION_ROW2,FLEX_DIRECTION_ROW_REVERSE as FLEX_DIRECTION_ROW_REVERSE2,Node as FlexilyNode,GUTTER_ALL as GUTTER_ALL2,GUTTER_COLUMN as GUTTER_COLUMN2,GUTTER_ROW as GUTTER_ROW2,JUSTIFY_CENTER as JUSTIFY_CENTER2,JUSTIFY_FLEX_END as JUSTIFY_FLEX_END2,JUSTIFY_FLEX_START as JUSTIFY_FLEX_START2,JUSTIFY_SPACE_AROUND as JUSTIFY_SPACE_AROUND2,JUSTIFY_SPACE_BETWEEN as JUSTIFY_SPACE_BETWEEN2,JUSTIFY_SPACE_EVENLY as JUSTIFY_SPACE_EVENLY2,MEASURE_MODE_AT_MOST as MEASURE_MODE_AT_MOST2,MEASURE_MODE_EXACTLY as MEASURE_MODE_EXACTLY2,MEASURE_MODE_UNDEFINED as MEASURE_MODE_UNDEFINED2,OVERFLOW_HIDDEN as OVERFLOW_HIDDEN2,OVERFLOW_SCROLL as OVERFLOW_SCROLL2,OVERFLOW_VISIBLE as OVERFLOW_VISIBLE2,POSITION_TYPE_ABSOLUTE as POSITION_TYPE_ABSOLUTE2,POSITION_TYPE_RELATIVE as POSITION_TYPE_RELATIVE2,POSITION_TYPE_STATIC as POSITION_TYPE_STATIC2,WRAP_NO_WRAP as WRAP_NO_WRAP2,WRAP_WRAP as WRAP_WRAP2,WRAP_WRAP_REVERSE as WRAP_WRAP_REVERSE2}from"flexily";class FlexilyZeroNodeAdapter{node;constructor(node){this.node=node}getFlexilyNode(){return this.node}insertChild(child,index){let flexilyChild=child.getFlexilyNode();this.node.insertChild(flexilyChild,index)}removeChild(child){let flexilyChild=child.getFlexilyNode();this.node.removeChild(flexilyChild)}free(){this.node.free()}setMeasureFunc(measureFunc){this.node.setMeasureFunc((width,widthMode,height,heightMode)=>{let widthModeStr=this.measureModeToString(widthMode),heightModeStr=this.measureModeToString(heightMode);return measureFunc(width,widthModeStr,height,heightModeStr)})}markDirty(){this.node.markDirty()}measureModeToString(mode){if(mode===MEASURE_MODE_EXACTLY2)return"exactly";if(mode===MEASURE_MODE_AT_MOST2)return"at-most";return"undefined"}setWidth(value){this.node.setWidth(value)}setWidthPercent(value){this.node.setWidthPercent(value)}setWidthAuto(){this.node.setWidthAuto()}setHeight(value){this.node.setHeight(value)}setHeightPercent(value){this.node.setHeightPercent(value)}setHeightAuto(){this.node.setHeightAuto()}setMinWidth(value){this.node.setMinWidth(value)}setMinWidthPercent(value){this.node.setMinWidthPercent(value)}setMinHeight(value){this.node.setMinHeight(value)}setMinHeightPercent(value){this.node.setMinHeightPercent(value)}setMaxWidth(value){this.node.setMaxWidth(value)}setMaxWidthPercent(value){this.node.setMaxWidthPercent(value)}setMaxHeight(value){this.node.setMaxHeight(value)}setMaxHeightPercent(value){this.node.setMaxHeightPercent(value)}setFlexGrow(value){this.node.setFlexGrow(value)}setFlexShrink(value){this.node.setFlexShrink(value)}setFlexBasis(value){this.node.setFlexBasis(value)}setFlexBasisPercent(value){this.node.setFlexBasisPercent(value)}setFlexBasisAuto(){this.node.setFlexBasisAuto()}setFlexDirection(direction){this.node.setFlexDirection(direction)}setFlexWrap(wrap){this.node.setFlexWrap(wrap)}setAlignItems(align){this.node.setAlignItems(align)}setAlignSelf(align){this.node.setAlignSelf(align)}setAlignContent(align){this.node.setAlignContent(align)}setJustifyContent(justify){this.node.setJustifyContent(justify)}setPadding(edge,value){this.node.setPadding(edge,value)}setMargin(edge,value){this.node.setMargin(edge,value)}setBorder(edge,value){this.node.setBorder(edge,value)}setGap(gutter,value){this.node.setGap(gutter,value)}setDisplay(display){this.node.setDisplay(display)}setPositionType(positionType){this.node.setPositionType(positionType)}setPosition(edge,value){this.node.setPosition(edge,value)}setPositionPercent(edge,value){this.node.setPositionPercent(edge,value)}setOverflow(overflow){this.node.setOverflow(overflow)}setAspectRatio(value){this.node.setAspectRatio(value)}calculateLayout(width,height,direction){this.node.calculateLayout(width,height,direction??DIRECTION_LTR2)}getComputedLeft(){return this.node.getComputedLeft()}getComputedTop(){return this.node.getComputedTop()}getComputedWidth(){return this.node.getComputedWidth()}getComputedHeight(){return this.node.getComputedHeight()}}class FlexilyZeroLayoutEngine{_constants={FLEX_DIRECTION_COLUMN:FLEX_DIRECTION_COLUMN2,FLEX_DIRECTION_COLUMN_REVERSE:FLEX_DIRECTION_COLUMN_REVERSE2,FLEX_DIRECTION_ROW:FLEX_DIRECTION_ROW2,FLEX_DIRECTION_ROW_REVERSE:FLEX_DIRECTION_ROW_REVERSE2,WRAP_NO_WRAP:WRAP_NO_WRAP2,WRAP_WRAP:WRAP_WRAP2,WRAP_WRAP_REVERSE:WRAP_WRAP_REVERSE2,ALIGN_AUTO:ALIGN_AUTO2,ALIGN_FLEX_START:ALIGN_FLEX_START2,ALIGN_CENTER:ALIGN_CENTER2,ALIGN_FLEX_END:ALIGN_FLEX_END2,ALIGN_STRETCH:ALIGN_STRETCH2,ALIGN_BASELINE:ALIGN_BASELINE2,ALIGN_SPACE_BETWEEN:ALIGN_SPACE_BETWEEN2,ALIGN_SPACE_AROUND:ALIGN_SPACE_AROUND2,ALIGN_SPACE_EVENLY,JUSTIFY_FLEX_START:JUSTIFY_FLEX_START2,JUSTIFY_CENTER:JUSTIFY_CENTER2,JUSTIFY_FLEX_END:JUSTIFY_FLEX_END2,JUSTIFY_SPACE_BETWEEN:JUSTIFY_SPACE_BETWEEN2,JUSTIFY_SPACE_AROUND:JUSTIFY_SPACE_AROUND2,JUSTIFY_SPACE_EVENLY:JUSTIFY_SPACE_EVENLY2,EDGE_LEFT:EDGE_LEFT2,EDGE_TOP:EDGE_TOP2,EDGE_RIGHT:EDGE_RIGHT2,EDGE_BOTTOM:EDGE_BOTTOM2,EDGE_HORIZONTAL:EDGE_HORIZONTAL2,EDGE_VERTICAL:EDGE_VERTICAL2,EDGE_ALL:EDGE_ALL2,GUTTER_COLUMN:GUTTER_COLUMN2,GUTTER_ROW:GUTTER_ROW2,GUTTER_ALL:GUTTER_ALL2,DISPLAY_FLEX:DISPLAY_FLEX2,DISPLAY_NONE:DISPLAY_NONE2,POSITION_TYPE_STATIC:POSITION_TYPE_STATIC2,POSITION_TYPE_RELATIVE:POSITION_TYPE_RELATIVE2,POSITION_TYPE_ABSOLUTE:POSITION_TYPE_ABSOLUTE2,OVERFLOW_VISIBLE:OVERFLOW_VISIBLE2,OVERFLOW_HIDDEN:OVERFLOW_HIDDEN2,OVERFLOW_SCROLL:OVERFLOW_SCROLL2,DIRECTION_LTR:DIRECTION_LTR2,MEASURE_MODE_UNDEFINED:MEASURE_MODE_UNDEFINED2,MEASURE_MODE_EXACTLY:MEASURE_MODE_EXACTLY2,MEASURE_MODE_AT_MOST:MEASURE_MODE_AT_MOST2};createNode(){return new FlexilyZeroNodeAdapter(FlexilyNode.create())}get constants(){return this._constants}get name(){return"flexily-zero"}}function createFlexilyZeroEngine(){return new FlexilyZeroLayoutEngine}var init_flexily_zero_adapter=()=>{};var init_derive2=__esm(()=>{init_src2()});var init_color=__esm(()=>{init_src()});var catppuccinMocha,catppuccinFrappe,catppuccinMacchiato,catppuccinLatte;var init_catppuccin=__esm(()=>{init_color();catppuccinMocha={name:"catppuccin-mocha",dark:!0,black:"#11111B",red:"#F38BA8",green:"#A6E3A1",yellow:"#F9E2AF",blue:"#89B4FA",magenta:"#CBA6F7",cyan:"#94E2D5",white:"#A6ADC8",brightBlack:"#313244",brightRed:"#FAB387",brightGreen:brighten("#A6E3A1",0.15),brightYellow:brighten("#F9E2AF",0.15),brightBlue:brighten("#89B4FA",0.15),brightMagenta:"#F5C2E7",brightCyan:brighten("#94E2D5",0.15),brightWhite:"#CDD6F4",foreground:"#CDD6F4",background:"#1E1E2E",cursorColor:"#CDD6F4",cursorText:"#1E1E2E",selectionBackground:"#6C7086",selectionForeground:"#CDD6F4"},catppuccinFrappe={name:"catppuccin-frappe",dark:!0,black:"#232634",red:"#E78284",green:"#A6D189",yellow:"#E5C890",blue:"#8CAAEE",magenta:"#CA9EE6",cyan:"#81C8BE",white:"#A5ADCE",brightBlack:"#414559",brightRed:"#EF9F76",brightGreen:brighten("#A6D189",0.15),brightYellow:brighten("#E5C890",0.15),brightBlue:brighten("#8CAAEE",0.15),brightMagenta:"#F4B8E4",brightCyan:brighten("#81C8BE",0.15),brightWhite:"#C6D0F5",foreground:"#C6D0F5",background:"#303446",cursorColor:"#C6D0F5",cursorText:"#303446",selectionBackground:"#737994",selectionForeground:"#C6D0F5"},catppuccinMacchiato={name:"catppuccin-macchiato",dark:!0,black:"#181926",red:"#ED8796",green:"#A6DA95",yellow:"#EED49F",blue:"#8AADF4",magenta:"#C6A0F6",cyan:"#8BD5CA",white:"#A5ADCB",brightBlack:"#363A4F",brightRed:"#F5A97F",brightGreen:brighten("#A6DA95",0.15),brightYellow:brighten("#EED49F",0.15),brightBlue:brighten("#8AADF4",0.15),brightMagenta:"#F5BDE6",brightCyan:brighten("#8BD5CA",0.15),brightWhite:"#CAD3F5",foreground:"#CAD3F5",background:"#24273A",cursorColor:"#CAD3F5",cursorText:"#24273A",selectionBackground:"#6E738D",selectionForeground:"#CAD3F5"},catppuccinLatte={name:"catppuccin-latte",dark:!1,black:"#DCE0E8",red:"#D20F39",green:"#40A02B",yellow:"#DF8E1D",blue:"#1E66F5",magenta:"#8839EF",cyan:"#179299",white:"#6C6F85",brightBlack:"#CCD0DA",brightRed:"#FE640B",brightGreen:brighten("#40A02B",0.15),brightYellow:brighten("#DF8E1D",0.15),brightBlue:brighten("#1E66F5",0.15),brightMagenta:"#EA76CB",brightCyan:brighten("#179299",0.15),brightWhite:"#4C4F69",foreground:"#4C4F69",background:"#EFF1F5",cursorColor:"#4C4F69",cursorText:"#EFF1F5",selectionBackground:"#9CA0B0",selectionForeground:"#4C4F69"}});var nord;var init_nord=__esm(()=>{init_color();nord={name:"nord",dark:!0,black:"#2E3440",red:"#BF616A",green:"#A3BE8C",yellow:"#EBCB8B",blue:"#5E81AC",magenta:"#B48EAD",cyan:"#8FBCBB",white:"#D8DEE9",brightBlack:"#3B4252",brightRed:"#D08770",brightGreen:brighten("#A3BE8C",0.15),brightYellow:brighten("#EBCB8B",0.15),brightBlue:brighten("#5E81AC",0.15),brightMagenta:"#B48EAD",brightCyan:brighten("#8FBCBB",0.15),brightWhite:"#ECEFF4",foreground:"#ECEFF4",background:"#2E3440",cursorColor:"#ECEFF4",cursorText:"#2E3440",selectionBackground:"#4C566A",selectionForeground:"#ECEFF4"}});var dracula;var init_dracula=__esm(()=>{init_color();dracula={name:"dracula",dark:!0,black:"#21222C",red:"#FF5555",green:"#50FA7B",yellow:"#F1FA8C",blue:"#BD93F9",magenta:"#BD93F9",cyan:"#8BE9FD",white:"#6272A4",brightBlack:"#44475A",brightRed:"#FFB86C",brightGreen:brighten("#50FA7B",0.15),brightYellow:brighten("#F1FA8C",0.15),brightBlue:brighten("#BD93F9",0.15),brightMagenta:"#FF79C6",brightCyan:brighten("#8BE9FD",0.15),brightWhite:"#F8F8F2",foreground:"#F8F8F2",background:"#282A36",cursorColor:"#F8F8F2",cursorText:"#282A36",selectionBackground:"#6272A4",selectionForeground:"#F8F8F2"}});var solarizedDark,solarizedLight;var init_solarized=__esm(()=>{init_color();solarizedDark={name:"solarized-dark",dark:!0,black:"#002B36",red:"#DC322F",green:"#859900",yellow:"#B58900",blue:"#268BD2",magenta:"#6C71C4",cyan:"#2AA198",white:"#839496",brightBlack:"#586E75",brightRed:"#CB4B16",brightGreen:brighten("#859900",0.15),brightYellow:brighten("#B58900",0.15),brightBlue:brighten("#268BD2",0.15),brightMagenta:"#D33682",brightCyan:brighten("#2AA198",0.15),brightWhite:"#FDF6E3",foreground:"#FDF6E3",background:"#073642",cursorColor:"#FDF6E3",cursorText:"#073642",selectionBackground:"#657B83",selectionForeground:"#FDF6E3"},solarizedLight={name:"solarized-light",dark:!1,black:"#FDF6E3",red:"#DC322F",green:"#859900",yellow:"#B58900",blue:"#268BD2",magenta:"#6C71C4",cyan:"#2AA198",white:"#657B83",brightBlack:"#DDD6C1",brightRed:"#CB4B16",brightGreen:brighten("#859900",0.15),brightYellow:brighten("#B58900",0.15),brightBlue:brighten("#268BD2",0.15),brightMagenta:"#D33682",brightCyan:brighten("#2AA198",0.15),brightWhite:"#073642",foreground:"#073642",background:"#EEE8D5",cursorColor:"#073642",cursorText:"#EEE8D5",selectionBackground:"#93A1A1",selectionForeground:"#073642"}});var tokyoNight,tokyoNightStorm,tokyoNightDay;var init_tokyo_night=__esm(()=>{init_color();tokyoNight={name:"tokyo-night",dark:!0,black:"#1A1B26",red:"#F7768E",green:"#9ECE6A",yellow:"#E0AF68",blue:"#7AA2F7",magenta:"#BB9AF7",cyan:"#73DACA",white:"#A9B1D6",brightBlack:"#292E42",brightRed:"#FF9E64",brightGreen:brighten("#9ECE6A",0.15),brightYellow:brighten("#E0AF68",0.15),brightBlue:brighten("#7AA2F7",0.15),brightMagenta:"#FF007C",brightCyan:brighten("#73DACA",0.15),brightWhite:"#C0CAF5",foreground:"#C0CAF5",background:"#24283B",cursorColor:"#C0CAF5",cursorText:"#24283B",selectionBackground:"#545C7E",selectionForeground:"#C0CAF5"},tokyoNightStorm={name:"tokyo-night-storm",dark:!0,black:"#1F2335",red:"#F7768E",green:"#9ECE6A",yellow:"#E0AF68",blue:"#7AA2F7",magenta:"#BB9AF7",cyan:"#73DACA",white:"#A9B1D6",brightBlack:"#292E42",brightRed:"#FF9E64",brightGreen:brighten("#9ECE6A",0.15),brightYellow:brighten("#E0AF68",0.15),brightBlue:brighten("#7AA2F7",0.15),brightMagenta:"#FF007C",brightCyan:brighten("#73DACA",0.15),brightWhite:"#C0CAF5",foreground:"#C0CAF5",background:"#24283B",cursorColor:"#C0CAF5",cursorText:"#24283B",selectionBackground:"#545C7E",selectionForeground:"#C0CAF5"},tokyoNightDay={name:"tokyo-night-day",dark:!1,black:"#E1E2E7",red:"#F52A65",green:"#587539",yellow:"#8C6C3E",blue:"#2E7DE9",magenta:"#9854F1",cyan:"#118C74",white:"#6172B0",brightBlack:"#C4C5CB",brightRed:"#B15C00",brightGreen:brighten("#587539",0.15),brightYellow:brighten("#8C6C3E",0.15),brightBlue:brighten("#2E7DE9",0.15),brightMagenta:"#F52A65",brightCyan:brighten("#118C74",0.15),brightWhite:"#3760BF",foreground:"#3760BF",background:"#D5D6DB",cursorColor:"#3760BF",cursorText:"#D5D6DB",selectionBackground:"#9699A3",selectionForeground:"#3760BF"}});var oneDark;var init_one_dark=__esm(()=>{init_color();oneDark={name:"one-dark",dark:!0,black:"#21252B",red:"#E06C75",green:"#98C379",yellow:"#E5C07B",blue:"#61AFEF",magenta:"#C678DD",cyan:"#56B6C2",white:"#ABB2BF",brightBlack:"#2C313A",brightRed:"#D19A66",brightGreen:brighten("#98C379",0.15),brightYellow:brighten("#E5C07B",0.15),brightBlue:brighten("#61AFEF",0.15),brightMagenta:"#E06C75",brightCyan:brighten("#56B6C2",0.15),brightWhite:"#ABB2BF",foreground:"#ABB2BF",background:"#282C34",cursorColor:"#ABB2BF",cursorText:"#282C34",selectionBackground:"#5C6370",selectionForeground:"#ABB2BF"}});var gruvboxDark,gruvboxLight;var init_gruvbox=__esm(()=>{init_color();gruvboxDark={name:"gruvbox-dark",dark:!0,black:"#1D2021",red:"#FB4934",green:"#B8BB26",yellow:"#FABD2F",blue:"#83A598",magenta:"#D3869B",cyan:"#8EC07C",white:"#BDAE93",brightBlack:"#3C3836",brightRed:"#FE8019",brightGreen:brighten("#B8BB26",0.15),brightYellow:brighten("#FABD2F",0.15),brightBlue:brighten("#83A598",0.15),brightMagenta:"#D3869B",brightCyan:brighten("#8EC07C",0.15),brightWhite:"#EBDBB2",foreground:"#EBDBB2",background:"#282828",cursorColor:"#EBDBB2",cursorText:"#282828",selectionBackground:"#665C54",selectionForeground:"#EBDBB2"},gruvboxLight={name:"gruvbox-light",dark:!1,black:"#F9F5D7",red:"#CC241D",green:"#98971A",yellow:"#D79921",blue:"#458588",magenta:"#B16286",cyan:"#689D6A",white:"#665C54",brightBlack:"#EBDBB2",brightRed:"#D65D0E",brightGreen:brighten("#98971A",0.15),brightYellow:brighten("#D79921",0.15),brightBlue:brighten("#458588",0.15),brightMagenta:"#B16286",brightCyan:brighten("#689D6A",0.15),brightWhite:"#3C3836",foreground:"#3C3836",background:"#FBF1C7",cursorColor:"#3C3836",cursorText:"#FBF1C7",selectionBackground:"#A89984",selectionForeground:"#3C3836"}});var rosePine,rosePineMoon,rosePineDawn;var init_rose_pine=__esm(()=>{init_color();rosePine={name:"rose-pine",dark:!0,black:"#191724",red:"#EB6F92",green:"#31748F",yellow:"#F6C177",blue:"#3E8FB0",magenta:"#C4A7E7",cyan:"#9CCFD8",white:"#908CAA",brightBlack:"#26233A",brightRed:"#EA9A97",brightGreen:brighten("#31748F",0.15),brightYellow:brighten("#F6C177",0.15),brightBlue:brighten("#3E8FB0",0.15),brightMagenta:"#EBBCBA",brightCyan:brighten("#9CCFD8",0.15),brightWhite:"#E0DEF4",foreground:"#E0DEF4",background:"#1F1D2E",cursorColor:"#E0DEF4",cursorText:"#1F1D2E",selectionBackground:"#6E6A86",selectionForeground:"#E0DEF4"},rosePineMoon={name:"rose-pine-moon",dark:!0,black:"#232136",red:"#EB6F92",green:"#3E8FB0",yellow:"#F6C177",blue:"#3E8FB0",magenta:"#C4A7E7",cyan:"#9CCFD8",white:"#908CAA",brightBlack:"#393552",brightRed:"#EA9A97",brightGreen:brighten("#3E8FB0",0.15),brightYellow:brighten("#F6C177",0.15),brightBlue:brighten("#3E8FB0",0.15),brightMagenta:"#EA9A97",brightCyan:brighten("#9CCFD8",0.15),brightWhite:"#E0DEF4",foreground:"#E0DEF4",background:"#2A273F",cursorColor:"#E0DEF4",cursorText:"#2A273F",selectionBackground:"#6E6A86",selectionForeground:"#E0DEF4"},rosePineDawn={name:"rose-pine-dawn",dark:!1,black:"#FAF4ED",red:"#B4637A",green:"#286983",yellow:"#EA9D34",blue:"#286983",magenta:"#907AA9",cyan:"#56949F",white:"#797593",brightBlack:"#F2E9E1",brightRed:"#D7827E",brightGreen:brighten("#286983",0.15),brightYellow:brighten("#EA9D34",0.15),brightBlue:brighten("#286983",0.15),brightMagenta:"#D7827E",brightCyan:brighten("#56949F",0.15),brightWhite:"#575279",foreground:"#575279",background:"#FFFAF3",cursorColor:"#575279",cursorText:"#FFFAF3",selectionBackground:"#9893A5",selectionForeground:"#575279"}});var kanagawaWave,kanagawaDragon,kanagawaLotus;var init_kanagawa=__esm(()=>{init_color();kanagawaWave={name:"kanagawa-wave",dark:!0,black:"#16161D",red:"#C34043",green:"#98BB6C",yellow:"#E6C384",blue:"#7E9CD8",magenta:"#957FB8",cyan:"#6A9589",white:"#727169",brightBlack:"#2A2A37",brightRed:"#FFA066",brightGreen:brighten("#98BB6C",0.15),brightYellow:brighten("#E6C384",0.15),brightBlue:brighten("#7E9CD8",0.15),brightMagenta:"#D27E99",brightCyan:brighten("#6A9589",0.15),brightWhite:"#DCD7BA",foreground:"#DCD7BA",background:"#1F1F28",cursorColor:"#DCD7BA",cursorText:"#1F1F28",selectionBackground:"#54546D",selectionForeground:"#DCD7BA"},kanagawaDragon={name:"kanagawa-dragon",dark:!0,black:"#0d0c0c",red:"#c4746e",green:"#87a987",yellow:"#c4b28a",blue:"#8ba4b0",magenta:"#8992a7",cyan:"#8ea4a2",white:"#737c73",brightBlack:"#282727",brightRed:"#b6927b",brightGreen:brighten("#87a987",0.15),brightYellow:brighten("#c4b28a",0.15),brightBlue:brighten("#8ba4b0",0.15),brightMagenta:"#a292a3",brightCyan:brighten("#8ea4a2",0.15),brightWhite:"#c5c9c5",foreground:"#c5c9c5",background:"#181616",cursorColor:"#c5c9c5",cursorText:"#181616",selectionBackground:"#625e5a",selectionForeground:"#c5c9c5"},kanagawaLotus={name:"kanagawa-lotus",dark:!1,black:"#e5ddb0",red:"#c84053",green:"#6f894e",yellow:"#de9800",blue:"#4d699b",magenta:"#624c83",cyan:"#597b75",white:"#716e61",brightBlack:"#dcd5ac",brightRed:"#cc6d00",brightGreen:brighten("#6f894e",0.15),brightYellow:brighten("#de9800",0.15),brightBlue:brighten("#4d699b",0.15),brightMagenta:"#b35b79",brightCyan:brighten("#597b75",0.15),brightWhite:"#545464",foreground:"#545464",background:"#f2ecbc",cursorColor:"#545464",cursorText:"#f2ecbc",selectionBackground:"#8a8980",selectionForeground:"#545464"}});var everforestDark,everforestLight;var init_everforest=__esm(()=>{init_color();everforestDark={name:"everforest-dark",dark:!0,black:"#232a2e",red:"#e67e80",green:"#a7c080",yellow:"#dbbc7f",blue:"#7fbbb3",magenta:"#d699b6",cyan:"#83c092",white:"#859289",brightBlack:"#343f44",brightRed:"#e69875",brightGreen:brighten("#a7c080",0.15),brightYellow:brighten("#dbbc7f",0.15),brightBlue:brighten("#7fbbb3",0.15),brightMagenta:"#e67e80",brightCyan:brighten("#83c092",0.15),brightWhite:"#d3c6aa",foreground:"#d3c6aa",background:"#2d353b",cursorColor:"#d3c6aa",cursorText:"#2d353b",selectionBackground:"#4f585e",selectionForeground:"#d3c6aa"},everforestLight={name:"everforest-light",dark:!1,black:"#efebd4",red:"#f85552",green:"#8da101",yellow:"#dfa000",blue:"#3a94c5",magenta:"#df69ba",cyan:"#35a77c",white:"#939f91",brightBlack:"#f4f0d9",brightRed:"#f57d26",brightGreen:brighten("#8da101",0.15),brightYellow:brighten("#dfa000",0.15),brightBlue:brighten("#3a94c5",0.15),brightMagenta:"#f85552",brightCyan:brighten("#35a77c",0.15),brightWhite:"#5c6a72",foreground:"#5c6a72",background:"#fdf6e3",cursorColor:"#5c6a72",cursorText:"#fdf6e3",selectionBackground:"#e0dcc7",selectionForeground:"#5c6a72"}});var monokai,monokaiPro;var init_monokai=__esm(()=>{init_color();monokai={name:"monokai",dark:!0,black:"#1a1a1a",red:"#F92672",green:"#A6E22E",yellow:"#E6DB74",blue:"#66D9EF",magenta:"#AE81FF",cyan:"#66D9EF",white:"#a59f85",brightBlack:"#3e3d32",brightRed:"#FD971F",brightGreen:brighten("#A6E22E",0.15),brightYellow:brighten("#E6DB74",0.15),brightBlue:brighten("#66D9EF",0.15),brightMagenta:"#F92672",brightCyan:brighten("#66D9EF",0.15),brightWhite:"#F8F8F2",foreground:"#F8F8F2",background:"#272822",cursorColor:"#F8F8F2",cursorText:"#272822",selectionBackground:"#75715E",selectionForeground:"#F8F8F2"},monokaiPro={name:"monokai-pro",dark:!0,black:"#221f22",red:"#ff6188",green:"#a9dc76",yellow:"#ffd866",blue:"#78dce8",magenta:"#ab9df2",cyan:"#78dce8",white:"#939293",brightBlack:"#403e41",brightRed:"#fc9867",brightGreen:brighten("#a9dc76",0.15),brightYellow:brighten("#ffd866",0.15),brightBlue:brighten("#78dce8",0.15),brightMagenta:"#ff6188",brightCyan:brighten("#78dce8",0.15),brightWhite:"#fcfcfa",foreground:"#fcfcfa",background:"#2d2a2e",cursorColor:"#fcfcfa",cursorText:"#2d2a2e",selectionBackground:"#727072",selectionForeground:"#fcfcfa"}});var snazzy;var init_snazzy=__esm(()=>{init_color();snazzy={name:"snazzy",dark:!0,black:"#222430",red:"#ff5c57",green:"#5af78e",yellow:"#f3f99d",blue:"#57c7ff",magenta:"#b267e6",cyan:"#9aedfe",white:"#97979b",brightBlack:"#34353e",brightRed:"#ff9f43",brightGreen:brighten("#5af78e",0.15),brightYellow:brighten("#f3f99d",0.15),brightBlue:brighten("#57c7ff",0.15),brightMagenta:"#ff6ac1",brightCyan:brighten("#9aedfe",0.15),brightWhite:"#eff0eb",foreground:"#eff0eb",background:"#282a36",cursorColor:"#eff0eb",cursorText:"#282a36",selectionBackground:"#686868",selectionForeground:"#eff0eb"}});var materialDark,materialLight;var init_material=__esm(()=>{init_color();materialDark={name:"material-dark",dark:!0,black:"#171717",red:"#ff5370",green:"#c3e88d",yellow:"#ffcb6b",blue:"#82aaff",magenta:"#c792ea",cyan:"#89ddff",white:"#545454",brightBlack:"#2c2c2c",brightRed:"#f78c6c",brightGreen:brighten("#c3e88d",0.15),brightYellow:brighten("#ffcb6b",0.15),brightBlue:brighten("#82aaff",0.15),brightMagenta:"#f07178",brightCyan:brighten("#89ddff",0.15),brightWhite:"#eeffff",foreground:"#eeffff",background:"#212121",cursorColor:"#eeffff",cursorText:"#212121",selectionBackground:"#424242",selectionForeground:"#eeffff"},materialLight={name:"material-light",dark:!1,black:"#ecf0f1",red:"#e53935",green:"#91b859",yellow:"#ffb62c",blue:"#6182b8",magenta:"#7c4dff",cyan:"#39adb5",white:"#90a4ae",brightBlack:"#ebf4f3",brightRed:"#f76d47",brightGreen:brighten("#91b859",0.15),brightYellow:brighten("#ffb62c",0.15),brightBlue:brighten("#6182b8",0.15),brightMagenta:"#ff5370",brightCyan:brighten("#39adb5",0.15),brightWhite:"#546E7A",foreground:"#546E7A",background:"#fafafa",cursorColor:"#546E7A",cursorText:"#fafafa",selectionBackground:"#cfd8dc",selectionForeground:"#546E7A"}});var palenight;var init_palenight=__esm(()=>{init_color();palenight={name:"palenight",dark:!0,black:"#1c1f2b",red:"#f07178",green:"#c3e88d",yellow:"#ffcb6b",blue:"#82aaff",magenta:"#c792ea",cyan:"#89ddff",white:"#676e95",brightBlack:"#343b51",brightRed:"#f78c6c",brightGreen:brighten("#c3e88d",0.15),brightYellow:brighten("#ffcb6b",0.15),brightBlue:brighten("#82aaff",0.15),brightMagenta:"#ff5370",brightCyan:brighten("#89ddff",0.15),brightWhite:"#a6accd",foreground:"#a6accd",background:"#292d3e",cursorColor:"#a6accd",cursorText:"#292d3e",selectionBackground:"#4e5579",selectionForeground:"#a6accd"}});var ayuDark,ayuMirage,ayuLight;var init_ayu=__esm(()=>{init_color();ayuDark={name:"ayu-dark",dark:!0,black:"#05070A",red:"#D95757",green:"#AAD94C",yellow:"#E6B450",blue:"#59C2FF",magenta:"#D2A6FF",cyan:"#95E6CB",white:"#636A72",brightBlack:"#11151C",brightRed:"#F29668",brightGreen:brighten("#AAD94C",0.15),brightYellow:brighten("#E6B450",0.15),brightBlue:brighten("#59C2FF",0.15),brightMagenta:"#F07178",brightCyan:brighten("#95E6CB",0.15),brightWhite:"#BFBDB6",foreground:"#BFBDB6",background:"#0B0E14",cursorColor:"#BFBDB6",cursorText:"#0B0E14",selectionBackground:"#565B66",selectionForeground:"#BFBDB6"},ayuMirage={name:"ayu-mirage",dark:!0,black:"#101521",red:"#FF6666",green:"#D5FF80",yellow:"#FFCC66",blue:"#73D0FF",magenta:"#DFBFFF",cyan:"#95E6CB",white:"#6C7A8B",brightBlack:"#171B24",brightRed:"#F29E74",brightGreen:brighten("#D5FF80",0.15),brightYellow:brighten("#FFCC66",0.15),brightBlue:brighten("#73D0FF",0.15),brightMagenta:"#F28779",brightCyan:brighten("#95E6CB",0.15),brightWhite:"#CCCAC2",foreground:"#CCCAC2",background:"#1F2430",cursorColor:"#CCCAC2",cursorText:"#1F2430",selectionBackground:"#707A8C",selectionForeground:"#CCCAC2"},ayuLight={name:"ayu-light",dark:!1,black:"#E7EAED",red:"#E65050",green:"#86B300",yellow:"#FFAA33",blue:"#399EE6",magenta:"#A37ACC",cyan:"#4CBF99",white:"#ABADB1",brightBlack:"#F3F4F5",brightRed:"#ED9366",brightGreen:brighten("#86B300",0.15),brightYellow:brighten("#FFAA33",0.15),brightBlue:brighten("#399EE6",0.15),brightMagenta:"#F07171",brightCyan:brighten("#4CBF99",0.15),brightWhite:"#5C6166",foreground:"#5C6166",background:"#F8F9FA",cursorColor:"#5C6166",cursorText:"#F8F9FA",selectionBackground:"#8A9199",selectionForeground:"#5C6166"}});var nightfox,dawnfox;var init_nightfox=__esm(()=>{init_color();nightfox={name:"nightfox",dark:!0,black:"#131A24",red:"#C94F6D",green:"#81B29A",yellow:"#DBC074",blue:"#719CD6",magenta:"#9D79D6",cyan:"#63CDCF",white:"#71839B",brightBlack:"#212E3F",brightRed:"#F4A261",brightGreen:brighten("#81B29A",0.15),brightYellow:brighten("#DBC074",0.15),brightBlue:brighten("#719CD6",0.15),brightMagenta:"#D67AD2",brightCyan:brighten("#63CDCF",0.15),brightWhite:"#CDCECF",foreground:"#CDCECF",background:"#192330",cursorColor:"#CDCECF",cursorText:"#192330",selectionBackground:"#39506D",selectionForeground:"#CDCECF"},dawnfox={name:"dawnfox",dark:!1,black:"#EBE5DF",red:"#B4637A",green:"#618774",yellow:"#EA9D34",blue:"#286983",magenta:"#907AA9",cyan:"#56949F",white:"#A8A3B3",brightBlack:"#EBE0DF",brightRed:"#D7827E",brightGreen:brighten("#618774",0.15),brightYellow:brighten("#EA9D34",0.15),brightBlue:brighten("#286983",0.15),brightMagenta:"#D685AF",brightCyan:brighten("#56949F",0.15),brightWhite:"#575279",foreground:"#575279",background:"#FAF4ED",cursorColor:"#575279",cursorText:"#FAF4ED",selectionBackground:"#BDBFC9",selectionForeground:"#575279"}});var horizon;var init_horizon=__esm(()=>{init_color();horizon={name:"horizon",dark:!0,black:"#16161C",red:"#E95678",green:"#29D398",yellow:"#FAC29A",blue:"#26BBD9",magenta:"#B877DB",cyan:"#59E1E3",white:"#6C6F93",brightBlack:"#232530",brightRed:"#FAB795",brightGreen:brighten("#29D398",0.15),brightYellow:brighten("#FAC29A",0.15),brightBlue:brighten("#26BBD9",0.15),brightMagenta:"#EE64AC",brightCyan:brighten("#59E1E3",0.15),brightWhite:"#D5D8DA",foreground:"#D5D8DA",background:"#1C1E26",cursorColor:"#D5D8DA",cursorText:"#1C1E26",selectionBackground:"#2E303E",selectionForeground:"#D5D8DA"}});var moonfly;var init_moonfly=__esm(()=>{init_color();moonfly={name:"moonfly",dark:!0,black:"#121212",red:"#FF5D5D",green:"#8CC85F",yellow:"#E3C78A",blue:"#80A0FF",magenta:"#AE81FF",cyan:"#79DAC8",white:"#808080",brightBlack:"#1C1C1C",brightRed:"#DE935F",brightGreen:brighten("#8CC85F",0.15),brightYellow:brighten("#E3C78A",0.15),brightBlue:brighten("#80A0FF",0.15),brightMagenta:"#FF5189",brightCyan:brighten("#79DAC8",0.15),brightWhite:"#C6C6C6",foreground:"#C6C6C6",background:"#080808",cursorColor:"#C6C6C6",cursorText:"#080808",selectionBackground:"#323437",selectionForeground:"#C6C6C6"}});var nightfly;var init_nightfly=__esm(()=>{init_color();nightfly={name:"nightfly",dark:!0,black:"#081E2F",red:"#FC514E",green:"#A1CD5E",yellow:"#E3D18A",blue:"#82AAFF",magenta:"#C792EA",cyan:"#7FDBCA",white:"#7C8F8F",brightBlack:"#0E293F",brightRed:"#F78C6C",brightGreen:brighten("#A1CD5E",0.15),brightYellow:brighten("#E3D18A",0.15),brightBlue:brighten("#82AAFF",0.15),brightMagenta:"#FF5874",brightCyan:brighten("#7FDBCA",0.15),brightWhite:"#C3CCDC",foreground:"#C3CCDC",background:"#011627",cursorColor:"#C3CCDC",cursorText:"#011627",selectionBackground:"#2C3043",selectionForeground:"#C3CCDC"}});var oxocarbonDark,oxocarbonLight;var init_oxocarbon=__esm(()=>{init_color();oxocarbonDark={name:"oxocarbon-dark",dark:!0,black:"#131313",red:"#EE5396",green:"#42BE65",yellow:"#82CFFF",blue:"#78A9FF",magenta:"#BE95FF",cyan:"#08BDBA",white:"#5C5C5C",brightBlack:"#2A2A2A",brightRed:"#FF7EB6",brightGreen:brighten("#42BE65",0.15),brightYellow:brighten("#82CFFF",0.15),brightBlue:brighten("#78A9FF",0.15),brightMagenta:"#FF7EB6",brightCyan:brighten("#08BDBA",0.15),brightWhite:"#F3F3F3",foreground:"#F3F3F3",background:"#161616",cursorColor:"#F3F3F3",cursorText:"#161616",selectionBackground:"#404040",selectionForeground:"#F3F3F3"},oxocarbonLight={name:"oxocarbon-light",dark:!1,black:"#F3F3F3",red:"#EE5396",green:"#42BE65",yellow:"#FFAB91",blue:"#0F62FE",magenta:"#BE95FF",cyan:"#08BDBA",white:"#90A4AE",brightBlack:"#D5D5D5",brightRed:"#FF6F00",brightGreen:brighten("#42BE65",0.15),brightYellow:brighten("#FFAB91",0.15),brightBlue:brighten("#0F62FE",0.15),brightMagenta:"#FF7EB6",brightCyan:brighten("#08BDBA",0.15),brightWhite:"#37474F",foreground:"#37474F",background:"#FFFFFF",cursorColor:"#37474F",cursorText:"#FFFFFF",selectionBackground:"#525252",selectionForeground:"#37474F"}});var sonokai;var init_sonokai=__esm(()=>{init_color();sonokai={name:"sonokai",dark:!0,black:"#181819",red:"#FC5D7C",green:"#9ED072",yellow:"#E7C664",blue:"#76CCE0",magenta:"#B39DF3",cyan:"#76CCE0",white:"#7F8490",brightBlack:"#33353F",brightRed:"#F39660",brightGreen:brighten("#9ED072",0.15),brightYellow:brighten("#E7C664",0.15),brightBlue:brighten("#76CCE0",0.15),brightMagenta:"#FC5D7C",brightCyan:brighten("#76CCE0",0.15),brightWhite:"#E2E2E3",foreground:"#E2E2E3",background:"#2C2E34",cursorColor:"#E2E2E3",cursorText:"#2C2E34",selectionBackground:"#414550",selectionForeground:"#E2E2E3"}});var edgeDark,edgeLight;var init_edge=__esm(()=>{init_color();edgeDark={name:"edge-dark",dark:!0,black:"#202023",red:"#EC7279",green:"#A0C980",yellow:"#DEB974",blue:"#6CB6EB",magenta:"#D38AEA",cyan:"#5DBBC1",white:"#758094",brightBlack:"#33353F",brightRed:"#DEB974",brightGreen:brighten("#A0C980",0.15),brightYellow:brighten("#DEB974",0.15),brightBlue:brighten("#6CB6EB",0.15),brightMagenta:"#EC7279",brightCyan:brighten("#5DBBC1",0.15),brightWhite:"#C5CDD9",foreground:"#C5CDD9",background:"#2C2E34",cursorColor:"#C5CDD9",cursorText:"#2C2E34",selectionBackground:"#414550",selectionForeground:"#C5CDD9"},edgeLight={name:"edge-light",dark:!1,black:"#DDE2E7",red:"#D05858",green:"#608E32",yellow:"#BE7E05",blue:"#5079BE",magenta:"#B05CCC",cyan:"#3A8B84",white:"#8790A0",brightBlack:"#EEF1F4",brightRed:"#BE7E05",brightGreen:brighten("#608E32",0.15),brightYellow:brighten("#BE7E05",0.15),brightBlue:brighten("#5079BE",0.15),brightMagenta:"#D05858",brightCyan:brighten("#3A8B84",0.15),brightWhite:"#4B505B",foreground:"#4B505B",background:"#FAFAFA",cursorColor:"#4B505B",cursorText:"#FAFAFA",selectionBackground:"#DDE2E7",selectionForeground:"#4B505B"}});var modusVivendi,modusOperandi;var init_modus=__esm(()=>{init_color();modusVivendi={name:"modus-vivendi",dark:!0,black:"#000000",red:"#FF5F59",green:"#44BC44",yellow:"#D0BC00",blue:"#2FAFFF",magenta:"#B6A0FF",cyan:"#00D3D0",white:"#989898",brightBlack:"#1E1E1E",brightRed:"#FEC43F",brightGreen:brighten("#44BC44",0.15),brightYellow:brighten("#D0BC00",0.15),brightBlue:brighten("#2FAFFF",0.15),brightMagenta:"#FEACD0",brightCyan:brighten("#00D3D0",0.15),brightWhite:"#FFFFFF",foreground:"#FFFFFF",background:"#000000",cursorColor:"#FFFFFF",cursorText:"#000000",selectionBackground:"#535353",selectionForeground:"#FFFFFF"},modusOperandi={name:"modus-operandi",dark:!1,black:"#E0E0E0",red:"#A60000",green:"#006800",yellow:"#6F5500",blue:"#0031A9",magenta:"#531AB6",cyan:"#005E8B",white:"#595959",brightBlack:"#F2F2F2",brightRed:"#884900",brightGreen:brighten("#006800",0.15),brightYellow:brighten("#6F5500",0.15),brightBlue:brighten("#0031A9",0.15),brightMagenta:"#721045",brightCyan:brighten("#005E8B",0.15),brightWhite:"#000000",foreground:"#000000",background:"#FFFFFF",cursorColor:"#000000",cursorText:"#FFFFFF",selectionBackground:"#9F9F9F",selectionForeground:"#000000"}});var init_github=()=>{};var init_cobalt2=()=>{};var init_synthwave=()=>{};var init_tomorrow_night=()=>{};var init_zenburn=()=>{};var init_ubuntu=()=>{};var init_tango=()=>{};var init_cyberpunk=()=>{};var init_vscode=()=>{};var init_one_light=()=>{};var init_night_owl=()=>{};var init_shades_of_purple=()=>{};var init_homebrew=()=>{};var init_neon=()=>{};var init_challenger_deep=()=>{};var init_doom_one=()=>{};var init_mariana=()=>{};var init_darcula=()=>{};var init_espresso=()=>{};var init_iceberg=()=>{};var init_serendipity=()=>{};var init_twilight=()=>{};var init_breeze=()=>{};var init_andromeda=()=>{};var init_relaxed=()=>{};var ansi16DarkTheme2,defaultDarkTheme,defaultLightTheme;var init_palettes=__esm(()=>{init_derive2();init_catppuccin();init_nord();init_dracula();init_solarized();init_tokyo_night();init_one_dark();init_gruvbox();init_rose_pine();init_kanagawa();init_everforest();init_monokai();init_snazzy();init_material();init_palenight();init_ayu();init_nightfox();init_horizon();init_moonfly();init_nightfly();init_oxocarbon();init_sonokai();init_edge();init_modus();init_github();init_cobalt2();init_synthwave();init_tomorrow_night();init_zenburn();init_ubuntu();init_tango();init_cyberpunk();init_vscode();init_one_light();init_night_owl();init_shades_of_purple();init_homebrew();init_neon();init_challenger_deep();init_doom_one();init_mariana();init_darcula();init_espresso();init_iceberg();init_serendipity();init_twilight();init_breeze();init_andromeda();init_relaxed();init_catppuccin();init_nord();init_dracula();init_solarized();init_tokyo_night();init_one_dark();init_gruvbox();init_rose_pine();init_kanagawa();init_everforest();init_monokai();init_snazzy();init_material();init_palenight();init_ayu();init_nightfox();init_horizon();init_moonfly();init_nightfly();init_oxocarbon();init_sonokai();init_edge();init_modus();init_github();init_cobalt2();init_synthwave();init_tomorrow_night();init_zenburn();init_ubuntu();init_tango();init_cyberpunk();init_vscode();init_one_light();init_night_owl();init_shades_of_purple();init_homebrew();init_neon();init_challenger_deep();init_doom_one();init_mariana();init_darcula();init_espresso();init_iceberg();init_serendipity();init_twilight();init_breeze();init_andromeda();init_relaxed();ansi16DarkTheme2={name:"dark-ansi16",bg:"",fg:"whiteBright",muted:"white",mutedbg:"black",surface:"whiteBright",surfacebg:"black",popover:"whiteBright",popoverbg:"black",inverse:"black",inversebg:"whiteBright",cursor:"black",cursorbg:"yellow",selection:"black",selectionbg:"yellow",primary:"yellow",primaryfg:"black",secondary:"white",secondaryfg:"black",accent:"blueBright",accentfg:"black",error:"redBright",errorfg:"black",warning:"yellow",warningfg:"black",success:"greenBright",successfg:"black",info:"cyan",infofg:"black",border:"gray",inputborder:"gray",focusborder:"blueBright",link:"blueBright",disabledfg:"gray",palette:["black","red","green","yellow","blue","magenta","cyan","white","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"]},defaultDarkTheme=deriveTheme(nord),defaultLightTheme=deriveTheme(catppuccinLatte)});function setActiveTheme(theme){_activeTheme=theme}function getActiveTheme(){return _contextStack.length>0?_contextStack[_contextStack.length-1]:_activeTheme}function pushContextTheme(theme){_contextStack.push(theme)}function popContextTheme(){_contextStack.pop()}var _activeTheme,_contextStack;var init_state=__esm(()=>{init_palettes();_activeTheme=ansi16DarkTheme2;_contextStack=[]});var init_resolve=__esm(()=>{init_src2()});init_term_provider();init_ansi2();init_buffer();import React from"react";import{createContext}from"react";var TermContext=createContext(null),NodeContext=createContext(null),StdoutContext=createContext(null),StderrContext=createContext(null),RuntimeContext=createContext(null),CacheBackendContext=createContext("virtual"),FocusManagerContext=createContext(null),CapabilityRegistryContext=createContext(null);var layoutEngine=null;function setLayoutEngine(engine){layoutEngine=engine}function getLayoutEngine(){if(!layoutEngine)throw Error("Layout engine not initialized. Call setLayoutEngine() or initYoga()/initFlexily() first.");return layoutEngine}function isLayoutEngineInitialized(){return layoutEngine!==null}function getConstants(){return getLayoutEngine().constants}async function ensureDefaultLayoutEngine(engineType){if(isLayoutEngineInitialized())return;if((engineType??process.env.SILVERY_ENGINE?.toLowerCase()??"flexily")==="yoga"){let{initYogaEngine:initYogaEngine2}=await Promise.resolve().then(() => exports_yoga_adapter);setLayoutEngine(await initYogaEngine2())}else{let{createFlexilyZeroEngine:createFlexilyZeroEngine2}=await Promise.resolve().then(() => (init_flexily_zero_adapter(),exports_flexily_zero_adapter));setLayoutEngine(createFlexilyZeroEngine2())}}init_unicode();import{createLogger as createLogger8}from"loggily";import{createLogger as createLogger7}from"loggily";init_buffer();init_unicode();init_unicode();function collectPlainText(node){if(node.textContent!==void 0)return node.textContent;let result="";for(let i=0;i<node.children.length;i++){let child=node.children[i],childText=collectPlainText(child);if(childText.length>0&&child.props.internal_transform)childText=child.props.internal_transform(childText,i);result+=childText}return result}function collectPlainTextSkipHidden(node){if(node.textContent!==void 0)return node.textContent;let result="";for(let i=0;i<node.children.length;i++){let child=node.children[i];if(child.hidden)continue;let childText=collectPlainTextSkipHidden(child);if(childText.length>0&&child.props.internal_transform)childText=child.props.internal_transform(childText,i);result+=childText}return result}init_unicode();function getPadding(props){return{top:props.paddingTop??props.paddingY??props.padding??0,bottom:props.paddingBottom??props.paddingY??props.padding??0,left:props.paddingLeft??props.paddingX??props.padding??0,right:props.paddingRight??props.paddingX??props.padding??0}}function getBorderSize(props){if(!props.borderStyle||getActiveLineHeight()>1)return{top:0,bottom:0,left:0,right:0};return{top:props.borderTop!==!1?1:0,bottom:props.borderBottom!==!1?1:0,left:props.borderLeft!==!1?1:0,right:props.borderRight!==!1?1:0}}function measurePhase(root,ctx){traverseTree(root,(node)=>{if(!node.layoutNode)return;let props=node.props;if(props.width==="fit-content"||props.height==="fit-content"){let availableWidth;if(props.height==="fit-content"&&props.width!=="fit-content"&&typeof props.width==="number"){let padding=getPadding(props);if(availableWidth=props.width-padding.left-padding.right,props.borderStyle){let border=getBorderSize(props);availableWidth-=border.left+border.right}if(availableWidth<1)availableWidth=1}let intrinsicSize=measureIntrinsicSize(node,ctx,availableWidth);if(props.width==="fit-content")node.layoutNode.setWidth(intrinsicSize.width);if(props.height==="fit-content")node.layoutNode.setHeight(intrinsicSize.height)}})}function measureIntrinsicSize(node,ctx,availableWidth){let props=node.props;if(props.display==="none")return{width:0,height:0};if(node.type==="silvery-text"){let textProps=props,text=collectPlainText(node),transform=textProps.internal_transform,lines;if(availableWidth!==void 0&&availableWidth>0&&isWrapEnabled(textProps.wrap))lines=ctx?ctx.measurer.wrapText(text,availableWidth,!0,!0):wrapText(text,availableWidth,!0,!0);else lines=text.split(`
68
- `);if(transform)lines=lines.map((line,index)=>transform(line,index));return{width:Math.max(...lines.map((line)=>getTextWidth(line,ctx))),height:lines.length*getActiveLineHeight()}}let isRow=props.flexDirection==="row"||props.flexDirection==="row-reverse",width=0,height=0,childCount=0;for(let child of node.children){let childSize=measureIntrinsicSize(child,ctx,availableWidth);if(childCount++,isRow)width+=childSize.width,height=Math.max(height,childSize.height);else width=Math.max(width,childSize.width),height+=childSize.height}let gap=props.gap??0;if(gap>0&&childCount>1){let totalGap=gap*(childCount-1);if(isRow)width+=totalGap;else height+=totalGap}let padding=getPadding(props);if(width+=padding.left+padding.right,height+=padding.top+padding.bottom,props.borderStyle){let border=getBorderSize(props);width+=border.left+border.right,height+=border.top+border.bottom}return{width,height}}function isWrapEnabled(wrap){return wrap==="wrap"||wrap==="hard"||wrap===!0||wrap===void 0}function traverseTree(node,callback){callback(node);for(let child of node.children)traverseTree(child,callback)}function getTextWidth(text,ctx){if(ctx)return ctx.measurer.displayWidthAnsi(text);return displayWidthAnsi(text)}import{createLogger as createLogger4}from"loggily";var measureStats={calls:0,cacheHits:0,textCollects:0,displayWidthCalls:0,reset(){this.calls=0,this.cacheHits=0,this.textCollects=0,this.displayWidthCalls=0}};function rectEqual(a,b){if(a===b)return!0;if(!a||!b)return!1;return a.x===b.x&&a.y===b.y&&a.width===b.width&&a.height===b.height}var layoutDirtyNodes=new Set,contentDirtyNodes=new Set;function trackLayoutDirty(node){layoutDirtyNodes.add(node)}function trackContentDirty(node){contentDirtyNodes.add(node)}function hasLayoutDirty(){return layoutDirtyNodes.size>0}function clearDirtyTracking(){layoutDirtyNodes.clear(),contentDirtyNodes.clear()}function clearLayoutDirtyTracking(){layoutDirtyNodes.clear()}var log4=createLogger4("silvery:layout");function layoutPhase(root,width,height){let prevLayout=root.boxRect;if(!(prevLayout&&(prevLayout.width!==width||prevLayout.height!==height))&&!hasLayoutDirty())return;if(clearLayoutDirtyTracking(),root.layoutNode){let nodeCount=countNodes(root);measureStats.reset();let t0=Date.now();root.layoutNode.calculateLayout(width,height);let elapsed=Date.now()-t0;log4.debug?.(`calculateLayout: ${elapsed}ms (${nodeCount} nodes) measure: calls=${measureStats.calls} hits=${measureStats.cacheHits} collects=${measureStats.textCollects} displayWidth=${measureStats.displayWidthCalls}`)}propagateLayout(root,0,0)}function countNodes(node){let count=1;for(let child of node.children)count+=countNodes(child);return count}function propagateLayout(node,parentX,parentY){if(node.prevLayout=node.boxRect,!node.layoutNode){let rect2={x:parentX,y:parentY,width:0,height:0};node.boxRect=rect2,node.layoutDirty=!1;for(let child of node.children)propagateLayout(child,parentX,parentY);return}let rect={x:parentX+node.layoutNode.getComputedLeft(),y:parentY+node.layoutNode.getComputedTop(),width:node.layoutNode.getComputedWidth(),height:node.layoutNode.getComputedHeight()};if(node.boxRect=rect,node.layoutDirty=!1,node.layoutChangedThisFrame=!!(node.prevLayout&&!rectEqual(node.prevLayout,node.boxRect)),process?.env?.SILVERY_STRICT&&node.layoutChangedThisFrame){if(rectEqual(node.prevLayout,node.boxRect)){let props=node.props;throw Error(`[SILVERY_STRICT] layoutChangedThisFrame=true but prevLayout equals boxRect (node: ${props.id??node.type}, rect: ${JSON.stringify(node.boxRect)})`)}}if(node.layoutChangedThisFrame){let ancestor=node.parent;while(ancestor&&!ancestor.subtreeDirty)ancestor.subtreeDirty=!0,ancestor=ancestor.parent}for(let child of node.children)propagateLayout(child,rect.x,rect.y)}function notifyLayoutSubscribers(node){let contentChanged=!rectEqual(node.prevLayout,node.boxRect),screenChanged=!rectEqual(node.prevScrollRect,node.scrollRect),renderChanged=!rectEqual(node.prevScreenRect,node.screenRect);if(contentChanged||screenChanged||renderChanged)for(let subscriber of node.layoutSubscribers)subscriber();for(let child of node.children)notifyLayoutSubscribers(child)}function scrollPhase(root,options={}){let{skipStateUpdates=!1}=options;traverseTree2(root,(node)=>{let props=node.props;if(props.overflow!=="scroll")return;calculateScrollState(node,props,skipStateUpdates)})}function calculateScrollState(node,props,skipStateUpdates){let layout=node.boxRect;if(!layout||!node.layoutNode)return;let border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},padding=getPadding(props),rawViewportHeight=layout.height-border.top-border.bottom-padding.top-padding.bottom,contentHeight=0,childPositions=[];for(let i=0;i<node.children.length;i++){let child=node.children[i];if(!child.layoutNode||!child.boxRect)continue;let childTop=child.boxRect.y-layout.y-border.top-padding.top,childBottom=childTop+child.boxRect.height,childProps=child.props;childPositions.push({child,top:childTop,bottom:childBottom,index:i,isSticky:childProps.position==="sticky",stickyTop:childProps.stickyTop,stickyBottom:childProps.stickyBottom}),contentHeight=Math.max(contentHeight,childBottom)}let viewportHeight=rawViewportHeight,showBorderlessIndicator=props.overflowIndicator===!0&&!props.borderStyle,hasOverflow=contentHeight>rawViewportHeight,indicatorReserve=showBorderlessIndicator&&hasOverflow?1:0,prevOffset=node.scrollState?.offset,scrollOffset=props.scrollOffset??prevOffset??0,scrollTo=props.scrollTo;if(scrollTo!==void 0&&scrollTo>=0&&scrollTo<childPositions.length){let target=childPositions.find((c)=>c.index===scrollTo);if(target){let effectiveHeight=viewportHeight-indicatorReserve,visibleTop2=scrollOffset,visibleBottom2=scrollOffset+effectiveHeight;if(target.top<visibleTop2)scrollOffset=target.top;else if(target.bottom>visibleBottom2)scrollOffset=target.bottom-effectiveHeight}}scrollOffset=Math.max(0,scrollOffset),scrollOffset=Math.min(scrollOffset,Math.max(0,contentHeight-viewportHeight));let visibleTop=scrollOffset,visibleBottom=scrollOffset+viewportHeight-indicatorReserve,firstVisible=-1,lastVisible=-1,hiddenAbove=0,hiddenBelow=0;for(let cp of childPositions){if(cp.isSticky){if(firstVisible===-1)firstVisible=cp.index;lastVisible=Math.max(lastVisible,cp.index);continue}if(cp.top===cp.bottom)continue;if(cp.bottom<=visibleTop)hiddenAbove++;else if(cp.top>=visibleBottom)hiddenBelow++;else if(cp.top<visibleTop){if(firstVisible===-1)firstVisible=cp.index;lastVisible=Math.max(lastVisible,cp.index)}else if(cp.bottom>visibleBottom){if(firstVisible===-1)firstVisible=cp.index;if(lastVisible=cp.index,indicatorReserve>0)hiddenBelow++}else{if(firstVisible===-1)firstVisible=cp.index;lastVisible=cp.index}}let stickyChildren=[];for(let cp of childPositions){if(!cp.isSticky)continue;let childHeight=cp.bottom-cp.top,stickyTop=cp.stickyTop??0,stickyBottom=cp.stickyBottom,naturalRenderY=cp.top-scrollOffset,renderOffset;if(stickyBottom!==void 0){let bottomPinPosition=viewportHeight-stickyBottom-childHeight;renderOffset=Math.min(naturalRenderY,bottomPinPosition)}else if(naturalRenderY>=stickyTop)renderOffset=naturalRenderY;else if(childHeight>viewportHeight)renderOffset=Math.max(viewportHeight-childHeight,naturalRenderY);else renderOffset=stickyTop;if(renderOffset!==naturalRenderY)if(childHeight>viewportHeight)renderOffset=Math.max(viewportHeight-childHeight,renderOffset);else renderOffset=Math.max(0,Math.min(renderOffset,viewportHeight-childHeight));if(renderOffset+childHeight<=0||renderOffset>=viewportHeight)continue;stickyChildren.push({index:cp.index,renderOffset,naturalTop:cp.top,height:childHeight})}if(skipStateUpdates)return;let prevFirstVisible=node.scrollState?.firstVisibleChild??firstVisible,prevLastVisible=node.scrollState?.lastVisibleChild??lastVisible;if(scrollOffset!==prevOffset||firstVisible!==prevFirstVisible||lastVisible!==prevLastVisible)node.subtreeDirty=!0;node.scrollState={offset:scrollOffset,prevOffset:prevOffset??scrollOffset,contentHeight,viewportHeight,firstVisibleChild:firstVisible,lastVisibleChild:lastVisible,prevFirstVisibleChild:prevFirstVisible,prevLastVisibleChild:prevLastVisible,hiddenAbove,hiddenBelow,stickyChildren:stickyChildren.length>0?stickyChildren:void 0}}function stickyPhase(root){traverseTree2(root,(node)=>{let props=node.props;if(props.overflow==="scroll")return;let hasStickyChildren=!1;for(let child of node.children){let childProps=child.props;if(childProps.position==="sticky"&&childProps.stickyBottom!==void 0){hasStickyChildren=!0;break}}if(!hasStickyChildren){if(node.stickyChildren!==void 0)node.stickyChildren=void 0,node.subtreeDirty=!0;return}let layout=node.boxRect;if(!layout||!node.layoutNode)return;let border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},padding=getPadding(props),parentContentHeight=layout.height-border.top-border.bottom-padding.top-padding.bottom,newStickyChildren=[];for(let i=0;i<node.children.length;i++){let child=node.children[i],childProps=child.props;if(childProps.position!=="sticky")continue;if(childProps.stickyBottom===void 0)continue;if(!child.boxRect)continue;let naturalY=child.boxRect.y-layout.y-border.top-padding.top,childHeight=child.boxRect.height,stickyBottom=childProps.stickyBottom,bottomPin=parentContentHeight-stickyBottom-childHeight,renderOffset=Math.max(naturalY,bottomPin);newStickyChildren.push({index:i,renderOffset,naturalTop:naturalY,height:childHeight})}let prev=node.stickyChildren,next=newStickyChildren.length>0?newStickyChildren:void 0,changed=!stickyChildrenEqual(prev,next);if(node.stickyChildren=next,changed)node.subtreeDirty=!0})}function stickyChildrenEqual(a,b){if(a===b)return!0;if(!a||!b)return!1;if(a.length!==b.length)return!1;for(let i=0;i<a.length;i++){let ai=a[i],bi=b[i];if(ai.index!==bi.index||ai.renderOffset!==bi.renderOffset||ai.naturalTop!==bi.naturalTop||ai.height!==bi.height)return!1}return!0}function traverseTree2(node,callback){callback(node);for(let child of node.children)traverseTree2(child,callback)}function scrollrectPhase(root){propagateScrollRect(root,0)}function propagateScrollRect(node,ancestorScrollOffset){node.prevScrollRect=node.scrollRect,node.prevScreenRect=node.screenRect;let content=node.boxRect;if(!content){node.scrollRect=null,node.screenRect=null;for(let child of node.children)propagateScrollRect(child,ancestorScrollOffset);return}node.scrollRect={x:content.x,y:content.y-ancestorScrollOffset,width:content.width,height:content.height},node.screenRect=node.scrollRect;let scrollOffset=node.scrollState?.offset??0,childScrollOffset=ancestorScrollOffset+scrollOffset;computeStickyScreenRects(node);for(let child of node.children)propagateScrollRect(child,childScrollOffset)}function computeStickyScreenRects(parent){let stickyList=parent.scrollState?.stickyChildren??parent.stickyChildren;if(!stickyList||stickyList.length===0)return;let parentScrollRect=parent.scrollRect;if(!parentScrollRect)return;let props=parent.props,border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},padding=getPadding(props),contentOriginY=parentScrollRect.y+border.top+padding.top;for(let sticky of stickyList){let child=parent.children[sticky.index];if(!child?.scrollRect)continue;child.screenRect={x:child.scrollRect.x,y:contentOriginY+sticky.renderOffset,width:child.scrollRect.width,height:child.scrollRect.height}}}init_buffer();import{createLogger as createLogger6}from"loggily";init_buffer();init_state();init_resolve();init_unicode();var namedColors={black:0,red:1,green:2,yellow:3,blue:4,magenta:5,cyan:6,white:7,gray:8,grey:8,blackBright:8,redBright:9,greenBright:10,yellowBright:11,blueBright:12,magentaBright:13,cyanBright:14,whiteBright:15};function blendColors(c1,c2,t){return{r:Math.round(c1.r*(1-t)+c2.r*t),g:Math.round(c1.g*(1-t)+c2.g*t),b:Math.round(c1.b*(1-t)+c2.b*t)}}function parseColor(color){if(color==="inherit")return null;if(color==="$default")return DEFAULT_BG;if(color.startsWith("mix(")&&color.endsWith(")")){let inner=color.slice(4,-1),args=[],depth=0,start=0;for(let i=0;i<inner.length;i++)if(inner[i]==="(")depth++;else if(inner[i]===")")depth--;else if(inner[i]===","&&depth===0)args.push(inner.slice(start,i).trim()),start=i+1;if(args.push(inner.slice(start).trim()),args.length===3){let c1=parseColor(args[0]),c2=parseColor(args[1]),amountStr=args[2],t;if(amountStr.endsWith("%"))t=Number.parseFloat(amountStr.slice(0,-1))/100;else t=Number.parseFloat(amountStr);if(c1!==null&&c2!==null&&typeof c1==="object"&&typeof c2==="object"&&!Number.isNaN(t))return blendColors(c1,c2,Math.max(0,Math.min(1,t)));return null}}if(color.startsWith("$")){let resolved=resolveThemeColor(color,getActiveTheme());if(resolved&&resolved!==color)return parseColor(resolved);return null}if(color in namedColors)return namedColors[color];if(color.startsWith("#")){let hex=color.slice(1);if(hex.length===3){let r=Number.parseInt(hex[0]+hex[0],16),g=Number.parseInt(hex[1]+hex[1],16),b=Number.parseInt(hex[2]+hex[2],16);return{r,g,b}}if(hex.length===6){let r=Number.parseInt(hex.slice(0,2),16),g=Number.parseInt(hex.slice(2,4),16),b=Number.parseInt(hex.slice(4,6),16);return{r,g,b}}}let rgbMatch=color.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i);if(rgbMatch)return{r:Number.parseInt(rgbMatch[1],10),g:Number.parseInt(rgbMatch[2],10),b:Number.parseInt(rgbMatch[3],10)};let ansi256Match=color.match(/^ansi256\s*\(\s*(\d+)\s*\)$/i);if(ansi256Match)return Number.parseInt(ansi256Match[1],10);return null}var borders={single:{topLeft:"┌",topRight:"┐",bottomLeft:"└",bottomRight:"┘",horizontal:"─",vertical:"│"},double:{topLeft:"╔",topRight:"╗",bottomLeft:"╚",bottomRight:"╝",horizontal:"═",vertical:"║"},round:{topLeft:"╭",topRight:"╮",bottomLeft:"╰",bottomRight:"╯",horizontal:"─",vertical:"│"},bold:{topLeft:"┏",topRight:"┓",bottomLeft:"┗",bottomRight:"┛",horizontal:"━",vertical:"┃"},singleDouble:{topLeft:"╓",topRight:"╖",bottomLeft:"╙",bottomRight:"╜",horizontal:"─",vertical:"║"},doubleSingle:{topLeft:"╒",topRight:"╕",bottomLeft:"╘",bottomRight:"╛",horizontal:"═",vertical:"│"},classic:{topLeft:"+",topRight:"+",bottomLeft:"+",bottomRight:"+",horizontal:"-",vertical:"|"}};function getBorderChars(style2){if(style2&&typeof style2==="object"){let obj=style2,topHorizontal=obj.top??obj.horizontal??"-",leftVertical=obj.left??obj.vertical??"|";return{topLeft:obj.topLeft??"+",topRight:obj.topRight??"+",bottomLeft:obj.bottomLeft??"+",bottomRight:obj.bottomRight??"+",horizontal:topHorizontal,vertical:leftVertical,bottomHorizontal:obj.bottom&&obj.bottom!==topHorizontal?obj.bottom:void 0,rightVertical:obj.right&&obj.right!==leftVertical?obj.right:void 0}}return borders[style2??"single"]}function getTextStyle(props){let underlineStyle;if(props.underlineStyle!==void 0)underlineStyle=props.underlineStyle;else if(props.underline)underlineStyle="single";return{fg:props.color?parseColor(props.color):null,bg:props.backgroundColor?parseColor(props.backgroundColor):null,underlineColor:props.underlineColor?parseColor(props.underlineColor):null,attrs:{bold:props.bold,dim:props.dim||props.dimColor,italic:props.italic,underline:props.underline||!!underlineStyle,underlineStyle,strikethrough:props.strikethrough,inverse:props.inverse}}}function getTextWidth2(text,ctx){if(ctx)return ctx.measurer.displayWidthAnsi(text);return displayWidthAnsi(text)}init_buffer();init_unicode();import{createLogger as createLogger5}from"loggily";var log5=createLogger5("silvery:content"),bgConflictMode=(()=>{let env=typeof process<"u"?process.env.SILVERY_BG_CONFLICT?.toLowerCase():void 0;if(env==="ignore"||env==="warn"||env==="throw")return env;return"throw"})();function getBgConflictMode(){return bgConflictMode}var warnedBgConflicts=new Set;function formatBgConflictColor(c){if(c===null||c===void 0)return"none";if(typeof c==="number"){if(c&16777216){let r=c>>16&255,g=c>>8&255,b=c&255;return`#${r.toString(16).padStart(2,"0")}${g.toString(16).padStart(2,"0")}${b.toString(16).padStart(2,"0")}`}return{40:"black",41:"red",42:"green",43:"yellow",44:"blue",45:"magenta",46:"cyan",47:"white",100:"brightBlack",101:"brightRed",102:"brightGreen",103:"brightYellow",104:"brightBlue",105:"brightMagenta",106:"brightCyan",107:"brightWhite"}[c]??`palette(${c})`}return`rgb(${c.r},${c.g},${c.b})`}function clearBgConflictWarnings(){warnedBgConflicts.clear()}function styleToAnsi2(style2){let parts=[];if(style2.color){let color=parseColor(style2.color);if(color!==null)if(typeof color==="number")parts.push(`38;5;${color}`);else parts.push(`38;2;${color.r};${color.g};${color.b}`)}if(style2.bold)parts.push("1");if(style2.dim)parts.push("2");if(style2.italic)parts.push("3");if(style2.underlineStyle){let styleMap={single:"4:1",double:"4:2",curly:"4:3",dotted:"4:4",dashed:"4:5"};parts.push(styleMap[style2.underlineStyle]??"4")}else if(style2.underline)parts.push("4");if(style2.underlineColor){let ulColor=parseColor(style2.underlineColor);if(ulColor!==null)if(typeof ulColor==="number")parts.push(`58;5;${ulColor}`);else parts.push(`58;2;${ulColor.r};${ulColor.g};${ulColor.b}`)}if(style2.inverse)parts.push("7");if(style2.strikethrough)parts.push("9");if(parts.length===0)return"";return`\x1B[${parts.join(";")}m`}function mergeStyleContext(parent,childProps){return{color:childProps.color??parent.color,backgroundColor:childProps.backgroundColor??parent.backgroundColor,bold:childProps.bold??parent.bold,dim:childProps.dim??childProps.dimColor??parent.dim,italic:childProps.italic??parent.italic,underline:childProps.underline??childProps.underlineStyle?!0:parent.underline,underlineStyle:childProps.underlineStyle??parent.underlineStyle,underlineColor:childProps.underlineColor??parent.underlineColor,inverse:childProps.inverse??parent.inverse,strikethrough:childProps.strikethrough??parent.strikethrough}}function applyTextStyleAnsi(text,childStyle,parentStyle){if(!text)return text;let childAnsi=styleToAnsi2(childStyle),parentAnsi=styleToAnsi2(parentStyle);if(!childAnsi)return text;return`${childAnsi}${text}\x1B[0m${parentAnsi}`}function collectTextWithBg(node,parentContext={},offset=0,maxDisplayWidth,ctx){if(node.textContent!==void 0){let text=node.textContent;if(maxDisplayWidth!==void 0){if(getTextWidth2(text,ctx)>maxDisplayWidth)text=(ctx?ctx.measurer.sliceByWidth:sliceByWidth)(text,maxDisplayWidth)}let plainLen=getTextWidth2(text,ctx);return{text,bgSegments:[],childSpans:[],plainLen}}let result="",bgSegments=[],childSpans=[],currentOffset=offset,displayWidthCollected=0;for(let i=0;i<node.children.length;i++){let child=node.children[i];if(maxDisplayWidth!==void 0&&displayWidthCollected>=maxDisplayWidth)break;let childBudget=maxDisplayWidth!==void 0?maxDisplayWidth-displayWidthCollected:void 0;if(child.type==="silvery-text"&&child.props&&!child.layoutNode){let childProps=child.props,childContext=mergeStyleContext(parentContext,childProps),childResult=collectTextWithBg(child,childContext,currentOffset,childBudget,ctx),childTransform=childProps.internal_transform;if(childTransform&&childResult.text.length>0)childResult.text=childTransform(childResult.text,i);let styledText=applyTextStyleAnsi(childResult.text,childContext,parentContext);if(result+=styledText,childContext.backgroundColor){let bg=parseColor(childContext.backgroundColor);if(bg!==null){if(childResult.plainLen>0)bgSegments.push({start:currentOffset,end:currentOffset+childResult.plainLen,bg})}}else if(childProps.backgroundColor===""&&childResult.plainLen>0)bgSegments.push({start:currentOffset,end:currentOffset+childResult.plainLen,bg:null});if(childResult.plainLen>0)childSpans.push({node:child,start:currentOffset,end:currentOffset+childResult.plainLen});bgSegments.push(...childResult.bgSegments),childSpans.push(...childResult.childSpans),currentOffset+=childResult.plainLen,displayWidthCollected+=childResult.plainLen}else{let childResult=collectTextWithBg(child,parentContext,currentOffset,childBudget,ctx);result+=childResult.text,bgSegments.push(...childResult.bgSegments),childSpans.push(...childResult.childSpans),currentOffset+=childResult.plainLen,displayWidthCollected+=childResult.plainLen}}return{text:result,bgSegments,childSpans,plainLen:displayWidthCollected}}function applyBgSegmentsToLine(buffer,x,y,lineText,lineCharStart,lineCharEnd,bgSegments,ctx){if(bgSegments.length===0)return;if(y<0||y>=buffer.height)return;let bgCell=createMutableCell(),gWidthFn=ctx?ctx.measurer.graphemeWidth:graphemeWidth;for(let seg of bgSegments){let overlapStart=Math.max(seg.start,lineCharStart),overlapEnd=Math.min(seg.end,lineCharEnd);if(overlapStart>=overlapEnd)continue;let relStart=overlapStart-lineCharStart,relEnd=overlapEnd-lineCharStart,col=x,graphemes=splitGraphemes(hasAnsi(lineText)?stripAnsiForBg(lineText):lineText);for(let grapheme of graphemes){let gWidth=gWidthFn(grapheme);if(gWidth===0)continue;let displayOffset=col-x;if(displayOffset>=relStart&&displayOffset<relEnd){if(buffer.readCellInto(col,y,bgCell),bgCell.bg=seg.bg,buffer.setCell(col,y,bgCell),gWidth===2&&col+1<buffer.width)buffer.readCellInto(col+1,y,bgCell),bgCell.bg=seg.bg,buffer.setCell(col+1,y,bgCell)}if(col+=gWidth,col-x>=relEnd)break}}}function stripAnsiForBg(text){return text.replace(/\x1b\[[0-9;:?]*[A-Za-z]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b[DME78]/g,"").replace(/\x1b\(B/g,"")}function mapLinesToCharOffsets(originalText,formattedLines,ctx){let normalized=(hasAnsi(originalText)?stripAnsiForBg(originalText):originalText).replace(/\t/g," "),result=[],charOffset=0,displayOffset=0;for(let line of formattedLines){let plainLine=hasAnsi(line)?stripAnsiForBg(line):line,lineStart=findLineStart(normalized,plainLine,charOffset);if(lineStart>charOffset){let skipped=normalized.slice(charOffset,lineStart);displayOffset+=getTextWidth2(skipped,ctx)}let lineDisplayWidth=getTextWidth2(plainLine,ctx);result.push({start:displayOffset,end:displayOffset+lineDisplayWidth});let lineLen=Math.min(plainLine.length,normalized.length-lineStart);charOffset=lineStart+lineLen,displayOffset+=lineDisplayWidth}return result}function findLineStart(normalized,plainLine,fromOffset){if(plainLine.length===0){let pos2=fromOffset;while(pos2<normalized.length&&normalized[pos2]===`
67
+ `),getState:()=>({cols:emulator.cols,rows:emulator.rows}),subscribe:(listener)=>{return subscribers.add(listener),()=>subscribers.delete(listener)},events:()=>eq.events(),resize:(cols,rows)=>{emulator.resize(cols,rows),subscribers.forEach((l)=>l({cols,rows})),eq.push({type:"resize",data:{cols,rows}}),updateDims(cols,rows),resizeListeners.forEach((l)=>l())},sendInput:(data)=>eq.push(...parseInputEvents(data)),stripAnsi:stripAnsi3,paint:(buffer,prev)=>{let output=outputPhase(prev,buffer);if(output)emulator.feed(output);return _frame=createTextFrame(buffer),output},_emulator:emulator,[Symbol.dispose]:()=>{eq.dispose(),controller.abort(),subscribers.clear(),emulator.close().catch(()=>{})}};return finalizeTerm(createStyle({level:"truecolor"}),termBase,{get:()=>_frame},{defineProperties:{cols:{get:()=>emulator.cols,enumerable:!0},rows:{get:()=>emulator.rows,enumerable:!0},screen:{get:()=>emulator.screen,enumerable:!0},scrollback:{get:()=>emulator.scrollback,enumerable:!0}},delegateFrom:emulator})}var ANSI_REGEX2;var init_term=__esm(()=>{init_src2();init_buffer();init_output_phase();init_detection2();init_term_provider();init_keys();init_mouse();ANSI_REGEX2=/\x1b\[[0-9;:]*m|\x9b[0-9;:]*m|\x1b\]8;;[^\x07\x1b]*(?:\x07|\x1b\\)|\x9d8;;[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c)/g});var init_patch_console=()=>{};import{openSync,writeSync,closeSync}from"node:fs";import{createLogger as createLogger4}from"loggily";function createOutputGuard(options){let savedStdoutWrite=process.stdout.write,savedStderrWrite=process.stderr.write,origStdoutWrite=savedStdoutWrite.bind(process.stdout),origStderrWrite=savedStderrWrite.bind(process.stderr),silveryWriting=!1,disposed=!1,suppressedCount=0,redirectedCount=0,stderrLog=options?.stderrLog??process.env.DEBUG_LOG,stderrFd=null,stderrBuffer=[];if(stderrLog)try{stderrFd=openSync(stderrLog,"a")}catch{}process.stdout.write=function(chunk,...args){if(silveryWriting)return origStdoutWrite(chunk,...args);suppressedCount++;let preview=typeof chunk==="string"?chunk.slice(0,60):"<binary>";return log4?.debug?.(`suppressed stdout write (${suppressedCount}): ${JSON.stringify(preview)}`),!0},process.stderr.write=function(chunk,..._args){let str=typeof chunk==="string"?chunk:chunk.toString();if(redirectedCount++,stderrFd!==null){try{writeSync(stderrFd,str)}catch{}return!0}if(options?.bufferStderr)return stderrBuffer.push(str),!0;return!0};let{log:savedConsoleLog,info:savedConsoleInfo,warn:savedConsoleWarn,error:savedConsoleError,debug:savedConsoleDebug}=console;function redirectConsole(...args){let str=args.map((a)=>typeof a==="string"?a:String(a)).join(" ")+`
68
+ `;if(redirectedCount++,stderrFd!==null){try{writeSync(stderrFd,str)}catch{}return}if(options?.bufferStderr){stderrBuffer.push(str);return}}console.log=redirectConsole,console.info=redirectConsole,console.warn=redirectConsole,console.error=redirectConsole,console.debug=redirectConsole,log4?.info?.("activated"+(stderrLog?` (stderr -> ${stderrLog})`:" (stderr suppressed)"));function dispose(){if(disposed)return;disposed=!0,process.stdout.write=savedStdoutWrite,process.stderr.write=savedStderrWrite,console.log=savedConsoleLog,console.info=savedConsoleInfo,console.warn=savedConsoleWarn,console.error=savedConsoleError,console.debug=savedConsoleDebug,log4?.info?.(`deactivated (suppressed ${suppressedCount} stdout, redirected ${redirectedCount} stderr)`);for(let line of stderrBuffer)origStderrWrite(line);if(stderrFd!==null){try{closeSync(stderrFd)}catch{}stderrFd=null}}return{writeStdout(data){silveryWriting=!0;try{return origStdoutWrite(data)}finally{silveryWriting=!1}},get active(){return!disposed},get suppressedCount(){return suppressedCount},get redirectedCount(){return redirectedCount},dispose,[Symbol.dispose]:dispose}}var log4;var init_output_guard=__esm(()=>{log4=createLogger4("silvery:guard")});var init_utils2=__esm(()=>{init_src2()});var init_underline=__esm(()=>{init_src2()});var init_hyperlink2=__esm(()=>{init_src2()});var init_ansi=__esm(()=>{init_src2()});var _lazyTerm,term,BG_OVERRIDE_CODE=9999;var init_ansi2=__esm(()=>{init_term();init_term();init_patch_console();init_output_guard();init_detection2();init_utils2();init_underline();init_hyperlink2();init_ansi();term=new Proxy({},{get(_target,prop,receiver){if(!_lazyTerm)_lazyTerm=createTerm();return Reflect.get(_lazyTerm,prop,receiver)},apply(_target,thisArg,args){if(!_lazyTerm)_lazyTerm=createTerm();return Reflect.apply(_lazyTerm,thisArg,args)},has(_target,prop){if(!_lazyTerm)_lazyTerm=createTerm();return Reflect.has(_lazyTerm,prop)}})});var YGEnums,ALIGN_AUTO,ALIGN_FLEX_START,ALIGN_CENTER,ALIGN_FLEX_END,ALIGN_STRETCH,ALIGN_BASELINE,ALIGN_SPACE_BETWEEN,ALIGN_SPACE_AROUND,DIMENSION_WIDTH,DIMENSION_HEIGHT,DIRECTION_INHERIT,DIRECTION_LTR,DIRECTION_RTL,DISPLAY_FLEX,DISPLAY_NONE,EDGE_LEFT,EDGE_TOP,EDGE_RIGHT,EDGE_BOTTOM,EDGE_START,EDGE_END,EDGE_HORIZONTAL,EDGE_VERTICAL,EDGE_ALL,EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS,EXPERIMENTAL_FEATURE_ABSOLUTE_PERCENTAGE_AGAINST_PADDING_EDGE,EXPERIMENTAL_FEATURE_FIX_ABSOLUTE_TRAILING_COLUMN_MARGIN,FLEX_DIRECTION_COLUMN,FLEX_DIRECTION_COLUMN_REVERSE,FLEX_DIRECTION_ROW,FLEX_DIRECTION_ROW_REVERSE,GUTTER_COLUMN,GUTTER_ROW,GUTTER_ALL,JUSTIFY_FLEX_START,JUSTIFY_CENTER,JUSTIFY_FLEX_END,JUSTIFY_SPACE_BETWEEN,JUSTIFY_SPACE_AROUND,JUSTIFY_SPACE_EVENLY,LOG_LEVEL_ERROR,LOG_LEVEL_WARN,LOG_LEVEL_INFO,LOG_LEVEL_DEBUG,LOG_LEVEL_VERBOSE,LOG_LEVEL_FATAL,MEASURE_MODE_UNDEFINED,MEASURE_MODE_EXACTLY,MEASURE_MODE_AT_MOST,NODE_TYPE_DEFAULT,NODE_TYPE_TEXT,OVERFLOW_VISIBLE,OVERFLOW_HIDDEN,OVERFLOW_SCROLL,POSITION_TYPE_STATIC,POSITION_TYPE_RELATIVE,POSITION_TYPE_ABSOLUTE,PRINT_OPTIONS_LAYOUT,PRINT_OPTIONS_STYLE,PRINT_OPTIONS_CHILDREN,UNIT_UNDEFINED,UNIT_POINT,UNIT_PERCENT,UNIT_AUTO,WRAP_NO_WRAP,WRAP_WRAP,WRAP_WRAP_REVERSE,wrapAsm=(E)=>{function _(E2,_2,T2){let N2=E2[_2];E2[_2]=function(...E3){return T2.call(this,N2,...E3)}}for(let T2 of["setPosition","setMargin","setFlexBasis","setWidth","setHeight","setMinWidth","setMinHeight","setMaxWidth","setMaxHeight","setPadding"]){let N2={[YGEnums.UNIT_POINT]:E.Node.prototype[T2],[YGEnums.UNIT_PERCENT]:E.Node.prototype[`${T2}Percent`],[YGEnums.UNIT_AUTO]:E.Node.prototype[`${T2}Auto`]};_(E.Node.prototype,T2,function(E2,..._2){let I,L,O=_2.pop();if(O==="auto")I=YGEnums.UNIT_AUTO,L=void 0;else if(typeof O=="object")I=O.unit,L=O.valueOf();else if(I=typeof O=="string"&&O.endsWith("%")?YGEnums.UNIT_PERCENT:YGEnums.UNIT_POINT,L=parseFloat(O),!Number.isNaN(O)&&Number.isNaN(L))throw Error(`Invalid value ${O} for ${T2}`);if(!N2[I])throw Error(`Failed to execute "${T2}": Unsupported unit '${O}'`);return L!==void 0?N2[I].call(this,..._2,L):N2[I].call(this,..._2)})}function T(_2){return E.MeasureCallback.implement({measure:(...E2)=>{let{width:T2,height:N2}=_2(...E2);return{width:T2??NaN,height:N2??NaN}}})}function N(_2){return E.DirtiedCallback.implement({dirtied:_2})}return _(E.Node.prototype,"setMeasureFunc",function(E2,_2){return _2?E2.call(this,T(_2)):this.unsetMeasureFunc()}),_(E.Node.prototype,"setDirtiedFunc",function(E2,_2){E2.call(this,N(_2))}),_(E.Config.prototype,"free",function(){E.Config.destroy(this)}),_(E.Node,"create",(_2,T2)=>T2?E.Node.createWithConfig(T2):E.Node.createDefault()),_(E.Node.prototype,"free",function(){E.Node.destroy(this)}),_(E.Node.prototype,"freeRecursive",function(){for(let E2=0,_2=this.getChildCount();E2<_2;++E2)this.getChild(0).freeRecursive();this.free()}),_(E.Node.prototype,"calculateLayout",function(E2,_2=NaN,T2=NaN,N2=YGEnums.DIRECTION_LTR){return E2.call(this,_2,T2,N2)}),{Config:E.Config,Node:E.Node,...YGEnums}};var init_wrapAsm_f766f97f=__esm(()=>{YGEnums={},ALIGN_AUTO=YGEnums.ALIGN_AUTO=0,ALIGN_FLEX_START=YGEnums.ALIGN_FLEX_START=1,ALIGN_CENTER=YGEnums.ALIGN_CENTER=2,ALIGN_FLEX_END=YGEnums.ALIGN_FLEX_END=3,ALIGN_STRETCH=YGEnums.ALIGN_STRETCH=4,ALIGN_BASELINE=YGEnums.ALIGN_BASELINE=5,ALIGN_SPACE_BETWEEN=YGEnums.ALIGN_SPACE_BETWEEN=6,ALIGN_SPACE_AROUND=YGEnums.ALIGN_SPACE_AROUND=7,DIMENSION_WIDTH=YGEnums.DIMENSION_WIDTH=0,DIMENSION_HEIGHT=YGEnums.DIMENSION_HEIGHT=1,DIRECTION_INHERIT=YGEnums.DIRECTION_INHERIT=0,DIRECTION_LTR=YGEnums.DIRECTION_LTR=1,DIRECTION_RTL=YGEnums.DIRECTION_RTL=2,DISPLAY_FLEX=YGEnums.DISPLAY_FLEX=0,DISPLAY_NONE=YGEnums.DISPLAY_NONE=1,EDGE_LEFT=YGEnums.EDGE_LEFT=0,EDGE_TOP=YGEnums.EDGE_TOP=1,EDGE_RIGHT=YGEnums.EDGE_RIGHT=2,EDGE_BOTTOM=YGEnums.EDGE_BOTTOM=3,EDGE_START=YGEnums.EDGE_START=4,EDGE_END=YGEnums.EDGE_END=5,EDGE_HORIZONTAL=YGEnums.EDGE_HORIZONTAL=6,EDGE_VERTICAL=YGEnums.EDGE_VERTICAL=7,EDGE_ALL=YGEnums.EDGE_ALL=8,EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS=YGEnums.EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS=0,EXPERIMENTAL_FEATURE_ABSOLUTE_PERCENTAGE_AGAINST_PADDING_EDGE=YGEnums.EXPERIMENTAL_FEATURE_ABSOLUTE_PERCENTAGE_AGAINST_PADDING_EDGE=1,EXPERIMENTAL_FEATURE_FIX_ABSOLUTE_TRAILING_COLUMN_MARGIN=YGEnums.EXPERIMENTAL_FEATURE_FIX_ABSOLUTE_TRAILING_COLUMN_MARGIN=2,FLEX_DIRECTION_COLUMN=YGEnums.FLEX_DIRECTION_COLUMN=0,FLEX_DIRECTION_COLUMN_REVERSE=YGEnums.FLEX_DIRECTION_COLUMN_REVERSE=1,FLEX_DIRECTION_ROW=YGEnums.FLEX_DIRECTION_ROW=2,FLEX_DIRECTION_ROW_REVERSE=YGEnums.FLEX_DIRECTION_ROW_REVERSE=3,GUTTER_COLUMN=YGEnums.GUTTER_COLUMN=0,GUTTER_ROW=YGEnums.GUTTER_ROW=1,GUTTER_ALL=YGEnums.GUTTER_ALL=2,JUSTIFY_FLEX_START=YGEnums.JUSTIFY_FLEX_START=0,JUSTIFY_CENTER=YGEnums.JUSTIFY_CENTER=1,JUSTIFY_FLEX_END=YGEnums.JUSTIFY_FLEX_END=2,JUSTIFY_SPACE_BETWEEN=YGEnums.JUSTIFY_SPACE_BETWEEN=3,JUSTIFY_SPACE_AROUND=YGEnums.JUSTIFY_SPACE_AROUND=4,JUSTIFY_SPACE_EVENLY=YGEnums.JUSTIFY_SPACE_EVENLY=5,LOG_LEVEL_ERROR=YGEnums.LOG_LEVEL_ERROR=0,LOG_LEVEL_WARN=YGEnums.LOG_LEVEL_WARN=1,LOG_LEVEL_INFO=YGEnums.LOG_LEVEL_INFO=2,LOG_LEVEL_DEBUG=YGEnums.LOG_LEVEL_DEBUG=3,LOG_LEVEL_VERBOSE=YGEnums.LOG_LEVEL_VERBOSE=4,LOG_LEVEL_FATAL=YGEnums.LOG_LEVEL_FATAL=5,MEASURE_MODE_UNDEFINED=YGEnums.MEASURE_MODE_UNDEFINED=0,MEASURE_MODE_EXACTLY=YGEnums.MEASURE_MODE_EXACTLY=1,MEASURE_MODE_AT_MOST=YGEnums.MEASURE_MODE_AT_MOST=2,NODE_TYPE_DEFAULT=YGEnums.NODE_TYPE_DEFAULT=0,NODE_TYPE_TEXT=YGEnums.NODE_TYPE_TEXT=1,OVERFLOW_VISIBLE=YGEnums.OVERFLOW_VISIBLE=0,OVERFLOW_HIDDEN=YGEnums.OVERFLOW_HIDDEN=1,OVERFLOW_SCROLL=YGEnums.OVERFLOW_SCROLL=2,POSITION_TYPE_STATIC=YGEnums.POSITION_TYPE_STATIC=0,POSITION_TYPE_RELATIVE=YGEnums.POSITION_TYPE_RELATIVE=1,POSITION_TYPE_ABSOLUTE=YGEnums.POSITION_TYPE_ABSOLUTE=2,PRINT_OPTIONS_LAYOUT=YGEnums.PRINT_OPTIONS_LAYOUT=1,PRINT_OPTIONS_STYLE=YGEnums.PRINT_OPTIONS_STYLE=2,PRINT_OPTIONS_CHILDREN=YGEnums.PRINT_OPTIONS_CHILDREN=4,UNIT_UNDEFINED=YGEnums.UNIT_UNDEFINED=0,UNIT_POINT=YGEnums.UNIT_POINT=1,UNIT_PERCENT=YGEnums.UNIT_PERCENT=2,UNIT_AUTO=YGEnums.UNIT_AUTO=3,WRAP_NO_WRAP=YGEnums.WRAP_NO_WRAP=0,WRAP_WRAP=YGEnums.WRAP_WRAP=1,WRAP_WRAP_REVERSE=YGEnums.WRAP_WRAP_REVERSE=2});async function initYoga(t){let r=await yoga({instantiateWasm(n,r2){WebAssembly.instantiate(t,n).then((n2)=>{n2 instanceof WebAssembly.Instance?r2(n2):r2(n2.instance)})}});return wrapAsm(r)}var yoga;var init_dist=__esm(()=>{init_wrapAsm_f766f97f();init_wrapAsm_f766f97f();yoga=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(t={}){u||(u=t!==void 0?t:{}),u.ready=new Promise(function(n2,t2){c=n2,f=t2});var r,e,a=Object.assign({},u),i="";typeof document<"u"&&document.currentScript&&(i=document.currentScript.src),n&&(i=n),i=i.indexOf("blob:")!==0?i.substr(0,i.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var o=console.log.bind(console),s=console.warn.bind(console);Object.assign(u,a),a=null,typeof WebAssembly!="object"&&w("no native wasm support detected");var u,c,f,l,h=!1;function p(n2,t2,r2){r2=t2+r2;for(var e2="";!(t2>=r2);){var a2=n2[t2++];if(!a2)break;if(128&a2){var i2=63&n2[t2++];if((224&a2)==192)e2+=String.fromCharCode((31&a2)<<6|i2);else{var o2=63&n2[t2++];65536>(a2=(240&a2)==224?(15&a2)<<12|i2<<6|o2:(7&a2)<<18|i2<<12|o2<<6|63&n2[t2++])?e2+=String.fromCharCode(a2):(a2-=65536,e2+=String.fromCharCode(55296|a2>>10,56320|1023&a2))}}else e2+=String.fromCharCode(a2)}return e2}function v(){var n2=l.buffer;u.HEAP8=d=new Int8Array(n2),u.HEAP16=m=new Int16Array(n2),u.HEAP32=g=new Int32Array(n2),u.HEAPU8=y=new Uint8Array(n2),u.HEAPU16=E=new Uint16Array(n2),u.HEAPU32=_=new Uint32Array(n2),u.HEAPF32=T=new Float32Array(n2),u.HEAPF64=L=new Float64Array(n2)}var d,y,m,E,g,_,T,L,A,O=[],P=[],b=[],N=0,I=null;function w(n2){throw s(n2="Aborted("+n2+")"),h=!0,f(n2=new WebAssembly.RuntimeError(n2+". Build with -sASSERTIONS for more info.")),n2}function S(){return r.startsWith("data:application/octet-stream;base64,")}function R(){try{throw"both async and sync fetching of the wasm failed"}catch(n2){w(n2)}}function C(n2){for(;0<n2.length;)n2.shift()(u)}function W(n2){if(n2===void 0)return"_unknown";var t2=(n2=n2.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return 48<=t2&&57>=t2?"_"+n2:n2}function U(n2,t2){return n2=W(n2),function(){return t2.apply(this,arguments)}}r="yoga.wasm",S()||(r=i+r);var M=[{},{value:void 0},{value:null},{value:!0},{value:!1}],F=[];function D(n2){var t2=Error,r2=U(n2,function(t3){this.name=n2,this.message=t3,(t3=Error(t3).stack)!==void 0&&(this.stack=this.toString()+`
69
+ `+t3.replace(/^Error(:[^\n]*)?\n/,""))});return r2.prototype=Object.create(t2.prototype),r2.prototype.constructor=r2,r2.prototype.toString=function(){return this.message===void 0?this.name:this.name+": "+this.message},r2}var k=void 0;function V(n2){throw new k(n2)}var j=(n2)=>(n2||V("Cannot use deleted val. handle = "+n2),M[n2].value),G=(n2)=>{switch(n2){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:var t2=F.length?F.pop():M.length;return M[t2]={fa:1,value:n2},t2}},Y=void 0,X=void 0;function B(n2){for(var t2="";y[n2];)t2+=X[y[n2++]];return t2}var H=[];function x(){for(;H.length;){var n2=H.pop();n2.L.Z=!1,n2.delete()}}var z=void 0,$={};function Z(n2,t2){for(t2===void 0&&V("ptr should not be undefined");n2.P;)t2=n2.aa(t2),n2=n2.P;return t2}var J={};function q(n2){var t2=B(n2=nz(n2));return nZ(n2),t2}function K(n2,t2){var r2=J[n2];return r2===void 0&&V(t2+" has unknown type "+q(n2)),r2}function Q(){}var nn=!1;function nt(n2){--n2.count.value,n2.count.value===0&&(n2.S?n2.T.V(n2.S):n2.O.M.V(n2.N))}var nr={},ne=void 0;function na(n2){throw new ne(n2)}function ni(n2,t2){return t2.O&&t2.N||na("makeClassHandle requires ptr and ptrType"),!!t2.T!=!!t2.S&&na("Both smartPtrType and smartPtr must be specified"),t2.count={value:1},no(Object.create(n2,{L:{value:t2}}))}function no(n2){return typeof FinalizationRegistry>"u"?(no=(n3)=>n3,n2):(nn=new FinalizationRegistry((n3)=>{nt(n3.L)}),no=(n3)=>{var t2=n3.L;return t2.S&&nn.register(n3,{L:t2},n3),n3},Q=(n3)=>{nn.unregister(n3)},no(n2))}var ns={};function nu(n2){for(;n2.length;){var t2=n2.pop();n2.pop()(t2)}}function nc(n2){return this.fromWireType(g[n2>>2])}var nf={},nl={};function nh(n2,t2,r2){function e2(t3){(t3=r2(t3)).length!==n2.length&&na("Mismatched type converter count");for(var e3=0;e3<n2.length;++e3)nv(n2[e3],t3[e3])}n2.forEach(function(n3){nl[n3]=t2});var a2=Array(t2.length),i2=[],o2=0;t2.forEach((n3,t3)=>{J.hasOwnProperty(n3)?a2[t3]=J[n3]:(i2.push(n3),nf.hasOwnProperty(n3)||(nf[n3]=[]),nf[n3].push(()=>{a2[t3]=J[n3],++o2===i2.length&&e2(a2)}))}),i2.length===0&&e2(a2)}function np(n2){switch(n2){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw TypeError("Unknown type size: "+n2)}}function nv(n2,t2,r2={}){if(!("argPackAdvance"in t2))throw TypeError("registerType registeredInstance requires argPackAdvance");var e2=t2.name;if(n2||V('type "'+e2+'" must have a positive integer typeid pointer'),J.hasOwnProperty(n2)){if(r2.ta)return;V("Cannot register type '"+e2+"' twice")}J[n2]=t2,delete nl[n2],nf.hasOwnProperty(n2)&&(t2=nf[n2],delete nf[n2],t2.forEach((n3)=>n3()))}function nd(n2){V(n2.L.O.M.name+" instance already deleted")}function ny(){}function nm(n2,t2,r2){if(n2[t2].R===void 0){var e2=n2[t2];n2[t2]=function(){return n2[t2].R.hasOwnProperty(arguments.length)||V("Function '"+r2+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+n2[t2].R+")!"),n2[t2].R[arguments.length].apply(this,arguments)},n2[t2].R=[],n2[t2].R[e2.Y]=e2}}function nE(n2,t2,r2,e2,a2,i2,o2,s2){this.name=n2,this.constructor=t2,this.W=r2,this.V=e2,this.P=a2,this.oa=i2,this.aa=o2,this.ma=s2,this.ia=[]}function ng(n2,t2,r2){for(;t2!==r2;)t2.aa||V("Expected null or instance of "+r2.name+", got an instance of "+t2.name),n2=t2.aa(n2),t2=t2.P;return n2}function n_(n2,t2){return t2===null?(this.da&&V("null is not a valid "+this.name),0):(t2.L||V('Cannot pass "'+nC(t2)+'" as a '+this.name),t2.L.N||V("Cannot pass deleted object as a pointer of type "+this.name),ng(t2.L.N,t2.L.O.M,this.M))}function nT(n2,t2){if(t2===null){if(this.da&&V("null is not a valid "+this.name),this.ca){var r2=this.ea();return n2!==null&&n2.push(this.V,r2),r2}return 0}if(t2.L||V('Cannot pass "'+nC(t2)+'" as a '+this.name),t2.L.N||V("Cannot pass deleted object as a pointer of type "+this.name),!this.ba&&t2.L.O.ba&&V("Cannot convert argument of type "+(t2.L.T?t2.L.T.name:t2.L.O.name)+" to parameter type "+this.name),r2=ng(t2.L.N,t2.L.O.M,this.M),this.ca)switch(t2.L.S===void 0&&V("Passing raw pointer to smart pointer is illegal"),this.Aa){case 0:t2.L.T===this?r2=t2.L.S:V("Cannot convert argument of type "+(t2.L.T?t2.L.T.name:t2.L.O.name)+" to parameter type "+this.name);break;case 1:r2=t2.L.S;break;case 2:if(t2.L.T===this)r2=t2.L.S;else{var e2=t2.clone();r2=this.wa(r2,G(function(){e2.delete()})),n2!==null&&n2.push(this.V,r2)}break;default:V("Unsupporting sharing policy")}return r2}function nL(n2,t2){return t2===null?(this.da&&V("null is not a valid "+this.name),0):(t2.L||V('Cannot pass "'+nC(t2)+'" as a '+this.name),t2.L.N||V("Cannot pass deleted object as a pointer of type "+this.name),t2.L.O.ba&&V("Cannot convert argument of type "+t2.L.O.name+" to parameter type "+this.name),ng(t2.L.N,t2.L.O.M,this.M))}function nA(n2,t2,r2,e2){this.name=n2,this.M=t2,this.da=r2,this.ba=e2,this.ca=!1,this.V=this.wa=this.ea=this.ja=this.Aa=this.va=void 0,t2.P!==void 0?this.toWireType=nT:(this.toWireType=e2?n_:nL,this.U=null)}var nO=[];function nP(n2){var t2=nO[n2];return t2||(n2>=nO.length&&(nO.length=n2+1),nO[n2]=t2=A.get(n2)),t2}function nb(n2,t2){var r2,e2,a2=(n2=B(n2)).includes("j")?(r2=n2,e2=[],function(){if(e2.length=0,Object.assign(e2,arguments),r2.includes("j")){var n3=u["dynCall_"+r2];n3=e2&&e2.length?n3.apply(null,[t2].concat(e2)):n3.call(null,t2)}else n3=nP(t2).apply(null,e2);return n3}):nP(t2);return typeof a2!="function"&&V("unknown function pointer with signature "+n2+": "+t2),a2}var nN=void 0;function nI(n2,t2){var r2=[],e2={};throw t2.forEach(function n3(t3){e2[t3]||J[t3]||(nl[t3]?nl[t3].forEach(n3):(r2.push(t3),e2[t3]=!0))}),new nN(n2+": "+r2.map(q).join([", "]))}function nw(n2,t2,r2,e2,a2){var i2=t2.length;2>i2&&V("argTypes array size mismatch! Must at least get return value and 'this' types!");var o2=t2[1]!==null&&r2!==null,s2=!1;for(r2=1;r2<t2.length;++r2)if(t2[r2]!==null&&t2[r2].U===void 0){s2=!0;break}var u2=t2[0].name!=="void",c2=i2-2,f2=Array(c2),l2=[],h2=[];return function(){if(arguments.length!==c2&&V("function "+n2+" called with "+arguments.length+" arguments, expected "+c2+" args!"),h2.length=0,l2.length=o2?2:1,l2[0]=a2,o2){var r3=t2[1].toWireType(h2,this);l2[1]=r3}for(var i3=0;i3<c2;++i3)f2[i3]=t2[i3+2].toWireType(h2,arguments[i3]),l2.push(f2[i3]);if(i3=e2.apply(null,l2),s2)nu(h2);else for(var p2=o2?1:2;p2<t2.length;p2++){var v2=p2===1?r3:f2[p2-2];t2[p2].U!==null&&t2[p2].U(v2)}return u2?t2[0].fromWireType(i3):void 0}}function nS(n2,t2){for(var r2=[],e2=0;e2<n2;e2++)r2.push(_[t2+4*e2>>2]);return r2}function nR(n2){4<n2&&--M[n2].fa==0&&(M[n2]=void 0,F.push(n2))}function nC(n2){if(n2===null)return"null";var t2=typeof n2;return t2==="object"||t2==="array"||t2==="function"?n2.toString():""+n2}function nW(n2,t2){for(var r2="",e2=0;!(e2>=t2/2);++e2){var a2=m[n2+2*e2>>1];if(a2==0)break;r2+=String.fromCharCode(a2)}return r2}function nU(n2,t2,r2){if(r2===void 0&&(r2=2147483647),2>r2)return 0;r2-=2;var e2=t2;r2=r2<2*n2.length?r2/2:n2.length;for(var a2=0;a2<r2;++a2)m[t2>>1]=n2.charCodeAt(a2),t2+=2;return m[t2>>1]=0,t2-e2}function nM(n2){return 2*n2.length}function nF(n2,t2){for(var r2=0,e2="";!(r2>=t2/4);){var a2=g[n2+4*r2>>2];if(a2==0)break;++r2,65536<=a2?(a2-=65536,e2+=String.fromCharCode(55296|a2>>10,56320|1023&a2)):e2+=String.fromCharCode(a2)}return e2}function nD(n2,t2,r2){if(r2===void 0&&(r2=2147483647),4>r2)return 0;var e2=t2;r2=e2+r2-4;for(var a2=0;a2<n2.length;++a2){var i2=n2.charCodeAt(a2);if(55296<=i2&&57343>=i2&&(i2=65536+((1023&i2)<<10)|1023&n2.charCodeAt(++a2)),g[t2>>2]=i2,(t2+=4)+4>r2)break}return g[t2>>2]=0,t2-e2}function nk(n2){for(var t2=0,r2=0;r2<n2.length;++r2){var e2=n2.charCodeAt(r2);55296<=e2&&57343>=e2&&++r2,t2+=4}return t2}var nV={};function nj(n2){var t2=nV[n2];return t2===void 0?B(n2):t2}var nG=[],nY=[],nX=[null,[],[]];k=u.BindingError=D("BindingError"),u.count_emval_handles=function(){for(var n2=0,t2=5;t2<M.length;++t2)M[t2]!==void 0&&++n2;return n2},u.get_first_emval=function(){for(var n2=5;n2<M.length;++n2)if(M[n2]!==void 0)return M[n2];return null},Y=u.PureVirtualError=D("PureVirtualError");for(var nB=Array(256),nH=0;256>nH;++nH)nB[nH]=String.fromCharCode(nH);X=nB,u.getInheritedInstanceCount=function(){return Object.keys($).length},u.getLiveInheritedInstances=function(){var n2,t2=[];for(n2 in $)$.hasOwnProperty(n2)&&t2.push($[n2]);return t2},u.flushPendingDeletes=x,u.setDelayFunction=function(n2){z=n2,H.length&&z&&z(x)},ne=u.InternalError=D("InternalError"),ny.prototype.isAliasOf=function(n2){if(!(this instanceof ny&&n2 instanceof ny))return!1;var t2=this.L.O.M,r2=this.L.N,e2=n2.L.O.M;for(n2=n2.L.N;t2.P;)r2=t2.aa(r2),t2=t2.P;for(;e2.P;)n2=e2.aa(n2),e2=e2.P;return t2===e2&&r2===n2},ny.prototype.clone=function(){if(this.L.N||nd(this),this.L.$)return this.L.count.value+=1,this;var n2=no,t2=Object,r2=t2.create,e2=Object.getPrototypeOf(this),a2=this.L;return n2=n2(r2.call(t2,e2,{L:{value:{count:a2.count,Z:a2.Z,$:a2.$,N:a2.N,O:a2.O,S:a2.S,T:a2.T}}})),n2.L.count.value+=1,n2.L.Z=!1,n2},ny.prototype.delete=function(){this.L.N||nd(this),this.L.Z&&!this.L.$&&V("Object already scheduled for deletion"),Q(this),nt(this.L),this.L.$||(this.L.S=void 0,this.L.N=void 0)},ny.prototype.isDeleted=function(){return!this.L.N},ny.prototype.deleteLater=function(){return this.L.N||nd(this),this.L.Z&&!this.L.$&&V("Object already scheduled for deletion"),H.push(this),H.length===1&&z&&z(x),this.L.Z=!0,this},nA.prototype.pa=function(n2){return this.ja&&(n2=this.ja(n2)),n2},nA.prototype.ga=function(n2){this.V&&this.V(n2)},nA.prototype.argPackAdvance=8,nA.prototype.readValueFromPointer=nc,nA.prototype.deleteObject=function(n2){n2!==null&&n2.delete()},nA.prototype.fromWireType=function(n2){function t2(){return this.ca?ni(this.M.W,{O:this.va,N:e2,T:this,S:n2}):ni(this.M.W,{O:this,N:n2})}var r2,e2=this.pa(n2);if(!e2)return this.ga(n2),null;var a2=$[Z(this.M,e2)];if(a2!==void 0)return a2.L.count.value===0?(a2.L.N=e2,a2.L.S=n2,a2.clone()):(a2=a2.clone(),this.ga(n2),a2);if(!(a2=nr[a2=this.M.oa(e2)]))return t2.call(this);a2=this.ba?a2.ka:a2.pointerType;var i2=function n3(t3,r3,e3){return r3===e3?t3:e3.P===void 0?null:(t3=n3(t3,r3,e3.P))===null?null:e3.ma(t3)}(e2,this.M,a2.M);return i2===null?t2.call(this):this.ca?ni(a2.M.W,{O:a2,N:i2,T:this,S:n2}):ni(a2.M.W,{O:a2,N:i2})},nN=u.UnboundTypeError=D("UnboundTypeError");var nx={q:function(n2,t2,r2){n2=B(n2),t2=K(t2,"wrapper"),r2=j(r2);var e2=[].slice,a2=t2.M,i2=a2.W,o2=a2.P.W,s2=a2.P.constructor;for(var u2 in n2=U(n2,function(){a2.P.ia.forEach(function(n3){if(this[n3]===o2[n3])throw new Y("Pure virtual function "+n3+" must be implemented in JavaScript")}.bind(this)),Object.defineProperty(this,"__parent",{value:i2}),this.__construct.apply(this,e2.call(arguments))}),i2.__construct=function(){this===i2&&V("Pass correct 'this' to __construct");var n3=s2.implement.apply(void 0,[this].concat(e2.call(arguments)));Q(n3);var t3=n3.L;n3.notifyOnDestruction(),t3.$=!0,Object.defineProperties(this,{L:{value:t3}}),no(this),n3=Z(a2,n3=t3.N),$.hasOwnProperty(n3)?V("Tried to register registered instance: "+n3):$[n3]=this},i2.__destruct=function(){this===i2&&V("Pass correct 'this' to __destruct"),Q(this);var n3=this.L.N;n3=Z(a2,n3),$.hasOwnProperty(n3)?delete $[n3]:V("Tried to unregister unregistered instance: "+n3)},n2.prototype=Object.create(i2),r2)n2.prototype[u2]=r2[u2];return G(n2)},l:function(n2){var t2=ns[n2];delete ns[n2];var{ea:r2,V:e2,ha:a2}=t2;nh([n2],a2.map((n3)=>n3.sa).concat(a2.map((n3)=>n3.ya)),(n3)=>{var i2={};return a2.forEach((t3,r3)=>{var e3=n3[r3],o2=t3.qa,s2=t3.ra,u2=n3[r3+a2.length],c2=t3.xa,f2=t3.za;i2[t3.na]={read:(n4)=>e3.fromWireType(o2(s2,n4)),write:(n4,t4)=>{var r4=[];c2(f2,n4,u2.toWireType(r4,t4)),nu(r4)}}}),[{name:t2.name,fromWireType:function(n4){var t3,r3={};for(t3 in i2)r3[t3]=i2[t3].read(n4);return e2(n4),r3},toWireType:function(n4,t3){for(var a3 in i2)if(!(a3 in t3))throw TypeError('Missing field: "'+a3+'"');var o2=r2();for(a3 in i2)i2[a3].write(o2,t3[a3]);return n4!==null&&n4.push(e2,o2),o2},argPackAdvance:8,readValueFromPointer:nc,U:e2}]})},v:function(){},B:function(n2,t2,r2,e2,a2){var i2=np(r2);nv(n2,{name:t2=B(t2),fromWireType:function(n3){return!!n3},toWireType:function(n3,t3){return t3?e2:a2},argPackAdvance:8,readValueFromPointer:function(n3){if(r2===1)var e3=d;else if(r2===2)e3=m;else if(r2===4)e3=g;else throw TypeError("Unknown boolean type size: "+t2);return this.fromWireType(e3[n3>>i2])},U:null})},h:function(n2,t2,r2,e2,a2,i2,o2,s2,c2,f2,l2,h2,p2){l2=B(l2),i2=nb(a2,i2),s2&&(s2=nb(o2,s2)),f2&&(f2=nb(c2,f2)),p2=nb(h2,p2);var v2,d2=W(l2);v2=function(){nI("Cannot construct "+l2+" due to unbound types",[e2])},u.hasOwnProperty(d2)?(V("Cannot register public name '"+d2+"' twice"),nm(u,d2,d2),u.hasOwnProperty(void 0)&&V("Cannot register multiple overloads of a function with the same number of arguments (undefined)!"),u[d2].R[void 0]=v2):u[d2]=v2,nh([n2,t2,r2],e2?[e2]:[],function(t3){if(t3=t3[0],e2)var r3,a3=t3.M,o3=a3.W;else o3=ny.prototype;t3=U(d2,function(){if(Object.getPrototypeOf(this)!==c3)throw new k("Use 'new' to construct "+l2);if(h3.X===void 0)throw new k(l2+" has no accessible constructor");var n3=h3.X[arguments.length];if(n3===void 0)throw new k("Tried to invoke ctor of "+l2+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(h3.X).toString()+") parameters instead!");return n3.apply(this,arguments)});var c3=Object.create(o3,{constructor:{value:t3}});t3.prototype=c3;var h3=new nE(l2,t3,c3,p2,a3,i2,s2,f2);a3=new nA(l2,h3,!0,!1),o3=new nA(l2+"*",h3,!1,!1);var v3=new nA(l2+" const*",h3,!1,!0);return nr[n2]={pointerType:o3,ka:v3},r3=t3,u.hasOwnProperty(d2)||na("Replacing nonexistant public symbol"),u[d2]=r3,u[d2].Y=void 0,[a3,o3,v3]})},d:function(n2,t2,r2,e2,a2,i2,o2){var s2=nS(r2,e2);t2=B(t2),i2=nb(a2,i2),nh([],[n2],function(n3){function e3(){nI("Cannot call "+a3+" due to unbound types",s2)}var a3=(n3=n3[0]).name+"."+t2;t2.startsWith("@@")&&(t2=Symbol[t2.substring(2)]);var u2=n3.M.constructor;return u2[t2]===void 0?(e3.Y=r2-1,u2[t2]=e3):(nm(u2,t2,a3),u2[t2].R[r2-1]=e3),nh([],s2,function(n4){return n4=nw(a3,[n4[0],null].concat(n4.slice(1)),null,i2,o2),u2[t2].R===void 0?(n4.Y=r2-1,u2[t2]=n4):u2[t2].R[r2-1]=n4,[]}),[]})},p:function(n2,t2,r2,e2,a2,i2){0<t2||w();var o2=nS(t2,r2);a2=nb(e2,a2),nh([],[n2],function(n3){var r3="constructor "+(n3=n3[0]).name;if(n3.M.X===void 0&&(n3.M.X=[]),n3.M.X[t2-1]!==void 0)throw new k("Cannot register multiple constructors with identical number of parameters ("+(t2-1)+") for class '"+n3.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return n3.M.X[t2-1]=()=>{nI("Cannot construct "+n3.name+" due to unbound types",o2)},nh([],o2,function(e3){return e3.splice(1,0,null),n3.M.X[t2-1]=nw(r3,e3,null,a2,i2),[]}),[]})},a:function(n2,t2,r2,e2,a2,i2,o2,s2){var u2=nS(r2,e2);t2=B(t2),i2=nb(a2,i2),nh([],[n2],function(n3){function e3(){nI("Cannot call "+a3+" due to unbound types",u2)}var a3=(n3=n3[0]).name+"."+t2;t2.startsWith("@@")&&(t2=Symbol[t2.substring(2)]),s2&&n3.M.ia.push(t2);var c2=n3.M.W,f2=c2[t2];return f2===void 0||f2.R===void 0&&f2.className!==n3.name&&f2.Y===r2-2?(e3.Y=r2-2,e3.className=n3.name,c2[t2]=e3):(nm(c2,t2,a3),c2[t2].R[r2-2]=e3),nh([],u2,function(e4){return e4=nw(a3,e4,n3,i2,o2),c2[t2].R===void 0?(e4.Y=r2-2,c2[t2]=e4):c2[t2].R[r2-2]=e4,[]}),[]})},A:function(n2,t2){nv(n2,{name:t2=B(t2),fromWireType:function(n3){var t3=j(n3);return nR(n3),t3},toWireType:function(n3,t3){return G(t3)},argPackAdvance:8,readValueFromPointer:nc,U:null})},n:function(n2,t2,r2){r2=np(r2),nv(n2,{name:t2=B(t2),fromWireType:function(n3){return n3},toWireType:function(n3,t3){return t3},argPackAdvance:8,readValueFromPointer:function(n3,t3){switch(t3){case 2:return function(n4){return this.fromWireType(T[n4>>2])};case 3:return function(n4){return this.fromWireType(L[n4>>3])};default:throw TypeError("Unknown float type: "+n3)}}(t2,r2),U:null})},e:function(n2,t2,r2,e2,a2){t2=B(t2),a2===-1&&(a2=4294967295),a2=np(r2);var i2=(n3)=>n3;if(e2===0){var o2=32-8*r2;i2=(n3)=>n3<<o2>>>o2}r2=t2.includes("unsigned")?function(n3,t3){return t3>>>0}:function(n3,t3){return t3},nv(n2,{name:t2,fromWireType:i2,toWireType:r2,argPackAdvance:8,readValueFromPointer:function(n3,t3,r3){switch(t3){case 0:return r3?function(n4){return d[n4]}:function(n4){return y[n4]};case 1:return r3?function(n4){return m[n4>>1]}:function(n4){return E[n4>>1]};case 2:return r3?function(n4){return g[n4>>2]}:function(n4){return _[n4>>2]};default:throw TypeError("Unknown integer type: "+n3)}}(t2,a2,e2!==0),U:null})},b:function(n2,t2,r2){function e2(n3){n3>>=2;var t3=_;return new a2(t3.buffer,t3[n3+1],t3[n3])}var a2=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][t2];nv(n2,{name:r2=B(r2),fromWireType:e2,argPackAdvance:8,readValueFromPointer:e2},{ta:!0})},o:function(n2,t2){var r2=(t2=B(t2))==="std::string";nv(n2,{name:t2,fromWireType:function(n3){var t3=_[n3>>2],e2=n3+4;if(r2)for(var a2=e2,i2=0;i2<=t3;++i2){var o2=e2+i2;if(i2==t3||y[o2]==0){if(a2=a2?p(y,a2,o2-a2):"",s2===void 0)var s2=a2;else s2+="\x00"+a2;a2=o2+1}}else{for(i2=0,s2=Array(t3);i2<t3;++i2)s2[i2]=String.fromCharCode(y[e2+i2]);s2=s2.join("")}return nZ(n3),s2},toWireType:function(n3,t3){t3 instanceof ArrayBuffer&&(t3=new Uint8Array(t3));var e2,a2=typeof t3=="string";if(a2||t3 instanceof Uint8Array||t3 instanceof Uint8ClampedArray||t3 instanceof Int8Array||V("Cannot pass non-string to std::string"),r2&&a2){var i2=0;for(e2=0;e2<t3.length;++e2){var o2=t3.charCodeAt(e2);127>=o2?i2++:2047>=o2?i2+=2:55296<=o2&&57343>=o2?(i2+=4,++e2):i2+=3}e2=i2}else e2=t3.length;if(o2=(i2=n$(4+e2+1))+4,_[i2>>2]=e2,r2&&a2){if(a2=o2,o2=e2+1,e2=y,0<o2){o2=a2+o2-1;for(var s2=0;s2<t3.length;++s2){var u2=t3.charCodeAt(s2);if(55296<=u2&&57343>=u2&&(u2=65536+((1023&u2)<<10)|1023&t3.charCodeAt(++s2)),127>=u2){if(a2>=o2)break;e2[a2++]=u2}else{if(2047>=u2){if(a2+1>=o2)break;e2[a2++]=192|u2>>6}else{if(65535>=u2){if(a2+2>=o2)break;e2[a2++]=224|u2>>12}else{if(a2+3>=o2)break;e2[a2++]=240|u2>>18,e2[a2++]=128|u2>>12&63}e2[a2++]=128|u2>>6&63}e2[a2++]=128|63&u2}}e2[a2]=0}}else if(a2)for(a2=0;a2<e2;++a2)255<(s2=t3.charCodeAt(a2))&&(nZ(o2),V("String has UTF-16 code units that do not fit in 8 bits")),y[o2+a2]=s2;else for(a2=0;a2<e2;++a2)y[o2+a2]=t3[a2];return n3!==null&&n3.push(nZ,i2),i2},argPackAdvance:8,readValueFromPointer:nc,U:function(n3){nZ(n3)}})},k:function(n2,t2,r2){if(r2=B(r2),t2===2)var e2=nW,a2=nU,i2=nM,o2=()=>E,s2=1;else t2===4&&(e2=nF,a2=nD,i2=nk,o2=()=>_,s2=2);nv(n2,{name:r2,fromWireType:function(n3){for(var r3,a3=_[n3>>2],i3=o2(),u2=n3+4,c2=0;c2<=a3;++c2){var f2=n3+4+c2*t2;(c2==a3||i3[f2>>s2]==0)&&(u2=e2(u2,f2-u2),r3===void 0?r3=u2:r3+="\x00"+u2,u2=f2+t2)}return nZ(n3),r3},toWireType:function(n3,e3){typeof e3!="string"&&V("Cannot pass non-string to C++ string type "+r2);var o3=i2(e3),u2=n$(4+o3+t2);return _[u2>>2]=o3>>s2,a2(e3,u2+4,o3+t2),n3!==null&&n3.push(nZ,u2),u2},argPackAdvance:8,readValueFromPointer:nc,U:function(n3){nZ(n3)}})},m:function(n2,t2,r2,e2,a2,i2){ns[n2]={name:B(t2),ea:nb(r2,e2),V:nb(a2,i2),ha:[]}},c:function(n2,t2,r2,e2,a2,i2,o2,s2,u2,c2){ns[n2].ha.push({na:B(t2),sa:r2,qa:nb(e2,a2),ra:i2,ya:o2,xa:nb(s2,u2),za:c2})},C:function(n2,t2){nv(n2,{ua:!0,name:t2=B(t2),argPackAdvance:0,fromWireType:function(){},toWireType:function(){}})},t:function(n2,t2,r2,e2,a2){n2=nG[n2],t2=j(t2),r2=nj(r2);var i2=[];return _[e2>>2]=G(i2),n2(t2,r2,i2,a2)},j:function(n2,t2,r2,e2){n2=nG[n2],n2(t2=j(t2),r2=nj(r2),null,e2)},f:nR,g:function(n2,t2){var r2,e2,a2=function(n3,t3){for(var r3=Array(n3),e3=0;e3<n3;++e3)r3[e3]=K(_[t3+4*e3>>2],"parameter "+e3);return r3}(n2,t2),i2=a2[0],o2=nY[t2=i2.name+"_$"+a2.slice(1).map(function(n3){return n3.name}).join("_")+"$"];if(o2!==void 0)return o2;var s2=Array(n2-1);return r2=(t3,r3,e3,o3)=>{for(var u2=0,c2=0;c2<n2-1;++c2)s2[c2]=a2[c2+1].readValueFromPointer(o3+u2),u2+=a2[c2+1].argPackAdvance;for(c2=0,t3=t3[r3].apply(t3,s2);c2<n2-1;++c2)a2[c2+1].la&&a2[c2+1].la(s2[c2]);if(!i2.ua)return i2.toWireType(e3,t3)},e2=nG.length,nG.push(r2),o2=e2,nY[t2]=o2},r:function(n2){4<n2&&(M[n2].fa+=1)},s:function(n2){nu(j(n2)),nR(n2)},i:function(){w("")},x:function(n2,t2,r2){y.copyWithin(n2,t2,t2+r2)},w:function(n2){var t2=y.length;if(2147483648<(n2>>>=0))return!1;for(var r2=1;4>=r2;r2*=2){var e2=t2*(1+0.2/r2);e2=Math.min(e2,n2+100663296);var a2=Math,i2=a2.min;e2=Math.max(n2,e2),e2+=(65536-e2%65536)%65536;n:{var o2=l.buffer;try{l.grow(i2.call(a2,2147483648,e2)-o2.byteLength+65535>>>16),v();var s2=1;break n}catch(n3){}s2=void 0}if(s2)return!0}return!1},z:function(){return 52},u:function(){return 70},y:function(n2,t2,r2,e2){for(var a2=0,i2=0;i2<r2;i2++){var u2=_[t2>>2],c2=_[t2+4>>2];t2+=8;for(var f2=0;f2<c2;f2++){var l2=y[u2+f2],h2=nX[n2];l2===0||l2===10?((n2===1?o:s)(p(h2,0)),h2.length=0):h2.push(l2)}a2+=c2}return _[e2>>2]=a2,0}};(function(){function n2(n3){u.asm=n3.exports,l=u.asm.D,v(),A=u.asm.I,P.unshift(u.asm.E),--N==0&&I&&(n3=I,I=null,n3())}function t2(t3){n2(t3.instance)}function e2(n3){return(typeof fetch=="function"?fetch(r,{credentials:"same-origin"}).then(function(n4){if(!n4.ok)throw"failed to load wasm binary file at '"+r+"'";return n4.arrayBuffer()}).catch(function(){return R()}):Promise.resolve().then(function(){return R()})).then(function(n4){return WebAssembly.instantiate(n4,a2)}).then(function(n4){return n4}).then(n3,function(n4){s("failed to asynchronously prepare wasm: "+n4),w(n4)})}var a2={a:nx};if(N++,u.instantiateWasm)try{return u.instantiateWasm(a2,n2)}catch(n3){s("Module.instantiateWasm callback failed with error: "+n3),f(n3)}(typeof WebAssembly.instantiateStreaming!="function"||S()||typeof fetch!="function"?e2(t2):fetch(r,{credentials:"same-origin"}).then(function(n3){return WebAssembly.instantiateStreaming(n3,a2).then(t2,function(n4){return s("wasm streaming compile failed: "+n4),s("falling back to ArrayBuffer instantiation"),e2(t2)})})).catch(f)})();var nz=u.___getTypeName=function(){return(nz=u.___getTypeName=u.asm.F).apply(null,arguments)};function n$(){return(n$=u.asm.H).apply(null,arguments)}function nZ(){return(nZ=u.asm.J).apply(null,arguments)}function nJ(){0<N||(C(O),0<N||e||(e=!0,u.calledRun=!0,h||(C(P),c(u),C(b))))}return u.__embind_initialize_bindings=function(){return(u.__embind_initialize_bindings=u.asm.G).apply(null,arguments)},u.dynCall_jiji=function(){return(u.dynCall_jiji=u.asm.K).apply(null,arguments)},I=function n2(){e||nJ(),e||(I=n2)},nJ(),t.ready}})()});var exports_node={};__export(exports_node,{default:()=>Yoga,WRAP_WRAP_REVERSE:()=>WRAP_WRAP_REVERSE,WRAP_WRAP:()=>WRAP_WRAP,WRAP_NO_WRAP:()=>WRAP_NO_WRAP,UNIT_UNDEFINED:()=>UNIT_UNDEFINED,UNIT_POINT:()=>UNIT_POINT,UNIT_PERCENT:()=>UNIT_PERCENT,UNIT_AUTO:()=>UNIT_AUTO,PRINT_OPTIONS_STYLE:()=>PRINT_OPTIONS_STYLE,PRINT_OPTIONS_LAYOUT:()=>PRINT_OPTIONS_LAYOUT,PRINT_OPTIONS_CHILDREN:()=>PRINT_OPTIONS_CHILDREN,POSITION_TYPE_STATIC:()=>POSITION_TYPE_STATIC,POSITION_TYPE_RELATIVE:()=>POSITION_TYPE_RELATIVE,POSITION_TYPE_ABSOLUTE:()=>POSITION_TYPE_ABSOLUTE,OVERFLOW_VISIBLE:()=>OVERFLOW_VISIBLE,OVERFLOW_SCROLL:()=>OVERFLOW_SCROLL,OVERFLOW_HIDDEN:()=>OVERFLOW_HIDDEN,NODE_TYPE_TEXT:()=>NODE_TYPE_TEXT,NODE_TYPE_DEFAULT:()=>NODE_TYPE_DEFAULT,MEASURE_MODE_UNDEFINED:()=>MEASURE_MODE_UNDEFINED,MEASURE_MODE_EXACTLY:()=>MEASURE_MODE_EXACTLY,MEASURE_MODE_AT_MOST:()=>MEASURE_MODE_AT_MOST,LOG_LEVEL_WARN:()=>LOG_LEVEL_WARN,LOG_LEVEL_VERBOSE:()=>LOG_LEVEL_VERBOSE,LOG_LEVEL_INFO:()=>LOG_LEVEL_INFO,LOG_LEVEL_FATAL:()=>LOG_LEVEL_FATAL,LOG_LEVEL_ERROR:()=>LOG_LEVEL_ERROR,LOG_LEVEL_DEBUG:()=>LOG_LEVEL_DEBUG,JUSTIFY_SPACE_EVENLY:()=>JUSTIFY_SPACE_EVENLY,JUSTIFY_SPACE_BETWEEN:()=>JUSTIFY_SPACE_BETWEEN,JUSTIFY_SPACE_AROUND:()=>JUSTIFY_SPACE_AROUND,JUSTIFY_FLEX_START:()=>JUSTIFY_FLEX_START,JUSTIFY_FLEX_END:()=>JUSTIFY_FLEX_END,JUSTIFY_CENTER:()=>JUSTIFY_CENTER,GUTTER_ROW:()=>GUTTER_ROW,GUTTER_COLUMN:()=>GUTTER_COLUMN,GUTTER_ALL:()=>GUTTER_ALL,FLEX_DIRECTION_ROW_REVERSE:()=>FLEX_DIRECTION_ROW_REVERSE,FLEX_DIRECTION_ROW:()=>FLEX_DIRECTION_ROW,FLEX_DIRECTION_COLUMN_REVERSE:()=>FLEX_DIRECTION_COLUMN_REVERSE,FLEX_DIRECTION_COLUMN:()=>FLEX_DIRECTION_COLUMN,EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS:()=>EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS,EXPERIMENTAL_FEATURE_FIX_ABSOLUTE_TRAILING_COLUMN_MARGIN:()=>EXPERIMENTAL_FEATURE_FIX_ABSOLUTE_TRAILING_COLUMN_MARGIN,EXPERIMENTAL_FEATURE_ABSOLUTE_PERCENTAGE_AGAINST_PADDING_EDGE:()=>EXPERIMENTAL_FEATURE_ABSOLUTE_PERCENTAGE_AGAINST_PADDING_EDGE,EDGE_VERTICAL:()=>EDGE_VERTICAL,EDGE_TOP:()=>EDGE_TOP,EDGE_START:()=>EDGE_START,EDGE_RIGHT:()=>EDGE_RIGHT,EDGE_LEFT:()=>EDGE_LEFT,EDGE_HORIZONTAL:()=>EDGE_HORIZONTAL,EDGE_END:()=>EDGE_END,EDGE_BOTTOM:()=>EDGE_BOTTOM,EDGE_ALL:()=>EDGE_ALL,DISPLAY_NONE:()=>DISPLAY_NONE,DISPLAY_FLEX:()=>DISPLAY_FLEX,DIRECTION_RTL:()=>DIRECTION_RTL,DIRECTION_LTR:()=>DIRECTION_LTR,DIRECTION_INHERIT:()=>DIRECTION_INHERIT,DIMENSION_WIDTH:()=>DIMENSION_WIDTH,DIMENSION_HEIGHT:()=>DIMENSION_HEIGHT,ALIGN_STRETCH:()=>ALIGN_STRETCH,ALIGN_SPACE_BETWEEN:()=>ALIGN_SPACE_BETWEEN,ALIGN_SPACE_AROUND:()=>ALIGN_SPACE_AROUND,ALIGN_FLEX_START:()=>ALIGN_FLEX_START,ALIGN_FLEX_END:()=>ALIGN_FLEX_END,ALIGN_CENTER:()=>ALIGN_CENTER,ALIGN_BASELINE:()=>ALIGN_BASELINE,ALIGN_AUTO:()=>ALIGN_AUTO});import{readFile as E}from"node:fs/promises";import{createRequire as _}from"node:module";var Yoga;var init_node=__esm(async()=>{init_dist();init_wrapAsm_f766f97f();Yoga=await initYoga(await E(_(import.meta.url).resolve("./yoga.wasm")))});var exports_yoga_adapter={};__export(exports_yoga_adapter,{initYogaEngine:()=>initYogaEngine,createYogaEngine:()=>createYogaEngine,YogaLayoutEngine:()=>YogaLayoutEngine});class YogaNodeAdapter{node;yoga;hasMeasureFunc=!1;constructor(node,yoga2){this.node=node,this.yoga=yoga2}getYogaNode(){return this.node}insertChild(child,index){let yogaChild=child.getYogaNode();this.node.insertChild(yogaChild,index)}removeChild(child){let yogaChild=child.getYogaNode();this.node.removeChild(yogaChild)}free(){this.node.free()}setMeasureFunc(measureFunc){this.hasMeasureFunc=!0,this.node.setMeasureFunc((width,widthMode,height,heightMode)=>{let widthModeStr=this.measureModeToString(widthMode),heightModeStr=this.measureModeToString(heightMode);return measureFunc(width,widthModeStr,height,heightModeStr)})}markDirty(){if(this.hasMeasureFunc)this.node.markDirty()}measureModeToString(mode){if(mode===this.yoga.MEASURE_MODE_EXACTLY)return"exactly";if(mode===this.yoga.MEASURE_MODE_AT_MOST)return"at-most";return"undefined"}setWidth(value){this.node.setWidth(value)}setWidthPercent(value){this.node.setWidthPercent(value)}setWidthAuto(){this.node.setWidthAuto()}setHeight(value){this.node.setHeight(value)}setHeightPercent(value){this.node.setHeightPercent(value)}setHeightAuto(){this.node.setHeightAuto()}setMinWidth(value){this.node.setMinWidth(value)}setMinWidthPercent(value){this.node.setMinWidthPercent(value)}setMinHeight(value){this.node.setMinHeight(value)}setMinHeightPercent(value){this.node.setMinHeightPercent(value)}setMaxWidth(value){this.node.setMaxWidth(value)}setMaxWidthPercent(value){this.node.setMaxWidthPercent(value)}setMaxHeight(value){this.node.setMaxHeight(value)}setMaxHeightPercent(value){this.node.setMaxHeightPercent(value)}setFlexGrow(value){this.node.setFlexGrow(value)}setFlexShrink(value){this.node.setFlexShrink(value)}setFlexBasis(value){this.node.setFlexBasis(value)}setFlexBasisPercent(value){this.node.setFlexBasisPercent(value)}setFlexBasisAuto(){this.node.setFlexBasisAuto()}setFlexDirection(direction){this.node.setFlexDirection(direction)}setFlexWrap(wrap){this.node.setFlexWrap(wrap)}setAlignItems(align){this.node.setAlignItems(align)}setAlignSelf(align){this.node.setAlignSelf(align)}setAlignContent(align){this.node.setAlignContent(align)}setJustifyContent(justify){this.node.setJustifyContent(justify)}setPadding(edge,value){this.node.setPadding(edge,value)}setMargin(edge,value){this.node.setMargin(edge,value)}setBorder(edge,value){this.node.setBorder(edge,value)}setGap(gutter,value){this.node.setGap(gutter,value)}setDisplay(display){this.node.setDisplay(display)}setPositionType(positionType){this.node.setPositionType(positionType)}setPosition(edge,value){this.node.setPosition(edge,value)}setPositionPercent(edge,value){this.node.setPositionPercent(edge,value)}setOverflow(overflow){this.node.setOverflow(overflow)}setAspectRatio(value){this.node.setAspectRatio(value)}calculateLayout(width,height,direction){this.node.calculateLayout(width,height,direction??this.yoga.DIRECTION_LTR)}getComputedLeft(){return this.node.getComputedLeft()}getComputedTop(){return this.node.getComputedTop()}getComputedWidth(){return this.node.getComputedWidth()}getComputedHeight(){return this.node.getComputedHeight()}}class YogaLayoutEngine{yoga;_constants;constructor(yoga2){this.yoga=yoga2,this._constants={FLEX_DIRECTION_COLUMN:yoga2.FLEX_DIRECTION_COLUMN,FLEX_DIRECTION_COLUMN_REVERSE:yoga2.FLEX_DIRECTION_COLUMN_REVERSE,FLEX_DIRECTION_ROW:yoga2.FLEX_DIRECTION_ROW,FLEX_DIRECTION_ROW_REVERSE:yoga2.FLEX_DIRECTION_ROW_REVERSE,WRAP_NO_WRAP:yoga2.WRAP_NO_WRAP,WRAP_WRAP:yoga2.WRAP_WRAP,WRAP_WRAP_REVERSE:yoga2.WRAP_WRAP_REVERSE,ALIGN_AUTO:yoga2.ALIGN_AUTO,ALIGN_FLEX_START:yoga2.ALIGN_FLEX_START,ALIGN_CENTER:yoga2.ALIGN_CENTER,ALIGN_FLEX_END:yoga2.ALIGN_FLEX_END,ALIGN_STRETCH:yoga2.ALIGN_STRETCH,ALIGN_BASELINE:yoga2.ALIGN_BASELINE,ALIGN_SPACE_BETWEEN:yoga2.ALIGN_SPACE_BETWEEN,ALIGN_SPACE_AROUND:yoga2.ALIGN_SPACE_AROUND,ALIGN_SPACE_EVENLY:yoga2.ALIGN_SPACE_EVENLY,JUSTIFY_FLEX_START:yoga2.JUSTIFY_FLEX_START,JUSTIFY_CENTER:yoga2.JUSTIFY_CENTER,JUSTIFY_FLEX_END:yoga2.JUSTIFY_FLEX_END,JUSTIFY_SPACE_BETWEEN:yoga2.JUSTIFY_SPACE_BETWEEN,JUSTIFY_SPACE_AROUND:yoga2.JUSTIFY_SPACE_AROUND,JUSTIFY_SPACE_EVENLY:yoga2.JUSTIFY_SPACE_EVENLY,EDGE_LEFT:yoga2.EDGE_LEFT,EDGE_TOP:yoga2.EDGE_TOP,EDGE_RIGHT:yoga2.EDGE_RIGHT,EDGE_BOTTOM:yoga2.EDGE_BOTTOM,EDGE_HORIZONTAL:yoga2.EDGE_HORIZONTAL,EDGE_VERTICAL:yoga2.EDGE_VERTICAL,EDGE_ALL:yoga2.EDGE_ALL,GUTTER_COLUMN:yoga2.GUTTER_COLUMN,GUTTER_ROW:yoga2.GUTTER_ROW,GUTTER_ALL:yoga2.GUTTER_ALL,DISPLAY_FLEX:yoga2.DISPLAY_FLEX,DISPLAY_NONE:yoga2.DISPLAY_NONE,POSITION_TYPE_STATIC:yoga2.POSITION_TYPE_STATIC,POSITION_TYPE_RELATIVE:yoga2.POSITION_TYPE_RELATIVE,POSITION_TYPE_ABSOLUTE:yoga2.POSITION_TYPE_ABSOLUTE,OVERFLOW_VISIBLE:yoga2.OVERFLOW_VISIBLE,OVERFLOW_HIDDEN:yoga2.OVERFLOW_HIDDEN,OVERFLOW_SCROLL:yoga2.OVERFLOW_SCROLL,DIRECTION_LTR:yoga2.DIRECTION_LTR,MEASURE_MODE_UNDEFINED:yoga2.MEASURE_MODE_UNDEFINED,MEASURE_MODE_EXACTLY:yoga2.MEASURE_MODE_EXACTLY,MEASURE_MODE_AT_MOST:yoga2.MEASURE_MODE_AT_MOST}}createNode(){return new YogaNodeAdapter(this.yoga.Node.create(),this.yoga)}get constants(){return this._constants}get name(){return"yoga"}}function createYogaEngine(yoga2){return new YogaLayoutEngine(yoga2)}async function initYogaEngine(){let{default:yoga2}=await init_node().then(() => exports_node);return new YogaLayoutEngine(yoga2)}var exports_flexily_zero_adapter={};__export(exports_flexily_zero_adapter,{createFlexilyZeroEngine:()=>createFlexilyZeroEngine,FlexilyZeroLayoutEngine:()=>FlexilyZeroLayoutEngine});import{ALIGN_AUTO as ALIGN_AUTO2,ALIGN_BASELINE as ALIGN_BASELINE2,ALIGN_CENTER as ALIGN_CENTER2,ALIGN_FLEX_END as ALIGN_FLEX_END2,ALIGN_FLEX_START as ALIGN_FLEX_START2,ALIGN_SPACE_AROUND as ALIGN_SPACE_AROUND2,ALIGN_SPACE_BETWEEN as ALIGN_SPACE_BETWEEN2,ALIGN_SPACE_EVENLY,ALIGN_STRETCH as ALIGN_STRETCH2,DIRECTION_LTR as DIRECTION_LTR2,DISPLAY_FLEX as DISPLAY_FLEX2,DISPLAY_NONE as DISPLAY_NONE2,EDGE_ALL as EDGE_ALL2,EDGE_BOTTOM as EDGE_BOTTOM2,EDGE_HORIZONTAL as EDGE_HORIZONTAL2,EDGE_LEFT as EDGE_LEFT2,EDGE_RIGHT as EDGE_RIGHT2,EDGE_TOP as EDGE_TOP2,EDGE_VERTICAL as EDGE_VERTICAL2,FLEX_DIRECTION_COLUMN as FLEX_DIRECTION_COLUMN2,FLEX_DIRECTION_COLUMN_REVERSE as FLEX_DIRECTION_COLUMN_REVERSE2,FLEX_DIRECTION_ROW as FLEX_DIRECTION_ROW2,FLEX_DIRECTION_ROW_REVERSE as FLEX_DIRECTION_ROW_REVERSE2,Node as FlexilyNode,GUTTER_ALL as GUTTER_ALL2,GUTTER_COLUMN as GUTTER_COLUMN2,GUTTER_ROW as GUTTER_ROW2,JUSTIFY_CENTER as JUSTIFY_CENTER2,JUSTIFY_FLEX_END as JUSTIFY_FLEX_END2,JUSTIFY_FLEX_START as JUSTIFY_FLEX_START2,JUSTIFY_SPACE_AROUND as JUSTIFY_SPACE_AROUND2,JUSTIFY_SPACE_BETWEEN as JUSTIFY_SPACE_BETWEEN2,JUSTIFY_SPACE_EVENLY as JUSTIFY_SPACE_EVENLY2,MEASURE_MODE_AT_MOST as MEASURE_MODE_AT_MOST2,MEASURE_MODE_EXACTLY as MEASURE_MODE_EXACTLY2,MEASURE_MODE_UNDEFINED as MEASURE_MODE_UNDEFINED2,OVERFLOW_HIDDEN as OVERFLOW_HIDDEN2,OVERFLOW_SCROLL as OVERFLOW_SCROLL2,OVERFLOW_VISIBLE as OVERFLOW_VISIBLE2,POSITION_TYPE_ABSOLUTE as POSITION_TYPE_ABSOLUTE2,POSITION_TYPE_RELATIVE as POSITION_TYPE_RELATIVE2,POSITION_TYPE_STATIC as POSITION_TYPE_STATIC2,WRAP_NO_WRAP as WRAP_NO_WRAP2,WRAP_WRAP as WRAP_WRAP2,WRAP_WRAP_REVERSE as WRAP_WRAP_REVERSE2}from"flexily";class FlexilyZeroNodeAdapter{node;constructor(node){this.node=node}getFlexilyNode(){return this.node}insertChild(child,index){let flexilyChild=child.getFlexilyNode();this.node.insertChild(flexilyChild,index)}removeChild(child){let flexilyChild=child.getFlexilyNode();this.node.removeChild(flexilyChild)}free(){this.node.free()}setMeasureFunc(measureFunc){this.node.setMeasureFunc((width,widthMode,height,heightMode)=>{let widthModeStr=this.measureModeToString(widthMode),heightModeStr=this.measureModeToString(heightMode);return measureFunc(width,widthModeStr,height,heightModeStr)})}markDirty(){this.node.markDirty()}measureModeToString(mode){if(mode===MEASURE_MODE_EXACTLY2)return"exactly";if(mode===MEASURE_MODE_AT_MOST2)return"at-most";return"undefined"}setWidth(value){this.node.setWidth(value)}setWidthPercent(value){this.node.setWidthPercent(value)}setWidthAuto(){this.node.setWidthAuto()}setHeight(value){this.node.setHeight(value)}setHeightPercent(value){this.node.setHeightPercent(value)}setHeightAuto(){this.node.setHeightAuto()}setMinWidth(value){this.node.setMinWidth(value)}setMinWidthPercent(value){this.node.setMinWidthPercent(value)}setMinHeight(value){this.node.setMinHeight(value)}setMinHeightPercent(value){this.node.setMinHeightPercent(value)}setMaxWidth(value){this.node.setMaxWidth(value)}setMaxWidthPercent(value){this.node.setMaxWidthPercent(value)}setMaxHeight(value){this.node.setMaxHeight(value)}setMaxHeightPercent(value){this.node.setMaxHeightPercent(value)}setFlexGrow(value){this.node.setFlexGrow(value)}setFlexShrink(value){this.node.setFlexShrink(value)}setFlexBasis(value){this.node.setFlexBasis(value)}setFlexBasisPercent(value){this.node.setFlexBasisPercent(value)}setFlexBasisAuto(){this.node.setFlexBasisAuto()}setFlexDirection(direction){this.node.setFlexDirection(direction)}setFlexWrap(wrap){this.node.setFlexWrap(wrap)}setAlignItems(align){this.node.setAlignItems(align)}setAlignSelf(align){this.node.setAlignSelf(align)}setAlignContent(align){this.node.setAlignContent(align)}setJustifyContent(justify){this.node.setJustifyContent(justify)}setPadding(edge,value){this.node.setPadding(edge,value)}setMargin(edge,value){this.node.setMargin(edge,value)}setBorder(edge,value){this.node.setBorder(edge,value)}setGap(gutter,value){this.node.setGap(gutter,value)}setDisplay(display){this.node.setDisplay(display)}setPositionType(positionType){this.node.setPositionType(positionType)}setPosition(edge,value){this.node.setPosition(edge,value)}setPositionPercent(edge,value){this.node.setPositionPercent(edge,value)}setOverflow(overflow){this.node.setOverflow(overflow)}setAspectRatio(value){this.node.setAspectRatio(value)}calculateLayout(width,height,direction){this.node.calculateLayout(width,height,direction??DIRECTION_LTR2)}getComputedLeft(){return this.node.getComputedLeft()}getComputedTop(){return this.node.getComputedTop()}getComputedWidth(){return this.node.getComputedWidth()}getComputedHeight(){return this.node.getComputedHeight()}}class FlexilyZeroLayoutEngine{_constants={FLEX_DIRECTION_COLUMN:FLEX_DIRECTION_COLUMN2,FLEX_DIRECTION_COLUMN_REVERSE:FLEX_DIRECTION_COLUMN_REVERSE2,FLEX_DIRECTION_ROW:FLEX_DIRECTION_ROW2,FLEX_DIRECTION_ROW_REVERSE:FLEX_DIRECTION_ROW_REVERSE2,WRAP_NO_WRAP:WRAP_NO_WRAP2,WRAP_WRAP:WRAP_WRAP2,WRAP_WRAP_REVERSE:WRAP_WRAP_REVERSE2,ALIGN_AUTO:ALIGN_AUTO2,ALIGN_FLEX_START:ALIGN_FLEX_START2,ALIGN_CENTER:ALIGN_CENTER2,ALIGN_FLEX_END:ALIGN_FLEX_END2,ALIGN_STRETCH:ALIGN_STRETCH2,ALIGN_BASELINE:ALIGN_BASELINE2,ALIGN_SPACE_BETWEEN:ALIGN_SPACE_BETWEEN2,ALIGN_SPACE_AROUND:ALIGN_SPACE_AROUND2,ALIGN_SPACE_EVENLY,JUSTIFY_FLEX_START:JUSTIFY_FLEX_START2,JUSTIFY_CENTER:JUSTIFY_CENTER2,JUSTIFY_FLEX_END:JUSTIFY_FLEX_END2,JUSTIFY_SPACE_BETWEEN:JUSTIFY_SPACE_BETWEEN2,JUSTIFY_SPACE_AROUND:JUSTIFY_SPACE_AROUND2,JUSTIFY_SPACE_EVENLY:JUSTIFY_SPACE_EVENLY2,EDGE_LEFT:EDGE_LEFT2,EDGE_TOP:EDGE_TOP2,EDGE_RIGHT:EDGE_RIGHT2,EDGE_BOTTOM:EDGE_BOTTOM2,EDGE_HORIZONTAL:EDGE_HORIZONTAL2,EDGE_VERTICAL:EDGE_VERTICAL2,EDGE_ALL:EDGE_ALL2,GUTTER_COLUMN:GUTTER_COLUMN2,GUTTER_ROW:GUTTER_ROW2,GUTTER_ALL:GUTTER_ALL2,DISPLAY_FLEX:DISPLAY_FLEX2,DISPLAY_NONE:DISPLAY_NONE2,POSITION_TYPE_STATIC:POSITION_TYPE_STATIC2,POSITION_TYPE_RELATIVE:POSITION_TYPE_RELATIVE2,POSITION_TYPE_ABSOLUTE:POSITION_TYPE_ABSOLUTE2,OVERFLOW_VISIBLE:OVERFLOW_VISIBLE2,OVERFLOW_HIDDEN:OVERFLOW_HIDDEN2,OVERFLOW_SCROLL:OVERFLOW_SCROLL2,DIRECTION_LTR:DIRECTION_LTR2,MEASURE_MODE_UNDEFINED:MEASURE_MODE_UNDEFINED2,MEASURE_MODE_EXACTLY:MEASURE_MODE_EXACTLY2,MEASURE_MODE_AT_MOST:MEASURE_MODE_AT_MOST2};createNode(){return new FlexilyZeroNodeAdapter(FlexilyNode.create())}get constants(){return this._constants}get name(){return"flexily-zero"}}function createFlexilyZeroEngine(){return new FlexilyZeroLayoutEngine}var init_flexily_zero_adapter=()=>{};var init_derive2=__esm(()=>{init_src2()});var init_color=__esm(()=>{init_src()});var catppuccinMocha,catppuccinFrappe,catppuccinMacchiato,catppuccinLatte;var init_catppuccin=__esm(()=>{init_color();catppuccinMocha={name:"catppuccin-mocha",dark:!0,black:"#11111B",red:"#F38BA8",green:"#A6E3A1",yellow:"#F9E2AF",blue:"#89B4FA",magenta:"#CBA6F7",cyan:"#94E2D5",white:"#A6ADC8",brightBlack:"#313244",brightRed:"#FAB387",brightGreen:brighten("#A6E3A1",0.15),brightYellow:brighten("#F9E2AF",0.15),brightBlue:brighten("#89B4FA",0.15),brightMagenta:"#F5C2E7",brightCyan:brighten("#94E2D5",0.15),brightWhite:"#CDD6F4",foreground:"#CDD6F4",background:"#1E1E2E",cursorColor:"#CDD6F4",cursorText:"#1E1E2E",selectionBackground:"#6C7086",selectionForeground:"#CDD6F4"},catppuccinFrappe={name:"catppuccin-frappe",dark:!0,black:"#232634",red:"#E78284",green:"#A6D189",yellow:"#E5C890",blue:"#8CAAEE",magenta:"#CA9EE6",cyan:"#81C8BE",white:"#A5ADCE",brightBlack:"#414559",brightRed:"#EF9F76",brightGreen:brighten("#A6D189",0.15),brightYellow:brighten("#E5C890",0.15),brightBlue:brighten("#8CAAEE",0.15),brightMagenta:"#F4B8E4",brightCyan:brighten("#81C8BE",0.15),brightWhite:"#C6D0F5",foreground:"#C6D0F5",background:"#303446",cursorColor:"#C6D0F5",cursorText:"#303446",selectionBackground:"#737994",selectionForeground:"#C6D0F5"},catppuccinMacchiato={name:"catppuccin-macchiato",dark:!0,black:"#181926",red:"#ED8796",green:"#A6DA95",yellow:"#EED49F",blue:"#8AADF4",magenta:"#C6A0F6",cyan:"#8BD5CA",white:"#A5ADCB",brightBlack:"#363A4F",brightRed:"#F5A97F",brightGreen:brighten("#A6DA95",0.15),brightYellow:brighten("#EED49F",0.15),brightBlue:brighten("#8AADF4",0.15),brightMagenta:"#F5BDE6",brightCyan:brighten("#8BD5CA",0.15),brightWhite:"#CAD3F5",foreground:"#CAD3F5",background:"#24273A",cursorColor:"#CAD3F5",cursorText:"#24273A",selectionBackground:"#6E738D",selectionForeground:"#CAD3F5"},catppuccinLatte={name:"catppuccin-latte",dark:!1,black:"#DCE0E8",red:"#D20F39",green:"#40A02B",yellow:"#DF8E1D",blue:"#1E66F5",magenta:"#8839EF",cyan:"#179299",white:"#6C6F85",brightBlack:"#CCD0DA",brightRed:"#FE640B",brightGreen:brighten("#40A02B",0.15),brightYellow:brighten("#DF8E1D",0.15),brightBlue:brighten("#1E66F5",0.15),brightMagenta:"#EA76CB",brightCyan:brighten("#179299",0.15),brightWhite:"#4C4F69",foreground:"#4C4F69",background:"#EFF1F5",cursorColor:"#4C4F69",cursorText:"#EFF1F5",selectionBackground:"#9CA0B0",selectionForeground:"#4C4F69"}});var nord;var init_nord=__esm(()=>{init_color();nord={name:"nord",dark:!0,black:"#2E3440",red:"#BF616A",green:"#A3BE8C",yellow:"#EBCB8B",blue:"#5E81AC",magenta:"#B48EAD",cyan:"#8FBCBB",white:"#D8DEE9",brightBlack:"#3B4252",brightRed:"#D08770",brightGreen:brighten("#A3BE8C",0.15),brightYellow:brighten("#EBCB8B",0.15),brightBlue:brighten("#5E81AC",0.15),brightMagenta:"#B48EAD",brightCyan:brighten("#8FBCBB",0.15),brightWhite:"#ECEFF4",foreground:"#ECEFF4",background:"#2E3440",cursorColor:"#ECEFF4",cursorText:"#2E3440",selectionBackground:"#4C566A",selectionForeground:"#ECEFF4"}});var dracula;var init_dracula=__esm(()=>{init_color();dracula={name:"dracula",dark:!0,black:"#21222C",red:"#FF5555",green:"#50FA7B",yellow:"#F1FA8C",blue:"#BD93F9",magenta:"#BD93F9",cyan:"#8BE9FD",white:"#6272A4",brightBlack:"#44475A",brightRed:"#FFB86C",brightGreen:brighten("#50FA7B",0.15),brightYellow:brighten("#F1FA8C",0.15),brightBlue:brighten("#BD93F9",0.15),brightMagenta:"#FF79C6",brightCyan:brighten("#8BE9FD",0.15),brightWhite:"#F8F8F2",foreground:"#F8F8F2",background:"#282A36",cursorColor:"#F8F8F2",cursorText:"#282A36",selectionBackground:"#6272A4",selectionForeground:"#F8F8F2"}});var solarizedDark,solarizedLight;var init_solarized=__esm(()=>{init_color();solarizedDark={name:"solarized-dark",dark:!0,black:"#002B36",red:"#DC322F",green:"#859900",yellow:"#B58900",blue:"#268BD2",magenta:"#6C71C4",cyan:"#2AA198",white:"#839496",brightBlack:"#586E75",brightRed:"#CB4B16",brightGreen:brighten("#859900",0.15),brightYellow:brighten("#B58900",0.15),brightBlue:brighten("#268BD2",0.15),brightMagenta:"#D33682",brightCyan:brighten("#2AA198",0.15),brightWhite:"#FDF6E3",foreground:"#FDF6E3",background:"#073642",cursorColor:"#FDF6E3",cursorText:"#073642",selectionBackground:"#657B83",selectionForeground:"#FDF6E3"},solarizedLight={name:"solarized-light",dark:!1,black:"#FDF6E3",red:"#DC322F",green:"#859900",yellow:"#B58900",blue:"#268BD2",magenta:"#6C71C4",cyan:"#2AA198",white:"#657B83",brightBlack:"#DDD6C1",brightRed:"#CB4B16",brightGreen:brighten("#859900",0.15),brightYellow:brighten("#B58900",0.15),brightBlue:brighten("#268BD2",0.15),brightMagenta:"#D33682",brightCyan:brighten("#2AA198",0.15),brightWhite:"#073642",foreground:"#073642",background:"#EEE8D5",cursorColor:"#073642",cursorText:"#EEE8D5",selectionBackground:"#93A1A1",selectionForeground:"#073642"}});var tokyoNight,tokyoNightStorm,tokyoNightDay;var init_tokyo_night=__esm(()=>{init_color();tokyoNight={name:"tokyo-night",dark:!0,black:"#1A1B26",red:"#F7768E",green:"#9ECE6A",yellow:"#E0AF68",blue:"#7AA2F7",magenta:"#BB9AF7",cyan:"#73DACA",white:"#A9B1D6",brightBlack:"#292E42",brightRed:"#FF9E64",brightGreen:brighten("#9ECE6A",0.15),brightYellow:brighten("#E0AF68",0.15),brightBlue:brighten("#7AA2F7",0.15),brightMagenta:"#FF007C",brightCyan:brighten("#73DACA",0.15),brightWhite:"#C0CAF5",foreground:"#C0CAF5",background:"#24283B",cursorColor:"#C0CAF5",cursorText:"#24283B",selectionBackground:"#545C7E",selectionForeground:"#C0CAF5"},tokyoNightStorm={name:"tokyo-night-storm",dark:!0,black:"#1F2335",red:"#F7768E",green:"#9ECE6A",yellow:"#E0AF68",blue:"#7AA2F7",magenta:"#BB9AF7",cyan:"#73DACA",white:"#A9B1D6",brightBlack:"#292E42",brightRed:"#FF9E64",brightGreen:brighten("#9ECE6A",0.15),brightYellow:brighten("#E0AF68",0.15),brightBlue:brighten("#7AA2F7",0.15),brightMagenta:"#FF007C",brightCyan:brighten("#73DACA",0.15),brightWhite:"#C0CAF5",foreground:"#C0CAF5",background:"#24283B",cursorColor:"#C0CAF5",cursorText:"#24283B",selectionBackground:"#545C7E",selectionForeground:"#C0CAF5"},tokyoNightDay={name:"tokyo-night-day",dark:!1,black:"#E1E2E7",red:"#F52A65",green:"#587539",yellow:"#8C6C3E",blue:"#2E7DE9",magenta:"#9854F1",cyan:"#118C74",white:"#6172B0",brightBlack:"#C4C5CB",brightRed:"#B15C00",brightGreen:brighten("#587539",0.15),brightYellow:brighten("#8C6C3E",0.15),brightBlue:brighten("#2E7DE9",0.15),brightMagenta:"#F52A65",brightCyan:brighten("#118C74",0.15),brightWhite:"#3760BF",foreground:"#3760BF",background:"#D5D6DB",cursorColor:"#3760BF",cursorText:"#D5D6DB",selectionBackground:"#9699A3",selectionForeground:"#3760BF"}});var oneDark;var init_one_dark=__esm(()=>{init_color();oneDark={name:"one-dark",dark:!0,black:"#21252B",red:"#E06C75",green:"#98C379",yellow:"#E5C07B",blue:"#61AFEF",magenta:"#C678DD",cyan:"#56B6C2",white:"#ABB2BF",brightBlack:"#2C313A",brightRed:"#D19A66",brightGreen:brighten("#98C379",0.15),brightYellow:brighten("#E5C07B",0.15),brightBlue:brighten("#61AFEF",0.15),brightMagenta:"#E06C75",brightCyan:brighten("#56B6C2",0.15),brightWhite:"#ABB2BF",foreground:"#ABB2BF",background:"#282C34",cursorColor:"#ABB2BF",cursorText:"#282C34",selectionBackground:"#5C6370",selectionForeground:"#ABB2BF"}});var gruvboxDark,gruvboxLight;var init_gruvbox=__esm(()=>{init_color();gruvboxDark={name:"gruvbox-dark",dark:!0,black:"#1D2021",red:"#FB4934",green:"#B8BB26",yellow:"#FABD2F",blue:"#83A598",magenta:"#D3869B",cyan:"#8EC07C",white:"#BDAE93",brightBlack:"#3C3836",brightRed:"#FE8019",brightGreen:brighten("#B8BB26",0.15),brightYellow:brighten("#FABD2F",0.15),brightBlue:brighten("#83A598",0.15),brightMagenta:"#D3869B",brightCyan:brighten("#8EC07C",0.15),brightWhite:"#EBDBB2",foreground:"#EBDBB2",background:"#282828",cursorColor:"#EBDBB2",cursorText:"#282828",selectionBackground:"#665C54",selectionForeground:"#EBDBB2"},gruvboxLight={name:"gruvbox-light",dark:!1,black:"#F9F5D7",red:"#CC241D",green:"#98971A",yellow:"#D79921",blue:"#458588",magenta:"#B16286",cyan:"#689D6A",white:"#665C54",brightBlack:"#EBDBB2",brightRed:"#D65D0E",brightGreen:brighten("#98971A",0.15),brightYellow:brighten("#D79921",0.15),brightBlue:brighten("#458588",0.15),brightMagenta:"#B16286",brightCyan:brighten("#689D6A",0.15),brightWhite:"#3C3836",foreground:"#3C3836",background:"#FBF1C7",cursorColor:"#3C3836",cursorText:"#FBF1C7",selectionBackground:"#A89984",selectionForeground:"#3C3836"}});var rosePine,rosePineMoon,rosePineDawn;var init_rose_pine=__esm(()=>{init_color();rosePine={name:"rose-pine",dark:!0,black:"#191724",red:"#EB6F92",green:"#31748F",yellow:"#F6C177",blue:"#3E8FB0",magenta:"#C4A7E7",cyan:"#9CCFD8",white:"#908CAA",brightBlack:"#26233A",brightRed:"#EA9A97",brightGreen:brighten("#31748F",0.15),brightYellow:brighten("#F6C177",0.15),brightBlue:brighten("#3E8FB0",0.15),brightMagenta:"#EBBCBA",brightCyan:brighten("#9CCFD8",0.15),brightWhite:"#E0DEF4",foreground:"#E0DEF4",background:"#1F1D2E",cursorColor:"#E0DEF4",cursorText:"#1F1D2E",selectionBackground:"#6E6A86",selectionForeground:"#E0DEF4"},rosePineMoon={name:"rose-pine-moon",dark:!0,black:"#232136",red:"#EB6F92",green:"#3E8FB0",yellow:"#F6C177",blue:"#3E8FB0",magenta:"#C4A7E7",cyan:"#9CCFD8",white:"#908CAA",brightBlack:"#393552",brightRed:"#EA9A97",brightGreen:brighten("#3E8FB0",0.15),brightYellow:brighten("#F6C177",0.15),brightBlue:brighten("#3E8FB0",0.15),brightMagenta:"#EA9A97",brightCyan:brighten("#9CCFD8",0.15),brightWhite:"#E0DEF4",foreground:"#E0DEF4",background:"#2A273F",cursorColor:"#E0DEF4",cursorText:"#2A273F",selectionBackground:"#6E6A86",selectionForeground:"#E0DEF4"},rosePineDawn={name:"rose-pine-dawn",dark:!1,black:"#FAF4ED",red:"#B4637A",green:"#286983",yellow:"#EA9D34",blue:"#286983",magenta:"#907AA9",cyan:"#56949F",white:"#797593",brightBlack:"#F2E9E1",brightRed:"#D7827E",brightGreen:brighten("#286983",0.15),brightYellow:brighten("#EA9D34",0.15),brightBlue:brighten("#286983",0.15),brightMagenta:"#D7827E",brightCyan:brighten("#56949F",0.15),brightWhite:"#575279",foreground:"#575279",background:"#FFFAF3",cursorColor:"#575279",cursorText:"#FFFAF3",selectionBackground:"#9893A5",selectionForeground:"#575279"}});var kanagawaWave,kanagawaDragon,kanagawaLotus;var init_kanagawa=__esm(()=>{init_color();kanagawaWave={name:"kanagawa-wave",dark:!0,black:"#16161D",red:"#C34043",green:"#98BB6C",yellow:"#E6C384",blue:"#7E9CD8",magenta:"#957FB8",cyan:"#6A9589",white:"#727169",brightBlack:"#2A2A37",brightRed:"#FFA066",brightGreen:brighten("#98BB6C",0.15),brightYellow:brighten("#E6C384",0.15),brightBlue:brighten("#7E9CD8",0.15),brightMagenta:"#D27E99",brightCyan:brighten("#6A9589",0.15),brightWhite:"#DCD7BA",foreground:"#DCD7BA",background:"#1F1F28",cursorColor:"#DCD7BA",cursorText:"#1F1F28",selectionBackground:"#54546D",selectionForeground:"#DCD7BA"},kanagawaDragon={name:"kanagawa-dragon",dark:!0,black:"#0d0c0c",red:"#c4746e",green:"#87a987",yellow:"#c4b28a",blue:"#8ba4b0",magenta:"#8992a7",cyan:"#8ea4a2",white:"#737c73",brightBlack:"#282727",brightRed:"#b6927b",brightGreen:brighten("#87a987",0.15),brightYellow:brighten("#c4b28a",0.15),brightBlue:brighten("#8ba4b0",0.15),brightMagenta:"#a292a3",brightCyan:brighten("#8ea4a2",0.15),brightWhite:"#c5c9c5",foreground:"#c5c9c5",background:"#181616",cursorColor:"#c5c9c5",cursorText:"#181616",selectionBackground:"#625e5a",selectionForeground:"#c5c9c5"},kanagawaLotus={name:"kanagawa-lotus",dark:!1,black:"#e5ddb0",red:"#c84053",green:"#6f894e",yellow:"#de9800",blue:"#4d699b",magenta:"#624c83",cyan:"#597b75",white:"#716e61",brightBlack:"#dcd5ac",brightRed:"#cc6d00",brightGreen:brighten("#6f894e",0.15),brightYellow:brighten("#de9800",0.15),brightBlue:brighten("#4d699b",0.15),brightMagenta:"#b35b79",brightCyan:brighten("#597b75",0.15),brightWhite:"#545464",foreground:"#545464",background:"#f2ecbc",cursorColor:"#545464",cursorText:"#f2ecbc",selectionBackground:"#8a8980",selectionForeground:"#545464"}});var everforestDark,everforestLight;var init_everforest=__esm(()=>{init_color();everforestDark={name:"everforest-dark",dark:!0,black:"#232a2e",red:"#e67e80",green:"#a7c080",yellow:"#dbbc7f",blue:"#7fbbb3",magenta:"#d699b6",cyan:"#83c092",white:"#859289",brightBlack:"#343f44",brightRed:"#e69875",brightGreen:brighten("#a7c080",0.15),brightYellow:brighten("#dbbc7f",0.15),brightBlue:brighten("#7fbbb3",0.15),brightMagenta:"#e67e80",brightCyan:brighten("#83c092",0.15),brightWhite:"#d3c6aa",foreground:"#d3c6aa",background:"#2d353b",cursorColor:"#d3c6aa",cursorText:"#2d353b",selectionBackground:"#4f585e",selectionForeground:"#d3c6aa"},everforestLight={name:"everforest-light",dark:!1,black:"#efebd4",red:"#f85552",green:"#8da101",yellow:"#dfa000",blue:"#3a94c5",magenta:"#df69ba",cyan:"#35a77c",white:"#939f91",brightBlack:"#f4f0d9",brightRed:"#f57d26",brightGreen:brighten("#8da101",0.15),brightYellow:brighten("#dfa000",0.15),brightBlue:brighten("#3a94c5",0.15),brightMagenta:"#f85552",brightCyan:brighten("#35a77c",0.15),brightWhite:"#5c6a72",foreground:"#5c6a72",background:"#fdf6e3",cursorColor:"#5c6a72",cursorText:"#fdf6e3",selectionBackground:"#e0dcc7",selectionForeground:"#5c6a72"}});var monokai,monokaiPro;var init_monokai=__esm(()=>{init_color();monokai={name:"monokai",dark:!0,black:"#1a1a1a",red:"#F92672",green:"#A6E22E",yellow:"#E6DB74",blue:"#66D9EF",magenta:"#AE81FF",cyan:"#66D9EF",white:"#a59f85",brightBlack:"#3e3d32",brightRed:"#FD971F",brightGreen:brighten("#A6E22E",0.15),brightYellow:brighten("#E6DB74",0.15),brightBlue:brighten("#66D9EF",0.15),brightMagenta:"#F92672",brightCyan:brighten("#66D9EF",0.15),brightWhite:"#F8F8F2",foreground:"#F8F8F2",background:"#272822",cursorColor:"#F8F8F2",cursorText:"#272822",selectionBackground:"#75715E",selectionForeground:"#F8F8F2"},monokaiPro={name:"monokai-pro",dark:!0,black:"#221f22",red:"#ff6188",green:"#a9dc76",yellow:"#ffd866",blue:"#78dce8",magenta:"#ab9df2",cyan:"#78dce8",white:"#939293",brightBlack:"#403e41",brightRed:"#fc9867",brightGreen:brighten("#a9dc76",0.15),brightYellow:brighten("#ffd866",0.15),brightBlue:brighten("#78dce8",0.15),brightMagenta:"#ff6188",brightCyan:brighten("#78dce8",0.15),brightWhite:"#fcfcfa",foreground:"#fcfcfa",background:"#2d2a2e",cursorColor:"#fcfcfa",cursorText:"#2d2a2e",selectionBackground:"#727072",selectionForeground:"#fcfcfa"}});var snazzy;var init_snazzy=__esm(()=>{init_color();snazzy={name:"snazzy",dark:!0,black:"#222430",red:"#ff5c57",green:"#5af78e",yellow:"#f3f99d",blue:"#57c7ff",magenta:"#b267e6",cyan:"#9aedfe",white:"#97979b",brightBlack:"#34353e",brightRed:"#ff9f43",brightGreen:brighten("#5af78e",0.15),brightYellow:brighten("#f3f99d",0.15),brightBlue:brighten("#57c7ff",0.15),brightMagenta:"#ff6ac1",brightCyan:brighten("#9aedfe",0.15),brightWhite:"#eff0eb",foreground:"#eff0eb",background:"#282a36",cursorColor:"#eff0eb",cursorText:"#282a36",selectionBackground:"#686868",selectionForeground:"#eff0eb"}});var materialDark,materialLight;var init_material=__esm(()=>{init_color();materialDark={name:"material-dark",dark:!0,black:"#171717",red:"#ff5370",green:"#c3e88d",yellow:"#ffcb6b",blue:"#82aaff",magenta:"#c792ea",cyan:"#89ddff",white:"#545454",brightBlack:"#2c2c2c",brightRed:"#f78c6c",brightGreen:brighten("#c3e88d",0.15),brightYellow:brighten("#ffcb6b",0.15),brightBlue:brighten("#82aaff",0.15),brightMagenta:"#f07178",brightCyan:brighten("#89ddff",0.15),brightWhite:"#eeffff",foreground:"#eeffff",background:"#212121",cursorColor:"#eeffff",cursorText:"#212121",selectionBackground:"#424242",selectionForeground:"#eeffff"},materialLight={name:"material-light",dark:!1,black:"#ecf0f1",red:"#e53935",green:"#91b859",yellow:"#ffb62c",blue:"#6182b8",magenta:"#7c4dff",cyan:"#39adb5",white:"#90a4ae",brightBlack:"#ebf4f3",brightRed:"#f76d47",brightGreen:brighten("#91b859",0.15),brightYellow:brighten("#ffb62c",0.15),brightBlue:brighten("#6182b8",0.15),brightMagenta:"#ff5370",brightCyan:brighten("#39adb5",0.15),brightWhite:"#546E7A",foreground:"#546E7A",background:"#fafafa",cursorColor:"#546E7A",cursorText:"#fafafa",selectionBackground:"#cfd8dc",selectionForeground:"#546E7A"}});var palenight;var init_palenight=__esm(()=>{init_color();palenight={name:"palenight",dark:!0,black:"#1c1f2b",red:"#f07178",green:"#c3e88d",yellow:"#ffcb6b",blue:"#82aaff",magenta:"#c792ea",cyan:"#89ddff",white:"#676e95",brightBlack:"#343b51",brightRed:"#f78c6c",brightGreen:brighten("#c3e88d",0.15),brightYellow:brighten("#ffcb6b",0.15),brightBlue:brighten("#82aaff",0.15),brightMagenta:"#ff5370",brightCyan:brighten("#89ddff",0.15),brightWhite:"#a6accd",foreground:"#a6accd",background:"#292d3e",cursorColor:"#a6accd",cursorText:"#292d3e",selectionBackground:"#4e5579",selectionForeground:"#a6accd"}});var ayuDark,ayuMirage,ayuLight;var init_ayu=__esm(()=>{init_color();ayuDark={name:"ayu-dark",dark:!0,black:"#05070A",red:"#D95757",green:"#AAD94C",yellow:"#E6B450",blue:"#59C2FF",magenta:"#D2A6FF",cyan:"#95E6CB",white:"#636A72",brightBlack:"#11151C",brightRed:"#F29668",brightGreen:brighten("#AAD94C",0.15),brightYellow:brighten("#E6B450",0.15),brightBlue:brighten("#59C2FF",0.15),brightMagenta:"#F07178",brightCyan:brighten("#95E6CB",0.15),brightWhite:"#BFBDB6",foreground:"#BFBDB6",background:"#0B0E14",cursorColor:"#BFBDB6",cursorText:"#0B0E14",selectionBackground:"#565B66",selectionForeground:"#BFBDB6"},ayuMirage={name:"ayu-mirage",dark:!0,black:"#101521",red:"#FF6666",green:"#D5FF80",yellow:"#FFCC66",blue:"#73D0FF",magenta:"#DFBFFF",cyan:"#95E6CB",white:"#6C7A8B",brightBlack:"#171B24",brightRed:"#F29E74",brightGreen:brighten("#D5FF80",0.15),brightYellow:brighten("#FFCC66",0.15),brightBlue:brighten("#73D0FF",0.15),brightMagenta:"#F28779",brightCyan:brighten("#95E6CB",0.15),brightWhite:"#CCCAC2",foreground:"#CCCAC2",background:"#1F2430",cursorColor:"#CCCAC2",cursorText:"#1F2430",selectionBackground:"#707A8C",selectionForeground:"#CCCAC2"},ayuLight={name:"ayu-light",dark:!1,black:"#E7EAED",red:"#E65050",green:"#86B300",yellow:"#FFAA33",blue:"#399EE6",magenta:"#A37ACC",cyan:"#4CBF99",white:"#ABADB1",brightBlack:"#F3F4F5",brightRed:"#ED9366",brightGreen:brighten("#86B300",0.15),brightYellow:brighten("#FFAA33",0.15),brightBlue:brighten("#399EE6",0.15),brightMagenta:"#F07171",brightCyan:brighten("#4CBF99",0.15),brightWhite:"#5C6166",foreground:"#5C6166",background:"#F8F9FA",cursorColor:"#5C6166",cursorText:"#F8F9FA",selectionBackground:"#8A9199",selectionForeground:"#5C6166"}});var nightfox,dawnfox;var init_nightfox=__esm(()=>{init_color();nightfox={name:"nightfox",dark:!0,black:"#131A24",red:"#C94F6D",green:"#81B29A",yellow:"#DBC074",blue:"#719CD6",magenta:"#9D79D6",cyan:"#63CDCF",white:"#71839B",brightBlack:"#212E3F",brightRed:"#F4A261",brightGreen:brighten("#81B29A",0.15),brightYellow:brighten("#DBC074",0.15),brightBlue:brighten("#719CD6",0.15),brightMagenta:"#D67AD2",brightCyan:brighten("#63CDCF",0.15),brightWhite:"#CDCECF",foreground:"#CDCECF",background:"#192330",cursorColor:"#CDCECF",cursorText:"#192330",selectionBackground:"#39506D",selectionForeground:"#CDCECF"},dawnfox={name:"dawnfox",dark:!1,black:"#EBE5DF",red:"#B4637A",green:"#618774",yellow:"#EA9D34",blue:"#286983",magenta:"#907AA9",cyan:"#56949F",white:"#A8A3B3",brightBlack:"#EBE0DF",brightRed:"#D7827E",brightGreen:brighten("#618774",0.15),brightYellow:brighten("#EA9D34",0.15),brightBlue:brighten("#286983",0.15),brightMagenta:"#D685AF",brightCyan:brighten("#56949F",0.15),brightWhite:"#575279",foreground:"#575279",background:"#FAF4ED",cursorColor:"#575279",cursorText:"#FAF4ED",selectionBackground:"#BDBFC9",selectionForeground:"#575279"}});var horizon;var init_horizon=__esm(()=>{init_color();horizon={name:"horizon",dark:!0,black:"#16161C",red:"#E95678",green:"#29D398",yellow:"#FAC29A",blue:"#26BBD9",magenta:"#B877DB",cyan:"#59E1E3",white:"#6C6F93",brightBlack:"#232530",brightRed:"#FAB795",brightGreen:brighten("#29D398",0.15),brightYellow:brighten("#FAC29A",0.15),brightBlue:brighten("#26BBD9",0.15),brightMagenta:"#EE64AC",brightCyan:brighten("#59E1E3",0.15),brightWhite:"#D5D8DA",foreground:"#D5D8DA",background:"#1C1E26",cursorColor:"#D5D8DA",cursorText:"#1C1E26",selectionBackground:"#2E303E",selectionForeground:"#D5D8DA"}});var moonfly;var init_moonfly=__esm(()=>{init_color();moonfly={name:"moonfly",dark:!0,black:"#121212",red:"#FF5D5D",green:"#8CC85F",yellow:"#E3C78A",blue:"#80A0FF",magenta:"#AE81FF",cyan:"#79DAC8",white:"#808080",brightBlack:"#1C1C1C",brightRed:"#DE935F",brightGreen:brighten("#8CC85F",0.15),brightYellow:brighten("#E3C78A",0.15),brightBlue:brighten("#80A0FF",0.15),brightMagenta:"#FF5189",brightCyan:brighten("#79DAC8",0.15),brightWhite:"#C6C6C6",foreground:"#C6C6C6",background:"#080808",cursorColor:"#C6C6C6",cursorText:"#080808",selectionBackground:"#323437",selectionForeground:"#C6C6C6"}});var nightfly;var init_nightfly=__esm(()=>{init_color();nightfly={name:"nightfly",dark:!0,black:"#081E2F",red:"#FC514E",green:"#A1CD5E",yellow:"#E3D18A",blue:"#82AAFF",magenta:"#C792EA",cyan:"#7FDBCA",white:"#7C8F8F",brightBlack:"#0E293F",brightRed:"#F78C6C",brightGreen:brighten("#A1CD5E",0.15),brightYellow:brighten("#E3D18A",0.15),brightBlue:brighten("#82AAFF",0.15),brightMagenta:"#FF5874",brightCyan:brighten("#7FDBCA",0.15),brightWhite:"#C3CCDC",foreground:"#C3CCDC",background:"#011627",cursorColor:"#C3CCDC",cursorText:"#011627",selectionBackground:"#2C3043",selectionForeground:"#C3CCDC"}});var oxocarbonDark,oxocarbonLight;var init_oxocarbon=__esm(()=>{init_color();oxocarbonDark={name:"oxocarbon-dark",dark:!0,black:"#131313",red:"#EE5396",green:"#42BE65",yellow:"#82CFFF",blue:"#78A9FF",magenta:"#BE95FF",cyan:"#08BDBA",white:"#5C5C5C",brightBlack:"#2A2A2A",brightRed:"#FF7EB6",brightGreen:brighten("#42BE65",0.15),brightYellow:brighten("#82CFFF",0.15),brightBlue:brighten("#78A9FF",0.15),brightMagenta:"#FF7EB6",brightCyan:brighten("#08BDBA",0.15),brightWhite:"#F3F3F3",foreground:"#F3F3F3",background:"#161616",cursorColor:"#F3F3F3",cursorText:"#161616",selectionBackground:"#404040",selectionForeground:"#F3F3F3"},oxocarbonLight={name:"oxocarbon-light",dark:!1,black:"#F3F3F3",red:"#EE5396",green:"#42BE65",yellow:"#FFAB91",blue:"#0F62FE",magenta:"#BE95FF",cyan:"#08BDBA",white:"#90A4AE",brightBlack:"#D5D5D5",brightRed:"#FF6F00",brightGreen:brighten("#42BE65",0.15),brightYellow:brighten("#FFAB91",0.15),brightBlue:brighten("#0F62FE",0.15),brightMagenta:"#FF7EB6",brightCyan:brighten("#08BDBA",0.15),brightWhite:"#37474F",foreground:"#37474F",background:"#FFFFFF",cursorColor:"#37474F",cursorText:"#FFFFFF",selectionBackground:"#525252",selectionForeground:"#37474F"}});var sonokai;var init_sonokai=__esm(()=>{init_color();sonokai={name:"sonokai",dark:!0,black:"#181819",red:"#FC5D7C",green:"#9ED072",yellow:"#E7C664",blue:"#76CCE0",magenta:"#B39DF3",cyan:"#76CCE0",white:"#7F8490",brightBlack:"#33353F",brightRed:"#F39660",brightGreen:brighten("#9ED072",0.15),brightYellow:brighten("#E7C664",0.15),brightBlue:brighten("#76CCE0",0.15),brightMagenta:"#FC5D7C",brightCyan:brighten("#76CCE0",0.15),brightWhite:"#E2E2E3",foreground:"#E2E2E3",background:"#2C2E34",cursorColor:"#E2E2E3",cursorText:"#2C2E34",selectionBackground:"#414550",selectionForeground:"#E2E2E3"}});var edgeDark,edgeLight;var init_edge=__esm(()=>{init_color();edgeDark={name:"edge-dark",dark:!0,black:"#202023",red:"#EC7279",green:"#A0C980",yellow:"#DEB974",blue:"#6CB6EB",magenta:"#D38AEA",cyan:"#5DBBC1",white:"#758094",brightBlack:"#33353F",brightRed:"#DEB974",brightGreen:brighten("#A0C980",0.15),brightYellow:brighten("#DEB974",0.15),brightBlue:brighten("#6CB6EB",0.15),brightMagenta:"#EC7279",brightCyan:brighten("#5DBBC1",0.15),brightWhite:"#C5CDD9",foreground:"#C5CDD9",background:"#2C2E34",cursorColor:"#C5CDD9",cursorText:"#2C2E34",selectionBackground:"#414550",selectionForeground:"#C5CDD9"},edgeLight={name:"edge-light",dark:!1,black:"#DDE2E7",red:"#D05858",green:"#608E32",yellow:"#BE7E05",blue:"#5079BE",magenta:"#B05CCC",cyan:"#3A8B84",white:"#8790A0",brightBlack:"#EEF1F4",brightRed:"#BE7E05",brightGreen:brighten("#608E32",0.15),brightYellow:brighten("#BE7E05",0.15),brightBlue:brighten("#5079BE",0.15),brightMagenta:"#D05858",brightCyan:brighten("#3A8B84",0.15),brightWhite:"#4B505B",foreground:"#4B505B",background:"#FAFAFA",cursorColor:"#4B505B",cursorText:"#FAFAFA",selectionBackground:"#DDE2E7",selectionForeground:"#4B505B"}});var modusVivendi,modusOperandi;var init_modus=__esm(()=>{init_color();modusVivendi={name:"modus-vivendi",dark:!0,black:"#000000",red:"#FF5F59",green:"#44BC44",yellow:"#D0BC00",blue:"#2FAFFF",magenta:"#B6A0FF",cyan:"#00D3D0",white:"#989898",brightBlack:"#1E1E1E",brightRed:"#FEC43F",brightGreen:brighten("#44BC44",0.15),brightYellow:brighten("#D0BC00",0.15),brightBlue:brighten("#2FAFFF",0.15),brightMagenta:"#FEACD0",brightCyan:brighten("#00D3D0",0.15),brightWhite:"#FFFFFF",foreground:"#FFFFFF",background:"#000000",cursorColor:"#FFFFFF",cursorText:"#000000",selectionBackground:"#535353",selectionForeground:"#FFFFFF"},modusOperandi={name:"modus-operandi",dark:!1,black:"#E0E0E0",red:"#A60000",green:"#006800",yellow:"#6F5500",blue:"#0031A9",magenta:"#531AB6",cyan:"#005E8B",white:"#595959",brightBlack:"#F2F2F2",brightRed:"#884900",brightGreen:brighten("#006800",0.15),brightYellow:brighten("#6F5500",0.15),brightBlue:brighten("#0031A9",0.15),brightMagenta:"#721045",brightCyan:brighten("#005E8B",0.15),brightWhite:"#000000",foreground:"#000000",background:"#FFFFFF",cursorColor:"#000000",cursorText:"#FFFFFF",selectionBackground:"#9F9F9F",selectionForeground:"#000000"}});var init_github=()=>{};var init_cobalt2=()=>{};var init_synthwave=()=>{};var init_tomorrow_night=()=>{};var init_zenburn=()=>{};var init_ubuntu=()=>{};var init_tango=()=>{};var init_cyberpunk=()=>{};var init_vscode=()=>{};var init_one_light=()=>{};var init_night_owl=()=>{};var init_shades_of_purple=()=>{};var init_homebrew=()=>{};var init_neon=()=>{};var init_challenger_deep=()=>{};var init_doom_one=()=>{};var init_mariana=()=>{};var init_darcula=()=>{};var init_espresso=()=>{};var init_iceberg=()=>{};var init_serendipity=()=>{};var init_twilight=()=>{};var init_breeze=()=>{};var init_andromeda=()=>{};var init_relaxed=()=>{};var ansi16DarkTheme2,defaultDarkTheme,defaultLightTheme;var init_palettes=__esm(()=>{init_derive2();init_catppuccin();init_nord();init_dracula();init_solarized();init_tokyo_night();init_one_dark();init_gruvbox();init_rose_pine();init_kanagawa();init_everforest();init_monokai();init_snazzy();init_material();init_palenight();init_ayu();init_nightfox();init_horizon();init_moonfly();init_nightfly();init_oxocarbon();init_sonokai();init_edge();init_modus();init_github();init_cobalt2();init_synthwave();init_tomorrow_night();init_zenburn();init_ubuntu();init_tango();init_cyberpunk();init_vscode();init_one_light();init_night_owl();init_shades_of_purple();init_homebrew();init_neon();init_challenger_deep();init_doom_one();init_mariana();init_darcula();init_espresso();init_iceberg();init_serendipity();init_twilight();init_breeze();init_andromeda();init_relaxed();init_catppuccin();init_nord();init_dracula();init_solarized();init_tokyo_night();init_one_dark();init_gruvbox();init_rose_pine();init_kanagawa();init_everforest();init_monokai();init_snazzy();init_material();init_palenight();init_ayu();init_nightfox();init_horizon();init_moonfly();init_nightfly();init_oxocarbon();init_sonokai();init_edge();init_modus();init_github();init_cobalt2();init_synthwave();init_tomorrow_night();init_zenburn();init_ubuntu();init_tango();init_cyberpunk();init_vscode();init_one_light();init_night_owl();init_shades_of_purple();init_homebrew();init_neon();init_challenger_deep();init_doom_one();init_mariana();init_darcula();init_espresso();init_iceberg();init_serendipity();init_twilight();init_breeze();init_andromeda();init_relaxed();ansi16DarkTheme2={name:"dark-ansi16",bg:"",fg:"whiteBright",muted:"white",mutedbg:"black",surface:"whiteBright",surfacebg:"black",popover:"whiteBright",popoverbg:"black",inverse:"black",inversebg:"whiteBright",cursor:"black",cursorbg:"yellow",selection:"black",selectionbg:"yellow",primary:"yellow",primaryfg:"black",secondary:"white",secondaryfg:"black",accent:"blueBright",accentfg:"black",error:"redBright",errorfg:"black",warning:"yellow",warningfg:"black",success:"greenBright",successfg:"black",info:"cyan",infofg:"black",border:"gray",inputborder:"gray",focusborder:"blueBright",link:"blueBright",disabledfg:"gray",palette:["black","red","green","yellow","blue","magenta","cyan","white","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"]},defaultDarkTheme=deriveTheme(nord),defaultLightTheme=deriveTheme(catppuccinLatte)});function setActiveTheme(theme){_activeTheme=theme}function getActiveTheme(){return _contextStack.length>0?_contextStack[_contextStack.length-1]:_activeTheme}function pushContextTheme(theme){_contextStack.push(theme)}function popContextTheme(){_contextStack.pop()}var _activeTheme,_contextStack;var init_state=__esm(()=>{init_palettes();_activeTheme=ansi16DarkTheme2;_contextStack=[]});var init_resolve=__esm(()=>{init_src2()});init_term_provider();init_ansi2();init_buffer();import React from"react";import{createContext}from"react";var TermContext=createContext(null),NodeContext=createContext(null),StdoutContext=createContext(null),StderrContext=createContext(null),RuntimeContext=createContext(null),CacheBackendContext=createContext("virtual"),FocusManagerContext=createContext(null),CapabilityRegistryContext=createContext(null);var layoutEngine=null;function setLayoutEngine(engine){layoutEngine=engine}function getLayoutEngine(){if(!layoutEngine)throw Error("Layout engine not initialized. Call setLayoutEngine() or initYoga()/initFlexily() first.");return layoutEngine}function isLayoutEngineInitialized(){return layoutEngine!==null}function getConstants(){return getLayoutEngine().constants}async function ensureDefaultLayoutEngine(engineType){if(isLayoutEngineInitialized())return;if((engineType??process.env.SILVERY_ENGINE?.toLowerCase()??"flexily")==="yoga"){let{initYogaEngine:initYogaEngine2}=await Promise.resolve().then(() => exports_yoga_adapter);setLayoutEngine(await initYogaEngine2())}else{let{createFlexilyZeroEngine:createFlexilyZeroEngine2}=await Promise.resolve().then(() => (init_flexily_zero_adapter(),exports_flexily_zero_adapter));setLayoutEngine(createFlexilyZeroEngine2())}}init_unicode();import{createLogger as createLogger9}from"loggily";import{createLogger as createLogger8}from"loggily";var INITIAL_EPOCH=-1,CONTENT_BIT=1,STYLE_PROPS_BIT=2,BG_BIT=4,CHILDREN_BIT=8,SUBTREE_BIT=16,ABS_CHILD_BIT=32,DESC_OVERFLOW_BIT=64,ALL_RECONCILER_BITS=31;var renderEpoch=0;function getRenderEpoch(){return renderEpoch}function advanceRenderEpoch(){renderEpoch++}function isCurrentEpoch(epoch){return epoch===renderEpoch}function isDirty(dirtyBits,dirtyEpoch,bit){return dirtyEpoch===renderEpoch&&(dirtyBits&bit)!==0}function isAnyDirty(dirtyBits,dirtyEpoch){return dirtyEpoch===renderEpoch&&dirtyBits!==0}init_buffer();init_unicode();init_unicode();function collectPlainText(node){if(node.textContent!==void 0)return node.textContent;let result="";for(let i=0;i<node.children.length;i++){let child=node.children[i],childText=collectPlainText(child);if(childText.length>0&&child.props.internal_transform)childText=child.props.internal_transform(childText,i);result+=childText}return result}function collectPlainTextSkipHidden(node){if(node.textContent!==void 0)return node.textContent;let result="";for(let i=0;i<node.children.length;i++){let child=node.children[i];if(child.hidden)continue;let childText=collectPlainTextSkipHidden(child);if(childText.length>0&&child.props.internal_transform)childText=child.props.internal_transform(childText,i);result+=childText}return result}var MAX_FORMAT_ENTRIES=4,PLAIN_TEXT_DIRTY=CONTENT_BIT|CHILDREN_BIT,COLLECTED_TEXT_DIRTY=CONTENT_BIT|CHILDREN_BIT|STYLE_PROPS_BIT|BG_BIT|SUBTREE_BIT,_cacheDisabled=!!process.env.SILVERY_NO_TEXT_CACHE;var textCaches=new WeakMap;function getOrCreate(node){let entry=textCaches.get(node);if(!entry)entry={plainText:null,plainTextLineCount:0,collected:null,collectedMaxDisplayWidth:void 0,formats:[],analysis:null},textCaches.set(node,entry);return entry}function getCachedPlainText(node){if(_cacheDisabled)return null;let entry=textCaches.get(node);if(entry?.plainText==null)return null;if(isDirty(node.dirtyBits,node.dirtyEpoch,PLAIN_TEXT_DIRTY))return entry.plainText=null,null;return{text:entry.plainText,lineCount:entry.plainTextLineCount}}function setCachedPlainText(node,text,lineCount){let entry=getOrCreate(node);entry.plainText=text,entry.plainTextLineCount=lineCount}function getCachedCollectedText(node,maxDisplayWidth){if(_cacheDisabled)return null;let entry=textCaches.get(node);if(!entry?.collected)return null;if(isDirty(node.dirtyBits,node.dirtyEpoch,COLLECTED_TEXT_DIRTY))return entry.collected=null,entry.formats=[],entry.analysis=null,null;if(entry.collectedMaxDisplayWidth!==maxDisplayWidth)return entry.collected=null,entry.formats=[],entry.analysis=null,null;return entry.collected}function setCachedCollectedText(node,result,maxDisplayWidth){let entry=getOrCreate(node);entry.collected=result,entry.collectedMaxDisplayWidth=maxDisplayWidth}function getCachedFormat(node,width,wrap,trim){if(_cacheDisabled)return null;let entry=textCaches.get(node);if(!entry||entry.formats.length===0)return null;for(let i=0;i<entry.formats.length;i++){let f=entry.formats[i];if(f.width===width&&f.wrap===wrap&&f.trim===trim){if(i<entry.formats.length-1)entry.formats.splice(i,1),entry.formats.push(f);return f}}return null}function setCachedFormat(node,width,wrap,trim,lines,lineOffsets,hasLineOffsets){let entry=getOrCreate(node);for(let i=0;i<entry.formats.length;i++){let f=entry.formats[i];if(f.width===width&&f.wrap===wrap&&f.trim===trim){entry.formats[i]={width,wrap,trim,lines,lineOffsets,hasLineOffsets};return}}if(entry.formats.length>=MAX_FORMAT_ENTRIES)entry.formats.shift();entry.formats.push({width,wrap,trim,lines,lineOffsets,hasLineOffsets})}function getCachedAnalysis(node){if(_cacheDisabled)return null;return textCaches.get(node)?.analysis??null}function setCachedAnalysis(node,analysis){let entry=getOrCreate(node);entry.analysis=analysis}init_unicode();function buildTextAnalysis(text,gWidthFn=graphemeWidth){let graphemes=splitGraphemesAnsiAware(text),len=graphemes.length,widths=Array(len),cumWidths=Array(len+1),newlineIndices=[],breakIndices=[];cumWidths[0]=0;let maxWordWidth=0,currentWordWidth=0;for(let i=0;i<len;i++){let g=graphemes[i],w=gWidthFn(g);if(widths[i]=w,cumWidths[i+1]=cumWidths[i]+w,g===`
70
+ `)newlineIndices.push(i),maxWordWidth=Math.max(maxWordWidth,currentWordWidth),currentWordWidth=0;else if(isWordBoundary(g))breakIndices.push(i+1),maxWordWidth=Math.max(maxWordWidth,currentWordWidth),currentWordWidth=0;else if(canBreakAnywhere(g))breakIndices.push(i),maxWordWidth=Math.max(maxWordWidth,currentWordWidth),currentWordWidth=w;else if(w>0)currentWordWidth+=w}return maxWordWidth=Math.max(maxWordWidth,currentWordWidth),{graphemes,widths,cumWidths,totalWidth:cumWidths[len],maxWordWidth,newlineIndices,breakIndices}}function countLinesAtWidth(analysis,width){if(width<=0)return 1/0;let{widths,totalWidth,newlineIndices}=analysis;if(totalWidth<=width&&newlineIndices.length===0)return 1;let lines=1,currentWidth=0,lastBreakWidth=-1,hasBreak=!1,newlineSet=newlineIndices.length>0?new Set(newlineIndices):null,breakSet=analysis.breakIndices.length>0?new Set(analysis.breakIndices):null;for(let i=0;i<widths.length;i++){if(newlineSet?.has(i)){lines++,currentWidth=0,hasBreak=!1,lastBreakWidth=-1;continue}let w=widths[i];if(w===0)continue;if(breakSet?.has(i))lastBreakWidth=currentWidth,hasBreak=!0;if(currentWidth+w>width){if(lines++,hasBreak&&lastBreakWidth>=0)currentWidth=currentWidth-lastBreakWidth+w;else currentWidth=w;hasBreak=!1,lastBreakWidth=-1}else currentWidth+=w}return lines}function shrinkwrapWidth(analysis,maxWidth){if(maxWidth<=0)return 0;let targetLineCount=countLinesAtWidth(analysis,maxWidth);if(targetLineCount<=1)return Math.min(Math.ceil(analysis.totalWidth),maxWidth);let lo=Math.max(1,analysis.maxWordWidth),hi=maxWidth;while(lo<hi){let mid=lo+hi>>1;if(countLinesAtWidth(analysis,mid)<=targetLineCount)hi=mid;else lo=mid+1}return lo}function balancedWidth(analysis,maxWidth){if(maxWidth<=0)return 0;let lineCount=countLinesAtWidth(analysis,maxWidth);if(lineCount<=1)return Math.min(Math.ceil(analysis.totalWidth),maxWidth);let idealWidth=Math.ceil(analysis.totalWidth/lineCount),candidateWidth=Math.max(analysis.maxWordWidth,Math.min(idealWidth,maxWidth));if(countLinesAtWidth(analysis,candidateWidth)>lineCount)return shrinkwrapWidth(analysis,maxWidth);return shrinkwrapWidth(analysis,candidateWidth)}init_unicode();function getPadding(props){return{top:props.paddingTop??props.paddingY??props.padding??0,bottom:props.paddingBottom??props.paddingY??props.padding??0,left:props.paddingLeft??props.paddingX??props.padding??0,right:props.paddingRight??props.paddingX??props.padding??0}}function getBorderSize(props){if(!props.borderStyle||getActiveLineHeight()>1)return{top:0,bottom:0,left:0,right:0};return{top:props.borderTop!==!1?1:0,bottom:props.borderBottom!==!1?1:0,left:props.borderLeft!==!1?1:0,right:props.borderRight!==!1?1:0}}function measurePhase(root,ctx){traverseTree(root,(node)=>{if(!node.layoutNode)return;let props=node.props,isFitContent=props.width==="fit-content"||props.height==="fit-content",isShrinkwrap=props.width==="shrinkwrap";if(isFitContent||isShrinkwrap){let availableWidth,widthIsFixed=typeof props.width==="number";if(props.height==="fit-content"&&widthIsFixed){let padding=getPadding(props);if(availableWidth=props.width-padding.left-padding.right,props.borderStyle){let border=getBorderSize(props);availableWidth-=border.left+border.right}if(availableWidth<1)availableWidth=1}let intrinsicSize=measureIntrinsicSize(node,ctx,availableWidth);if(isShrinkwrap){let shrunkWidth=computeShrinkwrapWidth(node,intrinsicSize.width,ctx);node.layoutNode.setWidth(shrunkWidth)}else if(props.width==="fit-content")node.layoutNode.setWidth(intrinsicSize.width);if(props.height==="fit-content")node.layoutNode.setHeight(intrinsicSize.height)}})}function measureIntrinsicSize(node,ctx,availableWidth){let props=node.props;if(props.display==="none")return{width:0,height:0};if(node.type==="silvery-text"){let textProps=props,cached=getCachedPlainText(node),text;if(cached)text=cached.text;else{text=collectPlainText(node);let lineCount=(text.match(/\n/g)?.length??0)+1;setCachedPlainText(node,text,lineCount)}let transform=textProps.internal_transform,lines;if(availableWidth!==void 0&&availableWidth>0&&isWrapEnabled(textProps.wrap))lines=ctx?ctx.measurer.wrapText(text,availableWidth,!0,!0):wrapText(text,availableWidth,!0,!0);else lines=text.split(`
71
+ `);if(transform)lines=lines.map((line,index)=>transform(line,index));return{width:Math.max(...lines.map((line)=>getTextWidth(line,ctx))),height:lines.length*getActiveLineHeight()}}let isRow=props.flexDirection==="row"||props.flexDirection==="row-reverse",width=0,height=0,childCount=0;for(let child of node.children){let childSize=measureIntrinsicSize(child,ctx,availableWidth);if(childCount++,isRow)width+=childSize.width,height=Math.max(height,childSize.height);else width=Math.max(width,childSize.width),height+=childSize.height}let gap=props.gap??0;if(gap>0&&childCount>1){let totalGap=gap*(childCount-1);if(isRow)width+=totalGap;else height+=totalGap}let padding=getPadding(props);if(width+=padding.left+padding.right,height+=padding.top+padding.bottom,props.borderStyle){let border=getBorderSize(props);width+=border.left+border.right,height+=border.top+border.bottom}return{width,height}}function isWrapEnabled(wrap){return wrap==="wrap"||wrap==="hard"||wrap==="balanced"||wrap===!0||wrap===void 0}function computeShrinkwrapWidth(node,fitContentWidth,ctx){let analysis=getCachedAnalysis(node);if(!analysis){let cached=getCachedPlainText(node),text=cached?cached.text:collectPlainText(node),gWidthFn=ctx?.measurer?.graphemeWidth?.bind(ctx.measurer)??graphemeWidth;if(analysis=buildTextAnalysis(text,gWidthFn),setCachedAnalysis(node,analysis),!cached){let lineCount=(text.match(/\n/g)?.length??0)+1;setCachedPlainText(node,text,lineCount)}}return shrinkwrapWidth(analysis,fitContentWidth)}function traverseTree(node,callback){callback(node);for(let child of node.children)traverseTree(child,callback)}function getTextWidth(text,ctx){if(ctx)return ctx.measurer.displayWidthAnsi(text);return displayWidthAnsi(text)}import{createLogger as createLogger5}from"loggily";var measureStats={calls:0,cacheHits:0,textCollects:0,displayWidthCalls:0,reset(){this.calls=0,this.cacheHits=0,this.textCollects=0,this.displayWidthCalls=0}};function rectEqual(a,b){if(a===b)return!0;if(!a||!b)return!1;return a.x===b.x&&a.y===b.y&&a.width===b.width&&a.height===b.height}var layoutDirtyNodes=new Set,contentDirtyNodes=new Set,styleOnlyDirtyNodes=new Set,scrollDirtyNodes=new Set;function trackLayoutDirty(node){layoutDirtyNodes.add(node)}function trackContentDirty(node){contentDirtyNodes.add(node)}function trackStyleOnlyDirty(node){styleOnlyDirtyNodes.add(node)}function trackScrollDirty(node){scrollDirtyNodes.add(node)}function hasLayoutDirty(){return layoutDirtyNodes.size>0}function hasScrollDirty(){return scrollDirtyNodes.size>0}function clearDirtyTracking(){layoutDirtyNodes.clear(),contentDirtyNodes.clear(),styleOnlyDirtyNodes.clear(),scrollDirtyNodes.clear()}function clearLayoutDirtyTracking(){layoutDirtyNodes.clear()}var log5=createLogger5("silvery:layout");function layoutPhase(root,width,height){let prevLayout=root.boxRect,dimensionsChanged=prevLayout&&(prevLayout.width!==width||prevLayout.height!==height);if(!dimensionsChanged&&!hasLayoutDirty())return;if(clearLayoutDirtyTracking(),root.layoutNode){let nodeCount=countNodes(root);measureStats.reset();let t0=Date.now();root.layoutNode.calculateLayout(width,height);let elapsed=Date.now()-t0;log5.debug?.(`calculateLayout: ${elapsed}ms (${nodeCount} nodes) measure: calls=${measureStats.calls} hits=${measureStats.cacheHits} collects=${measureStats.textCollects} displayWidth=${measureStats.displayWidthCalls}`)}propagateLayout(root,0,0,!dimensionsChanged)}function countNodes(node){let count=1;for(let child of node.children)count+=countNodes(child);return count}function propagateLayout(node,parentX,parentY,incrementalSkip){if(!node.layoutNode){node.prevLayout=node.boxRect;let rect2={x:parentX,y:parentY,width:0,height:0};node.boxRect=rect2,node.layoutDirty=!1;for(let child of node.children)propagateLayout(child,parentX,parentY,incrementalSkip);return}let rect={x:parentX+node.layoutNode.getComputedLeft(),y:parentY+node.layoutNode.getComputedTop(),width:node.layoutNode.getComputedWidth(),height:node.layoutNode.getComputedHeight()};if(incrementalSkip&&node.boxRect&&!node.layoutDirty&&!isDirty(node.dirtyBits,node.dirtyEpoch,SUBTREE_BIT)&&!isDirty(node.dirtyBits,node.dirtyEpoch,CHILDREN_BIT)){if(rect.x===node.boxRect.x&&rect.y===node.boxRect.y&&rect.width===node.boxRect.width&&rect.height===node.boxRect.height)return}node.prevLayout=node.boxRect,node.boxRect=rect,node.layoutDirty=!1;let layoutDidChange=!!(node.prevLayout&&!rectEqual(node.prevLayout,node.boxRect));if(node.layoutChangedThisFrame=layoutDidChange?getRenderEpoch():INITIAL_EPOCH,process?.env?.SILVERY_STRICT&&isCurrentEpoch(node.layoutChangedThisFrame)){if(rectEqual(node.prevLayout,node.boxRect)){let props=node.props;throw Error(`[SILVERY_STRICT] layoutChangedThisFrame=true but prevLayout equals boxRect (node: ${props.id??node.type}, rect: ${JSON.stringify(node.boxRect)})`)}}if(isCurrentEpoch(node.layoutChangedThisFrame)){let epoch=getRenderEpoch(),ancestor=node.parent;while(ancestor&&!isDirty(ancestor.dirtyBits,ancestor.dirtyEpoch,SUBTREE_BIT)){if(ancestor.dirtyEpoch!==epoch)ancestor.dirtyBits=SUBTREE_BIT,ancestor.dirtyEpoch=epoch;else ancestor.dirtyBits|=SUBTREE_BIT;ancestor=ancestor.parent}}for(let child of node.children)propagateLayout(child,rect.x,rect.y,incrementalSkip);if(isDirty(node.dirtyBits,node.dirtyEpoch,SUBTREE_BIT)&&node.children.length>0){let epoch=getRenderEpoch(),absChild=_hasAbsoluteChildMutated(node.children),descOverflow=_hasDescendantOverflowChanged(node,rect),bits=node.dirtyBits;if(absChild)bits|=ABS_CHILD_BIT;else bits&=~ABS_CHILD_BIT;if(descOverflow)bits|=DESC_OVERFLOW_BIT;else bits&=~DESC_OVERFLOW_BIT;node.dirtyBits=bits,node.dirtyEpoch=epoch}else if(node.dirtyEpoch===getRenderEpoch())node.dirtyBits&=~(ABS_CHILD_BIT|DESC_OVERFLOW_BIT)}function _hasAbsoluteChildMutated(children){for(let child of children)if(child.props.position==="absolute"&&(isDirty(child.dirtyBits,child.dirtyEpoch,CHILDREN_BIT)||isCurrentEpoch(child.layoutChangedThisFrame)||_hasChildPositionChanged(child)))return!0;return!1}function _hasChildPositionChanged(node){for(let child of node.children)if(child.boxRect&&child.prevLayout){if(child.boxRect.x!==child.prevLayout.x||child.boxRect.y!==child.prevLayout.y)return!0}return!1}function _hasDescendantOverflowChanged(node,rect){return _checkDescendantOverflow(node.children,rect.x,rect.y,rect.x+rect.width,rect.y+rect.height)}function _checkDescendantOverflow(children,nodeLeft,nodeTop,nodeRight,nodeBottom){for(let child of children){if(child.prevLayout&&isCurrentEpoch(child.layoutChangedThisFrame)){let prev=child.prevLayout;if(prev.x+prev.width>nodeRight||prev.y+prev.height>nodeBottom||prev.x<nodeLeft||prev.y<nodeTop)return!0}if(isDirty(child.dirtyBits,child.dirtyEpoch,SUBTREE_BIT)&&child.children!==void 0){if(_checkDescendantOverflow(child.children,nodeLeft,nodeTop,nodeRight,nodeBottom))return!0}}return!1}function notifyLayoutSubscribers(node){let contentChanged=!rectEqual(node.prevLayout,node.boxRect),screenChanged=!rectEqual(node.prevScrollRect,node.scrollRect),renderChanged=!rectEqual(node.prevScreenRect,node.screenRect);if(contentChanged||screenChanged||renderChanged)for(let subscriber of node.layoutSubscribers)subscriber();for(let child of node.children)notifyLayoutSubscribers(child)}function scrollPhase(root,options={}){let{skipStateUpdates=!1}=options;traverseTree2(root,(node)=>{let props=node.props;if(props.overflow!=="scroll")return;calculateScrollState(node,props,skipStateUpdates)})}function calculateScrollState(node,props,skipStateUpdates){let layout=node.boxRect;if(!layout||!node.layoutNode)return;let border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},padding=getPadding(props),rawViewportHeight=layout.height-border.top-border.bottom-padding.top-padding.bottom,contentHeight=0,childPositions=[];for(let i=0;i<node.children.length;i++){let child=node.children[i];if(!child.layoutNode||!child.boxRect)continue;let childTop=child.boxRect.y-layout.y-border.top-padding.top,childBottom=childTop+child.boxRect.height,childProps=child.props;childPositions.push({child,top:childTop,bottom:childBottom,index:i,isSticky:childProps.position==="sticky",stickyTop:childProps.stickyTop,stickyBottom:childProps.stickyBottom}),contentHeight=Math.max(contentHeight,childBottom)}let viewportHeight=rawViewportHeight,showBorderlessIndicator=props.overflowIndicator===!0&&!props.borderStyle,hasOverflow=contentHeight>rawViewportHeight,indicatorReserve=showBorderlessIndicator&&hasOverflow?1:0,prevOffset=node.scrollState?.offset,scrollOffset=props.scrollOffset??prevOffset??0,scrollTo=props.scrollTo;if(scrollTo!==void 0&&scrollTo>=0&&scrollTo<childPositions.length){let target=childPositions.find((c)=>c.index===scrollTo);if(target){let effectiveHeight=viewportHeight-indicatorReserve,visibleTop2=scrollOffset,visibleBottom2=scrollOffset+effectiveHeight;if(target.top<visibleTop2)scrollOffset=target.top;else if(target.bottom>visibleBottom2)scrollOffset=target.bottom-effectiveHeight}}scrollOffset=Math.max(0,scrollOffset),scrollOffset=Math.min(scrollOffset,Math.max(0,contentHeight-viewportHeight));let visibleTop=scrollOffset,visibleBottom=scrollOffset+viewportHeight-indicatorReserve,firstVisible=-1,lastVisible=-1,hiddenAbove=0,hiddenBelow=0;for(let cp of childPositions){if(cp.isSticky){if(firstVisible===-1)firstVisible=cp.index;lastVisible=Math.max(lastVisible,cp.index);continue}if(cp.top===cp.bottom)continue;if(cp.bottom<=visibleTop)hiddenAbove++;else if(cp.top>=visibleBottom)hiddenBelow++;else if(cp.top<visibleTop){if(firstVisible===-1)firstVisible=cp.index;lastVisible=Math.max(lastVisible,cp.index)}else if(cp.bottom>visibleBottom){if(firstVisible===-1)firstVisible=cp.index;if(lastVisible=cp.index,indicatorReserve>0)hiddenBelow++}else{if(firstVisible===-1)firstVisible=cp.index;lastVisible=cp.index}}let stickyChildren=[];for(let cp of childPositions){if(!cp.isSticky)continue;let childHeight=cp.bottom-cp.top,stickyTop=cp.stickyTop??0,stickyBottom=cp.stickyBottom,naturalRenderY=cp.top-scrollOffset,renderOffset;if(stickyBottom!==void 0){let bottomPinPosition=viewportHeight-stickyBottom-childHeight;renderOffset=Math.min(naturalRenderY,bottomPinPosition)}else if(naturalRenderY>=stickyTop)renderOffset=naturalRenderY;else if(childHeight>viewportHeight)renderOffset=Math.max(viewportHeight-childHeight,naturalRenderY);else renderOffset=stickyTop;if(renderOffset!==naturalRenderY)if(childHeight>viewportHeight)renderOffset=Math.max(viewportHeight-childHeight,renderOffset);else renderOffset=Math.max(0,Math.min(renderOffset,viewportHeight-childHeight));if(renderOffset+childHeight<=0||renderOffset>=viewportHeight)continue;stickyChildren.push({index:cp.index,renderOffset,naturalTop:cp.top,height:childHeight})}if(skipStateUpdates)return;let prevFirstVisible=node.scrollState?.firstVisibleChild??firstVisible,prevLastVisible=node.scrollState?.lastVisibleChild??lastVisible;if(scrollOffset!==prevOffset||firstVisible!==prevFirstVisible||lastVisible!==prevLastVisible){let epoch=getRenderEpoch();if(node.dirtyEpoch!==epoch)node.dirtyBits=SUBTREE_BIT,node.dirtyEpoch=epoch;else node.dirtyBits|=SUBTREE_BIT}node.scrollState={offset:scrollOffset,prevOffset:prevOffset??scrollOffset,contentHeight,viewportHeight,firstVisibleChild:firstVisible,lastVisibleChild:lastVisible,prevFirstVisibleChild:prevFirstVisible,prevLastVisibleChild:prevLastVisible,hiddenAbove,hiddenBelow,stickyChildren:stickyChildren.length>0?stickyChildren:void 0}}function stickyPhase(root){traverseTree2(root,(node)=>{let props=node.props;if(props.overflow==="scroll")return;let hasStickyChildren=!1;for(let child of node.children){let childProps=child.props;if(childProps.position==="sticky"&&childProps.stickyBottom!==void 0){hasStickyChildren=!0;break}}if(!hasStickyChildren){if(node.stickyChildren!==void 0){node.stickyChildren=void 0;let epoch=getRenderEpoch();if(node.dirtyEpoch!==epoch)node.dirtyBits=SUBTREE_BIT,node.dirtyEpoch=epoch;else node.dirtyBits|=SUBTREE_BIT}return}let layout=node.boxRect;if(!layout||!node.layoutNode)return;let border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},padding=getPadding(props),parentContentHeight=layout.height-border.top-border.bottom-padding.top-padding.bottom,newStickyChildren=[];for(let i=0;i<node.children.length;i++){let child=node.children[i],childProps=child.props;if(childProps.position!=="sticky")continue;if(childProps.stickyBottom===void 0)continue;if(!child.boxRect)continue;let naturalY=child.boxRect.y-layout.y-border.top-padding.top,childHeight=child.boxRect.height,stickyBottom=childProps.stickyBottom,bottomPin=parentContentHeight-stickyBottom-childHeight,renderOffset=Math.max(naturalY,bottomPin);newStickyChildren.push({index:i,renderOffset,naturalTop:naturalY,height:childHeight})}let prev=node.stickyChildren,next=newStickyChildren.length>0?newStickyChildren:void 0,changed=!stickyChildrenEqual(prev,next);if(node.stickyChildren=next,changed){let epoch=getRenderEpoch();if(node.dirtyEpoch!==epoch)node.dirtyBits=SUBTREE_BIT,node.dirtyEpoch=epoch;else node.dirtyBits|=SUBTREE_BIT}})}function stickyChildrenEqual(a,b){if(a===b)return!0;if(!a||!b)return!1;if(a.length!==b.length)return!1;for(let i=0;i<a.length;i++){let ai=a[i],bi=b[i];if(ai.index!==bi.index||ai.renderOffset!==bi.renderOffset||ai.naturalTop!==bi.naturalTop||ai.height!==bi.height)return!1}return!0}function traverseTree2(node,callback){callback(node);for(let child of node.children)traverseTree2(child,callback)}function scrollrectPhase(root){propagateScrollRect(root,0)}function scrollrectPhaseSimple(root){propagateScrollRectSimple(root)}function propagateScrollRect(node,ancestorScrollOffset){node.prevScrollRect=node.scrollRect,node.prevScreenRect=node.screenRect;let content=node.boxRect;if(!content){node.scrollRect=null,node.screenRect=null;for(let child of node.children)propagateScrollRect(child,ancestorScrollOffset);return}node.scrollRect={x:content.x,y:content.y-ancestorScrollOffset,width:content.width,height:content.height},node.screenRect=node.scrollRect;let scrollOffset=node.scrollState?.offset??0,childScrollOffset=ancestorScrollOffset+scrollOffset;computeStickyScreenRects(node);for(let child of node.children)propagateScrollRect(child,childScrollOffset)}function computeStickyScreenRects(parent){let stickyList=parent.scrollState?.stickyChildren??parent.stickyChildren;if(!stickyList||stickyList.length===0)return;let parentScrollRect=parent.scrollRect;if(!parentScrollRect)return;let props=parent.props,border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},padding=getPadding(props),contentOriginY=parentScrollRect.y+border.top+padding.top;for(let sticky of stickyList){let child=parent.children[sticky.index];if(!child?.scrollRect)continue;child.screenRect={x:child.scrollRect.x,y:contentOriginY+sticky.renderOffset,width:child.scrollRect.width,height:child.scrollRect.height}}}function propagateScrollRectSimple(node){node.prevScrollRect=node.scrollRect,node.prevScreenRect=node.screenRect;let content=node.boxRect;if(!content){node.scrollRect=null,node.screenRect=null;for(let child of node.children)propagateScrollRectSimple(child);return}node.scrollRect={x:content.x,y:content.y,width:content.width,height:content.height},node.screenRect=node.scrollRect;for(let child of node.children)propagateScrollRectSimple(child)}function detectPipelineFeatures(root){let hasScroll=!1,hasSticky=!1;function scan(node){let props=node.props;if(props.overflow==="scroll")hasScroll=!0;if(props.position==="sticky")hasSticky=!0;if(hasScroll&&hasSticky)return;for(let child of node.children)if(scan(child),hasScroll&&hasSticky)return}return scan(root),{hasScroll,hasSticky}}init_buffer();import{createLogger as createLogger7}from"loggily";init_buffer();init_state();init_resolve();init_unicode();var namedColors={black:0,red:1,green:2,yellow:3,blue:4,magenta:5,cyan:6,white:7,gray:8,grey:8,blackBright:8,redBright:9,greenBright:10,yellowBright:11,blueBright:12,magentaBright:13,cyanBright:14,whiteBright:15};function blendColors(c1,c2,t){return{r:Math.round(c1.r*(1-t)+c2.r*t),g:Math.round(c1.g*(1-t)+c2.g*t),b:Math.round(c1.b*(1-t)+c2.b*t)}}function parseColor(color){if(color==="inherit")return null;if(color==="$default")return DEFAULT_BG;if(color.startsWith("mix(")&&color.endsWith(")")){let inner=color.slice(4,-1),args=[],depth=0,start=0;for(let i=0;i<inner.length;i++)if(inner[i]==="(")depth++;else if(inner[i]===")")depth--;else if(inner[i]===","&&depth===0)args.push(inner.slice(start,i).trim()),start=i+1;if(args.push(inner.slice(start).trim()),args.length===3){let c1=parseColor(args[0]),c2=parseColor(args[1]),amountStr=args[2],t;if(amountStr.endsWith("%"))t=Number.parseFloat(amountStr.slice(0,-1))/100;else t=Number.parseFloat(amountStr);if(c1!==null&&c2!==null&&typeof c1==="object"&&typeof c2==="object"&&!Number.isNaN(t))return blendColors(c1,c2,Math.max(0,Math.min(1,t)));return null}}if(color.startsWith("$")){let resolved=resolveThemeColor(color,getActiveTheme());if(resolved&&resolved!==color)return parseColor(resolved);return null}if(color in namedColors)return namedColors[color];if(color.startsWith("#")){let hex=color.slice(1);if(hex.length===3){let r=Number.parseInt(hex[0]+hex[0],16),g=Number.parseInt(hex[1]+hex[1],16),b=Number.parseInt(hex[2]+hex[2],16);return{r,g,b}}if(hex.length===6){let r=Number.parseInt(hex.slice(0,2),16),g=Number.parseInt(hex.slice(2,4),16),b=Number.parseInt(hex.slice(4,6),16);return{r,g,b}}}let rgbMatch=color.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i);if(rgbMatch)return{r:Number.parseInt(rgbMatch[1],10),g:Number.parseInt(rgbMatch[2],10),b:Number.parseInt(rgbMatch[3],10)};let ansi256Match=color.match(/^ansi256\s*\(\s*(\d+)\s*\)$/i);if(ansi256Match)return Number.parseInt(ansi256Match[1],10);return null}var borders={single:{topLeft:"┌",topRight:"┐",bottomLeft:"└",bottomRight:"┘",horizontal:"─",vertical:"│"},double:{topLeft:"╔",topRight:"╗",bottomLeft:"╚",bottomRight:"╝",horizontal:"═",vertical:"║"},round:{topLeft:"╭",topRight:"╮",bottomLeft:"╰",bottomRight:"╯",horizontal:"─",vertical:"│"},bold:{topLeft:"┏",topRight:"┓",bottomLeft:"┗",bottomRight:"┛",horizontal:"━",vertical:"┃"},singleDouble:{topLeft:"╓",topRight:"╖",bottomLeft:"╙",bottomRight:"╜",horizontal:"─",vertical:"║"},doubleSingle:{topLeft:"╒",topRight:"╕",bottomLeft:"╘",bottomRight:"╛",horizontal:"═",vertical:"│"},classic:{topLeft:"+",topRight:"+",bottomLeft:"+",bottomRight:"+",horizontal:"-",vertical:"|"}};function getBorderChars(style2){if(style2&&typeof style2==="object"){let obj=style2,topHorizontal=obj.top??obj.horizontal??"-",leftVertical=obj.left??obj.vertical??"|";return{topLeft:obj.topLeft??"+",topRight:obj.topRight??"+",bottomLeft:obj.bottomLeft??"+",bottomRight:obj.bottomRight??"+",horizontal:topHorizontal,vertical:leftVertical,bottomHorizontal:obj.bottom&&obj.bottom!==topHorizontal?obj.bottom:void 0,rightVertical:obj.right&&obj.right!==leftVertical?obj.right:void 0}}return borders[style2??"single"]}function getTextStyle(props){let underlineStyle;if(props.underlineStyle!==void 0)underlineStyle=props.underlineStyle;else if(props.underline)underlineStyle="single";return{fg:props.color?parseColor(props.color):null,bg:props.backgroundColor?parseColor(props.backgroundColor):null,underlineColor:props.underlineColor?parseColor(props.underlineColor):null,attrs:{bold:props.bold,dim:props.dim||props.dimColor,italic:props.italic,underline:props.underline||!!underlineStyle,underlineStyle,strikethrough:props.strikethrough,inverse:props.inverse}}}function getTextWidth2(text,ctx){if(ctx)return ctx.measurer.displayWidthAnsi(text);return displayWidthAnsi(text)}init_buffer();init_unicode();import{createLogger as createLogger6}from"loggily";var log6=createLogger6("silvery:content"),bgConflictMode=(()=>{let env=typeof process<"u"?process.env.SILVERY_BG_CONFLICT?.toLowerCase():void 0;if(env==="ignore"||env==="warn"||env==="throw")return env;return"throw"})();function getBgConflictMode(){return bgConflictMode}var warnedBgConflicts=new Set;function formatBgConflictColor(c){if(c===null||c===void 0)return"none";if(typeof c==="number"){if(c&16777216){let r=c>>16&255,g=c>>8&255,b=c&255;return`#${r.toString(16).padStart(2,"0")}${g.toString(16).padStart(2,"0")}${b.toString(16).padStart(2,"0")}`}return{40:"black",41:"red",42:"green",43:"yellow",44:"blue",45:"magenta",46:"cyan",47:"white",100:"brightBlack",101:"brightRed",102:"brightGreen",103:"brightYellow",104:"brightBlue",105:"brightMagenta",106:"brightCyan",107:"brightWhite"}[c]??`palette(${c})`}return`rgb(${c.r},${c.g},${c.b})`}function clearBgConflictWarnings(){warnedBgConflicts.clear()}function styleToAnsi2(style2){let parts=[];if(style2.color){let color=parseColor(style2.color);if(color!==null)if(typeof color==="number")parts.push(`38;5;${color}`);else parts.push(`38;2;${color.r};${color.g};${color.b}`)}if(style2.bold)parts.push("1");if(style2.dim)parts.push("2");if(style2.italic)parts.push("3");if(style2.underlineStyle){let styleMap={single:"4:1",double:"4:2",curly:"4:3",dotted:"4:4",dashed:"4:5"};parts.push(styleMap[style2.underlineStyle]??"4")}else if(style2.underline)parts.push("4");if(style2.underlineColor){let ulColor=parseColor(style2.underlineColor);if(ulColor!==null)if(typeof ulColor==="number")parts.push(`58;5;${ulColor}`);else parts.push(`58;2;${ulColor.r};${ulColor.g};${ulColor.b}`)}if(style2.inverse)parts.push("7");if(style2.strikethrough)parts.push("9");if(parts.length===0)return"";return`\x1B[${parts.join(";")}m`}function mergeStyleContext(parent,childProps){return{color:childProps.color??parent.color,backgroundColor:childProps.backgroundColor??parent.backgroundColor,bold:childProps.bold??parent.bold,dim:childProps.dim??childProps.dimColor??parent.dim,italic:childProps.italic??parent.italic,underline:childProps.underline??childProps.underlineStyle?!0:parent.underline,underlineStyle:childProps.underlineStyle??parent.underlineStyle,underlineColor:childProps.underlineColor??parent.underlineColor,inverse:childProps.inverse??parent.inverse,strikethrough:childProps.strikethrough??parent.strikethrough}}function applyTextStyleAnsi(text,childStyle,parentStyle){if(!text)return text;let childAnsi=styleToAnsi2(childStyle),parentAnsi=styleToAnsi2(parentStyle);if(!childAnsi)return text;return`${childAnsi}${text}\x1B[0m${parentAnsi}`}function collectTextWithBg(node,parentContext={},offset=0,maxDisplayWidth,ctx){if(node.textContent!==void 0){let text=node.textContent;if(maxDisplayWidth!==void 0){if(getTextWidth2(text,ctx)>maxDisplayWidth)text=(ctx?ctx.measurer.sliceByWidth:sliceByWidth)(text,maxDisplayWidth)}let plainLen=getTextWidth2(text,ctx);return{text,bgSegments:[],childSpans:[],plainLen}}let result="",bgSegments=[],childSpans=[],currentOffset=offset,displayWidthCollected=0;for(let i=0;i<node.children.length;i++){let child=node.children[i];if(maxDisplayWidth!==void 0&&displayWidthCollected>=maxDisplayWidth)break;let childBudget=maxDisplayWidth!==void 0?maxDisplayWidth-displayWidthCollected:void 0;if(child.type==="silvery-text"&&child.props&&!child.layoutNode){let childProps=child.props,childContext=mergeStyleContext(parentContext,childProps),childResult=collectTextWithBg(child,childContext,currentOffset,childBudget,ctx),childTransform=childProps.internal_transform;if(childTransform&&childResult.text.length>0)childResult.text=childTransform(childResult.text,i);let styledText=applyTextStyleAnsi(childResult.text,childContext,parentContext);if(result+=styledText,childContext.backgroundColor){let bg=parseColor(childContext.backgroundColor);if(bg!==null){if(childResult.plainLen>0)bgSegments.push({start:currentOffset,end:currentOffset+childResult.plainLen,bg})}}else if(childProps.backgroundColor===""&&childResult.plainLen>0)bgSegments.push({start:currentOffset,end:currentOffset+childResult.plainLen,bg:null});if(childResult.plainLen>0)childSpans.push({node:child,start:currentOffset,end:currentOffset+childResult.plainLen});bgSegments.push(...childResult.bgSegments),childSpans.push(...childResult.childSpans),currentOffset+=childResult.plainLen,displayWidthCollected+=childResult.plainLen}else{let childResult=collectTextWithBg(child,parentContext,currentOffset,childBudget,ctx);result+=childResult.text,bgSegments.push(...childResult.bgSegments),childSpans.push(...childResult.childSpans),currentOffset+=childResult.plainLen,displayWidthCollected+=childResult.plainLen}}return{text:result,bgSegments,childSpans,plainLen:displayWidthCollected}}function applyBgSegmentsToLine(buffer,x,y,lineText,lineCharStart,lineCharEnd,bgSegments,ctx){if(bgSegments.length===0)return;if(y<0||y>=buffer.height)return;let bgCell=createMutableCell(),gWidthFn=ctx?ctx.measurer.graphemeWidth:graphemeWidth;for(let seg of bgSegments){let overlapStart=Math.max(seg.start,lineCharStart),overlapEnd=Math.min(seg.end,lineCharEnd);if(overlapStart>=overlapEnd)continue;let relStart=overlapStart-lineCharStart,relEnd=overlapEnd-lineCharStart,col=x,graphemes=splitGraphemes(hasAnsi(lineText)?stripAnsiForBg(lineText):lineText);for(let grapheme of graphemes){let gWidth=gWidthFn(grapheme);if(gWidth===0)continue;let displayOffset=col-x;if(displayOffset>=relStart&&displayOffset<relEnd){if(buffer.readCellInto(col,y,bgCell),bgCell.bg=seg.bg,buffer.setCell(col,y,bgCell),gWidth===2&&col+1<buffer.width)buffer.readCellInto(col+1,y,bgCell),bgCell.bg=seg.bg,buffer.setCell(col+1,y,bgCell)}if(col+=gWidth,col-x>=relEnd)break}}}function stripAnsiForBg(text){return text.replace(/\x1b\[[0-9;:?]*[A-Za-z]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b[DME78]/g,"").replace(/\x1b\(B/g,"")}function mapLinesToCharOffsets(originalText,formattedLines,ctx){let normalized=(hasAnsi(originalText)?stripAnsiForBg(originalText):originalText).replace(/\t/g," "),result=[],charOffset=0,displayOffset=0;for(let line of formattedLines){let plainLine=hasAnsi(line)?stripAnsiForBg(line):line,lineStart=findLineStart(normalized,plainLine,charOffset);if(lineStart>charOffset){let skipped=normalized.slice(charOffset,lineStart);displayOffset+=getTextWidth2(skipped,ctx)}let lineDisplayWidth=getTextWidth2(plainLine,ctx);result.push({start:displayOffset,end:displayOffset+lineDisplayWidth});let lineLen=Math.min(plainLine.length,normalized.length-lineStart);charOffset=lineStart+lineLen,displayOffset+=lineDisplayWidth}return result}function findLineStart(normalized,plainLine,fromOffset){if(plainLine.length===0){let pos2=fromOffset;while(pos2<normalized.length&&normalized[pos2]===`
69
72
  `)pos2++;return pos2}if(normalized.startsWith(plainLine,fromOffset))return fromOffset;let ELLIPSIS="…",ellipsisIdx=plainLine.indexOf(ELLIPSIS),truncatedPrefix=ellipsisIdx>0?plainLine.slice(0,ellipsisIdx):null;if(truncatedPrefix&&normalized.startsWith(truncatedPrefix,fromOffset))return fromOffset;let pos=fromOffset;while(pos<normalized.length){let ch=normalized[pos];if(ch===`
70
73
  `||ch===" "){pos++;continue}if(normalized.startsWith(plainLine,pos))return pos;if(truncatedPrefix&&normalized.startsWith(truncatedPrefix,pos))return pos;pos++}return fromOffset}function formatTextLines(text,width,wrap,ctx,trim=!0){if(width<=0)return[];let normalizedText=text.replace(/\t/g," "),lines=normalizedText.split(`
71
- `);if(wrap==="clip"){let sliceFn=ctx?ctx.measurer.sliceByWidth:sliceByWidth;return lines.map((line)=>{if(getTextWidth2(line,ctx)<=width)return line;return sliceFn(line,width)})}if(wrap==="hard"){let sliceFn=ctx?ctx.measurer.sliceByWidth:sliceByWidth,out=[];for(let line of lines){if(line===""){out.push("");continue}let remaining=line;while(getTextWidth2(remaining,ctx)>width){let head=sliceFn(remaining,width);if(head.length===0)break;out.push(head),remaining=remaining.slice(head.length)}out.push(remaining)}return out}if(wrap===!1||wrap==="truncate-end"||wrap==="truncate")return lines.map((line)=>truncateText(line,width,"end",ctx));if(wrap==="truncate-start")return lines.map((line)=>truncateText(line,width,"start",ctx));if(wrap==="truncate-middle")return lines.map((line)=>truncateText(line,width,"middle",ctx));if(ctx)return ctx.measurer.wrapText(normalizedText,width,!0,trim);return wrapText(normalizedText,width,!0,trim)}function truncateText(text,width,mode,ctx){if(getTextWidth2(text,ctx)<=width)return text;let ellipsis="…",availableWidth=width-1;if(availableWidth<=0)return width>0?ellipsis:"";let sliceFn=ctx?ctx.measurer.sliceByWidth:sliceByWidth,sliceEndFn=ctx?ctx.measurer.sliceByWidthFromEnd:sliceByWidthFromEnd;if(mode==="end")return sliceFn(text,availableWidth)+ellipsis;if(mode==="start")return ellipsis+sliceEndFn(text,availableWidth);let halfWidth=Math.floor(availableWidth/2),startPart=sliceFn(text,halfWidth),endPart=sliceEndFn(text,availableWidth-halfWidth);return startPart+ellipsis+endPart}function renderTextLine(buffer,x,y,text,baseStyle,maxCol,inheritedBg,ctx){if(hasAnsi(text)){renderAnsiTextLine(buffer,x,y,text,baseStyle,maxCol,inheritedBg,ctx);return}renderGraphemes(buffer,splitGraphemes(text),x,y,baseStyle,maxCol,inheritedBg,ctx)}function renderTextLineReturn(buffer,x,y,text,baseStyle,maxCol,inheritedBg,ctx,minCol){if(hasAnsi(text))return renderAnsiTextLineReturn(buffer,x,y,text,baseStyle,maxCol,inheritedBg,ctx,minCol);return renderGraphemes(buffer,splitGraphemes(text),x,y,baseStyle,maxCol,inheritedBg,ctx,minCol)}function renderGraphemes(buffer,graphemes,startCol,y,style2,maxCol,inheritedBg,ctx,minCol){let col=startCol,rightEdge=maxCol!==void 0?Math.min(maxCol,buffer.width):buffer.width,leftEdge=minCol!==void 0?Math.max(minCol,0):0,gWidthFn=ctx?ctx.measurer.graphemeWidth:graphemeWidth;for(let grapheme of graphemes){if(col>=rightEdge)break;let width=gWidthFn(grapheme);if(width===0)continue;if(col+width<=leftEdge){col+=width;continue}if(col<leftEdge){col=leftEdge;continue}let existingBg=style2.bg!==null?style2.bg:inheritedBg!==void 0?inheritedBg:buffer.getCellBg(col,y);if(width===2&&col+1>=rightEdge){buffer.setCell(col,y,{char:" ",fg:style2.fg,bg:existingBg,underlineColor:style2.underlineColor??null,attrs:style2.attrs,wide:!1,continuation:!1,hyperlink:style2.hyperlink}),col+=1;continue}let outputChar=width===2?ensureEmojiPresentation(grapheme):grapheme;if(buffer.setCell(col,y,{char:outputChar,fg:style2.fg,bg:existingBg,underlineColor:style2.underlineColor??null,attrs:style2.attrs,wide:width===2,continuation:!1,hyperlink:style2.hyperlink}),width===2&&col+1<buffer.width){let existingBg2=style2.bg!==null?style2.bg:inheritedBg!==void 0?inheritedBg:buffer.getCellBg(col+1,y);buffer.setCell(col+1,y,{char:"",fg:style2.fg,bg:existingBg2,underlineColor:style2.underlineColor??null,attrs:style2.attrs,wide:!1,continuation:!0,hyperlink:style2.hyperlink}),col+=2}else col+=width}return col}function renderAnsiTextLine(buffer,x,y,text,baseStyle,maxCol,inheritedBg,ctx){renderAnsiTextLineReturn(buffer,x,y,text,baseStyle,maxCol,inheritedBg,ctx)}function renderAnsiTextLineReturn(buffer,x,y,text,baseStyle,maxCol,inheritedBg,ctx,minCol){let segments=parseAnsiText(text),col=x;for(let segment of segments){let style2=mergeAnsiStyle(baseStyle,segment),effectiveBgConflictMode=ctx?.bgConflictMode??getBgConflictMode();if(effectiveBgConflictMode!=="ignore"&&!segment.bgOverride&&segment.bg!==void 0&&segment.bg!==null){let existingBufBg=col<buffer.width?buffer.getCellBg(col,y):null;if(baseStyle.bg!==null||existingBufBg!==null){let preview=segment.text.slice(0,30),chalkBg=formatBgConflictColor(segment.bg),silveryBg=baseStyle.bg!==null?`Text.bg=${formatBgConflictColor(baseStyle.bg)}`:`bufferBg=${formatBgConflictColor(existingBufBg)}`,textPreview=text.length>80?text.slice(0,80)+"…":text,msg=`[silvery] Background conflict at (${col},${y}): chalk bg=${chalkBg} on silvery ${silveryBg}. Text: "${preview}${segment.text.length>30?"…":""}". Raw ANSI (first 80): ${JSON.stringify(textPreview)}. Chalk bg will override only text characters, causing visual gaps in padding. Use ansi.bgOverride() to suppress if intentional.`;if(effectiveBgConflictMode==="throw")throw Error(msg);let effectiveWarnedBgConflicts=ctx?.warnedBgConflicts??warnedBgConflicts,key=`${JSON.stringify(existingBufBg)}-${segment.bg}-${preview}`;if(!effectiveWarnedBgConflicts.has(key))effectiveWarnedBgConflicts.add(key),log5.warn?.(msg)}}col=renderGraphemes(buffer,splitGraphemes(segment.text),col,y,style2,maxCol,inheritedBg,ctx,minCol)}return col}function mergeStyles(base,overlay,options={}){let{preserveDecorations=!0,preserveEmphasis=!0}=options,baseAttrs=base.attrs??{},overlayAttrs=overlay.attrs??{},attrs={};if(preserveDecorations){let hasBaseUnderline=baseAttrs.underline||baseAttrs.underlineStyle,hasOverlayUnderline=overlayAttrs.underline||overlayAttrs.underlineStyle;if(hasBaseUnderline||hasOverlayUnderline)attrs.underline=!0,attrs.underlineStyle=overlayAttrs.underlineStyle??baseAttrs.underlineStyle??"single";attrs.strikethrough=overlayAttrs.strikethrough||baseAttrs.strikethrough}else attrs.underline=overlayAttrs.underline??baseAttrs.underline,attrs.underlineStyle=overlayAttrs.underlineStyle??baseAttrs.underlineStyle,attrs.strikethrough=overlayAttrs.strikethrough??baseAttrs.strikethrough;if(preserveEmphasis)attrs.bold=overlayAttrs.bold||baseAttrs.bold,attrs.dim=overlayAttrs.dim||baseAttrs.dim,attrs.italic=overlayAttrs.italic||baseAttrs.italic;else attrs.bold=overlayAttrs.bold??baseAttrs.bold,attrs.dim=overlayAttrs.dim??baseAttrs.dim,attrs.italic=overlayAttrs.italic??baseAttrs.italic;return attrs.inverse=overlayAttrs.inverse,attrs.hidden=overlayAttrs.hidden,attrs.blink=overlayAttrs.blink,{fg:overlay.fg??base.fg,bg:overlay.bg??base.bg,underlineColor:overlay.underlineColor??base.underlineColor,attrs}}function mergeAnsiStyle(base,segment,options={}){let{preserveDecorations=!0,preserveEmphasis=!0}=options,fg=base.fg,bg=base.bg,underlineColor2=base.underlineColor??null;if(segment.fg!==void 0&&segment.fg!==null)fg=ansiColorToColor(segment.fg);if(segment.bg!==void 0&&segment.bg!==null)bg=ansiColorToColor(segment.bg);if(segment.underlineColor!==void 0&&segment.underlineColor!==null)underlineColor2=ansiColorToColor(segment.underlineColor);let overlayAttrs={};if(segment.bold!==void 0)overlayAttrs.bold=segment.bold;if(segment.dim!==void 0)overlayAttrs.dim=segment.dim;if(segment.italic!==void 0)overlayAttrs.italic=segment.italic;if(segment.underline!==void 0)overlayAttrs.underline=segment.underline;if(segment.underlineStyle!==void 0)overlayAttrs.underlineStyle=segment.underlineStyle;if(segment.inverse!==void 0)overlayAttrs.inverse=segment.inverse;let merged=mergeStyles(base,{fg,bg,underlineColor:underlineColor2,attrs:overlayAttrs},{preserveDecorations,preserveEmphasis});if(segment.hyperlink)merged.hyperlink=segment.hyperlink;return merged}function ansiColorToColor(code){if(code>=16777216){let r=code>>16&255,g=code>>8&255,b=code&255;return{r,g,b}}if(code<30||code>=38&&code<40||code>=48&&code<90)return code;if(code>=30&&code<=37)return code-30;if(code>=40&&code<=47)return code-40;if(code>=90&&code<=97)return code-90+8;if(code>=100&&code<=107)return code-100+8;return null}function renderText(node,buffer,layout,props,nodeState,inheritedBg,inheritedFg,ctx){let{scrollOffset,clipBounds}=nodeState,{x,width,height}=layout,{y}=layout;if(y-=scrollOffset,props.backgroundColor==="")inheritedBg=null;if(clipBounds){if(y+height<=clipBounds.top||y>=clipBounds.bottom)return;if(clipBounds.left!==void 0&&clipBounds.right!==void 0){if(x+width<=clipBounds.left||x>=clipBounds.right)return}}let maxDisplayWidth;if((props.wrap===!1||props.wrap==="truncate-end"||props.wrap==="truncate"||props.wrap==="clip")&&width>0){let lineCount=(collectPlainText(node).match(/\n/g)?.length??0)+1;maxDisplayWidth=(width+1)*lineCount}let{text,bgSegments,childSpans}=collectTextWithBg(node,{},0,maxDisplayWidth,ctx),style2=getTextStyle(props);if(style2.fg===null&&inheritedFg!==void 0)style2.fg=inheritedFg;let hasBg=style2.bg!==null||bgSegments.length>0||inheritedBg!==void 0&&inheritedBg!==null,lines=formatTextLines(text,width,props.wrap,ctx,!hasBg),internalTransform=props.internal_transform;if(internalTransform)lines=lines.map((line,index)=>internalTransform(line,index));let lineOffsets=bgSegments.length>0||childSpans.length>0?mapLinesToCharOffsets(text,lines,ctx):[];for(let lineIdx=0;lineIdx<lines.length&&lineIdx<height;lineIdx++){let lineY=y+lineIdx;if(clipBounds&&(lineY<clipBounds.top||lineY>=clipBounds.bottom))continue;let line=lines[lineIdx],layoutRight=internalTransform?buffer.width:x+width,maxCol=clipBounds&&"right"in clipBounds&&clipBounds.right!==void 0?Math.min(layoutRight,clipBounds.right):layoutRight,minCol=clipBounds&&"left"in clipBounds&&clipBounds.left!==void 0?clipBounds.left:void 0,endCol=renderTextLineReturn(buffer,x,lineY,line,style2,maxCol,inheritedBg,ctx,minCol),clearStart=minCol!==void 0?Math.max(endCol,minCol):endCol;if(clearStart<maxCol){let clearBg=inheritedBg??null;for(let cx=clearStart;cx<maxCol&&cx<buffer.width;cx++)buffer.setCell(cx,lineY,{char:" ",fg:style2.fg,bg:clearBg,underlineColor:null,attrs:{bold:!1,dim:!1,italic:!1,underline:!1,inverse:!1,strikethrough:!1,blink:!1,hidden:!1},wide:!1,continuation:!1})}if(bgSegments.length>0&&lineIdx<lineOffsets.length){let{start,end}=lineOffsets[lineIdx];applyBgSegmentsToLine(buffer,x,lineY,line,start,end,bgSegments,ctx)}}if(childSpans.length>0&&lineOffsets.length>0)computeInlineRects(childSpans,lineOffsets,x,y,lines.length,height)}function computeInlineRects(childSpans,lineOffsets,parentX,parentY,lineCount,maxHeight){for(let span of childSpans){let rects=[];for(let lineIdx=0;lineIdx<lineCount&&lineIdx<maxHeight;lineIdx++){let lineOffset=lineOffsets[lineIdx];if(!lineOffset)continue;let overlapStart=Math.max(span.start,lineOffset.start),overlapEnd=Math.min(span.end,lineOffset.end);if(overlapStart>=overlapEnd)continue;let rectX=parentX+(overlapStart-lineOffset.start),rectY=parentY+lineIdx,rectWidth=overlapEnd-overlapStart;rects.push({x:rectX,y:rectY,width:rectWidth,height:1})}span.node.inlineRects=rects.length>0?rects:null}}function getEffectiveBg(props){if(props.backgroundColor)return props.backgroundColor;if(props.theme)return props.theme.bg;return}function renderBox(_node,buffer,layout,props,nodeState,skipBgFill=!1,inheritedBg){let{scrollOffset,clipBounds}=nodeState,{x,width,height}=layout,y=layout.y-scrollOffset;if(clipBounds){if(y+height<=clipBounds.top||y>=clipBounds.bottom)return;if(clipBounds.left!==void 0&&clipBounds.right!==void 0){if(x+width<=clipBounds.left||x>=clipBounds.right)return}}let effectiveBgStr=getEffectiveBg(props);if(effectiveBgStr&&!skipBgFill){let bg=parseColor(effectiveBgStr);if(clipBounds){let clippedY=Math.max(y,clipBounds.top),clippedHeight=Math.min(y+height,clipBounds.bottom)-clippedY,clippedX=x,clippedWidth=width;if(clipBounds.left!==void 0&&clipBounds.right!==void 0)clippedX=Math.max(x,clipBounds.left),clippedWidth=Math.min(x+width,clipBounds.right)-clippedX;if(clippedHeight>0&&clippedWidth>0)buffer.fill(clippedX,clippedY,clippedWidth,clippedHeight,{bg})}else buffer.fill(x,y,width,height,{bg})}if(props.borderStyle)renderBorder(buffer,x,y,width,height,props,clipBounds,inheritedBg)}function renderBorder(buffer,x,y,width,height,props,clipBounds,inheritedBg){let chars=getBorderChars(props.borderStyle??"single"),color=props.borderColor?parseColor(props.borderColor):null,baseBg=props.backgroundColor?parseColor(props.backgroundColor):inheritedBg??null,borderBgStr=props.borderBackgroundColor,borderBgBase=borderBgStr?parseColor(borderBgStr):baseBg,topBorderBgStr=props.borderTopBackgroundColor,bottomBorderBgStr=props.borderBottomBackgroundColor,leftBorderBgStr=props.borderLeftBackgroundColor,rightBorderBgStr=props.borderRightBackgroundColor,topBg=topBorderBgStr?parseColor(topBorderBgStr):borderBgBase,bottomBg=bottomBorderBgStr?parseColor(bottomBorderBgStr):borderBgBase,leftBg=leftBorderBgStr?parseColor(leftBorderBgStr):borderBgBase,rightBg=rightBorderBgStr?parseColor(rightBorderBgStr):borderBgBase,showTop=props.borderTop!==!1,showBottom=props.borderBottom!==!1,showLeft=props.borderLeft!==!1,showRight=props.borderRight!==!1,isRowVisible=(row)=>{if(!clipBounds)return row>=0&&row<buffer.height;return row>=clipBounds.top&&row<clipBounds.bottom&&row<buffer.height},isColVisible=(col)=>{if(clipBounds?.left===void 0||clipBounds.right===void 0)return col>=0&&col<buffer.width;return col>=clipBounds.left&&col<clipBounds.right&&col<buffer.width};if(showTop&&isRowVisible(y)){if(showLeft&&isColVisible(x))buffer.setCell(x,y,{char:chars.topLeft,fg:color,bg:topBg});let hStart=showLeft?x+1:x,hEnd=showRight?x+width-1:x+width;for(let col=hStart;col<hEnd&&col<buffer.width;col++)if(isColVisible(col))buffer.setCell(col,y,{char:chars.horizontal,fg:color,bg:topBg});if(showRight&&x+width-1<buffer.width&&isColVisible(x+width-1))buffer.setCell(x+width-1,y,{char:chars.topRight,fg:color,bg:topBg})}let rightVertical=chars.rightVertical??chars.vertical,sideStart=showTop?y+1:y,sideEnd=showBottom?y+height-1:y+height;for(let row=sideStart;row<sideEnd;row++){if(!isRowVisible(row))continue;if(showLeft&&isColVisible(x))buffer.setCell(x,row,{char:chars.vertical,fg:color,bg:leftBg});if(showRight&&x+width-1<buffer.width&&isColVisible(x+width-1))buffer.setCell(x+width-1,row,{char:rightVertical,fg:color,bg:rightBg})}let bottomHorizontal=chars.bottomHorizontal??chars.horizontal,bottomY=y+height-1;if(showBottom&&isRowVisible(bottomY)){if(showLeft&&isColVisible(x))buffer.setCell(x,bottomY,{char:chars.bottomLeft,fg:color,bg:bottomBg});let bStart=showLeft?x+1:x,bEnd=showRight?x+width-1:x+width;for(let col=bStart;col<bEnd&&col<buffer.width;col++)if(isColVisible(col))buffer.setCell(col,bottomY,{char:bottomHorizontal,fg:color,bg:bottomBg});if(showRight&&x+width-1<buffer.width&&isColVisible(x+width-1))buffer.setCell(x+width-1,bottomY,{char:chars.bottomRight,fg:color,bg:bottomBg})}}function renderOutline(buffer,x,y,width,height,props,clipBounds,inheritedBg){let chars=getBorderChars(props.outlineStyle??"single"),color=props.outlineColor?parseColor(props.outlineColor):null,bg=props.backgroundColor?parseColor(props.backgroundColor):inheritedBg??null,attrs=props.outlineDimColor?{dim:!0}:{},isRowVisible=(row)=>{if(!clipBounds)return row>=0&&row<buffer.height;return row>=clipBounds.top&&row<clipBounds.bottom&&row<buffer.height},isColVisible=(col)=>{if(clipBounds?.left===void 0||clipBounds.right===void 0)return col>=0&&col<buffer.width;return col>=clipBounds.left&&col<clipBounds.right&&col<buffer.width},showTop=props.outlineTop!==!1,showBottom=props.outlineBottom!==!1,showLeft=props.outlineLeft!==!1,showRight=props.outlineRight!==!1;if(showTop&&isRowVisible(y)){if(showLeft&&isColVisible(x))buffer.setCell(x,y,{char:chars.topLeft,fg:color,bg,attrs});for(let col=x+1;col<x+width-1&&col<buffer.width;col++)if(isColVisible(col))buffer.setCell(col,y,{char:chars.horizontal,fg:color,bg,attrs});if(showRight&&x+width-1<buffer.width&&isColVisible(x+width-1))buffer.setCell(x+width-1,y,{char:chars.topRight,fg:color,bg,attrs})}let outlineRightVertical=chars.rightVertical??chars.vertical,sideStart=showTop?y+1:y,sideEnd=showBottom?y+height-1:y+height;for(let row=sideStart;row<sideEnd;row++){if(!isRowVisible(row))continue;if(showLeft&&isColVisible(x))buffer.setCell(x,row,{char:chars.vertical,fg:color,bg,attrs});if(showRight&&x+width-1<buffer.width&&isColVisible(x+width-1))buffer.setCell(x+width-1,row,{char:outlineRightVertical,fg:color,bg,attrs})}let outlineBottomHorizontal=chars.bottomHorizontal??chars.horizontal,bottomY=y+height-1;if(showBottom&&isRowVisible(bottomY)){if(showLeft&&isColVisible(x))buffer.setCell(x,bottomY,{char:chars.bottomLeft,fg:color,bg,attrs});for(let col=x+1;col<x+width-1&&col<buffer.width;col++)if(isColVisible(col))buffer.setCell(col,bottomY,{char:outlineBottomHorizontal,fg:color,bg,attrs});if(showRight&&x+width-1<buffer.width&&isColVisible(x+width-1))buffer.setCell(x+width-1,bottomY,{char:chars.bottomRight,fg:color,bg,attrs})}}function renderScrollIndicators(_node,buffer,layout,props,ss,ctx){let border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},indicatorStyle={fg:15,bg:8,attrs:{}},showBorderless=props.overflowIndicator===!0;if(ss.hiddenAbove>0){let indicator=`▲${ss.hiddenAbove}`;if(border.top>0){let contentWidth=layout.width-border.left-border.right,bar=padCenter(indicator,contentWidth),x=layout.x+border.left,y=layout.y,maxCol=x+contentWidth;renderTextLine(buffer,x,y,bar,indicatorStyle,maxCol,void 0,ctx)}else if(showBorderless){let padding=getPadding(props),contentWidth=layout.width-padding.left-padding.right,bar=padCenter(indicator,contentWidth),x=layout.x+padding.left,y=layout.y+padding.top,maxCol=x+contentWidth;renderTextLine(buffer,x,y,bar,indicatorStyle,maxCol,void 0,ctx)}}if(ss.hiddenBelow>0){let indicator=`▼${ss.hiddenBelow}`;if(border.bottom>0){let contentWidth=layout.width-border.left-border.right,bar=padCenter(indicator,contentWidth),x=layout.x+border.left,y=layout.y+layout.height-1,maxCol=x+contentWidth;renderTextLine(buffer,x,y,bar,indicatorStyle,maxCol,void 0,ctx)}else if(showBorderless){let padding=getPadding(props),contentWidth=layout.width-padding.left-padding.right,bar=padCenter(indicator,contentWidth),x=layout.x+padding.left,y=layout.y+layout.height-padding.bottom-1,maxCol=x+contentWidth;renderTextLine(buffer,x,y,bar,indicatorStyle,maxCol,void 0,ctx)}}}function padCenter(text,width){if(width<=0)return"";if(text.length>width)return text.slice(0,width);if(text.length===width)return text;let leftPad=Math.floor((width-text.length)/2),rightPad=width-text.length-leftPad;return" ".repeat(leftPad)+text+" ".repeat(rightPad)}init_state();function computeCascade(inputs){let{hasPrevBuffer,contentDirty,stylePropsDirty,layoutChanged,subtreeDirty,childrenDirty,childPositionChanged,ancestorLayoutChanged,ancestorCleared,bgDirty,isTextNode,hasBgColor,absoluteChildMutated,descendantOverflowChanged}=inputs,canSkipEntireSubtree=hasPrevBuffer&&!contentDirty&&!stylePropsDirty&&!layoutChanged&&!subtreeDirty&&!childrenDirty&&!childPositionChanged&&!ancestorLayoutChanged,contentAreaAffected=contentDirty||layoutChanged||childPositionChanged||childrenDirty||bgDirty||isTextNode&&stylePropsDirty||absoluteChildMutated||descendantOverflowChanged,bgRefillNeeded=hasPrevBuffer&&!contentAreaAffected&&subtreeDirty&&hasBgColor;return{canSkipEntireSubtree,contentAreaAffected,bgRefillNeeded,contentRegionCleared:(hasPrevBuffer||ancestorCleared)&&contentAreaAffected&&!hasBgColor,skipBgFill:hasPrevBuffer&&!ancestorCleared&&!contentAreaAffected&&!bgRefillNeeded,childrenNeedFreshRender:(hasPrevBuffer||ancestorCleared)&&(contentAreaAffected||bgRefillNeeded)}}var contentLog=createLogger6("silvery:content"),traceLog=createLogger6("silvery:content:trace"),cellLog=createLogger6("silvery:content:cell");function renderPhase(root,prevBuffer,ctx){let layout=root.boxRect;if(!layout)throw Error("renderPhase called before layout phase");let instrumentEnabled=ctx?.instrumentEnabled??_instrumentEnabled,stats=ctx?.stats??_renderPhaseStats,nodeTrace=ctx?.nodeTrace??_nodeTrace,nodeTraceEnabled=ctx?.nodeTraceEnabled??_nodeTraceEnabled,hasPrevBuffer=prevBuffer&&prevBuffer.width===layout.width&&prevBuffer.height===layout.height;if(instrumentEnabled)_renderPhaseCallCount++,stats._prevBufferNull=prevBuffer==null?1:0,stats._prevBufferDimMismatch=prevBuffer&&!hasPrevBuffer?1:0,stats._hasPrevBuffer=hasPrevBuffer?1:0,stats._layoutW=layout.width,stats._layoutH=layout.height,stats._prevW=prevBuffer?.width??0,stats._prevH=prevBuffer?.height??0,stats._callCount=_renderPhaseCallCount;let t0=instrumentEnabled?performance.now():0,buffer=hasPrevBuffer?prevBuffer.clone():new TerminalBuffer(layout.width,layout.height),tClone=instrumentEnabled?performance.now()-t0:0;buffer.setSelectableMode(!0);let t1=instrumentEnabled?performance.now():0;renderNodeToBuffer(root,buffer,{scrollOffset:0,clipBounds:void 0,hasPrevBuffer:!!hasPrevBuffer,ancestorCleared:!1,bufferIsCloned:!!hasPrevBuffer,ancestorLayoutChanged:!1},ctx);let tRender=instrumentEnabled?performance.now()-t1:0;if(instrumentEnabled){let snap={clone:tClone,render:tRender,...structuredClone(stats)};globalThis.__silvery_content_detail=snap,(globalThis.__silvery_content_all??=[]).push(snap),contentLog.debug?.(`frame ${snap._callCount}: ${snap.nodesRendered}/${snap.nodesVisited} rendered, ${snap.nodesSkipped} skipped (${tClone.toFixed(1)}ms clone, ${tRender.toFixed(1)}ms render)`);for(let key of Object.keys(stats))stats[key]=0;stats.cascadeMinDepth=999,stats.cascadeNodes="",stats.scrollClearReason="",stats.normalRepaintReason=""}if(nodeTraceEnabled&&nodeTrace.length>0)(globalThis.__silvery_node_trace??=[]).push([...nodeTrace]),traceLog.debug?.(`${nodeTrace.length} nodes traced`),nodeTrace.length=0;return syncPrevLayout(root),buffer}function syncPrevLayout(root){let stack=[root];while(stack.length>0){let node=stack.pop();node.prevLayout=node.boxRect;let children=node.children;for(let i=children.length-1;i>=0;i--)stack.push(children[i])}}function envTruthy(val){return!!val&&val!=="0"&&val!=="false"}var _instrumentEnabled=typeof process<"u"&&(envTruthy(process.env?.SILVERY_STRICT)||envTruthy(process.env?.SILVERY_INSTRUMENT)),_renderPhaseStats={nodesVisited:0,nodesRendered:0,nodesSkipped:0,textNodes:0,boxNodes:0,clearOps:0,noPrevBuffer:0,flagContentDirty:0,flagStylePropsDirty:0,flagLayoutChanged:0,flagSubtreeDirty:0,flagChildrenDirty:0,flagChildPositionChanged:0,flagAncestorLayoutChanged:0,scrollContainerCount:0,scrollViewportCleared:0,scrollClearReason:"",normalChildrenRepaint:0,normalRepaintReason:"",cascadeMinDepth:999,cascadeNodes:"",_prevBufferNull:0,_prevBufferDimMismatch:0,_hasPrevBuffer:0,_layoutW:0,_layoutH:0,_prevW:0,_prevH:0,_callCount:0},_renderPhaseCallCount=0,_nodeTrace=[],_nodeTraceEnabled=typeof process<"u"&&envTruthy(process.env?.SILVERY_STRICT);function _getNodeDepth(node){let depth=0,n=node.parent;while(n)depth++,n=n.parent;return depth}function renderNodeToBuffer(node,buffer,nodeState,ctx){let{scrollOffset,clipBounds,hasPrevBuffer,ancestorCleared,bufferIsCloned,ancestorLayoutChanged=!1}=nodeState,instrumentEnabled=ctx?.instrumentEnabled??_instrumentEnabled,stats=ctx?.stats??_renderPhaseStats,nodeTrace=ctx?.nodeTrace??_nodeTrace,nodeTraceEnabled=ctx?.nodeTraceEnabled??_nodeTraceEnabled;if(instrumentEnabled)stats.nodesVisited++;let layout=node.boxRect;if(!layout)return;if(!node.layoutNode){clearVirtualTextFlags(node);return}if(node.hidden){clearDirtyFlags(node);return}let props=node.props,prevSelectableMode=buffer.getSelectableMode(),userSelect=props.userSelect;if(userSelect==="none")buffer.setSelectableMode(!1);else if(userSelect==="text"||userSelect==="contain")buffer.setSelectableMode(!0);if(props.display==="none"){clearDirtyFlags(node),buffer.setSelectableMode(prevSelectableMode);return}let screenY=layout.y-scrollOffset;if(screenY>=buffer.height||screenY+layout.height<=0){buffer.setSelectableMode(prevSelectableMode);return}let layoutChanged=node.layoutChangedThisFrame,childPositionChanged=!!(hasPrevBuffer&&!layoutChanged&&hasChildPositionChanged(node)),scrollOffsetChanged=!!(node.scrollState&&node.scrollState.offset!==node.scrollState.prevOffset),canSkipEntireSubtree=hasPrevBuffer&&!node.contentDirty&&!node.stylePropsDirty&&!layoutChanged&&!node.subtreeDirty&&!node.childrenDirty&&!childPositionChanged&&!ancestorLayoutChanged&&!scrollOffsetChanged,_nodeId=instrumentEnabled?props.id??"":"",_traceThis=instrumentEnabled&&nodeTraceEnabled&&_nodeId,_cellDbg=globalThis.__silvery_cell_debug,_coversCellNow=_cellDbg&&layout.x<=_cellDbg.x&&layout.x+layout.width>_cellDbg.x&&screenY<=_cellDbg.y&&screenY+layout.height>_cellDbg.y,_coversCellPrev=_cellDbg&&node.prevLayout&&node.prevLayout.x<=_cellDbg.x&&node.prevLayout.x+node.prevLayout.width>_cellDbg.x&&node.prevLayout.y-scrollOffset<=_cellDbg.y&&node.prevLayout.y-scrollOffset+node.prevLayout.height>_cellDbg.y;if(canSkipEntireSubtree){if(_cellDbg&&(_coversCellNow||_coversCellPrev)){let id=props.id??node.type,depth=_getNodeDepth(node),prev=node.prevLayout,msg=`SKIP ${id}@${depth} rect=${layout.x},${screenY} ${layout.width}x${layout.height} prev=${prev?`${prev.x},${prev.y-scrollOffset} ${prev.width}x${prev.height}`:"null"} coversNow=${_coversCellNow} coversPrev=${_coversCellPrev}`;_cellDbg.log.push(msg),cellLog.debug?.(msg)}if(instrumentEnabled){if(stats.nodesSkipped++,_traceThis)nodeTrace.push({id:_nodeId,type:node.type,depth:_getNodeDepth(node),rect:`${layout.x},${layout.y} ${layout.width}x${layout.height}`,prevLayout:node.prevLayout?`${node.prevLayout.x},${node.prevLayout.y} ${node.prevLayout.width}x${node.prevLayout.height}`:"null",hasPrev:hasPrevBuffer,ancestorCleared,flags:"",decision:"SKIPPED",layoutChanged})}clearDirtyFlags(node),buffer.setSelectableMode(prevSelectableMode);return}if(instrumentEnabled){if(stats.nodesRendered++,!hasPrevBuffer)stats.noPrevBuffer++;if(node.contentDirty)stats.flagContentDirty++;if(node.stylePropsDirty)stats.flagStylePropsDirty++;if(layoutChanged)stats.flagLayoutChanged++;if(node.subtreeDirty)stats.flagSubtreeDirty++;if(node.childrenDirty)stats.flagChildrenDirty++;if(childPositionChanged)stats.flagChildPositionChanged++;if(ancestorLayoutChanged)stats.flagAncestorLayoutChanged++}let nodeTheme=props.theme;if(nodeTheme)pushContextTheme(nodeTheme);try{let isScrollContainer=props.overflow==="scroll"&&node.scrollState,{absoluteChildMutated,descendantOverflowChanged}=buildCascadeInputs(node,hasPrevBuffer),cascade=computeCascade({hasPrevBuffer,contentDirty:node.contentDirty,stylePropsDirty:node.stylePropsDirty,layoutChanged,subtreeDirty:node.subtreeDirty,childrenDirty:node.childrenDirty,childPositionChanged,ancestorLayoutChanged,ancestorCleared,bgDirty:node.bgDirty,isTextNode:node.type==="silvery-text",hasBgColor:!!getEffectiveBg(props),absoluteChildMutated,descendantOverflowChanged}),{contentRegionCleared,skipBgFill,childrenNeedFreshRender}=cascade;if(instrumentEnabled||_cellDbg&&(_coversCellNow||_coversCellPrev))traceRenderDecision(node,props,layout,screenY,scrollOffset,hasPrevBuffer,ancestorCleared,layoutChanged,childPositionChanged,cascade,_nodeId,_traceThis,_cellDbg,_coversCellNow,_coversCellPrev,instrumentEnabled,stats,nodeTrace);executeRegionClearing(node,buffer,layout,scrollOffset,clipBounds,bufferIsCloned,layoutChanged,contentRegionCleared,descendantOverflowChanged,instrumentEnabled,stats,nodeState.inheritedBg);let needsOwnRepaint=!hasPrevBuffer||ancestorCleared||ancestorLayoutChanged||cascade.contentAreaAffected||node.stylePropsDirty||cascade.bgRefillNeeded,boxInheritedBg=node.type==="silvery-box"&&!getEffectiveBg(props)?nodeState.inheritedBg?.color??findInheritedBg(node).color:void 0;if(needsOwnRepaint)renderOwnContent(node,buffer,layout,props,nodeState,skipBgFill,instrumentEnabled,stats,ctx);let effectiveBg=getEffectiveBg(props),childInheritedBg=effectiveBg?{color:parseColor(effectiveBg),ancestorRect:node.boxRect}:nodeTheme?{color:parseColor(nodeTheme.bg),ancestorRect:node.boxRect}:nodeState.inheritedBg,childInheritedFg=props.color?parseColor(props.color):nodeTheme?parseColor(nodeTheme.fg):nodeState.inheritedFg,childState={...nodeState,inheritedBg:childInheritedBg,inheritedFg:childInheritedFg};if(isScrollContainer)renderScrollContainerChildren(node,buffer,props,childState,contentRegionCleared,childrenNeedFreshRender,ctx),renderScrollIndicators(node,buffer,layout,props,node.scrollState,ctx);else renderNormalChildren(node,buffer,props,childState,childPositionChanged,contentRegionCleared,childrenNeedFreshRender,ctx);if(node.type==="silvery-box"&&props.outlineStyle){let{x,width,height}=layout,y=layout.y-scrollOffset;renderOutline(buffer,x,y,width,height,props,clipBounds,boxInheritedBg)}clearNodeDirtyFlags(node)}finally{if(nodeTheme)popContextTheme();buffer.setSelectableMode(prevSelectableMode)}}function buildCascadeInputs(node,hasPrevBuffer){if(!hasPrevBuffer||!node.subtreeDirty||node.children===void 0)return{absoluteChildMutated:!1,descendantOverflowChanged:!1};let absoluteChildMutated=node.children.some((child)=>{return child.props.position==="absolute"&&(child.childrenDirty||child.layoutChangedThisFrame||hasChildPositionChanged(child))}),descendantOverflowChanged=hasDescendantOverflowChanged(node);return{absoluteChildMutated,descendantOverflowChanged}}function traceRenderDecision(node,props,layout,screenY,scrollOffset,hasPrevBuffer,ancestorCleared,layoutChanged,childPositionChanged,cascade,_nodeId,_traceThis,_cellDbg,_coversCellNow,_coversCellPrev,instrumentEnabled,stats,nodeTrace){let{contentAreaAffected,contentRegionCleared,skipBgFill,childrenNeedFreshRender}=cascade;if(instrumentEnabled){if(_traceThis){let flagStr=[node.contentDirty&&"C",node.stylePropsDirty&&"P",node.bgDirty&&"B",node.subtreeDirty&&"S",node.childrenDirty&&"Ch",childPositionChanged&&"CP"].filter(Boolean).join(","),childHasPrev_=node.childrenDirty||childPositionChanged||childrenNeedFreshRender?!1:hasPrevBuffer,childAncestorCleared_=contentRegionCleared||ancestorCleared&&!getEffectiveBg(props);nodeTrace.push({id:_nodeId,type:node.type,depth:_getNodeDepth(node),rect:`${layout.x},${layout.y} ${layout.width}x${layout.height}`,prevLayout:node.prevLayout?`${node.prevLayout.x},${node.prevLayout.y} ${node.prevLayout.width}x${node.prevLayout.height}`:"null",hasPrev:hasPrevBuffer,ancestorCleared,flags:flagStr,decision:"RENDER",layoutChanged,contentAreaAffected,contentRegionCleared,childrenNeedFreshRender,childHasPrev:childHasPrev_,childAncestorCleared:childAncestorCleared_,skipBgFill,bgColor:props.backgroundColor})}if(childrenNeedFreshRender&&node.children.length>0){let depth=_getNodeDepth(node);if(depth<stats.cascadeMinDepth)stats.cascadeMinDepth=depth;let id=node.props.id??node.type,flags=[node.contentDirty&&"C",node.stylePropsDirty&&"P",node.childrenDirty&&"Ch",layoutChanged&&"L",childPositionChanged&&"CP"].filter(Boolean).join(""),entry=`${id}@${depth}[${flags}:${node.children.length}ch]`;stats.cascadeNodes+=(stats.cascadeNodes?" ":"")+entry}}if(_cellDbg&&(_coversCellNow||_coversCellPrev)){let id=props.id??node.type,depth=_getNodeDepth(node),prev=node.prevLayout,flags=[node.contentDirty&&"C",node.stylePropsDirty&&"P",layoutChanged&&"L",node.subtreeDirty&&"S",node.childrenDirty&&"Ch",childPositionChanged&&"CP",node.bgDirty&&"B"].filter(Boolean).join(","),msg=`RENDER ${id}@${depth} rect=${layout.x},${screenY} ${layout.width}x${layout.height} prev=${prev?`${prev.x},${prev.y-scrollOffset} ${prev.width}x${prev.height}`:"null"} flags=[${flags}] hasPrev=${hasPrevBuffer} ancClr=${ancestorCleared} caa=${contentAreaAffected} prc=${contentRegionCleared} prm=${childrenNeedFreshRender} coversNow=${_coversCellNow} coversPrev=${_coversCellPrev} bg=${props.backgroundColor??"none"}`;_cellDbg.log.push(msg),cellLog.debug?.(msg)}}function executeRegionClearing(node,buffer,layout,scrollOffset,clipBounds,bufferIsCloned,layoutChanged,contentRegionCleared,descendantOverflowChanged,instrumentEnabled,stats,threadedInheritedBg){if(contentRegionCleared){if(instrumentEnabled)stats.clearOps++;clearNodeRegion(node,buffer,layout,scrollOffset,clipBounds,layoutChanged,threadedInheritedBg)}else if(bufferIsCloned&&layoutChanged&&node.prevLayout)clearExcessArea(node,buffer,layout,scrollOffset,clipBounds,layoutChanged,threadedInheritedBg);if(descendantOverflowChanged)clearDescendantOverflowRegions(node,buffer,layout,scrollOffset,clipBounds,threadedInheritedBg)}function renderOwnContent(node,buffer,layout,props,nodeState,skipBgFill,instrumentEnabled,stats,ctx){let boxInheritedBg=node.type==="silvery-box"&&!getEffectiveBg(props)?nodeState.inheritedBg?.color??findInheritedBg(node).color:void 0;if(node.type==="silvery-box"){if(instrumentEnabled)stats.boxNodes++;renderBox(node,buffer,layout,props,nodeState,skipBgFill,boxInheritedBg)}else if(node.type==="silvery-text"){if(instrumentEnabled)stats.textNodes++;let textInheritedBg=nodeState.inheritedBg?.color??findInheritedBg(node).color,textInheritedFg=nodeState.inheritedFg??findInheritedFg(node);renderText(node,buffer,layout,props,nodeState,textInheritedBg,textInheritedFg,ctx)}return boxInheritedBg}function planScrollRender(inputs){let{scrollOffsetChanged,visibleRangeChanged,hasStickyChildren,childrenNeedFreshRender,childrenDirty,hasPrevBuffer,ancestorCleared,contentRegionCleared,scrollBg}=inputs,scrollOnly=hasPrevBuffer&&scrollOffsetChanged&&!childrenDirty&&!childrenNeedFreshRender&&!hasStickyChildren&&!visibleRangeChanged,needsViewportClear=hasPrevBuffer&&!scrollOnly&&(scrollOffsetChanged||childrenDirty||childrenNeedFreshRender||visibleRangeChanged),stickyForceRefresh=hasStickyChildren&&hasPrevBuffer&&!needsViewportClear,reasons=[];if(scrollOnly)reasons.push("SHIFT");if(needsViewportClear){if(scrollOffsetChanged)reasons.push("scrollOffset");if(childrenDirty)reasons.push("childrenDirty");if(childrenNeedFreshRender)reasons.push("childrenNeedFreshRender");if(visibleRangeChanged)reasons.push("visibleRangeChanged")}if(stickyForceRefresh)reasons.push("stickyForceRefresh");return{tier:scrollOnly?"shift":needsViewportClear?"clear":"subtree-only",clearBg:scrollOnly||needsViewportClear?scrollBg:null,childHasPrev:needsViewportClear?!1:hasPrevBuffer,childAncestorCleared:needsViewportClear?!0:ancestorCleared||contentRegionCleared,stickyForceRefresh,reasons}}function renderScrollContainerChildren(node,buffer,props,nodeState,contentRegionCleared=!1,childrenNeedFreshRender=!1,ctx){let{clipBounds,hasPrevBuffer,ancestorCleared,bufferIsCloned,ancestorLayoutChanged,inheritedBg,inheritedFg}=nodeState,instrumentEnabled=ctx?.instrumentEnabled??_instrumentEnabled,stats=ctx?.stats??_renderPhaseStats,layout=node.boxRect,ss=node.scrollState;if(!layout||!ss)return;let border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},padding=getPadding(props),childClipBounds=computeChildClipBounds(layout,props,clipBounds,0,!1,!0),scrollOffsetChanged=ss.offset!==ss.prevOffset,hasStickyChildren=!!(ss.stickyChildren&&ss.stickyChildren.length>0),visibleRangeChanged=ss.firstVisibleChild!==ss.prevFirstVisibleChild||ss.lastVisibleChild!==ss.prevLastVisibleChild,clearY=childClipBounds.top,clearHeight=childClipBounds.bottom-childClipBounds.top,contentX=layout.x+border.left+padding.left,contentWidth=layout.width-border.left-border.right-padding.left-padding.right,scrollBg=scrollOffsetChanged||node.childrenDirty||childrenNeedFreshRender||visibleRangeChanged?getEffectiveBg(props)?parseColor(getEffectiveBg(props)):inheritedBg?.color??findInheritedBg(node).color:null,plan=planScrollRender({scrollOffsetChanged,visibleRangeChanged,hasStickyChildren,childrenNeedFreshRender,childrenDirty:node.childrenDirty,hasPrevBuffer,ancestorCleared,contentRegionCleared,scrollBg}),{tier,stickyForceRefresh}=plan,defaultChildHasPrev=plan.childHasPrev,defaultChildAncestorCleared=plan.childAncestorCleared;if(instrumentEnabled){if(stats.scrollContainerCount++,tier!=="subtree-only"||stickyForceRefresh){stats.scrollViewportCleared++;let reasons=[...plan.reasons];if(scrollOffsetChanged)reasons.push(`scrollOffset(${ss.prevOffset}->${ss.offset})`);reasons.push(`vp=${ss.viewportHeight} content=${ss.contentHeight} vis=${ss.firstVisibleChild}-${ss.lastVisibleChild}`),stats.scrollClearReason=reasons.join("+")}}if(process?.env?.SILVERY_STRICT&&tier==="shift"&&hasStickyChildren)throw Error(`[SILVERY_STRICT] Scroll Tier 1 (buffer shift) activated with sticky children (node: ${props.id??node.type}, stickyCount: ${ss.stickyChildren?.length??0})`);let scrollDelta=ss.offset-(ss.prevOffset??ss.offset);if(tier==="shift"&&clearHeight>0){if(props.overflowIndicator===!0&&!border.top&&!border.bottom){let topIndicatorY=clearY,bottomIndicatorY=clearY+clearHeight-1;if(ss.prevOffset!=null&&ss.prevOffset>0)buffer.fill(contentX,topIndicatorY,contentWidth,1,{char:" ",bg:plan.clearBg});buffer.fill(contentX,bottomIndicatorY,contentWidth,1,{char:" ",bg:plan.clearBg})}buffer.scrollRegion(contentX,clearY,contentWidth,clearHeight,scrollDelta,{char:" ",bg:plan.clearBg})}if(tier==="clear"&&clearHeight>0)buffer.fill(contentX,clearY,contentWidth,clearHeight,{char:" ",bg:plan.clearBg});if(stickyForceRefresh&&clearHeight>0)buffer.fill(contentX,clearY,contentWidth,clearHeight,{char:" ",bg:null});let childAncestorLayoutChanged=node.layoutChangedThisFrame||!!ancestorLayoutChanged,prevVisTop=ss.prevOffset??ss.offset,prevVisBottom=prevVisTop+ss.viewportHeight;for(let i=0;i<node.children.length;i++){let child=node.children[i];if(!child)continue;if(child.props.position==="sticky")continue;if(i<ss.firstVisibleChild||i>ss.lastVisibleChild)continue;let thisChildHasPrev=defaultChildHasPrev,thisChildAncestorCleared=defaultChildAncestorCleared;if(tier==="shift"){let childRect=child.boxRect;if(childRect){let childTop=childRect.y-layout.y-border.top-padding.top,childBottom=childTop+childRect.height,wasFullyVisible=childTop>=prevVisTop&&childBottom<=prevVisBottom;thisChildHasPrev=wasFullyVisible,thisChildAncestorCleared=wasFullyVisible?ancestorCleared||contentRegionCleared:!0}}if(stickyForceRefresh&&thisChildHasPrev)thisChildHasPrev=!1,thisChildAncestorCleared=!1;renderNodeToBuffer(child,buffer,{scrollOffset:ss.offset,clipBounds:childClipBounds,hasPrevBuffer:thisChildHasPrev,ancestorCleared:thisChildAncestorCleared,bufferIsCloned,ancestorLayoutChanged:childAncestorLayoutChanged,inheritedBg,inheritedFg},ctx)}if(ss.stickyChildren)for(let sticky of ss.stickyChildren){let child=node.children[sticky.index];if(!child?.boxRect)continue;let stickyScrollOffset=sticky.naturalTop-sticky.renderOffset;renderNodeToBuffer(child,buffer,{scrollOffset:stickyScrollOffset,clipBounds:childClipBounds,hasPrevBuffer:!1,ancestorCleared:!1,bufferIsCloned,ancestorLayoutChanged:childAncestorLayoutChanged,inheritedBg,inheritedFg},ctx)}}function renderNormalChildren(node,buffer,props,nodeState,childPositionChanged=!1,contentRegionCleared=!1,childrenNeedFreshRender=!1,ctx){let{scrollOffset,clipBounds,hasPrevBuffer,ancestorCleared,bufferIsCloned,ancestorLayoutChanged,inheritedBg,inheritedFg}=nodeState,instrumentEnabled=ctx?.instrumentEnabled??_instrumentEnabled,stats=ctx?.stats??_renderPhaseStats,layout=node.boxRect;if(!layout)return;let clipX=(props.overflowX??props.overflow)==="hidden",clipY=(props.overflowY??props.overflow)==="hidden",effectiveClipBounds=clipX||clipY?computeChildClipBounds(layout,props,clipBounds,scrollOffset,clipX,clipY):clipBounds,hasStickyChildren=!!(node.stickyChildren&&node.stickyChildren.length>0),stickyForceRefresh=hasStickyChildren&&hasPrevBuffer;if(stickyForceRefresh){let border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},padding=getPadding(props),clearX=layout.x+border.left+padding.left,clearY=layout.y-scrollOffset+border.top+padding.top,clearW=layout.width-border.left-border.right-padding.left-padding.right,clearH=layout.height-border.top-border.bottom-padding.top-padding.bottom;if(clipBounds){let{top:clipTop,bottom:clipBottom}=clipBounds;if(clearY<clipTop)clearH-=clipTop-clearY,clearY=clipTop;if(clearY+clearH>clipBottom)clearH=clipBottom-clearY;if(clipBounds.left!==void 0&&clearX<clipBounds.left)clearW-=clipBounds.left-clearX,clearX=clipBounds.left;if(clipBounds.right!==void 0&&clearX+clearW>clipBounds.right)clearW=clipBounds.right-clearX}if(clearW>0&&clearH>0)buffer.fill(clearX,clearY,clearW,clearH,{char:" ",bg:null})}let childrenNeedRepaint=node.childrenDirty||childPositionChanged||childrenNeedFreshRender;if(instrumentEnabled&&childrenNeedRepaint&&hasPrevBuffer){stats.normalChildrenRepaint++;let reasons=[];if(node.childrenDirty)reasons.push("childrenDirty");if(childPositionChanged)reasons.push("childPositionChanged");if(childrenNeedFreshRender)reasons.push("childrenNeedFreshRender");stats.normalRepaintReason=reasons.join("+")}let childHasPrev=childrenNeedRepaint?!1:hasPrevBuffer,childAncestorCleared=contentRegionCleared||ancestorCleared&&!getEffectiveBg(props),childAncestorLayoutChanged=node.layoutChangedThisFrame||!!ancestorLayoutChanged;if(stickyForceRefresh)childHasPrev=!1,childAncestorCleared=!1;let hasAbsoluteChildren=!1;for(let child of node.children){let childProps=child.props;if(childProps.position==="absolute"){hasAbsoluteChildren=!0;continue}if(hasStickyChildren&&childProps.position==="sticky")continue;renderNodeToBuffer(child,buffer,{scrollOffset,clipBounds:effectiveClipBounds,hasPrevBuffer:childHasPrev,ancestorCleared:childAncestorCleared,bufferIsCloned,ancestorLayoutChanged:childAncestorLayoutChanged,inheritedBg,inheritedFg},ctx)}if(node.stickyChildren)for(let sticky of node.stickyChildren){let child=node.children[sticky.index];if(!child?.boxRect)continue;let stickyScrollOffset=sticky.naturalTop-sticky.renderOffset;renderNodeToBuffer(child,buffer,{scrollOffset:stickyScrollOffset,clipBounds:effectiveClipBounds,hasPrevBuffer:!1,ancestorCleared:!1,bufferIsCloned,ancestorLayoutChanged:childAncestorLayoutChanged,inheritedBg,inheritedFg},ctx)}if(hasAbsoluteChildren)for(let child of node.children){if(child.props.position!=="absolute")continue;renderNodeToBuffer(child,buffer,{scrollOffset,clipBounds:effectiveClipBounds,hasPrevBuffer:!1,ancestorCleared:!1,bufferIsCloned,ancestorLayoutChanged:childAncestorLayoutChanged,inheritedBg,inheritedFg},ctx)}}function clearNodeDirtyFlags(node){node.contentDirty=!1,node.stylePropsDirty=!1,node.bgDirty=!1,node.subtreeDirty=!1,node.childrenDirty=!1,node.layoutChangedThisFrame=!1}function clearDirtyFlags(node){clearNodeDirtyFlags(node);for(let child of node.children)if(child.layoutNode)clearDirtyFlags(child);else clearVirtualTextFlags(child)}function clearVirtualTextFlags(node){clearNodeDirtyFlags(node);for(let child of node.children)clearVirtualTextFlags(child)}function hasChildPositionChanged(node){for(let child of node.children)if(child.boxRect&&child.prevLayout){if(child.boxRect.x!==child.prevLayout.x||child.boxRect.y!==child.prevLayout.y)return!0}return!1}function hasDescendantOverflowChanged(node){let rect=node.boxRect;return _checkDescendantOverflow(node.children,rect.x,rect.y,rect.x+rect.width,rect.y+rect.height)}function _checkDescendantOverflow(children,nodeLeft,nodeTop,nodeRight,nodeBottom){for(let child of children){if(child.prevLayout&&child.layoutChangedThisFrame){let prev=child.prevLayout;if(prev.x+prev.width>nodeRight||prev.y+prev.height>nodeBottom||prev.x<nodeLeft||prev.y<nodeTop)return!0}if(child.subtreeDirty&&child.children!==void 0){if(_checkDescendantOverflow(child.children,nodeLeft,nodeTop,nodeRight,nodeBottom))return!0}}return!1}function computeChildClipBounds(layout,props,parentClip,scrollOffset=0,horizontal=!0,vertical=!0){let border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},padding=getPadding(props),adjustedY=layout.y-scrollOffset,nodeClip=vertical?{top:adjustedY+border.top+padding.top,bottom:adjustedY+layout.height-border.bottom-padding.bottom}:{top:-1/0,bottom:1/0};if(horizontal)nodeClip.left=layout.x+border.left+padding.left,nodeClip.right=layout.x+layout.width-border.right-padding.right;if(!parentClip)return nodeClip;let result={top:vertical?Math.max(parentClip.top,nodeClip.top):parentClip.top,bottom:vertical?Math.min(parentClip.bottom,nodeClip.bottom):parentClip.bottom};if(horizontal&&nodeClip.left!==void 0&&nodeClip.right!==void 0)result.left=Math.max(parentClip.left??0,nodeClip.left),result.right=Math.min(parentClip.right??1/0,nodeClip.right);else if(parentClip.left!==void 0&&parentClip.right!==void 0)result.left=parentClip.left,result.right=parentClip.right;return result}function findInheritedBg(node){let current=node.parent;while(current){let props=current.props;if(props.backgroundColor)return{color:parseColor(props.backgroundColor),ancestorRect:current.boxRect};if(props.theme){let theme=props.theme;return{color:parseColor(theme.bg),ancestorRect:current.boxRect}}current=current.parent}return{color:null,ancestorRect:null}}function findInheritedFg(node){let current=node.parent;while(current){let props=current.props;if(props.color)return parseColor(props.color);if(props.theme){let theme=props.theme;return parseColor(theme.fg)}current=current.parent}return null}function clearDescendantOverflowRegions(node,buffer,layout,scrollOffset,clipBounds,threadedInheritedBg){let clearBg=(threadedInheritedBg??findInheritedBg(node)).color,nodeRight=layout.x+layout.width,nodeBottom=layout.y-scrollOffset+layout.height,nodeLeft=layout.x,nodeTop=layout.y-scrollOffset;_clearDescendantOverflow(node.children,buffer,nodeLeft,nodeTop,nodeRight,nodeBottom,scrollOffset,clipBounds,clearBg)}function _clearDescendantOverflow(children,buffer,nodeLeft,nodeTop,nodeRight,nodeBottom,scrollOffset,clipBounds,clearBg){for(let child of children){if(child.prevLayout&&child.layoutChangedThisFrame){let prev=child.prevLayout,prevRight=prev.x+prev.width,prevBottom=prev.y-scrollOffset+prev.height,prevTop=prev.y-scrollOffset;if(prevRight>nodeRight){let overflowX=nodeRight,overflowWidth=Math.min(prevRight,buffer.width)-overflowX,overflowTop=Math.max(prevTop,clipBounds?.top??0),overflowBottom=Math.min(prevBottom,clipBounds?.bottom??buffer.height);if(overflowWidth>0&&overflowBottom>overflowTop)buffer.fill(overflowX,overflowTop,overflowWidth,overflowBottom-overflowTop,{char:" ",bg:clearBg})}if(prevBottom>nodeBottom){let overflowTop=Math.max(nodeBottom,clipBounds?.top??0),overflowBottom=Math.min(prevBottom,clipBounds?.bottom??buffer.height),overflowX=Math.max(prev.x,clipBounds?.left??0),overflowWidth=Math.min(prevRight,clipBounds?.right??buffer.width)-overflowX;if(overflowWidth>0&&overflowBottom>overflowTop)buffer.fill(overflowX,overflowTop,overflowWidth,overflowBottom-overflowTop,{char:" ",bg:clearBg})}if(prev.x<nodeLeft){let overflowX=Math.max(prev.x,0),overflowWidth=Math.min(nodeLeft,buffer.width)-overflowX,overflowTop=Math.max(prevTop,clipBounds?.top??0),overflowBottom=Math.min(prevBottom,clipBounds?.bottom??buffer.height);if(overflowWidth>0&&overflowBottom>overflowTop)buffer.fill(overflowX,overflowTop,overflowWidth,overflowBottom-overflowTop,{char:" ",bg:clearBg})}if(prevTop<nodeTop){let overflowTop=Math.max(prevTop,clipBounds?.top??0),overflowBottom=Math.min(nodeTop,clipBounds?.bottom??buffer.height),overflowX=Math.max(prev.x,clipBounds?.left??0),overflowWidth=Math.min(prevRight,clipBounds?.right??buffer.width)-overflowX;if(overflowWidth>0&&overflowBottom>overflowTop)buffer.fill(overflowX,overflowTop,overflowWidth,overflowBottom-overflowTop,{char:" ",bg:clearBg})}}if(child.subtreeDirty&&child.children!==void 0)_clearDescendantOverflow(child.children,buffer,nodeLeft,nodeTop,nodeRight,nodeBottom,scrollOffset,clipBounds,clearBg)}}function clearNodeRegion(node,buffer,layout,scrollOffset,clipBounds,layoutChanged,threadedInheritedBg){let inherited=threadedInheritedBg??findInheritedBg(node),clearBg=inherited.color,screenY=layout.y-scrollOffset,parentRect=node.parent?.boxRect,parentBottom=parentRect?parentRect.y-scrollOffset+parentRect.height:void 0,clearY=clipBounds?Math.max(screenY,clipBounds.top):screenY,clearBottom=clipBounds?Math.min(screenY+layout.height,clipBounds.bottom):screenY+layout.height;if(parentBottom!==void 0)clearBottom=Math.min(clearBottom,parentBottom);let{x:clearX,width:clearWidth}=layout;if(clipBounds?.left!==void 0&&clipBounds.right!==void 0){if(clearX<clipBounds.left)clearWidth-=clipBounds.left-clearX,clearX=clipBounds.left;if(clearX+clearWidth>clipBounds.right)clearWidth=Math.max(0,clipBounds.right-clearX)}if(inherited.ancestorRect){let ancestorRight=inherited.ancestorRect.x+inherited.ancestorRect.width,ancestorLeft=inherited.ancestorRect.x;if(clearX<ancestorLeft)clearWidth-=ancestorLeft-clearX,clearX=ancestorLeft;if(clearX+clearWidth>ancestorRight)clearWidth=Math.max(0,ancestorRight-clearX)}let clearHeight=clearBottom-clearY;if(clearHeight>0&&clearWidth>0){let _cellDbg2=globalThis.__silvery_cell_debug;if(_cellDbg2){if(clearX<=_cellDbg2.x&&clearX+clearWidth>_cellDbg2.x&&clearY<=_cellDbg2.y&&clearY+clearHeight>_cellDbg2.y){let msg=`CLEAR_REGION ${node.props.id??node.type} fill=${clearX},${clearY} ${clearWidth}x${clearHeight} bg=${String(clearBg)} COVERS TARGET`;_cellDbg2.log.push(msg),cellLog.debug?.(msg)}}buffer.fill(clearX,clearY,clearWidth,clearHeight,{char:" ",bg:clearBg})}clearExcessArea(node,buffer,layout,scrollOffset,clipBounds,layoutChanged,inherited)}function clearExcessArea(node,buffer,layout,scrollOffset,clipBounds,layoutChanged,inherited){if(!layoutChanged||!node.prevLayout)return;let prev=node.prevLayout,_cellDbg3=globalThis.__silvery_cell_debug,_prevCoversCell3=_cellDbg3&&prev.x<=_cellDbg3.x&&prev.x+prev.width>_cellDbg3.x&&prev.y-scrollOffset<=_cellDbg3.y&&prev.y-scrollOffset+prev.height>_cellDbg3.y;if(prev.width<=layout.width&&prev.height<=layout.height){if(_cellDbg3&&_prevCoversCell3){let msg=`EXCESS_SKIP_NO_SHRINK ${node.props.id??node.type} prev=${prev.x},${prev.y-scrollOffset} ${prev.width}x${prev.height} now=${layout.x},${layout.y-scrollOffset} ${layout.width}x${layout.height}`;_cellDbg3.log.push(msg),cellLog.debug?.(msg)}return}if(prev.x!==layout.x||prev.y!==layout.y){if(_cellDbg3&&_prevCoversCell3){let msg=`EXCESS_SKIP_MOVED ${node.props.id??node.type} prev=${prev.x},${prev.y-scrollOffset} ${prev.width}x${prev.height} now=${layout.x},${layout.y-scrollOffset} ${layout.width}x${layout.height} (dx=${layout.x-prev.x} dy=${layout.y-prev.y})`;_cellDbg3.log.push(msg),cellLog.debug?.(msg)}return}if(!inherited)inherited=findInheritedBg(node);let clearBg=inherited.color,screenY=layout.y-scrollOffset,prevScreenY=prev.y-scrollOffset,clipRect=inherited.ancestorRect??node.parent?.boxRect;if(!clipRect)return;let clipRectBottom=clipRect.y-scrollOffset+clipRect.height,clipRectRight=clipRect.x+clipRect.width,parent=node.parent;if(parent?.boxRect){let parentProps=parent.props,border=getBorderSize(parentProps),padding=getPadding(parentProps),parentRight=parent.boxRect.x+parent.boxRect.width-border.right-padding.right,parentBottom=parent.boxRect.y-scrollOffset+parent.boxRect.height-border.bottom-padding.bottom;clipRectRight=Math.min(clipRectRight,parentRight),clipRectBottom=Math.min(clipRectBottom,parentBottom)}if(prev.width>layout.width){let excessX=layout.x+layout.width,excessWidth=prev.width-layout.width;if(excessX+excessWidth>clipRectRight)excessWidth=Math.max(0,clipRectRight-excessX);if(excessWidth>0)clippedFill(buffer,excessX,excessWidth,prevScreenY,prevScreenY+prev.height,clipBounds,clipRectBottom,clearBg)}if(prev.height>layout.height){let bottomWidth=prev.width;if(layout.x+bottomWidth>clipRectRight)bottomWidth=Math.max(0,clipRectRight-layout.x);clippedFill(buffer,layout.x,bottomWidth,screenY+layout.height,prevScreenY+prev.height,clipBounds,clipRectBottom,clearBg)}}function clippedFill(buffer,x,width,top,bottom,clipBounds,outerBottom,bg){let clippedTop=clipBounds?Math.max(top,clipBounds.top):top,clippedBottom=Math.min(clipBounds?Math.min(bottom,clipBounds.bottom):bottom,outerBottom),clippedX=x,clippedWidth=width;if(clipBounds?.left!==void 0&&clipBounds.right!==void 0){if(clippedX<clipBounds.left)clippedWidth-=clipBounds.left-clippedX,clippedX=clipBounds.left;if(clippedX+clippedWidth>clipBounds.right)clippedWidth=Math.max(0,clipBounds.right-clippedX)}let height=clippedBottom-clippedTop;if(height>0&&clippedWidth>0)buffer.fill(clippedX,clippedTop,clippedWidth,height,{char:" ",bg})}var log6=createLogger7("silvery:render"),baseLog=createLogger7("@silvery/ag-react");function createAg(root,options){let measurer=options?.measurer,ctx=measurer?{measurer}:void 0,_prevBuffer=null;function doLayout(cols,rows,opts){let __stack6=[];try{const render=__using(__stack6,baseLog.span("pipeline",{width:cols,height:rows}),0);let tMeasure;{let __stack=[];try{const _m=__using(__stack,render.span("measure"),0);let t=performance.now();measurePhase(root,ctx);tMeasure=performance.now()-t;log6.debug?.(`measure: ${tMeasure.toFixed(2)}ms`)}catch(_catch){var _err=_catch,_hasErr=1}finally{__callDispose(__stack,_err,_hasErr)}}let tLayout;{let __stack2=[];try{const _l=__using(__stack2,render.span("layout"),0);let t=performance.now();layoutPhase(root,cols,rows);tLayout=performance.now()-t;log6.debug?.(`layout: ${tLayout.toFixed(2)}ms`)}catch(_catch2){var _err2=_catch2,_hasErr2=1}finally{__callDispose(__stack2,_err2,_hasErr2)}}let tScroll;{let __stack3=[];try{const _s=__using(__stack3,render.span("scroll"),0);let t=performance.now();scrollPhase(root,{skipStateUpdates:opts?.skipScrollStateUpdates});tScroll=performance.now()-t}catch(_catch3){var _err3=_catch3,_hasErr3=1}finally{__callDispose(__stack3,_err3,_hasErr3)}}stickyPhase(root);let tScrollRect;{let __stack4=[];try{const _r=__using(__stack4,render.span("scrollRect"),0);let t=performance.now();scrollrectPhase(root);tScrollRect=performance.now()-t}catch(_catch4){var _err4=_catch4,_hasErr4=1}finally{__callDispose(__stack4,_err4,_hasErr4)}}let tNotify=0;if(!opts?.skipLayoutNotifications){let __stack5=[];try{const _n=__using(__stack5,render.span("notify"),0);let t=performance.now();notifyLayoutSubscribers(root);tNotify=performance.now()-t}catch(_catch5){var _err5=_catch5,_hasErr5=1}finally{__callDispose(__stack5,_err5,_hasErr5)}}let acc=globalThis.__silvery_bench_phases;if(acc)acc.measure+=tMeasure,acc.layout+=tLayout,acc.scroll+=tScroll,acc.scrollRect+=tScrollRect,acc.notify+=tNotify,acc.layoutTotal+=tMeasure+tLayout+tScroll+tScrollRect+tNotify;return{tMeasure,tLayout,tScroll,tScrollRect,tNotify}}catch(_catch6){var _err6=_catch6,_hasErr6=1}finally{__callDispose(__stack6,_err6,_hasErr6)}}function doRender(opts){clearBgConflictWarnings();let prevBuffer=opts?.fresh?null:opts?.prevBuffer!==void 0?opts.prevBuffer:_prevBuffer,tContent,buffer;{let t=performance.now();buffer=renderPhase(root,prevBuffer,ctx),tContent=performance.now()-t,log6.debug?.(`content: ${tContent.toFixed(2)}ms`)}if(!opts?.fresh)_prevBuffer=buffer;clearDirtyTracking();let acc=globalThis.__silvery_bench_phases;if(acc)acc.content+=tContent,acc.renderCalls+=1;return{frame:createTextFrame(buffer),buffer,prevBuffer,tContent}}function agCreateNode(type,props){let layoutNode=getLayoutEngine().createNode();return{type,props,children:[],parent:null,layoutNode,boxRect:null,scrollRect:null,screenRect:null,prevLayout:null,prevScrollRect:null,prevScreenRect:null,layoutChangedThisFrame:!1,layoutDirty:!0,contentDirty:!0,stylePropsDirty:!0,bgDirty:!0,subtreeDirty:!0,childrenDirty:!0,layoutSubscribers:new Set}}function agInsertChild(parent,child,index){if(child.parent)agRemoveChild(child.parent,child);if(parent.children.splice(index,0,child),child.parent=parent,parent.layoutNode&&child.layoutNode){let layoutIndex=parent.children.slice(0,index).filter((c)=>c.layoutNode!==null).length;parent.layoutNode.insertChild(child.layoutNode,layoutIndex)}}function agRemoveChild(parent,child){let index=parent.children.indexOf(child);if(index===-1)return;if(parent.children.splice(index,1),parent.layoutNode&&child.layoutNode)parent.layoutNode.removeChild(child.layoutNode),child.layoutNode.free();child.parent=null}return{root,layout(dims,options2){if(measurer)runWithMeasurer(measurer,()=>doLayout(dims.cols,dims.rows,options2));else doLayout(dims.cols,dims.rows,options2)},render(options2){let result=measurer?runWithMeasurer(measurer,()=>doRender(options2)):doRender(options2);return{frame:result.frame,buffer:result.buffer,prevBuffer:result.prevBuffer}},resetBuffer(){_prevBuffer=null},createNode:agCreateNode,insertChild:agInsertChild,removeChild:agRemoveChild,updateProps(node,props,oldProps){if(node.props=props,node.layoutNode)node.layoutNode.markDirty()},setText(node,text){if(node.textContent=text,node.contentDirty=!0,node.stylePropsDirty=!0,node.layoutNode)node.layoutNode.markDirty()},toString(){return`[Ag root=${root.type} children=${root.children.length}]`}}}init_unicode();init_output_phase();init_output_phase();var log7=createLogger8("silvery:render"),baseLog2=createLogger8("@silvery/ag-react");function executeRender(root,width,height,prevBuffer,options="fullscreen",config){if(config?.measurer)return runWithMeasurer(config.measurer,()=>{return executeRenderCore(root,width,height,prevBuffer,options,config)});return executeRenderCore(root,width,height,prevBuffer,options,config)}function executeRenderCore(root,width,height,prevBuffer,options="fullscreen",config){let opts=typeof options==="string"?{mode:options}:options,{mode="fullscreen",skipLayoutNotifications=!1,skipScrollStateUpdates=!1,scrollbackOffset=0,termRows,cursorPos}=opts;if(process?.env?.SILVERY_DEV&&prevBuffer===null&&root.prevLayout!==null&&!skipLayoutNotifications)log7.warn?.("executeRender called with prevBuffer=null on frame 2+ — "+"incremental content rendering is disabled (full render every frame). Track the returned buffer and pass it as prevBuffer on subsequent renders.");let start=performance.now(),ag=createAg(root,{measurer:config?.measurer});ag.layout({cols:width,rows:height},{skipLayoutNotifications,skipScrollStateUpdates});let{buffer}=ag.render({prevBuffer}),tLayout=performance.now()-start,output,tOutput;{let t4=performance.now(),outputFn=config?.outputPhaseFn??outputPhase;try{output=outputFn(prevBuffer,buffer,mode,scrollbackOffset,termRows,cursorPos)}catch(e){if(e instanceof Error)e.__silvery_buffer=buffer;throw e}tOutput=performance.now()-t4,log7.debug?.(`output: ${tOutput.toFixed(2)}ms (${output.length} bytes)`)}let total=performance.now()-start;globalThis.__silvery_last_pipeline={layout:tLayout,output:tOutput,total,incremental:prevBuffer!==null},globalThis.__silvery_render_count=(globalThis.__silvery_render_count??0)+1;let acc=globalThis.__silvery_bench_phases;if(acc)acc.output+=tOutput,acc.total+=total,acc.pipelineCalls+=1;return log7.debug?.(`pipeline: layout+render=${tLayout.toFixed(1)}ms output=${tOutput.toFixed(1)}ms total=${total.toFixed(1)}ms`),{output,buffer}}import Reconciler from"react-reconciler";import{createContext as createContext2}from"react";import{DefaultEventPriority,DiscreteEventPriority,NoEventPriority}from"react-reconciler/constants.js";var LAYOUT_PROPS=new Set(["width","height","minWidth","minHeight","maxWidth","maxHeight","flexDirection","flexWrap","justifyContent","alignItems","alignContent","alignSelf","flexGrow","flexShrink","flexBasis","padding","paddingX","paddingY","paddingTop","paddingBottom","paddingLeft","paddingRight","margin","marginX","marginY","marginTop","marginBottom","marginLeft","marginRight","gap","columnGap","rowGap","borderStyle","borderTop","borderBottom","borderLeft","borderRight","display","position","top","left","bottom","right","aspectRatio","overflow","overflowX","overflowY"]),TEXT_CONTENT_PROPS=new Set(["wrap","internal_transform"]),STYLE_PROPS=new Set(["color","backgroundColor","bold","dim","dimColor","italic","underline","underlineStyle","underlineColor","strikethrough","inverse","borderColor","borderBackgroundColor","borderTopBackgroundColor","borderBottomBackgroundColor","borderLeftBackgroundColor","borderRightBackgroundColor","borderStyle","outlineStyle","outlineColor","outlineDimColor","outlineTop","outlineBottom","outlineLeft","outlineRight","theme"]),NO_CHANGES={anyChanged:!1,layoutChanged:!1,contentChanged:!1};function classifyPropChanges(oldProps,newProps){if(oldProps===newProps)return NO_CHANGES;let keysA=Object.keys(oldProps),keysB=Object.keys(newProps),sameKeyCount=keysA.length===keysB.length,layoutChanged=!1,contentChanged=!1,anyChanged=!1;for(let key of keysA)if(oldProps[key]!==newProps[key]){if(anyChanged=!0,LAYOUT_PROPS.has(key))layoutChanged=!0;if(contentChanged!=="text"){if(key==="children"){let oldIsPrimitive=typeof oldProps[key]==="string"||typeof oldProps[key]==="number",newIsPrimitive=typeof newProps[key]==="string"||typeof newProps[key]==="number";if(oldIsPrimitive||newIsPrimitive)contentChanged="text"}else if(TEXT_CONTENT_PROPS.has(key))contentChanged="text";else if(contentChanged!=="style"&&STYLE_PROPS.has(key))contentChanged="style"}if(layoutChanged&&contentChanged==="text")break}if(!sameKeyCount){for(let key of keysB)if(!(key in oldProps)){if(anyChanged=!0,LAYOUT_PROPS.has(key))layoutChanged=!0;if(contentChanged!=="text"){if(key==="children"){if(typeof newProps[key]==="string"||typeof newProps[key]==="number")contentChanged="text"}else if(TEXT_CONTENT_PROPS.has(key))contentChanged="text";else if(contentChanged!=="style"&&STYLE_PROPS.has(key))contentChanged="style"}if(layoutChanged&&contentChanged==="text")break}}if(!anyChanged&&!sameKeyCount)anyChanged=!0;if(!anyChanged)return NO_CHANGES;return{anyChanged,layoutChanged,contentChanged}}import{createLogger as createLogger9}from"loggily";init_unicode();var measureLog=createLogger9("silvery:measure");function createNode(type,props,measurer){let layoutNode=getLayoutEngine().createNode(),node={type,props,children:[],parent:null,layoutNode,boxRect:null,scrollRect:null,screenRect:null,prevLayout:null,prevScrollRect:null,prevScreenRect:null,layoutChangedThisFrame:!1,layoutDirty:!0,contentDirty:!0,stylePropsDirty:!0,bgDirty:!0,subtreeDirty:!0,childrenDirty:!0,layoutSubscribers:new Set};if(type==="silvery-box")applyBoxProps(layoutNode,props);if(type==="silvery-text"){let cachedText=null,measureCache=new Map;layoutNode.setMeasureFunc((width,widthMode,height,heightMode)=>{measureStats.calls++,measureLog.debug?.(`measure "${collectPlainTextSkipHidden(node).slice(0,40)}" width=${width} widthMode=${widthMode} height=${height} heightMode=${heightMode}`);let cacheKey=`${width}|${widthMode}|${height}|${heightMode}`,cached=measureCache.get(cacheKey);if(cached&&cachedText!==null&&!node.contentDirty)return measureStats.cacheHits++,cached;let text;if(cachedText!==null&&!node.contentDirty)text=cachedText;else{measureStats.textCollects++;let newText=collectPlainTextSkipHidden(node);if(newText!==cachedText)measureCache.clear();text=newText,cachedText=text,node.contentDirty=!1}if(!text)return{width:0,height:0};let cachedAfterCollect=measureCache.get(cacheKey);if(cachedAfterCollect)return measureStats.cacheHits++,cachedAfterCollect;let lines=text.split(`
72
- `),maxWidth=widthMode==="undefined"||Number.isNaN(width)?Number.POSITIVE_INFINITY:width,{wrap}=node.props,isTruncate=wrap==="truncate"||wrap==="truncate-start"||wrap==="truncate-middle"||wrap==="truncate-end"||wrap==="clip"||wrap===!1,isHardWrap=wrap==="hard",totalHeight=0,actualWidth=0,dw=measurer?measurer.displayWidth.bind(measurer):displayWidth,wt=measurer?measurer.wrapText.bind(measurer):wrapText,lh=getActiveLineHeight();for(let line of lines){measureStats.displayWidthCalls++;let lineWidth=dw(line);if(isTruncate||lineWidth<=maxWidth)totalHeight+=lh,actualWidth=Math.max(actualWidth,isTruncate?Math.min(lineWidth,maxWidth):lineWidth);else if(isHardWrap)if(Number.isFinite(maxWidth)&&maxWidth>0)totalHeight+=Math.ceil(lineWidth/maxWidth)*lh,actualWidth=Math.max(actualWidth,maxWidth);else totalHeight+=lh,actualWidth=Math.max(actualWidth,lineWidth);else{let wrapped=wt(line,maxWidth,!1,!0);totalHeight+=wrapped.length*lh;for(let wl of wrapped)actualWidth=Math.max(actualWidth,dw(wl))}}let resultHeight=Math.max(lh,totalHeight);if(heightMode==="exactly"&&Number.isFinite(height))resultHeight=height;else if(heightMode==="at-most"&&Number.isFinite(height))resultHeight=Math.min(resultHeight,height);let result={width:Math.min(actualWidth,maxWidth),height:resultHeight};return measureCache.set(cacheKey,result),result})}return node}function createRootNode(){let node=createNode("silvery-root",{}),c=getConstants();return node.layoutNode.setFlexDirection(c.FLEX_DIRECTION_COLUMN),node}function createVirtualTextNode(props){return{type:"silvery-text",props,children:[],parent:null,layoutNode:null,boxRect:null,scrollRect:null,screenRect:null,prevLayout:null,prevScrollRect:null,prevScreenRect:null,layoutChangedThisFrame:!1,layoutDirty:!1,contentDirty:!0,stylePropsDirty:!0,bgDirty:!0,subtreeDirty:!0,childrenDirty:!1,layoutSubscribers:new Set,isRawText:!1,inlineRects:null}}function applyBoxProps(layoutNode,props,oldProps){let c=getConstants(),wasRemoved=(prop)=>oldProps?.[prop]!==void 0&&props[prop]===void 0;if(props.width!==void 0){if(typeof props.width==="string"&&props.width.endsWith("%"))layoutNode.setWidthPercent(Number.parseFloat(props.width));else if(typeof props.width==="number")layoutNode.setWidth(props.width);else if(props.width==="auto")layoutNode.setWidthAuto()}else if(wasRemoved("width"))layoutNode.setWidthAuto();if(props.height!==void 0){if(typeof props.height==="string"&&props.height.endsWith("%"))layoutNode.setHeightPercent(Number.parseFloat(props.height));else if(typeof props.height==="number")layoutNode.setHeight(props.height);else if(props.height==="auto")layoutNode.setHeightAuto()}else if(wasRemoved("height"))layoutNode.setHeightAuto();if(props.minWidth!==void 0){if(typeof props.minWidth==="string"&&props.minWidth.endsWith("%"))layoutNode.setMinWidthPercent(Number.parseFloat(props.minWidth));else if(typeof props.minWidth==="number")layoutNode.setMinWidth(props.minWidth)}else if(wasRemoved("minWidth"))layoutNode.setMinWidth(0);if(props.minHeight!==void 0){if(typeof props.minHeight==="string"&&props.minHeight.endsWith("%"))layoutNode.setMinHeightPercent(Number.parseFloat(props.minHeight));else if(typeof props.minHeight==="number")layoutNode.setMinHeight(props.minHeight)}else if(wasRemoved("minHeight"))layoutNode.setMinHeight(0);if(props.maxWidth!==void 0){if(typeof props.maxWidth==="string"&&props.maxWidth.endsWith("%"))layoutNode.setMaxWidthPercent(Number.parseFloat(props.maxWidth));else if(typeof props.maxWidth==="number")layoutNode.setMaxWidth(props.maxWidth)}else if(wasRemoved("maxWidth"))layoutNode.setMaxWidth(Number.POSITIVE_INFINITY);if(props.maxHeight!==void 0){if(typeof props.maxHeight==="string"&&props.maxHeight.endsWith("%"))layoutNode.setMaxHeightPercent(Number.parseFloat(props.maxHeight));else if(typeof props.maxHeight==="number")layoutNode.setMaxHeight(props.maxHeight)}else if(wasRemoved("maxHeight"))layoutNode.setMaxHeight(Number.POSITIVE_INFINITY);if(props.flexGrow!==void 0)layoutNode.setFlexGrow(props.flexGrow);else if(wasRemoved("flexGrow"))layoutNode.setFlexGrow(0);if(props.flexShrink!==void 0)layoutNode.setFlexShrink(props.flexShrink);else if(wasRemoved("flexShrink"))layoutNode.setFlexShrink(1);if(props.flexBasis!==void 0){if(typeof props.flexBasis==="string"&&props.flexBasis.endsWith("%"))layoutNode.setFlexBasisPercent(Number.parseFloat(props.flexBasis));else if(props.flexBasis==="auto")layoutNode.setFlexBasisAuto();else if(typeof props.flexBasis==="number")layoutNode.setFlexBasis(props.flexBasis)}else if(wasRemoved("flexBasis"))layoutNode.setFlexBasisAuto();if(props.flexDirection!==void 0){let directionMap={row:c.FLEX_DIRECTION_ROW,column:c.FLEX_DIRECTION_COLUMN,"row-reverse":c.FLEX_DIRECTION_ROW_REVERSE,"column-reverse":c.FLEX_DIRECTION_COLUMN_REVERSE};layoutNode.setFlexDirection(directionMap[props.flexDirection]??c.FLEX_DIRECTION_ROW)}else if(wasRemoved("flexDirection"))layoutNode.setFlexDirection(c.FLEX_DIRECTION_ROW);if(props.flexWrap!==void 0){let wrapMap={nowrap:c.WRAP_NO_WRAP,wrap:c.WRAP_WRAP,"wrap-reverse":c.WRAP_WRAP_REVERSE};layoutNode.setFlexWrap(wrapMap[props.flexWrap]??c.WRAP_NO_WRAP)}else if(wasRemoved("flexWrap"))layoutNode.setFlexWrap(c.WRAP_NO_WRAP);if(props.alignItems!==void 0)layoutNode.setAlignItems(alignToConstant(props.alignItems));else if(wasRemoved("alignItems"))layoutNode.setAlignItems(c.ALIGN_STRETCH);if(props.alignSelf!==void 0)if(props.alignSelf==="auto")layoutNode.setAlignSelf(c.ALIGN_AUTO);else layoutNode.setAlignSelf(alignToConstant(props.alignSelf));else if(wasRemoved("alignSelf"))layoutNode.setAlignSelf(c.ALIGN_AUTO);if(props.alignContent!==void 0)layoutNode.setAlignContent(alignToConstant(props.alignContent));else if(wasRemoved("alignContent"))layoutNode.setAlignContent(c.ALIGN_FLEX_START);if(props.justifyContent!==void 0)layoutNode.setJustifyContent(justifyToConstant(props.justifyContent));else if(wasRemoved("justifyContent"))layoutNode.setJustifyContent(c.JUSTIFY_FLEX_START);if(applySpacing(layoutNode,"padding",props),applySpacing(layoutNode,"margin",props),props.gap!==void 0)layoutNode.setGap(c.GUTTER_ALL,props.gap);else if(wasRemoved("gap"))layoutNode.setGap(c.GUTTER_ALL,0);if(props.columnGap!==void 0)layoutNode.setGap(c.GUTTER_COLUMN,props.columnGap);else if(wasRemoved("columnGap"))layoutNode.setGap(c.GUTTER_COLUMN,0);if(props.rowGap!==void 0)layoutNode.setGap(c.GUTTER_ROW,props.rowGap);else if(wasRemoved("rowGap"))layoutNode.setGap(c.GUTTER_ROW,0);if(props.display!==void 0)layoutNode.setDisplay(props.display==="none"?c.DISPLAY_NONE:c.DISPLAY_FLEX);else if(wasRemoved("display"))layoutNode.setDisplay(c.DISPLAY_FLEX);if(props.position!==void 0)if(props.position==="absolute")layoutNode.setPositionType(c.POSITION_TYPE_ABSOLUTE);else if(props.position==="static")layoutNode.setPositionType(c.POSITION_TYPE_STATIC);else layoutNode.setPositionType(c.POSITION_TYPE_RELATIVE);else if(wasRemoved("position"))layoutNode.setPositionType(c.POSITION_TYPE_RELATIVE);if(props.position!=="static")applyPositionOffset(layoutNode,c.EDGE_TOP,props.top),applyPositionOffset(layoutNode,c.EDGE_LEFT,props.left),applyPositionOffset(layoutNode,c.EDGE_BOTTOM,props.bottom),applyPositionOffset(layoutNode,c.EDGE_RIGHT,props.right);if(props.aspectRatio!==void 0)layoutNode.setAspectRatio(props.aspectRatio);else if(wasRemoved("aspectRatio"))layoutNode.setAspectRatio(NaN);let effectiveOverflow=props.overflow??(props.overflowX==="hidden"||props.overflowY==="hidden"?"hidden":void 0);if(effectiveOverflow!==void 0)if(effectiveOverflow==="hidden")layoutNode.setOverflow(c.OVERFLOW_HIDDEN);else if(effectiveOverflow==="scroll")layoutNode.setOverflow(c.OVERFLOW_HIDDEN);else layoutNode.setOverflow(c.OVERFLOW_VISIBLE);else if(wasRemoved("overflow")||wasRemoved("overflowX")||wasRemoved("overflowY"))layoutNode.setOverflow(c.OVERFLOW_VISIBLE);if(props.borderStyle){let borderWidth=getActiveLineHeight()>1?0:1;if(props.borderTop!==!1)layoutNode.setBorder(c.EDGE_TOP,borderWidth);else layoutNode.setBorder(c.EDGE_TOP,0);if(props.borderBottom!==!1)layoutNode.setBorder(c.EDGE_BOTTOM,borderWidth);else layoutNode.setBorder(c.EDGE_BOTTOM,0);if(props.borderLeft!==!1)layoutNode.setBorder(c.EDGE_LEFT,borderWidth);else layoutNode.setBorder(c.EDGE_LEFT,0);if(props.borderRight!==!1)layoutNode.setBorder(c.EDGE_RIGHT,borderWidth);else layoutNode.setBorder(c.EDGE_RIGHT,0)}else layoutNode.setBorder(c.EDGE_TOP,0),layoutNode.setBorder(c.EDGE_BOTTOM,0),layoutNode.setBorder(c.EDGE_LEFT,0),layoutNode.setBorder(c.EDGE_RIGHT,0)}function applySpacing(layoutNode,type,props){let c=getConstants(),set=type==="padding"?layoutNode.setPadding.bind(layoutNode):layoutNode.setMargin.bind(layoutNode),all=props[type],x=props[`${type}X`],yy=props[`${type}Y`],top=props[`${type}Top`],bottom=props[`${type}Bottom`],left=props[`${type}Left`],right=props[`${type}Right`];set(c.EDGE_TOP,top??yy??all??0),set(c.EDGE_BOTTOM,bottom??yy??all??0),set(c.EDGE_LEFT,left??x??all??0),set(c.EDGE_RIGHT,right??x??all??0)}function applyPositionOffset(layoutNode,edge,value){if(value===void 0){layoutNode.setPosition(edge,NaN);return}if(typeof value==="string"&&value.endsWith("%"))layoutNode.setPositionPercent(edge,Number.parseFloat(value));else if(typeof value==="number")layoutNode.setPosition(edge,value)}function alignToConstant(align){let c=getConstants();return{"flex-start":c.ALIGN_FLEX_START,"flex-end":c.ALIGN_FLEX_END,center:c.ALIGN_CENTER,stretch:c.ALIGN_STRETCH,baseline:c.ALIGN_BASELINE,"space-between":c.ALIGN_SPACE_BETWEEN,"space-around":c.ALIGN_SPACE_AROUND,"space-evenly":c.ALIGN_SPACE_EVENLY}[align]??c.ALIGN_STRETCH}function justifyToConstant(justify){let c=getConstants();return{"flex-start":c.JUSTIFY_FLEX_START,"flex-end":c.JUSTIFY_FLEX_END,center:c.JUSTIFY_CENTER,"space-between":c.JUSTIFY_SPACE_BETWEEN,"space-around":c.JUSTIFY_SPACE_AROUND,"space-evenly":c.JUSTIFY_SPACE_EVENLY}[justify]??c.JUSTIFY_FLEX_START}import{createLogger as createLogger10}from"loggily";var log8=createLogger10("silvery:reconciler");function normalizeNodeType(type){if(type==="ink-box")return"silvery-box";if(type==="ink-text")return"silvery-text";return type}var onNodeRemovedCallback=null;function setOnNodeRemoved(callback){onNodeRemovedCallback=callback}function markSubtreeDirty(node){while(node&&!node.subtreeDirty)node.subtreeDirty=!0,node=node.parent}function markLayoutAncestorDirty(node){if(node.layoutNode)return;let ancestor=node.parent;while(ancestor&&!ancestor.layoutNode)ancestor=ancestor.parent;if(ancestor?.layoutNode)ancestor.contentDirty=!0,ancestor.stylePropsDirty=!0,ancestor.layoutDirty=!0,ancestor.layoutNode.markDirty(),trackLayoutDirty(ancestor),trackContentDirty(ancestor)}var hasWarnedBoxInsideText=!1;var inkStrictValidation=!1;var currentUpdatePriority=NoEventPriority;var hostConfig={rendererPackageName:"@silvery/ag-react",rendererVersion:"0.0.1",supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,isPrimaryRenderer:!0,scheduleTimeout:setTimeout,cancelTimeout:clearTimeout,noTimeout:-1,supportsMicrotasks:!0,scheduleMicrotask:queueMicrotask,getRootHostContext(){return{isInsideText:!1}},getChildHostContext(parentHostContext,type){let normalizedType=normalizeNodeType(type),isInsideText=parentHostContext.isInsideText||normalizedType==="silvery-text";if(isInsideText===parentHostContext.isInsideText)return parentHostContext;return{isInsideText}},createInstance(type,props,_rootContainer,hostContext){if(type=normalizeNodeType(type),"style"in props&&props.style&&typeof props.style==="object")props={...props.style,...props};if(type==="silvery-box"&&hostContext.isInsideText){if(inkStrictValidation)throw Error("<Box> can’t be nested inside <Text> component");if(!hasWarnedBoxInsideText)hasWarnedBoxInsideText=!0,log8.warn?.("<Box> cannot be nested inside <Text>. This produces undefined layout behavior.")}if(type==="silvery-text"&&hostContext.isInsideText)return createVirtualTextNode(props);return createNode(type,props)},createTextInstance(text,_rootContainer,hostContext){if(inkStrictValidation&&!hostContext.isInsideText&&text.trim().length>0)throw Error(`Text string "${text}" must be rendered inside <Text> component`);return{type:"silvery-text",props:{children:text},children:[],parent:null,layoutNode:null,boxRect:null,scrollRect:null,screenRect:null,prevLayout:null,prevScrollRect:null,prevScreenRect:null,layoutChangedThisFrame:!1,layoutDirty:!1,contentDirty:!0,stylePropsDirty:!0,bgDirty:!0,subtreeDirty:!0,childrenDirty:!1,layoutSubscribers:new Set,textContent:text,isRawText:!0}},appendChild(parentInstance,child){let existingIndex=parentInstance.children.indexOf(child);if(existingIndex!==-1){if(parentInstance.children.splice(existingIndex,1),parentInstance.layoutNode&&child.layoutNode)parentInstance.layoutNode.removeChild(child.layoutNode)}if(child.parent=parentInstance,parentInstance.children.push(child),parentInstance.layoutNode&&child.layoutNode){let layoutIndex=parentInstance.children.filter((c)=>c.layoutNode!==null).length-1;parentInstance.layoutNode.insertChild(child.layoutNode,layoutIndex)}parentInstance.childrenDirty=!0,parentInstance.contentDirty=!0,parentInstance.layoutDirty=!0,parentInstance.layoutNode?.markDirty(),trackLayoutDirty(parentInstance),trackContentDirty(parentInstance),markLayoutAncestorDirty(parentInstance),markSubtreeDirty(parentInstance)},appendInitialChild(parentInstance,child){if(child.parent=parentInstance,parentInstance.children.push(child),parentInstance.layoutNode&&child.layoutNode){let layoutIndex=parentInstance.children.filter((c)=>c.layoutNode!==null).length-1;parentInstance.layoutNode.insertChild(child.layoutNode,layoutIndex)}},appendChildToContainer(container,child){let existingIndex=container.root.children.indexOf(child);if(existingIndex!==-1){if(container.root.children.splice(existingIndex,1),container.root.layoutNode&&child.layoutNode)container.root.layoutNode.removeChild(child.layoutNode)}if(child.parent=container.root,container.root.children.push(child),container.root.layoutNode&&child.layoutNode){let layoutIndex=container.root.children.filter((c)=>c.layoutNode!==null).length-1;container.root.layoutNode.insertChild(child.layoutNode,layoutIndex)}container.root.childrenDirty=!0,container.root.contentDirty=!0,container.root.layoutDirty=!0,container.root.layoutNode?.markDirty(),trackLayoutDirty(container.root),trackContentDirty(container.root),markSubtreeDirty(container.root)},removeChild(parentInstance,child){let index=parentInstance.children.indexOf(child);if(index!==-1){if(onNodeRemovedCallback?.(child),parentInstance.children.splice(index,1),parentInstance.layoutNode&&child.layoutNode)parentInstance.layoutNode.removeChild(child.layoutNode),child.layoutNode.free();child.parent=null,parentInstance.childrenDirty=!0,parentInstance.contentDirty=!0,parentInstance.layoutDirty=!0,parentInstance.layoutNode?.markDirty(),trackLayoutDirty(parentInstance),trackContentDirty(parentInstance),markLayoutAncestorDirty(parentInstance),markSubtreeDirty(parentInstance)}},removeChildFromContainer(container,child){let index=container.root.children.indexOf(child);if(index!==-1){if(onNodeRemovedCallback?.(child),container.root.children.splice(index,1),container.root.layoutNode&&child.layoutNode)container.root.layoutNode.removeChild(child.layoutNode),child.layoutNode.free();child.parent=null,container.root.childrenDirty=!0,container.root.contentDirty=!0,container.root.layoutDirty=!0,container.root.layoutNode?.markDirty(),trackLayoutDirty(container.root),trackContentDirty(container.root),markSubtreeDirty(container.root)}},insertBefore(parentInstance,child,beforeChild){let existingIndex=parentInstance.children.indexOf(child);if(existingIndex!==-1){if(parentInstance.children.splice(existingIndex,1),parentInstance.layoutNode&&child.layoutNode)parentInstance.layoutNode.removeChild(child.layoutNode)}let beforeIndex=parentInstance.children.indexOf(beforeChild);if(beforeIndex!==-1){if(child.parent=parentInstance,parentInstance.children.splice(beforeIndex,0,child),parentInstance.layoutNode&&child.layoutNode){let layoutIndex=parentInstance.children.slice(0,beforeIndex).filter((c)=>c.layoutNode!==null).length;parentInstance.layoutNode.insertChild(child.layoutNode,layoutIndex)}parentInstance.childrenDirty=!0,parentInstance.contentDirty=!0,parentInstance.layoutDirty=!0,parentInstance.layoutNode?.markDirty(),trackLayoutDirty(parentInstance),trackContentDirty(parentInstance),markLayoutAncestorDirty(parentInstance),markSubtreeDirty(parentInstance)}},insertInContainerBefore(container,child,beforeChild){let existingIndex=container.root.children.indexOf(child);if(existingIndex!==-1){if(container.root.children.splice(existingIndex,1),container.root.layoutNode&&child.layoutNode)container.root.layoutNode.removeChild(child.layoutNode)}let beforeIndex=container.root.children.indexOf(beforeChild);if(beforeIndex!==-1){if(child.parent=container.root,container.root.children.splice(beforeIndex,0,child),container.root.layoutNode&&child.layoutNode){let layoutIndex=container.root.children.slice(0,beforeIndex).filter((c)=>c.layoutNode!==null).length;container.root.layoutNode.insertChild(child.layoutNode,layoutIndex)}container.root.childrenDirty=!0,container.root.contentDirty=!0,container.root.layoutDirty=!0,container.root.layoutNode?.markDirty(),trackLayoutDirty(container.root),trackContentDirty(container.root),markSubtreeDirty(container.root)}},prepareUpdate(_instance,_type,oldProps,newProps){return classifyPropChanges(oldProps,newProps).anyChanged},commitUpdate(instance,_type,oldProps,newProps,_finishedWork){if("style"in oldProps&&oldProps.style&&typeof oldProps.style==="object")oldProps={...oldProps.style,...oldProps};if("style"in newProps&&newProps.style&&typeof newProps.style==="object")newProps={...newProps.style,...newProps};let{anyChanged,layoutChanged,contentChanged}=classifyPropChanges(oldProps,newProps);if(!anyChanged){instance.props=newProps;return}if(layoutChanged){if(instance.layoutNode)applyBoxProps(instance.layoutNode,newProps,oldProps),instance.layoutNode.markDirty();instance.layoutDirty=!0,trackLayoutDirty(instance)}if(contentChanged){if(instance.stylePropsDirty=!0,contentChanged==="text"){if(instance.contentDirty=!0,instance.layoutNode)instance.layoutNode.markDirty()}if(oldProps.backgroundColor!==newProps.backgroundColor)instance.bgDirty=!0;if(oldProps.borderStyle&&!newProps.borderStyle)instance.bgDirty=!0;if(oldProps.outlineStyle&&!newProps.outlineStyle)instance.bgDirty=!0;if(oldProps.theme!==newProps.theme)instance.bgDirty=!0}if(contentChanged)trackContentDirty(instance);instance.props=newProps;let scrollToChanged=oldProps.scrollTo!==newProps.scrollTo,scrollOffsetChanged=oldProps.scrollOffset!==newProps.scrollOffset;if(instance.layoutDirty||contentChanged||scrollToChanged||scrollOffsetChanged)markLayoutAncestorDirty(instance),markSubtreeDirty(instance)},commitTextUpdate(textInstance,_oldText,newText){textInstance.textContent=newText,textInstance.props={children:newText},textInstance.contentDirty=!0,textInstance.stylePropsDirty=!0,trackContentDirty(textInstance),markLayoutAncestorDirty(textInstance),markSubtreeDirty(textInstance)},finalizeInitialChildren(){return!1},prepareForCommit(){return null},resetAfterCommit(container){container.onRender()},getPublicInstance(instance){return instance},shouldSetTextContent(){return!1},clearContainer(container){for(let child of container.root.children)onNodeRemovedCallback?.(child);for(let child of container.root.children)if(container.root.layoutNode&&child.layoutNode)container.root.layoutNode.removeChild(child.layoutNode),child.layoutNode.free();container.root.children=[],container.root.childrenDirty=!0,container.root.contentDirty=!0,container.root.layoutDirty=!0,container.root.layoutNode?.markDirty(),trackLayoutDirty(container.root),trackContentDirty(container.root),markSubtreeDirty(container.root)},preparePortalMount(){},getCurrentEventPriority(){if(currentUpdatePriority!==NoEventPriority)return currentUpdatePriority;return DefaultEventPriority},getInstanceFromNode(){return null},beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},prepareScopeUpdate(){},getInstanceFromScope(){return null},detachDeletedInstance(){},setCurrentUpdatePriority(newPriority){currentUpdatePriority=newPriority},getCurrentUpdatePriority(){return currentUpdatePriority},resolveUpdatePriority(){if(currentUpdatePriority!==NoEventPriority)return currentUpdatePriority;return DefaultEventPriority},maySuspendCommit(){return!1},NotPendingTransition:null,HostTransitionContext:createContext2(null),resetFormInstance(){},requestPostPaintCallback(){},shouldAttemptEagerTransition(){return!1},trackSchedulerEvent(){},resolveEventType(){return null},resolveEventTimeStamp(){return-1.1},preloadInstance(){return!0},startSuspendingCommit(){},suspendInstance(){},waitForCommitToBeReady(){return null},hideInstance(instance){if(instance.hidden=!0,instance.contentDirty=!0,instance.stylePropsDirty=!0,instance.layoutDirty=!0,instance.layoutNode)instance.layoutNode.markDirty();if(trackLayoutDirty(instance),trackContentDirty(instance),instance.parent)instance.parent.contentDirty=!0,trackContentDirty(instance.parent);markLayoutAncestorDirty(instance),markSubtreeDirty(instance)},unhideInstance(instance,_props){if(instance.hidden=!1,instance.contentDirty=!0,instance.stylePropsDirty=!0,instance.layoutDirty=!0,instance.layoutNode)instance.layoutNode.markDirty();if(trackLayoutDirty(instance),trackContentDirty(instance),instance.parent)instance.parent.contentDirty=!0,trackContentDirty(instance.parent);markLayoutAncestorDirty(instance),markSubtreeDirty(instance)},hideTextInstance(textInstance){if(textInstance.hidden=!0,textInstance.contentDirty=!0,textInstance.stylePropsDirty=!0,trackContentDirty(textInstance),textInstance.parent)textInstance.parent.contentDirty=!0,trackContentDirty(textInstance.parent);markLayoutAncestorDirty(textInstance),markSubtreeDirty(textInstance)},unhideTextInstance(textInstance,_text){if(textInstance.hidden=!1,textInstance.contentDirty=!0,textInstance.stylePropsDirty=!0,trackContentDirty(textInstance),textInstance.parent)textInstance.parent.contentDirty=!0,trackContentDirty(textInstance.parent);markLayoutAncestorDirty(textInstance),markSubtreeDirty(textInstance)}};var reconciler=Reconciler(hostConfig);function createContainer(onRender){return{root:createRootNode(),onRender}}function createFiberRoot(container){return reconciler.createContainer(container,1,null,!1,null,"",()=>{},()=>{},()=>{},null)}function getContainerRoot(container){return container.root}async function ensureLayoutEngine(){if(!isLayoutEngineInitialized())await ensureDefaultLayoutEngine()}function layout(element,dims,options={}){if(!isLayoutEngineInitialized())throw Error("Layout engine not initialized. Call ensureLayoutEngine() first.");let{skipLayoutNotifications=!0,plain=!1}=options,{cols:width,rows:height}=dims,container=createContainer(()=>{}),fiberRoot=createFiberRoot(container),mockStdout={columns:width,rows:height,write:()=>!0,isTTY:!1,on:()=>mockStdout,off:()=>mockStdout,once:()=>mockStdout,removeListener:()=>mockStdout,addListener:()=>mockStdout},mockTerm=createTerm({color:plain?null:"truecolor"}),wrapped=React.createElement(TermContext.Provider,{value:mockTerm},React.createElement(StdoutContext.Provider,{value:{stdout:mockStdout,write:()=>{}}},React.createElement(StderrContext.Provider,{value:{stderr:process.stderr,write:(data)=>{process.stderr.write(data)}}},element)));withoutActWarnings(()=>{reconciler.updateContainerSync(wrapped,fiberRoot,null,null),reconciler.flushSyncWork()});let root=getContainerRoot(container),{buffer:termBuffer}=executeRender(root,width,height,null,{skipLayoutNotifications}),text=bufferToText(termBuffer),ansi=bufferToStyledText(termBuffer);return withoutActWarnings(()=>{reconciler.updateContainerSync(null,fiberRoot,null,null),reconciler.flushSyncWork()}),{text,ansi,nodes:root,_buffer:termBuffer}}function layoutSync(element,dims,options={}){return layout(element,dims,options)}function withoutActWarnings(fn){let prev=globalThis.IS_REACT_ACT_ENVIRONMENT;globalThis.IS_REACT_ACT_ENVIRONMENT=!1;try{fn()}finally{globalThis.IS_REACT_ACT_ENVIRONMENT=prev}}function diff(prev,next,mode="fullscreen",scrollbackOffset=0,termRows){let prevBuffer=prev?._buffer??null,nextBuffer=next._buffer;return outputPhase(prevBuffer,nextBuffer,mode,scrollbackOffset,termRows)}function render(buffer,mode="fullscreen"){return outputPhase(null,buffer._buffer,mode)}init_buffer();function createBuffer2(termBuffer,nodes){let _text,_ansi;return{get text(){return _text??=bufferToText(termBuffer)},get ansi(){return _ansi??=bufferToStyledText(termBuffer)},nodes,_buffer:termBuffer}}init_output_phase();async function*merge(...sources){if(sources.length===0)return;let iterators=sources.map((source)=>source[Symbol.asyncIterator]()),pending=new Map;async function nextWithIndex(idx){let iterator=iterators[idx];if(!iterator)throw Error(`No iterator at index ${idx}`);let result=await iterator.next();return{index:idx,result}}for(let i=0;i<iterators.length;i++)pending.set(i,nextWithIndex(i));try{while(pending.size>0){let{index,result}=await Promise.race(pending.values());if(result.done)pending.delete(index);else yield result.value,pending.set(index,nextWithIndex(index))}}finally{await Promise.all(iterators.map((it)=>it.return?it.return():Promise.resolve()))}}async function*map(source,fn){let iterator=source[Symbol.asyncIterator]();try{for await(let value of{[Symbol.asyncIterator]:()=>iterator})yield fn(value)}finally{if(iterator.return)await iterator.return()}}async function*filter(source,predicate){let iterator=source[Symbol.asyncIterator]();try{for await(let value of{[Symbol.asyncIterator]:()=>iterator})if(predicate(value))yield value}finally{if(iterator.return)await iterator.return()}}async function*filterMap(source,fn){let iterator=source[Symbol.asyncIterator]();try{for await(let value of{[Symbol.asyncIterator]:()=>iterator}){let mapped=fn(value);if(mapped!==void 0)yield mapped}}finally{if(iterator.return)await iterator.return()}}async function*takeUntil(source,signal){if(signal.aborted)return;let iterator=source[Symbol.asyncIterator](),abortResolve,abortPromise=new Promise((resolve)=>{abortResolve=resolve}),onAbort=()=>abortResolve();signal.addEventListener("abort",onAbort,{once:!0});try{while(!signal.aborted){let result=await Promise.race([iterator.next(),abortPromise.then(()=>({done:!0,value:void 0}))]);if(result.done)break;yield result.value}}finally{if(signal.removeEventListener("abort",onAbort),iterator.return)await iterator.return()}}async function*take(source,count){if(count<=0)return;let iterator=source[Symbol.asyncIterator](),taken=0;try{for await(let value of{[Symbol.asyncIterator]:()=>iterator})if(yield value,taken++,taken>=count)break}finally{if(iterator.return)await iterator.return()}}async function*fromArray(items){for(let item of items)yield item}async function*fromArrayWithDelay(items,delayMs){for(let item of items)await new Promise((resolve)=>setTimeout(resolve,delayMs)),yield item}async function*throttle(source,ms){let iterator=source[Symbol.asyncIterator](),lastEmit=0;try{for await(let value of{[Symbol.asyncIterator]:()=>iterator}){let now=Date.now();if(now-lastEmit>=ms)lastEmit=now,yield value}}finally{if(iterator.return)await iterator.return()}}async function*debounce(source,ms){let iterator=source[Symbol.asyncIterator](),last;try{for await(let value of{[Symbol.asyncIterator]:()=>iterator})last={value};if(last)await new Promise((resolve)=>setTimeout(resolve,ms)),yield last.value}finally{if(iterator.return)await iterator.return()}}function batch(source,size){if(size<=0)throw Error("Batch size must be positive");return batchImpl(source,size)}async function*batchImpl(source,size){let iterator=source[Symbol.asyncIterator](),buffer=[];try{for await(let value of{[Symbol.asyncIterator]:()=>iterator})if(buffer.push(value),buffer.length>=size)yield buffer,buffer=[];if(buffer.length>0)yield buffer}finally{if(iterator.return)await iterator.return()}}async function*concat(...sources){for(let source of sources)yield*source}async function*zip(...sources){let iterators=sources.map((source)=>source[Symbol.asyncIterator]());try{while(!0){let results=await Promise.all(iterators.map((it)=>it.next()));if(results.some((r)=>r.done))break;yield results.map((r)=>r.value)}}finally{await Promise.all(iterators.map((it)=>it.return?it.return():Promise.resolve()))}}function createEventChannel(signal){let queue=[],pendingResolve,disposed=!1,onAbort=()=>{if(pendingResolve)pendingResolve(null),pendingResolve=void 0};return signal.addEventListener("abort",onAbort,{once:!0}),{push(event){if(disposed||signal.aborted)return;if(pendingResolve){let r=pendingResolve;pendingResolve=void 0,r(event)}else queue.push(event)},events(){return{[Symbol.asyncIterator](){return{async next(){if(disposed||signal.aborted)return{done:!0,value:void 0};if(queue.length>0)return{done:!1,value:queue.shift()};let event=await new Promise((resolve)=>{pendingResolve=resolve});if(event===null||disposed||signal.aborted)return{done:!0,value:void 0};return{done:!1,value:event}}}}}},dispose(){if(disposed=!0,signal.removeEventListener("abort",onAbort),pendingResolve)pendingResolve(null),pendingResolve=void 0}}}function createRuntime(options){let{target,signal:externalSignal,mode="fullscreen"}=options,fallbackOutputPhase=mode==="inline"?createOutputPhase({}):void 0,outputPhaseFn=options.outputPhaseFn??fallbackOutputPhase,controller=new AbortController,signal=controller.signal,externalAbortHandler;if(externalSignal)if(externalSignal.aborted)controller.abort();else externalAbortHandler=()=>controller.abort(),externalSignal.addEventListener("abort",externalAbortHandler,{once:!0});let prevBuffer=null,scrollbackOffset=0,disposed=!1,eventChannel=createEventChannel(signal),unsubscribeResize;if(target.onResize)unsubscribeResize=target.onResize((dims)=>{eventChannel.push({type:"resize",cols:dims.cols,rows:dims.rows})});let effectId=0;return{events(){return takeUntil(eventChannel.events(),signal)},schedule(effect,opts){if(disposed)return;let id=`effect-${effectId++}`,effectSignal=opts?.signal;if(effectSignal?.aborted)return;let execute=async()=>{let abortHandler;try{if(effectSignal){let aborted=new Promise((_resolve,reject)=>{abortHandler=()=>reject(Error("Effect aborted")),effectSignal.addEventListener("abort",abortHandler,{once:!0})}),result=await Promise.race([effect(),aborted]);if(abortHandler)effectSignal.removeEventListener("abort",abortHandler);eventChannel.push({type:"effect",id,result})}else{let result=await effect();eventChannel.push({type:"effect",id,result})}}catch(error){if(abortHandler&&effectSignal)effectSignal.removeEventListener("abort",abortHandler);if(error instanceof Error&&(error.message==="Effect aborted"||error.name==="AbortError"))return;eventChannel.push({type:"error",error:error instanceof Error?error:Error(String(error))})}};queueMicrotask(()=>{execute()})},render(buffer){if(disposed)return;let offset=scrollbackOffset;scrollbackOffset=0;let termRows=target.getDims().rows,patch;if(outputPhaseFn){let prevBuf=prevBuffer?._buffer??null,nextBuf=buffer._buffer;patch=outputPhaseFn(prevBuf,nextBuf,mode,offset,termRows)}else patch=diff(prevBuffer,buffer,mode,offset,termRows);if(prevBuffer=buffer,process.env.SILVERY_CAPTURE_RAW)try{__require("fs").appendFileSync("/tmp/silvery-runtime-raw.ansi",patch)}catch{}target.write(patch)},addScrollbackLines(lines){if(mode!=="inline"||lines<=0)return;scrollbackOffset+=lines},invalidate(){prevBuffer=null},setOutputPhaseFn(fn){if(fn)outputPhaseFn=fn},resetInlineCursor(){outputPhaseFn?.resetInlineState?.()},getInlineCursorRow(){return outputPhaseFn?.getInlineCursorRow?.()??-1},promoteScrollback(content,lines){outputPhaseFn?.promoteScrollback?.(content,lines)},getDims(){return target.getDims()},[Symbol.dispose](){if(disposed)return;if(disposed=!0,controller.abort(),externalAbortHandler&&externalSignal)externalSignal.removeEventListener("abort",externalAbortHandler);if(unsubscribeResize)unsubscribeResize();eventChannel.dispose()}}}import{useContext as useContext5,useEffect as useEffect3,useRef as useRef4}from"react";import{writeSync as writeSync3}from"node:fs";import process2 from"node:process";import React5,{createContext as createContext4,useContext as useContext3,useEffect as useEffect2,useRef as useRef3}from"react";function createReactiveSystem({update,notify,unwatched}){return{link,unlink,propagate,checkDirty,shallowPropagate};function link(dep,sub,version){let prevDep=sub.depsTail;if(prevDep!==void 0&&prevDep.dep===dep)return;let nextDep=prevDep!==void 0?prevDep.nextDep:sub.deps;if(nextDep!==void 0&&nextDep.dep===dep){nextDep.version=version,sub.depsTail=nextDep;return}let prevSub=dep.subsTail;if(prevSub!==void 0&&prevSub.version===version&&prevSub.sub===sub)return;let newLink=sub.depsTail=dep.subsTail={version,dep,sub,prevDep,nextDep,prevSub,nextSub:void 0};if(nextDep!==void 0)nextDep.prevDep=newLink;if(prevDep!==void 0)prevDep.nextDep=newLink;else sub.deps=newLink;if(prevSub!==void 0)prevSub.nextSub=newLink;else dep.subs=newLink}function unlink(link2,sub=link2.sub){let{dep,prevDep,nextDep,nextSub,prevSub}=link2;if(nextDep!==void 0)nextDep.prevDep=prevDep;else sub.depsTail=prevDep;if(prevDep!==void 0)prevDep.nextDep=nextDep;else sub.deps=nextDep;if(nextSub!==void 0)nextSub.prevSub=prevSub;else dep.subsTail=prevSub;if(prevSub!==void 0)prevSub.nextSub=nextSub;else if((dep.subs=nextSub)===void 0)unwatched(dep);return nextDep}function propagate(link2){let next=link2.nextSub,stack;top:do{let sub=link2.sub,flags=sub.flags;if(!(flags&60))sub.flags=flags|32;else if(!(flags&12))flags=0;else if(!(flags&4))sub.flags=flags&-9|32;else if(!(flags&48)&&isValidLink(link2,sub))sub.flags=flags|40,flags&=1;else flags=0;if(flags&2)notify(sub);if(flags&1){let subSubs=sub.subs;if(subSubs!==void 0){let nextSub=(link2=subSubs).nextSub;if(nextSub!==void 0)stack={value:next,prev:stack},next=nextSub;continue}}if((link2=next)!==void 0){next=link2.nextSub;continue}while(stack!==void 0)if(link2=stack.value,stack=stack.prev,link2!==void 0){next=link2.nextSub;continue top}break}while(!0)}function checkDirty(link2,sub){let stack,checkDepth=0,dirty=!1;top:do{let dep=link2.dep,flags=dep.flags;if(sub.flags&16)dirty=!0;else if((flags&17)===17){if(update(dep)){let subs=dep.subs;if(subs.nextSub!==void 0)shallowPropagate(subs);dirty=!0}}else if((flags&33)===33){if(link2.nextSub!==void 0||link2.prevSub!==void 0)stack={value:link2,prev:stack};link2=dep.deps,sub=dep,++checkDepth;continue}if(!dirty){let nextDep=link2.nextDep;if(nextDep!==void 0){link2=nextDep;continue}}while(checkDepth--){let firstSub=sub.subs,hasMultipleSubs=firstSub.nextSub!==void 0;if(hasMultipleSubs)link2=stack.value,stack=stack.prev;else link2=firstSub;if(dirty){if(update(sub)){if(hasMultipleSubs)shallowPropagate(firstSub);sub=link2.sub;continue}dirty=!1}else sub.flags&=-33;sub=link2.sub;let nextDep=link2.nextDep;if(nextDep!==void 0){link2=nextDep;continue top}}return dirty}while(!0)}function shallowPropagate(link2){do{let sub=link2.sub,flags=sub.flags;if((flags&48)===32){if(sub.flags=flags|16,(flags&6)===2)notify(sub)}}while((link2=link2.nextSub)!==void 0)}function isValidLink(checkLink,sub){let link2=sub.depsTail;while(link2!==void 0){if(link2===checkLink)return!0;link2=link2.prevDep}return!1}}var cycle=0,batchDepth=0,notifyIndex=0,queuedLength=0,activeSub,queued=[],{link,unlink,propagate,checkDirty,shallowPropagate}=createReactiveSystem({update(node){if(node.depsTail!==void 0)return updateComputed(node);else return updateSignal(node)},notify(effect){let insertIndex=queuedLength,firstInsertedIndex=insertIndex;do if(queued[insertIndex++]=effect,effect.flags&=-3,effect=effect.subs?.sub,effect===void 0||!(effect.flags&2))break;while(!0);queuedLength=insertIndex;while(firstInsertedIndex<--insertIndex){let left=queued[firstInsertedIndex];queued[firstInsertedIndex++]=queued[insertIndex],queued[insertIndex]=left}},unwatched(node){if(!(node.flags&1))effectScopeOper.call(node);else if(node.depsTail!==void 0)node.depsTail=void 0,node.flags=17,purgeDeps(node)}});function setActiveSub(sub){let prevSub=activeSub;return activeSub=sub,prevSub}function signal(initialValue){return signalOper.bind({currentValue:initialValue,pendingValue:initialValue,subs:void 0,subsTail:void 0,flags:1})}function updateComputed(c){++cycle,c.depsTail=void 0,c.flags=5;let prevSub=setActiveSub(c);try{let oldValue=c.value;return oldValue!==(c.value=c.getter(oldValue))}finally{activeSub=prevSub,c.flags&=-5,purgeDeps(c)}}function updateSignal(s){return s.flags=1,s.currentValue!==(s.currentValue=s.pendingValue)}function run(e){let flags=e.flags;if(flags&16||flags&32&&checkDirty(e.deps,e)){++cycle,e.depsTail=void 0,e.flags=6;let prevSub=setActiveSub(e);try{e.fn()}finally{activeSub=prevSub,e.flags&=-5,purgeDeps(e)}}else e.flags=2}function flush(){try{while(notifyIndex<queuedLength){let effect=queued[notifyIndex];queued[notifyIndex++]=void 0,run(effect)}}finally{while(notifyIndex<queuedLength){let effect=queued[notifyIndex];queued[notifyIndex++]=void 0,effect.flags|=10}notifyIndex=0,queuedLength=0}}function signalOper(...value){if(value.length){if(this.pendingValue!==(this.pendingValue=value[0])){this.flags=17;let subs=this.subs;if(subs!==void 0){if(propagate(subs),!batchDepth)flush()}}}else{if(this.flags&16){if(updateSignal(this)){let subs=this.subs;if(subs!==void 0)shallowPropagate(subs)}}let sub=activeSub;while(sub!==void 0){if(sub.flags&3){link(this,sub,cycle);break}sub=sub.subs?.sub}return this.currentValue}}function effectScopeOper(){this.depsTail=void 0,this.flags=0,purgeDeps(this);let sub=this.subs;if(sub!==void 0)unlink(sub)}function purgeDeps(sub){let depsTail=sub.depsTail,dep=depsTail!==void 0?depsTail.nextDep:sub.deps;while(dep!==void 0)dep=unlink(dep,sub)}function createStore(factory){let listeners=new Set,state$=signal(void 0),initialState,setState=(partial,replace)=>{let prev=state$(),raw=typeof partial==="function"?partial(prev):partial,next;if(!replace&&raw!==null&&typeof raw==="object"&&!Array.isArray(raw))next={...prev,...raw};else next=raw;if(Object.is(prev,next))return;state$(next);for(let listener of listeners)listener(next,prev)},getState=()=>state$(),api={setState,getState,getInitialState:()=>initialState,subscribe:(listener)=>{return listeners.add(listener),()=>{listeners.delete(listener)}}},created=factory(setState,getState,api);return state$(created),initialState=created,api}init_ansi2();import*as fs from"node:fs";import React2,{Component}from"react";function parseStackLine(line){let trimmed=line.trim();if(!trimmed.startsWith("at "))return null;let rest=trimmed.slice(3),match1=rest.match(/^(.+?)\s+\((.+?):(\d+):(\d+)\)$/);if(match1)return{function:match1[1],file:match1[2],line:Number(match1[3]),column:Number(match1[4])};let match2=rest.match(/^(.+?):(\d+):(\d+)$/);if(match2)return{file:match2[1],line:Number(match2[2]),column:Number(match2[3])};return null}function cleanupPath(filePath){if(!filePath)return filePath;let p=filePath,cwdPath=process.cwd();p=p.replace(/^file:\/\//,"");for(let prefix of[cwdPath,`/private${cwdPath}`])if(p.startsWith(`${prefix}/`)){p=p.slice(prefix.length+1);break}return p}function getCodeExcerpt(filePath,line){try{if(!fs.existsSync(filePath))return null;let lines=fs.readFileSync(filePath,"utf8").split(`
74
+ `);if(wrap==="clip"){let sliceFn=ctx?ctx.measurer.sliceByWidth:sliceByWidth;return lines.map((line)=>{if(getTextWidth2(line,ctx)<=width)return line;return sliceFn(line,width)})}if(wrap==="hard"){let sliceFn=ctx?ctx.measurer.sliceByWidth:sliceByWidth,out=[];for(let line of lines){if(line===""){out.push("");continue}let remaining=line;while(getTextWidth2(remaining,ctx)>width){let head=sliceFn(remaining,width);if(head.length===0)break;out.push(head),remaining=remaining.slice(head.length)}out.push(remaining)}return out}if(wrap===!1||wrap==="truncate-end"||wrap==="truncate")return lines.map((line)=>truncateText(line,width,"end",ctx));if(wrap==="truncate-start")return lines.map((line)=>truncateText(line,width,"start",ctx));if(wrap==="truncate-middle")return lines.map((line)=>truncateText(line,width,"middle",ctx));if(wrap==="balanced"){let gWidthFn=ctx?.measurer?.graphemeWidth?.bind(ctx.measurer)??graphemeWidth,analysis=buildTextAnalysis(normalizedText,gWidthFn),bWidth=balancedWidth(analysis,width);if(ctx)return ctx.measurer.wrapText(normalizedText,bWidth,!0,trim);return wrapText(normalizedText,bWidth,!0,trim)}if(ctx)return ctx.measurer.wrapText(normalizedText,width,!0,trim);return wrapText(normalizedText,width,!0,trim)}function truncateText(text,width,mode,ctx){if(getTextWidth2(text,ctx)<=width)return text;let ellipsis="…",availableWidth=width-1;if(availableWidth<=0)return width>0?ellipsis:"";let sliceFn=ctx?ctx.measurer.sliceByWidth:sliceByWidth,sliceEndFn=ctx?ctx.measurer.sliceByWidthFromEnd:sliceByWidthFromEnd;if(mode==="end")return sliceFn(text,availableWidth)+ellipsis;if(mode==="start")return ellipsis+sliceEndFn(text,availableWidth);let halfWidth=Math.floor(availableWidth/2),startPart=sliceFn(text,halfWidth),endPart=sliceEndFn(text,availableWidth-halfWidth);return startPart+ellipsis+endPart}function renderTextLine(buffer,x,y,text,baseStyle,maxCol,inheritedBg,ctx){if(hasAnsi(text)){renderAnsiTextLine(buffer,x,y,text,baseStyle,maxCol,inheritedBg,ctx);return}renderGraphemes(buffer,splitGraphemes(text),x,y,baseStyle,maxCol,inheritedBg,ctx)}function renderTextLineReturn(buffer,x,y,text,baseStyle,maxCol,inheritedBg,ctx,minCol){if(hasAnsi(text))return renderAnsiTextLineReturn(buffer,x,y,text,baseStyle,maxCol,inheritedBg,ctx,minCol);return renderGraphemes(buffer,splitGraphemes(text),x,y,baseStyle,maxCol,inheritedBg,ctx,minCol)}function renderGraphemes(buffer,graphemes,startCol,y,style2,maxCol,inheritedBg,ctx,minCol){let col=startCol,rightEdge=maxCol!==void 0?Math.min(maxCol,buffer.width):buffer.width,leftEdge=minCol!==void 0?Math.max(minCol,0):0,gWidthFn=ctx?ctx.measurer.graphemeWidth:graphemeWidth;for(let grapheme of graphemes){if(col>=rightEdge)break;let width=gWidthFn(grapheme);if(width===0)continue;if(col+width<=leftEdge){col+=width;continue}if(col<leftEdge){col=leftEdge;continue}let existingBg=style2.bg!==null?style2.bg:inheritedBg!==void 0?inheritedBg:buffer.getCellBg(col,y);if(width===2&&col+1>=rightEdge){buffer.setCell(col,y,{char:" ",fg:style2.fg,bg:existingBg,underlineColor:style2.underlineColor??null,attrs:style2.attrs,wide:!1,continuation:!1,hyperlink:style2.hyperlink}),col+=1;continue}let outputChar=width===2?ensureEmojiPresentation(grapheme):grapheme;if(buffer.setCell(col,y,{char:outputChar,fg:style2.fg,bg:existingBg,underlineColor:style2.underlineColor??null,attrs:style2.attrs,wide:width===2,continuation:!1,hyperlink:style2.hyperlink}),width===2&&col+1<buffer.width){let existingBg2=style2.bg!==null?style2.bg:inheritedBg!==void 0?inheritedBg:buffer.getCellBg(col+1,y);buffer.setCell(col+1,y,{char:"",fg:style2.fg,bg:existingBg2,underlineColor:style2.underlineColor??null,attrs:style2.attrs,wide:!1,continuation:!0,hyperlink:style2.hyperlink}),col+=2}else col+=width}return col}function renderAnsiTextLine(buffer,x,y,text,baseStyle,maxCol,inheritedBg,ctx){renderAnsiTextLineReturn(buffer,x,y,text,baseStyle,maxCol,inheritedBg,ctx)}function renderAnsiTextLineReturn(buffer,x,y,text,baseStyle,maxCol,inheritedBg,ctx,minCol){let segments=parseAnsiText(text),col=x;for(let segment of segments){let style2=mergeAnsiStyle(baseStyle,segment),effectiveBgConflictMode=ctx?.bgConflictMode??getBgConflictMode();if(effectiveBgConflictMode!=="ignore"&&!segment.bgOverride&&segment.bg!==void 0&&segment.bg!==null){let existingBufBg=col<buffer.width?buffer.getCellBg(col,y):null;if(baseStyle.bg!==null||existingBufBg!==null){let preview=segment.text.slice(0,30),chalkBg=formatBgConflictColor(segment.bg),silveryBg=baseStyle.bg!==null?`Text.bg=${formatBgConflictColor(baseStyle.bg)}`:`bufferBg=${formatBgConflictColor(existingBufBg)}`,textPreview=text.length>80?text.slice(0,80)+"…":text,msg=`[silvery] Background conflict at (${col},${y}): chalk bg=${chalkBg} on silvery ${silveryBg}. Text: "${preview}${segment.text.length>30?"…":""}". Raw ANSI (first 80): ${JSON.stringify(textPreview)}. Chalk bg will override only text characters, causing visual gaps in padding. Use ansi.bgOverride() to suppress if intentional.`;if(effectiveBgConflictMode==="throw")throw Error(msg);let effectiveWarnedBgConflicts=ctx?.warnedBgConflicts??warnedBgConflicts,key=`${JSON.stringify(existingBufBg)}-${segment.bg}-${preview}`;if(!effectiveWarnedBgConflicts.has(key))effectiveWarnedBgConflicts.add(key),log6.warn?.(msg)}}col=renderGraphemes(buffer,splitGraphemes(segment.text),col,y,style2,maxCol,inheritedBg,ctx,minCol)}return col}function mergeStyles(base,overlay,options={}){let{preserveDecorations=!0,preserveEmphasis=!0}=options,baseAttrs=base.attrs??{},overlayAttrs=overlay.attrs??{},attrs={};if(preserveDecorations){let hasBaseUnderline=baseAttrs.underline||baseAttrs.underlineStyle,hasOverlayUnderline=overlayAttrs.underline||overlayAttrs.underlineStyle;if(hasBaseUnderline||hasOverlayUnderline)attrs.underline=!0,attrs.underlineStyle=overlayAttrs.underlineStyle??baseAttrs.underlineStyle??"single";attrs.strikethrough=overlayAttrs.strikethrough||baseAttrs.strikethrough}else attrs.underline=overlayAttrs.underline??baseAttrs.underline,attrs.underlineStyle=overlayAttrs.underlineStyle??baseAttrs.underlineStyle,attrs.strikethrough=overlayAttrs.strikethrough??baseAttrs.strikethrough;if(preserveEmphasis)attrs.bold=overlayAttrs.bold||baseAttrs.bold,attrs.dim=overlayAttrs.dim||baseAttrs.dim,attrs.italic=overlayAttrs.italic||baseAttrs.italic;else attrs.bold=overlayAttrs.bold??baseAttrs.bold,attrs.dim=overlayAttrs.dim??baseAttrs.dim,attrs.italic=overlayAttrs.italic??baseAttrs.italic;return attrs.inverse=overlayAttrs.inverse,attrs.hidden=overlayAttrs.hidden,attrs.blink=overlayAttrs.blink,{fg:overlay.fg??base.fg,bg:overlay.bg??base.bg,underlineColor:overlay.underlineColor??base.underlineColor,attrs}}function mergeAnsiStyle(base,segment,options={}){let{preserveDecorations=!0,preserveEmphasis=!0}=options,fg=base.fg,bg=base.bg,underlineColor2=base.underlineColor??null;if(segment.fg!==void 0&&segment.fg!==null)fg=ansiColorToColor(segment.fg);if(segment.bg!==void 0&&segment.bg!==null)bg=ansiColorToColor(segment.bg);if(segment.underlineColor!==void 0&&segment.underlineColor!==null)underlineColor2=ansiColorToColor(segment.underlineColor);let overlayAttrs={};if(segment.bold!==void 0)overlayAttrs.bold=segment.bold;if(segment.dim!==void 0)overlayAttrs.dim=segment.dim;if(segment.italic!==void 0)overlayAttrs.italic=segment.italic;if(segment.underline!==void 0)overlayAttrs.underline=segment.underline;if(segment.underlineStyle!==void 0)overlayAttrs.underlineStyle=segment.underlineStyle;if(segment.inverse!==void 0)overlayAttrs.inverse=segment.inverse;let merged=mergeStyles(base,{fg,bg,underlineColor:underlineColor2,attrs:overlayAttrs},{preserveDecorations,preserveEmphasis});if(segment.hyperlink)merged.hyperlink=segment.hyperlink;return merged}function ansiColorToColor(code){if(code>=16777216){let r=code>>16&255,g=code>>8&255,b=code&255;return{r,g,b}}if(code<30||code>=38&&code<40||code>=48&&code<90)return code;if(code>=30&&code<=37)return code-30;if(code>=40&&code<=47)return code-40;if(code>=90&&code<=97)return code-90+8;if(code>=100&&code<=107)return code-100+8;return null}function renderText(node,buffer,layout,props,nodeState,inheritedBg,inheritedFg,ctx){let{scrollOffset,clipBounds}=nodeState,{x,width,height}=layout,{y}=layout;if(y-=scrollOffset,props.backgroundColor==="")inheritedBg=null;if(clipBounds){if(y+height<=clipBounds.top||y>=clipBounds.bottom)return;if(clipBounds.left!==void 0&&clipBounds.right!==void 0){if(x+width<=clipBounds.left||x>=clipBounds.right)return}}let maxDisplayWidth;if((props.wrap===!1||props.wrap==="truncate-end"||props.wrap==="truncate"||props.wrap==="clip")&&width>0){let cachedPlain=getCachedPlainText(node),lineCount;if(cachedPlain)lineCount=cachedPlain.lineCount;else{let plainText=collectPlainText(node);lineCount=(plainText.match(/\n/g)?.length??0)+1,setCachedPlainText(node,plainText,lineCount)}maxDisplayWidth=(width+1)*lineCount}let text,bgSegments,childSpans,cachedCollected=getCachedCollectedText(node,maxDisplayWidth);if(cachedCollected)text=cachedCollected.text,bgSegments=cachedCollected.bgSegments,childSpans=cachedCollected.childSpans;else{let collected=collectTextWithBg(node,{},0,maxDisplayWidth,ctx);text=collected.text,bgSegments=collected.bgSegments,childSpans=collected.childSpans,setCachedCollectedText(node,collected,maxDisplayWidth)}let style2=getTextStyle(props);if(style2.fg===null&&inheritedFg!==void 0)style2.fg=inheritedFg;let trim=!(style2.bg!==null||bgSegments.length>0||inheritedBg!==void 0&&inheritedBg!==null),internalTransform=props.internal_transform,lines,lineOffsets,cachedFmt=!internalTransform?getCachedFormat(node,width,props.wrap,trim):null;if(cachedFmt)lines=cachedFmt.lines,lineOffsets=cachedFmt.hasLineOffsets?cachedFmt.lineOffsets:[];else{if(lines=formatTextLines(text,width,props.wrap,ctx,trim),internalTransform)lines=lines.map((line,index)=>internalTransform(line,index));let needLineOffsets=bgSegments.length>0||childSpans.length>0;if(lineOffsets=needLineOffsets?mapLinesToCharOffsets(text,lines,ctx):[],!internalTransform)setCachedFormat(node,width,props.wrap,trim,lines,lineOffsets,needLineOffsets)}for(let lineIdx=0;lineIdx<lines.length&&lineIdx<height;lineIdx++){let lineY=y+lineIdx;if(clipBounds&&(lineY<clipBounds.top||lineY>=clipBounds.bottom))continue;let line=lines[lineIdx],layoutRight=internalTransform?buffer.width:x+width,maxCol=clipBounds&&"right"in clipBounds&&clipBounds.right!==void 0?Math.min(layoutRight,clipBounds.right):layoutRight,minCol=clipBounds&&"left"in clipBounds&&clipBounds.left!==void 0?clipBounds.left:void 0,endCol=renderTextLineReturn(buffer,x,lineY,line,style2,maxCol,inheritedBg,ctx,minCol),clearStart=minCol!==void 0?Math.max(endCol,minCol):endCol;if(clearStart<maxCol){let clearBg=inheritedBg??null;for(let cx=clearStart;cx<maxCol&&cx<buffer.width;cx++)buffer.setCell(cx,lineY,{char:" ",fg:style2.fg,bg:clearBg,underlineColor:null,attrs:{bold:!1,dim:!1,italic:!1,underline:!1,inverse:!1,strikethrough:!1,blink:!1,hidden:!1},wide:!1,continuation:!1})}if(bgSegments.length>0&&lineIdx<lineOffsets.length){let{start,end}=lineOffsets[lineIdx];applyBgSegmentsToLine(buffer,x,lineY,line,start,end,bgSegments,ctx)}}if(childSpans.length>0&&lineOffsets.length>0)computeInlineRects(childSpans,lineOffsets,x,y,lines.length,height)}function computeInlineRects(childSpans,lineOffsets,parentX,parentY,lineCount,maxHeight){for(let span of childSpans){let rects=[];for(let lineIdx=0;lineIdx<lineCount&&lineIdx<maxHeight;lineIdx++){let lineOffset=lineOffsets[lineIdx];if(!lineOffset)continue;let overlapStart=Math.max(span.start,lineOffset.start),overlapEnd=Math.min(span.end,lineOffset.end);if(overlapStart>=overlapEnd)continue;let rectX=parentX+(overlapStart-lineOffset.start),rectY=parentY+lineIdx,rectWidth=overlapEnd-overlapStart;rects.push({x:rectX,y:rectY,width:rectWidth,height:1})}span.node.inlineRects=rects.length>0?rects:null}}function getEffectiveBg(props){if(props.backgroundColor)return props.backgroundColor;if(props.theme)return props.theme.bg;return}function renderBox(_node,buffer,layout,props,nodeState,skipBgFill=!1,inheritedBg,bgOnlyChange=!1){let{scrollOffset,clipBounds}=nodeState,{x,width,height}=layout,y=layout.y-scrollOffset;if(clipBounds){if(y+height<=clipBounds.top||y>=clipBounds.bottom)return;if(clipBounds.left!==void 0&&clipBounds.right!==void 0){if(x+width<=clipBounds.left||x>=clipBounds.right)return}}let effectiveBgStr=getEffectiveBg(props);if(effectiveBgStr&&!skipBgFill){let bg=parseColor(effectiveBgStr);if(clipBounds){let clippedY=Math.max(y,clipBounds.top),clippedHeight=Math.min(y+height,clipBounds.bottom)-clippedY,clippedX=x,clippedWidth=width;if(clipBounds.left!==void 0&&clipBounds.right!==void 0)clippedX=Math.max(x,clipBounds.left),clippedWidth=Math.min(x+width,clipBounds.right)-clippedX;if(clippedHeight>0&&clippedWidth>0)if(bgOnlyChange)buffer.fillBg(clippedX,clippedY,clippedWidth,clippedHeight,bg);else buffer.fill(clippedX,clippedY,clippedWidth,clippedHeight,{bg})}else if(bgOnlyChange)buffer.fillBg(x,y,width,height,bg);else buffer.fill(x,y,width,height,{bg})}if(props.borderStyle)renderBorder(buffer,x,y,width,height,props,clipBounds,inheritedBg)}function renderBorder(buffer,x,y,width,height,props,clipBounds,inheritedBg){let chars=getBorderChars(props.borderStyle??"single"),color=props.borderColor?parseColor(props.borderColor):null,baseBg=props.backgroundColor?parseColor(props.backgroundColor):inheritedBg??null,borderBgStr=props.borderBackgroundColor,borderBgBase=borderBgStr?parseColor(borderBgStr):baseBg,topBorderBgStr=props.borderTopBackgroundColor,bottomBorderBgStr=props.borderBottomBackgroundColor,leftBorderBgStr=props.borderLeftBackgroundColor,rightBorderBgStr=props.borderRightBackgroundColor,topBg=topBorderBgStr?parseColor(topBorderBgStr):borderBgBase,bottomBg=bottomBorderBgStr?parseColor(bottomBorderBgStr):borderBgBase,leftBg=leftBorderBgStr?parseColor(leftBorderBgStr):borderBgBase,rightBg=rightBorderBgStr?parseColor(rightBorderBgStr):borderBgBase,showTop=props.borderTop!==!1,showBottom=props.borderBottom!==!1,showLeft=props.borderLeft!==!1,showRight=props.borderRight!==!1,isRowVisible=(row)=>{if(!clipBounds)return row>=0&&row<buffer.height;return row>=clipBounds.top&&row<clipBounds.bottom&&row<buffer.height},isColVisible=(col)=>{if(clipBounds?.left===void 0||clipBounds.right===void 0)return col>=0&&col<buffer.width;return col>=clipBounds.left&&col<clipBounds.right&&col<buffer.width};if(showTop&&isRowVisible(y)){if(showLeft&&isColVisible(x))buffer.setCell(x,y,{char:chars.topLeft,fg:color,bg:topBg});let hStart=showLeft?x+1:x,hEnd=showRight?x+width-1:x+width;for(let col=hStart;col<hEnd&&col<buffer.width;col++)if(isColVisible(col))buffer.setCell(col,y,{char:chars.horizontal,fg:color,bg:topBg});if(showRight&&x+width-1<buffer.width&&isColVisible(x+width-1))buffer.setCell(x+width-1,y,{char:chars.topRight,fg:color,bg:topBg})}let rightVertical=chars.rightVertical??chars.vertical,sideStart=showTop?y+1:y,sideEnd=showBottom?y+height-1:y+height;for(let row=sideStart;row<sideEnd;row++){if(!isRowVisible(row))continue;if(showLeft&&isColVisible(x))buffer.setCell(x,row,{char:chars.vertical,fg:color,bg:leftBg});if(showRight&&x+width-1<buffer.width&&isColVisible(x+width-1))buffer.setCell(x+width-1,row,{char:rightVertical,fg:color,bg:rightBg})}let bottomHorizontal=chars.bottomHorizontal??chars.horizontal,bottomY=y+height-1;if(showBottom&&isRowVisible(bottomY)){if(showLeft&&isColVisible(x))buffer.setCell(x,bottomY,{char:chars.bottomLeft,fg:color,bg:bottomBg});let bStart=showLeft?x+1:x,bEnd=showRight?x+width-1:x+width;for(let col=bStart;col<bEnd&&col<buffer.width;col++)if(isColVisible(col))buffer.setCell(col,bottomY,{char:bottomHorizontal,fg:color,bg:bottomBg});if(showRight&&x+width-1<buffer.width&&isColVisible(x+width-1))buffer.setCell(x+width-1,bottomY,{char:chars.bottomRight,fg:color,bg:bottomBg})}}function renderOutline(buffer,x,y,width,height,props,clipBounds,inheritedBg){let chars=getBorderChars(props.outlineStyle??"single"),color=props.outlineColor?parseColor(props.outlineColor):null,bg=props.backgroundColor?parseColor(props.backgroundColor):inheritedBg??null,attrs=props.outlineDimColor?{dim:!0}:{},isRowVisible=(row)=>{if(!clipBounds)return row>=0&&row<buffer.height;return row>=clipBounds.top&&row<clipBounds.bottom&&row<buffer.height},isColVisible=(col)=>{if(clipBounds?.left===void 0||clipBounds.right===void 0)return col>=0&&col<buffer.width;return col>=clipBounds.left&&col<clipBounds.right&&col<buffer.width},showTop=props.outlineTop!==!1,showBottom=props.outlineBottom!==!1,showLeft=props.outlineLeft!==!1,showRight=props.outlineRight!==!1;if(showTop&&isRowVisible(y)){if(showLeft&&isColVisible(x))buffer.setCell(x,y,{char:chars.topLeft,fg:color,bg,attrs});for(let col=x+1;col<x+width-1&&col<buffer.width;col++)if(isColVisible(col))buffer.setCell(col,y,{char:chars.horizontal,fg:color,bg,attrs});if(showRight&&x+width-1<buffer.width&&isColVisible(x+width-1))buffer.setCell(x+width-1,y,{char:chars.topRight,fg:color,bg,attrs})}let outlineRightVertical=chars.rightVertical??chars.vertical,sideStart=showTop?y+1:y,sideEnd=showBottom?y+height-1:y+height;for(let row=sideStart;row<sideEnd;row++){if(!isRowVisible(row))continue;if(showLeft&&isColVisible(x))buffer.setCell(x,row,{char:chars.vertical,fg:color,bg,attrs});if(showRight&&x+width-1<buffer.width&&isColVisible(x+width-1))buffer.setCell(x+width-1,row,{char:outlineRightVertical,fg:color,bg,attrs})}let outlineBottomHorizontal=chars.bottomHorizontal??chars.horizontal,bottomY=y+height-1;if(showBottom&&isRowVisible(bottomY)){if(showLeft&&isColVisible(x))buffer.setCell(x,bottomY,{char:chars.bottomLeft,fg:color,bg,attrs});for(let col=x+1;col<x+width-1&&col<buffer.width;col++)if(isColVisible(col))buffer.setCell(col,bottomY,{char:outlineBottomHorizontal,fg:color,bg,attrs});if(showRight&&x+width-1<buffer.width&&isColVisible(x+width-1))buffer.setCell(x+width-1,bottomY,{char:chars.bottomRight,fg:color,bg,attrs})}}function renderScrollIndicators(_node,buffer,layout,props,ss,ctx){let border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},indicatorStyle={fg:15,bg:8,attrs:{}},showBorderless=props.overflowIndicator===!0;if(ss.hiddenAbove>0){let indicator=`▲${ss.hiddenAbove}`;if(border.top>0){let contentWidth=layout.width-border.left-border.right,bar=padCenter(indicator,contentWidth),x=layout.x+border.left,y=layout.y,maxCol=x+contentWidth;renderTextLine(buffer,x,y,bar,indicatorStyle,maxCol,void 0,ctx)}else if(showBorderless){let padding=getPadding(props),contentWidth=layout.width-padding.left-padding.right,bar=padCenter(indicator,contentWidth),x=layout.x+padding.left,y=layout.y+padding.top,maxCol=x+contentWidth;renderTextLine(buffer,x,y,bar,indicatorStyle,maxCol,void 0,ctx)}}if(ss.hiddenBelow>0){let indicator=`▼${ss.hiddenBelow}`;if(border.bottom>0){let contentWidth=layout.width-border.left-border.right,bar=padCenter(indicator,contentWidth),x=layout.x+border.left,y=layout.y+layout.height-1,maxCol=x+contentWidth;renderTextLine(buffer,x,y,bar,indicatorStyle,maxCol,void 0,ctx)}else if(showBorderless){let padding=getPadding(props),contentWidth=layout.width-padding.left-padding.right,bar=padCenter(indicator,contentWidth),x=layout.x+padding.left,y=layout.y+layout.height-padding.bottom-1,maxCol=x+contentWidth;renderTextLine(buffer,x,y,bar,indicatorStyle,maxCol,void 0,ctx)}}}function padCenter(text,width){if(width<=0)return"";if(text.length>width)return text.slice(0,width);if(text.length===width)return text;let leftPad=Math.floor((width-text.length)/2),rightPad=width-text.length-leftPad;return" ".repeat(leftPad)+text+" ".repeat(rightPad)}init_state();function computeCascade(inputs){let{hasPrevBuffer,contentDirty,stylePropsDirty,layoutChanged,subtreeDirty,childrenDirty,childPositionChanged,ancestorLayoutChanged,ancestorCleared,bgDirty,isTextNode,hasBgColor,absoluteChildMutated,descendantOverflowChanged}=inputs,canSkipEntireSubtree=hasPrevBuffer&&!contentDirty&&!stylePropsDirty&&!layoutChanged&&!subtreeDirty&&!childrenDirty&&!childPositionChanged&&!ancestorLayoutChanged,textPaintDirty=isTextNode&&stylePropsDirty,contentAreaAffected=contentDirty||layoutChanged||childPositionChanged||childrenDirty||bgDirty||textPaintDirty||absoluteChildMutated||descendantOverflowChanged,bgOnlyAffected=bgDirty&&!contentDirty&&!layoutChanged&&!childPositionChanged&&!childrenDirty&&!textPaintDirty&&!absoluteChildMutated&&!descendantOverflowChanged,bgOnlyChange=!1,bgRefillNeeded=hasPrevBuffer&&!contentAreaAffected&&subtreeDirty&&hasBgColor;return{canSkipEntireSubtree,contentAreaAffected,bgRefillNeeded,contentRegionCleared:(hasPrevBuffer||ancestorCleared)&&contentAreaAffected&&!hasBgColor,skipBgFill:hasPrevBuffer&&!ancestorCleared&&!contentAreaAffected&&!bgRefillNeeded,childrenNeedFreshRender:(hasPrevBuffer||ancestorCleared)&&(contentAreaAffected||bgRefillNeeded)&&!0,bgOnlyChange:!1}}function createReactiveSystem({update,notify,unwatched}){return{link,unlink,propagate,checkDirty,shallowPropagate};function link(dep,sub,version){let prevDep=sub.depsTail;if(prevDep!==void 0&&prevDep.dep===dep)return;let nextDep=prevDep!==void 0?prevDep.nextDep:sub.deps;if(nextDep!==void 0&&nextDep.dep===dep){nextDep.version=version,sub.depsTail=nextDep;return}let prevSub=dep.subsTail;if(prevSub!==void 0&&prevSub.version===version&&prevSub.sub===sub)return;let newLink=sub.depsTail=dep.subsTail={version,dep,sub,prevDep,nextDep,prevSub,nextSub:void 0};if(nextDep!==void 0)nextDep.prevDep=newLink;if(prevDep!==void 0)prevDep.nextDep=newLink;else sub.deps=newLink;if(prevSub!==void 0)prevSub.nextSub=newLink;else dep.subs=newLink}function unlink(link2,sub=link2.sub){let{dep,prevDep,nextDep,nextSub,prevSub}=link2;if(nextDep!==void 0)nextDep.prevDep=prevDep;else sub.depsTail=prevDep;if(prevDep!==void 0)prevDep.nextDep=nextDep;else sub.deps=nextDep;if(nextSub!==void 0)nextSub.prevSub=prevSub;else dep.subsTail=prevSub;if(prevSub!==void 0)prevSub.nextSub=nextSub;else if((dep.subs=nextSub)===void 0)unwatched(dep);return nextDep}function propagate(link2){let next=link2.nextSub,stack;top:do{let sub=link2.sub,flags=sub.flags;if(!(flags&60))sub.flags=flags|32;else if(!(flags&12))flags=0;else if(!(flags&4))sub.flags=flags&-9|32;else if(!(flags&48)&&isValidLink(link2,sub))sub.flags=flags|40,flags&=1;else flags=0;if(flags&2)notify(sub);if(flags&1){let subSubs=sub.subs;if(subSubs!==void 0){let nextSub=(link2=subSubs).nextSub;if(nextSub!==void 0)stack={value:next,prev:stack},next=nextSub;continue}}if((link2=next)!==void 0){next=link2.nextSub;continue}while(stack!==void 0)if(link2=stack.value,stack=stack.prev,link2!==void 0){next=link2.nextSub;continue top}break}while(!0)}function checkDirty(link2,sub){let stack,checkDepth=0,dirty=!1;top:do{let dep=link2.dep,flags=dep.flags;if(sub.flags&16)dirty=!0;else if((flags&17)===17){if(update(dep)){let subs=dep.subs;if(subs.nextSub!==void 0)shallowPropagate(subs);dirty=!0}}else if((flags&33)===33){if(link2.nextSub!==void 0||link2.prevSub!==void 0)stack={value:link2,prev:stack};link2=dep.deps,sub=dep,++checkDepth;continue}if(!dirty){let nextDep=link2.nextDep;if(nextDep!==void 0){link2=nextDep;continue}}while(checkDepth--){let firstSub=sub.subs,hasMultipleSubs=firstSub.nextSub!==void 0;if(hasMultipleSubs)link2=stack.value,stack=stack.prev;else link2=firstSub;if(dirty){if(update(sub)){if(hasMultipleSubs)shallowPropagate(firstSub);sub=link2.sub;continue}dirty=!1}else sub.flags&=-33;sub=link2.sub;let nextDep=link2.nextDep;if(nextDep!==void 0){link2=nextDep;continue top}}return dirty}while(!0)}function shallowPropagate(link2){do{let sub=link2.sub,flags=sub.flags;if((flags&48)===32){if(sub.flags=flags|16,(flags&6)===2)notify(sub)}}while((link2=link2.nextSub)!==void 0)}function isValidLink(checkLink,sub){let link2=sub.depsTail;while(link2!==void 0){if(link2===checkLink)return!0;link2=link2.prevDep}return!1}}var cycle=0,batchDepth=0,notifyIndex=0,queuedLength=0,activeSub,queued=[],{link,unlink,propagate,checkDirty,shallowPropagate}=createReactiveSystem({update(node){if(node.depsTail!==void 0)return updateComputed(node);else return updateSignal(node)},notify(effect){let insertIndex=queuedLength,firstInsertedIndex=insertIndex;do if(queued[insertIndex++]=effect,effect.flags&=-3,effect=effect.subs?.sub,effect===void 0||!(effect.flags&2))break;while(!0);queuedLength=insertIndex;while(firstInsertedIndex<--insertIndex){let left=queued[firstInsertedIndex];queued[firstInsertedIndex++]=queued[insertIndex],queued[insertIndex]=left}},unwatched(node){if(!(node.flags&1))effectScopeOper.call(node);else if(node.depsTail!==void 0)node.depsTail=void 0,node.flags=17,purgeDeps(node)}});function setActiveSub(sub){let prevSub=activeSub;return activeSub=sub,prevSub}function signal(initialValue){return signalOper.bind({currentValue:initialValue,pendingValue:initialValue,subs:void 0,subsTail:void 0,flags:1})}function computed(getter){return computedOper.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:0,getter})}function updateComputed(c){++cycle,c.depsTail=void 0,c.flags=5;let prevSub=setActiveSub(c);try{let oldValue=c.value;return oldValue!==(c.value=c.getter(oldValue))}finally{activeSub=prevSub,c.flags&=-5,purgeDeps(c)}}function updateSignal(s){return s.flags=1,s.currentValue!==(s.currentValue=s.pendingValue)}function run(e){let flags=e.flags;if(flags&16||flags&32&&checkDirty(e.deps,e)){++cycle,e.depsTail=void 0,e.flags=6;let prevSub=setActiveSub(e);try{e.fn()}finally{activeSub=prevSub,e.flags&=-5,purgeDeps(e)}}else e.flags=2}function flush(){try{while(notifyIndex<queuedLength){let effect=queued[notifyIndex];queued[notifyIndex++]=void 0,run(effect)}}finally{while(notifyIndex<queuedLength){let effect=queued[notifyIndex];queued[notifyIndex++]=void 0,effect.flags|=10}notifyIndex=0,queuedLength=0}}function computedOper(){let flags=this.flags;if(flags&16||flags&32&&(checkDirty(this.deps,this)||(this.flags=flags&-33,!1))){if(updateComputed(this)){let subs=this.subs;if(subs!==void 0)shallowPropagate(subs)}}else if(!flags){this.flags=5;let prevSub=setActiveSub(this);try{this.value=this.getter()}finally{activeSub=prevSub,this.flags&=-5}}let sub=activeSub;if(sub!==void 0)link(this,sub,cycle);return this.value}function signalOper(...value){if(value.length){if(this.pendingValue!==(this.pendingValue=value[0])){this.flags=17;let subs=this.subs;if(subs!==void 0){if(propagate(subs),!batchDepth)flush()}}}else{if(this.flags&16){if(updateSignal(this)){let subs=this.subs;if(subs!==void 0)shallowPropagate(subs)}}let sub=activeSub;while(sub!==void 0){if(sub.flags&3){link(this,sub,cycle);break}sub=sub.subs?.sub}return this.currentValue}}function effectScopeOper(){this.depsTail=void 0,this.flags=0,purgeDeps(this);let sub=this.subs;if(sub!==void 0)unlink(sub)}function purgeDeps(sub){let depsTail=sub.depsTail,dep=depsTail!==void 0?depsTail.nextDep:sub.deps;while(dep!==void 0)dep=unlink(dep,sub)}function createReactiveNodeState(){let contentDirty=signal(!1),stylePropsDirty=signal(!1),bgDirty=signal(!1),childrenDirty=signal(!1),subtreeDirty=signal(!1),layoutChanged=signal(!1),hasPrevBuffer=signal(!1),childPositionChanged=signal(!1),ancestorLayoutChanged=signal(!1),ancestorCleared=signal(!1),isTextNode=signal(!1),hasBgColor=signal(!1),absoluteChildMutated=signal(!1),descendantOverflowChanged=signal(!1),canSkipEntireSubtree=computed(()=>hasPrevBuffer()&&!contentDirty()&&!stylePropsDirty()&&!layoutChanged()&&!subtreeDirty()&&!childrenDirty()&&!childPositionChanged()&&!ancestorLayoutChanged()),textPaintDirty=computed(()=>isTextNode()&&stylePropsDirty()),contentAreaAffected=computed(()=>contentDirty()||layoutChanged()||childPositionChanged()||childrenDirty()||bgDirty()||textPaintDirty()||absoluteChildMutated()||descendantOverflowChanged()),bgOnlyChange=computed(()=>!1),bgRefillNeeded=computed(()=>hasPrevBuffer()&&!contentAreaAffected()&&subtreeDirty()&&hasBgColor()),contentRegionCleared=computed(()=>(hasPrevBuffer()||ancestorCleared())&&contentAreaAffected()&&!hasBgColor()),skipBgFill=computed(()=>hasPrevBuffer()&&!ancestorCleared()&&!contentAreaAffected()&&!bgRefillNeeded()),childrenNeedFreshRender=computed(()=>(hasPrevBuffer()||ancestorCleared())&&(contentAreaAffected()||bgRefillNeeded())&&!bgOnlyChange());return{contentDirty,stylePropsDirty,bgDirty,childrenDirty,subtreeDirty,layoutChanged,hasPrevBuffer,childPositionChanged,ancestorLayoutChanged,ancestorCleared,isTextNode,hasBgColor,absoluteChildMutated,descendantOverflowChanged,canSkipEntireSubtree,textPaintDirty,contentAreaAffected,bgRefillNeeded,contentRegionCleared,skipBgFill,childrenNeedFreshRender,bgOnlyChange}}function syncToSignals(state,node,ctx){state.contentDirty(isDirty(node.dirtyBits,node.dirtyEpoch,CONTENT_BIT)),state.stylePropsDirty(isDirty(node.dirtyBits,node.dirtyEpoch,STYLE_PROPS_BIT)),state.bgDirty(isDirty(node.dirtyBits,node.dirtyEpoch,BG_BIT)),state.childrenDirty(isDirty(node.dirtyBits,node.dirtyEpoch,CHILDREN_BIT)),state.subtreeDirty(isDirty(node.dirtyBits,node.dirtyEpoch,SUBTREE_BIT)),state.layoutChanged(ctx.layoutChanged),state.hasPrevBuffer(ctx.hasPrevBuffer),state.childPositionChanged(ctx.childPositionChanged),state.ancestorLayoutChanged(ctx.ancestorLayoutChanged),state.ancestorCleared(ctx.ancestorCleared),state.isTextNode(node.type==="silvery-text"),state.hasBgColor(ctx.hasBgColor),state.absoluteChildMutated(ctx.absoluteChildMutated),state.descendantOverflowChanged(ctx.descendantOverflowChanged)}function readReactiveCascade(state){return{canSkipEntireSubtree:state.canSkipEntireSubtree(),contentAreaAffected:state.contentAreaAffected(),bgRefillNeeded:state.bgRefillNeeded(),contentRegionCleared:state.contentRegionCleared(),skipBgFill:state.skipBgFill(),childrenNeedFreshRender:state.childrenNeedFreshRender(),bgOnlyChange:state.bgOnlyChange()}}function assertReactiveMatchesOracle(state,oracle,nodeId){let fields=["canSkipEntireSubtree","contentAreaAffected","bgRefillNeeded","contentRegionCleared","skipBgFill","childrenNeedFreshRender","bgOnlyChange"],mismatches=[];for(let field of fields){let reactiveValue=state[field](),oracleValue=oracle[field];if(reactiveValue!==oracleValue)mismatches.push(` ${field}: reactive=${reactiveValue}, oracle=${oracleValue}`)}if(mismatches.length>0)throw Error(`ReactiveNodeState mismatch for ${nodeId||"(unnamed)"}:
75
+ ${mismatches.join(`
76
+ `)}`)}var nodeStates=new WeakMap;function getReactiveState(node){let state=nodeStates.get(node);if(!state)state=createReactiveNodeState(),nodeStates.set(node,state);return state}var contentLog=createLogger7("silvery:content"),traceLog=createLogger7("silvery:content:trace"),cellLog=createLogger7("silvery:content:cell");function renderPhase(root,prevBuffer,ctx){let layout=root.boxRect;if(!layout)throw Error("renderPhase called before layout phase");let instr=resolveInstrumentation(ctx),hasPrevBuffer=prevBuffer&&prevBuffer.width===layout.width&&prevBuffer.height===layout.height;if(instr.enabled)instr.stats._prevBufferNull=prevBuffer==null?1:0,instr.stats._prevBufferDimMismatch=prevBuffer&&!hasPrevBuffer?1:0,instr.stats._hasPrevBuffer=hasPrevBuffer?1:0,instr.stats._layoutW=layout.width,instr.stats._layoutH=layout.height,instr.stats._prevW=prevBuffer?.width??0,instr.stats._prevH=prevBuffer?.height??0;let t0=instr.enabled?performance.now():0,buffer=hasPrevBuffer?prevBuffer.clone():new TerminalBuffer(layout.width,layout.height),tClone=instr.enabled?performance.now()-t0:0;buffer.setSelectableMode(!0);let t1=instr.enabled?performance.now():0;renderNodeToBuffer(root,buffer,{scrollOffset:0,clipBounds:void 0,hasPrevBuffer:!!hasPrevBuffer,ancestorCleared:!1,bufferIsCloned:!!hasPrevBuffer,ancestorLayoutChanged:!1,inheritedBg:{color:null,ancestorRect:null},inheritedFg:null},ctx);let tRender=instr.enabled?performance.now()-t1:0;if(instr.enabled)emitRenderPhaseStats(instr.stats,instr.nodeTrace,instr.nodeTraceEnabled,tClone,tRender);return syncPrevLayout(root),advanceRenderEpoch(),buffer}function syncPrevLayout(root){let stack=[root];while(stack.length>0){let node=stack.pop();node.prevLayout=node.boxRect;let children=node.children;for(let i=children.length-1;i>=0;i--)stack.push(children[i])}}function envTruthy(val){return!!val&&val!=="0"&&val!=="false"}var _instrumentEnabled=typeof process<"u"&&(envTruthy(process.env?.SILVERY_STRICT)||envTruthy(process.env?.SILVERY_INSTRUMENT)),_renderPhaseStats={nodesVisited:0,nodesRendered:0,nodesSkipped:0,textNodes:0,boxNodes:0,clearOps:0,noPrevBuffer:0,flagContentDirty:0,flagStylePropsDirty:0,flagLayoutChanged:0,flagSubtreeDirty:0,flagChildrenDirty:0,flagChildPositionChanged:0,flagAncestorLayoutChanged:0,scrollContainerCount:0,scrollViewportCleared:0,scrollClearReason:"",normalChildrenRepaint:0,normalRepaintReason:"",cascadeMinDepth:999,cascadeNodes:"",_prevBufferNull:0,_prevBufferDimMismatch:0,_hasPrevBuffer:0,_layoutW:0,_layoutH:0,_prevW:0,_prevH:0,_callCount:0},_renderPhaseCallCount=0,_nodeTrace=[],_nodeTraceEnabled=typeof process<"u"&&envTruthy(process.env?.SILVERY_STRICT),_reactiveEnabled=typeof process>"u"||process.env?.SILVERY_REACTIVE!=="0",_reactiveVerifyEnabled=_reactiveEnabled&&typeof process<"u"&&envTruthy(process.env?.SILVERY_STRICT);function resolveInstrumentation(ctx){return{enabled:ctx?.instrumentEnabled??_instrumentEnabled,stats:ctx?.stats??_renderPhaseStats,nodeTrace:ctx?.nodeTrace??_nodeTrace,nodeTraceEnabled:ctx?.nodeTraceEnabled??_nodeTraceEnabled}}function getCellDebug(){return globalThis.__silvery_cell_debug}function cellCoversPoint(cellDbg,x,y,width,height){return x<=cellDbg.x&&x+width>cellDbg.x&&y<=cellDbg.y&&y+height>cellDbg.y}function _getNodeDepth(node){let depth=0,n=node.parent;while(n)depth++,n=n.parent;return depth}function emitRenderPhaseStats(stats,nodeTrace,nodeTraceEnabled,tClone,tRender){_renderPhaseCallCount++,stats._callCount=_renderPhaseCallCount;let snap={clone:tClone,render:tRender,...structuredClone(stats)};globalThis.__silvery_content_detail=snap,(globalThis.__silvery_content_all??=[]).push(snap),contentLog.debug?.(`frame ${snap._callCount}: ${snap.nodesRendered}/${snap.nodesVisited} rendered, ${snap.nodesSkipped} skipped (${tClone.toFixed(1)}ms clone, ${tRender.toFixed(1)}ms render)`);for(let key of Object.keys(stats))stats[key]=0;if(stats.cascadeMinDepth=999,stats.cascadeNodes="",stats.scrollClearReason="",stats.normalRepaintReason="",nodeTraceEnabled&&nodeTrace.length>0)(globalThis.__silvery_node_trace??=[]).push([...nodeTrace]),traceLog.debug?.(`${nodeTrace.length} nodes traced`),nodeTrace.length=0}function renderNodeToBuffer(node,buffer,nodeState,ctx){let{scrollOffset,clipBounds,hasPrevBuffer,ancestorCleared,bufferIsCloned,ancestorLayoutChanged=!1}=nodeState,instr=resolveInstrumentation(ctx);if(instr.enabled)instr.stats.nodesVisited++;let layout=node.boxRect;if(!layout)return;if(!node.layoutNode){clearVirtualTextFlags(node);return}if(node.hidden){clearDirtyFlags(node);return}let props=node.props,prevSelectableMode=buffer.getSelectableMode(),userSelect=props.userSelect;if(userSelect==="none")buffer.setSelectableMode(!1);else if(userSelect==="text"||userSelect==="contain")buffer.setSelectableMode(!0);if(props.display==="none"){clearDirtyFlags(node),buffer.setSelectableMode(prevSelectableMode);return}let screenY=layout.y-scrollOffset;if(screenY>=buffer.height||screenY+layout.height<=0){buffer.setSelectableMode(prevSelectableMode);return}let layoutChanged=isCurrentEpoch(node.layoutChangedThisFrame),childPositionChanged=!!(hasPrevBuffer&&!layoutChanged&&hasChildPositionChanged(node)),scrollOffsetChanged=!!(node.scrollState&&node.scrollState.offset!==node.scrollState.prevOffset),canSkipEntireSubtree=hasPrevBuffer&&!isDirty(node.dirtyBits,node.dirtyEpoch,CONTENT_BIT)&&!isDirty(node.dirtyBits,node.dirtyEpoch,STYLE_PROPS_BIT)&&!layoutChanged&&!isDirty(node.dirtyBits,node.dirtyEpoch,SUBTREE_BIT)&&!isDirty(node.dirtyBits,node.dirtyEpoch,CHILDREN_BIT)&&!childPositionChanged&&!ancestorLayoutChanged&&!scrollOffsetChanged,_nodeId=instr.enabled?props.id??"":"",_traceThis=instr.enabled&&instr.nodeTraceEnabled&&_nodeId,_cellDbg=getCellDebug(),_coversCellNow=_cellDbg&&cellCoversPoint(_cellDbg,layout.x,screenY,layout.width,layout.height),_coversCellPrev=_cellDbg&&node.prevLayout&&cellCoversPoint(_cellDbg,node.prevLayout.x,node.prevLayout.y-scrollOffset,node.prevLayout.width,node.prevLayout.height);if(canSkipEntireSubtree){if(_cellDbg&&(_coversCellNow||_coversCellPrev)){let id=props.id??node.type,depth=_getNodeDepth(node),prev=node.prevLayout,msg=`SKIP ${id}@${depth} rect=${layout.x},${screenY} ${layout.width}x${layout.height} prev=${prev?`${prev.x},${prev.y-scrollOffset} ${prev.width}x${prev.height}`:"null"} coversNow=${_coversCellNow} coversPrev=${_coversCellPrev}`;_cellDbg.log.push(msg),cellLog.debug?.(msg)}if(instr.enabled){if(instr.stats.nodesSkipped++,_traceThis)instr.nodeTrace.push({id:_nodeId,type:node.type,depth:_getNodeDepth(node),rect:`${layout.x},${layout.y} ${layout.width}x${layout.height}`,prevLayout:node.prevLayout?`${node.prevLayout.x},${node.prevLayout.y} ${node.prevLayout.width}x${node.prevLayout.height}`:"null",hasPrev:hasPrevBuffer,ancestorCleared,flags:"",decision:"SKIPPED",layoutChanged})}clearDirtyFlags(node),buffer.setSelectableMode(prevSelectableMode);return}if(instr.enabled){if(instr.stats.nodesRendered++,!hasPrevBuffer)instr.stats.noPrevBuffer++;if(isDirty(node.dirtyBits,node.dirtyEpoch,CONTENT_BIT))instr.stats.flagContentDirty++;if(isDirty(node.dirtyBits,node.dirtyEpoch,STYLE_PROPS_BIT))instr.stats.flagStylePropsDirty++;if(layoutChanged)instr.stats.flagLayoutChanged++;if(isDirty(node.dirtyBits,node.dirtyEpoch,SUBTREE_BIT))instr.stats.flagSubtreeDirty++;if(isDirty(node.dirtyBits,node.dirtyEpoch,CHILDREN_BIT))instr.stats.flagChildrenDirty++;if(childPositionChanged)instr.stats.flagChildPositionChanged++;if(ancestorLayoutChanged)instr.stats.flagAncestorLayoutChanged++}let nodeTheme=props.theme;if(nodeTheme)pushContextTheme(nodeTheme);try{let isScrollContainer=props.overflow==="scroll"&&node.scrollState,{absoluteChildMutated,descendantOverflowChanged}=buildCascadeInputs(node,hasPrevBuffer),cascadeInputs={hasPrevBuffer,contentDirty:isDirty(node.dirtyBits,node.dirtyEpoch,CONTENT_BIT),stylePropsDirty:isDirty(node.dirtyBits,node.dirtyEpoch,STYLE_PROPS_BIT),layoutChanged,subtreeDirty:isDirty(node.dirtyBits,node.dirtyEpoch,SUBTREE_BIT),childrenDirty:isDirty(node.dirtyBits,node.dirtyEpoch,CHILDREN_BIT),childPositionChanged,ancestorLayoutChanged,ancestorCleared,bgDirty:isDirty(node.dirtyBits,node.dirtyEpoch,BG_BIT),isTextNode:node.type==="silvery-text",hasBgColor:!!getEffectiveBg(props),absoluteChildMutated,descendantOverflowChanged},cascade;if(_reactiveEnabled){let reactiveState=getReactiveState(node);if(syncToSignals(reactiveState,node,{hasPrevBuffer,layoutChanged,childPositionChanged,ancestorLayoutChanged,ancestorCleared,absoluteChildMutated,descendantOverflowChanged,hasBgColor:cascadeInputs.hasBgColor}),cascade=readReactiveCascade(reactiveState),_reactiveVerifyEnabled)assertReactiveMatchesOracle(reactiveState,computeCascade(cascadeInputs),props.id??node.type)}else cascade=computeCascade(cascadeInputs);if(cascade.bgOnlyChange&&hasDescendantWithBg(node)){let childrenNeedFreshRender2=(hasPrevBuffer||ancestorCleared)&&(cascade.contentAreaAffected||cascade.bgRefillNeeded);cascade={...cascade,bgOnlyChange:!1,childrenNeedFreshRender:childrenNeedFreshRender2}}let{contentRegionCleared,skipBgFill,childrenNeedFreshRender}=cascade;if(instr.enabled||_cellDbg&&(_coversCellNow||_coversCellPrev))traceRenderDecision(node,props,layout,screenY,scrollOffset,hasPrevBuffer,ancestorCleared,layoutChanged,childPositionChanged,cascade,_nodeId,_traceThis,_cellDbg,_coversCellNow,_coversCellPrev,instr.enabled,instr.stats,instr.nodeTrace);let useTextStyleFastPath=!1;executeRegionClearing(node,buffer,layout,scrollOffset,clipBounds,bufferIsCloned,layoutChanged,useTextStyleFastPath?!1:contentRegionCleared,descendantOverflowChanged,instr.enabled,instr.stats,nodeState.inheritedBg);let needsOwnRepaint=!hasPrevBuffer||ancestorCleared||ancestorLayoutChanged||cascade.contentAreaAffected||isDirty(node.dirtyBits,node.dirtyEpoch,STYLE_PROPS_BIT)||cascade.bgRefillNeeded,boxInheritedBg=node.type==="silvery-box"&&!getEffectiveBg(props)?nodeState.inheritedBg.color:void 0;if(needsOwnRepaint)renderOwnContent(node,buffer,layout,props,nodeState,skipBgFill,instr.enabled,instr.stats,ctx,cascade.bgOnlyChange,useTextStyleFastPath);let effectiveBg=getEffectiveBg(props),childInheritedBg=effectiveBg?{color:parseColor(effectiveBg),ancestorRect:node.boxRect}:nodeTheme?{color:parseColor(nodeTheme.bg),ancestorRect:node.boxRect}:nodeState.inheritedBg,childInheritedFg=props.color?parseColor(props.color):nodeTheme?parseColor(nodeTheme.fg):nodeState.inheritedFg,childState={...nodeState,inheritedBg:childInheritedBg,inheritedFg:childInheritedFg};if(isScrollContainer)renderScrollContainerChildren(node,buffer,props,childState,contentRegionCleared,childrenNeedFreshRender,ctx),renderScrollIndicators(node,buffer,layout,props,node.scrollState,ctx);else renderNormalChildren(node,buffer,props,childState,childPositionChanged,contentRegionCleared,childrenNeedFreshRender,ctx);if(node.type==="silvery-box"&&props.outlineStyle){let{x,width,height}=layout,y=layout.y-scrollOffset;renderOutline(buffer,x,y,width,height,props,clipBounds,boxInheritedBg)}clearNodeDirtyFlags(node)}finally{if(nodeTheme)popContextTheme();buffer.setSelectableMode(prevSelectableMode)}}function buildCascadeInputs(node,hasPrevBuffer){if(!hasPrevBuffer||!isDirty(node.dirtyBits,node.dirtyEpoch,SUBTREE_BIT)||node.children===void 0)return{absoluteChildMutated:!1,descendantOverflowChanged:!1};return{absoluteChildMutated:isDirty(node.dirtyBits,node.dirtyEpoch,ABS_CHILD_BIT),descendantOverflowChanged:isDirty(node.dirtyBits,node.dirtyEpoch,DESC_OVERFLOW_BIT)}}function traceRenderDecision(node,props,layout,screenY,scrollOffset,hasPrevBuffer,ancestorCleared,layoutChanged,childPositionChanged,cascade,_nodeId,_traceThis,_cellDbg,_coversCellNow,_coversCellPrev,instrumentEnabled,stats,nodeTrace){let{contentAreaAffected,contentRegionCleared,skipBgFill,childrenNeedFreshRender}=cascade;if(instrumentEnabled){if(_traceThis){let flagStr=[isDirty(node.dirtyBits,node.dirtyEpoch,CONTENT_BIT)&&"C",isDirty(node.dirtyBits,node.dirtyEpoch,STYLE_PROPS_BIT)&&"P",isDirty(node.dirtyBits,node.dirtyEpoch,BG_BIT)&&"B",isDirty(node.dirtyBits,node.dirtyEpoch,SUBTREE_BIT)&&"S",isDirty(node.dirtyBits,node.dirtyEpoch,CHILDREN_BIT)&&"Ch",childPositionChanged&&"CP"].filter(Boolean).join(","),childHasPrev_=isDirty(node.dirtyBits,node.dirtyEpoch,CHILDREN_BIT)||childPositionChanged||childrenNeedFreshRender?!1:hasPrevBuffer,childAncestorCleared_=contentRegionCleared||ancestorCleared&&!getEffectiveBg(props);nodeTrace.push({id:_nodeId,type:node.type,depth:_getNodeDepth(node),rect:`${layout.x},${layout.y} ${layout.width}x${layout.height}`,prevLayout:node.prevLayout?`${node.prevLayout.x},${node.prevLayout.y} ${node.prevLayout.width}x${node.prevLayout.height}`:"null",hasPrev:hasPrevBuffer,ancestorCleared,flags:flagStr,decision:"RENDER",layoutChanged,contentAreaAffected,contentRegionCleared,childrenNeedFreshRender,childHasPrev:childHasPrev_,childAncestorCleared:childAncestorCleared_,skipBgFill,bgColor:props.backgroundColor})}if(childrenNeedFreshRender&&node.children.length>0){let depth=_getNodeDepth(node);if(depth<stats.cascadeMinDepth)stats.cascadeMinDepth=depth;let id=node.props.id??node.type,flags=[isDirty(node.dirtyBits,node.dirtyEpoch,CONTENT_BIT)&&"C",isDirty(node.dirtyBits,node.dirtyEpoch,STYLE_PROPS_BIT)&&"P",isDirty(node.dirtyBits,node.dirtyEpoch,CHILDREN_BIT)&&"Ch",layoutChanged&&"L",childPositionChanged&&"CP"].filter(Boolean).join(""),entry=`${id}@${depth}[${flags}:${node.children.length}ch]`;stats.cascadeNodes+=(stats.cascadeNodes?" ":"")+entry}}if(_cellDbg&&(_coversCellNow||_coversCellPrev)){let id=props.id??node.type,depth=_getNodeDepth(node),prev=node.prevLayout,flags=[isDirty(node.dirtyBits,node.dirtyEpoch,CONTENT_BIT)&&"C",isDirty(node.dirtyBits,node.dirtyEpoch,STYLE_PROPS_BIT)&&"P",layoutChanged&&"L",isDirty(node.dirtyBits,node.dirtyEpoch,SUBTREE_BIT)&&"S",isDirty(node.dirtyBits,node.dirtyEpoch,CHILDREN_BIT)&&"Ch",childPositionChanged&&"CP",isDirty(node.dirtyBits,node.dirtyEpoch,BG_BIT)&&"B"].filter(Boolean).join(","),msg=`RENDER ${id}@${depth} rect=${layout.x},${screenY} ${layout.width}x${layout.height} prev=${prev?`${prev.x},${prev.y-scrollOffset} ${prev.width}x${prev.height}`:"null"} flags=[${flags}] hasPrev=${hasPrevBuffer} ancClr=${ancestorCleared} caa=${contentAreaAffected} prc=${contentRegionCleared} prm=${childrenNeedFreshRender} coversNow=${_coversCellNow} coversPrev=${_coversCellPrev} bg=${props.backgroundColor??"none"}`;_cellDbg.log.push(msg),cellLog.debug?.(msg)}}function executeRegionClearing(node,buffer,layout,scrollOffset,clipBounds,bufferIsCloned,layoutChanged,contentRegionCleared,descendantOverflowChanged,instrumentEnabled,stats,threadedInheritedBg){if(contentRegionCleared){if(instrumentEnabled)stats.clearOps++;clearNodeRegion(node,buffer,layout,scrollOffset,clipBounds,layoutChanged,threadedInheritedBg)}else if(bufferIsCloned&&layoutChanged&&node.prevLayout)clearExcessArea(node,buffer,layout,scrollOffset,clipBounds,layoutChanged,threadedInheritedBg);if(descendantOverflowChanged)clearDescendantOverflowRegions(node,buffer,layout,scrollOffset,clipBounds,threadedInheritedBg)}function renderOwnContent(node,buffer,layout,props,nodeState,skipBgFill,instrumentEnabled,stats,ctx,bgOnlyChange=!1,useTextStyleFastPath=!1){let boxInheritedBg=node.type==="silvery-box"&&!getEffectiveBg(props)?nodeState.inheritedBg.color:void 0;if(node.type==="silvery-box"){if(instrumentEnabled)stats.boxNodes++;renderBox(node,buffer,layout,props,nodeState,skipBgFill,boxInheritedBg,bgOnlyChange)}else if(node.type==="silvery-text"){if(instrumentEnabled)stats.textNodes++;let textInheritedBg=nodeState.inheritedBg.color,textInheritedFg=nodeState.inheritedFg;if(useTextStyleFastPath){let style2=getTextStyle(props);if(style2.fg===null&&textInheritedFg!==void 0)style2.fg=textInheritedFg;let effectiveBg=style2.bg!==null?style2.bg:textInheritedBg??null,{x,width,height}=layout,y=layout.y-nodeState.scrollOffset;buffer.restyleRegion(x,y,width,height,{fg:style2.fg,bg:effectiveBg,underlineColor:style2.underlineColor??null,attrs:style2.attrs})}else renderText(node,buffer,layout,props,nodeState,textInheritedBg,textInheritedFg,ctx)}return boxInheritedBg}function planScrollRender(inputs){let{scrollOffsetChanged,visibleRangeChanged,hasStickyChildren,childrenNeedFreshRender,childrenDirty,hasPrevBuffer,ancestorCleared,contentRegionCleared,scrollBg}=inputs,scrollOnly=hasPrevBuffer&&scrollOffsetChanged&&!childrenDirty&&!childrenNeedFreshRender&&!hasStickyChildren&&!visibleRangeChanged,needsViewportClear=hasPrevBuffer&&!scrollOnly&&(scrollOffsetChanged||childrenDirty||childrenNeedFreshRender||visibleRangeChanged),stickyForceRefresh=hasStickyChildren&&hasPrevBuffer&&!needsViewportClear,reasons=[];if(scrollOnly)reasons.push("SHIFT");if(needsViewportClear){if(scrollOffsetChanged)reasons.push("scrollOffset");if(childrenDirty)reasons.push("childrenDirty");if(childrenNeedFreshRender)reasons.push("childrenNeedFreshRender");if(visibleRangeChanged)reasons.push("visibleRangeChanged")}if(stickyForceRefresh)reasons.push("stickyForceRefresh");return{tier:scrollOnly?"shift":needsViewportClear?"clear":"subtree-only",clearBg:scrollOnly||needsViewportClear?scrollBg:null,childHasPrev:needsViewportClear?!1:hasPrevBuffer,childAncestorCleared:needsViewportClear?!0:ancestorCleared||contentRegionCleared,stickyForceRefresh,reasons}}function renderScrollContainerChildren(node,buffer,props,nodeState,contentRegionCleared=!1,childrenNeedFreshRender=!1,ctx){let{clipBounds,hasPrevBuffer,ancestorCleared,bufferIsCloned,ancestorLayoutChanged,inheritedBg,inheritedFg}=nodeState,instr=resolveInstrumentation(ctx),layout=node.boxRect,ss=node.scrollState;if(!layout||!ss)return;let border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},padding=getPadding(props),childClipBounds=computeChildClipBounds(layout,props,clipBounds,0,!1,!0),scrollOffsetChanged=ss.offset!==ss.prevOffset,hasStickyChildren=!!(ss.stickyChildren&&ss.stickyChildren.length>0),visibleRangeChanged=ss.firstVisibleChild!==ss.prevFirstVisibleChild||ss.lastVisibleChild!==ss.prevLastVisibleChild,clearY=childClipBounds.top,clearHeight=childClipBounds.bottom-childClipBounds.top,contentX=layout.x+border.left+padding.left,contentWidth=layout.width-border.left-border.right-padding.left-padding.right,scrollBg=scrollOffsetChanged||isDirty(node.dirtyBits,node.dirtyEpoch,CHILDREN_BIT)||childrenNeedFreshRender||visibleRangeChanged?getEffectiveBg(props)?parseColor(getEffectiveBg(props)):inheritedBg.color:null,plan=planScrollRender({scrollOffsetChanged,visibleRangeChanged,hasStickyChildren,childrenNeedFreshRender,childrenDirty:isDirty(node.dirtyBits,node.dirtyEpoch,CHILDREN_BIT),hasPrevBuffer,ancestorCleared,contentRegionCleared,scrollBg}),{tier,stickyForceRefresh}=plan,defaultChildHasPrev=plan.childHasPrev,defaultChildAncestorCleared=plan.childAncestorCleared;if(instr.enabled){if(instr.stats.scrollContainerCount++,tier!=="subtree-only"||stickyForceRefresh){instr.stats.scrollViewportCleared++;let reasons=[...plan.reasons];if(scrollOffsetChanged)reasons.push(`scrollOffset(${ss.prevOffset}->${ss.offset})`);reasons.push(`vp=${ss.viewportHeight} content=${ss.contentHeight} vis=${ss.firstVisibleChild}-${ss.lastVisibleChild}`),instr.stats.scrollClearReason=reasons.join("+")}}if(process?.env?.SILVERY_STRICT&&tier==="shift"&&hasStickyChildren)throw Error(`[SILVERY_STRICT] Scroll Tier 1 (buffer shift) activated with sticky children (node: ${props.id??node.type}, stickyCount: ${ss.stickyChildren?.length??0})`);let scrollDelta=ss.offset-(ss.prevOffset??ss.offset);if(tier==="shift"&&clearHeight>0){if(props.overflowIndicator===!0&&!border.top&&!border.bottom){let topIndicatorY=clearY,bottomIndicatorY=clearY+clearHeight-1;if(ss.prevOffset!=null&&ss.prevOffset>0)buffer.fill(contentX,topIndicatorY,contentWidth,1,{char:" ",bg:plan.clearBg});buffer.fill(contentX,bottomIndicatorY,contentWidth,1,{char:" ",bg:plan.clearBg})}buffer.scrollRegion(contentX,clearY,contentWidth,clearHeight,scrollDelta,{char:" ",bg:plan.clearBg})}if(tier==="clear"&&clearHeight>0)buffer.fill(contentX,clearY,contentWidth,clearHeight,{char:" ",bg:plan.clearBg});if(stickyForceRefresh&&clearHeight>0)buffer.fill(contentX,clearY,contentWidth,clearHeight,{char:" ",bg:null});let childAncestorLayoutChanged=isCurrentEpoch(node.layoutChangedThisFrame)||!!ancestorLayoutChanged,prevVisTop=ss.prevOffset??ss.offset,prevVisBottom=prevVisTop+ss.viewportHeight;for(let i=0;i<node.children.length;i++){let child=node.children[i];if(!child)continue;if(child.props.position==="sticky")continue;if(i<ss.firstVisibleChild||i>ss.lastVisibleChild)continue;let thisChildHasPrev=defaultChildHasPrev,thisChildAncestorCleared=defaultChildAncestorCleared;if(tier==="shift"){let childRect=child.boxRect;if(childRect){let childTop=childRect.y-layout.y-border.top-padding.top,childBottom=childTop+childRect.height,wasFullyVisible=childTop>=prevVisTop&&childBottom<=prevVisBottom;thisChildHasPrev=wasFullyVisible,thisChildAncestorCleared=wasFullyVisible?ancestorCleared||contentRegionCleared:!0}}if(stickyForceRefresh&&thisChildHasPrev)thisChildHasPrev=!1,thisChildAncestorCleared=!1;if(canSkipChildSubtree(child,thisChildHasPrev,childAncestorLayoutChanged))continue;renderNodeToBuffer(child,buffer,{scrollOffset:ss.offset,clipBounds:childClipBounds,hasPrevBuffer:thisChildHasPrev,ancestorCleared:thisChildAncestorCleared,bufferIsCloned,ancestorLayoutChanged:childAncestorLayoutChanged,inheritedBg,inheritedFg},ctx)}if(ss.stickyChildren)for(let sticky of ss.stickyChildren){let child=node.children[sticky.index];if(!child?.boxRect)continue;let stickyScrollOffset=sticky.naturalTop-sticky.renderOffset;renderNodeToBuffer(child,buffer,{scrollOffset:stickyScrollOffset,clipBounds:childClipBounds,hasPrevBuffer:!1,ancestorCleared:!1,bufferIsCloned,ancestorLayoutChanged:childAncestorLayoutChanged,inheritedBg,inheritedFg},ctx)}}function renderNormalChildren(node,buffer,props,nodeState,childPositionChanged=!1,contentRegionCleared=!1,childrenNeedFreshRender=!1,ctx){let{scrollOffset,clipBounds,hasPrevBuffer,ancestorCleared,bufferIsCloned,ancestorLayoutChanged,inheritedBg,inheritedFg}=nodeState,instr=resolveInstrumentation(ctx),layout=node.boxRect;if(!layout)return;let clipX=(props.overflowX??props.overflow)==="hidden",clipY=(props.overflowY??props.overflow)==="hidden",effectiveClipBounds=clipX||clipY?computeChildClipBounds(layout,props,clipBounds,scrollOffset,clipX,clipY):clipBounds,hasStickyChildren=!!(node.stickyChildren&&node.stickyChildren.length>0),stickyForceRefresh=hasStickyChildren&&hasPrevBuffer;if(stickyForceRefresh){let border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},padding=getPadding(props),clearX=layout.x+border.left+padding.left,clearY=layout.y-scrollOffset+border.top+padding.top,clearW=layout.width-border.left-border.right-padding.left-padding.right,clearH=layout.height-border.top-border.bottom-padding.top-padding.bottom;if(clipBounds){let{top:clipTop,bottom:clipBottom}=clipBounds;if(clearY<clipTop)clearH-=clipTop-clearY,clearY=clipTop;if(clearY+clearH>clipBottom)clearH=clipBottom-clearY;if(clipBounds.left!==void 0&&clearX<clipBounds.left)clearW-=clipBounds.left-clearX,clearX=clipBounds.left;if(clipBounds.right!==void 0&&clearX+clearW>clipBounds.right)clearW=clipBounds.right-clearX}if(clearW>0&&clearH>0)buffer.fill(clearX,clearY,clearW,clearH,{char:" ",bg:null})}let childrenNeedRepaint=isDirty(node.dirtyBits,node.dirtyEpoch,CHILDREN_BIT)||childPositionChanged||childrenNeedFreshRender;if(instr.enabled&&childrenNeedRepaint&&hasPrevBuffer){instr.stats.normalChildrenRepaint++;let reasons=[];if(isDirty(node.dirtyBits,node.dirtyEpoch,CHILDREN_BIT))reasons.push("childrenDirty");if(childPositionChanged)reasons.push("childPositionChanged");if(childrenNeedFreshRender)reasons.push("childrenNeedFreshRender");instr.stats.normalRepaintReason=reasons.join("+")}let childHasPrev=childrenNeedRepaint?!1:hasPrevBuffer,childAncestorCleared=contentRegionCleared||ancestorCleared&&!getEffectiveBg(props),childAncestorLayoutChanged=isCurrentEpoch(node.layoutChangedThisFrame)||!!ancestorLayoutChanged;if(stickyForceRefresh)childHasPrev=!1,childAncestorCleared=!1;let hasAbsoluteChildren=!1;for(let child of node.children){let childProps=child.props;if(childProps.position==="absolute"){hasAbsoluteChildren=!0;continue}if(hasStickyChildren&&childProps.position==="sticky")continue;if(canSkipChildSubtree(child,childHasPrev,childAncestorLayoutChanged))continue;renderNodeToBuffer(child,buffer,{scrollOffset,clipBounds:effectiveClipBounds,hasPrevBuffer:childHasPrev,ancestorCleared:childAncestorCleared,bufferIsCloned,ancestorLayoutChanged:childAncestorLayoutChanged,inheritedBg,inheritedFg},ctx)}if(node.stickyChildren)for(let sticky of node.stickyChildren){let child=node.children[sticky.index];if(!child?.boxRect)continue;let stickyScrollOffset=sticky.naturalTop-sticky.renderOffset;renderNodeToBuffer(child,buffer,{scrollOffset:stickyScrollOffset,clipBounds:effectiveClipBounds,hasPrevBuffer:!1,ancestorCleared:!1,bufferIsCloned,ancestorLayoutChanged:childAncestorLayoutChanged,inheritedBg,inheritedFg},ctx)}if(hasAbsoluteChildren)for(let child of node.children){if(child.props.position!=="absolute")continue;renderNodeToBuffer(child,buffer,{scrollOffset,clipBounds:effectiveClipBounds,hasPrevBuffer:!1,ancestorCleared:!1,bufferIsCloned,ancestorLayoutChanged:childAncestorLayoutChanged,inheritedBg,inheritedFg},ctx)}}function canSkipChildSubtree(child,childHasPrev,childAncestorLayoutChanged){if(!childHasPrev)return!1;if(childAncestorLayoutChanged)return!1;if(isDirty(child.dirtyBits,child.dirtyEpoch,SUBTREE_BIT))return!1;if(isCurrentEpoch(child.layoutChangedThisFrame))return!1;if(child.scrollState&&child.scrollState.offset!==child.scrollState.prevOffset)return!1;return!0}function clearNodeDirtyFlags(node){node.dirtyBits=0,node.dirtyEpoch=INITIAL_EPOCH,node.layoutChangedThisFrame=INITIAL_EPOCH}function clearDirtyFlags(node){clearNodeDirtyFlags(node);for(let child of node.children)if(child.layoutNode)clearDirtyFlags(child);else clearVirtualTextFlags(child)}function clearVirtualTextFlags(node){clearNodeDirtyFlags(node);for(let child of node.children)clearVirtualTextFlags(child)}function hasChildPositionChanged(node){for(let child of node.children)if(child.boxRect&&child.prevLayout){if(child.boxRect.x!==child.prevLayout.x||child.boxRect.y!==child.prevLayout.y)return!0}return!1}function hasDescendantWithBg(node){for(let child of node.children){if(getEffectiveBg(child.props))return!0;if(child.children.length>0&&hasDescendantWithBg(child))return!0}return!1}function computeChildClipBounds(layout,props,parentClip,scrollOffset=0,horizontal=!0,vertical=!0){let border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},padding=getPadding(props),adjustedY=layout.y-scrollOffset,nodeClip=vertical?{top:adjustedY+border.top+padding.top,bottom:adjustedY+layout.height-border.bottom-padding.bottom}:{top:-1/0,bottom:1/0};if(horizontal)nodeClip.left=layout.x+border.left+padding.left,nodeClip.right=layout.x+layout.width-border.right-padding.right;if(!parentClip)return nodeClip;let result={top:vertical?Math.max(parentClip.top,nodeClip.top):parentClip.top,bottom:vertical?Math.min(parentClip.bottom,nodeClip.bottom):parentClip.bottom};if(horizontal&&nodeClip.left!==void 0&&nodeClip.right!==void 0)result.left=Math.max(parentClip.left??0,nodeClip.left),result.right=Math.min(parentClip.right??1/0,nodeClip.right);else if(parentClip.left!==void 0&&parentClip.right!==void 0)result.left=parentClip.left,result.right=parentClip.right;return result}function clearDescendantOverflowRegions(node,buffer,layout,scrollOffset,clipBounds,threadedInheritedBg){let clearBg=threadedInheritedBg.color,nodeRight=layout.x+layout.width,nodeBottom=layout.y-scrollOffset+layout.height,nodeLeft=layout.x,nodeTop=layout.y-scrollOffset;_clearDescendantOverflow(node.children,buffer,nodeLeft,nodeTop,nodeRight,nodeBottom,scrollOffset,clipBounds,clearBg)}function _clearDescendantOverflow(children,buffer,nodeLeft,nodeTop,nodeRight,nodeBottom,scrollOffset,clipBounds,clearBg){for(let child of children){if(child.prevLayout&&isCurrentEpoch(child.layoutChangedThisFrame)){let prev=child.prevLayout,prevRight=prev.x+prev.width,prevBottom=prev.y-scrollOffset+prev.height,prevTop=prev.y-scrollOffset;if(prevRight>nodeRight){let overflowX=nodeRight,overflowWidth=Math.min(prevRight,buffer.width)-overflowX,overflowTop=Math.max(prevTop,clipBounds?.top??0),overflowBottom=Math.min(prevBottom,clipBounds?.bottom??buffer.height);if(overflowWidth>0&&overflowBottom>overflowTop)buffer.fill(overflowX,overflowTop,overflowWidth,overflowBottom-overflowTop,{char:" ",bg:clearBg})}if(prevBottom>nodeBottom){let overflowTop=Math.max(nodeBottom,clipBounds?.top??0),overflowBottom=Math.min(prevBottom,clipBounds?.bottom??buffer.height),overflowX=Math.max(prev.x,clipBounds?.left??0),overflowWidth=Math.min(prevRight,clipBounds?.right??buffer.width)-overflowX;if(overflowWidth>0&&overflowBottom>overflowTop)buffer.fill(overflowX,overflowTop,overflowWidth,overflowBottom-overflowTop,{char:" ",bg:clearBg})}if(prev.x<nodeLeft){let overflowX=Math.max(prev.x,0),overflowWidth=Math.min(nodeLeft,buffer.width)-overflowX,overflowTop=Math.max(prevTop,clipBounds?.top??0),overflowBottom=Math.min(prevBottom,clipBounds?.bottom??buffer.height);if(overflowWidth>0&&overflowBottom>overflowTop)buffer.fill(overflowX,overflowTop,overflowWidth,overflowBottom-overflowTop,{char:" ",bg:clearBg})}if(prevTop<nodeTop){let overflowTop=Math.max(prevTop,clipBounds?.top??0),overflowBottom=Math.min(nodeTop,clipBounds?.bottom??buffer.height),overflowX=Math.max(prev.x,clipBounds?.left??0),overflowWidth=Math.min(prevRight,clipBounds?.right??buffer.width)-overflowX;if(overflowWidth>0&&overflowBottom>overflowTop)buffer.fill(overflowX,overflowTop,overflowWidth,overflowBottom-overflowTop,{char:" ",bg:clearBg})}}if(isDirty(child.dirtyBits,child.dirtyEpoch,SUBTREE_BIT)&&child.children!==void 0)_clearDescendantOverflow(child.children,buffer,nodeLeft,nodeTop,nodeRight,nodeBottom,scrollOffset,clipBounds,clearBg)}}function clearNodeRegion(node,buffer,layout,scrollOffset,clipBounds,layoutChanged,threadedInheritedBg){let inherited=threadedInheritedBg,clearBg=inherited.color,screenY=layout.y-scrollOffset,parentRect=node.parent?.boxRect,parentBottom=parentRect?parentRect.y-scrollOffset+parentRect.height:void 0,clearY=clipBounds?Math.max(screenY,clipBounds.top):screenY,clearBottom=clipBounds?Math.min(screenY+layout.height,clipBounds.bottom):screenY+layout.height;if(parentBottom!==void 0)clearBottom=Math.min(clearBottom,parentBottom);let{x:clearX,width:clearWidth}=layout;if(clipBounds?.left!==void 0&&clipBounds.right!==void 0){if(clearX<clipBounds.left)clearWidth-=clipBounds.left-clearX,clearX=clipBounds.left;if(clearX+clearWidth>clipBounds.right)clearWidth=Math.max(0,clipBounds.right-clearX)}if(inherited.ancestorRect){let ancestorRight=inherited.ancestorRect.x+inherited.ancestorRect.width,ancestorLeft=inherited.ancestorRect.x;if(clearX<ancestorLeft)clearWidth-=ancestorLeft-clearX,clearX=ancestorLeft;if(clearX+clearWidth>ancestorRight)clearWidth=Math.max(0,ancestorRight-clearX)}let clearHeight=clearBottom-clearY;if(clearHeight>0&&clearWidth>0){let _cellDbg2=getCellDebug();if(_cellDbg2&&cellCoversPoint(_cellDbg2,clearX,clearY,clearWidth,clearHeight)){let msg=`CLEAR_REGION ${node.props.id??node.type} fill=${clearX},${clearY} ${clearWidth}x${clearHeight} bg=${String(clearBg)} COVERS TARGET`;_cellDbg2.log.push(msg),cellLog.debug?.(msg)}buffer.fill(clearX,clearY,clearWidth,clearHeight,{char:" ",bg:clearBg})}clearExcessArea(node,buffer,layout,scrollOffset,clipBounds,layoutChanged,inherited)}function clearExcessArea(node,buffer,layout,scrollOffset,clipBounds,layoutChanged,inherited){if(!layoutChanged||!node.prevLayout)return;let prev=node.prevLayout,_cellDbg3=getCellDebug(),_prevCoversCell3=_cellDbg3&&cellCoversPoint(_cellDbg3,prev.x,prev.y-scrollOffset,prev.width,prev.height);if(prev.width<=layout.width&&prev.height<=layout.height){if(_cellDbg3&&_prevCoversCell3){let msg=`EXCESS_SKIP_NO_SHRINK ${node.props.id??node.type} prev=${prev.x},${prev.y-scrollOffset} ${prev.width}x${prev.height} now=${layout.x},${layout.y-scrollOffset} ${layout.width}x${layout.height}`;_cellDbg3.log.push(msg),cellLog.debug?.(msg)}return}if(prev.x!==layout.x||prev.y!==layout.y){if(_cellDbg3&&_prevCoversCell3){let msg=`EXCESS_SKIP_MOVED ${node.props.id??node.type} prev=${prev.x},${prev.y-scrollOffset} ${prev.width}x${prev.height} now=${layout.x},${layout.y-scrollOffset} ${layout.width}x${layout.height} (dx=${layout.x-prev.x} dy=${layout.y-prev.y})`;_cellDbg3.log.push(msg),cellLog.debug?.(msg)}return}let clearBg=inherited.color,screenY=layout.y-scrollOffset,prevScreenY=prev.y-scrollOffset,clipRect=inherited.ancestorRect??node.parent?.boxRect;if(!clipRect)return;let clipRectBottom=clipRect.y-scrollOffset+clipRect.height,clipRectRight=clipRect.x+clipRect.width,parent=node.parent;if(parent?.boxRect){let parentProps=parent.props,border=getBorderSize(parentProps),padding=getPadding(parentProps),parentRight=parent.boxRect.x+parent.boxRect.width-border.right-padding.right,parentBottom=parent.boxRect.y-scrollOffset+parent.boxRect.height-border.bottom-padding.bottom;clipRectRight=Math.min(clipRectRight,parentRight),clipRectBottom=Math.min(clipRectBottom,parentBottom)}if(prev.width>layout.width){let excessX=layout.x+layout.width,excessWidth=prev.width-layout.width;if(excessX+excessWidth>clipRectRight)excessWidth=Math.max(0,clipRectRight-excessX);if(excessWidth>0)clippedFill(buffer,excessX,excessWidth,prevScreenY,prevScreenY+prev.height,clipBounds,clipRectBottom,clearBg)}if(prev.height>layout.height){let bottomWidth=prev.width;if(layout.x+bottomWidth>clipRectRight)bottomWidth=Math.max(0,clipRectRight-layout.x);clippedFill(buffer,layout.x,bottomWidth,screenY+layout.height,prevScreenY+prev.height,clipBounds,clipRectBottom,clearBg)}}function clippedFill(buffer,x,width,top,bottom,clipBounds,outerBottom,bg){let clippedTop=clipBounds?Math.max(top,clipBounds.top):top,clippedBottom=Math.min(clipBounds?Math.min(bottom,clipBounds.bottom):bottom,outerBottom),clippedX=x,clippedWidth=width;if(clipBounds?.left!==void 0&&clipBounds.right!==void 0){if(clippedX<clipBounds.left)clippedWidth-=clipBounds.left-clippedX,clippedX=clipBounds.left;if(clippedX+clippedWidth>clipBounds.right)clippedWidth=Math.max(0,clipBounds.right-clippedX)}let height=clippedBottom-clippedTop;if(height>0&&clippedWidth>0)buffer.fill(clippedX,clippedTop,clippedWidth,height,{char:" ",bg})}var log7=createLogger8("silvery:render"),baseLog=createLogger8("@silvery/ag-react");function createAg(root,options){let measurer=options?.measurer,ctx=measurer?{measurer}:void 0,_prevBuffer=null,hasScroll=!1,hasSticky=!1;function doLayout(cols,rows,opts){let __stack6=[];try{let prevRootLayout=root.boxRect;let dimensionsChanged=prevRootLayout&&(prevRootLayout.width!==cols||prevRootLayout.height!==rows);if(!dimensionsChanged&&!hasLayoutDirty()&&!hasScrollDirty())return log7.debug?.("layout: skipped (no layoutDirty, no scrollDirty, dimensions unchanged)"),{tMeasure:0,tLayout:0,tScroll:0,tScrollRect:0,tNotify:0};const render=__using(__stack6,baseLog.span("pipeline",{width:cols,height:rows}),0);let tMeasure;{let __stack=[];try{const _m=__using(__stack,render.span("measure"),0);let t=performance.now();measurePhase(root,ctx);tMeasure=performance.now()-t;log7.debug?.(`measure: ${tMeasure.toFixed(2)}ms`)}catch(_catch){var _err=_catch,_hasErr=1}finally{__callDispose(__stack,_err,_hasErr)}}let tLayout;{let __stack2=[];try{const _l=__using(__stack2,render.span("layout"),0);let t=performance.now();layoutPhase(root,cols,rows);tLayout=performance.now()-t;log7.debug?.(`layout: ${tLayout.toFixed(2)}ms`)}catch(_catch2){var _err2=_catch2,_hasErr2=1}finally{__callDispose(__stack2,_err2,_hasErr2)}}if(!hasScroll||!hasSticky){let features=detectPipelineFeatures(root);if(features.hasScroll)hasScroll=!0;if(features.hasSticky)hasSticky=!0}let tScroll;if(hasScroll){let __stack3=[];try{const _s=__using(__stack3,render.span("scroll"),0);let t=performance.now();scrollPhase(root,{skipStateUpdates:opts?.skipScrollStateUpdates});tScroll=performance.now()-t}catch(_catch3){var _err3=_catch3,_hasErr3=1}finally{__callDispose(__stack3,_err3,_hasErr3)}}else tScroll=0;if(hasSticky)stickyPhase(root);let tScrollRect;{let __stack4=[];try{const _r=__using(__stack4,render.span("scrollRect"),0);let t=performance.now();if(hasScroll||hasSticky)scrollrectPhase(root);else scrollrectPhaseSimple(root);tScrollRect=performance.now()-t}catch(_catch4){var _err4=_catch4,_hasErr4=1}finally{__callDispose(__stack4,_err4,_hasErr4)}}let tNotify=0;if(!opts?.skipLayoutNotifications){let __stack5=[];try{const _n=__using(__stack5,render.span("notify"),0);let t=performance.now();notifyLayoutSubscribers(root);tNotify=performance.now()-t}catch(_catch5){var _err5=_catch5,_hasErr5=1}finally{__callDispose(__stack5,_err5,_hasErr5)}}let acc=globalThis.__silvery_bench_phases;if(acc)acc.measure+=tMeasure,acc.layout+=tLayout,acc.scroll+=tScroll,acc.scrollRect+=tScrollRect,acc.notify+=tNotify,acc.layoutTotal+=tMeasure+tLayout+tScroll+tScrollRect+tNotify;return{tMeasure,tLayout,tScroll,tScrollRect,tNotify}}catch(_catch6){var _err6=_catch6,_hasErr6=1}finally{__callDispose(__stack6,_err6,_hasErr6)}}function doRender(opts){clearBgConflictWarnings();let prevBuffer=opts?.fresh?null:opts?.prevBuffer!==void 0?opts.prevBuffer:_prevBuffer,tContent,buffer;{let t=performance.now();buffer=renderPhase(root,prevBuffer,ctx),tContent=performance.now()-t,log7.debug?.(`content: ${tContent.toFixed(2)}ms`)}if(!opts?.fresh)_prevBuffer=buffer;clearDirtyTracking();let acc=globalThis.__silvery_bench_phases;if(acc)acc.content+=tContent,acc.renderCalls+=1;return{frame:createTextFrame(buffer),buffer,prevBuffer,tContent}}function agCreateNode(type,props){let layoutNode=getLayoutEngine().createNode();return{type,props,children:[],parent:null,layoutNode,boxRect:null,scrollRect:null,screenRect:null,prevLayout:null,prevScrollRect:null,prevScreenRect:null,layoutChangedThisFrame:INITIAL_EPOCH,layoutDirty:!0,dirtyBits:ALL_RECONCILER_BITS,dirtyEpoch:getRenderEpoch(),layoutSubscribers:new Set}}function agInsertChild(parent,child,index){if(child.parent)agRemoveChild(child.parent,child);if(parent.children.splice(index,0,child),child.parent=parent,parent.layoutNode&&child.layoutNode){let layoutIndex=parent.children.slice(0,index).filter((c)=>c.layoutNode!==null).length;parent.layoutNode.insertChild(child.layoutNode,layoutIndex)}}function agRemoveChild(parent,child){let index=parent.children.indexOf(child);if(index===-1)return;if(parent.children.splice(index,1),parent.layoutNode&&child.layoutNode)parent.layoutNode.removeChild(child.layoutNode),child.layoutNode.free();child.parent=null}return{root,layout(dims,options2){if(measurer)runWithMeasurer(measurer,()=>doLayout(dims.cols,dims.rows,options2));else doLayout(dims.cols,dims.rows,options2)},render(options2){let result=measurer?runWithMeasurer(measurer,()=>doRender(options2)):doRender(options2);return{frame:result.frame,buffer:result.buffer,prevBuffer:result.prevBuffer}},resetBuffer(){_prevBuffer=null},createNode:agCreateNode,insertChild:agInsertChild,removeChild:agRemoveChild,updateProps(node,props,oldProps){if(node.props=props,node.layoutNode)node.layoutNode.markDirty()},setText(node,text){node.textContent=text;let epoch=getRenderEpoch(),bits=CONTENT_BIT|STYLE_PROPS_BIT;if(node.dirtyBits=node.dirtyEpoch!==epoch?bits:node.dirtyBits|bits,node.dirtyEpoch=epoch,node.layoutNode)node.layoutNode.markDirty()},toString(){return`[Ag root=${root.type} children=${root.children.length}]`}}}init_unicode();init_output_phase();init_output_phase();var log8=createLogger9("silvery:render"),baseLog2=createLogger9("@silvery/ag-react");function executeRender(root,width,height,prevBuffer,options="fullscreen",config){if(config?.measurer)return runWithMeasurer(config.measurer,()=>{return executeRenderCore(root,width,height,prevBuffer,options,config)});return executeRenderCore(root,width,height,prevBuffer,options,config)}function executeRenderCore(root,width,height,prevBuffer,options="fullscreen",config){let opts=typeof options==="string"?{mode:options}:options,{mode="fullscreen",skipLayoutNotifications=!1,skipScrollStateUpdates=!1,scrollbackOffset=0,termRows,cursorPos}=opts;if(process?.env?.SILVERY_DEV&&prevBuffer===null&&root.prevLayout!==null&&!skipLayoutNotifications)log8.warn?.("executeRender called with prevBuffer=null on frame 2+ — "+"incremental content rendering is disabled (full render every frame). Track the returned buffer and pass it as prevBuffer on subsequent renders.");let start=performance.now(),ag=createAg(root,{measurer:config?.measurer});ag.layout({cols:width,rows:height},{skipLayoutNotifications,skipScrollStateUpdates});let{buffer}=ag.render({prevBuffer}),tLayout=performance.now()-start,output,tOutput;{let t4=performance.now(),outputFn=config?.outputPhaseFn??outputPhase;try{output=outputFn(prevBuffer,buffer,mode,scrollbackOffset,termRows,cursorPos)}catch(e){if(e instanceof Error)e.__silvery_buffer=buffer;throw e}tOutput=performance.now()-t4,log8.debug?.(`output: ${tOutput.toFixed(2)}ms (${output.length} bytes)`)}let total=performance.now()-start;globalThis.__silvery_last_pipeline={layout:tLayout,output:tOutput,total,incremental:prevBuffer!==null},globalThis.__silvery_render_count=(globalThis.__silvery_render_count??0)+1;let acc=globalThis.__silvery_bench_phases;if(acc)acc.output+=tOutput,acc.total+=total,acc.pipelineCalls+=1;return log8.debug?.(`pipeline: layout+render=${tLayout.toFixed(1)}ms output=${tOutput.toFixed(1)}ms total=${total.toFixed(1)}ms`),{output,buffer}}import Reconciler from"react-reconciler";import{createContext as createContext2}from"react";import{DefaultEventPriority,DiscreteEventPriority,NoEventPriority}from"react-reconciler/constants.js";var LAYOUT_PROPS=new Set(["width","height","minWidth","minHeight","maxWidth","maxHeight","flexDirection","flexWrap","justifyContent","alignItems","alignContent","alignSelf","flexGrow","flexShrink","flexBasis","padding","paddingX","paddingY","paddingTop","paddingBottom","paddingLeft","paddingRight","margin","marginX","marginY","marginTop","marginBottom","marginLeft","marginRight","gap","columnGap","rowGap","borderStyle","borderTop","borderBottom","borderLeft","borderRight","display","position","top","left","bottom","right","aspectRatio","overflow","overflowX","overflowY"]),TEXT_CONTENT_PROPS=new Set(["wrap","internal_transform"]),STYLE_PROPS=new Set(["color","backgroundColor","bold","dim","dimColor","italic","underline","underlineStyle","underlineColor","strikethrough","inverse","borderColor","borderBackgroundColor","borderTopBackgroundColor","borderBottomBackgroundColor","borderLeftBackgroundColor","borderRightBackgroundColor","borderStyle","outlineStyle","outlineColor","outlineDimColor","outlineTop","outlineBottom","outlineLeft","outlineRight","theme"]),NO_CHANGES={anyChanged:!1,layoutChanged:!1,contentChanged:!1};function classifyPropChanges(oldProps,newProps){if(oldProps===newProps)return NO_CHANGES;let keysA=Object.keys(oldProps),keysB=Object.keys(newProps),sameKeyCount=keysA.length===keysB.length,layoutChanged=!1,contentChanged=!1,anyChanged=!1;for(let key of keysA)if(oldProps[key]!==newProps[key]){if(anyChanged=!0,LAYOUT_PROPS.has(key))layoutChanged=!0;if(contentChanged!=="text"){if(key==="children"){let oldIsPrimitive=typeof oldProps[key]==="string"||typeof oldProps[key]==="number",newIsPrimitive=typeof newProps[key]==="string"||typeof newProps[key]==="number";if(oldIsPrimitive||newIsPrimitive)contentChanged="text"}else if(TEXT_CONTENT_PROPS.has(key))contentChanged="text";else if(contentChanged!=="style"&&STYLE_PROPS.has(key))contentChanged="style"}if(layoutChanged&&contentChanged==="text")break}if(!sameKeyCount){for(let key of keysB)if(!(key in oldProps)){if(anyChanged=!0,LAYOUT_PROPS.has(key))layoutChanged=!0;if(contentChanged!=="text"){if(key==="children"){if(typeof newProps[key]==="string"||typeof newProps[key]==="number")contentChanged="text"}else if(TEXT_CONTENT_PROPS.has(key))contentChanged="text";else if(contentChanged!=="style"&&STYLE_PROPS.has(key))contentChanged="style"}if(layoutChanged&&contentChanged==="text")break}}if(!anyChanged&&!sameKeyCount)anyChanged=!0;if(!anyChanged)return NO_CHANGES;return{anyChanged,layoutChanged,contentChanged}}import{createLogger as createLogger10}from"loggily";init_unicode();var measureLog=createLogger10("silvery:measure");function createNode(type,props,measurer){let layoutNode=getLayoutEngine().createNode(),epoch=getRenderEpoch(),node={type,props,children:[],parent:null,layoutNode,boxRect:null,scrollRect:null,screenRect:null,prevLayout:null,prevScrollRect:null,prevScreenRect:null,layoutChangedThisFrame:epoch,layoutDirty:!0,dirtyBits:ALL_RECONCILER_BITS,dirtyEpoch:epoch,layoutSubscribers:new Set};if(type==="silvery-box")applyBoxProps(layoutNode,props);if(type==="silvery-text"){let cachedText=null,measureCache=new Map;layoutNode.setMeasureFunc((width,widthMode,height,heightMode)=>{measureStats.calls++,measureLog.debug?.(`measure "${collectPlainTextSkipHidden(node).slice(0,40)}" width=${width} widthMode=${widthMode} height=${height} heightMode=${heightMode}`);let cacheKey=`${width}|${widthMode}|${height}|${heightMode}`,cached=measureCache.get(cacheKey);if(cached&&cachedText!==null&&!isDirty(node.dirtyBits,node.dirtyEpoch,CONTENT_BIT))return measureStats.cacheHits++,cached;let text;if(cachedText!==null&&!isDirty(node.dirtyBits,node.dirtyEpoch,CONTENT_BIT))text=cachedText;else{measureStats.textCollects++;let newText=collectPlainTextSkipHidden(node);if(newText!==cachedText)measureCache.clear();text=newText,cachedText=text,node.dirtyBits&=~CONTENT_BIT}if(!text)return{width:0,height:0};let cachedAfterCollect=measureCache.get(cacheKey);if(cachedAfterCollect)return measureStats.cacheHits++,cachedAfterCollect;let lines=text.split(`
77
+ `),maxWidth=widthMode==="undefined"||Number.isNaN(width)?Number.POSITIVE_INFINITY:width,{wrap}=node.props,isTruncate=wrap==="truncate"||wrap==="truncate-start"||wrap==="truncate-middle"||wrap==="truncate-end"||wrap==="clip"||wrap===!1,isHardWrap=wrap==="hard",totalHeight=0,actualWidth=0,dw=measurer?measurer.displayWidth.bind(measurer):displayWidth,wt=measurer?measurer.wrapText.bind(measurer):wrapText,lh=getActiveLineHeight();for(let line of lines){measureStats.displayWidthCalls++;let lineWidth=dw(line);if(isTruncate||lineWidth<=maxWidth)totalHeight+=lh,actualWidth=Math.max(actualWidth,isTruncate?Math.min(lineWidth,maxWidth):lineWidth);else if(isHardWrap)if(Number.isFinite(maxWidth)&&maxWidth>0)totalHeight+=Math.ceil(lineWidth/maxWidth)*lh,actualWidth=Math.max(actualWidth,maxWidth);else totalHeight+=lh,actualWidth=Math.max(actualWidth,lineWidth);else{let wrapped=wt(line,maxWidth,!1,!0);totalHeight+=wrapped.length*lh;for(let wl of wrapped)actualWidth=Math.max(actualWidth,dw(wl))}}let resultHeight=Math.max(lh,totalHeight);if(heightMode==="exactly"&&Number.isFinite(height))resultHeight=height;else if(heightMode==="at-most"&&Number.isFinite(height))resultHeight=Math.min(resultHeight,height);let result={width:Math.min(actualWidth,maxWidth),height:resultHeight};return measureCache.set(cacheKey,result),result})}return node}function createRootNode(){let node=createNode("silvery-root",{}),c=getConstants();return node.layoutNode.setFlexDirection(c.FLEX_DIRECTION_COLUMN),node}function createVirtualTextNode(props){let epoch=getRenderEpoch();return{type:"silvery-text",props,children:[],parent:null,layoutNode:null,boxRect:null,scrollRect:null,screenRect:null,prevLayout:null,prevScrollRect:null,prevScreenRect:null,layoutChangedThisFrame:INITIAL_EPOCH,layoutDirty:!1,dirtyBits:CONTENT_BIT|STYLE_PROPS_BIT|BG_BIT|SUBTREE_BIT,dirtyEpoch:epoch,layoutSubscribers:new Set,isRawText:!1,inlineRects:null}}function applyBoxProps(layoutNode,props,oldProps){let c=getConstants(),wasRemoved=(prop)=>oldProps?.[prop]!==void 0&&props[prop]===void 0;if(props.width!==void 0){if(typeof props.width==="string"&&props.width.endsWith("%"))layoutNode.setWidthPercent(Number.parseFloat(props.width));else if(typeof props.width==="number")layoutNode.setWidth(props.width);else if(props.width==="auto")layoutNode.setWidthAuto()}else if(wasRemoved("width"))layoutNode.setWidthAuto();if(props.height!==void 0){if(typeof props.height==="string"&&props.height.endsWith("%"))layoutNode.setHeightPercent(Number.parseFloat(props.height));else if(typeof props.height==="number")layoutNode.setHeight(props.height);else if(props.height==="auto")layoutNode.setHeightAuto()}else if(wasRemoved("height"))layoutNode.setHeightAuto();if(props.minWidth!==void 0){if(typeof props.minWidth==="string"&&props.minWidth.endsWith("%"))layoutNode.setMinWidthPercent(Number.parseFloat(props.minWidth));else if(typeof props.minWidth==="number")layoutNode.setMinWidth(props.minWidth)}else if(wasRemoved("minWidth"))layoutNode.setMinWidth(0);if(props.minHeight!==void 0){if(typeof props.minHeight==="string"&&props.minHeight.endsWith("%"))layoutNode.setMinHeightPercent(Number.parseFloat(props.minHeight));else if(typeof props.minHeight==="number")layoutNode.setMinHeight(props.minHeight)}else if(wasRemoved("minHeight"))layoutNode.setMinHeight(0);if(props.maxWidth!==void 0){if(typeof props.maxWidth==="string"&&props.maxWidth.endsWith("%"))layoutNode.setMaxWidthPercent(Number.parseFloat(props.maxWidth));else if(typeof props.maxWidth==="number")layoutNode.setMaxWidth(props.maxWidth)}else if(wasRemoved("maxWidth"))layoutNode.setMaxWidth(Number.POSITIVE_INFINITY);if(props.maxHeight!==void 0){if(typeof props.maxHeight==="string"&&props.maxHeight.endsWith("%"))layoutNode.setMaxHeightPercent(Number.parseFloat(props.maxHeight));else if(typeof props.maxHeight==="number")layoutNode.setMaxHeight(props.maxHeight)}else if(wasRemoved("maxHeight"))layoutNode.setMaxHeight(Number.POSITIVE_INFINITY);if(props.flexGrow!==void 0)layoutNode.setFlexGrow(props.flexGrow);else if(wasRemoved("flexGrow"))layoutNode.setFlexGrow(0);if(props.flexShrink!==void 0)layoutNode.setFlexShrink(props.flexShrink);else if(wasRemoved("flexShrink"))layoutNode.setFlexShrink(1);if(props.flexBasis!==void 0){if(typeof props.flexBasis==="string"&&props.flexBasis.endsWith("%"))layoutNode.setFlexBasisPercent(Number.parseFloat(props.flexBasis));else if(props.flexBasis==="auto")layoutNode.setFlexBasisAuto();else if(typeof props.flexBasis==="number")layoutNode.setFlexBasis(props.flexBasis)}else if(wasRemoved("flexBasis"))layoutNode.setFlexBasisAuto();if(props.flexDirection!==void 0){let directionMap={row:c.FLEX_DIRECTION_ROW,column:c.FLEX_DIRECTION_COLUMN,"row-reverse":c.FLEX_DIRECTION_ROW_REVERSE,"column-reverse":c.FLEX_DIRECTION_COLUMN_REVERSE};layoutNode.setFlexDirection(directionMap[props.flexDirection]??c.FLEX_DIRECTION_ROW)}else if(wasRemoved("flexDirection"))layoutNode.setFlexDirection(c.FLEX_DIRECTION_ROW);if(props.flexWrap!==void 0){let wrapMap={nowrap:c.WRAP_NO_WRAP,wrap:c.WRAP_WRAP,"wrap-reverse":c.WRAP_WRAP_REVERSE};layoutNode.setFlexWrap(wrapMap[props.flexWrap]??c.WRAP_NO_WRAP)}else if(wasRemoved("flexWrap"))layoutNode.setFlexWrap(c.WRAP_NO_WRAP);if(props.alignItems!==void 0)layoutNode.setAlignItems(alignToConstant(props.alignItems));else if(wasRemoved("alignItems"))layoutNode.setAlignItems(c.ALIGN_STRETCH);if(props.alignSelf!==void 0)if(props.alignSelf==="auto")layoutNode.setAlignSelf(c.ALIGN_AUTO);else layoutNode.setAlignSelf(alignToConstant(props.alignSelf));else if(wasRemoved("alignSelf"))layoutNode.setAlignSelf(c.ALIGN_AUTO);if(props.alignContent!==void 0)layoutNode.setAlignContent(alignToConstant(props.alignContent));else if(wasRemoved("alignContent"))layoutNode.setAlignContent(c.ALIGN_FLEX_START);if(props.justifyContent!==void 0)layoutNode.setJustifyContent(justifyToConstant(props.justifyContent));else if(wasRemoved("justifyContent"))layoutNode.setJustifyContent(c.JUSTIFY_FLEX_START);if(applySpacing(layoutNode,"padding",props),applySpacing(layoutNode,"margin",props),props.gap!==void 0)layoutNode.setGap(c.GUTTER_ALL,props.gap);else if(wasRemoved("gap"))layoutNode.setGap(c.GUTTER_ALL,0);if(props.columnGap!==void 0)layoutNode.setGap(c.GUTTER_COLUMN,props.columnGap);else if(wasRemoved("columnGap"))layoutNode.setGap(c.GUTTER_COLUMN,0);if(props.rowGap!==void 0)layoutNode.setGap(c.GUTTER_ROW,props.rowGap);else if(wasRemoved("rowGap"))layoutNode.setGap(c.GUTTER_ROW,0);if(props.display!==void 0)layoutNode.setDisplay(props.display==="none"?c.DISPLAY_NONE:c.DISPLAY_FLEX);else if(wasRemoved("display"))layoutNode.setDisplay(c.DISPLAY_FLEX);if(props.position!==void 0)if(props.position==="absolute")layoutNode.setPositionType(c.POSITION_TYPE_ABSOLUTE);else if(props.position==="static")layoutNode.setPositionType(c.POSITION_TYPE_STATIC);else layoutNode.setPositionType(c.POSITION_TYPE_RELATIVE);else if(wasRemoved("position"))layoutNode.setPositionType(c.POSITION_TYPE_RELATIVE);if(props.position!=="static")applyPositionOffset(layoutNode,c.EDGE_TOP,props.top),applyPositionOffset(layoutNode,c.EDGE_LEFT,props.left),applyPositionOffset(layoutNode,c.EDGE_BOTTOM,props.bottom),applyPositionOffset(layoutNode,c.EDGE_RIGHT,props.right);if(props.aspectRatio!==void 0)layoutNode.setAspectRatio(props.aspectRatio);else if(wasRemoved("aspectRatio"))layoutNode.setAspectRatio(NaN);let effectiveOverflow=props.overflow??(props.overflowX==="hidden"||props.overflowY==="hidden"?"hidden":void 0);if(effectiveOverflow!==void 0)if(effectiveOverflow==="hidden")layoutNode.setOverflow(c.OVERFLOW_HIDDEN);else if(effectiveOverflow==="scroll")layoutNode.setOverflow(c.OVERFLOW_HIDDEN);else layoutNode.setOverflow(c.OVERFLOW_VISIBLE);else if(wasRemoved("overflow")||wasRemoved("overflowX")||wasRemoved("overflowY"))layoutNode.setOverflow(c.OVERFLOW_VISIBLE);if(props.borderStyle){let borderWidth=getActiveLineHeight()>1?0:1;if(props.borderTop!==!1)layoutNode.setBorder(c.EDGE_TOP,borderWidth);else layoutNode.setBorder(c.EDGE_TOP,0);if(props.borderBottom!==!1)layoutNode.setBorder(c.EDGE_BOTTOM,borderWidth);else layoutNode.setBorder(c.EDGE_BOTTOM,0);if(props.borderLeft!==!1)layoutNode.setBorder(c.EDGE_LEFT,borderWidth);else layoutNode.setBorder(c.EDGE_LEFT,0);if(props.borderRight!==!1)layoutNode.setBorder(c.EDGE_RIGHT,borderWidth);else layoutNode.setBorder(c.EDGE_RIGHT,0)}else layoutNode.setBorder(c.EDGE_TOP,0),layoutNode.setBorder(c.EDGE_BOTTOM,0),layoutNode.setBorder(c.EDGE_LEFT,0),layoutNode.setBorder(c.EDGE_RIGHT,0)}function applySpacing(layoutNode,type,props){let c=getConstants(),set=type==="padding"?layoutNode.setPadding.bind(layoutNode):layoutNode.setMargin.bind(layoutNode),all=props[type],x=props[`${type}X`],yy=props[`${type}Y`],top=props[`${type}Top`],bottom=props[`${type}Bottom`],left=props[`${type}Left`],right=props[`${type}Right`];set(c.EDGE_TOP,top??yy??all??0),set(c.EDGE_BOTTOM,bottom??yy??all??0),set(c.EDGE_LEFT,left??x??all??0),set(c.EDGE_RIGHT,right??x??all??0)}function applyPositionOffset(layoutNode,edge,value){if(value===void 0){layoutNode.setPosition(edge,NaN);return}if(typeof value==="string"&&value.endsWith("%"))layoutNode.setPositionPercent(edge,Number.parseFloat(value));else if(typeof value==="number")layoutNode.setPosition(edge,value)}function alignToConstant(align){let c=getConstants();return{"flex-start":c.ALIGN_FLEX_START,"flex-end":c.ALIGN_FLEX_END,center:c.ALIGN_CENTER,stretch:c.ALIGN_STRETCH,baseline:c.ALIGN_BASELINE,"space-between":c.ALIGN_SPACE_BETWEEN,"space-around":c.ALIGN_SPACE_AROUND,"space-evenly":c.ALIGN_SPACE_EVENLY}[align]??c.ALIGN_STRETCH}function justifyToConstant(justify){let c=getConstants();return{"flex-start":c.JUSTIFY_FLEX_START,"flex-end":c.JUSTIFY_FLEX_END,center:c.JUSTIFY_CENTER,"space-between":c.JUSTIFY_SPACE_BETWEEN,"space-around":c.JUSTIFY_SPACE_AROUND,"space-evenly":c.JUSTIFY_SPACE_EVENLY}[justify]??c.JUSTIFY_FLEX_START}import{createLogger as createLogger11}from"loggily";var log9=createLogger11("silvery:reconciler");function normalizeNodeType(type){if(type==="ink-box")return"silvery-box";if(type==="ink-text")return"silvery-text";return type}var onNodeRemovedCallback=null;function setOnNodeRemoved(callback){onNodeRemovedCallback=callback}function markSubtreeDirty(node){let epoch=getRenderEpoch();while(node&&!isDirty(node.dirtyBits,node.dirtyEpoch,SUBTREE_BIT)){if(node.dirtyEpoch!==epoch)node.dirtyBits=SUBTREE_BIT,node.dirtyEpoch=epoch;else node.dirtyBits|=SUBTREE_BIT;node=node.parent}}function markLayoutAncestorDirty(node){if(node.layoutNode)return;let ancestor=node.parent;while(ancestor&&!ancestor.layoutNode)ancestor=ancestor.parent;if(ancestor?.layoutNode){let epoch=getRenderEpoch();if(ancestor.dirtyEpoch!==epoch)ancestor.dirtyBits=CONTENT_BIT|STYLE_PROPS_BIT,ancestor.dirtyEpoch=epoch;else ancestor.dirtyBits|=CONTENT_BIT|STYLE_PROPS_BIT;ancestor.layoutDirty=!0,ancestor.layoutNode.markDirty(),trackLayoutDirty(ancestor),trackContentDirty(ancestor)}}var hasWarnedBoxInsideText=!1;var inkStrictValidation=!1;var currentUpdatePriority=NoEventPriority;var hostConfig={rendererPackageName:"@silvery/ag-react",rendererVersion:"0.0.1",supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,isPrimaryRenderer:!0,scheduleTimeout:setTimeout,cancelTimeout:clearTimeout,noTimeout:-1,supportsMicrotasks:!0,scheduleMicrotask:queueMicrotask,getRootHostContext(){return{isInsideText:!1}},getChildHostContext(parentHostContext,type){let normalizedType=normalizeNodeType(type),isInsideText=parentHostContext.isInsideText||normalizedType==="silvery-text";if(isInsideText===parentHostContext.isInsideText)return parentHostContext;return{isInsideText}},createInstance(type,props,_rootContainer,hostContext){if(type=normalizeNodeType(type),"style"in props&&props.style&&typeof props.style==="object")props={...props.style,...props};if(type==="silvery-box"&&hostContext.isInsideText){if(inkStrictValidation)throw Error("<Box> can’t be nested inside <Text> component");if(!hasWarnedBoxInsideText)hasWarnedBoxInsideText=!0,log9.warn?.("<Box> cannot be nested inside <Text>. This produces undefined layout behavior.")}if(type==="silvery-text"&&hostContext.isInsideText)return createVirtualTextNode(props);return createNode(type,props)},createTextInstance(text,_rootContainer,hostContext){if(inkStrictValidation&&!hostContext.isInsideText&&text.trim().length>0)throw Error(`Text string "${text}" must be rendered inside <Text> component`);let epoch=getRenderEpoch();return{type:"silvery-text",props:{children:text},children:[],parent:null,layoutNode:null,boxRect:null,scrollRect:null,screenRect:null,prevLayout:null,prevScrollRect:null,prevScreenRect:null,layoutChangedThisFrame:INITIAL_EPOCH,layoutDirty:!1,dirtyBits:CONTENT_BIT|STYLE_PROPS_BIT|BG_BIT|SUBTREE_BIT,dirtyEpoch:epoch,layoutSubscribers:new Set,textContent:text,isRawText:!0}},appendChild(parentInstance,child){let existingIndex=parentInstance.children.indexOf(child);if(existingIndex!==-1){if(parentInstance.children.splice(existingIndex,1),parentInstance.layoutNode&&child.layoutNode)parentInstance.layoutNode.removeChild(child.layoutNode)}if(child.parent=parentInstance,parentInstance.children.push(child),parentInstance.layoutNode&&child.layoutNode){let layoutIndex=parentInstance.children.filter((c)=>c.layoutNode!==null).length-1;parentInstance.layoutNode.insertChild(child.layoutNode,layoutIndex)}{let epoch=getRenderEpoch(),bits=CHILDREN_BIT|CONTENT_BIT;parentInstance.dirtyBits=parentInstance.dirtyEpoch!==epoch?bits:parentInstance.dirtyBits|bits,parentInstance.dirtyEpoch=epoch}parentInstance.layoutDirty=!0,parentInstance.layoutNode?.markDirty(),trackLayoutDirty(parentInstance),trackContentDirty(parentInstance),markLayoutAncestorDirty(parentInstance),markSubtreeDirty(parentInstance)},appendInitialChild(parentInstance,child){if(child.parent=parentInstance,parentInstance.children.push(child),parentInstance.layoutNode&&child.layoutNode){let layoutIndex=parentInstance.children.filter((c)=>c.layoutNode!==null).length-1;parentInstance.layoutNode.insertChild(child.layoutNode,layoutIndex)}},appendChildToContainer(container,child){let existingIndex=container.root.children.indexOf(child);if(existingIndex!==-1){if(container.root.children.splice(existingIndex,1),container.root.layoutNode&&child.layoutNode)container.root.layoutNode.removeChild(child.layoutNode)}if(child.parent=container.root,container.root.children.push(child),container.root.layoutNode&&child.layoutNode){let layoutIndex=container.root.children.filter((c)=>c.layoutNode!==null).length-1;container.root.layoutNode.insertChild(child.layoutNode,layoutIndex)}{let epoch=getRenderEpoch(),bits=CHILDREN_BIT|CONTENT_BIT;container.root.dirtyBits=container.root.dirtyEpoch!==epoch?bits:container.root.dirtyBits|bits,container.root.dirtyEpoch=epoch}container.root.layoutDirty=!0,container.root.layoutNode?.markDirty(),trackLayoutDirty(container.root),trackContentDirty(container.root),markSubtreeDirty(container.root)},removeChild(parentInstance,child){let index=parentInstance.children.indexOf(child);if(index!==-1){if(onNodeRemovedCallback?.(child),parentInstance.children.splice(index,1),parentInstance.layoutNode&&child.layoutNode)parentInstance.layoutNode.removeChild(child.layoutNode),child.layoutNode.free();child.parent=null;{let epoch=getRenderEpoch(),bits=CHILDREN_BIT|CONTENT_BIT;parentInstance.dirtyBits=parentInstance.dirtyEpoch!==epoch?bits:parentInstance.dirtyBits|bits,parentInstance.dirtyEpoch=epoch}parentInstance.layoutDirty=!0,parentInstance.layoutNode?.markDirty(),trackLayoutDirty(parentInstance),trackContentDirty(parentInstance),markLayoutAncestorDirty(parentInstance),markSubtreeDirty(parentInstance)}},removeChildFromContainer(container,child){let index=container.root.children.indexOf(child);if(index!==-1){if(onNodeRemovedCallback?.(child),container.root.children.splice(index,1),container.root.layoutNode&&child.layoutNode)container.root.layoutNode.removeChild(child.layoutNode),child.layoutNode.free();child.parent=null;{let epoch=getRenderEpoch(),bits=CHILDREN_BIT|CONTENT_BIT;container.root.dirtyBits=container.root.dirtyEpoch!==epoch?bits:container.root.dirtyBits|bits,container.root.dirtyEpoch=epoch}container.root.layoutDirty=!0,container.root.layoutNode?.markDirty(),trackLayoutDirty(container.root),trackContentDirty(container.root),markSubtreeDirty(container.root)}},insertBefore(parentInstance,child,beforeChild){let existingIndex=parentInstance.children.indexOf(child);if(existingIndex!==-1){if(parentInstance.children.splice(existingIndex,1),parentInstance.layoutNode&&child.layoutNode)parentInstance.layoutNode.removeChild(child.layoutNode)}let beforeIndex=parentInstance.children.indexOf(beforeChild);if(beforeIndex!==-1){if(child.parent=parentInstance,parentInstance.children.splice(beforeIndex,0,child),parentInstance.layoutNode&&child.layoutNode){let layoutIndex=parentInstance.children.slice(0,beforeIndex).filter((c)=>c.layoutNode!==null).length;parentInstance.layoutNode.insertChild(child.layoutNode,layoutIndex)}{let epoch=getRenderEpoch(),bits=CHILDREN_BIT|CONTENT_BIT;parentInstance.dirtyBits=parentInstance.dirtyEpoch!==epoch?bits:parentInstance.dirtyBits|bits,parentInstance.dirtyEpoch=epoch}parentInstance.layoutDirty=!0,parentInstance.layoutNode?.markDirty(),trackLayoutDirty(parentInstance),trackContentDirty(parentInstance),markLayoutAncestorDirty(parentInstance),markSubtreeDirty(parentInstance)}},insertInContainerBefore(container,child,beforeChild){let existingIndex=container.root.children.indexOf(child);if(existingIndex!==-1){if(container.root.children.splice(existingIndex,1),container.root.layoutNode&&child.layoutNode)container.root.layoutNode.removeChild(child.layoutNode)}let beforeIndex=container.root.children.indexOf(beforeChild);if(beforeIndex!==-1){if(child.parent=container.root,container.root.children.splice(beforeIndex,0,child),container.root.layoutNode&&child.layoutNode){let layoutIndex=container.root.children.slice(0,beforeIndex).filter((c)=>c.layoutNode!==null).length;container.root.layoutNode.insertChild(child.layoutNode,layoutIndex)}{let epoch=getRenderEpoch(),bits=CHILDREN_BIT|CONTENT_BIT;container.root.dirtyBits=container.root.dirtyEpoch!==epoch?bits:container.root.dirtyBits|bits,container.root.dirtyEpoch=epoch}container.root.layoutDirty=!0,container.root.layoutNode?.markDirty(),trackLayoutDirty(container.root),trackContentDirty(container.root),markSubtreeDirty(container.root)}},prepareUpdate(_instance,_type,oldProps,newProps){return classifyPropChanges(oldProps,newProps).anyChanged},commitUpdate(instance,_type,oldProps,newProps,_finishedWork){if("style"in oldProps&&oldProps.style&&typeof oldProps.style==="object")oldProps={...oldProps.style,...oldProps};if("style"in newProps&&newProps.style&&typeof newProps.style==="object")newProps={...newProps.style,...newProps};let{anyChanged,layoutChanged,contentChanged}=classifyPropChanges(oldProps,newProps);if(!anyChanged){instance.props=newProps;return}if(layoutChanged){if(instance.layoutNode)applyBoxProps(instance.layoutNode,newProps,oldProps),instance.layoutNode.markDirty();instance.layoutDirty=!0,trackLayoutDirty(instance)}if(contentChanged){let epoch=getRenderEpoch(),bits=STYLE_PROPS_BIT;if(contentChanged==="text"){if(bits|=CONTENT_BIT,instance.layoutNode)instance.layoutNode.markDirty()}if(oldProps.backgroundColor!==newProps.backgroundColor)bits|=BG_BIT;if(oldProps.borderStyle&&!newProps.borderStyle)bits|=BG_BIT;if(oldProps.outlineStyle&&!newProps.outlineStyle)bits|=BG_BIT;if(oldProps.theme!==newProps.theme)bits|=BG_BIT;instance.dirtyBits=instance.dirtyEpoch!==epoch?bits:instance.dirtyBits|bits,instance.dirtyEpoch=epoch}if(contentChanged)trackContentDirty(instance);if(contentChanged==="style"&&!layoutChanged&&!isDirty(instance.dirtyBits,instance.dirtyEpoch,BG_BIT)&&!isDirty(instance.dirtyBits,instance.dirtyEpoch,CONTENT_BIT)&&!isDirty(instance.dirtyBits,instance.dirtyEpoch,CHILDREN_BIT))trackStyleOnlyDirty(instance);instance.props=newProps;let scrollToChanged=oldProps.scrollTo!==newProps.scrollTo,scrollOffsetChanged=oldProps.scrollOffset!==newProps.scrollOffset;if(scrollToChanged||scrollOffsetChanged)trackScrollDirty(instance);if(instance.layoutDirty||contentChanged||scrollToChanged||scrollOffsetChanged)markLayoutAncestorDirty(instance),markSubtreeDirty(instance)},commitTextUpdate(textInstance,_oldText,newText){textInstance.textContent=newText,textInstance.props={children:newText};let epoch=getRenderEpoch(),bits=CONTENT_BIT|STYLE_PROPS_BIT;textInstance.dirtyBits=textInstance.dirtyEpoch!==epoch?bits:textInstance.dirtyBits|bits,textInstance.dirtyEpoch=epoch,trackContentDirty(textInstance),markLayoutAncestorDirty(textInstance),markSubtreeDirty(textInstance)},finalizeInitialChildren(){return!1},prepareForCommit(){return null},resetAfterCommit(container){container.onRender()},getPublicInstance(instance){return instance},shouldSetTextContent(){return!1},clearContainer(container){for(let child of container.root.children)onNodeRemovedCallback?.(child);for(let child of container.root.children)if(container.root.layoutNode&&child.layoutNode)container.root.layoutNode.removeChild(child.layoutNode),child.layoutNode.free();container.root.children=[];{let epoch=getRenderEpoch(),bits=CHILDREN_BIT|CONTENT_BIT;container.root.dirtyBits=container.root.dirtyEpoch!==epoch?bits:container.root.dirtyBits|bits,container.root.dirtyEpoch=epoch}container.root.layoutDirty=!0,container.root.layoutNode?.markDirty(),trackLayoutDirty(container.root),trackContentDirty(container.root),markSubtreeDirty(container.root)},preparePortalMount(){},getCurrentEventPriority(){if(currentUpdatePriority!==NoEventPriority)return currentUpdatePriority;return DefaultEventPriority},getInstanceFromNode(){return null},beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},prepareScopeUpdate(){},getInstanceFromScope(){return null},detachDeletedInstance(){},setCurrentUpdatePriority(newPriority){currentUpdatePriority=newPriority},getCurrentUpdatePriority(){return currentUpdatePriority},resolveUpdatePriority(){if(currentUpdatePriority!==NoEventPriority)return currentUpdatePriority;return DefaultEventPriority},maySuspendCommit(){return!1},NotPendingTransition:null,HostTransitionContext:createContext2(null),resetFormInstance(){},requestPostPaintCallback(){},shouldAttemptEagerTransition(){return!1},trackSchedulerEvent(){},resolveEventType(){return null},resolveEventTimeStamp(){return-1.1},preloadInstance(){return!0},startSuspendingCommit(){},suspendInstance(){},waitForCommitToBeReady(){return null},hideInstance(instance){instance.hidden=!0;let epoch=getRenderEpoch(),bits=CONTENT_BIT|STYLE_PROPS_BIT;if(instance.dirtyBits=instance.dirtyEpoch!==epoch?bits:instance.dirtyBits|bits,instance.dirtyEpoch=epoch,instance.layoutDirty=!0,instance.layoutNode)instance.layoutNode.markDirty();if(trackLayoutDirty(instance),trackContentDirty(instance),instance.parent){if(instance.parent.dirtyEpoch!==epoch)instance.parent.dirtyBits=CONTENT_BIT,instance.parent.dirtyEpoch=epoch;else instance.parent.dirtyBits|=CONTENT_BIT;trackContentDirty(instance.parent)}markLayoutAncestorDirty(instance),markSubtreeDirty(instance)},unhideInstance(instance,_props){instance.hidden=!1;let epoch=getRenderEpoch(),bits=CONTENT_BIT|STYLE_PROPS_BIT;if(instance.dirtyBits=instance.dirtyEpoch!==epoch?bits:instance.dirtyBits|bits,instance.dirtyEpoch=epoch,instance.layoutDirty=!0,instance.layoutNode)instance.layoutNode.markDirty();if(trackLayoutDirty(instance),trackContentDirty(instance),instance.parent){if(instance.parent.dirtyEpoch!==epoch)instance.parent.dirtyBits=CONTENT_BIT,instance.parent.dirtyEpoch=epoch;else instance.parent.dirtyBits|=CONTENT_BIT;trackContentDirty(instance.parent)}markLayoutAncestorDirty(instance),markSubtreeDirty(instance)},hideTextInstance(textInstance){textInstance.hidden=!0;let epoch=getRenderEpoch(),bits=CONTENT_BIT|STYLE_PROPS_BIT;if(textInstance.dirtyBits=textInstance.dirtyEpoch!==epoch?bits:textInstance.dirtyBits|bits,textInstance.dirtyEpoch=epoch,trackContentDirty(textInstance),textInstance.parent){if(textInstance.parent.dirtyEpoch!==epoch)textInstance.parent.dirtyBits=CONTENT_BIT,textInstance.parent.dirtyEpoch=epoch;else textInstance.parent.dirtyBits|=CONTENT_BIT;trackContentDirty(textInstance.parent)}markLayoutAncestorDirty(textInstance),markSubtreeDirty(textInstance)},unhideTextInstance(textInstance,_text){textInstance.hidden=!1;let epoch=getRenderEpoch(),bits=CONTENT_BIT|STYLE_PROPS_BIT;if(textInstance.dirtyBits=textInstance.dirtyEpoch!==epoch?bits:textInstance.dirtyBits|bits,textInstance.dirtyEpoch=epoch,trackContentDirty(textInstance),textInstance.parent){if(textInstance.parent.dirtyEpoch!==epoch)textInstance.parent.dirtyBits=CONTENT_BIT,textInstance.parent.dirtyEpoch=epoch;else textInstance.parent.dirtyBits|=CONTENT_BIT;trackContentDirty(textInstance.parent)}markLayoutAncestorDirty(textInstance),markSubtreeDirty(textInstance)}};var reconciler=Reconciler(hostConfig);function createContainer(onRender){return{root:createRootNode(),onRender}}function createFiberRoot(container){return reconciler.createContainer(container,1,null,!1,null,"",()=>{},()=>{},()=>{},null)}function getContainerRoot(container){return container.root}async function ensureLayoutEngine(){if(!isLayoutEngineInitialized())await ensureDefaultLayoutEngine()}function layout(element,dims,options={}){if(!isLayoutEngineInitialized())throw Error("Layout engine not initialized. Call ensureLayoutEngine() first.");let{skipLayoutNotifications=!0,plain=!1}=options,{cols:width,rows:height}=dims,container=createContainer(()=>{}),fiberRoot=createFiberRoot(container),mockStdout={columns:width,rows:height,write:()=>!0,isTTY:!1,on:()=>mockStdout,off:()=>mockStdout,once:()=>mockStdout,removeListener:()=>mockStdout,addListener:()=>mockStdout},mockTerm=createTerm({color:plain?null:"truecolor"}),wrapped=React.createElement(TermContext.Provider,{value:mockTerm},React.createElement(StdoutContext.Provider,{value:{stdout:mockStdout,write:()=>{}}},React.createElement(StderrContext.Provider,{value:{stderr:process.stderr,write:(data)=>{process.stderr.write(data)}}},element)));withoutActWarnings(()=>{reconciler.updateContainerSync(wrapped,fiberRoot,null,null),reconciler.flushSyncWork()});let root=getContainerRoot(container),{buffer:termBuffer}=executeRender(root,width,height,null,{skipLayoutNotifications}),text=bufferToText(termBuffer),ansi=bufferToStyledText(termBuffer);return withoutActWarnings(()=>{reconciler.updateContainerSync(null,fiberRoot,null,null),reconciler.flushSyncWork()}),{text,ansi,nodes:root,_buffer:termBuffer}}function layoutSync(element,dims,options={}){return layout(element,dims,options)}function withoutActWarnings(fn){let prev=globalThis.IS_REACT_ACT_ENVIRONMENT;globalThis.IS_REACT_ACT_ENVIRONMENT=!1;try{fn()}finally{globalThis.IS_REACT_ACT_ENVIRONMENT=prev}}function diff(prev,next,mode="fullscreen",scrollbackOffset=0,termRows){let prevBuffer=prev?._buffer??null,nextBuffer=next._buffer;return outputPhase(prevBuffer,nextBuffer,mode,scrollbackOffset,termRows)}function render(buffer,mode="fullscreen"){return outputPhase(null,buffer._buffer,mode)}init_buffer();function createBuffer2(termBuffer,nodes){let _text,_ansi;return{get text(){return _text??=bufferToText(termBuffer)},get ansi(){return _ansi??=bufferToStyledText(termBuffer)},nodes,_buffer:termBuffer}}init_output_phase();async function*merge(...sources){if(sources.length===0)return;let iterators=sources.map((source)=>source[Symbol.asyncIterator]()),pending=new Map;async function nextWithIndex(idx){let iterator=iterators[idx];if(!iterator)throw Error(`No iterator at index ${idx}`);let result=await iterator.next();return{index:idx,result}}for(let i=0;i<iterators.length;i++)pending.set(i,nextWithIndex(i));try{while(pending.size>0){let{index,result}=await Promise.race(pending.values());if(result.done)pending.delete(index);else yield result.value,pending.set(index,nextWithIndex(index))}}finally{await Promise.all(iterators.map((it)=>it.return?it.return():Promise.resolve()))}}async function*map(source,fn){let iterator=source[Symbol.asyncIterator]();try{for await(let value of{[Symbol.asyncIterator]:()=>iterator})yield fn(value)}finally{if(iterator.return)await iterator.return()}}async function*filter(source,predicate){let iterator=source[Symbol.asyncIterator]();try{for await(let value of{[Symbol.asyncIterator]:()=>iterator})if(predicate(value))yield value}finally{if(iterator.return)await iterator.return()}}async function*filterMap(source,fn){let iterator=source[Symbol.asyncIterator]();try{for await(let value of{[Symbol.asyncIterator]:()=>iterator}){let mapped=fn(value);if(mapped!==void 0)yield mapped}}finally{if(iterator.return)await iterator.return()}}async function*takeUntil(source,signal2){if(signal2.aborted)return;let iterator=source[Symbol.asyncIterator](),abortResolve,abortPromise=new Promise((resolve)=>{abortResolve=resolve}),onAbort=()=>abortResolve();signal2.addEventListener("abort",onAbort,{once:!0});try{while(!signal2.aborted){let result=await Promise.race([iterator.next(),abortPromise.then(()=>({done:!0,value:void 0}))]);if(result.done)break;yield result.value}}finally{if(signal2.removeEventListener("abort",onAbort),iterator.return)await iterator.return()}}async function*take(source,count){if(count<=0)return;let iterator=source[Symbol.asyncIterator](),taken=0;try{for await(let value of{[Symbol.asyncIterator]:()=>iterator})if(yield value,taken++,taken>=count)break}finally{if(iterator.return)await iterator.return()}}async function*fromArray(items){for(let item of items)yield item}async function*fromArrayWithDelay(items,delayMs){for(let item of items)await new Promise((resolve)=>setTimeout(resolve,delayMs)),yield item}async function*throttle(source,ms){let iterator=source[Symbol.asyncIterator](),lastEmit=0;try{for await(let value of{[Symbol.asyncIterator]:()=>iterator}){let now=Date.now();if(now-lastEmit>=ms)lastEmit=now,yield value}}finally{if(iterator.return)await iterator.return()}}async function*debounce(source,ms){let iterator=source[Symbol.asyncIterator](),last;try{for await(let value of{[Symbol.asyncIterator]:()=>iterator})last={value};if(last)await new Promise((resolve)=>setTimeout(resolve,ms)),yield last.value}finally{if(iterator.return)await iterator.return()}}function batch(source,size){if(size<=0)throw Error("Batch size must be positive");return batchImpl(source,size)}async function*batchImpl(source,size){let iterator=source[Symbol.asyncIterator](),buffer=[];try{for await(let value of{[Symbol.asyncIterator]:()=>iterator})if(buffer.push(value),buffer.length>=size)yield buffer,buffer=[];if(buffer.length>0)yield buffer}finally{if(iterator.return)await iterator.return()}}async function*concat(...sources){for(let source of sources)yield*source}async function*zip(...sources){let iterators=sources.map((source)=>source[Symbol.asyncIterator]());try{while(!0){let results=await Promise.all(iterators.map((it)=>it.next()));if(results.some((r)=>r.done))break;yield results.map((r)=>r.value)}}finally{await Promise.all(iterators.map((it)=>it.return?it.return():Promise.resolve()))}}function createEventChannel(signal2){let queue=[],pendingResolve,disposed=!1,onAbort=()=>{if(pendingResolve)pendingResolve(null),pendingResolve=void 0};return signal2.addEventListener("abort",onAbort,{once:!0}),{push(event){if(disposed||signal2.aborted)return;if(pendingResolve){let r=pendingResolve;pendingResolve=void 0,r(event)}else queue.push(event)},events(){return{[Symbol.asyncIterator](){return{async next(){if(disposed||signal2.aborted)return{done:!0,value:void 0};if(queue.length>0)return{done:!1,value:queue.shift()};let event=await new Promise((resolve)=>{pendingResolve=resolve});if(event===null||disposed||signal2.aborted)return{done:!0,value:void 0};return{done:!1,value:event}}}}}},dispose(){if(disposed=!0,signal2.removeEventListener("abort",onAbort),pendingResolve)pendingResolve(null),pendingResolve=void 0}}}function createRuntime(options){let{target,signal:externalSignal,mode="fullscreen"}=options,fallbackOutputPhase=mode==="inline"?createOutputPhase({}):void 0,outputPhaseFn=options.outputPhaseFn??fallbackOutputPhase,controller=new AbortController,signal2=controller.signal,externalAbortHandler;if(externalSignal)if(externalSignal.aborted)controller.abort();else externalAbortHandler=()=>controller.abort(),externalSignal.addEventListener("abort",externalAbortHandler,{once:!0});let prevBuffer=null,scrollbackOffset=0,disposed=!1,eventChannel=createEventChannel(signal2),unsubscribeResize;if(target.onResize)unsubscribeResize=target.onResize((dims)=>{eventChannel.push({type:"resize",cols:dims.cols,rows:dims.rows})});let effectId=0;return{events(){return takeUntil(eventChannel.events(),signal2)},schedule(effect2,opts){if(disposed)return;let id=`effect-${effectId++}`,effectSignal=opts?.signal;if(effectSignal?.aborted)return;let execute=async()=>{let abortHandler;try{if(effectSignal){let aborted=new Promise((_resolve,reject)=>{abortHandler=()=>reject(Error("Effect aborted")),effectSignal.addEventListener("abort",abortHandler,{once:!0})}),result=await Promise.race([effect2(),aborted]);if(abortHandler)effectSignal.removeEventListener("abort",abortHandler);eventChannel.push({type:"effect",id,result})}else{let result=await effect2();eventChannel.push({type:"effect",id,result})}}catch(error){if(abortHandler&&effectSignal)effectSignal.removeEventListener("abort",abortHandler);if(error instanceof Error&&(error.message==="Effect aborted"||error.name==="AbortError"))return;eventChannel.push({type:"error",error:error instanceof Error?error:Error(String(error))})}};queueMicrotask(()=>{execute()})},render(buffer){if(disposed)return;let offset=scrollbackOffset;scrollbackOffset=0;let termRows=target.getDims().rows,patch;if(outputPhaseFn){let prevBuf=prevBuffer?._buffer??null,nextBuf=buffer._buffer;patch=outputPhaseFn(prevBuf,nextBuf,mode,offset,termRows)}else patch=diff(prevBuffer,buffer,mode,offset,termRows);if(prevBuffer=buffer,process.env.SILVERY_CAPTURE_RAW)try{__require("fs").appendFileSync("/tmp/silvery-runtime-raw.ansi",patch)}catch{}target.write(patch)},addScrollbackLines(lines){if(mode!=="inline"||lines<=0)return;scrollbackOffset+=lines},invalidate(){prevBuffer=null},setOutputPhaseFn(fn){if(fn)outputPhaseFn=fn},resetInlineCursor(){outputPhaseFn?.resetInlineState?.()},getInlineCursorRow(){return outputPhaseFn?.getInlineCursorRow?.()??-1},promoteScrollback(content,lines){outputPhaseFn?.promoteScrollback?.(content,lines)},getDims(){return target.getDims()},[Symbol.dispose](){if(disposed)return;if(disposed=!0,controller.abort(),externalAbortHandler&&externalSignal)externalSignal.removeEventListener("abort",externalAbortHandler);if(unsubscribeResize)unsubscribeResize();eventChannel.dispose()}}}import{useContext as useContext5,useEffect as useEffect3,useRef as useRef4}from"react";import{writeSync as writeSync3}from"node:fs";import process2 from"node:process";import React5,{createContext as createContext4,useContext as useContext3,useEffect as useEffect2,useRef as useRef3}from"react";function createStore(factory){let listeners=new Set,state$=signal(void 0),initialState,setState=(partial,replace)=>{let prev=state$(),raw=typeof partial==="function"?partial(prev):partial,next;if(!replace&&raw!==null&&typeof raw==="object"&&!Array.isArray(raw))next={...prev,...raw};else next=raw;if(Object.is(prev,next))return;state$(next);for(let listener of listeners)listener(next,prev)},getState=()=>state$(),api={setState,getState,getInitialState:()=>initialState,subscribe:(listener)=>{return listeners.add(listener),()=>{listeners.delete(listener)}}},created=factory(setState,getState,api);return state$(created),initialState=created,api}init_ansi2();import*as fs from"node:fs";import React2,{Component}from"react";function parseStackLine(line){let trimmed=line.trim();if(!trimmed.startsWith("at "))return null;let rest=trimmed.slice(3),match1=rest.match(/^(.+?)\s+\((.+?):(\d+):(\d+)\)$/);if(match1)return{function:match1[1],file:match1[2],line:Number(match1[3]),column:Number(match1[4])};let match2=rest.match(/^(.+?):(\d+):(\d+)$/);if(match2)return{file:match2[1],line:Number(match2[2]),column:Number(match2[3])};return null}function cleanupPath(filePath){if(!filePath)return filePath;let p=filePath,cwdPath=process.cwd();p=p.replace(/^file:\/\//,"");for(let prefix of[cwdPath,`/private${cwdPath}`])if(p.startsWith(`${prefix}/`)){p=p.slice(prefix.length+1);break}return p}function getCodeExcerpt(filePath,line){try{if(!fs.existsSync(filePath))return null;let lines=fs.readFileSync(filePath,"utf8").split(`
73
78
  `),start=Math.max(0,line-4),end=Math.min(lines.length,line+3),result=[];for(let i=start;i<end;i++)result.push({line:i+1,value:(lines[i]??"").replace(/\t/g," ")});return result}catch{return null}}class SilveryErrorBoundary extends Component{state={error:null};static getDerivedStateFromError(error){return{error}}componentDidCatch(error){this.props.onError?.(error)}render(){if(this.state.error){let err=this.state.error,stack=err.stack?err.stack.split(`
74
- `).slice(1):[],origin=stack.length>0?parseStackLine(stack[0]):null,filePath=cleanupPath(origin?.file),excerpt=null,lineWidth=0;if(filePath&&origin?.line){if(excerpt=getCodeExcerpt(filePath,origin.line),excerpt)for(let{line}of excerpt)lineWidth=Math.max(lineWidth,String(line).length)}let children=[];if(children.push(React2.createElement("silvery-box",{key:"header"},React2.createElement("silvery-text",{backgroundColor:"red",color:"white"}," ERROR "),React2.createElement("silvery-text",{},` ${err.message}`))),filePath&&origin)children.push(React2.createElement("silvery-box",{key:"location",marginTop:1},React2.createElement("silvery-text",{dimColor:!0},`${filePath}:${origin.line}:${origin.column}`)));if(excerpt&&origin){let codeLines=excerpt.map(({line,value})=>{let lineNum=String(line).padStart(lineWidth," ");return React2.createElement("silvery-box",{key:`code-${line}`},React2.createElement("silvery-text",{dimColor:line!==origin.line,backgroundColor:line===origin.line?"red":void 0,color:line===origin.line?"white":void 0},`${lineNum}:`),React2.createElement("silvery-text",{backgroundColor:line===origin.line?"red":void 0,color:line===origin.line?"white":void 0},` ${value}`))});children.push(React2.createElement("silvery-box",{key:"code",marginTop:1,flexDirection:"column"},...codeLines))}if(stack.length>0){let stackLines=stack.map((line,i)=>{let parsed=parseStackLine(line);if(!parsed)return React2.createElement("silvery-box",{key:`stack-${i}`},React2.createElement("silvery-text",{dimColor:!0},`- ${line.trim()}`));let cleanFile=cleanupPath(parsed.file);return React2.createElement("silvery-box",{key:`stack-${i}`},React2.createElement("silvery-text",{dimColor:!0},"- "),React2.createElement("silvery-text",{dimColor:!0,bold:!0},parsed.function??""),React2.createElement("silvery-text",{dimColor:!0,color:"gray"},` (${cleanFile??""}:${parsed.line}:${parsed.column})`))});children.push(React2.createElement("silvery-box",{key:"stack",marginTop:1,flexDirection:"column"},...stackLines))}return React2.createElement("silvery-box",{flexDirection:"column",padding:1},...children)}return this.props.children}}function isFocusable(node){if(node.hidden)return!1;let props=node.props;return Boolean(props.focusable)&&props.display!=="none"}function isFocusScope(node){let props=node.props;return Boolean(props.focusScope)}function findFocusableAncestor(node){let current=node;while(current){if(isFocusable(current))return current;current=current.parent}return null}function getTabOrder(root,scope){let result=[],walkRoot=scope??root;function walk(node){if(node.hidden)return;if(node.props.display==="none")return;if(node!==walkRoot&&isFocusScope(node)){if(isFocusable(node))result.push(node);return}if(isFocusable(node))result.push(node);for(let child of node.children)walk(child)}return walk(walkRoot),result}function findByTestID(root,testID){if(root.props.testID===testID)return root;for(let child of root.children){let found=findByTestID(child,testID);if(found)return found}return null}function rectCenter(rect){return{cx:rect.x+rect.width/2,cy:rect.y+rect.height/2}}function isInCone(source,candidate,direction){let dx=candidate.cx-source.cx,dy=candidate.cy-source.cy;switch(direction){case"up":if(dy>=0)return!1;return Math.abs(dx)<=Math.abs(dy);case"down":if(dy<=0)return!1;return Math.abs(dx)<=Math.abs(dy);case"left":if(dx>=0)return!1;return Math.abs(dy)<=Math.abs(dx);case"right":if(dx<=0)return!1;return Math.abs(dy)<=Math.abs(dx)}}function distance(a,b){let dx=a.cx-b.cx,dy=a.cy-b.cy;return Math.sqrt(dx*dx+dy*dy)}function findSpatialTarget(from,direction,candidates,layoutFn){let sourceRect=layoutFn(from);if(!sourceRect)return null;let source=rectCenter(sourceRect),best=null,bestDist=1/0;for(let candidate of candidates){if(candidate===from)continue;let candidateRect=layoutFn(candidate);if(!candidateRect)continue;let target=rectCenter(candidateRect);if(!isInCone(source,target,direction))continue;let dist=distance(source,target);if(dist<bestDist)bestDist=dist,best=candidate}return best}function getExplicitFocusLink(node,direction){let props=node.props,propName=`nextFocus${direction.charAt(0).toUpperCase()}${direction.slice(1)}`,value=props[propName];return typeof value==="string"?value:null}function ensureInteractiveState(node){if(!node.interactiveState)node.interactiveState={hovered:!1,armed:!1,selected:!1,focused:!1,dropTarget:!1};return node.interactiveState}function setHovered(node,value){let state=ensureInteractiveState(node);if(state.hovered===value)return!1;return state.hovered=value,!0}function setArmed(node,value){let state=ensureInteractiveState(node);if(state.armed===value)return!1;return state.armed=value,!0}function setFocused(node,value){let state=ensureInteractiveState(node);if(state.focused===value)return!1;return state.focused=value,!0}function createFocusManager(options){let onFocusChange=options?.onFocusChange,activeElement=null,activeId=null,previousElement=null,previousId=null,focusOrigin=null,scopeStack=[],scopeMemory={},activeScopeId=null,hookFocusables=[],hookFocusEnabled=!0,listeners=new Set,snapshot=null,notifyCount=0;function notify(){snapshot=null,notifyCount++;for(let listener of listeners)listener()}function getTestID(node){let props=node.props;return typeof props.testID==="string"?props.testID:null}function focus(node,origin="programmatic"){if(activeElement===node){if(focusOrigin!==origin)focusOrigin=origin,notify();return}let oldElement=activeElement;if(previousElement=activeElement,previousId=activeId,activeElement=node,activeId=getTestID(node),focusOrigin=origin,oldElement)setFocused(oldElement,!1);if(setFocused(node,!0),activeId&&scopeStack.length>0)scopeMemory[scopeStack[scopeStack.length-1]]=activeId;notify(),onFocusChange?.(oldElement,node,origin)}function focusById(id,root,origin="programmatic"){let node=findByTestID(root,id);if(node){let focusable=findFocusableAncestor(node);if(focusable){focus(focusable,origin);return}}let oldElement=activeElement;if(previousElement=activeElement,previousId=activeId,activeElement=null,activeId=id,focusOrigin=origin,oldElement)setFocused(oldElement,!1);notify(),onFocusChange?.(oldElement,null,origin)}function blur(){if(!activeElement&&!activeId)return;let oldElement=activeElement;if(previousElement=activeElement,previousId=activeId,activeElement=null,activeId=null,focusOrigin=null,oldElement)setFocused(oldElement,!1);notify(),onFocusChange?.(oldElement,null,null)}function focusVirtualId(id,origin="programmatic"){if(activeId===id&&!activeElement){if(focusOrigin!==origin)focusOrigin=origin,notify();return}let oldElement=activeElement;if(previousElement=activeElement,previousId=activeId,activeElement=null,activeId=id,focusOrigin=origin,oldElement)setFocused(oldElement,!1);notify(),onFocusChange?.(oldElement,null,origin)}function registerHookFocusable(id,opts={}){let{isActive=!0,autoFocus=!1}=opts,existing=hookFocusables.findIndex((f)=>f.id===id);if(existing!==-1)hookFocusables[existing]={id,isActive};else hookFocusables.push({id,isActive});if(autoFocus&&isActive&&activeId===null)focusVirtualId(id,"programmatic");else notify();return()=>{let idx=hookFocusables.findIndex((f)=>f.id===id);if(idx===-1)return;if(hookFocusables.splice(idx,1),activeId===id&&!activeElement){previousId=activeId,activeId=null,focusOrigin=null,notify(),onFocusChange?.(null,null,null);return}notify()}}function setHookFocusableActive(id,isActive){let entry=hookFocusables.find((f)=>f.id===id);if(!entry)return;if(entry.isActive===isActive)return;if(entry.isActive=isActive,!isActive&&activeId===id&&!activeElement){previousId=activeId,activeId=null,focusOrigin=null,notify(),onFocusChange?.(null,null,null);return}notify()}function setHookFocusEnabled(enabled){if(hookFocusEnabled===enabled)return;hookFocusEnabled=enabled,notify()}function subtreeContains(subtreeRoot,target){if(subtreeRoot===target)return!0;for(let child of subtreeRoot.children)if(subtreeContains(child,target))return!0;return!1}function handleSubtreeRemoved(removedRoot){let changed=!1;if(activeElement&&subtreeContains(removedRoot,activeElement)){let oldElement=activeElement;setFocused(oldElement,!1),previousElement=activeElement,previousId=activeId,activeElement=null,activeId=null,focusOrigin=null,changed=!0,onFocusChange?.(oldElement,null,null)}if(previousElement&&subtreeContains(removedRoot,previousElement))previousElement=null,previousId=null,changed=!0;if(changed)notify()}function enterScope(scopeId){scopeStack.push(scopeId),notify()}function exitScope(){if(scopeStack.pop()===void 0)return;notify()}function activateScope(scopeId,root){if(activeScopeId&&activeId)scopeMemory[activeScopeId]=activeId;activeScopeId=scopeId;let countBefore=notifyCount,remembered=scopeMemory[scopeId];if(remembered)focusById(remembered,root,"programmatic");else{let scopeNode=findByTestID(root,scopeId);if(scopeNode){let order=getTabOrder(root,scopeNode);if(order.length>0)focus(order[0],"programmatic")}}if(notifyCount===countBefore)notify()}function getFocusPath(root){if(!activeElement)return[];let path=[],current=activeElement;while(current&&current!==root.parent){let id=getTestID(current);if(id)path.push(id);current=current.parent}return path}function hasFocusWithin(root,testID){if(!activeElement)return!1;let target=findByTestID(root,testID);if(!target)return!1;let current=activeElement;while(current){if(current===target)return!0;current=current.parent}return!1}function resolveScope(root,explicitScope){if(explicitScope)return explicitScope;if(scopeStack.length>0){let scopeId=scopeStack[scopeStack.length-1],scopeNode=findByTestID(root,scopeId);if(scopeNode)return scopeNode}return}function buildTabEntries(root,scope){let effectiveScope=resolveScope(root,scope),entries=getTabOrder(root,effectiveScope).map((node)=>({kind:"node",node}));if(!effectiveScope&&hookFocusEnabled){for(let entry of hookFocusables)if(entry.isActive)entries.push({kind:"hook",id:entry.id})}return entries}function currentTabIndex(entries){if(activeElement){for(let i=0;i<entries.length;i++){let e=entries[i];if(e.kind==="node"&&e.node===activeElement)return i}return-1}if(activeId)for(let i=0;i<entries.length;i++){let e=entries[i];if(e.kind==="hook"&&e.id===activeId)return i}return-1}function focusTabEntry(entry,origin){if(entry.kind==="node")focus(entry.node,origin);else focusVirtualId(entry.id,origin)}function focusNext(root,scope){let entries=buildTabEntries(root,scope);if(entries.length===0)return;let currentIndex=currentTabIndex(entries);if(currentIndex===-1){focusTabEntry(entries[0],"keyboard");return}let nextIndex=(currentIndex+1)%entries.length;focusTabEntry(entries[nextIndex],"keyboard")}function focusPrev(root,scope){let entries=buildTabEntries(root,scope);if(entries.length===0)return;let currentIndex=currentTabIndex(entries);if(currentIndex===-1){focusTabEntry(entries[entries.length-1],"keyboard");return}let prevIndex=currentIndex<=0?entries.length-1:currentIndex-1;focusTabEntry(entries[prevIndex],"keyboard")}function focusDirection(root,direction,layoutFn){if(!activeElement)return;let explicitTarget=getExplicitFocusLink(activeElement,direction);if(explicitTarget){focusById(explicitTarget,root,"keyboard");return}let candidates=getTabOrder(root),target=findSpatialTarget(activeElement,direction,candidates,layoutFn??((node)=>node.scrollRect));if(target)focus(target,"keyboard")}function subscribe(listener){return listeners.add(listener),()=>{listeners.delete(listener)}}function getSnapshot(){if(!snapshot)snapshot={activeId,previousId,focusOrigin,scopeStack:[...scopeStack],activeScopeId};return snapshot}return{get activeElement(){return activeElement},get activeId(){return activeId},get previousElement(){return previousElement},get previousId(){return previousId},get focusOrigin(){return focusOrigin},get scopeStack(){return[...scopeStack]},get scopeMemory(){return scopeMemory},get activeScopeId(){return activeScopeId},focus,focusById,focusVirtualId,blur,handleSubtreeRemoved,enterScope,exitScope,activateScope,getFocusPath,hasFocusWithin,focusNext,focusPrev,focusDirection,subscribe,getSnapshot,registerHookFocusable,setHookFocusableActive,get hasHookFocusables(){return hookFocusables.length>0},get hookFocusEnabled(){return hookFocusEnabled},setHookFocusEnabled}}import React3,{createContext as createContext3,useCallback,useContext as useContext2,useEffect,useLayoutEffect as useLayoutEffect2,useRef as useRef2}from"react";import{useContext,useLayoutEffect,useReducer,useRef}from"react";function createCursorStore(){let store={state:null,listeners:new Set,accessors:null,setCursorState(s){store.state=s;for(let listener of store.listeners)listener()}};return store.accessors={getCursorState:()=>store.state,subscribeCursor:(listener)=>{return store.listeners.add(listener),()=>{store.listeners.delete(listener)}}},store}var CursorCtx=createContext3(null);function CursorProvider({store,children}){return React3.createElement(CursorCtx.Provider,{value:store},children)}function getAncestorPath(node){let path=[],current=node;while(current)path.push(current),current=current.parent;return path}function pointInRect(x,y,rect){return x>=rect.x&&x<rect.x+rect.width&&y>=rect.y&&y<rect.y+rect.height}function createKeyEvent(input,key,target){let propagationStopped=!1,defaultPrevented=!1;return{key:input,input,ctrl:key.ctrl,meta:key.meta,shift:key.shift,super:key.super,hyper:key.hyper,eventType:key.eventType,target,currentTarget:target,nativeEvent:{input,key},get propagationStopped(){return propagationStopped},get defaultPrevented(){return defaultPrevented},stopPropagation(){propagationStopped=!0},preventDefault(){defaultPrevented=!0}}}function createFocusEvent(type,target,relatedTarget){let propagationStopped=!1;return{type,target,relatedTarget,currentTarget:target,get propagationStopped(){return propagationStopped},stopPropagation(){propagationStopped=!0}}}function dispatchKeyEvent(event,dispatch){let path=getAncestorPath(event.target),mutableEvent=event,isRelease=event.eventType==="release",handlerProp=isRelease?"onKeyUp":"onKeyDown";if(!isRelease)for(let i=path.length-1;i>0;i--){if(event.propagationStopped)return;let node=path[i],handler=node.props.onKeyDownCapture;if(handler)mutableEvent.currentTarget=node,handler(event)}if(!event.propagationStopped){let target=path[0];mutableEvent.currentTarget=target;let handler=target.props[handlerProp];if(handler)handler(event,dispatch)}for(let i=1;i<path.length;i++){if(event.propagationStopped)return;let node=path[i],handler=node.props[handlerProp];if(handler)mutableEvent.currentTarget=node,handler(event,dispatch)}}function dispatchFocusEvent(event){let handlerProp=event.type==="focus"?"onFocus":"onBlur",path=getAncestorPath(event.target),mutableEvent=event;for(let node of path){if(event.propagationStopped)break;let handler=node.props[handlerProp];if(handler)mutableEvent.currentTarget=node,handler(event)}}init_unicode();init_output_phase();function createPipeline(options={}){let{caps,measurer:explicitMeasurer}=options,measurer=explicitMeasurer??createWidthMeasurer(caps?{textEmojiWide:caps.textEmojiWide,textSizingEnabled:caps.textSizingSupported}:{}),outputPhaseFn=createOutputPhase(caps?{underlineStyles:caps.underlineStyles,underlineColor:caps.underlineColor,colorLevel:caps.colorLevel}:{},measurer);return{measurer,outputPhaseFn}}init_text_sizing();init_output_phase();import React4 from"react";init_keys();init_buffer();init_output_phase();init_unicode();init_src2();var ESC2="\x1B",CSI=`${ESC2}[`,CURSOR_HIDE=`${CSI}?25l`,CURSOR_SHOW=`${CSI}?25h`,CURSOR_HOME=`${CSI}H`,SYNC_BEGIN=`${CSI}?2026h`,SYNC_END=`${CSI}?2026l`,RESET=`${CSI}0m`;function resetCursorStyle(){return`${CSI}0 q`}function enterAlternateScreen(){return`${CSI}?1049h${CSI}2J${CURSOR_HOME}${CURSOR_HIDE}`}function leaveAlternateScreen(){return`${SYNC_END}${CURSOR_SHOW}${CSI}?1049l`}var enableMouse2=enableMouse,disableMouse2=disableMouse,KittyFlags={DISAMBIGUATE:1,REPORT_EVENTS:2,REPORT_ALTERNATE:4,REPORT_ALL_KEYS:8,REPORT_TEXT:16},enableKittyKeyboard2=enableKittyKeyboard;function queryKittyKeyboard(){return`${CSI}?u`}var disableKittyKeyboard2=disableKittyKeyboard;init_src2();var KITTY_RESPONSE_RE=/\x1b\[\?(\d+)u/;async function detectKittySupport(write,read,timeoutMs=200){write(queryKittyKeyboard());let data=await read(timeoutMs);if(data==null)return{supported:!1,flags:0};let match=KITTY_RESPONSE_RE.exec(data);if(!match)return{supported:!1,flags:0,buffered:data};let flags=parseInt(match[1],10),before=data.slice(0,match.index),after=data.slice(match.index+match[0].length),buffered=before+after;return{supported:!0,flags,buffered:buffered||void 0}}async function detectKittyFromStdio(stdout,stdin,timeoutMs=200){let wasRaw=stdin.isRaw;if(!wasRaw)stdin.setRawMode(!0);try{return await detectKittySupport((s)=>{stdout.write(s)},(ms)=>new Promise((resolve)=>{let timer=setTimeout(()=>{stdin.removeListener("data",onData),resolve(null)},ms);function onData(chunk){clearTimeout(timer),stdin.removeListener("data",onData),resolve(chunk.toString())}stdin.on("data",onData)}),timeoutMs)}finally{if(!wasRaw)stdin.setRawMode(!1)}}init_detection2();var ESC3="\x1B",CSI2=`${ESC3}[`,RESET2=`${CSI2}0m`;init_text_sizing();init_src2();init_src2();var WidthMode={UTF8:1020,CJK_WIDTH:1021,EMOJI_WIDTH:1022,PRIVATE_USE_WIDTH:1023},DEFAULT_WIDTH_CONFIG={utf8:!0,cjkWidth:1,emojiWidth:2,privateUseWidth:1},DECRPM_RE=/\x1b\[\?(\d+);(\d+)\$y/g;function isSet(ps){return ps===1||ps===3}function queryWidthMode(write,onData,mode,timeoutMs){return new Promise((resolve)=>{let timer=null,unsubscribe=null,buffer="";function cleanup(){if(timer!==null)clearTimeout(timer),timer=null;if(unsubscribe!==null)unsubscribe(),unsubscribe=null}unsubscribe=onData((data)=>{buffer+=data,DECRPM_RE.lastIndex=0;let match;while((match=DECRPM_RE.exec(buffer))!==null)if(parseInt(match[1],10)===mode){let ps=parseInt(match[2],10);cleanup(),resolve(ps);return}}),timer=setTimeout(()=>{cleanup(),resolve(null)},timeoutMs),write(`\x1B[?${mode}$p`)})}function applyWidthConfig(caps,config){return{...caps,textEmojiWide:config.emojiWidth===2,textSizingSupported:config.privateUseWidth===2}}function createWidthDetector(options){let{write,onData,timeoutMs=200}=options,config=null,disposed=!1;return{get config(){return config},async detect(){if(disposed)return config??{...DEFAULT_WIDTH_CONFIG};if(config!==null)return config;let utf8Ps=await queryWidthMode(write,onData,WidthMode.UTF8,timeoutMs),cjkPs=await queryWidthMode(write,onData,WidthMode.CJK_WIDTH,timeoutMs),emojiPs=await queryWidthMode(write,onData,WidthMode.EMOJI_WIDTH,timeoutMs),puaPs=await queryWidthMode(write,onData,WidthMode.PRIVATE_USE_WIDTH,timeoutMs);return config={utf8:utf8Ps!==null?isSet(utf8Ps):DEFAULT_WIDTH_CONFIG.utf8,cjkWidth:cjkPs!==null?isSet(cjkPs)?2:1:DEFAULT_WIDTH_CONFIG.cjkWidth,emojiWidth:emojiPs!==null?isSet(emojiPs)?2:1:DEFAULT_WIDTH_CONFIG.emojiWidth,privateUseWidth:puaPs!==null?isSet(puaPs)?2:1:DEFAULT_WIDTH_CONFIG.privateUseWidth},config},dispose(){disposed=!0}}}init_mouse();import{createLogger as createLogger11}from"loggily";var mouseLog=createLogger11("silvery:mouse");function createMouseEvent(type,x,y,target,parsed,keyboardMods){let propagationStopped=!1,defaultPrevented=!1,metaKey=keyboardMods?.super??!1;if(type==="click"||type==="mousedown")mouseLog.debug?.(`createMouseEvent(${type}) metaKey=${metaKey} keyboardMods.super=${keyboardMods?.super}`);return{type,clientX:x,clientY:y,button:parsed.button,altKey:parsed.meta,ctrlKey:parsed.ctrl,metaKey,shiftKey:parsed.shift,target,currentTarget:target,nativeEvent:parsed,get propagationStopped(){return propagationStopped},get defaultPrevented(){return defaultPrevented},stopPropagation(){propagationStopped=!0},preventDefault(){defaultPrevented=!0}}}function createWheelEvent(x,y,target,parsed,keyboardMods){let base=createMouseEvent("wheel",x,y,target,parsed,keyboardMods);return base.deltaY=parsed.delta??0,base.deltaX=0,base}function hitTest(node,x,y){let rect=node.scrollRect;if(!rect)return null;if(!pointInRect(x,y,rect))return null;let props=node.props;if(props.pointerEvents==="none")return null;let clips=props.overflow==="hidden"||props.overflow==="scroll";for(let i=node.children.length-1;i>=0;i--){let child=node.children[i];if(clips){if(child.scrollRect&&!pointInRect(x,y,rect))continue}let hit=hitTest(child,x,y);if(hit)return hit}if(node.type==="silvery-text")for(let i=node.children.length-1;i>=0;i--){let child=node.children[i];if(child.inlineRects){for(let inlineRect of child.inlineRects)if(pointInRect(x,y,inlineRect))return child}}return node}function resolveUserSelect(node){let current=node;while(current){let value=current.props.userSelect;if(value==="none"||value==="text"||value==="contain")return value;current=current.parent}return"text"}function selectionHitTest(node,x,y){let rect=node.scrollRect;if(!rect)return null;if(!pointInRect(x,y,rect))return null;let props=node.props;if(resolveUserSelect(node)==="none")return null;let clips=props.overflow==="hidden"||props.overflow==="scroll";for(let i=node.children.length-1;i>=0;i--){let child=node.children[i];if(clips){if(child.scrollRect&&!pointInRect(x,y,rect))continue}let hit=selectionHitTest(child,x,y);if(hit)return hit}if(node.type==="silvery-text")for(let i=node.children.length-1;i>=0;i--){let child=node.children[i];if(child.inlineRects){for(let inlineRect of child.inlineRects)if(pointInRect(x,y,inlineRect))return child}}return node}function findContainBoundary(node){let current=node;while(current){if(current.props.userSelect==="contain"){let rect=current.scrollRect;if(rect)return{top:rect.y,bottom:rect.y+rect.height-1,left:rect.x,right:rect.x+rect.width-1}}current=current.parent}return null}var EVENT_HANDLER_MAP={click:"onClick",dblclick:"onDoubleClick",mousedown:"onMouseDown",mouseup:"onMouseUp",mousemove:"onMouseMove",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",wheel:"onWheel"};function dispatchMouseEvent(event){let handlerProp=EVENT_HANDLER_MAP[event.type];if(!handlerProp)return;if(event.type==="mouseenter"||event.type==="mouseleave"){let handler=event.target.props[handlerProp];if(handler){let mutableEvent=event;mutableEvent.currentTarget=event.target,handler(event)}return}let path=getAncestorPath(event.target);for(let node of path){if(event.propagationStopped)break;let handler=node.props[handlerProp];if(handler){let mutableEvent=event;mutableEvent.currentTarget=node,handler(event)}}}function createDoubleClickState(){return{lastClickTime:0,lastClickX:-999,lastClickY:-999,lastClickButton:-1}}var DOUBLE_CLICK_TIME_MS=300,DOUBLE_CLICK_DISTANCE=2;function checkDoubleClick(state,x,y,button,now=Date.now()){let timeDelta=now-state.lastClickTime,dx=Math.abs(x-state.lastClickX),dy=Math.abs(y-state.lastClickY),isDouble=button===state.lastClickButton&&timeDelta<=DOUBLE_CLICK_TIME_MS&&dx<=DOUBLE_CLICK_DISTANCE&&dy<=DOUBLE_CLICK_DISTANCE;if(state.lastClickTime=now,state.lastClickX=x,state.lastClickY=y,state.lastClickButton=button,isDouble)state.lastClickTime=0;return isDouble}function computeEnterLeave(prevPath,nextPath){let prevSet=new Set(prevPath),nextSet=new Set(nextPath),entered=nextPath.filter((n)=>!prevSet.has(n)),left=prevPath.filter((n)=>!nextSet.has(n));return{entered,left}}function createMouseEventProcessor(options){return{doubleClick:createDoubleClickState(),hoverPath:[],mouseDownTarget:null,focusManager:options?.focusManager,keyboardModifiers:{super:!1,hyper:!1,capsLock:!1,numLock:!1}}}function updateKeyboardModifiers(state,key){let isRelease=key.eventType==="release",prevSuper=state.keyboardModifiers.super;if(key.super!==void 0)state.keyboardModifiers.super=isRelease?!1:key.super;if(key.hyper!==void 0)state.keyboardModifiers.hyper=isRelease?!1:key.hyper;if(key.capsLock!==void 0)state.keyboardModifiers.capsLock=key.capsLock;if(key.numLock!==void 0)state.keyboardModifiers.numLock=key.numLock;if(state.keyboardModifiers.super!==prevSuper)mouseLog.debug?.(`keyboardModifiers.super: ${prevSuper} → ${state.keyboardModifiers.super} (key.super=${key.super}, eventType=${key.eventType})`)}function processMouseEvent(state,parsed,root){let{x,y,action}=parsed,target=hitTest(root,x,y);if(action==="move"){let nodeType=target?.type??"null",nodeId=target?target.props.id??"":"",enterAncestor="";if(target){let n=target;while(n){if("onMouseEnter"in n.props){enterAncestor=`${n.type}#${n.props.id??""}`;break}n=n.parent}}let newPath=target?getAncestorPath(target):[],{entered}=computeEnterLeave(state.hoverPath,newPath);mouseLog.debug?.(`move x=${x} y=${y} target=${nodeType}#${nodeId} enterAncestor=${enterAncestor||"none"} entered=${entered.length} prevPath=${state.hoverPath.length}`)}if(!target)return!1;let defaultPrevented=!1;if(action==="down"){if(state.mouseDownTarget=target,setArmed(target,!0),state.focusManager){let focusable=findFocusableAncestor(target);if(focusable)state.focusManager.focus(focusable,"mouse")}let event=createMouseEvent("mousedown",x,y,target,parsed,state.keyboardModifiers);if(dispatchMouseEvent(event),event.defaultPrevented)defaultPrevented=!0}else if(action==="up"){if(state.mouseDownTarget)setArmed(state.mouseDownTarget,!1);let event=createMouseEvent("mouseup",x,y,target,parsed,state.keyboardModifiers);if(dispatchMouseEvent(event),state.mouseDownTarget){let clickEvent=createMouseEvent("click",x,y,target,parsed,state.keyboardModifiers);if(dispatchMouseEvent(clickEvent),clickEvent.defaultPrevented)defaultPrevented=!0;if(checkDoubleClick(state.doubleClick,x,y,parsed.button)){let dblEvent=createMouseEvent("dblclick",x,y,target,parsed,state.keyboardModifiers);if(dispatchMouseEvent(dblEvent),dblEvent.defaultPrevented)defaultPrevented=!0}}state.mouseDownTarget=null}else if(action==="move"){let event=createMouseEvent("mousemove",x,y,target,parsed,state.keyboardModifiers);dispatchMouseEvent(event);let newPath=getAncestorPath(target),{entered,left}=computeEnterLeave(state.hoverPath,newPath);for(let node of left){setHovered(node,!1);let leaveEvent=createMouseEvent("mouseleave",x,y,node,parsed,state.keyboardModifiers);dispatchMouseEvent(leaveEvent)}for(let node of entered.reverse()){setHovered(node,!0);let enterEvent=createMouseEvent("mouseenter",x,y,node,parsed,state.keyboardModifiers);dispatchMouseEvent(enterEvent)}state.hoverPath=newPath}else if(action==="wheel"){let event=createWheelEvent(x,y,target,parsed,state.keyboardModifiers);if(dispatchMouseEvent(event),event.defaultPrevented)defaultPrevented=!0}return defaultPrevented}init_unicode();init_unicode();var inspectorOutput=process.stderr;init_unicode();init_unicode();init_errors();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();function isWordChar(ch){return/\w/.test(ch)}function findWordBoundary(buffer,col,row){let width=buffer.width,ch=buffer.getCell(col,row).char;if(isWordChar(ch)){let startCol=col;while(startCol>0&&isWordChar(buffer.getCell(startCol-1,row).char))startCol--;let endCol=col;while(endCol<width-1&&isWordChar(buffer.getCell(endCol+1,row).char))endCol++;return{startCol,endCol}}return{startCol:col,endCol:col}}function findLineBoundary(buffer,row){let width=buffer.width,endCol=width-1;while(endCol>0&&buffer.getCell(endCol,row).char.trim()==="")endCol--;let startCol=0;while(startCol<endCol&&buffer.getCell(startCol,row).char.trim()==="")startCol++;if(startCol>=endCol&&buffer.getCell(startCol,row).char.trim()==="")return{startCol:0,endCol:width-1};return{startCol,endCol}}function extendByGranularity(col,row,anchor,granularity,buffer){if(granularity==="character"||!buffer)return{col,row};if(granularity==="word"){let{startCol,endCol}=findWordBoundary(buffer,col,row);return row>anchor.row||row===anchor.row&&col>=anchor.col?{col:endCol,row}:{col:startCol,row}}if(granularity==="line"){let{startCol,endCol}=findLineBoundary(buffer,row);return row>anchor.row||row===anchor.row&&col>=anchor.col?{col:endCol,row}:{col:startCol,row}}return{col,row}}function createTerminalSelectionState(){return{range:null,selecting:!1,source:null,granularity:"character",scope:null}}function clampToScope(col,row,scope){if(!scope)return{col,row};return{col:Math.max(scope.left,Math.min(scope.right,col)),row:Math.max(scope.top,Math.min(scope.bottom,row))}}function terminalSelectionUpdate(action,state){switch(action.type){case"start":{let scope=action.scope??null,pos=clampToScope(action.col,action.row,scope);return[{range:{anchor:pos,head:pos},selecting:!0,source:action.source??"mouse",granularity:"character",scope},[{type:"render"}]]}case"startWord":{let scope=action.scope??null,{startCol,endCol}=findWordBoundary(action.buffer,action.col,action.row),anchorPos=clampToScope(startCol,action.row,scope),headPos=clampToScope(endCol,action.row,scope);return[{range:{anchor:anchorPos,head:headPos},selecting:!0,source:action.source??"mouse",granularity:"word",scope},[{type:"render"}]]}case"startLine":{let scope=action.scope??null,{startCol,endCol}=findLineBoundary(action.buffer,action.row),anchorPos=clampToScope(startCol,action.row,scope),headPos=clampToScope(endCol,action.row,scope);return[{range:{anchor:anchorPos,head:headPos},selecting:!0,source:action.source??"mouse",granularity:"line",scope},[{type:"render"}]]}case"extend":{if(!state.selecting)return[state,[]];let extended=extendByGranularity(action.col,action.row,state.range.anchor,state.granularity,action.buffer),head=clampToScope(extended.col,extended.row,state.scope);return[{...state,range:{anchor:state.range.anchor,head},selecting:!0},[{type:"render"}]]}case"finish":{if(!state.range)return[{...state,selecting:!1},[]];return[{...state,range:state.range,selecting:!1},[]]}case"clear":{let hadRange=state.range!==null;return[createTerminalSelectionState(),hadRange?[{type:"render"}]:[]]}}}function normalizeRange(range){let{anchor,head}=range;if(anchor.row<head.row||anchor.row===head.row&&anchor.col<=head.col)return{startRow:anchor.row,startCol:anchor.col,endRow:head.row,endCol:head.col};return{startRow:head.row,startCol:head.col,endRow:anchor.row,endCol:anchor.col}}function extractText(buffer,range,options){let{startRow,startCol,endRow,endCol}=normalizeRange(range),respectSelectable=options?.respectSelectableFlag??!1,rowMeta=options?.rowMetadata,scope=options?.scope,parts=[];for(let row=startRow;row<=endRow;row++){let colStart=row===startRow?startCol:0,colEnd=row===endRow?endCol:buffer.width-1;if(scope){if(colStart=Math.max(colStart,scope.left),colEnd=Math.min(colEnd,scope.right),colStart>colEnd){if(!(rowMeta?.[row]?.softWrapped&&row<endRow)){if(parts.push(""),row<endRow)parts.push(`
79
+ `).slice(1):[],origin=stack.length>0?parseStackLine(stack[0]):null,filePath=cleanupPath(origin?.file),excerpt=null,lineWidth=0;if(filePath&&origin?.line){if(excerpt=getCodeExcerpt(filePath,origin.line),excerpt)for(let{line}of excerpt)lineWidth=Math.max(lineWidth,String(line).length)}let children=[];if(children.push(React2.createElement("silvery-box",{key:"header"},React2.createElement("silvery-text",{backgroundColor:"red",color:"white"}," ERROR "),React2.createElement("silvery-text",{},` ${err.message}`))),filePath&&origin)children.push(React2.createElement("silvery-box",{key:"location",marginTop:1},React2.createElement("silvery-text",{dimColor:!0},`${filePath}:${origin.line}:${origin.column}`)));if(excerpt&&origin){let codeLines=excerpt.map(({line,value})=>{let lineNum=String(line).padStart(lineWidth," ");return React2.createElement("silvery-box",{key:`code-${line}`},React2.createElement("silvery-text",{dimColor:line!==origin.line,backgroundColor:line===origin.line?"red":void 0,color:line===origin.line?"white":void 0},`${lineNum}:`),React2.createElement("silvery-text",{backgroundColor:line===origin.line?"red":void 0,color:line===origin.line?"white":void 0},` ${value}`))});children.push(React2.createElement("silvery-box",{key:"code",marginTop:1,flexDirection:"column"},...codeLines))}if(stack.length>0){let stackLines=stack.map((line,i)=>{let parsed=parseStackLine(line);if(!parsed)return React2.createElement("silvery-box",{key:`stack-${i}`},React2.createElement("silvery-text",{dimColor:!0},`- ${line.trim()}`));let cleanFile=cleanupPath(parsed.file);return React2.createElement("silvery-box",{key:`stack-${i}`},React2.createElement("silvery-text",{dimColor:!0},"- "),React2.createElement("silvery-text",{dimColor:!0,bold:!0},parsed.function??""),React2.createElement("silvery-text",{dimColor:!0,color:"gray"},` (${cleanFile??""}:${parsed.line}:${parsed.column})`))});children.push(React2.createElement("silvery-box",{key:"stack",marginTop:1,flexDirection:"column"},...stackLines))}return React2.createElement("silvery-box",{flexDirection:"column",padding:1},...children)}return this.props.children}}function isFocusable(node){if(node.hidden)return!1;let props=node.props;return Boolean(props.focusable)&&props.display!=="none"}function isFocusScope(node){let props=node.props;return Boolean(props.focusScope)}function findFocusableAncestor(node){let current=node;while(current){if(isFocusable(current))return current;current=current.parent}return null}function getTabOrder(root,scope){let result=[],walkRoot=scope??root;function walk(node){if(node.hidden)return;if(node.props.display==="none")return;if(node!==walkRoot&&isFocusScope(node)){if(isFocusable(node))result.push(node);return}if(isFocusable(node))result.push(node);for(let child of node.children)walk(child)}return walk(walkRoot),result}function findByTestID(root,testID){if(root.props.testID===testID)return root;for(let child of root.children){let found=findByTestID(child,testID);if(found)return found}return null}function rectCenter(rect){return{cx:rect.x+rect.width/2,cy:rect.y+rect.height/2}}function isInCone(source,candidate,direction){let dx=candidate.cx-source.cx,dy=candidate.cy-source.cy;switch(direction){case"up":if(dy>=0)return!1;return Math.abs(dx)<=Math.abs(dy);case"down":if(dy<=0)return!1;return Math.abs(dx)<=Math.abs(dy);case"left":if(dx>=0)return!1;return Math.abs(dy)<=Math.abs(dx);case"right":if(dx<=0)return!1;return Math.abs(dy)<=Math.abs(dx)}}function distance(a,b){let dx=a.cx-b.cx,dy=a.cy-b.cy;return Math.sqrt(dx*dx+dy*dy)}function findSpatialTarget(from,direction,candidates,layoutFn){let sourceRect=layoutFn(from);if(!sourceRect)return null;let source=rectCenter(sourceRect),best=null,bestDist=1/0;for(let candidate of candidates){if(candidate===from)continue;let candidateRect=layoutFn(candidate);if(!candidateRect)continue;let target=rectCenter(candidateRect);if(!isInCone(source,target,direction))continue;let dist=distance(source,target);if(dist<bestDist)bestDist=dist,best=candidate}return best}function getExplicitFocusLink(node,direction){let props=node.props,propName=`nextFocus${direction.charAt(0).toUpperCase()}${direction.slice(1)}`,value=props[propName];return typeof value==="string"?value:null}function ensureInteractiveState(node){if(!node.interactiveState)node.interactiveState={hovered:!1,armed:!1,selected:!1,focused:!1,dropTarget:!1};return node.interactiveState}function setHovered(node,value){let state=ensureInteractiveState(node);if(state.hovered===value)return!1;return state.hovered=value,!0}function setArmed(node,value){let state=ensureInteractiveState(node);if(state.armed===value)return!1;return state.armed=value,!0}function setFocused(node,value){let state=ensureInteractiveState(node);if(state.focused===value)return!1;return state.focused=value,!0}function createFocusManager(options){let onFocusChange=options?.onFocusChange,activeElement=null,activeId=null,previousElement=null,previousId=null,focusOrigin=null,scopeStack=[],scopeMemory={},activeScopeId=null,hookFocusables=[],hookFocusEnabled=!0,listeners=new Set,snapshot=null,notifyCount=0;function notify(){snapshot=null,notifyCount++;for(let listener of listeners)listener()}function getTestID(node){let props=node.props;return typeof props.testID==="string"?props.testID:null}function focus(node,origin="programmatic"){if(activeElement===node){if(focusOrigin!==origin)focusOrigin=origin,notify();return}let oldElement=activeElement;if(previousElement=activeElement,previousId=activeId,activeElement=node,activeId=getTestID(node),focusOrigin=origin,oldElement)setFocused(oldElement,!1);if(setFocused(node,!0),activeId&&scopeStack.length>0)scopeMemory[scopeStack[scopeStack.length-1]]=activeId;notify(),onFocusChange?.(oldElement,node,origin)}function focusById(id,root,origin="programmatic"){let node=findByTestID(root,id);if(node){let focusable=findFocusableAncestor(node);if(focusable){focus(focusable,origin);return}}if(activeId===id&&!activeElement)return;let oldElement=activeElement;if(previousElement=activeElement,previousId=activeId,activeElement=null,activeId=id,focusOrigin=origin,oldElement)setFocused(oldElement,!1);notify(),onFocusChange?.(oldElement,null,origin)}function blur(){if(!activeElement&&!activeId)return;let oldElement=activeElement;if(previousElement=activeElement,previousId=activeId,activeElement=null,activeId=null,focusOrigin=null,oldElement)setFocused(oldElement,!1);notify(),onFocusChange?.(oldElement,null,null)}function focusVirtualId(id,origin="programmatic"){if(activeId===id&&!activeElement){if(focusOrigin!==origin)focusOrigin=origin,notify();return}let oldElement=activeElement;if(previousElement=activeElement,previousId=activeId,activeElement=null,activeId=id,focusOrigin=origin,oldElement)setFocused(oldElement,!1);notify(),onFocusChange?.(oldElement,null,origin)}function unregisterHookFocusable(id){let idx=hookFocusables.findIndex((f)=>f.id===id);if(idx===-1)return;if(hookFocusables.splice(idx,1),activeId===id&&!activeElement){previousId=activeId,activeId=null,focusOrigin=null,notify(),onFocusChange?.(null,null,null);return}notify()}function registerHookFocusable(id,opts={}){let{isActive=!0,autoFocus=!1}=opts,existing=hookFocusables.findIndex((f)=>f.id===id);if(existing!==-1){if(hookFocusables[existing].isActive===isActive&&!autoFocus)return()=>unregisterHookFocusable(id);hookFocusables[existing]={id,isActive}}else hookFocusables.push({id,isActive});if(autoFocus&&isActive&&activeId===null)focusVirtualId(id,"programmatic");else notify();return()=>unregisterHookFocusable(id)}function setHookFocusableActive(id,isActive){let entry=hookFocusables.find((f)=>f.id===id);if(!entry)return;if(entry.isActive===isActive)return;if(entry.isActive=isActive,!isActive&&activeId===id&&!activeElement){previousId=activeId,activeId=null,focusOrigin=null,notify(),onFocusChange?.(null,null,null);return}notify()}function setHookFocusEnabled(enabled){if(hookFocusEnabled===enabled)return;hookFocusEnabled=enabled,notify()}function subtreeContains(subtreeRoot,target){if(subtreeRoot===target)return!0;for(let child of subtreeRoot.children)if(subtreeContains(child,target))return!0;return!1}function handleSubtreeRemoved(removedRoot){let changed=!1;if(activeElement&&subtreeContains(removedRoot,activeElement)){let oldElement=activeElement;setFocused(oldElement,!1),previousElement=activeElement,previousId=activeId,activeElement=null,activeId=null,focusOrigin=null,changed=!0,onFocusChange?.(oldElement,null,null)}if(previousElement&&subtreeContains(removedRoot,previousElement))previousElement=null,previousId=null,changed=!0;if(changed)notify()}function enterScope(scopeId){scopeStack.push(scopeId),notify()}function exitScope(){if(scopeStack.pop()===void 0)return;notify()}function activateScope(scopeId,root){if(activeScopeId&&activeId)scopeMemory[activeScopeId]=activeId;activeScopeId=scopeId;let countBefore=notifyCount,remembered=scopeMemory[scopeId];if(remembered)focusById(remembered,root,"programmatic");else{let scopeNode=findByTestID(root,scopeId);if(scopeNode){let order=getTabOrder(root,scopeNode);if(order.length>0)focus(order[0],"programmatic")}}if(notifyCount===countBefore)notify()}function getFocusPath(root){if(!activeElement)return[];let path=[],current=activeElement;while(current&&current!==root.parent){let id=getTestID(current);if(id)path.push(id);current=current.parent}return path}function hasFocusWithin(root,testID){if(!activeElement)return!1;let target=findByTestID(root,testID);if(!target)return!1;let current=activeElement;while(current){if(current===target)return!0;current=current.parent}return!1}function resolveScope(root,explicitScope){if(explicitScope)return explicitScope;if(scopeStack.length>0){let scopeId=scopeStack[scopeStack.length-1],scopeNode=findByTestID(root,scopeId);if(scopeNode)return scopeNode}return}function buildTabEntries(root,scope){let effectiveScope=resolveScope(root,scope),nodes=getTabOrder(root,effectiveScope),entries=nodes.map((node)=>({kind:"node",node}));if(!effectiveScope&&hookFocusEnabled){let treeIds=new Set(nodes.map((n)=>n.props.testID).filter(Boolean));for(let entry of hookFocusables)if(entry.isActive&&!treeIds.has(entry.id))entries.push({kind:"hook",id:entry.id})}return entries}function currentTabIndex(entries){if(activeElement){for(let i=0;i<entries.length;i++){let e=entries[i];if(e.kind==="node"&&e.node===activeElement)return i}return-1}if(activeId)for(let i=0;i<entries.length;i++){let e=entries[i];if(e.kind==="hook"&&e.id===activeId)return i}return-1}function focusTabEntry(entry,origin){if(entry.kind==="node")focus(entry.node,origin);else focusVirtualId(entry.id,origin)}function focusNext(root,scope){let entries=buildTabEntries(root,scope);if(entries.length===0)return;let currentIndex=currentTabIndex(entries);if(currentIndex===-1){focusTabEntry(entries[0],"keyboard");return}let nextIndex=(currentIndex+1)%entries.length;focusTabEntry(entries[nextIndex],"keyboard")}function focusPrev(root,scope){let entries=buildTabEntries(root,scope);if(entries.length===0)return;let currentIndex=currentTabIndex(entries);if(currentIndex===-1){focusTabEntry(entries[entries.length-1],"keyboard");return}let prevIndex=currentIndex<=0?entries.length-1:currentIndex-1;focusTabEntry(entries[prevIndex],"keyboard")}function focusDirection(root,direction,layoutFn){if(!activeElement)return;let explicitTarget=getExplicitFocusLink(activeElement,direction);if(explicitTarget){focusById(explicitTarget,root,"keyboard");return}let candidates=getTabOrder(root),target=findSpatialTarget(activeElement,direction,candidates,layoutFn??((node)=>node.scrollRect));if(target)focus(target,"keyboard")}function subscribe(listener){return listeners.add(listener),()=>{listeners.delete(listener)}}function getSnapshot(){if(!snapshot)snapshot={activeId,previousId,focusOrigin,scopeStack:[...scopeStack],activeScopeId};return snapshot}return{get activeElement(){return activeElement},get activeId(){return activeId},get previousElement(){return previousElement},get previousId(){return previousId},get focusOrigin(){return focusOrigin},get scopeStack(){return[...scopeStack]},get scopeMemory(){return scopeMemory},get activeScopeId(){return activeScopeId},focus,focusById,focusVirtualId,blur,handleSubtreeRemoved,enterScope,exitScope,activateScope,getFocusPath,hasFocusWithin,focusNext,focusPrev,focusDirection,subscribe,getSnapshot,registerHookFocusable,setHookFocusableActive,get hasHookFocusables(){return hookFocusables.length>0},get hookFocusEnabled(){return hookFocusEnabled},setHookFocusEnabled}}import React3,{createContext as createContext3,useCallback,useContext as useContext2,useEffect,useLayoutEffect as useLayoutEffect2,useRef as useRef2}from"react";import{useContext,useLayoutEffect,useReducer,useRef}from"react";function createCursorStore(){let store={state:null,listeners:new Set,accessors:null,setCursorState(s){store.state=s;for(let listener of store.listeners)listener()}};return store.accessors={getCursorState:()=>store.state,subscribeCursor:(listener)=>{return store.listeners.add(listener),()=>{store.listeners.delete(listener)}}},store}var CursorCtx=createContext3(null);function CursorProvider({store,children}){return React3.createElement(CursorCtx.Provider,{value:store},children)}function getAncestorPath(node){let path=[],current=node;while(current)path.push(current),current=current.parent;return path}function pointInRect(x,y,rect){return x>=rect.x&&x<rect.x+rect.width&&y>=rect.y&&y<rect.y+rect.height}function createKeyEvent(input,key,target){let propagationStopped=!1,defaultPrevented=!1;return{key:input,input,ctrl:key.ctrl,meta:key.meta,shift:key.shift,super:key.super,hyper:key.hyper,eventType:key.eventType,target,currentTarget:target,nativeEvent:{input,key},get propagationStopped(){return propagationStopped},get defaultPrevented(){return defaultPrevented},stopPropagation(){propagationStopped=!0},preventDefault(){defaultPrevented=!0}}}function createFocusEvent(type,target,relatedTarget){let propagationStopped=!1;return{type,target,relatedTarget,currentTarget:target,get propagationStopped(){return propagationStopped},stopPropagation(){propagationStopped=!0}}}function dispatchKeyEvent(event,dispatch){let path=getAncestorPath(event.target),mutableEvent=event,isRelease=event.eventType==="release",handlerProp=isRelease?"onKeyUp":"onKeyDown";if(!isRelease)for(let i=path.length-1;i>0;i--){if(event.propagationStopped)return;let node=path[i],handler=node.props.onKeyDownCapture;if(handler)mutableEvent.currentTarget=node,handler(event)}if(!event.propagationStopped){let target=path[0];mutableEvent.currentTarget=target;let handler=target.props[handlerProp];if(handler)handler(event,dispatch)}for(let i=1;i<path.length;i++){if(event.propagationStopped)return;let node=path[i],handler=node.props[handlerProp];if(handler)mutableEvent.currentTarget=node,handler(event,dispatch)}}function dispatchFocusEvent(event){let handlerProp=event.type==="focus"?"onFocus":"onBlur",path=getAncestorPath(event.target),mutableEvent=event;for(let node of path){if(event.propagationStopped)break;let handler=node.props[handlerProp];if(handler)mutableEvent.currentTarget=node,handler(event)}}init_unicode();init_output_phase();function createPipeline(options={}){let{caps,measurer:explicitMeasurer}=options,measurer=explicitMeasurer??createWidthMeasurer(caps?{textEmojiWide:caps.textEmojiWide,textSizingEnabled:caps.textSizingSupported}:{}),outputPhaseFn=createOutputPhase(caps?{underlineStyles:caps.underlineStyles,underlineColor:caps.underlineColor,colorLevel:caps.colorLevel}:{},measurer);return{measurer,outputPhaseFn}}init_text_sizing();init_output_phase();import React4 from"react";init_keys();init_buffer();init_output_phase();init_unicode();init_src2();var ESC2="\x1B",CSI=`${ESC2}[`,CURSOR_HIDE=`${CSI}?25l`,CURSOR_SHOW=`${CSI}?25h`,CURSOR_HOME=`${CSI}H`,SYNC_BEGIN=`${CSI}?2026h`,SYNC_END=`${CSI}?2026l`,RESET=`${CSI}0m`;function resetCursorStyle(){return`${CSI}0 q`}function enterAlternateScreen(){return`${CSI}?1049h${CSI}2J${CURSOR_HOME}${CURSOR_HIDE}`}function leaveAlternateScreen(){return`${SYNC_END}${CURSOR_SHOW}${CSI}?1049l`}var enableMouse2=enableMouse,disableMouse2=disableMouse,KittyFlags={DISAMBIGUATE:1,REPORT_EVENTS:2,REPORT_ALTERNATE:4,REPORT_ALL_KEYS:8,REPORT_TEXT:16},enableKittyKeyboard2=enableKittyKeyboard;function queryKittyKeyboard(){return`${CSI}?u`}var disableKittyKeyboard2=disableKittyKeyboard;init_src2();var KITTY_RESPONSE_RE=/\x1b\[\?(\d+)u/;async function detectKittySupport(write,read,timeoutMs=200){write(queryKittyKeyboard());let data=await read(timeoutMs);if(data==null)return{supported:!1,flags:0};let match=KITTY_RESPONSE_RE.exec(data);if(!match)return{supported:!1,flags:0,buffered:data};let flags=parseInt(match[1],10),before=data.slice(0,match.index),after=data.slice(match.index+match[0].length),buffered=before+after;return{supported:!0,flags,buffered:buffered||void 0}}async function detectKittyFromStdio(stdout,stdin,timeoutMs=200){let wasRaw=stdin.isRaw;if(!wasRaw)stdin.setRawMode(!0);try{return await detectKittySupport((s)=>{stdout.write(s)},(ms)=>new Promise((resolve)=>{let timer=setTimeout(()=>{stdin.removeListener("data",onData),resolve(null)},ms);function onData(chunk){clearTimeout(timer),stdin.removeListener("data",onData),resolve(chunk.toString())}stdin.on("data",onData)}),timeoutMs)}finally{if(!wasRaw)stdin.setRawMode(!1)}}init_detection2();var ESC3="\x1B",CSI2=`${ESC3}[`,RESET2=`${CSI2}0m`;init_text_sizing();init_src2();init_src2();var WidthMode={UTF8:1020,CJK_WIDTH:1021,EMOJI_WIDTH:1022,PRIVATE_USE_WIDTH:1023},DEFAULT_WIDTH_CONFIG={utf8:!0,cjkWidth:1,emojiWidth:2,privateUseWidth:1},DECRPM_RE=/\x1b\[\?(\d+);(\d+)\$y/g;function isSet(ps){return ps===1||ps===3}function queryWidthMode(write,onData,mode,timeoutMs){return new Promise((resolve)=>{let timer=null,unsubscribe=null,buffer="";function cleanup(){if(timer!==null)clearTimeout(timer),timer=null;if(unsubscribe!==null)unsubscribe(),unsubscribe=null}unsubscribe=onData((data)=>{buffer+=data,DECRPM_RE.lastIndex=0;let match;while((match=DECRPM_RE.exec(buffer))!==null)if(parseInt(match[1],10)===mode){let ps=parseInt(match[2],10);cleanup(),resolve(ps);return}}),timer=setTimeout(()=>{cleanup(),resolve(null)},timeoutMs),write(`\x1B[?${mode}$p`)})}function applyWidthConfig(caps,config){return{...caps,textEmojiWide:config.emojiWidth===2,textSizingSupported:config.privateUseWidth===2}}function createWidthDetector(options){let{write,onData,timeoutMs=200}=options,config=null,disposed=!1;return{get config(){return config},async detect(){if(disposed)return config??{...DEFAULT_WIDTH_CONFIG};if(config!==null)return config;let utf8Ps=await queryWidthMode(write,onData,WidthMode.UTF8,timeoutMs),cjkPs=await queryWidthMode(write,onData,WidthMode.CJK_WIDTH,timeoutMs),emojiPs=await queryWidthMode(write,onData,WidthMode.EMOJI_WIDTH,timeoutMs),puaPs=await queryWidthMode(write,onData,WidthMode.PRIVATE_USE_WIDTH,timeoutMs);return config={utf8:utf8Ps!==null?isSet(utf8Ps):DEFAULT_WIDTH_CONFIG.utf8,cjkWidth:cjkPs!==null?isSet(cjkPs)?2:1:DEFAULT_WIDTH_CONFIG.cjkWidth,emojiWidth:emojiPs!==null?isSet(emojiPs)?2:1:DEFAULT_WIDTH_CONFIG.emojiWidth,privateUseWidth:puaPs!==null?isSet(puaPs)?2:1:DEFAULT_WIDTH_CONFIG.privateUseWidth},config},dispose(){disposed=!0}}}init_mouse();import{createLogger as createLogger12}from"loggily";var mouseLog=createLogger12("silvery:mouse");function createMouseEvent(type,x,y,target,parsed,keyboardMods){let propagationStopped=!1,defaultPrevented=!1,metaKey=keyboardMods?.super??!1;if(type==="click"||type==="mousedown")mouseLog.debug?.(`createMouseEvent(${type}) metaKey=${metaKey} keyboardMods.super=${keyboardMods?.super}`);return{type,clientX:x,clientY:y,button:parsed.button,altKey:parsed.meta,ctrlKey:parsed.ctrl,metaKey,shiftKey:parsed.shift,target,currentTarget:target,nativeEvent:parsed,get propagationStopped(){return propagationStopped},get defaultPrevented(){return defaultPrevented},stopPropagation(){propagationStopped=!0},preventDefault(){defaultPrevented=!0}}}function createWheelEvent(x,y,target,parsed,keyboardMods){let base=createMouseEvent("wheel",x,y,target,parsed,keyboardMods);return base.deltaY=parsed.delta??0,base.deltaX=0,base}function hitTest(node,x,y){let rect=node.scrollRect;if(!rect)return null;if(!pointInRect(x,y,rect))return null;let props=node.props;if(props.pointerEvents==="none")return null;let clips=props.overflow==="hidden"||props.overflow==="scroll";for(let i=node.children.length-1;i>=0;i--){let child=node.children[i];if(clips){if(child.scrollRect&&!pointInRect(x,y,rect))continue}let hit=hitTest(child,x,y);if(hit)return hit}if(node.type==="silvery-text")for(let i=node.children.length-1;i>=0;i--){let child=node.children[i];if(child.inlineRects){for(let inlineRect of child.inlineRects)if(pointInRect(x,y,inlineRect))return child}}return node}function resolveUserSelect(node){let current=node;while(current){let value=current.props.userSelect;if(value==="none"||value==="text"||value==="contain")return value;current=current.parent}return"text"}function selectionHitTest(node,x,y){let rect=node.scrollRect;if(!rect)return null;if(!pointInRect(x,y,rect))return null;let props=node.props;if(resolveUserSelect(node)==="none")return null;let clips=props.overflow==="hidden"||props.overflow==="scroll";for(let i=node.children.length-1;i>=0;i--){let child=node.children[i];if(clips){if(child.scrollRect&&!pointInRect(x,y,rect))continue}let hit=selectionHitTest(child,x,y);if(hit)return hit}if(node.type==="silvery-text")for(let i=node.children.length-1;i>=0;i--){let child=node.children[i];if(child.inlineRects){for(let inlineRect of child.inlineRects)if(pointInRect(x,y,inlineRect))return child}}return node}function findContainBoundary(node){let current=node;while(current){if(current.props.userSelect==="contain"){let rect=current.scrollRect;if(rect)return{top:rect.y,bottom:rect.y+rect.height-1,left:rect.x,right:rect.x+rect.width-1}}current=current.parent}return null}var EVENT_HANDLER_MAP={click:"onClick",dblclick:"onDoubleClick",mousedown:"onMouseDown",mouseup:"onMouseUp",mousemove:"onMouseMove",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",wheel:"onWheel"};function dispatchMouseEvent(event){let handlerProp=EVENT_HANDLER_MAP[event.type];if(!handlerProp)return;if(event.type==="mouseenter"||event.type==="mouseleave"){let handler=event.target.props[handlerProp];if(handler){let mutableEvent=event;mutableEvent.currentTarget=event.target,handler(event)}return}let path=getAncestorPath(event.target);for(let node of path){if(event.propagationStopped)break;let handler=node.props[handlerProp];if(handler){let mutableEvent=event;mutableEvent.currentTarget=node,handler(event)}}}function createDoubleClickState(){return{lastClickTime:0,lastClickX:-999,lastClickY:-999,lastClickButton:-1}}var DOUBLE_CLICK_TIME_MS=300,DOUBLE_CLICK_DISTANCE=2;function checkDoubleClick(state,x,y,button,now=Date.now()){let timeDelta=now-state.lastClickTime,dx=Math.abs(x-state.lastClickX),dy=Math.abs(y-state.lastClickY),isDouble=button===state.lastClickButton&&timeDelta<=DOUBLE_CLICK_TIME_MS&&dx<=DOUBLE_CLICK_DISTANCE&&dy<=DOUBLE_CLICK_DISTANCE;if(state.lastClickTime=now,state.lastClickX=x,state.lastClickY=y,state.lastClickButton=button,isDouble)state.lastClickTime=0;return isDouble}function computeEnterLeave(prevPath,nextPath){let prevSet=new Set(prevPath),nextSet=new Set(nextPath),entered=nextPath.filter((n)=>!prevSet.has(n)),left=prevPath.filter((n)=>!nextSet.has(n));return{entered,left}}function createMouseEventProcessor(options){return{doubleClick:createDoubleClickState(),hoverPath:[],mouseDownTarget:null,focusManager:options?.focusManager,keyboardModifiers:{super:!1,hyper:!1,capsLock:!1,numLock:!1}}}function updateKeyboardModifiers(state,key){let isRelease=key.eventType==="release",prevSuper=state.keyboardModifiers.super;if(key.super!==void 0)state.keyboardModifiers.super=isRelease?!1:key.super;if(key.hyper!==void 0)state.keyboardModifiers.hyper=isRelease?!1:key.hyper;if(key.capsLock!==void 0)state.keyboardModifiers.capsLock=key.capsLock;if(key.numLock!==void 0)state.keyboardModifiers.numLock=key.numLock;if(state.keyboardModifiers.super!==prevSuper)mouseLog.debug?.(`keyboardModifiers.super: ${prevSuper} → ${state.keyboardModifiers.super} (key.super=${key.super}, eventType=${key.eventType})`)}function processMouseEvent(state,parsed,root){let{x,y,action}=parsed,target=hitTest(root,x,y);if(action==="move"){let nodeType=target?.type??"null",nodeId=target?target.props.id??"":"",enterAncestor="";if(target){let n=target;while(n){if("onMouseEnter"in n.props){enterAncestor=`${n.type}#${n.props.id??""}`;break}n=n.parent}}let newPath=target?getAncestorPath(target):[],{entered}=computeEnterLeave(state.hoverPath,newPath);mouseLog.debug?.(`move x=${x} y=${y} target=${nodeType}#${nodeId} enterAncestor=${enterAncestor||"none"} entered=${entered.length} prevPath=${state.hoverPath.length}`)}if(!target)return!1;let defaultPrevented=!1;if(action==="down"){if(state.mouseDownTarget=target,setArmed(target,!0),state.focusManager){let focusable=findFocusableAncestor(target);if(focusable)state.focusManager.focus(focusable,"mouse")}let event=createMouseEvent("mousedown",x,y,target,parsed,state.keyboardModifiers);if(dispatchMouseEvent(event),event.defaultPrevented)defaultPrevented=!0}else if(action==="up"){if(state.mouseDownTarget)setArmed(state.mouseDownTarget,!1);let event=createMouseEvent("mouseup",x,y,target,parsed,state.keyboardModifiers);if(dispatchMouseEvent(event),state.mouseDownTarget){let clickEvent=createMouseEvent("click",x,y,target,parsed,state.keyboardModifiers);if(dispatchMouseEvent(clickEvent),clickEvent.defaultPrevented)defaultPrevented=!0;if(checkDoubleClick(state.doubleClick,x,y,parsed.button)){let dblEvent=createMouseEvent("dblclick",x,y,target,parsed,state.keyboardModifiers);if(dispatchMouseEvent(dblEvent),dblEvent.defaultPrevented)defaultPrevented=!0}}state.mouseDownTarget=null}else if(action==="move"){let event=createMouseEvent("mousemove",x,y,target,parsed,state.keyboardModifiers);dispatchMouseEvent(event);let newPath=getAncestorPath(target),{entered,left}=computeEnterLeave(state.hoverPath,newPath);for(let node of left){setHovered(node,!1);let leaveEvent=createMouseEvent("mouseleave",x,y,node,parsed,state.keyboardModifiers);dispatchMouseEvent(leaveEvent)}for(let node of entered.reverse()){setHovered(node,!0);let enterEvent=createMouseEvent("mouseenter",x,y,node,parsed,state.keyboardModifiers);dispatchMouseEvent(enterEvent)}state.hoverPath=newPath}else if(action==="wheel"){let event=createWheelEvent(x,y,target,parsed,state.keyboardModifiers);if(dispatchMouseEvent(event),event.defaultPrevented)defaultPrevented=!0}return defaultPrevented}init_unicode();init_unicode();var inspectorOutput=process.stderr;init_unicode();init_unicode();init_errors();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();function isWordChar(ch){return/\w/.test(ch)}function findWordBoundary(buffer,col,row){let width=buffer.width,ch=buffer.getCell(col,row).char;if(isWordChar(ch)){let startCol=col;while(startCol>0&&isWordChar(buffer.getCell(startCol-1,row).char))startCol--;let endCol=col;while(endCol<width-1&&isWordChar(buffer.getCell(endCol+1,row).char))endCol++;return{startCol,endCol}}return{startCol:col,endCol:col}}function findLineBoundary(buffer,row){let width=buffer.width,endCol=width-1;while(endCol>0&&buffer.getCell(endCol,row).char.trim()==="")endCol--;let startCol=0;while(startCol<endCol&&buffer.getCell(startCol,row).char.trim()==="")startCol++;if(startCol>=endCol&&buffer.getCell(startCol,row).char.trim()==="")return{startCol:0,endCol:width-1};return{startCol,endCol}}function extendByGranularity(col,row,anchor,granularity,buffer){if(granularity==="character"||!buffer)return{col,row};if(granularity==="word"){let{startCol,endCol}=findWordBoundary(buffer,col,row);return row>anchor.row||row===anchor.row&&col>=anchor.col?{col:endCol,row}:{col:startCol,row}}if(granularity==="line"){let{startCol,endCol}=findLineBoundary(buffer,row);return row>anchor.row||row===anchor.row&&col>=anchor.col?{col:endCol,row}:{col:startCol,row}}return{col,row}}function createTerminalSelectionState(){return{range:null,selecting:!1,source:null,granularity:"character",scope:null}}function clampToScope(col,row,scope){if(!scope)return{col,row};return{col:Math.max(scope.left,Math.min(scope.right,col)),row:Math.max(scope.top,Math.min(scope.bottom,row))}}function terminalSelectionUpdate(action,state){switch(action.type){case"start":{let scope=action.scope??null,pos=clampToScope(action.col,action.row,scope);return[{range:{anchor:pos,head:pos},selecting:!0,source:action.source??"mouse",granularity:"character",scope},[{type:"render"}]]}case"startWord":{let scope=action.scope??null,{startCol,endCol}=findWordBoundary(action.buffer,action.col,action.row),anchorPos=clampToScope(startCol,action.row,scope),headPos=clampToScope(endCol,action.row,scope);return[{range:{anchor:anchorPos,head:headPos},selecting:!0,source:action.source??"mouse",granularity:"word",scope},[{type:"render"}]]}case"startLine":{let scope=action.scope??null,{startCol,endCol}=findLineBoundary(action.buffer,action.row),anchorPos=clampToScope(startCol,action.row,scope),headPos=clampToScope(endCol,action.row,scope);return[{range:{anchor:anchorPos,head:headPos},selecting:!0,source:action.source??"mouse",granularity:"line",scope},[{type:"render"}]]}case"extend":{if(!state.selecting)return[state,[]];let extended=extendByGranularity(action.col,action.row,state.range.anchor,state.granularity,action.buffer),head=clampToScope(extended.col,extended.row,state.scope);return[{...state,range:{anchor:state.range.anchor,head},selecting:!0},[{type:"render"}]]}case"finish":{if(!state.range)return[{...state,selecting:!1},[]];return[{...state,range:state.range,selecting:!1},[]]}case"clear":{let hadRange=state.range!==null;return[createTerminalSelectionState(),hadRange?[{type:"render"}]:[]]}}}function normalizeRange(range){let{anchor,head}=range;if(anchor.row<head.row||anchor.row===head.row&&anchor.col<=head.col)return{startRow:anchor.row,startCol:anchor.col,endRow:head.row,endCol:head.col};return{startRow:head.row,startCol:head.col,endRow:anchor.row,endCol:anchor.col}}function extractText(buffer,range,options){let{startRow,startCol,endRow,endCol}=normalizeRange(range),respectSelectable=options?.respectSelectableFlag??!1,rowMeta=options?.rowMetadata,scope=options?.scope,parts=[];for(let row=startRow;row<=endRow;row++){let colStart=row===startRow?startCol:0,colEnd=row===endRow?endCol:buffer.width-1;if(scope){if(colStart=Math.max(colStart,scope.left),colEnd=Math.min(colEnd,scope.right),colStart>colEnd){if(!(rowMeta?.[row]?.softWrapped&&row<endRow)){if(parts.push(""),row<endRow)parts.push(`
75
80
  `)}continue}}let line="";for(let col=colStart;col<=colEnd;col++){if(buffer.isCellContinuation(col,row))continue;if(respectSelectable&&!buffer.isCellSelectable(col,row))continue;line+=buffer.getCellChar(col,row)}let meta=rowMeta?.[row];if(meta&&meta.lastContentCol>=0){if((row===endRow?endCol:buffer.width-1)-meta.lastContentCol>0&&line.length>0)line=line.replace(/\s+$/,"")}else line=line.replace(/\s+$/,"");if(meta?.softWrapped&&row<endRow)parts.push(line);else if(parts.push(line),row<endRow)parts.push(`
76
- `)}return parts.join("")}function renderSelectionOverlay(selection,buffer,mode="fullscreen",scope){if(!selection)return"";let{startRow,startCol,endRow,endCol}=normalizeRange(selection),out="";for(let row=startRow;row<=endRow;row++){let colStart=row===startRow?startCol:0,colEnd=row===endRow?endCol:buffer.width-1;if(scope)colStart=Math.max(colStart,scope.left),colEnd=Math.min(colEnd,scope.right);if(colStart>colEnd)continue;if(mode==="fullscreen")out+=`\x1B[${row+1};${colStart+1}H`;out+="\x1B[7m";for(let col=colStart;col<=colEnd;col++)out+=buffer.getCell(col,row).char;out+="\x1B[27m"}return out}init_unicode();function createVirtualScrollback(options){let maxLines=options?.maxLines??1e4,ansiLines=Array(maxLines),plainLines=Array(maxLines),head=0,count=0;return{push(lines){for(let line of lines)if(ansiLines[head]=line,plainLines[head]=stripAnsi2(line),head=(head+1)%maxLines,count<maxLines)count++},getVisibleRows(offset,rowCount){let result=[];for(let i=0;i<rowCount;i++){let logicalIndex=count-offset-rowCount+i;if(logicalIndex<0||logicalIndex>=count)result.push("");else{let physical=(head-count+logicalIndex+maxLines)%maxLines;result.push(ansiLines[physical])}}return result},get totalLines(){return count},search(query){if(!query)return[];let lowerQuery=query.toLowerCase(),matches=[];for(let i=0;i<count;i++){let physical=(head-count+i+maxLines)%maxLines;if(plainLines[physical].toLowerCase().includes(lowerQuery))matches.push(i)}return matches},clear(){head=0,count=0}}}init_unicode();init_unicode();function createSearchState(){return{active:!1,query:"",matches:[],currentMatch:-1,cursorPosition:0}}function searchUpdate(action,state,searchFn){switch(action.type){case"open":return[{...state,active:!0,query:"",matches:[],currentMatch:-1,cursorPosition:0},[{type:"render"}]];case"close":return[createSearchState(),[{type:"render"}]];case"input":{let query=state.query.slice(0,state.cursorPosition)+action.char+state.query.slice(state.cursorPosition),cursorPosition=state.cursorPosition+1,matches=searchFn?searchFn(query):[],currentMatch=matches.length>0?0:-1,effects=[{type:"render"}];if(currentMatch>=0)effects.push({type:"scrollTo",row:matches[0].row});return[{...state,query,cursorPosition,matches,currentMatch},effects]}case"backspace":{if(state.cursorPosition===0)return[state,[]];let query=state.query.slice(0,state.cursorPosition-1)+state.query.slice(state.cursorPosition),cursorPosition=state.cursorPosition-1,matches=searchFn?searchFn(query):[],currentMatch=matches.length>0?0:-1,effects=[{type:"render"}];if(currentMatch>=0)effects.push({type:"scrollTo",row:matches[0].row});return[{...state,query,cursorPosition,matches,currentMatch},effects]}case"nextMatch":{if(state.matches.length===0)return[state,[]];let currentMatch=(state.currentMatch+1)%state.matches.length;return[{...state,currentMatch},[{type:"scrollTo",row:state.matches[currentMatch].row},{type:"render"}]]}case"prevMatch":{if(state.matches.length===0)return[state,[]];let currentMatch=(state.currentMatch-1+state.matches.length)%state.matches.length;return[{...state,currentMatch},[{type:"scrollTo",row:state.matches[currentMatch].row},{type:"render"}]]}case"cursorLeft":if(state.cursorPosition===0)return[state,[]];return[{...state,cursorPosition:state.cursorPosition-1},[]];case"cursorRight":if(state.cursorPosition>=state.query.length)return[state,[]];return[{...state,cursorPosition:state.cursorPosition+1},[]];case"cursorToStart":if(state.cursorPosition===0)return[state,[]];return[{...state,cursorPosition:0},[]];case"cursorToEnd":if(state.cursorPosition>=state.query.length)return[state,[]];return[{...state,cursorPosition:state.query.length},[]];case"deleteWordBack":{if(state.cursorPosition===0)return[state,[]];let pos=state.cursorPosition;while(pos>0&&/\s/.test(state.query[pos-1]??""))pos--;while(pos>0&&!/\s/.test(state.query[pos-1]??""))pos--;let query=state.query.slice(0,pos)+state.query.slice(state.cursorPosition),cursorPosition=pos,matches=searchFn?searchFn(query):[],currentMatch=matches.length>0?0:-1,effects=[{type:"render"}];if(currentMatch>=0)effects.push({type:"scrollTo",row:matches[0].row});return[{...state,query,cursorPosition,matches,currentMatch},effects]}case"deleteToStart":{if(state.cursorPosition===0)return[state,[]];let query=state.query.slice(state.cursorPosition),cursorPosition=0,matches=searchFn?searchFn(query):[],currentMatch=matches.length>0?0:-1,effects=[{type:"render"}];if(currentMatch>=0)effects.push({type:"scrollTo",row:matches[0].row});return[{...state,query,cursorPosition,matches,currentMatch},effects]}}}function renderSearchBar(state,cols){let matchInfo=state.matches.length>0?` [${state.currentMatch+1}/${state.matches.length}]`:state.query?" [no matches]":"";return`\x1B[7m${(" / "+state.query+matchInfo).padEnd(cols)}\x1B[27m`}init_buffer();import{createLogger as createLogger12}from"loggily";init_errors();init_errors();var log9=createLogger12("silvery:scheduler"),SYNC_UPDATE_ENABLED=process.env.SILVERY_SYNC_UPDATE==="1"||process.env.SILVERY_SYNC_UPDATE==="true";function createHandlerContext(store,focusManager,container){let state=store.getState(),teaDispatch=typeof state.dispatch==="function"?state.dispatch:void 0;return{set:store.setState,get:store.getState,focusManager,focus(testID){let root=getContainerRoot(container);focusManager.focusById(testID,root,"programmatic")},activateScope(scopeId){let root=getContainerRoot(container);focusManager.activateScope(scopeId,root)},getFocusPath(){let root=getContainerRoot(container);return focusManager.getFocusPath(root)},dispatch:teaDispatch,hitTest(x,y){let root=getContainerRoot(container);return hitTest(root,x,y)}}}function handleFocusNavigation(input,parsedKey,focusManager,container){if(focusManager.activeElement){let keyEvent=createKeyEvent(input,parsedKey,focusManager.activeElement);if(dispatchKeyEvent(keyEvent),keyEvent.propagationStopped||keyEvent.defaultPrevented)return"consumed"}let root=getContainerRoot(container);if(parsedKey.tab&&!parsedKey.shift)return focusManager.focusNext(root),"consumed";if(parsedKey.tab&&parsedKey.shift)return focusManager.focusPrev(root),"consumed";if(parsedKey.return&&focusManager.activeElement){let activeEl=focusManager.activeElement,props=activeEl.props,testID=typeof props.testID==="string"?props.testID:null;if(props.focusScope&&testID)return focusManager.enterScope(testID),focusManager.focusNext(root,activeEl),"consumed"}if(parsedKey.escape){if(focusManager.scopeStack.length>0){let scopeId=focusManager.scopeStack[focusManager.scopeStack.length-1];focusManager.exitScope();let scopeNode=findByTestID(root,scopeId);if(scopeNode)focusManager.focus(scopeNode,"keyboard");return"consumed"}if(focusManager.activeElement)return focusManager.blur(),"consumed"}return"continue"}function dispatchMouseEventToTree(event,mouseEventState,root){if(event.event!=="mouse"||!event.data)return!1;let mouseData=event.data;return processMouseEvent(mouseEventState,{button:mouseData.button,x:mouseData.x,y:mouseData.y,action:mouseData.action,delta:mouseData.delta,shift:mouseData.shift,meta:mouseData.meta,ctrl:mouseData.ctrl},root)}function invokeEventHandler(event,handlers,ctx,mouseEventState,container){let root=getContainerRoot(container);if(dispatchMouseEventToTree(event,mouseEventState,root))return!0;let namespacedHandler=handlers?.[event.type];if(namespacedHandler&&typeof namespacedHandler==="function"){let result=namespacedHandler(event.data,ctx);if(result==="exit")return!1;if(result==="flush")return"flush"}return!0}function dispatchKeyToHandlers(input,parsedKey,handlers,ctx){let namespacedHandler=handlers?.["term:key"];if(namespacedHandler&&typeof namespacedHandler==="function"){if(namespacedHandler({input,key:parsedKey},ctx)==="exit")return"exit"}if(handlers?.key){if(handlers.key(input,parsedKey,ctx)==="exit")return"exit"}return}init_keys();init_keys2();import{writeSync as writeSync2}from"node:fs";function captureTerminalState(opts){return{rawMode:opts.rawMode??!0,alternateScreen:opts.alternateScreen??!1,cursorHidden:opts.cursorHidden??!0,mouseEnabled:opts.mouse??!1,kittyEnabled:opts.kitty??!1,kittyFlags:opts.kittyFlags??11,bracketedPaste:opts.bracketedPaste??!1,focusReporting:opts.focusReporting??!1}}function restoreTerminalState(stdout,stdin){try{stdin.removeAllListeners("data"),stdin.pause()}catch{}let sequences=["\x1B[0m","\x1B[?1004l",disableMouse2(),disableKittyKeyboard2(),"\x1B[?2004l",resetCursorStyle(),"\x1B[?25h","\x1B[?1049l"].join("");if(stdout===process.stdout)try{writeSync2(stdout.fd,sequences)}catch{try{stdout.write(sequences)}catch{}}else try{stdout.write(sequences)}catch{}try{stdin.resume();while(stdin.read()!==null);stdin.pause()}catch{}if(stdin.isTTY&&stdin.isRaw)try{stdin.setRawMode(!1)}catch{}}function resumeTerminalState(state,stdout,stdin){if(state.rawMode&&stdin.isTTY)try{stdin.setRawMode(!0),stdin.resume()}catch{}let sequences=[];if(state.alternateScreen)sequences.push("\x1B[?1049h");if(sequences.push("\x1B[2J\x1B[H"),state.cursorHidden)sequences.push("\x1B[?25l");if(state.kittyEnabled)sequences.push(enableKittyKeyboard2(state.kittyFlags));if(state.mouseEnabled)sequences.push(enableMouse2());if(state.bracketedPaste)sequences.push("\x1B[?2004h");if(state.focusReporting)sequences.push("\x1B[?1004h");let joined=sequences.join("");if(stdout===process.stdout)try{writeSync2(stdout.fd,joined)}catch{try{stdout.write(joined)}catch{}}else try{stdout.write(joined)}catch{}stdout.emit("resize")}function performSuspend(state,stdout,stdin,onResume){restoreTerminalState(stdout,stdin),process.once("SIGCONT",()=>{resumeTerminalState(state,stdout,stdin),onResume?.()}),process.kill(process.pid,"SIGTSTP")}var CTRL_C="\x03",CTRL_Z="\x1A";init_term_provider();function createSelectionBridge(options){return{get state(){return options.getState()},subscribe(listener){return options.subscribe(listener)},handleMouseDown(_col,_row,_altKey){},handleMouseMove(_col,_row){},handleMouseUp(_col,_row){},setRange(range){options.setRange(range)},clear(){options.clear()},dispose(){}}}function createCapabilityRegistry(){let capabilities=new Map;return{register(key,capability){capabilities.set(key,capability)},get(key){return capabilities.get(key)}}}var SELECTION_CAPABILITY=Symbol.for("silvery.selection");init_output_guard();import{createLogger as createLogger13}from"loggily";var perfLog=createLogger13("silvery:perf"),samples=null,budgetOverruns=0;function checkBudget(key,durationMs,budgetMs=16){if(samples)samples.push({key,durationMs});if(durationMs>budgetMs)budgetOverruns++,perfLog.warn?.(`keypress over budget: ${key} took ${durationMs.toFixed(1)}ms (budget: ${budgetMs}ms)`)}function startTracking(){if(!samples)samples=[]}function logExitSummary(){if(!samples||samples.length===0)return;let durations=samples.map((s)=>s.durationMs).sort((a,b)=>a-b),total=samples.length,mean=durations.reduce((sum,d)=>sum+d,0)/total,p95Index=Math.min(Math.floor(total*0.95),total-1),p95=durations[p95Index],max=durations[total-1];perfLog.info?.(`keypress summary: ${total} presses, mean=${mean.toFixed(1)}ms, p95=${p95.toFixed(1)}ms, max=${max.toFixed(1)}ms, overruns=${budgetOverruns}`),samples=null,budgetOverruns=0}import{createLogger as createLogger14}from"loggily";import{jsxDEV}from"react/jsx-dev-runtime";var log10=createLogger14("silvery:app"),ENV=typeof process2<"u"?process2.env:void 0,NO_INCREMENTAL=ENV?.SILVERY_NO_INCREMENTAL==="1",STRICT_MODE=(()=>{let v=ENV?.SILVERY_STRICT;return!!v&&v!=="0"&&v!=="false"})(),CELL_DEBUG=(()=>{let v=ENV?.SILVERY_CELL_DEBUG;if(!v||!v.includes(","))return null;let[cx,cy]=v.split(",").map(Number);if(!Number.isFinite(cx)||!Number.isFinite(cy))return null;return{x:cx,y:cy}})(),INSTRUMENTED=STRICT_MODE||CELL_DEBUG!==null;function isFullProvider(value){if(value===null||value===void 0)return!1;if(typeof value!=="object"&&typeof value!=="function")return!1;return"getState"in value&&"subscribe"in value&&"events"in value&&typeof value.getState==="function"&&typeof value.subscribe==="function"&&typeof value.events==="function"}function isBasicProvider(value){if(value===null||value===void 0)return!1;if(typeof value!=="object"&&typeof value!=="function")return!1;return"getState"in value&&"subscribe"in value&&typeof value.getState==="function"&&typeof value.subscribe==="function"}var StoreContext=createContext4(null);function useApp(selector){let store=useContext3(StoreContext);if(!store)throw Error("useApp must be used within createApp().run()");let[state,setState]=React5.useState(()=>selector(store.getState())),selectorRef=useRef3(selector);return selectorRef.current=selector,useEffect2(()=>{return store.subscribe((newState)=>{let next=selectorRef.current(newState);setState((prev)=>Object.is(prev,next)?prev:next)})},[store]),state}function shallowEqual(a,b){if(Object.is(a,b))return!0;if(typeof a!=="object"||typeof b!=="object"||a===null||b===null)return!1;let keysA=Object.keys(a),keysB=Object.keys(b);if(keysA.length!==keysB.length)return!1;for(let key of keysA)if(!Object.is(a[key],b[key]))return!1;return!0}function useAppShallow(selector){let store=useContext3(StoreContext);if(!store)throw Error("useAppShallow must be used within createApp().run()");let[state,setState]=React5.useState(()=>selector(store.getState())),selectorRef=useRef3(selector);return selectorRef.current=selector,useEffect2(()=>{return store.subscribe((newState)=>{let next=selectorRef.current(newState);setState((prev)=>shallowEqual(prev,next)?prev:next)})},[store]),state}function createApp(factory,handlers){return{run(element,options={}){let handlePromise=null,init=()=>{if(handlePromise)return handlePromise;return handlePromise=initApp(factory,handlers,element,options),handlePromise};return{then(onfulfilled,onrejected){return init().then(onfulfilled,onrejected)},[Symbol.asyncIterator](){let handle=null,iterator=null,started=!1;return{async next(){if(!started)started=!0,handle=await init(),iterator=handle[Symbol.asyncIterator]();return iterator.next()},async return(){if(handle)handle.unmount();return{done:!0,value:void 0}}}}}}}}async function initApp(factory,handlers,element,options){let{cols:explicitCols,rows:explicitRows,stdout:explicitStdout,stdin=process2.stdin,signal:externalSignal,alternateScreen=!1,kittyMode:explicitKittyMode,kitty:kittyOption,mouse:mouseOption=!1,virtualInline:virtualInlineOption=!1,suspendOnCtrlZ:suspendOption=!0,exitOnCtrlC:exitOnCtrlCOption=!0,onSuspend:onSuspendHook,onResume:onResumeHook,onInterrupt:onInterruptHook,textSizing:textSizingOption,widthDetection:widthDetectionOption,focusReporting:focusReportingOption=!1,selection:selectionOption,caps:capsOption,guardOutput:guardOutputOption,Root:RootComponent,capabilityRegistry:capabilityRegistryOption,writable:explicitWritable,onResize:explicitOnResize,...injectValues}=options,useKittyMode=explicitKittyMode??!!kittyOption,headless=explicitCols!=null&&explicitRows!=null&&!explicitStdout||explicitWritable!=null,cols=explicitCols??process2.stdout.columns??80,rows=explicitRows??process2.stdout.rows??24,stdout=explicitStdout??process2.stdout,isRealStdout=stdout===process2.stdout,shouldGuardOutput=guardOutputOption??(alternateScreen&&!headless&&isRealStdout),outputGuard=null;await ensureLayoutEngine();let controller=new AbortController,signal2=controller.signal;if(externalSignal)if(externalSignal.aborted)controller.abort();else externalSignal.addEventListener("abort",()=>controller.abort(),{once:!0});let providers={},plainValues={},providerCleanups=[],termProvider=null;if(!("term"in injectValues)||!isFullProvider(injectValues.term)){let resizeListeners=new Set,termStdout=headless?{columns:cols,rows,write:()=>!0,isTTY:!1,on(event,handler){if(event==="resize")resizeListeners.add(handler);return termStdout},off(event,handler){if(event==="resize")resizeListeners.delete(handler);return termStdout}}:stdout,termStdin=headless?{isTTY:!1,on:()=>termStdin,off:()=>termStdin,setRawMode:()=>{},resume:()=>{},pause:()=>{},setEncoding:()=>{}}:stdin;if(termProvider=createTermProvider(termStdin,termStdout,{cols,rows}),providers.term=termProvider,providerCleanups.push(()=>termProvider[Symbol.dispose]()),headless&&explicitOnResize){let unsub=explicitOnResize((dims)=>{currentDims=dims,termStdout.columns=dims.cols,termStdout.rows=dims.rows;for(let listener of resizeListeners)listener()});providerCleanups.push(unsub)}}for(let[name,value]of Object.entries(injectValues))if(isFullProvider(value))providers[name]=value;else plainValues[name]=value;let inject={...providers,...plainValues},stateUnsubscribes=[],store=createStore((set,get,api)=>{let mergedState={...factory(inject)(set,get,api)};for(let[name,provider]of Object.entries(providers))if(mergedState[name]=provider,isBasicProvider(provider)){let unsub=provider.subscribe((_providerState)=>{});stateUnsubscribes.push(unsub)}for(let[name,value]of Object.entries(plainValues))mergedState[name]=value;return mergedState}),currentDims={cols,rows},shouldExit=!1,renderPaused=!1,isRendering=!1,inEventHandler=!1,pendingRerender=!1,_ansiTrace=!headless&&process2.env?.SILVERY_TRACE==="1",_traceSeq=0,_traceStart=performance.now(),_origStdoutWrite;if(_ansiTrace){let fs2=__require("node:fs");fs2.writeFileSync("/tmp/silvery-trace.log",`=== SILVERY TRACE START ===
81
+ `)}return parts.join("")}function renderSelectionOverlay(selection,buffer,mode="fullscreen",scope){if(!selection)return"";let{startRow,startCol,endRow,endCol}=normalizeRange(selection),out="";for(let row=startRow;row<=endRow;row++){let colStart=row===startRow?startCol:0,colEnd=row===endRow?endCol:buffer.width-1;if(scope)colStart=Math.max(colStart,scope.left),colEnd=Math.min(colEnd,scope.right);if(colStart>colEnd)continue;if(mode==="fullscreen")out+=`\x1B[${row+1};${colStart+1}H`;out+="\x1B[7m";for(let col=colStart;col<=colEnd;col++)out+=buffer.getCell(col,row).char;out+="\x1B[27m"}return out}init_unicode();function createVirtualScrollback(options){let maxLines=options?.maxLines??1e4,ansiLines=Array(maxLines),plainLines=Array(maxLines),head=0,count=0;return{push(lines){for(let line of lines)if(ansiLines[head]=line,plainLines[head]=stripAnsi2(line),head=(head+1)%maxLines,count<maxLines)count++},getVisibleRows(offset,rowCount){let result=[];for(let i=0;i<rowCount;i++){let logicalIndex=count-offset-rowCount+i;if(logicalIndex<0||logicalIndex>=count)result.push("");else{let physical=(head-count+logicalIndex+maxLines)%maxLines;result.push(ansiLines[physical])}}return result},get totalLines(){return count},search(query){if(!query)return[];let lowerQuery=query.toLowerCase(),matches=[];for(let i=0;i<count;i++){let physical=(head-count+i+maxLines)%maxLines;if(plainLines[physical].toLowerCase().includes(lowerQuery))matches.push(i)}return matches},clear(){head=0,count=0}}}init_unicode();init_unicode();function createSearchState(){return{active:!1,query:"",matches:[],currentMatch:-1,cursorPosition:0}}function searchUpdate(action,state,searchFn){switch(action.type){case"open":return[{...state,active:!0,query:"",matches:[],currentMatch:-1,cursorPosition:0},[{type:"render"}]];case"close":return[createSearchState(),[{type:"render"}]];case"input":{let query=state.query.slice(0,state.cursorPosition)+action.char+state.query.slice(state.cursorPosition),cursorPosition=state.cursorPosition+1,matches=searchFn?searchFn(query):[],currentMatch=matches.length>0?0:-1,effects=[{type:"render"}];if(currentMatch>=0)effects.push({type:"scrollTo",row:matches[0].row});return[{...state,query,cursorPosition,matches,currentMatch},effects]}case"backspace":{if(state.cursorPosition===0)return[state,[]];let query=state.query.slice(0,state.cursorPosition-1)+state.query.slice(state.cursorPosition),cursorPosition=state.cursorPosition-1,matches=searchFn?searchFn(query):[],currentMatch=matches.length>0?0:-1,effects=[{type:"render"}];if(currentMatch>=0)effects.push({type:"scrollTo",row:matches[0].row});return[{...state,query,cursorPosition,matches,currentMatch},effects]}case"nextMatch":{if(state.matches.length===0)return[state,[]];let currentMatch=(state.currentMatch+1)%state.matches.length;return[{...state,currentMatch},[{type:"scrollTo",row:state.matches[currentMatch].row},{type:"render"}]]}case"prevMatch":{if(state.matches.length===0)return[state,[]];let currentMatch=(state.currentMatch-1+state.matches.length)%state.matches.length;return[{...state,currentMatch},[{type:"scrollTo",row:state.matches[currentMatch].row},{type:"render"}]]}case"cursorLeft":if(state.cursorPosition===0)return[state,[]];return[{...state,cursorPosition:state.cursorPosition-1},[]];case"cursorRight":if(state.cursorPosition>=state.query.length)return[state,[]];return[{...state,cursorPosition:state.cursorPosition+1},[]];case"cursorToStart":if(state.cursorPosition===0)return[state,[]];return[{...state,cursorPosition:0},[]];case"cursorToEnd":if(state.cursorPosition>=state.query.length)return[state,[]];return[{...state,cursorPosition:state.query.length},[]];case"deleteWordBack":{if(state.cursorPosition===0)return[state,[]];let pos=state.cursorPosition;while(pos>0&&/\s/.test(state.query[pos-1]??""))pos--;while(pos>0&&!/\s/.test(state.query[pos-1]??""))pos--;let query=state.query.slice(0,pos)+state.query.slice(state.cursorPosition),cursorPosition=pos,matches=searchFn?searchFn(query):[],currentMatch=matches.length>0?0:-1,effects=[{type:"render"}];if(currentMatch>=0)effects.push({type:"scrollTo",row:matches[0].row});return[{...state,query,cursorPosition,matches,currentMatch},effects]}case"deleteToStart":{if(state.cursorPosition===0)return[state,[]];let query=state.query.slice(state.cursorPosition),cursorPosition=0,matches=searchFn?searchFn(query):[],currentMatch=matches.length>0?0:-1,effects=[{type:"render"}];if(currentMatch>=0)effects.push({type:"scrollTo",row:matches[0].row});return[{...state,query,cursorPosition,matches,currentMatch},effects]}}}function renderSearchBar(state,cols){let matchInfo=state.matches.length>0?` [${state.currentMatch+1}/${state.matches.length}]`:state.query?" [no matches]":"";return`\x1B[7m${(" / "+state.query+matchInfo).padEnd(cols)}\x1B[27m`}init_buffer();import{createLogger as createLogger13}from"loggily";init_errors();init_errors();var log10=createLogger13("silvery:scheduler"),SYNC_UPDATE_ENABLED=process.env.SILVERY_SYNC_UPDATE==="1"||process.env.SILVERY_SYNC_UPDATE==="true";function createHandlerContext(store,focusManager,container){let state=store.getState(),teaDispatch=typeof state.dispatch==="function"?state.dispatch:void 0;return{set:store.setState,get:store.getState,focusManager,focus(testID){let root=getContainerRoot(container);focusManager.focusById(testID,root,"programmatic")},activateScope(scopeId){let root=getContainerRoot(container);focusManager.activateScope(scopeId,root)},getFocusPath(){let root=getContainerRoot(container);return focusManager.getFocusPath(root)},dispatch:teaDispatch,hitTest(x,y){let root=getContainerRoot(container);return hitTest(root,x,y)}}}function handleFocusNavigation(input,parsedKey,focusManager,container){if(focusManager.activeElement){let keyEvent=createKeyEvent(input,parsedKey,focusManager.activeElement);if(dispatchKeyEvent(keyEvent),keyEvent.propagationStopped||keyEvent.defaultPrevented)return"consumed"}let root=getContainerRoot(container);if(parsedKey.tab&&!parsedKey.shift)return focusManager.focusNext(root),"consumed";if(parsedKey.tab&&parsedKey.shift)return focusManager.focusPrev(root),"consumed";if(parsedKey.return&&focusManager.activeElement){let activeEl=focusManager.activeElement,props=activeEl.props,testID=typeof props.testID==="string"?props.testID:null;if(props.focusScope&&testID)return focusManager.enterScope(testID),focusManager.focusNext(root,activeEl),"consumed"}if(parsedKey.escape){if(focusManager.scopeStack.length>0){let scopeId=focusManager.scopeStack[focusManager.scopeStack.length-1];focusManager.exitScope();let scopeNode=findByTestID(root,scopeId);if(scopeNode)focusManager.focus(scopeNode,"keyboard");return"consumed"}}return"continue"}function dispatchMouseEventToTree(event,mouseEventState,root){if(event.event!=="mouse"||!event.data)return!1;let mouseData=event.data;return processMouseEvent(mouseEventState,{button:mouseData.button,x:mouseData.x,y:mouseData.y,action:mouseData.action,delta:mouseData.delta,shift:mouseData.shift,meta:mouseData.meta,ctrl:mouseData.ctrl},root)}function invokeEventHandler(event,handlers,ctx,mouseEventState,container){let root=getContainerRoot(container);if(dispatchMouseEventToTree(event,mouseEventState,root))return!0;let namespacedHandler=handlers?.[event.type];if(namespacedHandler&&typeof namespacedHandler==="function"){let result=namespacedHandler(event.data,ctx);if(result==="exit")return!1;if(result==="flush")return"flush"}return!0}function dispatchKeyToHandlers(input,parsedKey,handlers,ctx){let namespacedHandler=handlers?.["term:key"];if(namespacedHandler&&typeof namespacedHandler==="function"){if(namespacedHandler({input,key:parsedKey},ctx)==="exit")return"exit"}if(handlers?.key){if(handlers.key(input,parsedKey,ctx)==="exit")return"exit"}return}init_keys();init_keys2();import{writeSync as writeSync2}from"node:fs";function captureTerminalState(opts){return{rawMode:opts.rawMode??!0,alternateScreen:opts.alternateScreen??!1,cursorHidden:opts.cursorHidden??!0,mouseEnabled:opts.mouse??!1,kittyEnabled:opts.kitty??!1,kittyFlags:opts.kittyFlags??11,bracketedPaste:opts.bracketedPaste??!1,focusReporting:opts.focusReporting??!1}}function restoreTerminalState(stdout,stdin){try{stdin.removeAllListeners("data"),stdin.pause()}catch{}let sequences=["\x1B[0m","\x1B[?1004l",disableMouse2(),disableKittyKeyboard2(),"\x1B[?2004l",resetCursorStyle(),"\x1B[?25h","\x1B[?1049l"].join("");if(stdout===process.stdout)try{writeSync2(stdout.fd,sequences)}catch{try{stdout.write(sequences)}catch{}}else try{stdout.write(sequences)}catch{}try{stdin.resume();while(stdin.read()!==null);stdin.pause()}catch{}if(stdin.isTTY&&stdin.isRaw)try{stdin.setRawMode(!1)}catch{}}function resumeTerminalState(state,stdout,stdin){if(state.rawMode&&stdin.isTTY)try{stdin.setRawMode(!0),stdin.resume()}catch{}let sequences=[];if(state.alternateScreen)sequences.push("\x1B[?1049h");if(sequences.push("\x1B[2J\x1B[H"),state.cursorHidden)sequences.push("\x1B[?25l");if(state.kittyEnabled)sequences.push(enableKittyKeyboard2(state.kittyFlags));if(state.mouseEnabled)sequences.push(enableMouse2());if(state.bracketedPaste)sequences.push("\x1B[?2004h");if(state.focusReporting)sequences.push("\x1B[?1004h");let joined=sequences.join("");if(stdout===process.stdout)try{writeSync2(stdout.fd,joined)}catch{try{stdout.write(joined)}catch{}}else try{stdout.write(joined)}catch{}stdout.emit("resize")}function performSuspend(state,stdout,stdin,onResume){restoreTerminalState(stdout,stdin),process.once("SIGCONT",()=>{resumeTerminalState(state,stdout,stdin),onResume?.()}),process.kill(process.pid,"SIGTSTP")}var CTRL_C="\x03",CTRL_Z="\x1A";init_term_provider();function createSelectionBridge(options){return{get state(){return options.getState()},subscribe(listener){return options.subscribe(listener)},handleMouseDown(_col,_row,_altKey){},handleMouseMove(_col,_row){},handleMouseUp(_col,_row){},setRange(range){options.setRange(range)},clear(){options.clear()},dispose(){}}}function createCapabilityRegistry(){let capabilities=new Map;return{register(key,capability){capabilities.set(key,capability)},get(key){return capabilities.get(key)}}}var SELECTION_CAPABILITY=Symbol.for("silvery.selection");init_output_guard();import{createLogger as createLogger14}from"loggily";var perfLog=createLogger14("silvery:perf"),samples=null,budgetOverruns=0;function checkBudget(key,durationMs,budgetMs=16){if(samples)samples.push({key,durationMs});if(durationMs>budgetMs)budgetOverruns++,perfLog.warn?.(`keypress over budget: ${key} took ${durationMs.toFixed(1)}ms (budget: ${budgetMs}ms)`)}function startTracking(){if(!samples)samples=[]}function logExitSummary(){if(!samples||samples.length===0)return;let durations=samples.map((s)=>s.durationMs).sort((a,b)=>a-b),total=samples.length,mean=durations.reduce((sum,d)=>sum+d,0)/total,p95Index=Math.min(Math.floor(total*0.95),total-1),p95=durations[p95Index],max=durations[total-1];perfLog.info?.(`keypress summary: ${total} presses, mean=${mean.toFixed(1)}ms, p95=${p95.toFixed(1)}ms, max=${max.toFixed(1)}ms, overruns=${budgetOverruns}`),samples=null,budgetOverruns=0}import{createLogger as createLogger15}from"loggily";import{jsxDEV}from"react/jsx-dev-runtime";var log11=createLogger15("silvery:app"),ENV=typeof process2<"u"?process2.env:void 0,NO_INCREMENTAL=ENV?.SILVERY_NO_INCREMENTAL==="1",STRICT_MODE=(()=>{let v=ENV?.SILVERY_STRICT;return!!v&&v!=="0"&&v!=="false"})(),CELL_DEBUG=(()=>{let v=ENV?.SILVERY_CELL_DEBUG;if(!v||!v.includes(","))return null;let[cx,cy]=v.split(",").map(Number);if(!Number.isFinite(cx)||!Number.isFinite(cy))return null;return{x:cx,y:cy}})(),INSTRUMENTED=STRICT_MODE||CELL_DEBUG!==null;function isFullProvider(value){if(value===null||value===void 0)return!1;if(typeof value!=="object"&&typeof value!=="function")return!1;return"getState"in value&&"subscribe"in value&&"events"in value&&typeof value.getState==="function"&&typeof value.subscribe==="function"&&typeof value.events==="function"}function isBasicProvider(value){if(value===null||value===void 0)return!1;if(typeof value!=="object"&&typeof value!=="function")return!1;return"getState"in value&&"subscribe"in value&&typeof value.getState==="function"&&typeof value.subscribe==="function"}var StoreContext=createContext4(null);function useApp(selector){let store=useContext3(StoreContext);if(!store)throw Error("useApp must be used within createApp().run()");let[state,setState]=React5.useState(()=>selector(store.getState())),selectorRef=useRef3(selector);return selectorRef.current=selector,useEffect2(()=>{return store.subscribe((newState)=>{let next=selectorRef.current(newState);setState((prev)=>Object.is(prev,next)?prev:next)})},[store]),state}function shallowEqual(a,b){if(Object.is(a,b))return!0;if(typeof a!=="object"||typeof b!=="object"||a===null||b===null)return!1;let keysA=Object.keys(a),keysB=Object.keys(b);if(keysA.length!==keysB.length)return!1;for(let key of keysA)if(!Object.is(a[key],b[key]))return!1;return!0}function useAppShallow(selector){let store=useContext3(StoreContext);if(!store)throw Error("useAppShallow must be used within createApp().run()");let[state,setState]=React5.useState(()=>selector(store.getState())),selectorRef=useRef3(selector);return selectorRef.current=selector,useEffect2(()=>{return store.subscribe((newState)=>{let next=selectorRef.current(newState);setState((prev)=>shallowEqual(prev,next)?prev:next)})},[store]),state}function createApp(factory,handlers){return{run(element,options={}){let handlePromise=null,init=()=>{if(handlePromise)return handlePromise;return handlePromise=initApp(factory,handlers,element,options),handlePromise};return{then(onfulfilled,onrejected){return init().then(onfulfilled,onrejected)},[Symbol.asyncIterator](){let handle=null,iterator=null,started=!1;return{async next(){if(!started)started=!0,handle=await init(),iterator=handle[Symbol.asyncIterator]();return iterator.next()},async return(){if(handle)handle.unmount();return{done:!0,value:void 0}}}}}}}}async function initApp(factory,handlers,element,options){let{cols:explicitCols,rows:explicitRows,stdout:explicitStdout,stdin=process2.stdin,signal:externalSignal,alternateScreen=!1,kittyMode:explicitKittyMode,kitty:kittyOption,mouse:mouseOption=!1,virtualInline:virtualInlineOption=!1,suspendOnCtrlZ:suspendOption=!0,exitOnCtrlC:exitOnCtrlCOption=!0,onSuspend:onSuspendHook,onResume:onResumeHook,onInterrupt:onInterruptHook,textSizing:textSizingOption,widthDetection:widthDetectionOption,focusReporting:focusReportingOption=!1,selection:selectionOption,caps:capsOption,guardOutput:guardOutputOption,Root:RootComponent,capabilityRegistry:capabilityRegistryOption,writable:explicitWritable,onResize:explicitOnResize,...injectValues}=options,useKittyMode=explicitKittyMode??!!kittyOption,headless=explicitCols!=null&&explicitRows!=null&&!explicitStdout||explicitWritable!=null,cols=explicitCols??process2.stdout.columns??80,rows=explicitRows??process2.stdout.rows??24,stdout=explicitStdout??process2.stdout,isRealStdout=stdout===process2.stdout,shouldGuardOutput=guardOutputOption??(alternateScreen&&!headless&&isRealStdout),outputGuard=null;await ensureLayoutEngine();let controller=new AbortController,signal2=controller.signal;if(externalSignal)if(externalSignal.aborted)controller.abort();else externalSignal.addEventListener("abort",()=>controller.abort(),{once:!0});let providers={},plainValues={},providerCleanups=[],termProvider=null;if(!("term"in injectValues)||!isFullProvider(injectValues.term)){let resizeListeners=new Set,termStdout=headless?{columns:cols,rows,write:()=>!0,isTTY:!1,on(event,handler){if(event==="resize")resizeListeners.add(handler);return termStdout},off(event,handler){if(event==="resize")resizeListeners.delete(handler);return termStdout}}:stdout,termStdin=headless?{isTTY:!1,on:()=>termStdin,off:()=>termStdin,setRawMode:()=>{},resume:()=>{},pause:()=>{},setEncoding:()=>{}}:stdin;if(termProvider=createTermProvider(termStdin,termStdout,{cols,rows}),providers.term=termProvider,providerCleanups.push(()=>termProvider[Symbol.dispose]()),headless&&explicitOnResize){let unsub=explicitOnResize((dims)=>{currentDims=dims,termStdout.columns=dims.cols,termStdout.rows=dims.rows;for(let listener of resizeListeners)listener()});providerCleanups.push(unsub)}}for(let[name,value]of Object.entries(injectValues))if(isFullProvider(value))providers[name]=value;else plainValues[name]=value;let inject={...providers,...plainValues},stateUnsubscribes=[],store=createStore((set,get,api)=>{let mergedState={...factory(inject)(set,get,api)};for(let[name,provider]of Object.entries(providers))if(mergedState[name]=provider,isBasicProvider(provider)){let unsub=provider.subscribe((_providerState)=>{});stateUnsubscribes.push(unsub)}for(let[name,value]of Object.entries(plainValues))mergedState[name]=value;return mergedState}),currentDims={cols,rows};if(!headless){let onStdoutResize=()=>{currentDims={cols:stdout.columns||80,rows:stdout.rows||24};for(let listener of mockTermSubscribers)listener(currentDims)};stdout.on("resize",onStdoutResize),providerCleanups.push(()=>stdout.off("resize",onStdoutResize))}let shouldExit=!1,renderPaused=!1,isRendering=!1,inEventHandler=!1,pendingRerender=!1,_ansiTrace=!headless&&process2.env?.SILVERY_TRACE==="1",_traceSeq=0,_traceStart=performance.now(),_origStdoutWrite;if(_ansiTrace){let fs2=__require("node:fs");fs2.writeFileSync("/tmp/silvery-trace.log",`=== SILVERY TRACE START ===
77
82
  `),_origStdoutWrite=stdout.write.bind(stdout);let symbolize=(s)=>s.replace(/\x1b\[\?1049h/g,"⟨ALT_ON⟩").replace(/\x1b\[\?1049l/g,"⟨ALT_OFF⟩").replace(/\x1b\[2J/g,"⟨CLEAR⟩").replace(/\x1b\[H/g,"⟨HOME⟩").replace(/\x1b\[\?25l/g,"⟨CUR_HIDE⟩").replace(/\x1b\[\?25h/g,"⟨CUR_SHOW⟩").replace(/\x1b\[\?2026h/g,"⟨SYNC_ON⟩").replace(/\x1b\[\?2026l/g,"⟨SYNC_OFF⟩").replace(/\x1b\[\?2004h/g,"⟨BPASTE_ON⟩").replace(/\x1b\[\?2004l/g,"⟨BPASTE_OFF⟩").replace(/\x1b\[0m/g,"⟨RST⟩").replace(/\x1b\[(\d+);(\d+)H/g,"⟨GO $1,$2⟩").replace(/\x1b\[38;5;(\d+)m/g,"⟨F$1⟩").replace(/\x1b\[48;5;(\d+)m/g,"⟨B$1⟩").replace(/\x1b\[38;2;(\d+);(\d+);(\d+)m/g,"⟨FR$1,$2,$3⟩").replace(/\x1b\[48;2;(\d+);(\d+);(\d+)m/g,"⟨BR$1,$2,$3⟩").replace(/\x1b\[1m/g,"⟨BOLD⟩").replace(/\x1b\[2m/g,"⟨DIM⟩").replace(/\x1b\[3m/g,"⟨ITAL⟩").replace(/\x1b\[4m/g,"⟨UL⟩").replace(/\x1b\[7m/g,"⟨INV⟩").replace(/\x1b\[22m/g,"⟨/BOLD⟩").replace(/\x1b\[23m/g,"⟨/ITAL⟩").replace(/\x1b\[24m/g,"⟨/UL⟩").replace(/\x1b\[27m/g,"⟨/INV⟩").replace(/\x1b\[39m/g,"⟨/FG⟩").replace(/\x1b\[49m/g,"⟨/BG⟩").replace(/\x1b\[([0-9;]*)([A-Za-z])/g,"⟨CSI $1$2⟩").replace(/\x1b([^\[])/,"⟨ESC $1⟩"),traceWrite=function(chunk,...args){let str=typeof chunk==="string"?chunk:String(chunk),seq=++_traceSeq,ms=(performance.now()-_traceStart).toFixed(0),decoded=symbolize(str),preview=decoded.length>400?decoded.slice(0,200)+` ...[${decoded.length}ch]... `+decoded.slice(-100):decoded;return fs2.appendFileSync("/tmp/silvery-trace.log",`[${String(seq).padStart(4,"0")}] +${ms}ms (${str.length}b): ${preview}
78
83
  `),_origStdoutWrite.call(this,chunk,...args)};stdout.write=traceWrite,providerCleanups.push(()=>{if(_origStdoutWrite)stdout.write=_origStdoutWrite})}let target=headless?{write(frame){if(explicitWritable)explicitWritable.write(frame)},getDims:()=>currentDims}:{write(frame){if(_perfLog)__require("node:fs").appendFileSync("/tmp/silvery-perf.log",`TARGET.write: ${frame.length} bytes (paused=${renderPaused})
79
- `);if(!renderPaused)if(outputGuard)outputGuard.writeStdout(frame);else stdout.write(frame)},getDims(){return currentDims},onResize(handler){let onResize=()=>{currentDims={cols:stdout.columns||80,rows:stdout.rows||24},handler(currentDims)};return stdout.on("resize",onResize),()=>stdout.off("resize",onResize)}},heuristicSupported=capsOption?.textSizingSupported??isTextSizingLikelySupported(),shouldProbe=textSizingOption==="probe"||textSizingOption==="auto"&&heuristicSupported,cachedProbe=shouldProbe?getCachedProbeResult():void 0,textSizingEnabled;if(textSizingOption===!0)textSizingEnabled=!0;else if(textSizingOption==="probe")textSizingEnabled=cachedProbe?.supported??!1;else if(textSizingOption==="auto")if(cachedProbe!==void 0)textSizingEnabled=cachedProbe.supported;else textSizingEnabled=heuristicSupported;else textSizingEnabled=!1;let needsProbe=shouldProbe&&cachedProbe===void 0&&!headless,needsWidthDetection=!headless&&(widthDetectionOption===!0||widthDetectionOption==="auto"&&capsOption!=null),effectiveCaps=capsOption?{...capsOption,textSizingSupported:textSizingEnabled}:void 0,pipelineConfig=effectiveCaps?createPipeline({caps:effectiveCaps}):void 0,runtime=createRuntime({target,signal:signal2,mode:alternateScreen?"fullscreen":"inline",outputPhaseFn:pipelineConfig?.outputPhaseFn}),cleanedUp=!1,storeUnsubscribeFn=null,kittyEnabled=!1,defaultKittyFlags=KittyFlags.DISAMBIGUATE|KittyFlags.REPORT_EVENTS|KittyFlags.REPORT_ALL_KEYS,kittyFlags=defaultKittyFlags,mouseEnabled=!1,focusReportingEnabled=!1,selectionEnabled=selectionOption??!1,selectionState=createTerminalSelectionState(),selectionListeners=new Set;function notifySelectionListeners(){for(let listener of selectionListeners)listener()}let capabilityRegistry=capabilityRegistryOption??createCapabilityRegistry(),selectionBridge;if(selectionEnabled)selectionBridge=createSelectionBridge({getState:()=>selectionState,subscribe:(listener)=>{return selectionListeners.add(listener),()=>{selectionListeners.delete(listener)}},setRange:(range)=>{if(range===null){let[next]=terminalSelectionUpdate({type:"clear"},selectionState);selectionState=next}else{let[s1]=terminalSelectionUpdate({type:"start",col:range.anchor.col,row:range.anchor.row,source:"keyboard"},selectionState),[s2]=terminalSelectionUpdate({type:"extend",col:range.head.col,row:range.head.row},s1),[s3]=terminalSelectionUpdate({type:"finish"},s2);selectionState=s3}if(notifySelectionListeners(),currentBuffer)runtime.invalidate()},clear:()=>{let[next]=terminalSelectionUpdate({type:"clear"},selectionState);if(selectionState=next,notifySelectionListeners(),currentBuffer)runtime.invalidate()}}),capabilityRegistry.register(SELECTION_CAPABILITY,selectionBridge);let scrollback=virtualInlineOption?createVirtualScrollback():null,virtualScrollOffset=0,searchState=createSearchState(),focusManager=createFocusManager({onFocusChange(oldNode,newNode,_origin){if(oldNode){let blurEvent=createFocusEvent("blur",oldNode,newNode);dispatchFocusEvent(blurEvent)}if(newNode){let focusEvent=createFocusEvent("focus",newNode,oldNode);dispatchFocusEvent(focusEvent)}}});setOnNodeRemoved((removedNode)=>focusManager.handleSubtreeRemoved(removedNode));let cursorStore=createCursorStore(),mouseEventState=createMouseEventProcessor({focusManager}),cleanup=()=>{if(cleanedUp)return;cleanedUp=!0,logExitSummary();try{reconciler.updateContainerSync(null,fiberRoot,null,()=>{}),reconciler.flushSyncWork()}catch{}if(setOnNodeRemoved(null),storeUnsubscribeFn)storeUnsubscribeFn();if(stateUnsubscribes.forEach((unsub)=>{try{unsub()}catch{}}),outputGuard)outputGuard.dispose(),outputGuard=null;if(!headless&&stdin.isTTY){stdin.removeAllListeners("data"),stdin.pause();let sequences=["\x1B[?1004l",disableMouse2(),disableKittyKeyboard2(),"\x1B[?2004l","\x1B[0m",resetCursorStyle(),"\x1B[?25h",alternateScreen?"\x1B[?1049l":""].join("");if(stdout===process2.stdout){try{writeSync3(stdout.fd,sequences)}catch{try{stdout.write(sequences)}catch{}}try{stdin.resume();while(stdin.read()!==null);stdin.pause()}catch{}}else try{stdout.write(sequences)}catch{}try{stdin.setRawMode(!1)}catch{}}else if(!headless){let sequences=["\x1B[?1004l",disableMouse2(),disableKittyKeyboard2(),"\x1B[?2004l","\x1B[0m",resetCursorStyle(),"\x1B[?25h",alternateScreen?"\x1B[?1049l":""].join("");try{stdout.write(sequences)}catch{}}providerCleanups.forEach((fn)=>{try{fn()}catch{}}),runtime[Symbol.dispose]()},exit,container=createContainer(()=>{if(shouldExit)return;if(inEventHandler){pendingRerender=!0;return}if(!pendingRerender)pendingRerender=!0,queueMicrotask(()=>{if(!pendingRerender)return;if(pendingRerender=!1,!shouldExit&&!isRendering){isRendering=!0;try{currentBuffer=doRender(),runtime.render(currentBuffer)}finally{isRendering=!1}}})}),fiberRoot=createFiberRoot(container),currentBuffer,mockStdout={columns:cols,rows,write:()=>!0,isTTY:!1,on:()=>mockStdout,off:()=>mockStdout,once:()=>mockStdout,removeListener:()=>mockStdout,addListener:()=>mockStdout},baseMockTerm=createTerm({color:"truecolor"}),mockTerm=Object.create(baseMockTerm,{getState:{value:()=>currentDims}}),runtimeInputListeners=new Set,runtimePasteListeners=new Set,runtimeFocusListeners=new Set,runtimeEventListeners=new Map;runtimeEventListeners.set("input",runtimeInputListeners),runtimeEventListeners.set("paste",runtimePasteListeners),runtimeEventListeners.set("focus",runtimeFocusListeners);let runtimeContextValue={on(event,handler){let listeners=runtimeEventListeners.get(event);if(!listeners)listeners=new Set,runtimeEventListeners.set(event,listeners);return listeners.add(handler),()=>listeners.delete(handler)},emit(event,...args){let listeners=runtimeEventListeners.get(event);if(listeners)for(let listener of listeners)listener(...args)},exit:()=>exit()},Root=RootComponent??React5.Fragment,cacheBackend=!alternateScreen?"terminal":virtualInlineOption?"virtual":"retain",wrappedElement=jsxDEV(SilveryErrorBoundary,{children:jsxDEV(CursorProvider,{store:cursorStore,children:jsxDEV(CacheBackendContext.Provider,{value:cacheBackend,children:jsxDEV(TermContext.Provider,{value:mockTerm,children:jsxDEV(StdoutContext.Provider,{value:{stdout:mockStdout,write:()=>{},notifyScrollback:(lines)=>runtime.addScrollbackLines(lines),promoteScrollback:(content,lines)=>runtime.promoteScrollback(content,lines),resetInlineCursor:()=>runtime.resetInlineCursor(),getInlineCursorRow:()=>runtime.getInlineCursorRow()},children:jsxDEV(StderrContext.Provider,{value:{stderr:process2.stderr,write:(data)=>{process2.stderr.write(data)}},children:jsxDEV(FocusManagerContext.Provider,{value:focusManager,children:jsxDEV(RuntimeContext.Provider,{value:runtimeContextValue,children:jsxDEV(CapabilityRegistryContext.Provider,{value:capabilityRegistry,children:jsxDEV(Root,{children:jsxDEV(StoreContext.Provider,{value:store,children:element},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),_renderCount=0,_eventStart=0,_perfLog=typeof process2<"u"&&process2.env?.DEBUG?.includes("silvery:perf"),_noIncremental=NO_INCREMENTAL,_ag=null,_lastTermBuffer=null;function doRender(){if(_renderCount++,_ansiTrace)__require("node:fs").appendFileSync("/tmp/silvery-trace.log",`--- doRender #${_renderCount} (ag=${_ag?"reuse":"create"}, incremental=${!_noIncremental}) ---
80
- `);let renderStart=performance.now();reconciler.updateContainerSync(wrappedElement,fiberRoot,null,()=>{}),reconciler.flushSyncWork();let reconcileMs=performance.now()-renderStart;{let acc=globalThis.__silvery_bench_phases;if(acc)acc.reconcile+=reconcileMs}let pipelineStart=performance.now(),rootNode=getContainerRoot(container),dims=runtime.getDims(),isInline=!alternateScreen;if(!_ag)_ag=createAg(rootNode,{measurer:pipelineConfig?.measurer});if(_ag&&_renderCount>1){let lastBuffer=_lastTermBuffer;if(lastBuffer){let widthChanged=dims.cols!==lastBuffer.width,heightChanged=!isInline&&dims.rows!==lastBuffer.height;if(widthChanged||heightChanged)_ag.resetBuffer(),runtime.invalidate()}}if(INSTRUMENTED)globalThis.__silvery_content_all=void 0,globalThis.__silvery_node_trace=void 0,globalThis.__silvery_cell_debug=CELL_DEBUG!==null?{x:CELL_DEBUG.x,y:CELL_DEBUG.y,log:[]}:void 0;if(!(rootNode.layoutDirty||rootNode.contentDirty||rootNode.stylePropsDirty||rootNode.bgDirty||rootNode.subtreeDirty||rootNode.childrenDirty)&&_lastTermBuffer&&currentBuffer)return currentBuffer;if(_noIncremental)_ag.resetBuffer();_ag.layout(dims);let{buffer:termBuffer,prevBuffer:agPrevBuffer}=_ag.render();_lastTermBuffer=termBuffer;let wasIncremental=!_noIncremental&&agPrevBuffer!==null,pipelineMs=performance.now()-pipelineStart;globalThis.__silvery_last_pipeline={layout:pipelineMs,output:0,total:pipelineMs,incremental:wasIncremental},globalThis.__silvery_render_count=(globalThis.__silvery_render_count??0)+1;{let acc=globalThis.__silvery_bench_phases;if(acc)acc.total+=pipelineMs,acc.pipelineCalls+=1}if(STRICT_MODE&&wasIncremental){let{buffer:freshBuffer}=executeRender(rootNode,dims.cols,dims.rows,null,{skipLayoutNotifications:!0,skipScrollStateUpdates:!0},pipelineConfig),{cellEquals:cellEquals2,bufferToText:bufferToText2}=(init_buffer(),__toCommonJS(exports_buffer));for(let y=0;y<termBuffer.height;y++)for(let x=0;x<termBuffer.width;x++){let a=termBuffer.getCell(x,y),b=freshBuffer.getCell(x,y);if(!cellEquals2(a,b)){let cellDebugInfo="",savedCellDbg=globalThis.__silvery_cell_debug;if(savedCellDbg&&savedCellDbg.x===x&&savedCellDbg.y===y&&savedCellDbg.log.length>0)cellDebugInfo=`
84
+ `);if(!renderPaused)if(outputGuard)outputGuard.writeStdout(frame);else stdout.write(frame)},getDims(){return currentDims},onResize(handler){let onResize=()=>{currentDims={cols:stdout.columns||80,rows:stdout.rows||24},handler(currentDims)};return stdout.on("resize",onResize),()=>stdout.off("resize",onResize)}},heuristicSupported=capsOption?.textSizingSupported??isTextSizingLikelySupported(),shouldProbe=textSizingOption==="probe"||textSizingOption==="auto"&&heuristicSupported,cachedProbe=shouldProbe?getCachedProbeResult():void 0,textSizingEnabled;if(textSizingOption===!0)textSizingEnabled=!0;else if(textSizingOption==="probe")textSizingEnabled=cachedProbe?.supported??!1;else if(textSizingOption==="auto")if(cachedProbe!==void 0)textSizingEnabled=cachedProbe.supported;else textSizingEnabled=heuristicSupported;else textSizingEnabled=!1;let needsProbe=shouldProbe&&cachedProbe===void 0&&!headless,needsWidthDetection=!headless&&(widthDetectionOption===!0||widthDetectionOption==="auto"&&capsOption!=null),effectiveCaps=capsOption?{...capsOption,textSizingSupported:textSizingEnabled}:void 0,pipelineConfig=effectiveCaps?createPipeline({caps:effectiveCaps}):void 0,runtime=createRuntime({target,signal:signal2,mode:alternateScreen?"fullscreen":"inline",outputPhaseFn:pipelineConfig?.outputPhaseFn}),cleanedUp=!1,storeUnsubscribeFn=null,kittyEnabled=!1,defaultKittyFlags=KittyFlags.DISAMBIGUATE|KittyFlags.REPORT_EVENTS|KittyFlags.REPORT_ALL_KEYS,kittyFlags=defaultKittyFlags,mouseEnabled=!1,focusReportingEnabled=!1,selectionEnabled=selectionOption??!1,selectionState=createTerminalSelectionState(),selectionListeners=new Set;function notifySelectionListeners(){for(let listener of selectionListeners)listener()}let capabilityRegistry=capabilityRegistryOption??createCapabilityRegistry(),selectionBridge;if(selectionEnabled)selectionBridge=createSelectionBridge({getState:()=>selectionState,subscribe:(listener)=>{return selectionListeners.add(listener),()=>{selectionListeners.delete(listener)}},setRange:(range)=>{if(range===null){let[next]=terminalSelectionUpdate({type:"clear"},selectionState);selectionState=next}else{let[s1]=terminalSelectionUpdate({type:"start",col:range.anchor.col,row:range.anchor.row,source:"keyboard"},selectionState),[s2]=terminalSelectionUpdate({type:"extend",col:range.head.col,row:range.head.row},s1),[s3]=terminalSelectionUpdate({type:"finish"},s2);selectionState=s3}if(notifySelectionListeners(),currentBuffer)runtime.invalidate()},clear:()=>{let[next]=terminalSelectionUpdate({type:"clear"},selectionState);if(selectionState=next,notifySelectionListeners(),currentBuffer)runtime.invalidate()}}),capabilityRegistry.register(SELECTION_CAPABILITY,selectionBridge);let scrollback=virtualInlineOption?createVirtualScrollback():null,virtualScrollOffset=0,searchState=createSearchState(),focusManager=createFocusManager({onFocusChange(oldNode,newNode,_origin){if(oldNode){let blurEvent=createFocusEvent("blur",oldNode,newNode);dispatchFocusEvent(blurEvent)}if(newNode){let focusEvent=createFocusEvent("focus",newNode,oldNode);dispatchFocusEvent(focusEvent)}}});setOnNodeRemoved((removedNode)=>focusManager.handleSubtreeRemoved(removedNode));let cursorStore=createCursorStore(),mouseEventState=createMouseEventProcessor({focusManager}),cleanup=()=>{if(cleanedUp)return;cleanedUp=!0,logExitSummary();try{reconciler.updateContainerSync(null,fiberRoot,null,()=>{}),reconciler.flushSyncWork()}catch{}if(setOnNodeRemoved(null),storeUnsubscribeFn)storeUnsubscribeFn();if(stateUnsubscribes.forEach((unsub)=>{try{unsub()}catch{}}),outputGuard)outputGuard.dispose(),outputGuard=null;if(!headless&&stdin.isTTY){stdin.removeAllListeners("data"),stdin.pause();let sequences=["\x1B[?1004l",disableMouse2(),disableKittyKeyboard2(),"\x1B[?2004l","\x1B[0m",resetCursorStyle(),"\x1B[?25h",alternateScreen?"\x1B[?1049l":""].join("");if(stdout===process2.stdout){try{writeSync3(stdout.fd,sequences)}catch{try{stdout.write(sequences)}catch{}}try{stdin.resume();while(stdin.read()!==null);stdin.pause()}catch{}}else try{stdout.write(sequences)}catch{}try{stdin.setRawMode(!1)}catch{}}else if(!headless){let sequences=["\x1B[?1004l",disableMouse2(),disableKittyKeyboard2(),"\x1B[?2004l","\x1B[0m",resetCursorStyle(),"\x1B[?25h",alternateScreen?"\x1B[?1049l":""].join("");try{stdout.write(sequences)}catch{}}providerCleanups.forEach((fn)=>{try{fn()}catch{}}),runtime[Symbol.dispose]()},exit,container=createContainer(()=>{if(shouldExit)return;if(inEventHandler){pendingRerender=!0;return}if(!pendingRerender)pendingRerender=!0,queueMicrotask(()=>{if(!pendingRerender)return;if(pendingRerender=!1,!shouldExit&&!isRendering){isRendering=!0;try{currentBuffer=doRender(),runtime.render(currentBuffer)}finally{isRendering=!1}}})}),fiberRoot=createFiberRoot(container),currentBuffer,mockStdout={columns:cols,rows,write:()=>!0,isTTY:!1,on:()=>mockStdout,off:()=>mockStdout,once:()=>mockStdout,removeListener:()=>mockStdout,addListener:()=>mockStdout},baseMockTerm=createTerm({color:"truecolor"}),mockTermSubscribers=new Set,mockTerm=Object.create(baseMockTerm,{getState:{value:()=>currentDims},subscribe:{value:(listener)=>{return mockTermSubscribers.add(listener),()=>mockTermSubscribers.delete(listener)}}}),runtimeInputListeners=new Set,runtimePasteListeners=new Set,runtimeFocusListeners=new Set,runtimeEventListeners=new Map;runtimeEventListeners.set("input",runtimeInputListeners),runtimeEventListeners.set("paste",runtimePasteListeners),runtimeEventListeners.set("focus",runtimeFocusListeners);let runtimeContextValue={on(event,handler){let listeners=runtimeEventListeners.get(event);if(!listeners)listeners=new Set,runtimeEventListeners.set(event,listeners);return listeners.add(handler),()=>listeners.delete(handler)},emit(event,...args){let listeners=runtimeEventListeners.get(event);if(listeners)for(let listener of listeners)listener(...args)},exit:()=>exit()},Root=RootComponent??React5.Fragment,cacheBackend=!alternateScreen?"terminal":virtualInlineOption?"virtual":"retain",wrappedElement=jsxDEV(SilveryErrorBoundary,{children:jsxDEV(CursorProvider,{store:cursorStore,children:jsxDEV(CacheBackendContext.Provider,{value:cacheBackend,children:jsxDEV(TermContext.Provider,{value:mockTerm,children:jsxDEV(StdoutContext.Provider,{value:{stdout:mockStdout,write:()=>{},notifyScrollback:(lines)=>runtime.addScrollbackLines(lines),promoteScrollback:(content,lines)=>runtime.promoteScrollback(content,lines),resetInlineCursor:()=>runtime.resetInlineCursor(),getInlineCursorRow:()=>runtime.getInlineCursorRow()},children:jsxDEV(StderrContext.Provider,{value:{stderr:process2.stderr,write:(data)=>{process2.stderr.write(data)}},children:jsxDEV(FocusManagerContext.Provider,{value:focusManager,children:jsxDEV(RuntimeContext.Provider,{value:runtimeContextValue,children:jsxDEV(CapabilityRegistryContext.Provider,{value:capabilityRegistry,children:jsxDEV(Root,{children:jsxDEV(StoreContext.Provider,{value:store,children:element},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),_renderCount=0,_eventStart=0,_perfLog=typeof process2<"u"&&process2.env?.DEBUG?.includes("silvery:perf"),_noIncremental=NO_INCREMENTAL,_ag=null,_lastTermBuffer=null;function doRender(){if(_renderCount++,_ansiTrace)__require("node:fs").appendFileSync("/tmp/silvery-trace.log",`--- doRender #${_renderCount} (ag=${_ag?"reuse":"create"}, incremental=${!_noIncremental}) ---
85
+ `);let renderStart=performance.now();reconciler.updateContainerSync(wrappedElement,fiberRoot,null,()=>{}),reconciler.flushSyncWork();let reconcileMs=performance.now()-renderStart;{let acc=globalThis.__silvery_bench_phases;if(acc)acc.reconcile+=reconcileMs}let pipelineStart=performance.now(),rootNode=getContainerRoot(container),dims=runtime.getDims(),isInline=!alternateScreen;if(!_ag)_ag=createAg(rootNode,{measurer:pipelineConfig?.measurer});if(_ag){let lastBuffer=_lastTermBuffer;if(lastBuffer){let widthChanged=dims.cols!==lastBuffer.width,heightChanged=!isInline&&dims.rows!==lastBuffer.height;if(widthChanged||heightChanged)_ag.resetBuffer(),runtime.invalidate()}}if(INSTRUMENTED)globalThis.__silvery_content_all=void 0,globalThis.__silvery_node_trace=void 0,globalThis.__silvery_cell_debug=CELL_DEBUG!==null?{x:CELL_DEBUG.x,y:CELL_DEBUG.y,log:[]}:void 0;let rootHasDirty=rootNode.layoutDirty||isAnyDirty(rootNode.dirtyBits,rootNode.dirtyEpoch),dimsChanged=_lastTermBuffer!=null&&(dims.cols!==_lastTermBuffer.width||dims.rows!==_lastTermBuffer.height);if(!rootHasDirty&&!dimsChanged&&_lastTermBuffer&&currentBuffer)return currentBuffer;if(_noIncremental)_ag.resetBuffer();_ag.layout(dims);let{buffer:termBuffer,prevBuffer:agPrevBuffer}=_ag.render();_lastTermBuffer=termBuffer;let wasIncremental=!_noIncremental&&agPrevBuffer!==null,pipelineMs=performance.now()-pipelineStart;globalThis.__silvery_last_pipeline={layout:pipelineMs,output:0,total:pipelineMs,incremental:wasIncremental},globalThis.__silvery_render_count=(globalThis.__silvery_render_count??0)+1;{let acc=globalThis.__silvery_bench_phases;if(acc)acc.total+=pipelineMs,acc.pipelineCalls+=1}if(STRICT_MODE&&wasIncremental){let{buffer:freshBuffer}=executeRender(rootNode,dims.cols,dims.rows,null,{skipLayoutNotifications:!0,skipScrollStateUpdates:!0},pipelineConfig),{cellEquals:cellEquals2,bufferToText:bufferToText2}=(init_buffer(),__toCommonJS(exports_buffer));for(let y=0;y<termBuffer.height;y++)for(let x=0;x<termBuffer.width;x++){let a=termBuffer.getCell(x,y),b=freshBuffer.getCell(x,y);if(!cellEquals2(a,b)){let cellDebugInfo="",savedCellDbg=globalThis.__silvery_cell_debug;if(savedCellDbg&&savedCellDbg.x===x&&savedCellDbg.y===y&&savedCellDbg.log.length>0)cellDebugInfo=`
81
86
  CELL DEBUG (${savedCellDbg.log.length} entries for (${x},${y})):
82
87
  ${savedCellDbg.log.join(`
83
88
  `)}
@@ -108,7 +113,7 @@ ${freshText}`;throw __require("node:fs").appendFileSync("/tmp/silvery-perf.log",
108
113
  `)}let buf=createBuffer2(termBuffer,rootNode);if(_perfLog){let renderDuration=performance.now()-renderStart,phases=globalThis.__silvery_last_pipeline,detail=globalThis.__silvery_content_detail,phaseStr=phases?` [measure=${phases.measure.toFixed(1)} layout=${phases.layout.toFixed(1)} content=${phases.content.toFixed(1)} output=${phases.output.toFixed(1)}]`:"",detailStr=detail?` {visited=${detail.nodesVisited} rendered=${detail.nodesRendered} skipped=${detail.nodesSkipped} noPrev=${detail.noPrevBuffer??0} dirty=${detail.flagContentDirty??0} paint=${detail.flagStylePropsDirty??0} layoutChg=${detail.flagLayoutChanged??0} subtree=${detail.flagSubtreeDirty??0} children=${detail.flagChildrenDirty??0} childPos=${detail.flagChildPositionChanged??0} scroll=${detail.scrollContainerCount??0}/${detail.scrollViewportCleared??0}${detail.scrollClearReason?`(${detail.scrollClearReason})`:""}}${detail.cascadeNodes?` CASCADE[minDepth=${detail.cascadeMinDepth} ${detail.cascadeNodes}]`:""}`:"";__require("node:fs").appendFileSync("/tmp/silvery-perf.log",`doRender #${_renderCount}: ${renderDuration.toFixed(1)}ms (reconcile=${reconcileMs.toFixed(1)}ms pipeline=${pipelineMs.toFixed(1)}ms ${dims.cols}x${dims.rows})${phaseStr}${detailStr}
109
114
  `)}return buf}if(_ansiTrace)__require("node:fs").appendFileSync("/tmp/silvery-trace.log",`=== INITIAL RENDER ===
110
115
  `);if(currentBuffer=doRender(),!headless){if(_ansiTrace)__require("node:fs").appendFileSync("/tmp/silvery-trace.log",`=== ALT SCREEN + CLEAR ===
111
- `);if(alternateScreen)stdout.write("\x1B[?1049h"),stdout.write("\x1B[2J\x1B[H");if(stdout.write("\x1B[?25l"),kittyOption!=null&&kittyOption!==!1)if(kittyOption===!0){if((await detectKittyFromStdio(stdout,stdin)).supported)stdout.write(enableKittyKeyboard2(defaultKittyFlags)),kittyEnabled=!0,kittyFlags=defaultKittyFlags}else stdout.write(enableKittyKeyboard2(kittyOption)),kittyEnabled=!0,kittyFlags=kittyOption;else stdout.write(enableKittyKeyboard2(defaultKittyFlags)),kittyEnabled=!0,kittyFlags=defaultKittyFlags;if(mouseOption)stdout.write(enableMouse2()),mouseEnabled=!0}if(_ansiTrace)__require("node:fs").appendFileSync("/tmp/silvery-trace.log",`=== RUNTIME.RENDER (initial) ===
116
+ `);if(alternateScreen)stdout.write("\x1B[?1049h"),stdout.write("\x1B[2J\x1B[H");if(stdout.write("\x1B[?25l"),kittyOption!=null&&kittyOption!==!1)if(kittyOption===!0){if((await detectKittyFromStdio(stdout,stdin)).supported)stdout.write(enableKittyKeyboard2(defaultKittyFlags)),kittyEnabled=!0,kittyFlags=defaultKittyFlags}else stdout.write(enableKittyKeyboard2(kittyOption)),kittyEnabled=!0,kittyFlags=kittyOption;else if(kittyOption==null)stdout.write(enableKittyKeyboard2(defaultKittyFlags)),kittyEnabled=!0,kittyFlags=defaultKittyFlags;if(mouseOption)stdout.write(enableMouse2()),mouseEnabled=!0}if(_ansiTrace)__require("node:fs").appendFileSync("/tmp/silvery-trace.log",`=== RUNTIME.RENDER (initial) ===
112
117
  `);if(runtime.render(currentBuffer),_perfLog)__require("node:fs").appendFileSync("/tmp/silvery-perf.log",`STARTUP: initial render done (render #${_renderCount}, incremental=${!_noIncremental})
113
118
  `);if(shouldGuardOutput)outputGuard=createOutputGuard();if(!headless)runtimeContextValue.pause=()=>{if(renderPaused=!0,outputGuard)outputGuard.dispose(),outputGuard=null;if(alternateScreen)stdout.write(leaveAlternateScreen())},runtimeContextValue.resume=()=>{if(alternateScreen)stdout.write(enterAlternateScreen());if(renderPaused=!1,shouldGuardOutput&&!outputGuard)outputGuard=createOutputGuard();if(runtime.invalidate(),_ag?.resetBuffer(),!isRendering)currentBuffer=doRender(),runtime.render(currentBuffer)};let exitResolve,exitResolved=!1,exitPromise=new Promise((resolve)=>{exitResolve=()=>{if(!exitResolved)exitResolved=!0,resolve()}});exit=()=>{if(shouldExit)return;if(shouldExit=!0,!headless&&stdout.isTTY){let earlyDisable=[disableKittyKeyboard2(),disableMouse2(),"\x1B[?1004l"].join("");try{writeSync3(stdout.fd,earlyDisable)}catch{try{stdout.write(earlyDisable)}catch{}}}if(controller.abort(),!inEventHandler)cleanup(),exitResolve()},runtimeContextValue.exit=exit;let frameResolve=null,framesDone=!1;function emitFrame(buf){if(frameResolve){let resolve=frameResolve;frameResolve=null,resolve(buf)}}storeUnsubscribeFn=store.subscribe(()=>{if(shouldExit)return;if(_ansiTrace){let _case=inEventHandler?"1:event":isRendering?"2:rendering":"3:standalone",stack=Error().stack?.split(`
114
119
  `).slice(1,5).join(`
@@ -119,7 +124,7 @@ ${stack}
119
124
  `);isRendering=!0;try{currentBuffer=doRender(),runtime.render(currentBuffer)}finally{isRendering=!1}});function createProviderEventStream(name,provider){return map(provider.events(),(event)=>({type:`${name}:${String(event.type)}`,provider:name,event:String(event.type),data:event.data}))}function writeSelectionOverlay(){if(!selectionEnabled||!selectionState.range||!currentBuffer)return;let mode=alternateScreen?"fullscreen":"inline",overlay=renderSelectionOverlay(selectionState.range,currentBuffer._buffer,mode,selectionState.scope);if(overlay)target.write(overlay)}function pushToScrollback(){if(!scrollback||!currentBuffer)return;let lines=currentBuffer.text.split(`
120
125
  `);scrollback.push(lines)}function renderVirtualScrollbackView(){if(!scrollback||virtualScrollOffset<=0)return;let dims=target.getDims(),rows2=scrollback.getVisibleRows(virtualScrollOffset,dims.rows),out="";for(let row=0;row<rows2.length;row++)out+=`\x1B[${row+1};1H\x1B[2K${rows2[row]??""}`;let indicator=` ↑ ${virtualScrollOffset} lines `,indicatorCol=Math.max(1,dims.cols-indicator.length+1);out+=`\x1B[1;${indicatorCol}H\x1B[7m${indicator}\x1B[27m`,target.write(out)}function renderSearchHighlights(){if(!searchState.active||searchState.currentMatch<0)return;let match=searchState.matches[searchState.currentMatch];if(!match)return;let dims=target.getDims(),screenRow;if(scrollback&&virtualScrollOffset>0){let firstVisibleLine=scrollback.totalLines-virtualScrollOffset-dims.rows;screenRow=match.row-firstVisibleLine}else screenRow=match.row;if(screenRow<0||screenRow>=dims.rows)return;let out=`\x1B[${screenRow+1};${match.startCol+1}H\x1B[7m`;for(let col=match.startCol;col<=match.endCol;col++)if(currentBuffer&&virtualScrollOffset<=0)out+=currentBuffer._buffer.getCell(col,screenRow).char;else out+=searchState.query[col-match.startCol]??" ";out+="\x1B[27m",target.write(out)}function renderSearchBarOverlay(){if(!searchState.active)return;let dims=target.getDims(),bar=renderSearchBar(searchState,dims.cols);target.write(`\x1B[${dims.rows};1H${bar}`)}function searchScrollback(query){if(!scrollback||!query)return[];let matchingLines=scrollback.search(query),lowerQuery=query.toLowerCase(),matches=[];for(let lineIdx of matchingLines){let plain=(scrollback.getVisibleRows(scrollback.totalLines-lineIdx-1,1)[0]??"").replace(/\x1b\[[0-9;]*[a-zA-Z]/g,""),col=plain.toLowerCase().indexOf(lowerQuery);while(col!==-1)matches.push({row:lineIdx,startCol:col,endCol:col+query.length-1}),col=plain.toLowerCase().indexOf(lowerQuery,col+1)}return matches}function runEventHandler(event){if(scrollback&&searchState.active&&event.type==="term:key"){let data=event.data;if(data.key.escape){let[next]=searchUpdate({type:"close"},searchState);return searchState=next,virtualScrollOffset=0,!0}if(data.key.return&&!data.key.shift){let[next,effects]=searchUpdate({type:"nextMatch"},searchState,searchScrollback);searchState=next;for(let eff of effects)if(eff.type==="scrollTo")virtualScrollOffset=Math.max(0,scrollback.totalLines-eff.row-target.getDims().rows);return!0}if(data.key.return&&data.key.shift){let[next,effects]=searchUpdate({type:"prevMatch"},searchState,searchScrollback);searchState=next;for(let eff of effects)if(eff.type==="scrollTo")virtualScrollOffset=Math.max(0,scrollback.totalLines-eff.row-target.getDims().rows);return!0}if(data.key.backspace){let[next,effects]=searchUpdate({type:"backspace"},searchState,searchScrollback);searchState=next;for(let eff of effects)if(eff.type==="scrollTo")virtualScrollOffset=Math.max(0,scrollback.totalLines-eff.row-target.getDims().rows);return!0}if(data.key.leftArrow){let[next]=searchUpdate({type:"cursorLeft"},searchState);return searchState=next,!0}if(data.key.rightArrow){let[next]=searchUpdate({type:"cursorRight"},searchState);return searchState=next,!0}if(data.input&&!data.key.ctrl&&!data.key.meta){let[next,effects]=searchUpdate({type:"input",char:data.input},searchState,searchScrollback);searchState=next;for(let eff of effects)if(eff.type==="scrollTo")virtualScrollOffset=Math.max(0,scrollback.totalLines-eff.row-target.getDims().rows);return!0}}if(scrollback&&event.type==="term:key"){let data=event.data;if(data.input==="f"&&data.key.ctrl){let[next]=searchUpdate({type:"open"},searchState);return searchState=next,!0}}if(scrollback&&event.event==="mouse"&&event.data){let mouseData=event.data;if(mouseData.action==="wheel"){if(mouseData.delta&&mouseData.delta<0)virtualScrollOffset=Math.min(virtualScrollOffset+3,Math.max(0,scrollback.totalLines-target.getDims().rows));else virtualScrollOffset=Math.max(0,virtualScrollOffset-3);return!0}}if(selectionEnabled&&event.event==="mouse"&&event.data){let mouseData=event.data;if(mouseData.button===0){if(mouseData.action==="down"){if(selectionState.range){let[cleared]=terminalSelectionUpdate({type:"clear"},selectionState);selectionState=cleared}let agRoot=getContainerRoot(container),hit=agRoot?selectionHitTest(agRoot,mouseData.x,mouseData.y):null,scope=hit?findContainBoundary(hit):null,[next]=terminalSelectionUpdate({type:"start",col:mouseData.x,row:mouseData.y,scope},selectionState);if(selectionState=next,notifySelectionListeners(),currentBuffer)runtime.invalidate(),currentBuffer=doRender(),runtime.render(currentBuffer),writeSelectionOverlay()}else if(mouseData.action==="move"&&selectionState.selecting){let[next]=terminalSelectionUpdate({type:"extend",col:mouseData.x,row:mouseData.y},selectionState);if(selectionState=next,notifySelectionListeners(),currentBuffer)runtime.render(currentBuffer),writeSelectionOverlay();return!0}else if(mouseData.action==="up"&&selectionState.selecting){let[next]=terminalSelectionUpdate({type:"finish"},selectionState);if(selectionState=next,notifySelectionListeners(),next.range&&currentBuffer){let text=extractText(currentBuffer._buffer,next.range,{scope:next.scope});if(text.length>0){let base64=globalThis.Buffer.from(text).toString("base64");target.write(`\x1B]52;c;${base64}\x07`)}}if(currentBuffer)runtime.render(currentBuffer),writeSelectionOverlay()}}}if(selectionEnabled&&event.type==="term:key"&&selectionState.range){let[next]=terminalSelectionUpdate({type:"clear"},selectionState);if(selectionState=next,notifySelectionListeners(),currentBuffer)runtime.invalidate(),currentBuffer=doRender(),runtime.render(currentBuffer)}if(scrollback&&virtualScrollOffset>0&&event.type==="term:key")return virtualScrollOffset=0,!0;let ctx=createHandlerContext(store,focusManager,container);return invokeEventHandler(event,handlers,ctx,mouseEventState,container)}async function processEventBatch(events){let __stack=[];try{if(shouldExit||events.length===0)return null;_renderCount=0;_eventStart=performance.now();const _perfSpan=__using(__stack,perfLog.span?.("keypress",(()=>{startTracking();let keyEvents=events.filter((e)=>e.type==="term:key");return{key:keyEvents.length>0?keyEvents.map((e)=>e.data.input).join(","):events[0]?.type??"unknown"}})()),0);if(!headless){for(let i=events.length-1;i>=0;i--){let event=events[i];if(event.type!=="term:key")continue;let data=event.data;if(data.input==="z"&&data.key.ctrl&&suspendOption)if(onSuspendHook?.()!==!1){events.splice(i,1);let state=captureTerminalState({alternateScreen,cursorHidden:!0,mouse:mouseEnabled,kitty:kittyEnabled,kittyFlags,bracketedPaste:!0,rawMode:!0,focusReporting:focusReportingEnabled});performSuspend(state,stdout,stdin,()=>{runtime.invalidate(),onResumeHook?.()})}else events.splice(i,1);if(data.input==="c"&&data.key.ctrl&&exitOnCtrlCOption){if(onInterruptHook?.()!==!1)return exit(),null;events.splice(i,1)}}if(events.length===0)return null}inEventHandler=!0;isRendering=!0;for(let event of events){if(event.type==="term:key"){let{input,key:parsedKey}=event.data;updateKeyboardModifiers(mouseEventState,parsedKey);for(let listener of runtimeInputListeners)listener(input,parsedKey)}else if(event.type==="term:paste"){let{text}=event.data;for(let listener of runtimePasteListeners)listener(text)}else if(event.type==="term:focus"){let{focused}=event.data;for(let listener of runtimeFocusListeners)listener(focused)}if(shouldExit)return inEventHandler=!1,null;if(event.type==="term:key"){let{input,key:k}=event.data;if(k.eventType==="release")continue;if(input===""&&!k.upArrow&&!k.downArrow&&!k.leftArrow&&!k.rightArrow&&!k.pageDown&&!k.pageUp&&!k.home&&!k.end&&!k.return&&!k.escape&&!k.tab&&!k.backspace&&!k.delete)continue}let result=runEventHandler(event);if(result===!1)return isRendering=!1,inEventHandler=!1,exit(),null;if(result==="flush"){if(pendingRerender=!1,currentBuffer=doRender(),runtime.render(currentBuffer),await Promise.resolve(),pendingRerender)pendingRerender=!1,currentBuffer=doRender(),runtime.render(currentBuffer)}}pendingRerender=!1;try{currentBuffer=doRender()}finally{isRendering=!1}let flushCount=0;let maxFlushes=5;while(flushCount<maxFlushes){if(await Promise.resolve(),!pendingRerender)break;pendingRerender=!1,isRendering=!0;try{currentBuffer=doRender()}finally{isRendering=!1}flushCount++}currentBuffer._buffer.markAllRowsDirty();inEventHandler=!1;let runtimeStart=performance.now();runtime.render(currentBuffer);pushToScrollback();if(virtualScrollOffset>0)renderVirtualScrollbackView();writeSelectionOverlay();renderSearchHighlights();renderSearchBarOverlay();let runtimeMs=performance.now()-runtimeStart;if(_perfLog){let totalMs=performance.now()-_eventStart;__require("node:fs").appendFileSync("/tmp/silvery-perf.log",`EVENT batch(${events.length} ${events[0]?.type}): ${totalMs.toFixed(1)}ms total, ${_renderCount} doRender() calls, runtime.render=${runtimeMs.toFixed(1)}ms
121
126
  ---
122
- `)}if(_perfSpan)checkBudget(events[0]?.type??"batch",performance.now()-_eventStart);return currentBuffer}catch(_catch){var _err=_catch,_hasErr=1}finally{__callDispose(__stack,_err,_hasErr)}}let eventQueue=[],eventQueueResolve=null;return(async()=>{let providerEventStreams=Object.entries(providers).map(([name,provider])=>createProviderEventStream(name,provider)),allEvents=merge(...providerEventStreams),pumpEvents=async()=>{try{for await(let event of takeUntil(allEvents,signal2)){if(eventQueue.push(event),eventQueueResolve){let resolve=eventQueueResolve;eventQueueResolve=null,resolve()}if(shouldExit)break}}finally{if(eventQueueResolve){let resolve=eventQueueResolve;eventQueueResolve=null,resolve()}}};if(needsProbe)try{let wasRaw=stdin.isRaw;if(stdin.isTTY&&!wasRaw)stdin.setRawMode(!0),stdin.resume(),stdin.setEncoding("utf8");let probeResult=await detectTextSizingSupport((data)=>outputGuard?outputGuard.writeStdout(data):stdout.write(data),()=>new Promise((resolve)=>{let onData=(data)=>{stdin.off("data",onData),resolve(data)};stdin.on("data",onData)}),500);if(probeResult.supported!==textSizingEnabled){if(textSizingEnabled=probeResult.supported,effectiveCaps)effectiveCaps={...effectiveCaps,textSizingSupported:textSizingEnabled},pipelineConfig=createPipeline({caps:effectiveCaps}),runtime.setOutputPhaseFn(pipelineConfig.outputPhaseFn);if(_ag=null,runtime.invalidate(),!isRendering){isRendering=!0;try{currentBuffer=doRender(),runtime.render(currentBuffer)}finally{isRendering=!1}}}if(stdin.isTTY&&!wasRaw)stdin.setRawMode(!1),stdin.pause()}catch{}if(needsWidthDetection)try{let wasRaw=stdin.isRaw;if(stdin.isTTY&&!wasRaw)stdin.setRawMode(!0),stdin.resume(),stdin.setEncoding("utf8");let stdinHandlers=[],stdinListener=(data)=>{for(let handler of stdinHandlers)handler(data)};stdin.on("data",stdinListener);let detector=createWidthDetector({write:(data)=>outputGuard?outputGuard.writeStdout(data):stdout.write(data),onData:(handler)=>{return stdinHandlers.push(handler),()=>{let idx=stdinHandlers.indexOf(handler);if(idx>=0)stdinHandlers.splice(idx,1)}},timeoutMs:200}),widthConfig=await detector.detect();if(detector.dispose(),stdin.off("data",stdinListener),effectiveCaps){let updatedCaps=applyWidthConfig(effectiveCaps,widthConfig);if(updatedCaps.textEmojiWide!==effectiveCaps.textEmojiWide||updatedCaps.textSizingSupported!==effectiveCaps.textSizingSupported){if(effectiveCaps=updatedCaps,pipelineConfig=createPipeline({caps:effectiveCaps}),runtime.setOutputPhaseFn(pipelineConfig.outputPhaseFn),_ag=null,runtime.invalidate(),!isRendering){isRendering=!0;try{currentBuffer=doRender(),runtime.render(currentBuffer)}finally{isRendering=!1}}}}if(stdin.isTTY&&!wasRaw)stdin.setRawMode(!1),stdin.pause()}catch{}if(pumpEvents().catch((err)=>log10.error?.(`pumpEvents failed: ${err}`)),focusReportingOption&&!focusReportingEnabled)enableFocusReporting((s)=>outputGuard?outputGuard.writeStdout(s):stdout.write(s)),focusReportingEnabled=!0;try{while(!shouldExit&&!signal2.aborted){if(eventQueue.length===0)await new Promise((resolve)=>{eventQueueResolve=resolve,signal2.addEventListener("abort",()=>resolve(),{once:!0})});if(shouldExit||signal2.aborted)break;if(eventQueue.length===0)continue;let maxDrainSpins=32,drainSpins=0,yieldToEventLoop=()=>new Promise((resolve)=>setImmediate(resolve));await yieldToEventLoop();let prevLen=eventQueue.length;while(drainSpins<maxDrainSpins){await yieldToEventLoop();let curLen=eventQueue.length;if(curLen===prevLen)break;prevLen=curLen,drainSpins++}if(_perfLog)__require("node:fs").appendFileSync("/tmp/silvery-perf.log",`DRAIN: spins=${drainSpins}, batch=${eventQueue.length}
123
- `);let _g=globalThis;_g.__silvery_last_drain_spins=drainSpins,_g.__silvery_last_batch_size=eventQueue.length,_g.__silvery_batch_count=(_g.__silvery_batch_count??0)+1;let buf=await processEventBatch(eventQueue.splice(0));if(buf)emitFrame(buf)}}finally{if(framesDone=!0,frameResolve){let resolve=frameResolve;frameResolve=null,resolve(null)}if(shouldExit&&!cleanedUp&&!headless&&stdin.isTTY)try{stdin.removeAllListeners("data"),stdin.resume(),await new Promise((resolve)=>setTimeout(resolve,15));while(stdin.read()!==null);stdin.pause()}catch{}cleanup(),exitResolve()}})().catch((err)=>log10.error?.(`eventLoop failed: ${err}`)),{get text(){return currentBuffer.text},get root(){return getContainerRoot(container)},get buffer(){return currentBuffer?._buffer??null},get store(){return store},waitUntilExit(){return exitPromise},unmount(){exit()},[Symbol.dispose](){exit()},async press(rawKey){let __stack=[];try{let pressStart=performance.now();let ansiKey=useKittyMode?keyToKittyAnsi(rawKey):keyToAnsi(rawKey);let[input,parsedKey]=parseKey(ansiKey);const _perfSpan=__using(__stack,perfLog.span?.("keypress",(()=>{return startTracking(),{key:input||rawKey}})()),0);if(input==="c"&&parsedKey.ctrl&&exitOnCtrlCOption){if(onInterruptHook?.()!==!1){exit();return}}for(let listener of runtimeInputListeners)listener(input,parsedKey);inEventHandler=!0;isRendering=!0;let focusResult=handleFocusNavigation(input,parsedKey,focusManager,container);if(focusResult==="consumed"){if(pendingRerender=!1,isRendering=!1,inEventHandler=!1,doRender(),await Promise.resolve(),_perfSpan)checkBudget(input||rawKey,performance.now()-pressStart);return}let handlerCtx=createHandlerContext(store,focusManager,container);if(dispatchKeyToHandlers(input,parsedKey,handlers,handlerCtx)==="exit"){isRendering=!1,inEventHandler=!1,exit();return}pendingRerender=!1;try{currentBuffer=doRender()}finally{isRendering=!1}let flushCount=0;let maxFlushes=5;while(flushCount<maxFlushes){if(await Promise.resolve(),!pendingRerender)break;pendingRerender=!1,isRendering=!0;try{currentBuffer=doRender()}finally{isRendering=!1}flushCount++}inEventHandler=!1;runtime.render(currentBuffer);if(_perfSpan)checkBudget(input||rawKey,performance.now()-pressStart)}catch(_catch){var _err=_catch,_hasErr=1}finally{__callDispose(__stack,_err,_hasErr)}},[Symbol.asyncIterator](){return{async next(){if(framesDone||shouldExit)return{done:!0,value:void 0};let buf=await new Promise((resolve)=>{if(framesDone||shouldExit){resolve(null);return}frameResolve=resolve});if(!buf)return{done:!0,value:void 0};return{done:!1,value:buf}},async return(){return exit(),{done:!0,value:void 0}}}}}}init_derive2();init_src2();init_nord();init_catppuccin();async function detectTheme2(opts={}){let colorLevel=opts.caps?.colorLevel;if(colorLevel==="none"||colorLevel==="basic")return opts.caps?.darkBackground??!0?ansi16DarkTheme:ansi16LightTheme;let detected=await detectTerminalPalette(opts.timeoutMs),isDark=detected?.dark??opts.caps?.darkBackground??!0,fallback=opts.fallback??(isDark?nord:catppuccinLatte);if(!detected)return deriveTheme(fallback);let merged={...fallback,...stripNulls(detected.palette)};return deriveTheme(merged)}function stripNulls(partial){let result={};for(let[k,v]of Object.entries(partial))if(v!=null)result[k]=v;return result}init_state();init_palettes();import React6,{createContext as createContext5,useContext as useContext4}from"react";var ThemeContext=createContext5(defaultDarkTheme);function ThemeProvider({theme,children}){return setActiveTheme(theme),React6.createElement(ThemeContext.Provider,{value:theme},children)}import{jsxDEV as jsxDEV2}from"react/jsx-dev-runtime";function useInput(handler){let rt=useContext5(RuntimeContext),handlerRef=useRef4(handler);handlerRef.current=handler,useEffect3(()=>{if(!rt)return;return rt.on("input",(input,key)=>{if(handlerRef.current(input,key)==="exit")rt.exit()})},[rt])}function useExit(){let rt=useContext5(RuntimeContext);if(!rt)throw Error("useExit must be used within run() or createApp()");return rt.exit}function usePaste(handler){let rt=useContext5(RuntimeContext),handlerRef=useRef4(handler);handlerRef.current=handler,useEffect3(()=>{if(!rt)return;return rt.on("paste",(text)=>{handlerRef.current(text)})},[rt])}async function run2(element,optionsOrTerm={},termOptions){if(isTerm2(optionsOrTerm)){let term2=optionsOrTerm;if(term2._emulator){let{EventEmitter}=await import("node:events"),stdinEmitter=new EventEmitter,mockStdin=Object.assign(stdinEmitter,{isTTY:!0,isRaw:!1,fd:0,setRawMode(_mode){return mockStdin.isRaw=_mode,mockStdin},read(){return null},resume(){return mockStdin},pause(){return mockStdin},ref(){return mockStdin},unref(){return mockStdin},setEncoding(){return mockStdin}});if(term2.sendInput)term2.sendInput=(data)=>{stdinEmitter.emit("data",data)};let altScreen=termOptions?.mode==="inline"?!1:!0,handle3=await createApp(()=>()=>({})).run(element,{alternateScreen:altScreen,...termOptions,stdin:mockStdin,stdout:term2.stdout,guardOutput:!1,cols:term2.cols??80,rows:term2.rows??24});return wrapHandle(handle3)}let caps2=term2.caps??detectTerminalCaps(),theme=await detectTheme2(),themed2=jsxDEV2(ThemeProvider,{theme,children:element},void 0,!1,void 0,this),handle2=await createApp(()=>()=>({})).run(themed2,{term:term2,stdout:term2.stdout,stdin:term2.stdin,cols:term2.cols??void 0,rows:term2.rows??void 0,caps:caps2,alternateScreen:!0,kitty:caps2.kittyKeyboard,mouse:!0,focusReporting:!0,textSizing:"auto",widthDetection:"auto"});return wrapHandle(handle2)}let{mode,...rest}=optionsOrTerm,caps=rest.caps??detectTerminalCaps(),themed=rest.writable!=null||rest.cols!=null&&rest.rows!=null&&!rest.stdout?element:await detectTheme2().then((theme)=>jsxDEV2(ThemeProvider,{theme,children:element},void 0,!1,void 0,this)),handle=await createApp(()=>()=>({})).run(themed,{...rest,caps,alternateScreen:mode!=="inline",virtualInline:mode==="virtualInline",kitty:rest.kitty??caps.kittyKeyboard,mouse:rest.mouse??mode!=="inline",focusReporting:rest.focusReporting??mode!=="inline",textSizing:rest.textSizing??"auto",widthDetection:rest.widthDetection??"auto"});return wrapHandle(handle)}function isTerm2(obj){if(obj==null)return!1;if(typeof obj!=="object"&&typeof obj!=="function")return!1;let o=obj;return typeof o.getState==="function"&&typeof o.events==="function"}function wrapHandle(handle){return{get text(){return handle.text},get root(){return handle.root},get buffer(){return handle.buffer},waitUntilExit:()=>handle.waitUntilExit(),unmount:()=>handle.unmount(),[Symbol.dispose]:()=>handle[Symbol.dispose](),press:(key)=>handle.press(key)}}init_keys2();var none={type:"none"};function withFocusManagement(){return(innerUpdate)=>(msg,model)=>{switch(msg.type){case"focus":{let focusMsg=msg;return[{...model,focus:{...model.focus,previousId:model.focus.activeId,activeId:focusMsg.nodeId,origin:focusMsg.origin??"programmatic",scopeMemory:model.focus.scopeStack.length>0?{...model.focus.scopeMemory,[model.focus.scopeStack[model.focus.scopeStack.length-1]]:focusMsg.nodeId}:model.focus.scopeMemory}},[none]]}case"blur":return[{...model,focus:{...model.focus,previousId:model.focus.activeId,activeId:null,origin:null}},[none]];case"scope-enter":{let scopeMsg=msg;return[{...model,focus:{...model.focus,scopeStack:[...model.focus.scopeStack,scopeMsg.scopeId]}},[none]]}case"scope-exit":return[{...model,focus:{...model.focus,scopeStack:model.focus.scopeStack.slice(0,-1)}},[none]];default:return innerUpdate(msg,model)}}}function silveryUpdate(_msg,model){return[model,[none]]}function defaultInit(){return[{focus:{activeId:null,previousId:null,origin:null,scopeStack:[],scopeMemory:{}}},[none]]}function createStore2(config){let[initialModel,initialEffects]=config.init(),model=initialModel,listeners=new Set;function notify2(){for(let listener of listeners)listener()}let isDispatching=!1,dispatchQueue=[];function executeEffects(effects){for(let effect of effects)executeEffect(effect)}function executeEffect(effect){switch(effect.type){case"none":break;case"batch":executeEffects(effect.effects);break;case"dispatch":dispatchQueue.push(effect.msg);break}}function dispatch(msg){if(isDispatching){dispatchQueue.push(msg);return}isDispatching=!0;try{let[newModel,effects]=config.update(msg,model),changed=newModel!==model;if(model=newModel,executeEffects(effects),changed)notify2();while(dispatchQueue.length>0){let queued2=dispatchQueue.shift(),[nextModel,nextEffects]=config.update(queued2,model),nextChanged=nextModel!==model;if(model=nextModel,executeEffects(nextEffects),nextChanged)notify2()}}finally{isDispatching=!1}}function getModel(){return model}function subscribe(listener){return listeners.add(listener),()=>{listeners.delete(listener)}}function getSnapshot(selector){return selector(model)}executeEffects(initialEffects);while(dispatchQueue.length>0){let queued2=dispatchQueue.shift(),[nextModel,nextEffects]=config.update(queued2,model);model=nextModel,executeEffects(nextEffects)}return{dispatch,getModel,subscribe,getSnapshot}}function createTick(intervalMs,signal2){return{[Symbol.asyncIterator]:()=>createTickIterator(intervalMs,signal2)}}function createTickIterator(intervalMs,signal2){let count=0,timer,pendingResolve,done=!1,onAbort=()=>{if(done=!0,timer)clearTimeout(timer),timer=void 0;if(pendingResolve)pendingResolve({done:!0,value:void 0}),pendingResolve=void 0};if(signal2)if(signal2.aborted)done=!0;else signal2.addEventListener("abort",onAbort,{once:!0});return{async next(){if(done)return{done:!0,value:void 0};return new Promise((resolve,_reject)=>{pendingResolve=resolve,timer=setTimeout(()=>{if(!done){let value=count++;pendingResolve=void 0,resolve({done:!1,value})}},intervalMs)})},async return(){if(done=!0,timer)clearTimeout(timer),timer=void 0;if(signal2)signal2.removeEventListener("abort",onAbort);if(pendingResolve)pendingResolve({done:!0,value:void 0}),pendingResolve=void 0;return{done:!0,value:void 0}}}}function createFrameTick(signal2){return createTick(16,signal2)}function createSecondTick(signal2){return createTick(1000,signal2)}function createAdaptiveTick(targetFps=60,signal2){let targetMs=1000/targetFps,lastTime=Date.now(),tick=0;return{[Symbol.asyncIterator]:()=>{let done=!1,timer,pendingResolve,onAbort=()=>{if(done=!0,timer)clearTimeout(timer),timer=void 0;if(pendingResolve)pendingResolve({done:!0,value:void 0}),pendingResolve=void 0};if(signal2)if(signal2.aborted)done=!0;else signal2.addEventListener("abort",onAbort,{once:!0});return{async next(){if(done)return{done:!0,value:void 0};return new Promise((resolve)=>{pendingResolve=resolve;let elapsed=Date.now()-lastTime,delay=Math.max(0,targetMs-elapsed);timer=setTimeout(()=>{if(!done){let currentTime=Date.now(),delta=currentTime-lastTime;lastTime=currentTime,pendingResolve=void 0,resolve({done:!1,value:{tick:tick++,elapsed:currentTime,delta}})}},delay)})},async return(){if(done=!0,timer)clearTimeout(timer),timer=void 0;if(signal2)signal2.removeEventListener("abort",onAbort);if(pendingResolve)pendingResolve({done:!0,value:void 0}),pendingResolve=void 0;return{done:!0,value:void 0}}}}}}export{zip,withFocusManagement,usePaste,useInput,useExit,useAppShallow,useApp,throttle,takeUntil,take,silveryUpdate,run2 as run,resumeTerminalState,restoreTerminalState,render,performSuspend,parseKey,merge,map,layoutSync,layout,fromArrayWithDelay,fromArray,filterMap,filter,ensureLayoutEngine,emptyKey,diff,defaultInit,debounce,createTick,createTermProvider,createStore2 as createStore,createSecondTick,createRuntime,createFrameTick,createBuffer2 as createBuffer,createApp,createAdaptiveTick,concat,captureTerminalState,batch,StoreContext,CTRL_Z,CTRL_C};
127
+ `)}if(_perfSpan)checkBudget(events[0]?.type??"batch",performance.now()-_eventStart);return currentBuffer}catch(_catch){var _err=_catch,_hasErr=1}finally{__callDispose(__stack,_err,_hasErr)}}let eventQueue=[],eventQueueResolve=null;return(async()=>{let providerEventStreams=Object.entries(providers).map(([name,provider])=>createProviderEventStream(name,provider)),allEvents=merge(...providerEventStreams),pumpEvents=async()=>{try{for await(let event of takeUntil(allEvents,signal2)){if(eventQueue.push(event),eventQueueResolve){let resolve=eventQueueResolve;eventQueueResolve=null,resolve()}if(shouldExit)break}}finally{if(eventQueueResolve){let resolve=eventQueueResolve;eventQueueResolve=null,resolve()}}};if(needsProbe)try{let wasRaw=stdin.isRaw;if(stdin.isTTY&&!wasRaw)stdin.setRawMode(!0),stdin.resume(),stdin.setEncoding("utf8");let probeResult=await detectTextSizingSupport((data)=>outputGuard?outputGuard.writeStdout(data):stdout.write(data),()=>new Promise((resolve)=>{let onData=(data)=>{stdin.off("data",onData),resolve(data)};stdin.on("data",onData)}),500);if(probeResult.supported!==textSizingEnabled){if(textSizingEnabled=probeResult.supported,effectiveCaps)effectiveCaps={...effectiveCaps,textSizingSupported:textSizingEnabled},pipelineConfig=createPipeline({caps:effectiveCaps}),runtime.setOutputPhaseFn(pipelineConfig.outputPhaseFn);if(_ag=null,runtime.invalidate(),!isRendering){isRendering=!0;try{currentBuffer=doRender(),runtime.render(currentBuffer)}finally{isRendering=!1}}}if(stdin.isTTY&&!wasRaw)stdin.setRawMode(!1),stdin.pause()}catch{}if(needsWidthDetection)try{let wasRaw=stdin.isRaw;if(stdin.isTTY&&!wasRaw)stdin.setRawMode(!0),stdin.resume(),stdin.setEncoding("utf8");let stdinHandlers=[],stdinListener=(data)=>{for(let handler of stdinHandlers)handler(data)};stdin.on("data",stdinListener);let detector=createWidthDetector({write:(data)=>outputGuard?outputGuard.writeStdout(data):stdout.write(data),onData:(handler)=>{return stdinHandlers.push(handler),()=>{let idx=stdinHandlers.indexOf(handler);if(idx>=0)stdinHandlers.splice(idx,1)}},timeoutMs:200}),widthConfig=await detector.detect();if(detector.dispose(),stdin.off("data",stdinListener),effectiveCaps){let updatedCaps=applyWidthConfig(effectiveCaps,widthConfig);if(updatedCaps.textEmojiWide!==effectiveCaps.textEmojiWide||updatedCaps.textSizingSupported!==effectiveCaps.textSizingSupported){if(effectiveCaps=updatedCaps,pipelineConfig=createPipeline({caps:effectiveCaps}),runtime.setOutputPhaseFn(pipelineConfig.outputPhaseFn),_ag=null,runtime.invalidate(),!isRendering){isRendering=!0;try{currentBuffer=doRender(),runtime.render(currentBuffer)}finally{isRendering=!1}}}}if(stdin.isTTY&&!wasRaw)stdin.setRawMode(!1),stdin.pause()}catch{}if(pumpEvents().catch((err)=>log11.error?.(`pumpEvents failed: ${err}`)),focusReportingOption&&!focusReportingEnabled)enableFocusReporting((s)=>outputGuard?outputGuard.writeStdout(s):stdout.write(s)),focusReportingEnabled=!0;try{while(!shouldExit&&!signal2.aborted){if(eventQueue.length===0)await new Promise((resolve)=>{eventQueueResolve=resolve,signal2.addEventListener("abort",()=>resolve(),{once:!0})});if(shouldExit||signal2.aborted)break;if(eventQueue.length===0)continue;let maxDrainSpins=32,drainSpins=0,yieldToEventLoop=()=>new Promise((resolve)=>setImmediate(resolve));await yieldToEventLoop();let prevLen=eventQueue.length;while(drainSpins<maxDrainSpins){await yieldToEventLoop();let curLen=eventQueue.length;if(curLen===prevLen)break;prevLen=curLen,drainSpins++}if(_perfLog)__require("node:fs").appendFileSync("/tmp/silvery-perf.log",`DRAIN: spins=${drainSpins}, batch=${eventQueue.length}
128
+ `);let _g=globalThis;_g.__silvery_last_drain_spins=drainSpins,_g.__silvery_last_batch_size=eventQueue.length,_g.__silvery_batch_count=(_g.__silvery_batch_count??0)+1;let buf=await processEventBatch(eventQueue.splice(0));if(buf)emitFrame(buf)}}finally{if(framesDone=!0,frameResolve){let resolve=frameResolve;frameResolve=null,resolve(null)}if(shouldExit&&!cleanedUp&&!headless&&stdin.isTTY)try{stdin.removeAllListeners("data"),stdin.resume(),await new Promise((resolve)=>setTimeout(resolve,15));while(stdin.read()!==null);stdin.pause()}catch{}cleanup(),exitResolve()}})().catch((err)=>log11.error?.(`eventLoop failed: ${err}`)),{get text(){return currentBuffer.text},get root(){return getContainerRoot(container)},get buffer(){return currentBuffer?._buffer??null},get store(){return store},waitUntilExit(){return exitPromise},unmount(){exit()},[Symbol.dispose](){exit()},async press(rawKey){let __stack=[];try{let pressStart=performance.now();let ansiKey=useKittyMode?keyToKittyAnsi(rawKey):keyToAnsi(rawKey);let[input,parsedKey]=parseKey(ansiKey);const _perfSpan=__using(__stack,perfLog.span?.("keypress",(()=>{return startTracking(),{key:input||rawKey}})()),0);if(input==="c"&&parsedKey.ctrl&&exitOnCtrlCOption){if(onInterruptHook?.()!==!1){exit();return}}for(let listener of runtimeInputListeners)listener(input,parsedKey);inEventHandler=!0;isRendering=!0;let focusResult=handleFocusNavigation(input,parsedKey,focusManager,container);if(focusResult==="consumed"){if(pendingRerender=!1,isRendering=!1,inEventHandler=!1,doRender(),await Promise.resolve(),_perfSpan)checkBudget(input||rawKey,performance.now()-pressStart);return}let handlerCtx=createHandlerContext(store,focusManager,container);if(dispatchKeyToHandlers(input,parsedKey,handlers,handlerCtx)==="exit"){isRendering=!1,inEventHandler=!1,exit();return}pendingRerender=!1;try{currentBuffer=doRender()}finally{isRendering=!1}let flushCount=0;let maxFlushes=5;while(flushCount<maxFlushes){if(await Promise.resolve(),!pendingRerender)break;pendingRerender=!1,isRendering=!0;try{currentBuffer=doRender()}finally{isRendering=!1}flushCount++}inEventHandler=!1;runtime.render(currentBuffer);if(_perfSpan)checkBudget(input||rawKey,performance.now()-pressStart)}catch(_catch){var _err=_catch,_hasErr=1}finally{__callDispose(__stack,_err,_hasErr)}},[Symbol.asyncIterator](){return{async next(){if(framesDone||shouldExit)return{done:!0,value:void 0};let buf=await new Promise((resolve)=>{if(framesDone||shouldExit){resolve(null);return}frameResolve=resolve});if(!buf)return{done:!0,value:void 0};return{done:!1,value:buf}},async return(){return exit(),{done:!0,value:void 0}}}}}}init_derive2();init_src2();init_nord();init_catppuccin();async function detectTheme2(opts={}){let colorLevel=opts.caps?.colorLevel;if(colorLevel==="none"||colorLevel==="basic")return opts.caps?.darkBackground??!0?ansi16DarkTheme:ansi16LightTheme;let detected=await detectTerminalPalette(opts.timeoutMs),isDark=detected?.dark??opts.caps?.darkBackground??!0,fallback=opts.fallback??(isDark?nord:catppuccinLatte);if(!detected)return deriveTheme(fallback);let merged={...fallback,...stripNulls(detected.palette)};return deriveTheme(merged)}function stripNulls(partial){let result={};for(let[k,v]of Object.entries(partial))if(v!=null)result[k]=v;return result}init_state();init_palettes();import React6,{createContext as createContext5,useContext as useContext4}from"react";var ThemeContext=createContext5(defaultDarkTheme);function ThemeProvider({theme,children}){return setActiveTheme(theme),React6.createElement(ThemeContext.Provider,{value:theme},children)}import{jsxDEV as jsxDEV2}from"react/jsx-dev-runtime";function useInput(handler){let rt=useContext5(RuntimeContext),handlerRef=useRef4(handler);handlerRef.current=handler,useEffect3(()=>{if(!rt)return;return rt.on("input",(input,key)=>{if(handlerRef.current(input,key)==="exit")rt.exit()})},[rt])}function useExit(){let rt=useContext5(RuntimeContext);if(!rt)throw Error("useExit must be used within run() or createApp()");return rt.exit}function usePaste(handler){let rt=useContext5(RuntimeContext),handlerRef=useRef4(handler);handlerRef.current=handler,useEffect3(()=>{if(!rt)return;return rt.on("paste",(text)=>{handlerRef.current(text)})},[rt])}async function run2(element,optionsOrTerm={},termOptions){if(isTerm2(optionsOrTerm)){let term2=optionsOrTerm;if(term2._emulator){let{EventEmitter}=await import("node:events"),stdinEmitter=new EventEmitter,mockStdin=Object.assign(stdinEmitter,{isTTY:!0,isRaw:!1,fd:0,setRawMode(_mode){return mockStdin.isRaw=_mode,mockStdin},read(){return null},resume(){return mockStdin},pause(){return mockStdin},ref(){return mockStdin},unref(){return mockStdin},setEncoding(){return mockStdin}});if(term2.sendInput)term2.sendInput=(data)=>{stdinEmitter.emit("data",data)};let altScreen=termOptions?.mode==="inline"?!1:!0,handle3=await createApp(()=>()=>({})).run(element,{alternateScreen:altScreen,...termOptions,stdin:mockStdin,stdout:term2.stdout,guardOutput:!1,cols:term2.cols??80,rows:term2.rows??24});return wrapHandle(handle3)}let caps2=term2.caps??detectTerminalCaps(),theme=await detectTheme2(),themed2=jsxDEV2(ThemeProvider,{theme,children:element},void 0,!1,void 0,this),handle2=await createApp(()=>()=>({})).run(themed2,{term:term2,stdout:term2.stdout,stdin:term2.stdin,cols:term2.cols??void 0,rows:term2.rows??void 0,caps:caps2,alternateScreen:!0,kitty:caps2.kittyKeyboard,mouse:!0,focusReporting:!0,textSizing:"auto",widthDetection:"auto"});return wrapHandle(handle2)}let{mode,...rest}=optionsOrTerm,caps=rest.caps??detectTerminalCaps(),themed=rest.writable!=null||rest.cols!=null&&rest.rows!=null&&!rest.stdout?element:await detectTheme2().then((theme)=>jsxDEV2(ThemeProvider,{theme,children:element},void 0,!1,void 0,this)),handle=await createApp(()=>()=>({})).run(themed,{...rest,caps,alternateScreen:mode!=="inline",virtualInline:mode==="virtualInline",kitty:rest.kitty??caps.kittyKeyboard,mouse:rest.mouse??mode!=="inline",focusReporting:rest.focusReporting??mode!=="inline",textSizing:rest.textSizing??"auto",widthDetection:rest.widthDetection??"auto"});return wrapHandle(handle)}function isTerm2(obj){if(obj==null)return!1;if(typeof obj!=="object"&&typeof obj!=="function")return!1;let o=obj;return typeof o.getState==="function"&&typeof o.events==="function"}function wrapHandle(handle){return{get text(){return handle.text},get root(){return handle.root},get buffer(){return handle.buffer},waitUntilExit:()=>handle.waitUntilExit(),unmount:()=>handle.unmount(),[Symbol.dispose]:()=>handle[Symbol.dispose](),press:(key)=>handle.press(key)}}init_keys2();var none={type:"none"};function withFocusManagement(){return(innerUpdate)=>(msg,model)=>{switch(msg.type){case"focus":{let focusMsg=msg;return[{...model,focus:{...model.focus,previousId:model.focus.activeId,activeId:focusMsg.nodeId,origin:focusMsg.origin??"programmatic",scopeMemory:model.focus.scopeStack.length>0?{...model.focus.scopeMemory,[model.focus.scopeStack[model.focus.scopeStack.length-1]]:focusMsg.nodeId}:model.focus.scopeMemory}},[none]]}case"blur":return[{...model,focus:{...model.focus,previousId:model.focus.activeId,activeId:null,origin:null}},[none]];case"scope-enter":{let scopeMsg=msg;return[{...model,focus:{...model.focus,scopeStack:[...model.focus.scopeStack,scopeMsg.scopeId]}},[none]]}case"scope-exit":return[{...model,focus:{...model.focus,scopeStack:model.focus.scopeStack.slice(0,-1)}},[none]];default:return innerUpdate(msg,model)}}}function silveryUpdate(_msg,model){return[model,[none]]}function defaultInit(){return[{focus:{activeId:null,previousId:null,origin:null,scopeStack:[],scopeMemory:{}}},[none]]}function createStore2(config){let[initialModel,initialEffects]=config.init(),model=initialModel,listeners=new Set;function notify2(){for(let listener of listeners)listener()}let isDispatching=!1,dispatchQueue=[];function executeEffects(effects){for(let effect2 of effects)executeEffect(effect2)}function executeEffect(effect2){switch(effect2.type){case"none":break;case"batch":executeEffects(effect2.effects);break;case"dispatch":dispatchQueue.push(effect2.msg);break}}function dispatch(msg){if(isDispatching){dispatchQueue.push(msg);return}isDispatching=!0;try{let[newModel,effects]=config.update(msg,model),changed=newModel!==model;if(model=newModel,executeEffects(effects),changed)notify2();while(dispatchQueue.length>0){let queued2=dispatchQueue.shift(),[nextModel,nextEffects]=config.update(queued2,model),nextChanged=nextModel!==model;if(model=nextModel,executeEffects(nextEffects),nextChanged)notify2()}}finally{isDispatching=!1}}function getModel(){return model}function subscribe(listener){return listeners.add(listener),()=>{listeners.delete(listener)}}function getSnapshot(selector){return selector(model)}executeEffects(initialEffects);while(dispatchQueue.length>0){let queued2=dispatchQueue.shift(),[nextModel,nextEffects]=config.update(queued2,model);model=nextModel,executeEffects(nextEffects)}return{dispatch,getModel,subscribe,getSnapshot}}function createTick(intervalMs,signal2){return{[Symbol.asyncIterator]:()=>createTickIterator(intervalMs,signal2)}}function createTickIterator(intervalMs,signal2){let count=0,timer,pendingResolve,done=!1,onAbort=()=>{if(done=!0,timer)clearTimeout(timer),timer=void 0;if(pendingResolve)pendingResolve({done:!0,value:void 0}),pendingResolve=void 0};if(signal2)if(signal2.aborted)done=!0;else signal2.addEventListener("abort",onAbort,{once:!0});return{async next(){if(done)return{done:!0,value:void 0};return new Promise((resolve,_reject)=>{pendingResolve=resolve,timer=setTimeout(()=>{if(!done){let value=count++;pendingResolve=void 0,resolve({done:!1,value})}},intervalMs)})},async return(){if(done=!0,timer)clearTimeout(timer),timer=void 0;if(signal2)signal2.removeEventListener("abort",onAbort);if(pendingResolve)pendingResolve({done:!0,value:void 0}),pendingResolve=void 0;return{done:!0,value:void 0}}}}function createFrameTick(signal2){return createTick(16,signal2)}function createSecondTick(signal2){return createTick(1000,signal2)}function createAdaptiveTick(targetFps=60,signal2){let targetMs=1000/targetFps,lastTime=Date.now(),tick=0;return{[Symbol.asyncIterator]:()=>{let done=!1,timer,pendingResolve,onAbort=()=>{if(done=!0,timer)clearTimeout(timer),timer=void 0;if(pendingResolve)pendingResolve({done:!0,value:void 0}),pendingResolve=void 0};if(signal2)if(signal2.aborted)done=!0;else signal2.addEventListener("abort",onAbort,{once:!0});return{async next(){if(done)return{done:!0,value:void 0};return new Promise((resolve)=>{pendingResolve=resolve;let elapsed=Date.now()-lastTime,delay=Math.max(0,targetMs-elapsed);timer=setTimeout(()=>{if(!done){let currentTime=Date.now(),delta=currentTime-lastTime;lastTime=currentTime,pendingResolve=void 0,resolve({done:!1,value:{tick:tick++,elapsed:currentTime,delta}})}},delay)})},async return(){if(done=!0,timer)clearTimeout(timer),timer=void 0;if(signal2)signal2.removeEventListener("abort",onAbort);if(pendingResolve)pendingResolve({done:!0,value:void 0}),pendingResolve=void 0;return{done:!0,value:void 0}}}}}}export{zip,withFocusManagement,usePaste,useInput,useExit,useAppShallow,useApp,throttle,takeUntil,take,silveryUpdate,run2 as run,resumeTerminalState,restoreTerminalState,render,performSuspend,parseKey,merge,map,layoutSync,layout,fromArrayWithDelay,fromArray,filterMap,filter,ensureLayoutEngine,emptyKey,diff,defaultInit,debounce,createTick,createTermProvider,createStore2 as createStore,createSecondTick,createRuntime,createFrameTick,createBuffer2 as createBuffer,createApp,createAdaptiveTick,concat,captureTerminalState,batch,StoreContext,CTRL_Z,CTRL_C};
124
129
 
125
- //# debugId=10A89E66A00AFB9464756E2164756E21
130
+ //# debugId=A661E68AB61C2D0C64756E2164756E21