silvery 0.16.2 → 0.16.4

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/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{createRequire}from"node:module";var __defProp=Object.defineProperty;var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn,res)=>()=>(fn&&(res=fn(fn=0)),res);var __require=createRequire(import.meta.url),__dispose=Symbol.dispose||Symbol.for("Symbol.dispose"),__asyncDispose=Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose"),__using=(stack,value,async)=>{if(value!=null){if(typeof value!=="object"&&typeof value!=="function")throw TypeError('Object expected to be assigned to "using" declaration');var dispose;if(async)dispose=value[__asyncDispose];if(dispose===void 0)dispose=value[__dispose];if(typeof dispose!=="function")throw TypeError("Object not disposable");stack.push([async,dispose,value])}else if(async)stack.push([async]);return value},__callDispose=(stack,error,hasError)=>{var E=typeof SuppressedError==="function"?SuppressedError:function(e,s,m,_){return _=Error(m),_.name="SuppressedError",_.error=e,_.suppressed=s,_},fail=(e)=>error=hasError?new E(e,error,"An error was suppressed during disposal"):(hasError=!0,e),next=(it)=>{while(it=stack.pop())try{var result=it[1]&&it[1].call(it[2]);if(it[0])return Promise.resolve(result).then(next,(e)=>(fail(e),next()))}catch(e){fail(e)}if(hasError)throw error};return next()};import{createContext}from"react";var TermContext,NodeContext,StdoutContext,StderrContext,RuntimeContext,CacheBackendContext,FocusManagerContext,CapabilityRegistryContext;var init_context=__esm(()=>{TermContext=createContext(null),NodeContext=createContext(null),StdoutContext=createContext(null),StderrContext=createContext(null),RuntimeContext=createContext(null),CacheBackendContext=createContext("virtual"),FocusManagerContext=createContext(null),CapabilityRegistryContext=createContext(null)});import{createLogger}from"loggily";function isModifierOnlyEvent(_input,key){return key.isModifierOnly===!0}function normalizeModifier(mod){return MODIFIER_ALIASES[mod.toLowerCase()]??mod}function keyToAnsi(key){let parts=key.split("+"),mainKey=parts.pop(),modifiers=parts.map(normalizeModifier);if(modifiers.includes("Super")||modifiers.includes("Hyper"))return keyToKittyAnsi(key);if(!modifiers.length&&mainKey.length===1)return mainKey;if(modifiers.includes("Control")&&mainKey.length===1){let code=mainKey.toLowerCase().charCodeAt(0)-96;if(code>=1&&code<=26)return String.fromCharCode(code)}if(modifiers.includes("Control")&&mainKey==="/")return"\x1F";if(modifiers.includes("Control")&&mainKey==="Enter")return`
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames}=Object;var __hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn,res)=>()=>(fn&&(res=fn(fn=0)),res);var __promiseAll=(args)=>Promise.all(args),__require=createRequire(import.meta.url),__dispose=Symbol.dispose||Symbol.for("Symbol.dispose"),__asyncDispose=Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose"),__using=(stack,value,async)=>{if(value!=null){if(typeof value!=="object"&&typeof value!=="function")throw TypeError('Object expected to be assigned to "using" declaration');var dispose;if(async)dispose=value[__asyncDispose];if(dispose===void 0)dispose=value[__dispose];if(typeof dispose!=="function")throw TypeError("Object not disposable");stack.push([async,dispose,value])}else if(async)stack.push([async]);return value},__callDispose=(stack,error,hasError)=>{var E=typeof SuppressedError==="function"?SuppressedError:function(e,s,m,_){return _=Error(m),_.name="SuppressedError",_.error=e,_.suppressed=s,_},fail=(e)=>error=hasError?new E(e,error,"An error was suppressed during disposal"):(hasError=!0,e),next=(it)=>{while(it=stack.pop())try{var result=it[1]&&it[1].call(it[2]);if(it[0])return Promise.resolve(result).then(next,(e)=>(fail(e),next()))}catch(e){fail(e)}if(hasError)throw error};return next()};import{createContext}from"react";var TermContext,NodeContext,StdoutContext,StderrContext,RuntimeContext,CacheBackendContext,FocusManagerContext,CapabilityRegistryContext;var init_context=__esm(()=>{TermContext=createContext(null),NodeContext=createContext(null),StdoutContext=createContext(null),StderrContext=createContext(null),RuntimeContext=createContext(null),CacheBackendContext=createContext("virtual"),FocusManagerContext=createContext(null),CapabilityRegistryContext=createContext(null)});import{createLogger}from"loggily";function isModifierOnlyEvent(_input,key){return key.isModifierOnly===!0}function normalizeModifier(mod){return MODIFIER_ALIASES[mod.toLowerCase()]??mod}function keyToAnsi(key){let parts=key.split("+"),mainKey=parts.pop(),modifiers=parts.map(normalizeModifier);if(modifiers.includes("Super")||modifiers.includes("Hyper"))return keyToKittyAnsi(key);if(!modifiers.length&&mainKey.length===1)return mainKey;if(modifiers.includes("Control")&&mainKey.length===1){let code=mainKey.toLowerCase().charCodeAt(0)-96;if(code>=1&&code<=26)return String.fromCharCode(code)}if(modifiers.includes("Control")&&mainKey==="/")return"\x1F";if(modifiers.includes("Control")&&mainKey==="Enter")return`
2
2
  `;if((modifiers.includes("Alt")||modifiers.includes("Meta"))&&mainKey.length===1)return`\x1B${mainKey}`;if(modifiers.includes("Shift")&&mainKey==="Tab")return"\x1B[Z";if(modifiers.length===1&&modifiers[0]==="Shift"&&mainKey.length===1){if(mainKey>="a"&&mainKey<="z")return mainKey.toUpperCase();let shifted=BASE_TO_SHIFTED_PUNCT[mainKey];if(shifted)return shifted}let ARROW_SUFFIX={ArrowUp:"A",ArrowDown:"B",ArrowRight:"C",ArrowLeft:"D",Home:"H",End:"F"};if(modifiers.length>0&&mainKey in ARROW_SUFFIX){let mod=1;if(modifiers.includes("Shift"))mod+=1;if(modifiers.includes("Alt")||modifiers.includes("Meta"))mod+=2;if(modifiers.includes("Control"))mod+=4;if(modifiers.includes("Super"))mod+=8;if(modifiers.includes("Hyper"))mod+=16;return`\x1B[1;${mod}${ARROW_SUFFIX[mainKey]}`}let base=KEY_MAP[mainKey];if(base!==void 0&&base!==null)return base;return mainKey}function isValidCodepoint(cp){return cp>=0&&cp<=1114111&&!(cp>=55296&&cp<=57343)}function safeFromCodePoint(cp){return isValidCodepoint(cp)?String.fromCodePoint(cp):"?"}function kittyCodepointToName(cp){return KITTY_CODEPOINT_MAP[cp]}function numericToEventType(n){if(n===1)return"press";if(n===2)return"repeat";if(n===3)return"release";return}function parseKeypress(s){let input;if(typeof Buffer<"u"&&Buffer.isBuffer(s))if(s[0]!==void 0&&s[0]>127&&s[1]===void 0){let buf=Buffer.from(s);buf[0]-=128,input=`\x1B${buf.toString()}`}else input=s.toString();else input=typeof s==="string"?s??"":String(s);let key={name:"",ctrl:!1,meta:!1,shift:!1,option:!1,super:!1,hyper:!1,sequence:input};if(input==="\r")key.name="return";else if(input===`
3
3
  `)key.name="return",key.ctrl=!0;else if(input==="\t")key.name="tab";else if(input==="\b"||input==="\x1B\b")key.name="backspace",key.meta=input.charAt(0)==="\x1B";else if(input===""||input==="\x1B")key.name="backspace",key.meta=input.charAt(0)==="\x1B";else if(input==="\x1B\r")key.name="return",key.meta=!0;else if(input==="\x1B"||input==="\x1B\x1B")key.name="escape",key.meta=input.length===2;else if(input===" "||input==="\x1B ")key.name="space",key.meta=input.length===2;else if(input.length===1&&input<="\x1A")key.name=String.fromCharCode(input.charCodeAt(0)+97-1),key.ctrl=!0;else if(input==="\x1F")key.name="/",key.ctrl=!0;else if(input.length===1&&input>="0"&&input<="9")key.name="number";else if(input.length===1&&input>="a"&&input<="z")key.name=input;else if(input.length===1&&input>="A"&&input<="Z")key.name=input.toLowerCase(),key.shift=!0;else{let kittyParts=KITTY_RE.exec(input),kittySpecialParts=!kittyParts&&KITTY_SPECIAL_RE.exec(input),modifyOtherKeysParts=!kittyParts&&!kittySpecialParts&&MODIFY_OTHER_KEYS_RE.exec(input);if(kittySpecialParts){let number=Number(kittySpecialParts[1]),modifier=Math.max(0,Number(kittySpecialParts[2])-1),eventType=Number(kittySpecialParts[3]),terminator=kittySpecialParts[4],name=terminator==="~"?KITTY_SPECIAL_NUMBER_KEYS[number]:KITTY_SPECIAL_LETTER_KEYS[terminator];key.isKittyProtocol=!0,key.isPrintable=!1,key.raw=input,key.name=name??"",key.shift=!!(modifier&1),key.option=!!(modifier&2),key.ctrl=!!(modifier&4),key.super=!!(modifier&8),key.hyper=!!(modifier&16),key.meta=!!(modifier&32),key.capsLock=!!(modifier&64),key.numLock=!!(modifier&128);let eventTypeStr=numericToEventType(eventType);if(eventTypeStr)key.eventType=eventTypeStr}else if(kittyParts||modifyOtherKeysParts){let codepoint,modifier;if(kittyParts)codepoint=Number(kittyParts[1]),modifier=Math.max(0,Number(kittyParts[4]||1)-1);else{let mokParts=modifyOtherKeysParts;modifier=Math.max(0,Number(mokParts[1])-1),codepoint=Number(mokParts[2])}if(kittyParts){if(key.isKittyProtocol=!0,key.raw=input,!isValidCodepoint(codepoint))return key.name="",key.isPrintable=!1,key}if(key.shift=!!(modifier&1),key.option=!!(modifier&2),key.ctrl=!!(modifier&4),key.super=!!(modifier&8),key.hyper=!!(modifier&16),key.meta=!!(modifier&32),key.capsLock=!!(modifier&64),key.numLock=!!(modifier&128),kittyParts?.[5]){let et=numericToEventType(Number(kittyParts[5]));if(et)key.eventType=et}if(kittyParts?.[2])key.shiftedKey=String.fromCodePoint(Number(kittyParts[2]));if(kittyParts?.[3])key.baseLayoutKey=String.fromCodePoint(Number(kittyParts[3]));let textFromProtocol;if(kittyParts?.[6])textFromProtocol=kittyParts[6].split(":").map((cp)=>safeFromCodePoint(Number(cp))).join(""),key.associatedText=textFromProtocol,key.text=textFromProtocol;if(codepoint===32)key.name="space",key.isPrintable=!0;else if(codepoint===13)key.name="return",key.isPrintable=!0;else{let mapped=kittyCodepointToName(codepoint);if(mapped)key.name=mapped,key.isPrintable=!1;else if(codepoint>=1&&codepoint<=26)key.name=String.fromCodePoint(codepoint+96),key.isPrintable=!1;else if(codepoint>=32&&codepoint<=126){if(key.name=String.fromCharCode(codepoint).toLowerCase(),codepoint>=65&&codepoint<=90)key.shift=!0,key.name=String.fromCharCode(codepoint+32);key.isPrintable=!0}else if(isValidCodepoint(codepoint))key.name=safeFromCodePoint(codepoint),key.isPrintable=!0;else key.name="",key.isPrintable=!1}if(kittyParts&&key.isPrintable&&!textFromProtocol)if(key.shift&&key.shiftedKey)key.text=key.shiftedKey;else if(key.shift&&codepoint>=97&&codepoint<=122)key.text=String.fromCharCode(codepoint-32);else if(key.shift&&codepoint>=65&&codepoint<=90)key.text=String.fromCharCode(codepoint);else if(key.shift&&key.isPrintable&&!key.shiftedKey&&codepoint>=32&&codepoint<=126){let baseChar=safeFromCodePoint(codepoint),shifted=BASE_TO_SHIFTED_PUNCT[baseChar];key.text=shifted??baseChar}else key.text=safeFromCodePoint(codepoint)}else if(KITTY_RE.test(input))return key.isKittyProtocol=!0,key.isPrintable=!1,key.raw=input,key;else{let parts=META_KEY_CODE_RE.exec(input);if(parts)key.meta=!0,key.shift=/^[A-Z]$/.test(parts[1]??"");else if(parts=FN_KEY_RE.exec(input),parts){let segs=input.split("");if(segs[0]==="\x1B"&&segs[1]==="\x1B")key.option=!0;let code=[parts[1],parts[2],parts[4],parts[6]].filter(Boolean).join(""),modifier=Number(parts[3]||parts[5]||1)-1;key.ctrl=!!(modifier&4),key.meta=!!(modifier&2),key.super=!!(modifier&8),key.hyper=!!(modifier&16),key.shift=!!(modifier&1),key.capsLock=!!(modifier&64),key.numLock=!!(modifier&128),key.code=code,key.name=CODE_TO_KEY[code]??"",key.shift=SHIFT_CODES.has(code)||key.shift,key.ctrl=CTRL_CODES.has(code)||key.ctrl}}}return key}function parseKey(rawInput){let keypress=parseKeypress(rawInput),key={upArrow:keypress.name==="up",downArrow:keypress.name==="down",leftArrow:keypress.name==="left",rightArrow:keypress.name==="right",pageDown:keypress.name==="pagedown",pageUp:keypress.name==="pageup",home:keypress.name==="home",end:keypress.name==="end",return:keypress.name==="return",escape:keypress.name==="escape",ctrl:keypress.ctrl,shift:keypress.shift,tab:keypress.name==="tab",backspace:keypress.name==="backspace",delete:keypress.name==="delete",meta:keypress.name!=="escape"&&(keypress.meta||keypress.option),super:keypress.super,hyper:keypress.hyper,capsLock:keypress.capsLock??!1,numLock:keypress.numLock??!1,eventType:keypress.eventType},input;if(keypress.isKittyProtocol)if(keypress.isPrintable)if(keypress.shift&&keypress.name.length===1&&keypress.name>="a"&&keypress.name<="z")input=keypress.name.toUpperCase();else if(keypress.name==="space")input=" ";else if(keypress.name==="return")input="\r";else input=keypress.name;else if(keypress.ctrl&&keypress.name.length===1)input=keypress.name;else input="";else{if(input=keypress.ctrl?keypress.name:keypress.sequence,NON_ALPHANUMERIC_KEYS.includes(keypress.name))input="";if(input.startsWith("\x1B"))input=input.slice(1);if(input.startsWith("[")&&input.length>1||input.startsWith("O")&&input.length>1)if(keypress.super||keypress.hyper)input=keypress.name;else input=""}if(keypress.isKittyProtocol)key.text=keypress.text??input;else if(input.length>=1)key.text=input;if(!keypress.isKittyProtocol&&input.length===1&&!key.shift){let base=SHIFTED_PUNCT_MAP[input];if(base)input=base,key.shift=!0}if(input.length===1&&typeof input[0]==="string"&&/[A-Z]/.test(input[0]))key.shift=!0;if(input===""&&MODIFIER_ONLY_NAMES.has(keypress.name))key.isModifierOnly=!0;return[input,key]}function emptyKey(){return{upArrow:!1,downArrow:!1,leftArrow:!1,rightArrow:!1,pageDown:!1,pageUp:!1,home:!1,end:!1,return:!1,escape:!1,ctrl:!1,shift:!1,tab:!1,backspace:!1,delete:!1,meta:!1,super:!1,hyper:!1,capsLock:!1,numLock:!1}}function keyToName(key){if(key.upArrow)return"ArrowUp";if(key.downArrow)return"ArrowDown";if(key.leftArrow)return"ArrowLeft";if(key.rightArrow)return"ArrowRight";if(key.return)return"Enter";if(key.escape)return"Escape";if(key.backspace)return"Backspace";if(key.delete)return"Delete";if(key.tab)return"Tab";if(key.pageUp)return"PageUp";if(key.pageDown)return"PageDown";if(key.home)return"Home";if(key.end)return"End";return""}function keyToModifiers(key){return{ctrl:!!key.ctrl,meta:!!key.meta,shift:!!key.shift,alt:!1,super:!!key.super,hyper:!!key.hyper}}function parseHotkey(keyStr){let remaining=keyStr,symbolMods=new Set;for(let char of remaining)if(MODIFIER_SYMBOLS.has(char))symbolMods.add(char);else break;if(symbolMods.size>0){if(remaining=remaining.slice(symbolMods.size),remaining.startsWith("+"))remaining=remaining.slice(1)}let parts=remaining.split("+"),key=parts.pop()||keyStr,modifiers=new Set([...parts.map((p)=>p.toLowerCase()),...symbolMods]);return{key,ctrl:modifiers.has("control")||modifiers.has("ctrl")||modifiers.has("⌃"),meta:modifiers.has("meta")||modifiers.has("alt")||modifiers.has("opt")||modifiers.has("option")||modifiers.has("⌥"),shift:modifiers.has("shift")||modifiers.has("⇧"),alt:!1,super:modifiers.has("super")||modifiers.has("cmd")||modifiers.has("command")||modifiers.has("⌘"),hyper:modifiers.has("hyper")||modifiers.has("✦")}}function matchHotkey(hotkey,key,input){if(!!hotkey.ctrl!==!!key.ctrl)return!1;if(!!hotkey.meta!==!!key.meta)return!1;if(!!hotkey.super!==!!key.super)return!1;if(!!hotkey.hyper!==!!key.hyper)return!1;if(!!hotkey.alt!==!1)return!1;if(!(hotkey.key.length===1&&!hotkey.shift)&&!!hotkey.shift!==!!key.shift)return!1;let name=keyToName(key);if(name&&name===hotkey.key)return!0;if(input!==void 0&&input===hotkey.key)return!0;if(key.text!==void 0&&key.text===hotkey.key)return!0;return!1}function keyToKittyAnsi(key){let parts=key.split("+"),mainKey=parts.pop(),modifiers=parts.map(normalizeModifier),mod=0;if(modifiers.includes("Shift"))mod|=1;if(modifiers.includes("Alt")||modifiers.includes("Meta"))mod|=2;if(modifiers.includes("Control"))mod|=4;if(modifiers.includes("Super"))mod|=8;if(modifiers.includes("Hyper"))mod|=16;let specialLetter=PLAYWRIGHT_TO_KITTY_SPECIAL_LETTER[mainKey];if(specialLetter)return`\x1B[1;${mod+1}${specialLetter}`;let specialNumber=PLAYWRIGHT_TO_KITTY_SPECIAL_TILDE[mainKey];if(specialNumber!==void 0)return`\x1B[${specialNumber};${mod+1}~`;let csiUCodepoint=PLAYWRIGHT_TO_KITTY_CSI_U[mainKey];if(csiUCodepoint!==void 0){if(mod>0)return`\x1B[${csiUCodepoint};${mod+1}u`;return`\x1B[${csiUCodepoint}u`}if(mainKey.length===1){let codepoint=mainKey.charCodeAt(0);if(mod>0){if((mod&1)!==0){let shifted=BASE_TO_SHIFTED_PUNCT[mainKey];if(shifted)return`\x1B[${codepoint}:${shifted.charCodeAt(0)};${mod+1}u`;if(codepoint>=97&&codepoint<=122)return`\x1B[${codepoint}:${codepoint-32};${mod+1}u`}return`\x1B[${codepoint};${mod+1}u`}return`\x1B[${codepoint}u`}let cp=NAME_TO_KITTY_CODEPOINT[mainKey.toLowerCase()];if(cp!==void 0){let implicitMod=MODIFIER_KEY_IMPLICIT_BITS[mainKey.toLowerCase()];if(implicitMod!==void 0)mod|=implicitMod;if(mod>0)return`\x1B[${cp};${mod+1}u`;return`\x1B[${cp}u`}return keyToAnsi(key)}function*splitRawInput(data){if(data.length<=1){if(data.length===1)yield data;return}let i=0,textStart=-1;while(i<data.length)if(data.charCodeAt(i)===27){if(textStart>=0)yield*splitNonEscapeText(data.slice(textStart,i)),textStart=-1;if(i+1>=data.length){yield"\x1B",i++;continue}let next=data.charCodeAt(i+1);if(next===91){let j=i+2;while(j<data.length){let c=data.charCodeAt(j);if(c>=64&&c<=126){j++;break}j++}yield data.slice(i,j),i=j}else if(next===79){let end=Math.min(i+3,data.length);yield data.slice(i,end),i=end}else if(next===27)if(i+2<data.length){let third=data.charCodeAt(i+2);if(third===91){let j=i+3;while(j<data.length){let c=data.charCodeAt(j);if(c>=64&&c<=126){j++;break}j++}yield data.slice(i,j),i=j}else if(third===79){let end=Math.min(i+4,data.length);yield data.slice(i,end),i=end}else yield"\x1B\x1B",i+=2}else yield"\x1B\x1B",i+=2;else yield data.slice(i,i+2),i+=2}else{if(textStart<0)textStart=i;i++}if(textStart>=0)yield*splitNonEscapeText(data.slice(textStart))}function*splitNonEscapeText(text){let segmentStart=0;for(let i=0;i<text.length;i++){let ch=text.charCodeAt(i);if(ch===127||ch===8){if(i>segmentStart)yield text.slice(segmentStart,i);yield text[i],segmentStart=i+1}}if(segmentStart<text.length)yield text.slice(segmentStart)}var log,KEY_MAP,MODIFIER_ALIASES,MODIFIER_SYMBOLS,CODE_TO_KEY,NON_ALPHANUMERIC_KEYS,SHIFT_CODES,CTRL_CODES,META_KEY_CODE_RE,FN_KEY_RE,SHIFTED_PUNCT_MAP,BASE_TO_SHIFTED_PUNCT,KITTY_RE,MODIFY_OTHER_KEYS_RE,KITTY_SPECIAL_RE,KITTY_SPECIAL_LETTER_KEYS,KITTY_SPECIAL_NUMBER_KEYS,KITTY_CODEPOINT_MAP,MODIFIER_ONLY_NAMES,NAME_TO_KITTY_CODEPOINT,MODIFIER_KEY_IMPLICIT_BITS,PLAYWRIGHT_TO_KITTY_CSI_U,PLAYWRIGHT_TO_KITTY_SPECIAL_LETTER,PLAYWRIGHT_TO_KITTY_SPECIAL_TILDE,graphemeSegmenter;var init_keys=__esm(()=>{log=createLogger("silvery:keys");KEY_MAP={ArrowUp:"\x1B[A",ArrowDown:"\x1B[B",ArrowLeft:"\x1B[D",ArrowRight:"\x1B[C",Home:"\x1B[H",End:"\x1B[F",PageUp:"\x1B[5~",PageDown:"\x1B[6~",Enter:"\r",Tab:"\t",Backspace:"",Delete:"\x1B[3~",Escape:"\x1B",Space:" ",Control:null,Shift:null,Alt:null,Meta:null,Super:null,Hyper:null},MODIFIER_ALIASES={ctrl:"Control",control:"Control","⌃":"Control",shift:"Shift","⇧":"Shift",alt:"Alt",meta:"Meta",opt:"Alt",option:"Alt","⌥":"Alt",cmd:"Super",command:"Super",super:"Super","⌘":"Super",hyper:"Hyper","✦":"Hyper"},MODIFIER_SYMBOLS=new Set(["⌃","⇧","⌥","⌘","✦"]);CODE_TO_KEY={"[A":"up","[B":"down","[C":"right","[D":"left","[E":"clear","[F":"end","[H":"home",OA:"up",OB:"down",OC:"right",OD:"left",OE:"clear",OF:"end",OH:"home",OP:"f1",OQ:"f2",OR:"f3",OS:"f4","[11~":"f1","[12~":"f2","[13~":"f3","[14~":"f4","[15~":"f5","[17~":"f6","[18~":"f7","[19~":"f8","[20~":"f9","[21~":"f10","[23~":"f11","[24~":"f12","[[A":"f1","[[B":"f2","[[C":"f3","[[D":"f4","[[E":"f5","[1~":"home","[2~":"insert","[3~":"delete","[4~":"end","[5~":"pageup","[6~":"pagedown","[[5~":"pageup","[[6~":"pagedown","[7~":"home","[8~":"end","[a":"up","[b":"down","[c":"right","[d":"left","[e":"clear","[2$":"insert","[3$":"delete","[5$":"pageup","[6$":"pagedown","[7$":"home","[8$":"end",Oa:"up",Ob:"down",Oc:"right",Od:"left",Oe:"clear","[2^":"insert","[3^":"delete","[5^":"pageup","[6^":"pagedown","[7^":"home","[8^":"end","[Z":"tab"},NON_ALPHANUMERIC_KEYS=[...Object.values(CODE_TO_KEY),"backspace","tab","delete"],SHIFT_CODES=new Set(["[a","[b","[c","[d","[e","[2$","[3$","[5$","[6$","[7$","[8$","[Z"]),CTRL_CODES=new Set(["Oa","Ob","Oc","Od","Oe","[2^","[3^","[5^","[6^","[7^","[8^"]),META_KEY_CODE_RE=/^(?:\x1b)([a-zA-Z0-9])$/,FN_KEY_RE=/^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/,SHIFTED_PUNCT_MAP={"!":"1","@":"2","#":"3",$:"4","%":"5","^":"6","&":"7","*":"8","(":"9",")":"0",_:"-","+":"=","~":"`","{":"[","}":"]","|":"\\",":":";",'"':"'","<":",",">":".","?":"/"},BASE_TO_SHIFTED_PUNCT=Object.fromEntries(Object.entries(SHIFTED_PUNCT_MAP).map(([shifted,base])=>[base,shifted])),KITTY_RE=/^\x1b\[(\d+)(?::(\d+))?(?::(\d+))?(?:;(\d+)(?::(\d+))?(?:;([\d:]+))?)?u$/,MODIFY_OTHER_KEYS_RE=/^\x1b\[27;(\d+);(\d+)~$/,KITTY_SPECIAL_RE=/^\x1b\[(\d+);(\d+):(\d+)([A-Za-z~])$/,KITTY_SPECIAL_LETTER_KEYS={A:"up",B:"down",C:"right",D:"left",E:"clear",F:"end",H:"home",P:"f1",Q:"f2",R:"f3",S:"f4"},KITTY_SPECIAL_NUMBER_KEYS={2:"insert",3:"delete",5:"pageup",6:"pagedown",7:"home",8:"end",11:"f1",12:"f2",13:"f3",14:"f4",15:"f5",17:"f6",18:"f7",19:"f8",20:"f9",21:"f10",23:"f11",24:"f12"};KITTY_CODEPOINT_MAP={8:"backspace",9:"tab",13:"return",27:"escape",127:"backspace",57376:"f13",57377:"f14",57378:"f15",57379:"f16",57380:"f17",57381:"f18",57382:"f19",57383:"f20",57384:"f21",57385:"f22",57386:"f23",57387:"f24",57388:"f25",57389:"f26",57390:"f27",57391:"f28",57392:"f29",57393:"f30",57394:"f31",57395:"f32",57396:"f33",57397:"f34",57398:"f35",57358:"capslock",57359:"scrolllock",57360:"numlock",57361:"printscreen",57362:"pause",57363:"menu",57399:"kp0",57400:"kp1",57401:"kp2",57402:"kp3",57403:"kp4",57404:"kp5",57405:"kp6",57406:"kp7",57407:"kp8",57408:"kp9",57409:"kpdecimal",57410:"kpdivide",57411:"kpmultiply",57412:"kpsubtract",57413:"kpadd",57414:"kpenter",57415:"kpequal",57416:"kpseparator",57417:"kpleft",57418:"kpright",57419:"kpup",57420:"kpdown",57421:"kppageup",57422:"kppagedown",57423:"kphome",57424:"kpend",57425:"kpinsert",57426:"kpdelete",57427:"kpbegin",57428:"mediaplay",57429:"mediapause",57430:"mediaplaypause",57431:"mediareverse",57432:"mediastop",57433:"mediafastforward",57434:"mediarewind",57435:"mediatracknext",57436:"mediatrackprevious",57437:"mediarecord",57438:"lowervolume",57439:"raisevolume",57440:"mutevolume",57441:"leftshift",57442:"leftcontrol",57443:"leftalt",57444:"leftsuper",57445:"lefthyper",57446:"leftmeta",57447:"rightshift",57448:"rightcontrol",57449:"rightalt",57450:"rightsuper",57451:"righthyper",57452:"rightmeta",57453:"isoLevel3Shift",57454:"isoLevel5Shift"},MODIFIER_ONLY_NAMES=new Set(["leftshift","leftcontrol","leftalt","leftsuper","lefthyper","leftmeta","rightshift","rightcontrol","rightalt","rightsuper","righthyper","rightmeta","isoLevel3Shift","isoLevel5Shift"]);NAME_TO_KITTY_CODEPOINT={};for(let[cp,name]of Object.entries(KITTY_CODEPOINT_MAP))NAME_TO_KITTY_CODEPOINT[name]=Number(cp);MODIFIER_KEY_IMPLICIT_BITS={leftshift:1,rightshift:1,leftcontrol:4,rightcontrol:4,leftalt:2,rightalt:2,leftsuper:8,rightsuper:8,lefthyper:16,righthyper:16,leftmeta:32,rightmeta:32},PLAYWRIGHT_TO_KITTY_CSI_U={Enter:13,Escape:27,Backspace:127,Tab:9,Space:32},PLAYWRIGHT_TO_KITTY_SPECIAL_LETTER={ArrowUp:"A",ArrowDown:"B",ArrowRight:"C",ArrowLeft:"D",Home:"H",End:"F",F1:"P",F2:"Q",F3:"R",F4:"S"},PLAYWRIGHT_TO_KITTY_SPECIAL_TILDE={Insert:2,Delete:3,PageUp:5,PageDown:6,F5:15,F6:17,F7:18,F8:19,F9:20,F10:21,F11:23,F12:24};graphemeSegmenter=new Intl.Segmenter("en",{granularity:"grapheme"})});var init_constants=()=>{};function detectCursor(stdout){if(!stdout.isTTY)return!1;if(process.env.TERM==="dumb")return!1;return!0}function detectInput(stdin){if(!stdin.isTTY)return!1;return typeof stdin.setRawMode==="function"}function detectColor(stdout){if(process.env.NO_COLOR!==void 0)return null;let forceColor=process.env.FORCE_COLOR;if(forceColor!==void 0){if(forceColor==="0"||forceColor==="false")return null;if(forceColor==="1")return"basic";if(forceColor==="2")return"256";if(forceColor==="3")return"truecolor";return"basic"}if(!stdout.isTTY)return null;if(process.env.TERM==="dumb")return null;let colorTerm=process.env.COLORTERM;if(colorTerm==="truecolor"||colorTerm==="24bit")return"truecolor";let term=process.env.TERM??"";if(term.includes("truecolor")||term.includes("24bit")||term.includes("xterm-ghostty")||term.includes("xterm-kitty")||term.includes("wezterm"))return"truecolor";if(term.includes("256color")||term.includes("256"))return"256";let termProgram=process.env.TERM_PROGRAM;if(termProgram==="iTerm.app"||termProgram==="Apple_Terminal")return termProgram==="iTerm.app"?"truecolor":"256";if(termProgram==="Ghostty"||termProgram==="WezTerm")return"truecolor";if(process.env.KITTY_WINDOW_ID)return"truecolor";if(term.includes("xterm")||term.includes("color")||term.includes("ansi"))return"basic";if(CI_ENVS.some((env)=>process.env[env]!==void 0))return"basic";if(process.env.WT_SESSION)return"truecolor";return"basic"}function detectUnicode(){if(process.env.CI){if(process.env.GITHUB_ACTIONS)return!0}let lang=process.env.LANG??process.env.LC_ALL??process.env.LC_CTYPE??"";if(lang.toLowerCase().includes("utf-8")||lang.toLowerCase().includes("utf8"))return!0;if(process.env.WT_SESSION)return!0;let termProgram=process.env.TERM_PROGRAM??"";if(["iTerm.app","Ghostty","WezTerm","Apple_Terminal"].includes(termProgram))return!0;if(process.env.KITTY_WINDOW_ID)return!0;let term=process.env.TERM??"";if(term.includes("xterm")||term.includes("rxvt")||term.includes("screen")||term.includes("tmux"))return!0;return!1}function defaultCaps(){return{program:"",term:"",colorLevel:"truecolor",kittyKeyboard:!1,kittyGraphics:!1,sixel:!1,osc52:!1,hyperlinks:!1,notifications:!1,bracketedPaste:!0,mouse:!0,syncOutput:!1,unicode:!0,underlineStyles:!0,underlineColor:!0,textEmojiWide:!0,textSizingSupported:!1,darkBackground:!0,nerdfont:!1}}function detectMacOSDarkMode(){if(cachedMacOSDarkMode!==void 0)return cachedMacOSDarkMode;try{let{spawnSync}=__require("child_process");cachedMacOSDarkMode=spawnSync("defaults",["read","-g","AppleInterfaceStyle"],{encoding:"utf-8",timeout:500}).stdout?.trim()==="Dark"}catch{cachedMacOSDarkMode=!1}return cachedMacOSDarkMode}function detectTerminalCaps(){let program=process.env.TERM_PROGRAM??"",term=process.env.TERM??"",colorTerm=process.env.COLORTERM??"",noColor=process.env.NO_COLOR!==void 0,isAppleTerminal=program==="Apple_Terminal",colorLevel="none";if(!noColor){if(isAppleTerminal)colorLevel="256";else if(colorTerm==="truecolor"||colorTerm==="24bit")colorLevel="truecolor";else if(term.includes("256color"))colorLevel="256";else if(process.stdout?.isTTY)colorLevel="basic"}let isKitty=term==="xterm-kitty",isITerm=program==="iTerm.app",isGhostty=program==="ghostty",isWezTerm=program==="WezTerm",isAlacritty=program==="Alacritty",isFoot=term==="foot"||term==="foot-extra",isModern=isKitty||isITerm||isGhostty||isWezTerm||isFoot,isKittyWithTextSizing=!1;if(isKitty){let parts=(process.env.TERM_PROGRAM_VERSION??"").split("."),major=Number(parts[0])||0,minor=Number(parts[1])||0;isKittyWithTextSizing=major>0||major===0&&minor>=40}let darkBackground=!isAppleTerminal,colorFgBg=process.env.COLORFGBG;if(colorFgBg){let parts=colorFgBg.split(";"),bg=parseInt(parts[parts.length-1]??"",10);if(!isNaN(bg))darkBackground=bg<7}else if(isAppleTerminal)darkBackground=detectMacOSDarkMode();let nerdfont=isModern||isAlacritty,nfEnv=process.env.NERDFONT;if(nfEnv==="0"||nfEnv==="false")nerdfont=!1;else if(nfEnv==="1"||nfEnv==="true")nerdfont=!0;let underlineExtensions=isModern||isAlacritty;return{program,term,colorLevel,kittyKeyboard:isKitty||isGhostty||isWezTerm||isFoot,kittyGraphics:isKitty||isGhostty,sixel:isFoot||isWezTerm,osc52:isModern||isAlacritty,hyperlinks:isModern||isAlacritty,notifications:isITerm||isKitty,bracketedPaste:!0,mouse:!0,syncOutput:isModern||isAlacritty,unicode:!0,underlineStyles:underlineExtensions,underlineColor:underlineExtensions,textEmojiWide:!isAppleTerminal,textSizingSupported:isKittyWithTextSizing,darkBackground,nerdfont}}var CI_ENVS,cachedMacOSDarkMode;var init_detection=__esm(()=>{CI_ENVS=["CI","GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","BUILDKITE","CIRCLECI","TRAVIS"]});function fgColorCode(color){if(typeof color==="number"){if(color>=0&&color<=7)return`${30+color}`;return`38;5;${color}`}return`38;2;${color.r};${color.g};${color.b}`}function bgColorCode(color){if(typeof color==="number"){if(color>=0&&color<=7)return`${40+color}`;return`48;5;${color}`}return`48;2;${color.r};${color.g};${color.b}`}import stringWidth from"string-width";var init_utils=()=>{};function nearestAnsi16(r,g,b){let bestIdx=0,bestDist=1/0;for(let i=0;i<16;i++){let[cr,cg,cb]=ANSI_16_COLORS[i],dist=(r-cr)**2+(g-cg)**2+(b-cb)**2;if(dist<bestDist)bestDist=dist,bestIdx=i}return bestIdx}function rgbToAnsi256(r,g,b){if(r===g&&g===b){if(r<8)return 16;if(r>248)return 231;return Math.round((r-8)/247*24)+232}let ri=Math.round(r/255*5),gi=Math.round(g/255*5),bi=Math.round(b/255*5);return 16+36*ri+6*gi+bi}function fgFromRgb(r,g,b,level){if(level==="truecolor")return`38;2;${r};${g};${b}`;if(level==="256")return`38;5;${rgbToAnsi256(r,g,b)}`;let idx=nearestAnsi16(r,g,b);return idx<8?`${30+idx}`:`${82+idx}`}function bgFromRgb(r,g,b,level){if(level==="truecolor")return`48;2;${r};${g};${b}`;if(level==="256")return`48;5;${rgbToAnsi256(r,g,b)}`;let idx=nearestAnsi16(r,g,b);return idx<8?`${40+idx}`:`${92+idx}`}var MODIFIERS,FG_COLORS,BG_COLORS,ANSI_16_COLORS;var init_color_maps=__esm(()=>{MODIFIERS={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],overline:[53,55]},FG_COLORS={black:30,red:31,green:32,yellow:33,blue:34,magenta:35,cyan:36,white:37,blackBright:90,gray:90,grey:90,redBright:91,greenBright:92,yellowBright:93,blueBright:94,magentaBright:95,cyanBright:96,whiteBright:97},BG_COLORS={bgBlack:40,bgRed:41,bgGreen:42,bgYellow:43,bgBlue:44,bgMagenta:45,bgCyan:46,bgWhite:47,bgBlackBright:100,bgGray:100,bgGrey:100,bgRedBright:101,bgGreenBright:102,bgYellowBright:103,bgBlueBright:104,bgMagentaBright:105,bgCyanBright:106,bgWhiteBright:107},ANSI_16_COLORS=[[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]]});function enableMouse(){return"\x1B[?1003h\x1B[?1006h"}function disableMouse(){return"\x1B[?1006l\x1B[?1003l"}function enableKittyKeyboard(flags=1){return`\x1B[>${flags}u`}function disableKittyKeyboard(){return"\x1B[<u"}var init_underline_ext=__esm(()=>{init_constants();init_detection()});var init_hyperlink=__esm(()=>{init_constants()});function hexToRgb(hex){if(hex[0]!=="#")return null;let h=hex.slice(1);if(h.length===3)return[parseInt(h[0]+h[0],16),parseInt(h[1]+h[1],16),parseInt(h[2]+h[2],16)];if(h.length===6)return[parseInt(h.slice(0,2),16),parseInt(h.slice(2,4),16),parseInt(h.slice(4,6),16)];return null}function rgbToHex(r,g,b){let clamp=(n)=>Math.max(0,Math.min(255,Math.round(n)));return`#${clamp(r).toString(16).padStart(2,"0")}${clamp(g).toString(16).padStart(2,"0")}${clamp(b).toString(16).padStart(2,"0")}`.toUpperCase()}function blend(a,b,t){let rgbA=hexToRgb(a),rgbB=hexToRgb(b);if(!rgbA||!rgbB)return a;return rgbToHex(rgbA[0]+(rgbB[0]-rgbA[0])*t,rgbA[1]+(rgbB[1]-rgbA[1])*t,rgbA[2]+(rgbB[2]-rgbA[2])*t)}function brighten(color,amount){return blend(color,"#FFFFFF",amount)}function channelLuminance(c){let s=c/255;return s<=0.03928?s/12.92:Math.pow((s+0.055)/1.055,2.4)}function relativeLuminance(hex){let rgb=hexToRgb(hex);if(!rgb)return null;return 0.2126*channelLuminance(rgb[0])+0.7152*channelLuminance(rgb[1])+0.0722*channelLuminance(rgb[2])}function contrastFg(bg){let luminance=relativeLuminance(bg);if(luminance===null)return"#FFFFFF";return luminance>0.179?"#000000":"#FFFFFF"}function rgbToHsl(r,g,b){r/=255,g/=255,b/=255;let max=Math.max(r,g,b),min=Math.min(r,g,b),l=(max+min)/2;if(max===min)return[0,0,l];let d=max-min,s=l>0.5?d/(2-max-min):d/(max+min),h=0;if(max===r)h=((g-b)/d+(g<b?6:0))/6;else if(max===g)h=((b-r)/d+2)/6;else h=((r-g)/d+4)/6;return[h*360,s,l]}function hslToHex(h,s,l){h=(h%360+360)%360;let a=s*Math.min(l,1-l),f=(n)=>{let k=(n+h/30)%12;return l-a*Math.max(Math.min(k-3,9-k,1),-1)};return rgbToHex(f(0)*255,f(8)*255,f(4)*255)}function hexToHsl(hex){let rgb=hexToRgb(hex);if(!rgb)return null;return rgbToHsl(rgb[0],rgb[1],rgb[2])}function complement(color){let hsl=hexToHsl(color);if(!hsl)return color;let[h,s,l]=hsl;return hslToHex(h+180,s,l)}function checkContrast(fg,bg){let fgLum=relativeLuminance(fg),bgLum=relativeLuminance(bg);if(fgLum===null||bgLum===null)return null;let lighter=Math.max(fgLum,bgLum),darker=Math.min(fgLum,bgLum),ratio=(lighter+0.05)/(darker+0.05);return{ratio,aa:ratio>=4.5,aaa:ratio>=7}}function ensureContrast(color,against,minRatio){let current=checkContrast(color,against);if(!current)return color;if(current.ratio>=minRatio)return color;let hsl=hexToHsl(color);if(!hsl)return color;let[h,s]=hsl,lightBg=contrastFg(against)==="#000000",lo,hi;if(lightBg)lo=0,hi=hsl[2];else lo=hsl[2],hi=1;for(let i=0;i<20;i++){let mid=(lo+hi)/2,candidate=hslToHex(h,s,mid),r=checkContrast(candidate,against);if(!r)break;if(lightBg)if(r.ratio>=minRatio)lo=mid;else hi=mid;else if(r.ratio>=minRatio)hi=mid;else lo=mid}return hslToHex(h,s,lightBg?lo:hi)}var init_contrast=()=>{};var init_src=__esm(()=>{init_contrast()});var THEME_TOKEN_DEFAULTS;var init_colors=__esm(()=>{init_src();init_color_maps();THEME_TOKEN_DEFAULTS={primary:33,secondary:36,accent:35,error:31,warning:33,success:32,info:36,muted:2,link:34,border:90,surface:37}});function resolveThemeColor(name,theme){if(!name)return;if(!name.startsWith("$"))return name;if(!theme)return;return resolveToken(name,theme)}function resolveToken(name,theme){if(!theme)return;let token=name.startsWith("$")?name.slice(1):name;if(token.startsWith("color")){let idx=parseInt(token.slice(5),10);if(idx>=0&&idx<16&&theme.palette&&idx<theme.palette.length)return theme.palette[idx]}let key=token.replace(/-/g,""),val=theme[key];return typeof val==="string"?val:void 0}function fromChalkLevel(n){if(n<=0)return null;if(n===1)return"basic";if(n===2)return"256";return"truecolor"}function toChalkLevel(cl){if(cl===null)return 0;if(cl==="basic")return 1;if(cl==="256")return 2;return 3}function createStyle(options){let ref={level:null,theme:options?.theme};if(options?.level!==void 0)ref.level=options.level;else try{ref.level=detectColor(process.stdout)}catch{ref.level=null}return createChainWithRef({opens:[],closes:[]},ref)}function createChainWithRef(state,ref){let proxyRef={proxy:null},proxy=new Proxy(function(){},{apply(_target,_thisArg,args){let level=ref.level;if(state.visible&&level===null)return"";let text;if(args.length===0)text="";else if(Array.isArray(args[0])&&"raw"in args[0])text=String.raw(args[0],...args.slice(1));else if(args.length>1)text=args.map((a)=>String(a??"")).join(" ");else text=String(args[0]??"");if(text==="")return"";if(level===null||state.opens.length===0)return text;let open=`${ESC}${state.opens.join(";")}m`,close=`${ESC}${state.closes.join(";")}m`;for(let closeCode of state.closes){let closeSeq=`${ESC}${closeCode}m`,parts=text.split(closeSeq);if(parts.length>1)text=parts.join(`${closeSeq}${open}`)}if(text.includes(`
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 setPaletteColor(index,color,write){if(index<0||index>255)throw RangeError(`Palette index must be 0-255, got ${index}`);write(`\x1B]4;${index};${color}\x07`)}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)}async function queryCursorColor(write,read,timeoutMs=200){return queryOscColor(write,read,12,timeoutMs)}function setForegroundColor(write,color){write(`\x1B]10;${color}\x07`)}function setBackgroundColor(write,color){write(`\x1B]11;${color}\x07`)}function setCursorColor(write,color){write(`\x1B]12;${color}\x07`)}function resetForegroundColor(write){write("\x1B]110\x07")}function resetBackgroundColor(write){write("\x1B]111\x07")}function resetCursorColor(write){write("\x1B]112\x07")}async function detectColorScheme(write,read,timeoutMs=200){let bg=await queryBackgroundColor(write,read,timeoutMs);if(bg==null)return null;let r=parseInt(bg.slice(1,3),16)/255,g=parseInt(bg.slice(3,5),16)/255,b=parseInt(bg.slice(5,7),16)/255;return 0.2126*r+0.7152*g+0.0722*b>0.5?"light":"dark"}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()});function isDefaultBg(color){return color!==null&&typeof color==="object"&&color.r===-1}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(`
@@ -60,17 +60,21 @@ ${colDetails.join(`
60
60
  `)},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+`
61
61
  `),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});function patchConsole(console2,options){let suppress=options?.suppress??!1,capture=options?.capture??!0,entries=[],snapshot=entries,EMPTY=Object.freeze([]),stats={total:0,errors:0,warnings:0},subscribers=new Set,originals=new Map;for(let method of METHODS)originals.set(method,console2[method].bind(console2));let notifyPending=!1;function scheduleNotify(){if(notifyPending)return;notifyPending=!0,queueMicrotask(()=>{notifyPending=!1,subscribers.forEach((subscriber)=>subscriber())})}for(let method of METHODS){let original=originals.get(method);console2[method]=(...args)=>{if(stats.total++,method==="error")stats.errors++;else if(method==="warn")stats.warnings++;if(capture){let entry={method,args,stream:STDERR_METHODS.has(method)?"stderr":"stdout"};entries.push(entry),snapshot=entries.slice()}if(!suppress)original(...args);scheduleNotify()}}function restore(){for(let method of METHODS)console2[method]=originals.get(method)}return{getSnapshot(){return capture?snapshot:EMPTY},getStats(){return{...stats}},subscribe(onStoreChange){return subscribers.add(onStoreChange),()=>{subscribers.delete(onStoreChange)}},dispose(){restore(),subscribers.clear()},[Symbol.dispose](){this.dispose()}}}var METHODS,STDERR_METHODS;var init_patch_console=__esm(()=>{METHODS=["log","info","warn","error","debug"],STDERR_METHODS=new Set(["error","warn"])});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(" ")+`
62
62
  `;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()+`
63
- `+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 exports_layout_engine={};__export(exports_layout_engine,{setLayoutEngine:()=>setLayoutEngine,isLayoutEngineInitialized:()=>isLayoutEngineInitialized,getLayoutEngine:()=>getLayoutEngine,getConstants:()=>getConstants,ensureDefaultLayoutEngine:()=>ensureDefaultLayoutEngine});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())}}var layoutEngine=null;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}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,renderEpoch=0;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}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;let entry=textCaches.get(node);if(!entry?.analysis)return null;if(isDirty(node.dirtyBits,node.dirtyEpoch,PLAIN_TEXT_DIRTY))return entry.analysis=null,null;return entry.analysis}function setCachedAnalysis(node,analysis){let entry=getOrCreate(node);entry.analysis=analysis}var MAX_FORMAT_ENTRIES=4,PLAIN_TEXT_DIRTY,COLLECTED_TEXT_DIRTY,_cacheDisabled,textCaches;var init_prepared_text=__esm(()=>{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,textCaches=new WeakMap});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,maxGraphemeWidth=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,w>maxGraphemeWidth)maxGraphemeWidth=w;if(g===`
63
+ `+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 FLEX_DIRECTION_COLUMN2=0,FLEX_DIRECTION_COLUMN_REVERSE2=1,FLEX_DIRECTION_ROW2=2,FLEX_DIRECTION_ROW_REVERSE2=3,WRAP_NO_WRAP2=0,WRAP_WRAP2=1,WRAP_WRAP_REVERSE2=2,ALIGN_AUTO2=0,ALIGN_FLEX_START2=1,ALIGN_CENTER2=2,ALIGN_FLEX_END2=3,ALIGN_STRETCH2=4,ALIGN_BASELINE2=5,ALIGN_SPACE_BETWEEN2=6,ALIGN_SPACE_AROUND2=7,ALIGN_SPACE_EVENLY=8,JUSTIFY_FLEX_START2=0,JUSTIFY_CENTER2=1,JUSTIFY_FLEX_END2=2,JUSTIFY_SPACE_BETWEEN2=3,JUSTIFY_SPACE_AROUND2=4,JUSTIFY_SPACE_EVENLY2=5,EDGE_LEFT2=0,EDGE_TOP2=1,EDGE_RIGHT2=2,EDGE_BOTTOM2=3,EDGE_START2=4,EDGE_END2=5,EDGE_HORIZONTAL2=6,EDGE_VERTICAL2=7,EDGE_ALL2=8,GUTTER_COLUMN2=0,GUTTER_ROW2=1,GUTTER_ALL2=2,DISPLAY_FLEX2=0,DISPLAY_NONE2=1,POSITION_TYPE_STATIC2=0,POSITION_TYPE_RELATIVE2=1,POSITION_TYPE_ABSOLUTE2=2,OVERFLOW_VISIBLE2=0,OVERFLOW_HIDDEN2=1,OVERFLOW_SCROLL2=2,DIRECTION_LTR2=1,DIRECTION_RTL2=2,MEASURE_MODE_UNDEFINED2=0,MEASURE_MODE_EXACTLY2=1,MEASURE_MODE_AT_MOST2=2,UNIT_UNDEFINED2=0,UNIT_POINT2=1,UNIT_PERCENT2=2,UNIT_AUTO2=3;function setEdgeValue(arr,edge,value,unit){let v={value,unit};switch(edge){case EDGE_LEFT2:arr[0]=v;break;case EDGE_TOP2:arr[1]=v;break;case EDGE_RIGHT2:arr[2]=v;break;case EDGE_BOTTOM2:arr[3]=v;break;case EDGE_HORIZONTAL2:arr[0]=v,arr[2]=v;break;case EDGE_VERTICAL2:arr[1]=v,arr[3]=v;break;case EDGE_ALL2:arr[0]=v,arr[1]=v,arr[2]=v,arr[3]=v;break;case EDGE_START2:arr[4]=v;break;case EDGE_END2:arr[5]=v;break}}function setEdgeBorder(arr,edge,value){switch(edge){case EDGE_LEFT2:arr[0]=value;break;case EDGE_TOP2:arr[1]=value;break;case EDGE_RIGHT2:arr[2]=value;break;case EDGE_BOTTOM2:arr[3]=value;break;case EDGE_HORIZONTAL2:arr[0]=value,arr[2]=value;break;case EDGE_VERTICAL2:arr[1]=value,arr[3]=value;break;case EDGE_ALL2:arr[0]=value,arr[1]=value,arr[2]=value,arr[3]=value;break;case EDGE_START2:arr[4]=value;break;case EDGE_END2:arr[5]=value;break}}function getEdgeValue(arr,edge){switch(edge){case EDGE_LEFT2:return arr[0];case EDGE_TOP2:return arr[1];case EDGE_RIGHT2:return arr[2];case EDGE_BOTTOM2:return arr[3];case EDGE_START2:return arr[4];case EDGE_END2:return arr[5];default:return arr[0]}}function getEdgeBorderValue(arr,edge){switch(edge){case EDGE_LEFT2:return arr[0];case EDGE_TOP2:return arr[1];case EDGE_RIGHT2:return arr[2];case EDGE_BOTTOM2:return arr[3];case EDGE_START2:return arr[4];case EDGE_END2:return arr[5];default:return arr[0]}}function resolveValue(value,availableSize){switch(value.unit){case UNIT_POINT2:return value.value;case UNIT_PERCENT2:if(Number.isNaN(availableSize))return 0;return availableSize*(value.value/100);default:return 0}}function applyMinMax(size,min,max,available){let result=size;if(max.unit!==UNIT_UNDEFINED2)if(max.unit===UNIT_PERCENT2&&Number.isNaN(available));else{let maxValue=resolveValue(max,available);if(!Number.isNaN(maxValue))if(Number.isNaN(result)){if(maxValue!==1/0)result=maxValue}else result=Math.min(result,maxValue)}if(min.unit!==UNIT_UNDEFINED2)if(min.unit===UNIT_PERCENT2&&Number.isNaN(available));else{let minValue=resolveValue(min,available);if(!Number.isNaN(minValue)){if(!Number.isNaN(result))result=Math.max(result,minValue)}}return result}var traversalStack;var init_utils3=__esm(()=>{traversalStack=[]});var require_ms=__commonJS((exports,module)=>{var s=1000,m=s*60,h=m*60,d=h*24,w=d*7,y=d*365.25;module.exports=function(val,options){options=options||{};var type=typeof val;if(type==="string"&&val.length>0)return parse(val);else if(type==="number"&&isFinite(val))return options.long?fmtLong(val):fmtShort(val);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(val))};function parse(str){if(str=String(str),str.length>100)return;var match=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);if(!match)return;var n=parseFloat(match[1]),type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"weeks":case"week":case"w":return n*w;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}function fmtShort(ms){var msAbs=Math.abs(ms);if(msAbs>=d)return Math.round(ms/d)+"d";if(msAbs>=h)return Math.round(ms/h)+"h";if(msAbs>=m)return Math.round(ms/m)+"m";if(msAbs>=s)return Math.round(ms/s)+"s";return ms+"ms"}function fmtLong(ms){var msAbs=Math.abs(ms);if(msAbs>=d)return plural(ms,msAbs,d,"day");if(msAbs>=h)return plural(ms,msAbs,h,"hour");if(msAbs>=m)return plural(ms,msAbs,m,"minute");if(msAbs>=s)return plural(ms,msAbs,s,"second");return ms+" ms"}function plural(ms,msAbs,n,name){var isPlural=msAbs>=n*1.5;return Math.round(ms/n)+" "+name+(isPlural?"s":"")}});var require_common=__commonJS((exports,module)=>{function setup(env){createDebug.debug=createDebug,createDebug.default=createDebug,createDebug.coerce=coerce,createDebug.disable=disable,createDebug.enable=enable,createDebug.enabled=enabled,createDebug.humanize=require_ms(),createDebug.destroy=destroy,Object.keys(env).forEach((key)=>{createDebug[key]=env[key]}),createDebug.names=[],createDebug.skips=[],createDebug.formatters={};function selectColor(namespace){let hash=0;for(let i=0;i<namespace.length;i++)hash=(hash<<5)-hash+namespace.charCodeAt(i),hash|=0;return createDebug.colors[Math.abs(hash)%createDebug.colors.length]}createDebug.selectColor=selectColor;function createDebug(namespace){let prevTime,enableOverride=null,namespacesCache,enabledCache;function debug(...args){if(!debug.enabled)return;let self=debug,curr=Number(new Date),ms=curr-(prevTime||curr);if(self.diff=ms,self.prev=prevTime,self.curr=curr,prevTime=curr,args[0]=createDebug.coerce(args[0]),typeof args[0]!=="string")args.unshift("%O");let index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,(match,format)=>{if(match==="%%")return"%";index++;let formatter=createDebug.formatters[format];if(typeof formatter==="function"){let val=args[index];match=formatter.call(self,val),args.splice(index,1),index--}return match}),createDebug.formatArgs.call(self,args),(self.log||createDebug.log).apply(self,args)}if(debug.namespace=namespace,debug.useColors=createDebug.useColors(),debug.color=createDebug.selectColor(namespace),debug.extend=extend,debug.destroy=createDebug.destroy,Object.defineProperty(debug,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(enableOverride!==null)return enableOverride;if(namespacesCache!==createDebug.namespaces)namespacesCache=createDebug.namespaces,enabledCache=createDebug.enabled(namespace);return enabledCache},set:(v)=>{enableOverride=v}}),typeof createDebug.init==="function")createDebug.init(debug);return debug}function extend(namespace,delimiter){let newDebug=createDebug(this.namespace+(typeof delimiter>"u"?":":delimiter)+namespace);return newDebug.log=this.log,newDebug}function enable(namespaces){createDebug.save(namespaces),createDebug.namespaces=namespaces,createDebug.names=[],createDebug.skips=[];let split=(typeof namespaces==="string"?namespaces:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let ns of split)if(ns[0]==="-")createDebug.skips.push(ns.slice(1));else createDebug.names.push(ns)}function matchesTemplate(search,template){let searchIndex=0,templateIndex=0,starIndex=-1,matchIndex=0;while(searchIndex<search.length)if(templateIndex<template.length&&(template[templateIndex]===search[searchIndex]||template[templateIndex]==="*"))if(template[templateIndex]==="*")starIndex=templateIndex,matchIndex=searchIndex,templateIndex++;else searchIndex++,templateIndex++;else if(starIndex!==-1)templateIndex=starIndex+1,matchIndex++,searchIndex=matchIndex;else return!1;while(templateIndex<template.length&&template[templateIndex]==="*")templateIndex++;return templateIndex===template.length}function disable(){let namespaces=[...createDebug.names,...createDebug.skips.map((namespace)=>"-"+namespace)].join(",");return createDebug.enable(""),namespaces}function enabled(name){for(let skip of createDebug.skips)if(matchesTemplate(name,skip))return!1;for(let ns of createDebug.names)if(matchesTemplate(name,ns))return!0;return!1}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}function destroy(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return createDebug.enable(createDebug.load()),createDebug}module.exports=setup});var require_browser=__commonJS((exports,module)=>{exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.storage=localstorage();exports.destroy=(()=>{let warned=!1;return()=>{if(!warned)warned=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();exports.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function useColors(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let m;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(m=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(m[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function formatArgs(args){if(args[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+args[0]+(this.useColors?"%c ":" ")+"+"+module.exports.humanize(this.diff),!this.useColors)return;let c="color: "+this.color;args.splice(1,0,c,"color: inherit");let index=0,lastC=0;args[0].replace(/%[a-zA-Z%]/g,(match)=>{if(match==="%%")return;if(index++,match==="%c")lastC=index}),args.splice(lastC,0,c)}exports.log=console.debug||console.log||(()=>{});function save(namespaces){try{if(namespaces)exports.storage.setItem("debug",namespaces);else exports.storage.removeItem("debug")}catch(error){}}function load(){let r;try{r=exports.storage.getItem("debug")||exports.storage.getItem("DEBUG")}catch(error){}if(!r&&typeof process<"u"&&"env"in process)r=process.env.DEBUG;return r}function localstorage(){try{return localStorage}catch(error){}}module.exports=require_common()(exports);var{formatters}=module.exports;formatters.j=function(v){try{return JSON.stringify(v)}catch(error){return"[UnexpectedJSONParseError]: "+error.message}}});var require_node=__commonJS((exports,module)=>{var tty=__require("tty"),util=__require("util");exports.init=init;exports.log=log5;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.destroy=util.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");exports.colors=[6,2,3,4,5,1];try{let supportsColor=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(supportsColor&&(supportsColor.stderr||supportsColor).level>=2)exports.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch(error){}exports.inspectOpts=Object.keys(process.env).filter((key)=>{return/^debug_/i.test(key)}).reduce((obj,key)=>{let prop=key.substring(6).toLowerCase().replace(/_([a-z])/g,(_2,k)=>{return k.toUpperCase()}),val=process.env[key];if(/^(yes|on|true|enabled)$/i.test(val))val=!0;else if(/^(no|off|false|disabled)$/i.test(val))val=!1;else if(val==="null")val=null;else val=Number(val);return obj[prop]=val,obj},{});function useColors(){return"colors"in exports.inspectOpts?Boolean(exports.inspectOpts.colors):tty.isatty(process.stderr.fd)}function formatArgs(args){let{namespace:name,useColors:useColors2}=this;if(useColors2){let c=this.color,colorCode="\x1B[3"+(c<8?c:"8;5;"+c),prefix=` ${colorCode};1m${name} \x1B[0m`;args[0]=prefix+args[0].split(`
64
+ `).join(`
65
+ `+prefix),args.push(colorCode+"m+"+module.exports.humanize(this.diff)+"\x1B[0m")}else args[0]=getDate()+name+" "+args[0]}function getDate(){if(exports.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function log5(...args){return process.stderr.write(util.formatWithOptions(exports.inspectOpts,...args)+`
66
+ `)}function save(namespaces){if(namespaces)process.env.DEBUG=namespaces;else delete process.env.DEBUG}function load(){return process.env.DEBUG}function init(debug){debug.inspectOpts={};let keys=Object.keys(exports.inspectOpts);for(let i=0;i<keys.length;i++)debug.inspectOpts[keys[i]]=exports.inspectOpts[keys[i]]}module.exports=require_common()(exports);var{formatters}=module.exports;formatters.o=function(v){return this.inspectOpts.colors=this.useColors,util.inspect(v,this.inspectOpts).split(`
67
+ `).map((str)=>str.trim()).join(" ")};formatters.O=function(v){return this.inspectOpts.colors=this.useColors,util.inspect(v,this.inspectOpts)}});var require_src=__commonJS((exports,module)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)module.exports=require_browser();else module.exports=require_node()});async function createFallbackLogger(namespace){try{let{default:createDebug}=await Promise.resolve().then(() => __toESM(require_src(),1)),debug=createDebug(namespace);return{debug:debug.enabled?debug:void 0}}catch{return{debug:void 0}}}async function detectLogger(namespace){try{let{createLogger:createLogger5}=await import("loggily"),logger=createLogger5(namespace);if(logger.debug){let originalDebug=logger.debug;return{debug:(msg,...args)=>{let i=0,formatted=msg.replace(/%[sdOo]/g,()=>{let arg=args[i++];if(arg===void 0)return"";if(arg===null)return"null";if(typeof arg==="object")return JSON.stringify(arg);return String(arg)});originalDebug(formatted)}}}return{debug:void 0}}catch{return createFallbackLogger(namespace)}}var _logger=null,log5;var init_logger=__esm(async()=>{_logger=await detectLogger("flexily:layout");log5={get debug(){return _logger?.debug}}});function getTrace(){return _trace}var _trace=null;function isRowDirection(flexDirection){return flexDirection===FLEX_DIRECTION_ROW2||flexDirection===FLEX_DIRECTION_ROW_REVERSE2}function isReverseDirection(flexDirection){return flexDirection===FLEX_DIRECTION_ROW_REVERSE2||flexDirection===FLEX_DIRECTION_COLUMN_REVERSE2}function getLogicalEdgeValue(arr,physicalIndex,_flexDirection,direction=DIRECTION_LTR2){let isRTL=direction===DIRECTION_RTL2;if(physicalIndex===0)return isRTL?arr[5]:arr[4];else if(physicalIndex===2)return isRTL?arr[4]:arr[5];return}function resolveEdgeValue(arr,physicalIndex,flexDirection,availableSize,direction=DIRECTION_LTR2){let logicalValue=getLogicalEdgeValue(arr,physicalIndex,flexDirection,direction);if(logicalValue&&logicalValue.unit!==UNIT_UNDEFINED2)return resolveValue(logicalValue,availableSize);return resolveValue(arr[physicalIndex],availableSize)}function isEdgeAuto(arr,physicalIndex,flexDirection,direction=DIRECTION_LTR2){let logicalValue=getLogicalEdgeValue(arr,physicalIndex,flexDirection,direction);if(logicalValue&&logicalValue.unit!==UNIT_UNDEFINED2)return logicalValue.unit===UNIT_AUTO2;return arr[physicalIndex].unit===UNIT_AUTO2}function resolvePositionEdge(arr,physicalIndex,direction=DIRECTION_LTR2){let logicalValue=getLogicalEdgeValue(arr,physicalIndex,0,direction);if(logicalValue&&logicalValue.unit!==UNIT_UNDEFINED2)return logicalValue;return arr[physicalIndex]}function resolveEdgeBorderValue(arr,physicalIndex,_flexDirection,direction=DIRECTION_LTR2){let isRTL=direction===DIRECTION_RTL2,logicalSlot;if(physicalIndex===0)logicalSlot=isRTL?5:4;else if(physicalIndex===2)logicalSlot=isRTL?4:5;if(logicalSlot!==void 0&&!Number.isNaN(arr[logicalSlot]))return arr[logicalSlot];return arr[physicalIndex]}var init_layout_helpers=__esm(()=>{init_utils3()});function markSubtreeLayoutSeen(node){traversalStack.length=0,traversalStack.push(node);while(traversalStack.length>0){let current=traversalStack.pop();current._isDirty=!1,current._hasNewLayout=!0;for(let child of current.children)traversalStack.push(child)}}function countNodes(node){let count=0;traversalStack.length=0,traversalStack.push(node);while(traversalStack.length>0){let current=traversalStack.pop();count++;for(let child of current.children)traversalStack.push(child)}return count}function propagatePositionDelta(node,deltaX,deltaY){traversalStack.length=0;for(let child of node.children)traversalStack.push(child);while(traversalStack.length>0){let current=traversalStack.pop();current.flex.lastOffsetX+=deltaX,current.flex.lastOffsetY+=deltaY;for(let child of current.children)traversalStack.push(child)}}var init_layout_traversal=__esm(()=>{init_utils3()});function resetLayoutStats(){layoutNodeCalls=0,measureNodeCalls=0,layoutSizingCalls=0,layoutPositioningCalls=0,layoutCacheHits=0}function incLayoutNodeCalls(){layoutNodeCalls++}function incMeasureNodeCalls(){measureNodeCalls++}function incLayoutSizingCalls(){layoutSizingCalls++}function incLayoutPositioningCalls(){layoutPositioningCalls++}function incLayoutCacheHits(){layoutCacheHits++}var layoutNodeCalls=0,measureNodeCalls=0,layoutSizingCalls=0,layoutPositioningCalls=0,layoutCacheHits=0;function measureNode(node,availableWidth,availableHeight,direction=DIRECTION_LTR2){incMeasureNodeCalls();let{style:style2,layout}=node;if(style2.display===DISPLAY_NONE2){layout.width=0,layout.height=0;return}let marginLeft=resolveEdgeValue(style2.margin,0,style2.flexDirection,availableWidth,direction),marginTop=resolveEdgeValue(style2.margin,1,style2.flexDirection,availableWidth,direction),marginRight=resolveEdgeValue(style2.margin,2,style2.flexDirection,availableWidth,direction),marginBottom=resolveEdgeValue(style2.margin,3,style2.flexDirection,availableWidth,direction),paddingLeft=resolveEdgeValue(style2.padding,0,style2.flexDirection,availableWidth,direction),paddingTop=resolveEdgeValue(style2.padding,1,style2.flexDirection,availableWidth,direction),paddingRight=resolveEdgeValue(style2.padding,2,style2.flexDirection,availableWidth,direction),paddingBottom=resolveEdgeValue(style2.padding,3,style2.flexDirection,availableWidth,direction),borderLeft=resolveEdgeBorderValue(style2.border,0,style2.flexDirection,direction),borderTop=resolveEdgeBorderValue(style2.border,1,style2.flexDirection,direction),borderRight=resolveEdgeBorderValue(style2.border,2,style2.flexDirection,direction),borderBottom=resolveEdgeBorderValue(style2.border,3,style2.flexDirection,direction),nodeWidth;if(style2.width.unit===UNIT_POINT2)nodeWidth=style2.width.value;else if(style2.width.unit===UNIT_PERCENT2)nodeWidth=resolveValue(style2.width,availableWidth);else if(Number.isNaN(availableWidth))nodeWidth=NaN;else nodeWidth=availableWidth-marginLeft-marginRight;nodeWidth=applyMinMax(nodeWidth,style2.minWidth,style2.maxWidth,availableWidth);let nodeHeight;if(style2.height.unit===UNIT_POINT2)nodeHeight=style2.height.value;else if(style2.height.unit===UNIT_PERCENT2)nodeHeight=resolveValue(style2.height,availableHeight);else if(Number.isNaN(availableHeight))nodeHeight=NaN;else nodeHeight=availableHeight-marginTop-marginBottom;let aspectRatio=style2.aspectRatio;if(!Number.isNaN(aspectRatio)&&aspectRatio>0){let widthIsAuto=Number.isNaN(nodeWidth)||style2.width.unit===UNIT_AUTO2,heightIsAuto=Number.isNaN(nodeHeight)||style2.height.unit===UNIT_AUTO2;if(widthIsAuto&&!heightIsAuto&&!Number.isNaN(nodeHeight))nodeWidth=nodeHeight*aspectRatio,nodeWidth=applyMinMax(nodeWidth,style2.minWidth,style2.maxWidth,availableWidth);else if(heightIsAuto&&!widthIsAuto&&!Number.isNaN(nodeWidth))nodeHeight=nodeWidth/aspectRatio}nodeHeight=applyMinMax(nodeHeight,style2.minHeight,style2.maxHeight,availableHeight);let innerLeft=borderLeft+paddingLeft,innerTop=borderTop+paddingTop,innerRight=borderRight+paddingRight,innerBottom=borderBottom+paddingBottom,minInnerWidth=innerLeft+innerRight,minInnerHeight=innerTop+innerBottom;if(!Number.isNaN(nodeWidth)&&nodeWidth<minInnerWidth)nodeWidth=minInnerWidth;if(!Number.isNaN(nodeHeight)&&nodeHeight<minInnerHeight)nodeHeight=minInnerHeight;let contentWidth=Number.isNaN(nodeWidth)?NaN:Math.max(0,nodeWidth-innerLeft-innerRight),contentHeight=Number.isNaN(nodeHeight)?NaN:Math.max(0,nodeHeight-innerTop-innerBottom);if(node.hasMeasureFunc()&&node.children.length===0){let widthIsAuto=style2.width.unit===UNIT_AUTO2||style2.width.unit===UNIT_UNDEFINED2||Number.isNaN(nodeWidth),heightIsAuto=style2.height.unit===UNIT_AUTO2||style2.height.unit===UNIT_UNDEFINED2||Number.isNaN(nodeHeight),widthMode=widthIsAuto?MEASURE_MODE_AT_MOST2:MEASURE_MODE_EXACTLY2,heightMode=heightIsAuto?MEASURE_MODE_UNDEFINED2:MEASURE_MODE_EXACTLY2,measureWidth=Number.isNaN(contentWidth)?1/0:contentWidth,measureHeight=Number.isNaN(contentHeight)?1/0:contentHeight,measured=node.cachedMeasure(measureWidth,widthMode,measureHeight,heightMode);if(widthIsAuto)nodeWidth=measured.width+innerLeft+innerRight;if(heightIsAuto)nodeHeight=measured.height+innerTop+innerBottom;layout.width=Math.round(nodeWidth),layout.height=Math.round(nodeHeight);return}if(node.children.length===0){if(Number.isNaN(nodeWidth))nodeWidth=innerLeft+innerRight;if(Number.isNaN(nodeHeight))nodeHeight=innerTop+innerBottom;layout.width=Math.round(nodeWidth),layout.height=Math.round(nodeHeight);return}let relativeChildCount=0;for(let c of node.children){if(c.style.display===DISPLAY_NONE2)continue;if(c.style.positionType!==POSITION_TYPE_ABSOLUTE2)relativeChildCount++}if(relativeChildCount===0){if(Number.isNaN(nodeWidth))nodeWidth=minInnerWidth;if(Number.isNaN(nodeHeight))nodeHeight=minInnerHeight;layout.width=Math.round(nodeWidth),layout.height=Math.round(nodeHeight);return}let isRow=isRowDirection(style2.flexDirection),mainAxisSize=isRow?contentWidth:contentHeight,crossAxisSize=isRow?contentHeight:contentWidth,mainGap=isRow?style2.gap[0]:style2.gap[1],totalMainSize=0,maxCrossSize=0,itemCount=0;for(let child of node.children){if(child.style.display===DISPLAY_NONE2)continue;if(child.style.positionType===POSITION_TYPE_ABSOLUTE2)continue;let childStyle=child.style,childMarginMain=isRow?resolveEdgeValue(childStyle.margin,0,style2.flexDirection,contentWidth,direction)+resolveEdgeValue(childStyle.margin,2,style2.flexDirection,contentWidth,direction):resolveEdgeValue(childStyle.margin,1,style2.flexDirection,contentWidth,direction)+resolveEdgeValue(childStyle.margin,3,style2.flexDirection,contentWidth,direction),childMarginCross=isRow?resolveEdgeValue(childStyle.margin,1,style2.flexDirection,contentWidth,direction)+resolveEdgeValue(childStyle.margin,3,style2.flexDirection,contentWidth,direction):resolveEdgeValue(childStyle.margin,0,style2.flexDirection,contentWidth,direction)+resolveEdgeValue(childStyle.margin,2,style2.flexDirection,contentWidth,direction),childAvailW=isRow?NaN:crossAxisSize,childAvailH=isRow?crossAxisSize:NaN,measuredW=0,measuredH=0,cached=child.getCachedLayout(childAvailW,childAvailH);if(cached)incLayoutCacheHits();else{let savedW=child.layout.width,savedH=child.layout.height;measureNode(child,childAvailW,childAvailH,direction),measuredW=child.layout.width,measuredH=child.layout.height,child.layout.width=savedW,child.layout.height=savedH,child.setCachedLayout(childAvailW,childAvailH,measuredW,measuredH)}let childMainSize=cached?isRow?cached.width:cached.height:isRow?measuredW:measuredH,childCrossSize=cached?isRow?cached.height:cached.width:isRow?measuredH:measuredW;totalMainSize+=childMainSize+childMarginMain,maxCrossSize=Math.max(maxCrossSize,childCrossSize+childMarginCross),itemCount++}if(itemCount>1)totalMainSize+=mainGap*(itemCount-1);if(Number.isNaN(nodeWidth))nodeWidth=(isRow?totalMainSize:maxCrossSize)+innerLeft+innerRight;if(Number.isNaN(nodeHeight))nodeHeight=(isRow?maxCrossSize:totalMainSize)+innerTop+innerBottom;nodeWidth=applyMinMax(nodeWidth,style2.minWidth,style2.maxWidth,availableWidth),nodeHeight=applyMinMax(nodeHeight,style2.minHeight,style2.maxHeight,availableHeight),layout.width=Math.round(nodeWidth),layout.height=Math.round(nodeHeight)}var init_layout_measure=__esm(()=>{init_utils3();init_layout_helpers()});function growLineArrays(needed){let newSize=Math.max(needed,MAX_FLEX_LINES*2);MAX_FLEX_LINES=newSize,_lineCrossSizes=new Float64Array(newSize),_lineCrossOffsets=new Float64Array(newSize),_lineLengths=new Uint16Array(newSize),_lineJustifyStarts=new Float64Array(newSize),_lineItemSpacings=new Float64Array(newSize);while(_lineChildren.length<newSize)_lineChildren.push([])}function enterLayout(){if(_layoutDepth++===0)return null;return{crossSizes:_lineCrossSizes.slice(),crossOffsets:_lineCrossOffsets.slice(),lengths:_lineLengths.slice(),justifyStarts:_lineJustifyStarts.slice(),itemSpacings:_lineItemSpacings.slice(),children:_lineChildren.map((arr)=>arr.slice()),maxLines:MAX_FLEX_LINES}}function exitLayout(saved){if(_layoutDepth--,!saved)return;MAX_FLEX_LINES=saved.maxLines,_lineCrossSizes=saved.crossSizes,_lineCrossOffsets=saved.crossOffsets,_lineLengths=saved.lengths,_lineJustifyStarts=saved.justifyStarts,_lineItemSpacings=saved.itemSpacings,_lineChildren=saved.children}function breakIntoLines(parent,relativeCount,mainAxisSize,mainGap,wrap){if(wrap===WRAP_NO_WRAP2||Number.isNaN(mainAxisSize)||relativeCount===0){let lineArr=_lineChildren[0],idx=0;for(let child of parent.children)if(child.flex.relativeIndex>=0)child.flex.lineIndex=0,lineArr[idx++]=child;return lineArr.length=idx,_lineLengths[0]=relativeCount,_lineCrossSizes[0]=0,_lineCrossOffsets[0]=0,1}let lineIndex=0,lineMainSize=0,lineChildCount=0,lineChildIdx=0;for(let child of parent.children){if(child.flex.relativeIndex<0)continue;let flex=child.flex,childMainSize=Math.max(flex.minMain,Math.min(flex.maxMain,flex.baseSize))+flex.mainMargin,gapIfNotFirst=lineChildCount>0?mainGap:0;if(lineChildCount>0&&lineMainSize+gapIfNotFirst+childMainSize>mainAxisSize){if(_lineChildren[lineIndex].length=lineChildIdx,_lineLengths[lineIndex]=lineChildCount,lineIndex++,lineIndex>=MAX_FLEX_LINES)growLineArrays(lineIndex+16);lineChildIdx=0,lineMainSize=childMainSize,lineChildCount=1}else lineMainSize+=gapIfNotFirst+childMainSize,lineChildCount++;flex.lineIndex=lineIndex,_lineChildren[lineIndex][lineChildIdx++]=child}if(lineChildCount>0)_lineChildren[lineIndex].length=lineChildIdx,_lineLengths[lineIndex]=lineChildCount,lineIndex++;let numLines=lineIndex;for(let i=0;i<numLines;i++)_lineCrossSizes[i]=0,_lineCrossOffsets[i]=0;if(wrap===WRAP_WRAP_REVERSE2&&numLines>1){for(let i=0;i<Math.floor(numLines/2);i++){let j=numLines-1-i,lineI=_lineChildren[i],lineJ=_lineChildren[j],lenI=lineI.length,lenJ=lineJ.length,maxLen=Math.max(lenI,lenJ);for(let k=0;k<maxLen;k++){let hasI=k<lenI,hasJ=k<lenJ,tmpI=hasI?lineI[k]:null,tmpJ=hasJ?lineJ[k]:null;if(hasJ)lineI[k]=tmpJ;if(hasI)lineJ[k]=tmpI}lineI.length=lenJ,lineJ.length=lenI}for(let i=0;i<numLines;i++){let lc=_lineChildren[i];for(let c=0;c<lc.length;c++)lc[c].flex.lineIndex=i}}return numLines}function distributeFlexSpaceForLine(lineChildren,initialFreeSpace){let isGrowing=initialFreeSpace>0;if(initialFreeSpace===0)return;let childCount=lineChildren.length;if(childCount===0)return;if(childCount===1){let flex=lineChildren[0].flex;if(isGrowing?flex.flexGrow>0:flex.flexShrink>0){let target=flex.baseSize+initialFreeSpace;flex.mainSize=Math.max(flex.minMain,Math.min(flex.maxMain,target))}return}let totalBase=0;for(let i=0;i<childCount;i++)totalBase+=lineChildren[i].flex.baseSize;let containerInner=initialFreeSpace+totalBase;for(let i=0;i<childCount;i++)lineChildren[i].flex.frozen=!1;let freeSpace=initialFreeSpace,iterations=0,maxIterations=childCount+1;while(iterations++<maxIterations){let totalFlex=0;for(let i=0;i<childCount;i++){let flex=lineChildren[i].flex;if(flex.frozen)continue;if(isGrowing)totalFlex+=flex.flexGrow;else totalFlex+=flex.flexShrink*flex.baseSize}if(totalFlex===0)break;let effectiveFreeSpace=freeSpace;if(isGrowing&&totalFlex<1)effectiveFreeSpace=freeSpace*totalFlex;let totalViolation=0;for(let i=0;i<childCount;i++){let flex=lineChildren[i].flex;if(flex.frozen)continue;let flexFactor=isGrowing?flex.flexGrow:flex.flexShrink*flex.baseSize,ratio=totalFlex>0?flexFactor/totalFlex:0,target=flex.baseSize+effectiveFreeSpace*ratio,clamped=Math.max(flex.minMain,Math.min(flex.maxMain,target));totalViolation+=clamped-target,flex.mainSize=clamped}let anyFrozen=!1;if(Math.abs(totalViolation)<EPSILON_FLOAT){for(let i=0;i<childCount;i++)lineChildren[i].flex.frozen=!0;break}else if(totalViolation>0)for(let i=0;i<childCount;i++){let flex=lineChildren[i].flex;if(flex.frozen)continue;let target=flex.baseSize+(isGrowing?flex.flexGrow:flex.flexShrink*flex.baseSize)/totalFlex*effectiveFreeSpace;if(flex.mainSize>target+EPSILON_FLOAT)flex.frozen=!0,anyFrozen=!0}else for(let i=0;i<childCount;i++){let flex=lineChildren[i].flex;if(flex.frozen)continue;let flexFactor=isGrowing?flex.flexGrow:flex.flexShrink*flex.baseSize,target=flex.baseSize+flexFactor/totalFlex*effectiveFreeSpace;if(flex.mainSize<target-EPSILON_FLOAT)flex.frozen=!0,anyFrozen=!0}if(!anyFrozen)break;let frozenSpace=0,unfrozenBase=0;for(let i=0;i<childCount;i++){let flex=lineChildren[i].flex;if(flex.frozen)frozenSpace+=flex.mainSize;else unfrozenBase+=flex.baseSize}freeSpace=containerInner-frozenSpace-unfrozenBase}}var MAX_FLEX_LINES=32,_lineCrossSizes,_lineCrossOffsets,_lineLengths,_lineChildren,_lineJustifyStarts,_lineItemSpacings,_layoutDepth=0,EPSILON_FLOAT=0.001;var init_layout_flex_lines=__esm(()=>{_lineCrossSizes=new Float64Array(MAX_FLEX_LINES),_lineCrossOffsets=new Float64Array(MAX_FLEX_LINES),_lineLengths=new Uint16Array(MAX_FLEX_LINES),_lineChildren=Array.from({length:MAX_FLEX_LINES},()=>[]),_lineJustifyStarts=new Float64Array(MAX_FLEX_LINES),_lineItemSpacings=new Float64Array(MAX_FLEX_LINES)});function computeLayout(root,availableWidth,availableHeight,direction=DIRECTION_LTR2){let saved=enterLayout();try{resetLayoutStats(),getTrace()?.resetCounter(),root.resetLayoutCache(),layoutNode(root,availableWidth,availableHeight,0,0,0,0,direction)}finally{exitLayout(saved)}}function layoutNode(node,availableWidth,availableHeight,offsetX,offsetY,absX,absY,direction=DIRECTION_LTR2){if(incLayoutNodeCalls(),offsetX===0&&offsetY===0&&absX===0&&absY===0&&node.children.length>0)incLayoutSizingCalls();else incLayoutPositioningCalls();log5.debug?.("layoutNode called: availW=%d, availH=%d, offsetX=%d, offsetY=%d, absX=%d, absY=%d, children=%d",availableWidth,availableHeight,offsetX,offsetY,absX,absY,node.children.length);let _t=getTrace(),_tn=_t?.nextNode()??0;_t?.layoutEnter(_tn,availableWidth,availableHeight,node.isDirty(),node.children.length);let{style:style2,layout}=node;if(style2.display===DISPLAY_NONE2){layout.left=0,layout.top=0,layout.width=0,layout.height=0;return}let flex=node.flex;if(flex.layoutValid&&!node.isDirty()&&Object.is(flex.lastAvailW,availableWidth)&&Object.is(flex.lastAvailH,availableHeight)&&flex.lastDir===direction&&flex.lastAbsX===absX&&flex.lastAbsY===absY){_t?.fingerprintHit(_tn,availableWidth,availableHeight);let deltaX=offsetX-flex.lastOffsetX,deltaY=offsetY-flex.lastOffsetY;if(deltaX!==0||deltaY!==0)layout.left+=deltaX,layout.top+=deltaY,flex.lastOffsetX=offsetX,flex.lastOffsetY=offsetY,propagatePositionDelta(node,deltaX,deltaY);return}_t?.fingerprintMiss(_tn,availableWidth,availableHeight,{layoutValid:flex.layoutValid,isDirty:node.isDirty(),sameW:Object.is(flex.lastAvailW,availableWidth),sameH:Object.is(flex.lastAvailH,availableHeight),sameDir:flex.lastDir===direction,sameAbsX:flex.lastAbsX===absX,sameAbsY:flex.lastAbsY===absY});let marginLeft=resolveEdgeValue(style2.margin,0,style2.flexDirection,availableWidth,direction),marginTop=resolveEdgeValue(style2.margin,1,style2.flexDirection,availableWidth,direction),marginRight=resolveEdgeValue(style2.margin,2,style2.flexDirection,availableWidth,direction),marginBottom=resolveEdgeValue(style2.margin,3,style2.flexDirection,availableWidth,direction),paddingLeft=resolveEdgeValue(style2.padding,0,style2.flexDirection,availableWidth,direction),paddingTop=resolveEdgeValue(style2.padding,1,style2.flexDirection,availableWidth,direction),paddingRight=resolveEdgeValue(style2.padding,2,style2.flexDirection,availableWidth,direction),paddingBottom=resolveEdgeValue(style2.padding,3,style2.flexDirection,availableWidth,direction),borderLeft=resolveEdgeBorderValue(style2.border,0,style2.flexDirection,direction),borderTop=resolveEdgeBorderValue(style2.border,1,style2.flexDirection,direction),borderRight=resolveEdgeBorderValue(style2.border,2,style2.flexDirection,direction),borderBottom=resolveEdgeBorderValue(style2.border,3,style2.flexDirection,direction),nodeWidth;if(style2.width.unit===UNIT_POINT2)nodeWidth=style2.width.value;else if(style2.width.unit===UNIT_PERCENT2)nodeWidth=resolveValue(style2.width,availableWidth);else if(Number.isNaN(availableWidth))nodeWidth=NaN;else nodeWidth=availableWidth-marginLeft-marginRight;nodeWidth=applyMinMax(nodeWidth,style2.minWidth,style2.maxWidth,availableWidth);let nodeHeight;if(style2.height.unit===UNIT_POINT2)nodeHeight=style2.height.value;else if(style2.height.unit===UNIT_PERCENT2)nodeHeight=resolveValue(style2.height,availableHeight);else if(Number.isNaN(availableHeight))nodeHeight=NaN;else nodeHeight=availableHeight-marginTop-marginBottom;let aspectRatio=style2.aspectRatio;if(!Number.isNaN(aspectRatio)&&aspectRatio>0){let widthIsAuto=Number.isNaN(nodeWidth)||style2.width.unit===UNIT_AUTO2,heightIsAuto=Number.isNaN(nodeHeight)||style2.height.unit===UNIT_AUTO2;if(widthIsAuto&&!heightIsAuto&&!Number.isNaN(nodeHeight))nodeWidth=nodeHeight*aspectRatio,nodeWidth=applyMinMax(nodeWidth,style2.minWidth,style2.maxWidth,availableWidth);else if(heightIsAuto&&!widthIsAuto&&!Number.isNaN(nodeWidth))nodeHeight=nodeWidth/aspectRatio}nodeHeight=applyMinMax(nodeHeight,style2.minHeight,style2.maxHeight,availableHeight);let innerLeft=borderLeft+paddingLeft,innerTop=borderTop+paddingTop,innerRight=borderRight+paddingRight,innerBottom=borderBottom+paddingBottom,minInnerWidth=innerLeft+innerRight,minInnerHeight=innerTop+innerBottom;if(!Number.isNaN(nodeWidth)&&nodeWidth<minInnerWidth)nodeWidth=minInnerWidth;if(!Number.isNaN(nodeHeight)&&nodeHeight<minInnerHeight)nodeHeight=minInnerHeight;let contentWidth=Number.isNaN(nodeWidth)?NaN:Math.max(0,nodeWidth-innerLeft-innerRight),contentHeight=Number.isNaN(nodeHeight)?NaN:Math.max(0,nodeHeight-innerTop-innerBottom),parentPosOffsetX=0,parentPosOffsetY=0;if(style2.positionType===POSITION_TYPE_RELATIVE2){let leftPos=resolvePositionEdge(style2.position,0,direction),topPos=style2.position[1],rightPos=resolvePositionEdge(style2.position,2,direction),bottomPos=style2.position[3];if(leftPos.unit!==UNIT_UNDEFINED2)parentPosOffsetX=resolveValue(leftPos,availableWidth);else if(rightPos.unit!==UNIT_UNDEFINED2)parentPosOffsetX=-resolveValue(rightPos,availableWidth);if(topPos.unit!==UNIT_UNDEFINED2)parentPosOffsetY=resolveValue(topPos,availableHeight);else if(bottomPos.unit!==UNIT_UNDEFINED2)parentPosOffsetY=-resolveValue(bottomPos,availableHeight)}if(node.hasMeasureFunc()&&node.children.length===0){let widthIsAuto=style2.width.unit===UNIT_AUTO2||style2.width.unit===UNIT_UNDEFINED2||Number.isNaN(nodeWidth),heightIsAuto=style2.height.unit===UNIT_AUTO2||style2.height.unit===UNIT_UNDEFINED2||Number.isNaN(nodeHeight),widthMode=widthIsAuto?MEASURE_MODE_AT_MOST2:MEASURE_MODE_EXACTLY2,heightMode=heightIsAuto?MEASURE_MODE_UNDEFINED2:MEASURE_MODE_EXACTLY2,measureWidth=Number.isNaN(contentWidth)?1/0:contentWidth,measureHeight=Number.isNaN(contentHeight)?1/0:contentHeight,measured=node.cachedMeasure(measureWidth,widthMode,measureHeight,heightMode);if(widthIsAuto)nodeWidth=measured.width+innerLeft+innerRight;if(heightIsAuto)nodeHeight=measured.height+innerTop+innerBottom;layout.width=Math.round(nodeWidth),layout.height=Math.round(nodeHeight),layout.left=Math.round(offsetX+marginLeft),layout.top=Math.round(offsetY+marginTop);return}if(node.children.length===0){if(Number.isNaN(nodeWidth))nodeWidth=innerLeft+innerRight;if(Number.isNaN(nodeHeight))nodeHeight=innerTop+innerBottom;layout.width=Math.round(nodeWidth),layout.height=Math.round(nodeHeight),layout.left=Math.round(offsetX+marginLeft),layout.top=Math.round(offsetY+marginTop);return}let isRow=isRowDirection(style2.flexDirection),isReverse=isReverseDirection(style2.flexDirection),effectiveReverse=isRow?direction===DIRECTION_RTL2!==isReverse:isReverse,mainAxisSize=isRow?contentWidth:contentHeight,crossAxisSize=isRow?contentHeight:contentWidth,mainGap=isRow?style2.gap[0]:style2.gap[1],totalBaseMain=0,relativeCount=0,totalAutoMargins=0,hasBaselineAlignment=style2.alignItems===ALIGN_BASELINE2;for(let child of node.children){if(child.style.display===DISPLAY_NONE2||child.style.positionType===POSITION_TYPE_ABSOLUTE2){child.flex.relativeIndex=-1;continue}child.flex.relativeIndex=relativeCount++;let{style:childStyle,flex:cflex}=child,mainStartIndex=isRow?effectiveReverse?2:0:isReverse?3:1,mainEndIndex=isRow?effectiveReverse?0:2:isReverse?1:3;cflex.mainStartMarginAuto=isEdgeAuto(childStyle.margin,mainStartIndex,style2.flexDirection,direction),cflex.mainEndMarginAuto=isEdgeAuto(childStyle.margin,mainEndIndex,style2.flexDirection,direction),cflex.marginL=resolveEdgeValue(childStyle.margin,0,style2.flexDirection,contentWidth,direction),cflex.marginT=resolveEdgeValue(childStyle.margin,1,style2.flexDirection,contentWidth,direction),cflex.marginR=resolveEdgeValue(childStyle.margin,2,style2.flexDirection,contentWidth,direction),cflex.marginB=resolveEdgeValue(childStyle.margin,3,style2.flexDirection,contentWidth,direction),cflex.mainStartMarginValue=cflex.mainStartMarginAuto?0:isRow?effectiveReverse?cflex.marginR:cflex.marginL:isReverse?cflex.marginB:cflex.marginT,cflex.mainEndMarginValue=cflex.mainEndMarginAuto?0:isRow?effectiveReverse?cflex.marginL:cflex.marginR:isReverse?cflex.marginT:cflex.marginB,cflex.mainMargin=cflex.mainStartMarginValue+cflex.mainEndMarginValue;let baseSize=0;if(childStyle.flexBasis.unit===UNIT_POINT2)baseSize=childStyle.flexBasis.value;else if(childStyle.flexBasis.unit===UNIT_PERCENT2)baseSize=Number.isNaN(mainAxisSize)?0:mainAxisSize*(childStyle.flexBasis.value/100);else{let sizeVal=isRow?childStyle.width:childStyle.height;if(sizeVal.unit===UNIT_POINT2)baseSize=sizeVal.value;else if(sizeVal.unit===UNIT_PERCENT2)baseSize=Number.isNaN(mainAxisSize)?0:mainAxisSize*(sizeVal.value/100);else if(child.hasMeasureFunc()){let crossMargin=isRow?cflex.marginT+cflex.marginB:cflex.marginL+cflex.marginR,availCross=crossAxisSize-crossMargin,wantMaxContent=childStyle.flexGrow>0,mW=isRow?wantMaxContent?1/0:Number.isNaN(mainAxisSize)?1/0:mainAxisSize:Number.isNaN(availCross)?1/0:availCross,mH=isRow?Number.isNaN(availCross)?1/0:availCross:wantMaxContent?1/0:Number.isNaN(mainAxisSize)?1/0:mainAxisSize,mWMode=isRow?wantMaxContent?MEASURE_MODE_UNDEFINED2:MEASURE_MODE_AT_MOST2:Number.isNaN(availCross)?MEASURE_MODE_UNDEFINED2:MEASURE_MODE_AT_MOST2,mHMode=isRow?MEASURE_MODE_UNDEFINED2:wantMaxContent?MEASURE_MODE_UNDEFINED2:MEASURE_MODE_AT_MOST2,measured=child.cachedMeasure(mW,mWMode,mH,mHMode);baseSize=isRow?measured.width:measured.height}else if(child.children.length>0){let sizingW=isRow?NaN:crossAxisSize,sizingH=isRow?crossAxisSize:NaN,cached=child.getCachedLayout(sizingW,sizingH);if(cached)incLayoutCacheHits(),_t?.cacheHit(_tn,sizingW,sizingH,cached.width,cached.height),baseSize=isRow?cached.width:cached.height;else{_t?.cacheMiss(_tn,sizingW,sizingH);let savedW=child.layout.width,savedH=child.layout.height;measureNode(child,sizingW,sizingH,direction);let measuredW=child.layout.width,measuredH=child.layout.height;child.layout.width=savedW,child.layout.height=savedH,_t?.measureSaveRestore(_tn,savedW,savedH,measuredW,measuredH),baseSize=isRow?measuredW:measuredH,child.setCachedLayout(sizingW,sizingH,measuredW,measuredH)}}else{let parentWidth=isRow?mainAxisSize:crossAxisSize,childPadding=isRow?resolveEdgeValue(childStyle.padding,0,childStyle.flexDirection,parentWidth,direction)+resolveEdgeValue(childStyle.padding,2,childStyle.flexDirection,parentWidth,direction):resolveEdgeValue(childStyle.padding,1,childStyle.flexDirection,parentWidth,direction)+resolveEdgeValue(childStyle.padding,3,childStyle.flexDirection,parentWidth,direction),childBorder=isRow?resolveEdgeBorderValue(childStyle.border,0,childStyle.flexDirection,direction)+resolveEdgeBorderValue(childStyle.border,2,childStyle.flexDirection,direction):resolveEdgeBorderValue(childStyle.border,1,childStyle.flexDirection,direction)+resolveEdgeBorderValue(childStyle.border,3,childStyle.flexDirection,direction);baseSize=childPadding+childBorder}}let minVal=isRow?childStyle.minWidth:childStyle.minHeight,maxVal=isRow?childStyle.maxWidth:childStyle.maxHeight;cflex.minMain=minVal.unit!==UNIT_UNDEFINED2?resolveValue(minVal,mainAxisSize):0,cflex.maxMain=maxVal.unit!==UNIT_UNDEFINED2?resolveValue(maxVal,mainAxisSize):1/0,cflex.flexGrow=childStyle.flexGrow;let shrink=childStyle.flexShrink;if(childStyle.overflow!==OVERFLOW_VISIBLE2)shrink=Math.max(shrink,1);if(child.hasMeasureFunc()&&childStyle.flexGrow>0)shrink=Math.max(shrink,1);if(cflex.flexShrink=shrink,cflex.baseSize=baseSize,cflex.mainSize=baseSize,cflex.frozen=!1,totalBaseMain+=baseSize+cflex.mainMargin,cflex.mainStartMarginAuto)totalAutoMargins++;if(cflex.mainEndMarginAuto)totalAutoMargins++;if(!hasBaselineAlignment&&childStyle.alignSelf===ALIGN_BASELINE2)hasBaselineAlignment=!0}if(log5.debug?.("layoutNode: node.children=%d, relativeCount=%d",node.children.length,relativeCount),relativeCount>0){let numLines=breakIntoLines(node,relativeCount,mainAxisSize,mainGap,style2.flexWrap),crossGap=isRow?style2.gap[1]:style2.gap[0];for(let lineIdx=0;lineIdx<numLines;lineIdx++){let lineChildren=_lineChildren[lineIdx],lineLength=lineChildren.length;if(lineLength===0)continue;let lineTotalBaseMain=0;for(let i=0;i<lineLength;i++){let c=lineChildren[i];lineTotalBaseMain+=c.flex.baseSize+c.flex.mainMargin}let lineTotalGaps=lineLength>1?mainGap*(lineLength-1):0,effectiveMainSize=mainAxisSize;if(Number.isNaN(mainAxisSize)){let maxMainVal=isRow?style2.maxWidth:style2.maxHeight;if(maxMainVal.unit!==UNIT_UNDEFINED2){let maxMain=resolveValue(maxMainVal,isRow?availableWidth:availableHeight);if(!Number.isNaN(maxMain)&&lineTotalBaseMain+lineTotalGaps>maxMain){let innerMain=isRow?innerLeft+innerRight:innerTop+innerBottom;effectiveMainSize=maxMain-innerMain}}}if(!Number.isNaN(effectiveMainSize)){let adjustedFreeSpace=effectiveMainSize-lineTotalBaseMain-lineTotalGaps;distributeFlexSpaceForLine(lineChildren,adjustedFreeSpace)}for(let i=0;i<lineLength;i++){let f=lineChildren[i].flex;f.mainSize=Math.max(f.minMain,Math.min(f.maxMain,f.mainSize))}}for(let lineIdx=0;lineIdx<numLines;lineIdx++){let lineChildren=_lineChildren[lineIdx],lineLength=lineChildren.length;if(lineLength===0){_lineJustifyStarts[lineIdx]=0,_lineItemSpacings[lineIdx]=mainGap;continue}let lineUsedMain=0,lineAutoMargins=0;for(let i=0;i<lineLength;i++){let c=lineChildren[i];if(lineUsedMain+=c.flex.mainSize+c.flex.mainMargin,c.flex.mainStartMarginAuto)lineAutoMargins++;if(c.flex.mainEndMarginAuto)lineAutoMargins++}let lineGaps=lineLength>1?mainGap*(lineLength-1):0;lineUsedMain+=lineGaps;let lineRemainingSpace=Number.isNaN(mainAxisSize)?0:mainAxisSize-lineUsedMain,lineHasAutoMargins=lineAutoMargins>0;if(lineHasAutoMargins){let autoMarginValue=Math.max(0,lineRemainingSpace)/lineAutoMargins;for(let i=0;i<lineLength;i++){let child=lineChildren[i];if(child.flex.mainStartMarginAuto)child.flex.mainStartMarginValue=autoMarginValue;if(child.flex.mainEndMarginAuto)child.flex.mainEndMarginValue=autoMarginValue}}let lineStartOffset=0,lineItemSpacing=mainGap;if(!lineHasAutoMargins)switch(style2.justifyContent){case JUSTIFY_FLEX_END2:lineStartOffset=lineRemainingSpace;break;case JUSTIFY_CENTER2:lineStartOffset=lineRemainingSpace/2;break;case JUSTIFY_SPACE_BETWEEN2:if(lineLength>1&&lineRemainingSpace>0)lineItemSpacing=mainGap+lineRemainingSpace/(lineLength-1);break;case JUSTIFY_SPACE_AROUND2:if(lineLength>0&&lineRemainingSpace>0){let extraSpace=lineRemainingSpace/lineLength;lineStartOffset=extraSpace/2,lineItemSpacing=mainGap+extraSpace}break;case JUSTIFY_SPACE_EVENLY2:if(lineLength>0&&lineRemainingSpace>0){let extraSpace=lineRemainingSpace/(lineLength+1);lineStartOffset=extraSpace,lineItemSpacing=mainGap+extraSpace}break}_lineJustifyStarts[lineIdx]=lineStartOffset,_lineItemSpacings[lineIdx]=lineItemSpacing}let startOffset=_lineJustifyStarts[0],itemSpacing=_lineItemSpacings[0],maxBaseline=0,baselineZoneHeight=0,alignItemsIsBaseline=style2.alignItems===ALIGN_BASELINE2;if(hasBaselineAlignment&&isRow){let maxChildHeight=0;for(let child of node.children){if(child.flex.relativeIndex<0)continue;let childStyle=child.style,topMargin=child.flex.marginT,childWidth,childHeight,widthDim=childStyle.width,heightDim=childStyle.height;if(widthDim.unit===UNIT_POINT2)childWidth=widthDim.value;else if(widthDim.unit===UNIT_PERCENT2&&!Number.isNaN(mainAxisSize))childWidth=mainAxisSize*(widthDim.value/100);else childWidth=child.flex.mainSize;if(heightDim.unit===UNIT_POINT2)childHeight=heightDim.value;else if(heightDim.unit===UNIT_PERCENT2&&!Number.isNaN(crossAxisSize))childHeight=crossAxisSize*(heightDim.value/100);else{let cached=child.getCachedLayout(child.flex.mainSize,NaN);if(cached)incLayoutCacheHits(),_t?.cacheHit(_tn,child.flex.mainSize,NaN,cached.width,cached.height),childWidth=cached.width,childHeight=cached.height;else{_t?.cacheMiss(_tn,child.flex.mainSize,NaN);let savedW=child.layout.width,savedH=child.layout.height;measureNode(child,child.flex.mainSize,NaN,direction),childWidth=child.layout.width,childHeight=child.layout.height,child.layout.width=savedW,child.layout.height=savedH,_t?.measureSaveRestore(_tn,savedW,savedH,childWidth,childHeight),child.setCachedLayout(child.flex.mainSize,NaN,childWidth,childHeight)}}if(child.baselineFunc!==null)child.flex.baseline=topMargin+child.baselineFunc(childWidth,childHeight);else child.flex.baseline=topMargin+childHeight;if(maxChildHeight=Math.max(maxChildHeight,topMargin+childHeight+child.flex.marginB),alignItemsIsBaseline||childStyle.alignSelf===ALIGN_BASELINE2)maxBaseline=Math.max(maxBaseline,child.flex.baseline)}baselineZoneHeight=Math.max(maxBaseline,maxChildHeight)}let cumulativeCrossOffset=0,isWrapReverse=style2.flexWrap===WRAP_WRAP_REVERSE2;for(let lineIdx=0;lineIdx<numLines;lineIdx++){_lineCrossOffsets[lineIdx]=cumulativeCrossOffset;let lineChildren=_lineChildren[lineIdx],lineLength=lineChildren.length,maxLineCross=0;for(let i=0;i<lineLength;i++){let child=lineChildren[i],childStyle=child.style,crossDim=isRow?childStyle.height:childStyle.width,crossMarginStart=isRow?child.flex.marginT:child.flex.marginL,crossMarginEnd=isRow?child.flex.marginB:child.flex.marginR,childCross=0;if(crossDim.unit===UNIT_POINT2)childCross=crossDim.value;else if(crossDim.unit===UNIT_PERCENT2&&!Number.isNaN(crossAxisSize))childCross=crossAxisSize*(crossDim.value/100);else if(child.hasMeasureFunc()){let crossMargin=crossMarginStart+crossMarginEnd,availCross=Number.isNaN(crossAxisSize)?1/0:crossAxisSize-crossMargin,childMainSize=child.flex.mainSize,mW=isRow?childMainSize:availCross,mH=isRow?availCross:childMainSize,mWMode=Number.isNaN(mW)?MEASURE_MODE_UNDEFINED2:MEASURE_MODE_AT_MOST2,mHMode=Number.isNaN(mH)?MEASURE_MODE_UNDEFINED2:MEASURE_MODE_AT_MOST2,measured=child.cachedMeasure(Number.isNaN(mW)?1/0:mW,mWMode,Number.isNaN(mH)?1/0:mH,mHMode);if(measured)childCross=isRow?measured.height:measured.width}else if(child.children.length>0){let savedW=child.layout.width,savedH=child.layout.height;measureNode(child,NaN,NaN,direction),childCross=isRow?child.layout.height:child.layout.width,child.layout.width=savedW,child.layout.height=savedH}maxLineCross=Math.max(maxLineCross,childCross+crossMarginStart+crossMarginEnd)}let lineCrossSize=maxLineCross;_lineCrossSizes[lineIdx]=lineCrossSize,cumulativeCrossOffset+=lineCrossSize+crossGap}if(!Number.isNaN(crossAxisSize)&&numLines>0){let totalLineCrossSize=cumulativeCrossOffset-crossGap,freeSpace=crossAxisSize-totalLineCrossSize;switch(style2.alignContent){case ALIGN_FLEX_END2:for(let i=0;i<numLines;i++)_lineCrossOffsets[i]+=freeSpace;break;case ALIGN_CENTER2:{let centerOffset=freeSpace/2;for(let i=0;i<numLines;i++)_lineCrossOffsets[i]+=centerOffset}break;case ALIGN_SPACE_BETWEEN2:if(freeSpace>0&&numLines>1){let gap=freeSpace/(numLines-1);for(let i=1;i<numLines;i++)_lineCrossOffsets[i]+=gap*i}break;case ALIGN_SPACE_AROUND2:if(freeSpace>0){let halfGap=freeSpace/(numLines*2);for(let i=0;i<numLines;i++)_lineCrossOffsets[i]+=halfGap+halfGap*2*i}else{let centerOffset=freeSpace/2;for(let i=0;i<numLines;i++)_lineCrossOffsets[i]+=centerOffset}break;case ALIGN_SPACE_EVENLY:if(freeSpace>0&&numLines>0){let gap=freeSpace/(numLines+1);for(let i=0;i<numLines;i++)_lineCrossOffsets[i]+=gap*(i+1)}else if(freeSpace<0){let centerOffset=freeSpace/2;for(let i=0;i<numLines;i++)_lineCrossOffsets[i]+=centerOffset}break;case ALIGN_STRETCH2:if(freeSpace>0&&numLines>0){let extraPerLine=freeSpace/numLines;for(let i=0;i<numLines;i++)if(_lineCrossSizes[i]+=extraPerLine,i>0)_lineCrossOffsets[i]=_lineCrossOffsets[i-1]+_lineCrossSizes[i-1]+crossGap}break}if(isWrapReverse){let totalLineCrossSize2=0;for(let i=0;i<numLines;i++)totalLineCrossSize2+=_lineCrossSizes[i];totalLineCrossSize2+=crossGap*(numLines-1);let crossStartOffset=crossAxisSize-totalLineCrossSize2;for(let i=0;i<numLines;i++)_lineCrossOffsets[i]+=crossStartOffset}}let savedLineCrossSizes=null,savedLineCrossOffsets=null,savedLineJustifyStarts=null,savedLineItemSpacings=null;if(numLines>1){savedLineCrossSizes=new Float64Array(numLines),savedLineCrossOffsets=new Float64Array(numLines),savedLineJustifyStarts=new Float64Array(numLines),savedLineItemSpacings=new Float64Array(numLines);for(let i=0;i<numLines;i++)savedLineCrossSizes[i]=_lineCrossSizes[i],savedLineCrossOffsets[i]=_lineCrossOffsets[i],savedLineJustifyStarts[i]=_lineJustifyStarts[i],savedLineItemSpacings[i]=_lineItemSpacings[i]}let effectiveMainAxisSize=mainAxisSize,mainIsAuto=isRow?style2.width.unit!==UNIT_POINT2&&style2.width.unit!==UNIT_PERCENT2:style2.height.unit!==UNIT_POINT2&&style2.height.unit!==UNIT_PERCENT2,totalGaps=relativeCount>1?mainGap*(relativeCount-1):0;if(effectiveReverse&&mainIsAuto){let totalContent=0;for(let child of node.children){if(child.flex.relativeIndex<0)continue;totalContent+=child.flex.mainSize+child.flex.mainStartMarginValue+child.flex.mainEndMarginValue}totalContent+=totalGaps,effectiveMainAxisSize=totalContent}let mainPos=effectiveReverse?effectiveMainAxisSize-startOffset:startOffset,currentLineIdx=-1,relIdx=0,lineChildIdx=0,currentLineLength=0,currentItemSpacing=itemSpacing;log5.debug?.("positioning children: isRow=%s, startOffset=%d, relativeCount=%d, effectiveReverse=%s, numLines=%d",isRow,startOffset,relativeCount,effectiveReverse,numLines);for(let child of node.children){if(child.flex.relativeIndex<0)continue;let{flex:cflex,style:childStyle}=child,childLineIdx=cflex.lineIndex;if(childLineIdx!==currentLineIdx){currentLineIdx=childLineIdx,lineChildIdx=0,currentLineLength=_lineChildren[childLineIdx].length;let lineOffset=savedLineJustifyStarts?savedLineJustifyStarts[childLineIdx]:_lineJustifyStarts[childLineIdx];currentItemSpacing=savedLineItemSpacings?savedLineItemSpacings[childLineIdx]:_lineItemSpacings[childLineIdx],mainPos=effectiveReverse?effectiveMainAxisSize-lineOffset:lineOffset}let lineCrossOffset=savedLineCrossOffsets?savedLineCrossOffsets[childLineIdx]:childLineIdx<MAX_FLEX_LINES?_lineCrossOffsets[childLineIdx]:0,childMarginLeft,childMarginTop,childMarginRight,childMarginBottom;if(isRow)childMarginLeft=cflex.mainStartMarginAuto&&!effectiveReverse?cflex.mainStartMarginValue:cflex.mainEndMarginAuto&&effectiveReverse?cflex.mainEndMarginValue:cflex.marginL,childMarginRight=cflex.mainEndMarginAuto&&!effectiveReverse?cflex.mainEndMarginValue:cflex.mainStartMarginAuto&&effectiveReverse?cflex.mainStartMarginValue:cflex.marginR,childMarginTop=cflex.marginT,childMarginBottom=cflex.marginB;else childMarginTop=cflex.mainStartMarginAuto&&!isReverse?cflex.mainStartMarginValue:cflex.mainEndMarginAuto&&isReverse?cflex.mainEndMarginValue:cflex.marginT,childMarginBottom=cflex.mainEndMarginAuto&&!isReverse?cflex.mainEndMarginValue:cflex.mainStartMarginAuto&&isReverse?cflex.mainStartMarginValue:cflex.marginB,childMarginLeft=cflex.marginL,childMarginRight=cflex.marginR;let childMainSize=cflex.mainSize,alignment=style2.alignItems;if(childStyle.alignSelf!==ALIGN_AUTO2)alignment=childStyle.alignSelf;let childCrossDimForAR=isRow?childStyle.height:childStyle.width,childCrossIsAutoForAR=childCrossDimForAR.unit===UNIT_AUTO2||childCrossDimForAR.unit===UNIT_UNDEFINED2;if(alignment===ALIGN_STRETCH2&&childStyle.alignSelf===ALIGN_AUTO2&&!Number.isNaN(childStyle.aspectRatio)&&childStyle.aspectRatio>0&&childCrossIsAutoForAR)alignment=ALIGN_FLEX_START2;let childCrossSize,crossDim=isRow?childStyle.height:childStyle.width,crossMargin=isRow?childMarginTop+childMarginBottom:childMarginLeft+childMarginRight,parentCrossDim=isRow?style2.height:style2.width,parentHasDefiniteCross=parentCrossDim.unit===UNIT_POINT2||parentCrossDim.unit===UNIT_PERCENT2||!Number.isNaN(crossAxisSize);if(crossDim.unit===UNIT_POINT2)childCrossSize=crossDim.value;else if(crossDim.unit===UNIT_PERCENT2)childCrossSize=resolveValue(crossDim,crossAxisSize);else if(parentHasDefiniteCross&&alignment===ALIGN_STRETCH2)childCrossSize=(numLines>1?savedLineCrossSizes?savedLineCrossSizes[childLineIdx]:_lineCrossSizes[childLineIdx]:crossAxisSize)-crossMargin;else childCrossSize=NaN;let crossMinVal=isRow?childStyle.minHeight:childStyle.minWidth,crossMaxVal=isRow?childStyle.maxHeight:childStyle.maxWidth,crossMin=crossMinVal.unit!==UNIT_UNDEFINED2?resolveValue(crossMinVal,crossAxisSize):0,crossMax=crossMaxVal.unit!==UNIT_UNDEFINED2?resolveValue(crossMaxVal,crossAxisSize):1/0;if(Number.isNaN(childCrossSize)){if(crossMin>0)childCrossSize=crossMin}else childCrossSize=Math.max(crossMin,Math.min(crossMax,childCrossSize));let mainDim=isRow?childStyle.width:childStyle.height,hasDefiniteFlexBasis=childStyle.flexBasis.unit===UNIT_POINT2||childStyle.flexBasis.unit===UNIT_PERCENT2,mainIsAutoChild=(mainDim.unit===UNIT_AUTO2||mainDim.unit===UNIT_UNDEFINED2)&&!hasDefiniteFlexBasis,hasFlexGrow=cflex.flexGrow>0,effectiveMainSize=childMainSize,childWidth=isRow?effectiveMainSize:childCrossSize,childHeight=isRow?childCrossSize:effectiveMainSize,shouldMeasure=child.hasMeasureFunc()&&child.children.length===0&&!hasFlexGrow;if(shouldMeasure){let widthAuto=childStyle.width.unit===UNIT_AUTO2||childStyle.width.unit===UNIT_UNDEFINED2,heightAuto=childStyle.height.unit===UNIT_AUTO2||childStyle.height.unit===UNIT_UNDEFINED2;if(widthAuto||heightAuto){let widthMode=widthAuto?MEASURE_MODE_AT_MOST2:MEASURE_MODE_EXACTLY2,heightMode=heightAuto?MEASURE_MODE_UNDEFINED2:MEASURE_MODE_EXACTLY2,rawAvailW=widthAuto?isRow?mainAxisSize-mainPos:crossAxisSize-crossMargin:childStyle.width.value,rawAvailH=heightAuto?isRow?crossAxisSize-crossMargin:mainAxisSize-mainPos:childStyle.height.value,availW=Number.isNaN(rawAvailW)?1/0:rawAvailW,availH=Number.isNaN(rawAvailH)?1/0:rawAvailH,measured=child.cachedMeasure(availW,widthMode,availH,heightMode);if(widthAuto)childWidth=measured.width;if(heightAuto)childHeight=measured.height}}let childX,childY;if(effectiveReverse)if(isRow)childX=mainPos-childMainSize-childMarginRight,childY=lineCrossOffset+childMarginTop;else childX=lineCrossOffset+childMarginLeft,childY=mainPos-childMainSize-childMarginTop;else childX=isRow?mainPos+childMarginLeft:lineCrossOffset+childMarginLeft,childY=isRow?lineCrossOffset+childMarginTop:mainPos+childMarginTop;let fractionalLeft=innerLeft+childX,fractionalTop=innerTop+childY,posOffsetX=0,posOffsetY=0;if(childStyle.positionType===POSITION_TYPE_RELATIVE2){let relLeftPos=resolvePositionEdge(childStyle.position,0,direction),relTopPos=childStyle.position[1],relRightPos=resolvePositionEdge(childStyle.position,2,direction),relBottomPos=childStyle.position[3];if(relLeftPos.unit!==UNIT_UNDEFINED2)posOffsetX=resolveValue(relLeftPos,contentWidth);else if(relRightPos.unit!==UNIT_UNDEFINED2)posOffsetX=-resolveValue(relRightPos,contentWidth);if(relTopPos.unit!==UNIT_UNDEFINED2)posOffsetY=resolveValue(relTopPos,contentHeight);else if(relBottomPos.unit!==UNIT_UNDEFINED2)posOffsetY=-resolveValue(relBottomPos,contentHeight)}let absChildLeft=absX+marginLeft+parentPosOffsetX+fractionalLeft+posOffsetX,absChildTop=absY+marginTop+parentPosOffsetY+fractionalTop+posOffsetY,roundedAbsMainStart,roundedAbsMainEnd,edgeBasedMainSize,useEdgeBasedRounding=childMainSize>0,childPaddingL=resolveEdgeValue(childStyle.padding,0,childStyle.flexDirection,contentWidth,direction),childPaddingT=resolveEdgeValue(childStyle.padding,1,childStyle.flexDirection,contentWidth,direction),childPaddingR=resolveEdgeValue(childStyle.padding,2,childStyle.flexDirection,contentWidth,direction),childPaddingB=resolveEdgeValue(childStyle.padding,3,childStyle.flexDirection,contentWidth,direction),childBorderL=resolveEdgeBorderValue(childStyle.border,0,childStyle.flexDirection,direction),childBorderT=resolveEdgeBorderValue(childStyle.border,1,childStyle.flexDirection,direction),childBorderR=resolveEdgeBorderValue(childStyle.border,2,childStyle.flexDirection,direction),childBorderB=resolveEdgeBorderValue(childStyle.border,3,childStyle.flexDirection,direction),childMinW=childPaddingL+childPaddingR+childBorderL+childBorderR,childMinH=childPaddingT+childPaddingB+childBorderT+childBorderB,childMinMain=isRow?childMinW:childMinH,constrainedMainSize=Math.max(childMainSize,childMinMain);if(useEdgeBasedRounding)if(isRow)roundedAbsMainStart=Math.round(absChildLeft),roundedAbsMainEnd=Math.round(absChildLeft+constrainedMainSize),edgeBasedMainSize=roundedAbsMainEnd-roundedAbsMainStart;else roundedAbsMainStart=Math.round(absChildTop),roundedAbsMainEnd=Math.round(absChildTop+constrainedMainSize),edgeBasedMainSize=roundedAbsMainEnd-roundedAbsMainStart;else roundedAbsMainStart=isRow?Math.round(absChildLeft):Math.round(absChildTop),edgeBasedMainSize=childMinMain;let posRound=shouldMeasure?Math.floor:Math.round,childLeft=posRound(fractionalLeft+posOffsetX),childTop=posRound(fractionalTop+posOffsetY),crossDimForLayoutCall=isRow?childStyle.height:childStyle.width,crossIsAutoForLayoutCall=crossDimForLayoutCall.unit===UNIT_AUTO2||crossDimForLayoutCall.unit===UNIT_UNDEFINED2,mainIsPercentForLayoutCall=(isRow?childStyle.width:childStyle.height).unit===UNIT_PERCENT2,crossIsPercentForLayoutCall=crossDimForLayoutCall.unit===UNIT_PERCENT2,flexDistChanged=child.flex.mainSize!==child.flex.baseSize,hasMeasureLeaf=child.hasMeasureFunc()&&child.children.length===0,passWidthToChild=isRow&&mainIsAutoChild&&!hasFlexGrow&&!flexDistChanged&&!hasMeasureLeaf?NaN:!isRow&&crossIsAutoForLayoutCall&&!parentHasDefiniteCross?NaN:isRow&&mainIsPercentForLayoutCall?mainAxisSize:!isRow&&crossIsPercentForLayoutCall?crossAxisSize:childWidth,passHeightToChild=!isRow&&mainIsAutoChild&&!hasFlexGrow&&!flexDistChanged&&!hasMeasureLeaf?NaN:isRow&&crossIsAutoForLayoutCall&&!parentHasDefiniteCross?NaN:!isRow&&mainIsPercentForLayoutCall?mainAxisSize:isRow&&crossIsPercentForLayoutCall?crossAxisSize:childHeight,childAbsX=absChildLeft-childMarginLeft,childAbsY=absChildTop-childMarginTop;if(layoutNode(child,passWidthToChild,passHeightToChild,childLeft,childTop,childAbsX,childAbsY,direction),childWidth<childMinW)childWidth=childMinW;if(childHeight<childMinH)childHeight=childMinH;let hasMeasure=child.hasMeasureFunc()&&child.children.length===0,flexDistributionChangedSize=child.flex.mainSize!==child.flex.baseSize;if(!mainIsAuto&&!mainIsAutoChild||hasFlexGrow||hasMeasure||flexDistributionChangedSize)if(isRow)_t?.parentOverride(_tn,"main",child.layout.width,edgeBasedMainSize),child.layout.width=edgeBasedMainSize;else _t?.parentOverride(_tn,"main",child.layout.height,edgeBasedMainSize),child.layout.height=edgeBasedMainSize;let crossDimForCheck=isRow?childStyle.height:childStyle.width,crossIsAuto=crossDimForCheck.unit===UNIT_AUTO2||crossDimForCheck.unit===UNIT_UNDEFINED2,parentCrossIsAuto=!parentHasDefiniteCross,hasCrossMinMax=crossMinVal.unit!==UNIT_UNDEFINED2||crossMaxVal.unit!==UNIT_UNDEFINED2;if(!crossIsAuto||!parentCrossIsAuto&&alignment===ALIGN_STRETCH2||hasCrossMinMax&&!Number.isNaN(childCrossSize))if(isRow)child.layout.height=Math.round(childHeight);else child.layout.width=Math.round(childWidth);child.layout.left=childLeft,child.layout.top=childTop,childWidth=child.layout.width,childHeight=child.layout.height;let finalCrossSize=isRow?child.layout.height:child.layout.width,crossOffset=0,crossStartIndex=isRow?1:0,crossEndIndex=isRow?3:2,hasAutoStartMargin=isEdgeAuto(childStyle.margin,crossStartIndex,style2.flexDirection,direction),hasAutoEndMargin=isEdgeAuto(childStyle.margin,crossEndIndex,style2.flexDirection,direction),availableCrossSpace=(hasBaselineAlignment&&isRow&&!alignItemsIsBaseline&&alignment!==ALIGN_BASELINE2&&baselineZoneHeight>0?baselineZoneHeight:crossAxisSize)-finalCrossSize-crossMargin;if(hasAutoStartMargin&&hasAutoEndMargin)crossOffset=Math.max(0,availableCrossSpace)/2;else if(hasAutoStartMargin)crossOffset=Math.max(0,availableCrossSpace);else if(hasAutoEndMargin)crossOffset=0;else switch(alignment){case ALIGN_FLEX_END2:crossOffset=availableCrossSpace;break;case ALIGN_CENTER2:crossOffset=availableCrossSpace/2;break;case ALIGN_BASELINE2:if(isRow&&hasBaselineAlignment)crossOffset=maxBaseline-child.flex.baseline;break}if(crossOffset!==0){let crossRound=shouldMeasure?Math.floor:Math.round;if(isRow)child.layout.top+=crossRound(crossOffset);else child.layout.left+=crossRound(crossOffset)}let fractionalMainSize=!mainIsAuto&&!mainIsAutoChild||hasFlexGrow||hasMeasure||flexDistributionChangedSize?constrainedMainSize:isRow?child.layout.width:child.layout.height,totalMainMargin=cflex.mainStartMarginValue+cflex.mainEndMarginValue;if(log5.debug?.(" child %d: mainPos=%d -> top=%d (fractionalMainSize=%d, totalMainMargin=%d)",relIdx,mainPos,child.layout.top,fractionalMainSize,totalMainMargin),effectiveReverse){if(mainPos-=fractionalMainSize+totalMainMargin,lineChildIdx<currentLineLength-1)mainPos-=currentItemSpacing}else if(mainPos+=fractionalMainSize+totalMainMargin,lineChildIdx<currentLineLength-1)mainPos+=currentItemSpacing;relIdx++,lineChildIdx++}let actualUsedMain=0;for(let child of node.children){if(child.flex.relativeIndex<0)continue;let childMainSize=isRow?child.layout.width:child.layout.height,totalMainMargin=child.flex.mainStartMarginValue+child.flex.mainEndMarginValue;actualUsedMain+=childMainSize+totalMainMargin}actualUsedMain+=totalGaps;let hasAR=!Number.isNaN(aspectRatio)&&aspectRatio>0;if(isRow&&style2.width.unit!==UNIT_POINT2&&style2.width.unit!==UNIT_PERCENT2&&!hasAR)nodeWidth=actualUsedMain+innerLeft+innerRight;if(!isRow&&style2.height.unit!==UNIT_POINT2&&style2.height.unit!==UNIT_PERCENT2&&!hasAR)nodeHeight=actualUsedMain+innerTop+innerBottom;let totalCrossSize=0;if(numLines>1){for(let i=0;i<numLines;i++)totalCrossSize+=savedLineCrossSizes?savedLineCrossSizes[i]:_lineCrossSizes[i];totalCrossSize+=crossGap*(numLines-1)}else for(let child of node.children){if(child.flex.relativeIndex<0)continue;let childCross=isRow?child.layout.height:child.layout.width,childMargin=isRow?resolveEdgeValue(child.style.margin,1,style2.flexDirection,contentWidth,direction)+resolveEdgeValue(child.style.margin,3,style2.flexDirection,contentWidth,direction):resolveEdgeValue(child.style.margin,0,style2.flexDirection,contentWidth,direction)+resolveEdgeValue(child.style.margin,2,style2.flexDirection,contentWidth,direction);totalCrossSize=Math.max(totalCrossSize,childCross+childMargin)}if(isRow&&style2.height.unit!==UNIT_POINT2&&style2.height.unit!==UNIT_PERCENT2&&Number.isNaN(availableHeight)&&!hasAR)nodeHeight=totalCrossSize+innerTop+innerBottom;if(!isRow&&style2.width.unit!==UNIT_POINT2&&style2.width.unit!==UNIT_PERCENT2&&Number.isNaN(availableWidth)&&!hasAR)nodeWidth=totalCrossSize+innerLeft+innerRight}if(nodeWidth=applyMinMax(nodeWidth,style2.minWidth,style2.maxWidth,availableWidth),nodeHeight=applyMinMax(nodeHeight,style2.minHeight,style2.maxHeight,availableHeight),!Number.isNaN(nodeWidth)&&nodeWidth<minInnerWidth)nodeWidth=minInnerWidth;if(!Number.isNaN(nodeHeight)&&nodeHeight<minInnerHeight)nodeHeight=minInnerHeight;if(Number.isNaN(crossAxisSize)&&relativeCount>0){let finalCross=isRow?nodeHeight-innerTop-innerBottom:nodeWidth-innerLeft-innerRight;if(!Number.isNaN(finalCross)&&finalCross>0){for(let child of node.children){if(child.flex.relativeIndex<0)continue;let cstyle=child.style,childAlign=style2.alignItems;if(cstyle.alignSelf!==ALIGN_AUTO2)childAlign=cstyle.alignSelf;let cCrossDim=isRow?cstyle.height:cstyle.width,cCrossIsAuto=cCrossDim.unit===UNIT_AUTO2||cCrossDim.unit===UNIT_UNDEFINED2;if(childAlign===ALIGN_STRETCH2&&cstyle.alignSelf===ALIGN_AUTO2&&!Number.isNaN(cstyle.aspectRatio)&&cstyle.aspectRatio>0&&cCrossIsAuto)childAlign=ALIGN_FLEX_START2;if(childAlign!==ALIGN_STRETCH2)continue;if(!cCrossIsAuto)continue;let cCrossMargin=isRow?resolveEdgeValue(cstyle.margin,1,style2.flexDirection,contentWidth,direction)+resolveEdgeValue(cstyle.margin,3,style2.flexDirection,contentWidth,direction):resolveEdgeValue(cstyle.margin,0,style2.flexDirection,contentWidth,direction)+resolveEdgeValue(cstyle.margin,2,style2.flexDirection,contentWidth,direction),stretchedCross=finalCross-cCrossMargin,currentCross=isRow?child.layout.height:child.layout.width;if(Math.round(stretchedCross)<=currentCross)continue;let savedLeft=child.layout.left,savedTop=child.layout.top,cMarginL=resolveEdgeValue(cstyle.margin,0,style2.flexDirection,contentWidth,direction),cMarginT=resolveEdgeValue(cstyle.margin,1,style2.flexDirection,contentWidth,direction),cAbsX=absX+innerLeft+savedLeft-cMarginL,cAbsY=absY+innerTop+savedTop-cMarginT,passW=isRow?child.layout.width:stretchedCross,passH=isRow?stretchedCross:child.layout.height;if(layoutNode(child,passW,passH,savedLeft,savedTop,cAbsX,cAbsY,direction),child.layout.left=savedLeft,child.layout.top=savedTop,isRow)child.layout.height=Math.round(stretchedCross);else child.layout.width=Math.round(stretchedCross)}if(Number.isNaN(crossAxisSize)&&relativeCount>0){let finalCross9c=isRow?nodeHeight-innerTop-innerBottom:nodeWidth-innerLeft-innerRight;if(!Number.isNaN(finalCross9c)&&finalCross9c>0)for(let child of node.children){if(child.flex.relativeIndex<0)continue;let cstyle=child.style,childAlign=style2.alignItems;if(cstyle.alignSelf!==ALIGN_AUTO2)childAlign=cstyle.alignSelf;let cCrossDim=isRow?cstyle.height:cstyle.width,cCrossIsAuto=cCrossDim.unit===UNIT_AUTO2||cCrossDim.unit===UNIT_UNDEFINED2;if(childAlign===ALIGN_STRETCH2&&cstyle.alignSelf===ALIGN_AUTO2&&!Number.isNaN(cstyle.aspectRatio)&&cstyle.aspectRatio>0&&cCrossIsAuto)childAlign=ALIGN_FLEX_START2;let crossStartIdx=isRow?1:0,crossEndIdx=isRow?3:2,hasAutoStart=isEdgeAuto(cstyle.margin,crossStartIdx,style2.flexDirection,direction),hasAutoEnd=isEdgeAuto(cstyle.margin,crossEndIdx,style2.flexDirection,direction);if(!(hasAutoStart||hasAutoEnd||childAlign===ALIGN_CENTER2||childAlign===ALIGN_FLEX_END2))continue;let childCrossSize=isRow?child.layout.height:child.layout.width,cCrossMargin=isRow?resolveEdgeValue(cstyle.margin,1,style2.flexDirection,contentWidth,direction)+resolveEdgeValue(cstyle.margin,3,style2.flexDirection,contentWidth,direction):resolveEdgeValue(cstyle.margin,0,style2.flexDirection,contentWidth,direction)+resolveEdgeValue(cstyle.margin,2,style2.flexDirection,contentWidth,direction),availSpace=finalCross9c-childCrossSize-cCrossMargin,crossOffset=0;if(hasAutoStart&&hasAutoEnd)crossOffset=Math.max(0,availSpace)/2;else if(hasAutoStart)crossOffset=Math.max(0,availSpace);else if(hasAutoEnd)crossOffset=0;else switch(childAlign){case ALIGN_FLEX_END2:crossOffset=availSpace;break;case ALIGN_CENTER2:crossOffset=availSpace/2;break}if(isRow){if(Number.isNaN(child.layout.top)){let cMarginT=resolveEdgeValue(cstyle.margin,1,style2.flexDirection,contentWidth,direction);child.layout.top=Math.round(cMarginT+crossOffset)}else if(crossOffset!==0)child.layout.top+=Math.round(crossOffset)}else if(Number.isNaN(child.layout.left)){let cMarginL=resolveEdgeValue(cstyle.margin,0,style2.flexDirection,contentWidth,direction);child.layout.left=Math.round(cMarginL+crossOffset)}else if(crossOffset!==0)child.layout.left+=Math.round(crossOffset)}}}}let absNodeLeft=absX+marginLeft+parentPosOffsetX,absNodeTop=absY+marginTop+parentPosOffsetY,absNodeRight=absNodeLeft+nodeWidth,absNodeBottom=absNodeTop+nodeHeight,roundedAbsLeft=Math.round(absNodeLeft),roundedAbsTop=Math.round(absNodeTop),roundedAbsRight=Math.round(absNodeRight),roundedAbsBottom=Math.round(absNodeBottom);layout.width=roundedAbsRight-roundedAbsLeft,layout.height=roundedAbsBottom-roundedAbsTop;let roundedAbsParentLeft=Math.round(absX),roundedAbsParentTop=Math.round(absY);layout.left=roundedAbsLeft-roundedAbsParentLeft,layout.top=roundedAbsTop-roundedAbsParentTop;let absInnerLeft=borderLeft,absInnerTop=borderTop,absInnerRight=borderRight,absInnerBottom=borderBottom,absPaddingBoxW=nodeWidth-absInnerLeft-absInnerRight,absPaddingBoxH=nodeHeight-absInnerTop-absInnerBottom,absContentBoxW=absPaddingBoxW-paddingLeft-paddingRight,absContentBoxH=absPaddingBoxH-paddingTop-paddingBottom;for(let child of node.children){if(child.style.display===DISPLAY_NONE2)continue;if(child.style.positionType!==POSITION_TYPE_ABSOLUTE2)continue;let childStyle=child.style,childMarginLeft=resolveEdgeValue(childStyle.margin,0,style2.flexDirection,nodeWidth,direction),childMarginTop=resolveEdgeValue(childStyle.margin,1,style2.flexDirection,nodeWidth,direction),childMarginRight=resolveEdgeValue(childStyle.margin,2,style2.flexDirection,nodeWidth,direction),childMarginBottom=resolveEdgeValue(childStyle.margin,3,style2.flexDirection,nodeWidth,direction),hasAutoMarginLeft=isEdgeAuto(childStyle.margin,0,style2.flexDirection,direction),hasAutoMarginRight=isEdgeAuto(childStyle.margin,2,style2.flexDirection,direction),hasAutoMarginTop=isEdgeAuto(childStyle.margin,1,style2.flexDirection,direction),hasAutoMarginBottom=isEdgeAuto(childStyle.margin,3,style2.flexDirection,direction),leftPos=resolvePositionEdge(childStyle.position,0,direction),topPos=childStyle.position[1],rightPos=resolvePositionEdge(childStyle.position,2,direction),bottomPos=childStyle.position[3],hasLeft=leftPos.unit!==UNIT_UNDEFINED2,hasRight=rightPos.unit!==UNIT_UNDEFINED2,hasTop=topPos.unit!==UNIT_UNDEFINED2,hasBottom=bottomPos.unit!==UNIT_UNDEFINED2,leftOffset=resolveValue(leftPos,absContentBoxW),topOffset=resolveValue(topPos,absContentBoxH),rightOffset=resolveValue(rightPos,absContentBoxW),bottomOffset=resolveValue(bottomPos,absContentBoxH),contentW=absPaddingBoxW,contentH=absPaddingBoxH,childAvailWidth,widthIsAuto=childStyle.width.unit===UNIT_AUTO2||childStyle.width.unit===UNIT_UNDEFINED2,widthIsPercent=childStyle.width.unit===UNIT_PERCENT2;if(widthIsAuto&&hasLeft&&hasRight)childAvailWidth=contentW-leftOffset-rightOffset-childMarginLeft-childMarginRight;else if(widthIsAuto)childAvailWidth=NaN;else if(widthIsPercent)childAvailWidth=absContentBoxW;else childAvailWidth=contentW;let childAvailHeight,heightIsAuto=childStyle.height.unit===UNIT_AUTO2||childStyle.height.unit===UNIT_UNDEFINED2,heightIsPercent=childStyle.height.unit===UNIT_PERCENT2;if(heightIsAuto&&hasTop&&hasBottom)childAvailHeight=contentH-topOffset-bottomOffset-childMarginTop-childMarginBottom;else if(heightIsAuto)childAvailHeight=NaN;else if(heightIsPercent)childAvailHeight=absContentBoxH;else childAvailHeight=contentH;let childX=childMarginLeft+leftOffset,childY=childMarginTop+topOffset,childAbsX=absX+marginLeft+absInnerLeft+leftOffset,childAbsY=absY+marginTop+absInnerTop+topOffset,clampIfNumber=(v)=>Number.isNaN(v)?NaN:Math.max(0,v);layoutNode(child,clampIfNumber(childAvailWidth),clampIfNumber(childAvailHeight),layout.left+absInnerLeft+childX,layout.top+absInnerTop+childY,childAbsX,childAbsY,direction);let childWidth=child.layout.width,childHeight=child.layout.height;if(!hasLeft&&!hasRight)if(isRow){let freeSpaceX=contentW-childWidth-childMarginLeft-childMarginRight;switch(style2.justifyContent){case JUSTIFY_CENTER2:childX=childMarginLeft+freeSpaceX/2;break;case JUSTIFY_FLEX_END2:childX=childMarginLeft+freeSpaceX;break;default:childX=childMarginLeft;break}}else{let alignment=style2.alignItems;if(childStyle.alignSelf!==ALIGN_AUTO2)alignment=childStyle.alignSelf;let freeSpaceX=contentW-childWidth-childMarginLeft-childMarginRight;switch(alignment){case ALIGN_CENTER2:childX=childMarginLeft+freeSpaceX/2;break;case ALIGN_FLEX_END2:childX=childMarginLeft+freeSpaceX;break;case ALIGN_STRETCH2:break;default:childX=childMarginLeft;break}}else if(!hasLeft&&hasRight)childX=contentW-rightOffset-childMarginRight-childWidth;else if(hasLeft&&hasRight){if(widthIsAuto)child.layout.width=Math.round(childAvailWidth);else if(hasAutoMarginLeft||hasAutoMarginRight){let freeSpace=Math.max(0,contentW-leftOffset-rightOffset-childWidth);if(hasAutoMarginLeft&&hasAutoMarginRight)childX=leftOffset+freeSpace/2;else if(hasAutoMarginLeft)childX=leftOffset+freeSpace}}if(!hasTop&&!hasBottom)if(isRow){let alignment=style2.alignItems;if(childStyle.alignSelf!==ALIGN_AUTO2)alignment=childStyle.alignSelf;let freeSpaceY=contentH-childHeight-childMarginTop-childMarginBottom;switch(alignment){case ALIGN_CENTER2:childY=childMarginTop+freeSpaceY/2;break;case ALIGN_FLEX_END2:childY=childMarginTop+freeSpaceY;break;case ALIGN_STRETCH2:break;default:childY=childMarginTop;break}}else{let freeSpaceY=contentH-childHeight-childMarginTop-childMarginBottom;switch(style2.justifyContent){case JUSTIFY_CENTER2:childY=childMarginTop+freeSpaceY/2;break;case JUSTIFY_FLEX_END2:childY=childMarginTop+freeSpaceY;break;default:childY=childMarginTop;break}}else if(!hasTop&&hasBottom)childY=contentH-bottomOffset-childMarginBottom-childHeight;else if(hasTop&&hasBottom){if(heightIsAuto)child.layout.height=Math.round(childAvailHeight);else if(hasAutoMarginTop||hasAutoMarginBottom){let freeSpace=Math.max(0,contentH-topOffset-bottomOffset-childHeight);if(hasAutoMarginTop&&hasAutoMarginBottom)childY=topOffset+freeSpace/2;else if(hasAutoMarginTop)childY=topOffset+freeSpace}}child.layout.left=Math.round(absInnerLeft+childX),child.layout.top=Math.round(absInnerTop+childY)}flex.lastAvailW=availableWidth,flex.lastAvailH=availableHeight,flex.lastOffsetX=offsetX,flex.lastOffsetY=offsetY,flex.lastAbsX=absX,flex.lastAbsY=absY,flex.lastDir=direction,flex.layoutValid=!0,_t?.layoutExit(_tn,layout.width,layout.height)}var init_layout_zero=__esm(async()=>{init_utils3();init_layout_helpers();init_layout_traversal();init_layout_measure();init_layout_helpers();init_layout_traversal();init_layout_measure();init_layout_flex_lines();await init_logger()});function createValue(value=0,unit=0){return{value,unit}}function createDefaultStyle(){return{display:0,positionType:1,position:[createValue(),createValue(),createValue(),createValue(),createValue(),createValue()],flexDirection:2,flexWrap:0,flexGrow:0,flexShrink:0,flexBasis:createValue(0,3),alignItems:4,alignSelf:0,alignContent:1,justifyContent:0,width:createValue(0,3),height:createValue(0,3),minWidth:createValue(),minHeight:createValue(),maxWidth:createValue(),maxHeight:createValue(),aspectRatio:NaN,margin:[createValue(),createValue(),createValue(),createValue(),createValue(),createValue()],padding:[createValue(),createValue(),createValue(),createValue(),createValue(),createValue()],border:[0,0,0,0,NaN,NaN],gap:[0,0],overflow:0}}var Node;var init_node_zero=__esm(async()=>{init_utils3();await __promiseAll([init_layout_zero(),init_logger()]);Node=class Node{_parent=null;_children=[];_style=createDefaultStyle();_measureFunc=null;_baselineFunc=null;_m0;_m1;_m2;_m3;_lc0;_lc1;_measureResult={width:0,height:0};_layoutResult={width:0,height:0};static measureCalls=0;static measureCacheHits=0;static resetMeasureStats(){Node.measureCalls=0,Node.measureCacheHits=0}_layout={left:0,top:0,width:0,height:0};_flex={mainSize:0,baseSize:0,mainMargin:0,flexGrow:0,flexShrink:0,minMain:0,maxMain:1/0,mainStartMarginAuto:!1,mainEndMarginAuto:!1,mainStartMarginValue:0,mainEndMarginValue:0,marginL:0,marginT:0,marginR:0,marginB:0,frozen:!1,lineIndex:0,relativeIndex:-1,baseline:0,lastAvailW:NaN,lastAvailH:NaN,lastOffsetX:NaN,lastOffsetY:NaN,lastAbsX:NaN,lastAbsY:NaN,layoutValid:!1,lastDir:0};_isDirty=!0;_hasNewLayout=!1;_lastCalcW=NaN;_lastCalcH=NaN;_lastCalcDir=0;static create(){return new Node}getChildCount(){return this._children.length}getChild(index){return this._children[index]}getParent(){return this._parent}insertChild(child,index){if(child===this)throw Error("Cannot insert a node as a child of itself");let ancestor=this._parent;while(ancestor!==null){if(ancestor===child)throw Error("Cannot insert an ancestor as a child (would create a cycle)");ancestor=ancestor._parent}if(child._parent!==null)child._parent.removeChild(child);child._parent=this;let clampedIndex=Math.max(0,Math.min(index,this._children.length));this._children.splice(clampedIndex,0,child);for(let i=clampedIndex+1;i<this._children.length;i++)this._children[i]._flex.layoutValid=!1;this.markDirty()}removeChild(child){let index=this._children.indexOf(child);if(index!==-1){this._children.splice(index,1),child._parent=null;for(let i=index;i<this._children.length;i++)this._children[i]._flex.layoutValid=!1;this.markDirty()}}free(){if(this._parent!==null)this._parent.removeChild(this);for(let child of this._children)child._parent=null;this._children=[],this._measureFunc=null,this._baselineFunc=null}freeRecursive(){let nodes=[];traversalStack.length=0,traversalStack.push(this);while(traversalStack.length>0){let current=traversalStack.pop();nodes.push(current);for(let child of current._children)traversalStack.push(child)}for(let i=nodes.length-1;i>=0;i--)nodes[i].free()}[Symbol.dispose](){this.free()}setMeasureFunc(measureFunc){this._measureFunc=measureFunc,this.markDirty()}unsetMeasureFunc(){this._measureFunc=null,this.markDirty()}hasMeasureFunc(){return this._measureFunc!==null}setBaselineFunc(baselineFunc){this._baselineFunc=baselineFunc,this.markDirty()}unsetBaselineFunc(){this._baselineFunc=null,this.markDirty()}hasBaselineFunc(){return this._baselineFunc!==null}cachedMeasure(w,wm,h,hm){if(!this._measureFunc)return null;Node.measureCalls++;let m0=this._m0;if(m0&&m0.w===w&&m0.wm===wm&&m0.h===h&&m0.hm===hm)return Node.measureCacheHits++,this._measureResult.width=m0.rw,this._measureResult.height=m0.rh,getTrace()?.measureCacheHit(0,w,h,m0.rw,m0.rh),this._measureResult;let m1=this._m1;if(m1&&m1.w===w&&m1.wm===wm&&m1.h===h&&m1.hm===hm)return Node.measureCacheHits++,this._measureResult.width=m1.rw,this._measureResult.height=m1.rh,getTrace()?.measureCacheHit(0,w,h,m1.rw,m1.rh),this._measureResult;let m2=this._m2;if(m2&&m2.w===w&&m2.wm===wm&&m2.h===h&&m2.hm===hm)return Node.measureCacheHits++,this._measureResult.width=m2.rw,this._measureResult.height=m2.rh,getTrace()?.measureCacheHit(0,w,h,m2.rw,m2.rh),this._measureResult;let m3=this._m3;if(m3&&m3.w===w&&m3.wm===wm&&m3.h===h&&m3.hm===hm)return Node.measureCacheHits++,this._measureResult.width=m3.rw,this._measureResult.height=m3.rh,getTrace()?.measureCacheHit(0,w,h,m3.rw,m3.rh),this._measureResult;getTrace()?.measureCacheMiss(0,w,h);let result=this._measureFunc(w,wm,h,hm);if(this._m2){if(!this._m3)this._m3={w:0,wm:0,h:0,hm:0,rw:0,rh:0};this._m3.w=this._m2.w,this._m3.wm=this._m2.wm,this._m3.h=this._m2.h,this._m3.hm=this._m2.hm,this._m3.rw=this._m2.rw,this._m3.rh=this._m2.rh}if(this._m1){if(!this._m2)this._m2={w:0,wm:0,h:0,hm:0,rw:0,rh:0};this._m2.w=this._m1.w,this._m2.wm=this._m1.wm,this._m2.h=this._m1.h,this._m2.hm=this._m1.hm,this._m2.rw=this._m1.rw,this._m2.rh=this._m1.rh}if(this._m0){if(!this._m1)this._m1={w:0,wm:0,h:0,hm:0,rw:0,rh:0};this._m1.w=this._m0.w,this._m1.wm=this._m0.wm,this._m1.h=this._m0.h,this._m1.hm=this._m0.hm,this._m1.rw=this._m0.rw,this._m1.rh=this._m0.rh}if(!this._m0)this._m0={w:0,wm:0,h:0,hm:0,rw:0,rh:0};return this._m0.w=w,this._m0.wm=wm,this._m0.h=h,this._m0.hm=hm,this._m0.rw=result.width,this._m0.rh=result.height,this._measureResult.width=result.width,this._measureResult.height=result.height,this._measureResult}getCachedLayout(availW,availH){if(this._isDirty)return null;let lc0=this._lc0;if(lc0&&Object.is(lc0.availW,availW)&&Object.is(lc0.availH,availH))return this._layoutResult.width=lc0.computedW,this._layoutResult.height=lc0.computedH,this._layoutResult;let lc1=this._lc1;if(lc1&&Object.is(lc1.availW,availW)&&Object.is(lc1.availH,availH))return this._layoutResult.width=lc1.computedW,this._layoutResult.height=lc1.computedH,this._layoutResult;return null}setCachedLayout(availW,availH,computedW,computedH){if(this._lc0){if(!this._lc1)this._lc1={availW:NaN,availH:NaN,computedW:0,computedH:0};this._lc1.availW=this._lc0.availW,this._lc1.availH=this._lc0.availH,this._lc1.computedW=this._lc0.computedW,this._lc1.computedH=this._lc0.computedH}if(!this._lc0)this._lc0={availW:0,availH:0,computedW:0,computedH:0};this._lc0.availW=availW,this._lc0.availH=availH,this._lc0.computedW=computedW,this._lc0.computedH=computedH}resetLayoutCache(){traversalStack.length=0,traversalStack.push(this);while(traversalStack.length>0){let node=traversalStack.pop();if(node._lc0)node._lc0.availW=-1;if(node._lc1)node._lc1.availW=-1;for(let child of node._children)traversalStack.push(child)}}isDirty(){return this._isDirty}markDirty(){let current=this;while(current!==null){if(current._m0=current._m1=current._m2=current._m3=void 0,current._lc0=current._lc1=void 0,current._isDirty)break;current._isDirty=!0,current._flex.layoutValid=!1,current=current._parent}}hasNewLayout(){return this._hasNewLayout}markLayoutSeen(){this._hasNewLayout=!1}calculateLayout(width,height,direction=DIRECTION_LTR2){let availableWidth=width??NaN,availableHeight=height??NaN;if(!this._isDirty&&Object.is(this._lastCalcW,availableWidth)&&Object.is(this._lastCalcH,availableHeight)&&this._lastCalcDir===direction){log5.debug?.("layout skip (not dirty, constraints unchanged)");return}this._lastCalcW=availableWidth,this._lastCalcH=availableHeight,this._lastCalcDir=direction;let start=log5.debug?Date.now():0,nodeCount=log5.debug?countNodes(this):0;Node.resetMeasureStats(),computeLayout(this,availableWidth,availableHeight,direction),this._isDirty=!1,this._hasNewLayout=!0,markSubtreeLayoutSeen(this),log5.debug?.("layout: %dx%d, %d nodes in %dms (measure: calls=%d hits=%d)",width,height,nodeCount,Date.now()-start,Node.measureCalls,Node.measureCacheHits)}getComputedLeft(){return this._layout.left}getComputedTop(){return this._layout.top}getComputedWidth(){return this._layout.width}getComputedHeight(){return this._layout.height}getComputedRight(){return this._layout.left+this._layout.width}getComputedBottom(){return this._layout.top+this._layout.height}getComputedPadding(edge){return getEdgeValue(this._style.padding,edge).value}getComputedMargin(edge){return getEdgeValue(this._style.margin,edge).value}getComputedBorder(edge){return getEdgeBorderValue(this._style.border,edge)}get children(){return this._children}get style(){return this._style}get layout(){return this._layout}get measureFunc(){return this._measureFunc}get baselineFunc(){return this._baselineFunc}get flex(){return this._flex}setWidth(value){if(Number.isNaN(value))this._style.width={value:0,unit:UNIT_AUTO2};else this._style.width={value,unit:UNIT_POINT2};this.markDirty()}setWidthPercent(value){this._style.width={value,unit:UNIT_PERCENT2},this.markDirty()}setWidthAuto(){this._style.width={value:0,unit:UNIT_AUTO2},this.markDirty()}setHeight(value){if(Number.isNaN(value))this._style.height={value:0,unit:UNIT_AUTO2};else this._style.height={value,unit:UNIT_POINT2};this.markDirty()}setHeightPercent(value){this._style.height={value,unit:UNIT_PERCENT2},this.markDirty()}setHeightAuto(){this._style.height={value:0,unit:UNIT_AUTO2},this.markDirty()}setMinWidth(value){this._style.minWidth={value,unit:UNIT_POINT2},this.markDirty()}setMinWidthPercent(value){this._style.minWidth={value,unit:UNIT_PERCENT2},this.markDirty()}setMinHeight(value){this._style.minHeight={value,unit:UNIT_POINT2},this.markDirty()}setMinHeightPercent(value){this._style.minHeight={value,unit:UNIT_PERCENT2},this.markDirty()}setMaxWidth(value){this._style.maxWidth={value,unit:UNIT_POINT2},this.markDirty()}setMaxWidthPercent(value){this._style.maxWidth={value,unit:UNIT_PERCENT2},this.markDirty()}setMaxHeight(value){this._style.maxHeight={value,unit:UNIT_POINT2},this.markDirty()}setMaxHeightPercent(value){this._style.maxHeight={value,unit:UNIT_PERCENT2},this.markDirty()}setAspectRatio(value){this._style.aspectRatio=value,this.markDirty()}setFlexGrow(value){this._style.flexGrow=value,this.markDirty()}setFlexShrink(value){this._style.flexShrink=value,this.markDirty()}setFlexBasis(value){this._style.flexBasis={value,unit:UNIT_POINT2},this.markDirty()}setFlexBasisPercent(value){this._style.flexBasis={value,unit:UNIT_PERCENT2},this.markDirty()}setFlexBasisAuto(){this._style.flexBasis={value:0,unit:UNIT_AUTO2},this.markDirty()}setFlexDirection(direction){this._style.flexDirection=direction,this.markDirty()}setFlexWrap(wrap){this._style.flexWrap=wrap,this.markDirty()}setAlignItems(align){this._style.alignItems=align,this.markDirty()}setAlignSelf(align){this._style.alignSelf=align,this.markDirty()}setAlignContent(align){this._style.alignContent=align,this.markDirty()}setJustifyContent(justify){this._style.justifyContent=justify,this.markDirty()}setPadding(edge,value){setEdgeValue(this._style.padding,edge,value,UNIT_POINT2),this.markDirty()}setPaddingPercent(edge,value){setEdgeValue(this._style.padding,edge,value,UNIT_PERCENT2),this.markDirty()}setMargin(edge,value){setEdgeValue(this._style.margin,edge,value,UNIT_POINT2),this.markDirty()}setMarginPercent(edge,value){setEdgeValue(this._style.margin,edge,value,UNIT_PERCENT2),this.markDirty()}setMarginAuto(edge){setEdgeValue(this._style.margin,edge,0,UNIT_AUTO2),this.markDirty()}setBorder(edge,value){setEdgeBorder(this._style.border,edge,value),this.markDirty()}setGap(gutter,value){if(gutter===GUTTER_COLUMN2)this._style.gap[0]=value;else if(gutter===GUTTER_ROW2)this._style.gap[1]=value;else if(gutter===GUTTER_ALL2)this._style.gap[0]=value,this._style.gap[1]=value;this.markDirty()}setPositionType(positionType){this._style.positionType=positionType,this.markDirty()}setPosition(edge,value){if(Number.isNaN(value))setEdgeValue(this._style.position,edge,0,UNIT_UNDEFINED2);else setEdgeValue(this._style.position,edge,value,UNIT_POINT2);this.markDirty()}setPositionPercent(edge,value){setEdgeValue(this._style.position,edge,value,UNIT_PERCENT2),this.markDirty()}setDisplay(display){this._style.display=display,this.markDirty()}setOverflow(overflow){this._style.overflow=overflow,this.markDirty()}getWidth(){return this._style.width}getHeight(){return this._style.height}getMinWidth(){return this._style.minWidth}getMinHeight(){return this._style.minHeight}getMaxWidth(){return this._style.maxWidth}getMaxHeight(){return this._style.maxHeight}getAspectRatio(){return this._style.aspectRatio}getFlexGrow(){return this._style.flexGrow}getFlexShrink(){return this._style.flexShrink}getFlexBasis(){return this._style.flexBasis}getFlexDirection(){return this._style.flexDirection}getFlexWrap(){return this._style.flexWrap}getAlignItems(){return this._style.alignItems}getAlignSelf(){return this._style.alignSelf}getAlignContent(){return this._style.alignContent}getJustifyContent(){return this._style.justifyContent}getPadding(edge){return getEdgeValue(this._style.padding,edge)}getMargin(edge){return getEdgeValue(this._style.margin,edge)}getBorder(edge){return getEdgeBorderValue(this._style.border,edge)}getPosition(edge){return getEdgeValue(this._style.position,edge)}getPositionType(){return this._style.positionType}getDisplay(){return this._style.display}getOverflow(){return this._style.overflow}getGap(gutter){if(gutter===GUTTER_COLUMN2)return this._style.gap[0];else if(gutter===GUTTER_ROW2)return this._style.gap[1];return this._style.gap[0]}}});var segmenter2;var init_monospace_measurer=__esm(()=>{segmenter2=new Intl.Segmenter(void 0,{granularity:"grapheme"})});var init_create_flexily=__esm(async()=>{init_monospace_measurer();await init_node_zero()});var segmenter3;var init_test_measurer=__esm(()=>{segmenter3=new Intl.Segmenter(void 0,{granularity:"grapheme"})});var init_src3=__esm(async()=>{init_monospace_measurer();init_test_measurer();await __promiseAll([init_create_flexily(),init_node_zero(),init_layout_zero()])});var exports_flexily_zero_adapter={};__export(exports_flexily_zero_adapter,{createFlexilyZeroEngine:()=>createFlexilyZeroEngine,FlexilyZeroLayoutEngine:()=>FlexilyZeroLayoutEngine});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(Node.create())}get constants(){return this._constants}get name(){return"flexily-zero"}}function createFlexilyZeroEngine(){return new FlexilyZeroLayoutEngine}var init_flexily_zero_adapter=__esm(async()=>{await init_src3()});var exports_layout_engine={};__export(exports_layout_engine,{setLayoutEngine:()=>setLayoutEngine,isLayoutEngineInitialized:()=>isLayoutEngineInitialized,getLayoutEngine:()=>getLayoutEngine,getConstants:()=>getConstants,ensureDefaultLayoutEngine:()=>ensureDefaultLayoutEngine});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 init_flexily_zero_adapter().then(() => exports_flexily_zero_adapter);setLayoutEngine(createFlexilyZeroEngine2())}}var layoutEngine=null;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}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,renderEpoch=0;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}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;let entry=textCaches.get(node);if(!entry?.analysis)return null;if(isDirty(node.dirtyBits,node.dirtyEpoch,PLAIN_TEXT_DIRTY))return entry.analysis=null,null;return entry.analysis}function setCachedAnalysis(node,analysis){let entry=getOrCreate(node);entry.analysis=analysis}var MAX_FORMAT_ENTRIES=4,PLAIN_TEXT_DIRTY,COLLECTED_TEXT_DIRTY,_cacheDisabled,textCaches;var init_prepared_text=__esm(()=>{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,textCaches=new WeakMap});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,maxGraphemeWidth=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,w>maxGraphemeWidth)maxGraphemeWidth=w;if(g===`
64
68
  `)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,maxGraphemeWidth,newlineIndices,breakIndices,text}}function countLinesAtWidth(analysis,width){if(width<=0)return 1/0;if(analysis.totalWidth<=width&&analysis.newlineIndices.length===0)return 1;return wrapText(analysis.text,width,!0,!0).length}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.maxGraphemeWidth),hi=maxWidth;if(lo>=hi)return Math.min(hi,maxWidth);while(lo<hi){let mid=lo+hi>>1;if(countLinesAtWidth(analysis,mid)<=targetLineCount)hi=mid;else lo=mid+1}return Math.min(lo,maxWidth)}function knuthPlassBreaks(analysis,width){if(width<=0)return[];if(analysis.totalWidth<=width&&analysis.newlineIndices.length===0)return[];let{newlineIndices,graphemes}=analysis,allBreaks=[],paragraphStarts=[0];for(let nl of newlineIndices)paragraphStarts.push(nl+1);for(let p=0;p<paragraphStarts.length;p++){let pStart=paragraphStarts[p],pEnd=p+1<paragraphStarts.length?paragraphStarts[p+1]-1:graphemes.length;if(pStart>=pEnd)continue;let breaks=knuthPlassForParagraph(analysis,pStart,pEnd,width);if(allBreaks.push(...breaks),p<paragraphStarts.length-1&&pEnd<graphemes.length)allBreaks.push(pEnd+1)}return allBreaks}function knuthPlassForParagraph(analysis,pStart,pEnd,width){let{cumWidths,breakIndices,widths,graphemes}=analysis,candidates=[pStart];for(let bp of breakIndices)if(bp>pStart&&bp<=pEnd)candidates.push(bp);candidates.push(pEnd);let n=candidates.length;if(n<=2)return[];let cost=Array(n).fill(1/0),next=Array(n).fill(-1);cost[n-1]=0;for(let i=n-2;i>=0;i--){let lineStart=candidates[i],lineStartCum=cumWidths[lineStart];for(let j=i+1;j<n;j++){let trimEnd=candidates[j];while(trimEnd>lineStart){let prevG=graphemes[trimEnd-1];if(widths[trimEnd-1]===0){trimEnd--;continue}if(prevG===" "||prevG==="\t"){trimEnd--;continue}break}let lineWidth=cumWidths[trimEnd]-lineStartCum;if(lineWidth>width)break;let leftover=width-lineWidth,totalCost=(j===n-1?0:leftover*leftover)+cost[j];if(totalCost<cost[i])cost[i]=totalCost,next[i]=j}}if(cost[0]===1/0)return[];let breaks=[],idx=0;while(idx<n-1&&next[idx]>=0)if(idx=next[idx],idx<n-1)breaks.push(candidates[idx]);return breaks}function optimalWrap(text,analysis,width){let breaks=knuthPlassBreaks(analysis,width);if(breaks.length===0){if(analysis.totalWidth<=width&&analysis.newlineIndices.length===0)return[text];return wrapText(text,width,!0,!0)}let{graphemes,widths}=analysis,lines=[],lineStart=0;for(let bp of breaks){let lineEnd=bp;while(lineEnd>lineStart){if(widths[lineEnd-1]===0){lineEnd--;continue}let g=graphemes[lineEnd-1];if(g===" "||g==="\t"||g===`
65
69
  `){lineEnd--;continue}break}lines.push(graphemes.slice(lineStart,lineEnd).join("")),lineStart=bp;while(lineStart<graphemes.length){let g=graphemes[lineStart];if(g===" "||g==="\t"){lineStart++;continue}break}}if(lineStart<graphemes.length)lines.push(graphemes.slice(lineStart).join(""));return lines}var init_pretext=__esm(()=>{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}}var init_helpers=__esm(()=>{init_unicode()});function measurePhase(root,ctx){traverseTree(root,(node)=>{if(!node.layoutNode)return;let props=node.props,isFitContent=props.width==="fit-content"||props.height==="fit-content",isSnugContent=props.width==="snug-content";if(isFitContent||isSnugContent){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(isSnugContent){let shrunkWidth=computeSnugContentWidth(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(`
66
- `);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==="even"||wrap===!0||wrap===void 0}function computeSnugContentWidth(node,fitContentWidth,ctx){let props=node.props,overhead=0,padding=getPadding(props);if(overhead+=padding.left+padding.right,props.borderStyle){let border=getBorderSize(props);overhead+=border.left+border.right}let contentWidth=fitContentWidth-overhead,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,contentWidth)+overhead}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)}var init_measure_phase=__esm(()=>{init_unicode();init_prepared_text();init_pretext();init_helpers()});var measureStats;var init_measure_stats=__esm(()=>{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}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 layoutDirtyNodes,contentDirtyNodes,styleOnlyDirtyNodes,scrollDirtyNodes;var init_dirty_tracking=__esm(()=>{layoutDirtyNodes=new Set,contentDirtyNodes=new Set,styleOnlyDirtyNodes=new Set,scrollDirtyNodes=new Set});import{createLogger as createLogger5}from"loggily";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}}var log5;var init_layout_phase=__esm(()=>{init_measure_stats();init_dirty_tracking();init_helpers();log5=createLogger5("silvery:layout")});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 githubDark,githubLight;var init_github=__esm(()=>{githubDark={name:"github-dark",dark:!0,black:"#000000",red:"#f78166",green:"#56d364",yellow:"#e3b341",blue:"#6ca4f8",magenta:"#db61a2",cyan:"#2b7489",white:"#ffffff",brightBlack:"#4d4d4d",brightRed:"#f78166",brightGreen:"#56d364",brightYellow:"#e3b341",brightBlue:"#6ca4f8",brightMagenta:"#db61a2",brightCyan:"#2b7489",brightWhite:"#ffffff",foreground:"#8b949e",background:"#101216",cursorColor:"#c9d1d9",cursorText:"#101216",selectionBackground:"#3b5070",selectionForeground:"#c9d1d9"},githubLight={name:"github-light",dark:!1,black:"#3e3e3e",red:"#970b16",green:"#07962a",yellow:"#f8eec7",blue:"#003e8a",magenta:"#e94691",cyan:"#89d1ec",white:"#ffffff",brightBlack:"#666666",brightRed:"#de0000",brightGreen:"#87d5a2",brightYellow:"#f1d007",brightBlue:"#2e6cba",brightMagenta:"#ffa29f",brightCyan:"#1cfafe",brightWhite:"#ffffff",foreground:"#3e3e3e",background:"#f4f4f4",cursorColor:"#3f3f3f",cursorText:"#f4f4f4",selectionBackground:"#a9c1e2",selectionForeground:"#3e3e3e"}});var cobalt2;var init_cobalt2=__esm(()=>{cobalt2={name:"cobalt2",dark:!0,black:"#000000",red:"#ff0000",green:"#38de21",yellow:"#ffe50a",blue:"#1460d2",magenta:"#ff005d",cyan:"#00bbbb",white:"#bbbbbb",brightBlack:"#555555",brightRed:"#f40e17",brightGreen:"#3bd01d",brightYellow:"#edc809",brightBlue:"#5555ff",brightMagenta:"#ff55ff",brightCyan:"#6ae3fa",brightWhite:"#ffffff",foreground:"#ffffff",background:"#132738",cursorColor:"#f0cc09",cursorText:"#132738",selectionBackground:"#18354f",selectionForeground:"#ffffff"}});var synthwave,synthwave84;var init_synthwave=__esm(()=>{synthwave={name:"synthwave",dark:!0,black:"#000000",red:"#f6188f",green:"#1ebb2b",yellow:"#fdf834",blue:"#2186ec",magenta:"#f85a21",cyan:"#12c3e2",white:"#ffffff",brightBlack:"#000000",brightRed:"#f841a0",brightGreen:"#25c141",brightYellow:"#fdf454",brightBlue:"#2f9ded",brightMagenta:"#f97137",brightCyan:"#19cde6",brightWhite:"#ffffff",foreground:"#dad9c7",background:"#000000",cursorColor:"#19cde6",cursorText:"#000000",selectionBackground:"#19cde6",selectionForeground:"#000000"},synthwave84={name:"synthwave-84",dark:!0,black:"#fefefe",red:"#f97e72",green:"#72f1b8",yellow:"#fede5d",blue:"#6d77b3",magenta:"#c792ea",cyan:"#f772e0",white:"#fefefe",brightBlack:"#fefefe",brightRed:"#f88414",brightGreen:"#72f1b8",brightYellow:"#fff951",brightBlue:"#36f9f6",brightMagenta:"#e1acff",brightCyan:"#f92aad",brightWhite:"#fefefe",foreground:"#f0eff1",background:"#2a2139",cursorColor:"#72f1b8",cursorText:"#2a2139",selectionBackground:"#181521",selectionForeground:"#f0eff1"}});var tomorrowNight,tomorrowNightBlue,tomorrowNightEighties;var init_tomorrow_night=__esm(()=>{tomorrowNight={name:"tomorrow-night",dark:!0,black:"#282a2e",red:"#cc6666",green:"#b5bd68",yellow:"#f0c674",blue:"#81a2be",magenta:"#b294bb",cyan:"#8abeb7",white:"#e0e0e0",brightBlack:"#373b41",brightRed:"#cc6666",brightGreen:"#b5bd68",brightYellow:"#f0c674",brightBlue:"#81a2be",brightMagenta:"#b294bb",brightCyan:"#8abeb7",brightWhite:"#ffffff",foreground:"#c5c8c6",background:"#1d1f21",cursorColor:"#c5c8c6",cursorText:"#1d1f21",selectionBackground:"#373b41",selectionForeground:"#c5c8c6"},tomorrowNightBlue={name:"tomorrow-night-blue",dark:!0,black:"#000000",red:"#ff9da4",green:"#d1f1a9",yellow:"#ffeead",blue:"#bbdaff",magenta:"#ebbbff",cyan:"#99ffff",white:"#ffffff",brightBlack:"#000000",brightRed:"#ff9da4",brightGreen:"#d1f1a9",brightYellow:"#ffeead",brightBlue:"#bbdaff",brightMagenta:"#ebbbff",brightCyan:"#99ffff",brightWhite:"#ffffff",foreground:"#ffffff",background:"#002451",cursorColor:"#ffffff",cursorText:"#002451",selectionBackground:"#003f8e",selectionForeground:"#ffffff"},tomorrowNightEighties={name:"tomorrow-night-eighties",dark:!0,black:"#393939",red:"#f2777a",green:"#99cc99",yellow:"#ffcc66",blue:"#6699cc",magenta:"#cc99cc",cyan:"#66cccc",white:"#e0e0e0",brightBlack:"#515151",brightRed:"#f2777a",brightGreen:"#99cc99",brightYellow:"#ffcc66",brightBlue:"#6699cc",brightMagenta:"#cc99cc",brightCyan:"#66cccc",brightWhite:"#ffffff",foreground:"#cccccc",background:"#2d2d2d",cursorColor:"#cccccc",cursorText:"#2d2d2d",selectionBackground:"#515151",selectionForeground:"#cccccc"}});var zenburn;var init_zenburn=__esm(()=>{zenburn={name:"zenburn",dark:!0,black:"#4d4d4d",red:"#705050",green:"#60b48a",yellow:"#f0dfaf",blue:"#506070",magenta:"#dc8cc3",cyan:"#8cd0d3",white:"#dcdccc",brightBlack:"#709080",brightRed:"#dca3a3",brightGreen:"#c3bf9f",brightYellow:"#e0cf9f",brightBlue:"#94bff3",brightMagenta:"#ec93d3",brightCyan:"#93e0e3",brightWhite:"#ffffff",foreground:"#dcdccc",background:"#3f3f3f",cursorColor:"#73635a",cursorText:"#3f3f3f",selectionBackground:"#21322f",selectionForeground:"#dcdccc"}});var ubuntu;var init_ubuntu=__esm(()=>{ubuntu={name:"ubuntu",dark:!0,black:"#2e3436",red:"#cc0000",green:"#4e9a06",yellow:"#c4a000",blue:"#3465a4",magenta:"#75507b",cyan:"#06989a",white:"#d3d7cf",brightBlack:"#555753",brightRed:"#ef2929",brightGreen:"#8ae234",brightYellow:"#fce94f",brightBlue:"#729fcf",brightMagenta:"#ad7fa8",brightCyan:"#34e2e2",brightWhite:"#eeeeec",foreground:"#eeeeec",background:"#300a24",cursorColor:"#bbbbbb",cursorText:"#300a24",selectionBackground:"#b5d5ff",selectionForeground:"#300a24"}});var tangoDark,tangoLight;var init_tango=__esm(()=>{tangoDark={name:"tango-dark",dark:!0,black:"#000000",red:"#cc0000",green:"#4e9a06",yellow:"#c4a000",blue:"#3465a4",magenta:"#75507b",cyan:"#06989a",white:"#d3d7cf",brightBlack:"#555753",brightRed:"#ef2929",brightGreen:"#8ae234",brightYellow:"#fce94f",brightBlue:"#729fcf",brightMagenta:"#ad7fa8",brightCyan:"#34e2e2",brightWhite:"#eeeeec",foreground:"#ffffff",background:"#000000",cursorColor:"#ffffff",cursorText:"#000000",selectionBackground:"#b5d5ff",selectionForeground:"#000000"},tangoLight={name:"tango-light",dark:!1,black:"#000000",red:"#cc0000",green:"#4e9a06",yellow:"#c4a000",blue:"#3465a4",magenta:"#75507b",cyan:"#06989a",white:"#d3d7cf",brightBlack:"#555753",brightRed:"#ef2929",brightGreen:"#8ae234",brightYellow:"#fce94f",brightBlue:"#729fcf",brightMagenta:"#ad7fa8",brightCyan:"#34e2e2",brightWhite:"#eeeeec",foreground:"#000000",background:"#ffffff",cursorColor:"#000000",cursorText:"#ffffff",selectionBackground:"#b5d5ff",selectionForeground:"#000000"}});var cyberpunk;var init_cyberpunk=__esm(()=>{cyberpunk={name:"cyberpunk",dark:!0,black:"#000000",red:"#ff7092",green:"#00fbac",yellow:"#fffa6a",blue:"#00bfff",magenta:"#df95ff",cyan:"#86cbfe",white:"#ffffff",brightBlack:"#000000",brightRed:"#ff8aa4",brightGreen:"#21f6bc",brightYellow:"#fff787",brightBlue:"#1bccfd",brightMagenta:"#e6aefe",brightCyan:"#99d6fc",brightWhite:"#ffffff",foreground:"#e5e5e5",background:"#332a57",cursorColor:"#21f6bc",cursorText:"#332a57",selectionBackground:"#c1deff",selectionForeground:"#332a57"}});var vscodeDark;var init_vscode=__esm(()=>{vscodeDark={name:"vscode-dark",dark:!0,black:"#000000",red:"#cd3131",green:"#0dbc79",yellow:"#e5e510",blue:"#2472c8",magenta:"#bc3fbc",cyan:"#11a8cd",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#f14c4c",brightGreen:"#23d18b",brightYellow:"#f5f543",brightBlue:"#3b8eea",brightMagenta:"#d670d6",brightCyan:"#29b8db",brightWhite:"#e5e5e5",foreground:"#cccccc",background:"#1e1e1e",cursorColor:"#ffffff",cursorText:"#1e1e1e",selectionBackground:"#3a3d41",selectionForeground:"#cccccc"}});var oneLight,oneHalfDark,oneHalfLight;var init_one_light=__esm(()=>{oneLight={name:"one-light",dark:!1,black:"#000000",red:"#de3e35",green:"#3f953a",yellow:"#d2b67c",blue:"#2f5af3",magenta:"#950095",cyan:"#3f953a",white:"#bbbbbb",brightBlack:"#000000",brightRed:"#de3e35",brightGreen:"#3f953a",brightYellow:"#d2b67c",brightBlue:"#2f5af3",brightMagenta:"#a00095",brightCyan:"#3f953a",brightWhite:"#ffffff",foreground:"#2a2c33",background:"#f9f9f9",cursorColor:"#bbbbbb",cursorText:"#f9f9f9",selectionBackground:"#ededed",selectionForeground:"#2a2c33"},oneHalfDark={name:"one-half-dark",dark:!0,black:"#282c34",red:"#e06c75",green:"#98c379",yellow:"#e5c07b",blue:"#61afef",magenta:"#c678dd",cyan:"#56b6c2",white:"#dcdfe4",brightBlack:"#282c34",brightRed:"#e06c75",brightGreen:"#98c379",brightYellow:"#e5c07b",brightBlue:"#61afef",brightMagenta:"#c678dd",brightCyan:"#56b6c2",brightWhite:"#dcdfe4",foreground:"#dcdfe4",background:"#282c34",cursorColor:"#a3b3cc",cursorText:"#282c34",selectionBackground:"#474e5d",selectionForeground:"#dcdfe4"},oneHalfLight={name:"one-half-light",dark:!1,black:"#383a42",red:"#e45649",green:"#50a14f",yellow:"#c18401",blue:"#0184bc",magenta:"#a626a4",cyan:"#0997b3",white:"#fafafa",brightBlack:"#4f525e",brightRed:"#e06c75",brightGreen:"#98c379",brightYellow:"#e5c07b",brightBlue:"#61afef",brightMagenta:"#c678dd",brightCyan:"#56b6c2",brightWhite:"#ffffff",foreground:"#383a42",background:"#fafafa",cursorColor:"#bfceff",cursorText:"#fafafa",selectionBackground:"#bfceff",selectionForeground:"#383a42"}});var nightOwlLight;var init_night_owl=__esm(()=>{nightOwlLight={name:"night-owl-light",dark:!1,black:"#011627",red:"#d3423e",green:"#2aa298",yellow:"#daaa01",blue:"#4876d6",magenta:"#403f53",cyan:"#08916a",white:"#7a8181",brightBlack:"#7a8181",brightRed:"#f76e6e",brightGreen:"#49d0c5",brightYellow:"#dac26b",brightBlue:"#5ca7e4",brightMagenta:"#697098",brightCyan:"#00c990",brightWhite:"#989fb1",foreground:"#403f53",background:"#ffffff",cursorColor:"#403f53",cursorText:"#ffffff",selectionBackground:"#f2f2f2",selectionForeground:"#403f53"}});var shadesOfPurple;var init_shades_of_purple=__esm(()=>{shadesOfPurple={name:"shades-of-purple",dark:!0,black:"#000000",red:"#d90429",green:"#3ad900",yellow:"#ffe700",blue:"#6943ff",magenta:"#ff2c70",cyan:"#00c5c7",white:"#c7c7c7",brightBlack:"#686868",brightRed:"#f92a1c",brightGreen:"#43d426",brightYellow:"#f1d000",brightBlue:"#6871ff",brightMagenta:"#ff77ff",brightCyan:"#79e8fb",brightWhite:"#ffffff",foreground:"#ffffff",background:"#1e1d40",cursorColor:"#fad000",cursorText:"#1e1d40",selectionBackground:"#b362ff",selectionForeground:"#ffffff"}});var homebrew;var init_homebrew=__esm(()=>{homebrew={name:"homebrew",dark:!0,black:"#000000",red:"#990000",green:"#00a600",yellow:"#999900",blue:"#0000b2",magenta:"#b200b2",cyan:"#00a6b2",white:"#bfbfbf",brightBlack:"#666666",brightRed:"#e50000",brightGreen:"#00d900",brightYellow:"#e5e500",brightBlue:"#0000ff",brightMagenta:"#e500e5",brightCyan:"#00e5e5",brightWhite:"#e5e5e5",foreground:"#00ff00",background:"#000000",cursorColor:"#23ff18",cursorText:"#000000",selectionBackground:"#083905",selectionForeground:"#00ff00"}});var neon;var init_neon=__esm(()=>{neon={name:"neon",dark:!0,black:"#000000",red:"#ff3045",green:"#5ffa74",yellow:"#fffc7e",blue:"#0208cb",magenta:"#f924e7",cyan:"#00fffc",white:"#c7c7c7",brightBlack:"#686868",brightRed:"#ff5a5a",brightGreen:"#75ff88",brightYellow:"#fffd96",brightBlue:"#3c40cb",brightMagenta:"#f15be5",brightCyan:"#88fffe",brightWhite:"#ffffff",foreground:"#00fffc",background:"#14161a",cursorColor:"#c7c7c7",cursorText:"#14161a",selectionBackground:"#0013ff",selectionForeground:"#ffffff"}});var challengerDeep;var init_challenger_deep=__esm(()=>{challengerDeep={name:"challenger-deep",dark:!0,black:"#141228",red:"#ff5458",green:"#62d196",yellow:"#ffb378",blue:"#65b2ff",magenta:"#906cff",cyan:"#63f2f1",white:"#a6b3cc",brightBlack:"#565575",brightRed:"#ff8080",brightGreen:"#95ffa4",brightYellow:"#ffe9aa",brightBlue:"#91ddff",brightMagenta:"#c991e1",brightCyan:"#aaffe4",brightWhite:"#cbe3e7",foreground:"#cbe1e7",background:"#1e1c31",cursorColor:"#fbfcfc",cursorText:"#1e1c31",selectionBackground:"#cbe1e7",selectionForeground:"#1e1c31"}});var doomOne;var init_doom_one=__esm(()=>{doomOne={name:"doom-one",dark:!0,black:"#000000",red:"#ff6c6b",green:"#98be65",yellow:"#ecbe7b",blue:"#a9a1e1",magenta:"#c678dd",cyan:"#51afef",white:"#bbc2cf",brightBlack:"#000000",brightRed:"#ff6655",brightGreen:"#99bb66",brightYellow:"#ecbe7b",brightBlue:"#a9a1e1",brightMagenta:"#c678dd",brightCyan:"#51afef",brightWhite:"#bfbfbf",foreground:"#bbc2cf",background:"#282c34",cursorColor:"#51afef",cursorText:"#282c34",selectionBackground:"#42444b",selectionForeground:"#bbc2cf"}});var mariana;var init_mariana=__esm(()=>{mariana={name:"mariana",dark:!0,black:"#000000",red:"#ec5f66",green:"#99c794",yellow:"#f9ae58",blue:"#6699cc",magenta:"#c695c6",cyan:"#5fb4b4",white:"#f7f7f7",brightBlack:"#333333",brightRed:"#f97b58",brightGreen:"#acd1a8",brightYellow:"#fac761",brightBlue:"#85add6",brightMagenta:"#d8b6d8",brightCyan:"#82c4c4",brightWhite:"#ffffff",foreground:"#d8dee9",background:"#343d46",cursorColor:"#fcbb6a",cursorText:"#343d46",selectionBackground:"#4e5a65",selectionForeground:"#d8dee9"}});var darcula;var init_darcula=__esm(()=>{darcula={name:"darcula",dark:!0,black:"#000000",red:"#fa5355",green:"#126e00",yellow:"#c2c300",blue:"#4581eb",magenta:"#fa54ff",cyan:"#33c2c1",white:"#adadad",brightBlack:"#555555",brightRed:"#fb7172",brightGreen:"#67ff4f",brightYellow:"#ffff00",brightBlue:"#6d9df1",brightMagenta:"#fb82ff",brightCyan:"#60d3d1",brightWhite:"#eeeeee",foreground:"#adadad",background:"#202020",cursorColor:"#ffffff",cursorText:"#202020",selectionBackground:"#1a3272",selectionForeground:"#adadad"}});var espresso;var init_espresso=__esm(()=>{espresso={name:"espresso",dark:!0,black:"#353535",red:"#d25252",green:"#a5c261",yellow:"#ffc66d",blue:"#6c99bb",magenta:"#d197d9",cyan:"#bed6ff",white:"#eeeeec",brightBlack:"#535353",brightRed:"#f00c0c",brightGreen:"#c2e075",brightYellow:"#e1e48b",brightBlue:"#8ab7d9",brightMagenta:"#efb5f7",brightCyan:"#dcf4ff",brightWhite:"#ffffff",foreground:"#ffffff",background:"#323232",cursorColor:"#d6d6d6",cursorText:"#323232",selectionBackground:"#5b5b5b",selectionForeground:"#ffffff"}});var icebergDark,icebergLight;var init_iceberg=__esm(()=>{icebergDark={name:"iceberg-dark",dark:!0,black:"#1e2132",red:"#e27878",green:"#b4be82",yellow:"#e2a478",blue:"#84a0c6",magenta:"#a093c7",cyan:"#89b8c2",white:"#c6c8d1",brightBlack:"#6b7089",brightRed:"#e98989",brightGreen:"#c0ca8e",brightYellow:"#e9b189",brightBlue:"#91acd1",brightMagenta:"#ada0d3",brightCyan:"#95c4ce",brightWhite:"#d2d4de",foreground:"#c6c8d1",background:"#161821",cursorColor:"#c6c8d1",cursorText:"#161821",selectionBackground:"#c6c8d1",selectionForeground:"#161821"},icebergLight={name:"iceberg-light",dark:!1,black:"#dcdfe7",red:"#cc517a",green:"#668e3d",yellow:"#c57339",blue:"#2d539e",magenta:"#7759b4",cyan:"#3f83a6",white:"#33374c",brightBlack:"#8389a3",brightRed:"#cc3768",brightGreen:"#598030",brightYellow:"#b6662d",brightBlue:"#22478e",brightMagenta:"#6845ad",brightCyan:"#327698",brightWhite:"#262a3f",foreground:"#33374c",background:"#e8e9ec",cursorColor:"#33374c",cursorText:"#e8e9ec",selectionBackground:"#33374c",selectionForeground:"#e8e9ec"}});var serendipityMidnight,serendipityMorning;var init_serendipity=__esm(()=>{serendipityMidnight={name:"serendipity-midnight",dark:!0,black:"#232534",red:"#ee8679",green:"#9ccfd8",yellow:"#f8d2c9",blue:"#5ba2d0",magenta:"#a78bfa",cyan:"#94b8ff",white:"#dee0ef",brightBlack:"#8d8f9e",brightRed:"#ee8679",brightGreen:"#9ccfd8",brightYellow:"#f8d2c9",brightBlue:"#5ba2d0",brightMagenta:"#a78bfa",brightCyan:"#94b8ff",brightWhite:"#dee0ef",foreground:"#dee0ef",background:"#1c1e2d",cursorColor:"#6b6d7c",cursorText:"#1c1e2d",selectionBackground:"#2c2e3d",selectionForeground:"#dee0ef"},serendipityMorning={name:"serendipity-morning",dark:!1,black:"#f2e9de",red:"#d26a5d",green:"#77aab3",yellow:"#c8a299",blue:"#3788be",magenta:"#886cdb",cyan:"#7397de",white:"#575279",brightBlack:"#6e6a86",brightRed:"#d26a5d",brightGreen:"#77aab3",brightYellow:"#c8a299",brightBlue:"#3788be",brightMagenta:"#886cdb",brightCyan:"#7397de",brightWhite:"#575279",foreground:"#575279",background:"#fffaf3",cursorColor:"#9893a5",cursorText:"#fffaf3",selectionBackground:"#f4efea",selectionForeground:"#575279"}});var twilight;var init_twilight=__esm(()=>{twilight={name:"twilight",dark:!0,black:"#141414",red:"#c06d44",green:"#afb97a",yellow:"#c2a86c",blue:"#44474a",magenta:"#b4be7c",cyan:"#778385",white:"#ffffd4",brightBlack:"#262626",brightRed:"#de7c4c",brightGreen:"#ccd88c",brightYellow:"#e2c47e",brightBlue:"#5a5e62",brightMagenta:"#d0dc8e",brightCyan:"#8a989b",brightWhite:"#ffffd4",foreground:"#ffffd4",background:"#141414",cursorColor:"#ffffff",cursorText:"#141414",selectionBackground:"#313131",selectionForeground:"#ffffd4"}});var breeze;var init_breeze=__esm(()=>{breeze={name:"breeze",dark:!0,black:"#31363b",red:"#ed1515",green:"#11d116",yellow:"#f67400",blue:"#1d99f3",magenta:"#9b59b6",cyan:"#1abc9c",white:"#eff0f1",brightBlack:"#7f8c8d",brightRed:"#c0392b",brightGreen:"#1cdc9a",brightYellow:"#fdbc4b",brightBlue:"#3daee9",brightMagenta:"#8e44ad",brightCyan:"#16a085",brightWhite:"#fcfcfc",foreground:"#eff0f1",background:"#31363b",cursorColor:"#eff0f1",cursorText:"#31363b",selectionBackground:"#eff0f1",selectionForeground:"#31363b"}});var andromeda;var init_andromeda=__esm(()=>{andromeda={name:"andromeda",dark:!0,black:"#000000",red:"#cd3131",green:"#05bc79",yellow:"#e5e512",blue:"#2472c8",magenta:"#bc3fbc",cyan:"#0fa8cd",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#cd3131",brightGreen:"#05bc79",brightYellow:"#e5e512",brightBlue:"#2472c8",brightMagenta:"#bc3fbc",brightCyan:"#0fa8cd",brightWhite:"#e5e5e5",foreground:"#e5e5e5",background:"#262a33",cursorColor:"#f8f8f0",cursorText:"#262a33",selectionBackground:"#5a5c62",selectionForeground:"#e5e5e5"}});var relaxed;var init_relaxed=__esm(()=>{relaxed={name:"relaxed",dark:!0,black:"#151515",red:"#bc5653",green:"#909d63",yellow:"#ebc17a",blue:"#6a8799",magenta:"#b06698",cyan:"#c9dfff",white:"#d9d9d9",brightBlack:"#636363",brightRed:"#bc5653",brightGreen:"#a0ac77",brightYellow:"#ebc17a",brightBlue:"#7eaac7",brightMagenta:"#b06698",brightCyan:"#acbbd0",brightWhite:"#f7f7f7",foreground:"#d9d9d9",background:"#353a44",cursorColor:"#d9d9d9",cursorText:"#353a44",selectionBackground:"#6a7985",selectionForeground:"#d9d9d9"}});function getThemeByName(name){if(!name)return ansi16DarkTheme2;let builtin=builtinThemes[name];if(builtin)return builtin;let palette=builtinPalettes[name];if(palette)return deriveTheme(palette);return ansi16DarkTheme2}var ansi16DarkTheme2,ansi16LightTheme2,defaultDarkTheme,defaultLightTheme,builtinPalettes,builtinThemes;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"]},ansi16LightTheme2={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"]},defaultDarkTheme=deriveTheme(nord),defaultLightTheme=deriveTheme(catppuccinLatte),builtinPalettes={"catppuccin-mocha":catppuccinMocha,"catppuccin-frappe":catppuccinFrappe,"catppuccin-macchiato":catppuccinMacchiato,"catppuccin-latte":catppuccinLatte,nord,dracula,"solarized-dark":solarizedDark,"solarized-light":solarizedLight,"tokyo-night":tokyoNight,"tokyo-night-storm":tokyoNightStorm,"tokyo-night-day":tokyoNightDay,"one-dark":oneDark,"gruvbox-dark":gruvboxDark,"gruvbox-light":gruvboxLight,"rose-pine":rosePine,"rose-pine-moon":rosePineMoon,"rose-pine-dawn":rosePineDawn,"kanagawa-wave":kanagawaWave,"kanagawa-dragon":kanagawaDragon,"kanagawa-lotus":kanagawaLotus,"everforest-dark":everforestDark,"everforest-light":everforestLight,monokai,"monokai-pro":monokaiPro,snazzy,"material-dark":materialDark,"material-light":materialLight,palenight,"ayu-dark":ayuDark,"ayu-mirage":ayuMirage,"ayu-light":ayuLight,nightfox,dawnfox,horizon,moonfly,nightfly,"oxocarbon-dark":oxocarbonDark,"oxocarbon-light":oxocarbonLight,sonokai,"edge-dark":edgeDark,"edge-light":edgeLight,"modus-vivendi":modusVivendi,"modus-operandi":modusOperandi,"github-dark":githubDark,"github-light":githubLight,cobalt2,synthwave,"synthwave-84":synthwave84,"tomorrow-night":tomorrowNight,"tomorrow-night-blue":tomorrowNightBlue,"tomorrow-night-eighties":tomorrowNightEighties,zenburn,ubuntu,"tango-dark":tangoDark,"tango-light":tangoLight,cyberpunk,"vscode-dark":vscodeDark,"one-light":oneLight,"one-half-dark":oneHalfDark,"one-half-light":oneHalfLight,"night-owl-light":nightOwlLight,"shades-of-purple":shadesOfPurple,homebrew,neon,"challenger-deep":challengerDeep,"doom-one":doomOne,mariana,darcula,espresso,"iceberg-dark":icebergDark,"iceberg-light":icebergLight,"serendipity-midnight":serendipityMidnight,"serendipity-morning":serendipityMorning,twilight,breeze,andromeda,relaxed},builtinThemes={"dark-ansi16":ansi16DarkTheme2,"light-ansi16":ansi16LightTheme2,"dark-truecolor":defaultDarkTheme,"light-truecolor":defaultLightTheme,dark:defaultDarkTheme,light:defaultLightTheme,"ansi16-dark":ansi16DarkTheme2,"ansi16-light":ansi16LightTheme2}});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()});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}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)}var namedColors,borders;var init_render_helpers=__esm(()=>{init_buffer();init_state();init_resolve();init_unicode();init_helpers();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};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:"|"}}});import{createLogger as createLogger6}from"loggily";function getBgConflictMode(){return bgConflictMode}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]===`
70
+ `);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==="even"||wrap===!0||wrap===void 0}function computeSnugContentWidth(node,fitContentWidth,ctx){let props=node.props,overhead=0,padding=getPadding(props);if(overhead+=padding.left+padding.right,props.borderStyle){let border=getBorderSize(props);overhead+=border.left+border.right}let contentWidth=fitContentWidth-overhead,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,contentWidth)+overhead}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)}var init_measure_phase=__esm(()=>{init_unicode();init_prepared_text();init_pretext();init_helpers()});var measureStats;var init_measure_stats=__esm(()=>{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}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 layoutDirtyNodes,contentDirtyNodes,styleOnlyDirtyNodes,scrollDirtyNodes;var init_dirty_tracking=__esm(()=>{layoutDirtyNodes=new Set,contentDirtyNodes=new Set,styleOnlyDirtyNodes=new Set,scrollDirtyNodes=new Set});import{createLogger as createLogger5}from"loggily";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=countNodes2(root);measureStats.reset();let t0=Date.now();root.layoutNode.calculateLayout(width,height);let elapsed=Date.now()-t0;log6.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 countNodes2(node){let count=1;for(let child of node.children)count+=countNodes2(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}}var log6;var init_layout_phase=__esm(()=>{init_measure_stats();init_dirty_tracking();init_helpers();log6=createLogger5("silvery:layout")});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 githubDark,githubLight;var init_github=__esm(()=>{githubDark={name:"github-dark",dark:!0,black:"#000000",red:"#f78166",green:"#56d364",yellow:"#e3b341",blue:"#6ca4f8",magenta:"#db61a2",cyan:"#2b7489",white:"#ffffff",brightBlack:"#4d4d4d",brightRed:"#f78166",brightGreen:"#56d364",brightYellow:"#e3b341",brightBlue:"#6ca4f8",brightMagenta:"#db61a2",brightCyan:"#2b7489",brightWhite:"#ffffff",foreground:"#8b949e",background:"#101216",cursorColor:"#c9d1d9",cursorText:"#101216",selectionBackground:"#3b5070",selectionForeground:"#c9d1d9"},githubLight={name:"github-light",dark:!1,black:"#3e3e3e",red:"#970b16",green:"#07962a",yellow:"#f8eec7",blue:"#003e8a",magenta:"#e94691",cyan:"#89d1ec",white:"#ffffff",brightBlack:"#666666",brightRed:"#de0000",brightGreen:"#87d5a2",brightYellow:"#f1d007",brightBlue:"#2e6cba",brightMagenta:"#ffa29f",brightCyan:"#1cfafe",brightWhite:"#ffffff",foreground:"#3e3e3e",background:"#f4f4f4",cursorColor:"#3f3f3f",cursorText:"#f4f4f4",selectionBackground:"#a9c1e2",selectionForeground:"#3e3e3e"}});var cobalt2;var init_cobalt2=__esm(()=>{cobalt2={name:"cobalt2",dark:!0,black:"#000000",red:"#ff0000",green:"#38de21",yellow:"#ffe50a",blue:"#1460d2",magenta:"#ff005d",cyan:"#00bbbb",white:"#bbbbbb",brightBlack:"#555555",brightRed:"#f40e17",brightGreen:"#3bd01d",brightYellow:"#edc809",brightBlue:"#5555ff",brightMagenta:"#ff55ff",brightCyan:"#6ae3fa",brightWhite:"#ffffff",foreground:"#ffffff",background:"#132738",cursorColor:"#f0cc09",cursorText:"#132738",selectionBackground:"#18354f",selectionForeground:"#ffffff"}});var synthwave,synthwave84;var init_synthwave=__esm(()=>{synthwave={name:"synthwave",dark:!0,black:"#000000",red:"#f6188f",green:"#1ebb2b",yellow:"#fdf834",blue:"#2186ec",magenta:"#f85a21",cyan:"#12c3e2",white:"#ffffff",brightBlack:"#000000",brightRed:"#f841a0",brightGreen:"#25c141",brightYellow:"#fdf454",brightBlue:"#2f9ded",brightMagenta:"#f97137",brightCyan:"#19cde6",brightWhite:"#ffffff",foreground:"#dad9c7",background:"#000000",cursorColor:"#19cde6",cursorText:"#000000",selectionBackground:"#19cde6",selectionForeground:"#000000"},synthwave84={name:"synthwave-84",dark:!0,black:"#fefefe",red:"#f97e72",green:"#72f1b8",yellow:"#fede5d",blue:"#6d77b3",magenta:"#c792ea",cyan:"#f772e0",white:"#fefefe",brightBlack:"#fefefe",brightRed:"#f88414",brightGreen:"#72f1b8",brightYellow:"#fff951",brightBlue:"#36f9f6",brightMagenta:"#e1acff",brightCyan:"#f92aad",brightWhite:"#fefefe",foreground:"#f0eff1",background:"#2a2139",cursorColor:"#72f1b8",cursorText:"#2a2139",selectionBackground:"#181521",selectionForeground:"#f0eff1"}});var tomorrowNight,tomorrowNightBlue,tomorrowNightEighties;var init_tomorrow_night=__esm(()=>{tomorrowNight={name:"tomorrow-night",dark:!0,black:"#282a2e",red:"#cc6666",green:"#b5bd68",yellow:"#f0c674",blue:"#81a2be",magenta:"#b294bb",cyan:"#8abeb7",white:"#e0e0e0",brightBlack:"#373b41",brightRed:"#cc6666",brightGreen:"#b5bd68",brightYellow:"#f0c674",brightBlue:"#81a2be",brightMagenta:"#b294bb",brightCyan:"#8abeb7",brightWhite:"#ffffff",foreground:"#c5c8c6",background:"#1d1f21",cursorColor:"#c5c8c6",cursorText:"#1d1f21",selectionBackground:"#373b41",selectionForeground:"#c5c8c6"},tomorrowNightBlue={name:"tomorrow-night-blue",dark:!0,black:"#000000",red:"#ff9da4",green:"#d1f1a9",yellow:"#ffeead",blue:"#bbdaff",magenta:"#ebbbff",cyan:"#99ffff",white:"#ffffff",brightBlack:"#000000",brightRed:"#ff9da4",brightGreen:"#d1f1a9",brightYellow:"#ffeead",brightBlue:"#bbdaff",brightMagenta:"#ebbbff",brightCyan:"#99ffff",brightWhite:"#ffffff",foreground:"#ffffff",background:"#002451",cursorColor:"#ffffff",cursorText:"#002451",selectionBackground:"#003f8e",selectionForeground:"#ffffff"},tomorrowNightEighties={name:"tomorrow-night-eighties",dark:!0,black:"#393939",red:"#f2777a",green:"#99cc99",yellow:"#ffcc66",blue:"#6699cc",magenta:"#cc99cc",cyan:"#66cccc",white:"#e0e0e0",brightBlack:"#515151",brightRed:"#f2777a",brightGreen:"#99cc99",brightYellow:"#ffcc66",brightBlue:"#6699cc",brightMagenta:"#cc99cc",brightCyan:"#66cccc",brightWhite:"#ffffff",foreground:"#cccccc",background:"#2d2d2d",cursorColor:"#cccccc",cursorText:"#2d2d2d",selectionBackground:"#515151",selectionForeground:"#cccccc"}});var zenburn;var init_zenburn=__esm(()=>{zenburn={name:"zenburn",dark:!0,black:"#4d4d4d",red:"#705050",green:"#60b48a",yellow:"#f0dfaf",blue:"#506070",magenta:"#dc8cc3",cyan:"#8cd0d3",white:"#dcdccc",brightBlack:"#709080",brightRed:"#dca3a3",brightGreen:"#c3bf9f",brightYellow:"#e0cf9f",brightBlue:"#94bff3",brightMagenta:"#ec93d3",brightCyan:"#93e0e3",brightWhite:"#ffffff",foreground:"#dcdccc",background:"#3f3f3f",cursorColor:"#73635a",cursorText:"#3f3f3f",selectionBackground:"#21322f",selectionForeground:"#dcdccc"}});var ubuntu;var init_ubuntu=__esm(()=>{ubuntu={name:"ubuntu",dark:!0,black:"#2e3436",red:"#cc0000",green:"#4e9a06",yellow:"#c4a000",blue:"#3465a4",magenta:"#75507b",cyan:"#06989a",white:"#d3d7cf",brightBlack:"#555753",brightRed:"#ef2929",brightGreen:"#8ae234",brightYellow:"#fce94f",brightBlue:"#729fcf",brightMagenta:"#ad7fa8",brightCyan:"#34e2e2",brightWhite:"#eeeeec",foreground:"#eeeeec",background:"#300a24",cursorColor:"#bbbbbb",cursorText:"#300a24",selectionBackground:"#b5d5ff",selectionForeground:"#300a24"}});var tangoDark,tangoLight;var init_tango=__esm(()=>{tangoDark={name:"tango-dark",dark:!0,black:"#000000",red:"#cc0000",green:"#4e9a06",yellow:"#c4a000",blue:"#3465a4",magenta:"#75507b",cyan:"#06989a",white:"#d3d7cf",brightBlack:"#555753",brightRed:"#ef2929",brightGreen:"#8ae234",brightYellow:"#fce94f",brightBlue:"#729fcf",brightMagenta:"#ad7fa8",brightCyan:"#34e2e2",brightWhite:"#eeeeec",foreground:"#ffffff",background:"#000000",cursorColor:"#ffffff",cursorText:"#000000",selectionBackground:"#b5d5ff",selectionForeground:"#000000"},tangoLight={name:"tango-light",dark:!1,black:"#000000",red:"#cc0000",green:"#4e9a06",yellow:"#c4a000",blue:"#3465a4",magenta:"#75507b",cyan:"#06989a",white:"#d3d7cf",brightBlack:"#555753",brightRed:"#ef2929",brightGreen:"#8ae234",brightYellow:"#fce94f",brightBlue:"#729fcf",brightMagenta:"#ad7fa8",brightCyan:"#34e2e2",brightWhite:"#eeeeec",foreground:"#000000",background:"#ffffff",cursorColor:"#000000",cursorText:"#ffffff",selectionBackground:"#b5d5ff",selectionForeground:"#000000"}});var cyberpunk;var init_cyberpunk=__esm(()=>{cyberpunk={name:"cyberpunk",dark:!0,black:"#000000",red:"#ff7092",green:"#00fbac",yellow:"#fffa6a",blue:"#00bfff",magenta:"#df95ff",cyan:"#86cbfe",white:"#ffffff",brightBlack:"#000000",brightRed:"#ff8aa4",brightGreen:"#21f6bc",brightYellow:"#fff787",brightBlue:"#1bccfd",brightMagenta:"#e6aefe",brightCyan:"#99d6fc",brightWhite:"#ffffff",foreground:"#e5e5e5",background:"#332a57",cursorColor:"#21f6bc",cursorText:"#332a57",selectionBackground:"#c1deff",selectionForeground:"#332a57"}});var vscodeDark;var init_vscode=__esm(()=>{vscodeDark={name:"vscode-dark",dark:!0,black:"#000000",red:"#cd3131",green:"#0dbc79",yellow:"#e5e510",blue:"#2472c8",magenta:"#bc3fbc",cyan:"#11a8cd",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#f14c4c",brightGreen:"#23d18b",brightYellow:"#f5f543",brightBlue:"#3b8eea",brightMagenta:"#d670d6",brightCyan:"#29b8db",brightWhite:"#e5e5e5",foreground:"#cccccc",background:"#1e1e1e",cursorColor:"#ffffff",cursorText:"#1e1e1e",selectionBackground:"#3a3d41",selectionForeground:"#cccccc"}});var oneLight,oneHalfDark,oneHalfLight;var init_one_light=__esm(()=>{oneLight={name:"one-light",dark:!1,black:"#000000",red:"#de3e35",green:"#3f953a",yellow:"#d2b67c",blue:"#2f5af3",magenta:"#950095",cyan:"#3f953a",white:"#bbbbbb",brightBlack:"#000000",brightRed:"#de3e35",brightGreen:"#3f953a",brightYellow:"#d2b67c",brightBlue:"#2f5af3",brightMagenta:"#a00095",brightCyan:"#3f953a",brightWhite:"#ffffff",foreground:"#2a2c33",background:"#f9f9f9",cursorColor:"#bbbbbb",cursorText:"#f9f9f9",selectionBackground:"#ededed",selectionForeground:"#2a2c33"},oneHalfDark={name:"one-half-dark",dark:!0,black:"#282c34",red:"#e06c75",green:"#98c379",yellow:"#e5c07b",blue:"#61afef",magenta:"#c678dd",cyan:"#56b6c2",white:"#dcdfe4",brightBlack:"#282c34",brightRed:"#e06c75",brightGreen:"#98c379",brightYellow:"#e5c07b",brightBlue:"#61afef",brightMagenta:"#c678dd",brightCyan:"#56b6c2",brightWhite:"#dcdfe4",foreground:"#dcdfe4",background:"#282c34",cursorColor:"#a3b3cc",cursorText:"#282c34",selectionBackground:"#474e5d",selectionForeground:"#dcdfe4"},oneHalfLight={name:"one-half-light",dark:!1,black:"#383a42",red:"#e45649",green:"#50a14f",yellow:"#c18401",blue:"#0184bc",magenta:"#a626a4",cyan:"#0997b3",white:"#fafafa",brightBlack:"#4f525e",brightRed:"#e06c75",brightGreen:"#98c379",brightYellow:"#e5c07b",brightBlue:"#61afef",brightMagenta:"#c678dd",brightCyan:"#56b6c2",brightWhite:"#ffffff",foreground:"#383a42",background:"#fafafa",cursorColor:"#bfceff",cursorText:"#fafafa",selectionBackground:"#bfceff",selectionForeground:"#383a42"}});var nightOwlLight;var init_night_owl=__esm(()=>{nightOwlLight={name:"night-owl-light",dark:!1,black:"#011627",red:"#d3423e",green:"#2aa298",yellow:"#daaa01",blue:"#4876d6",magenta:"#403f53",cyan:"#08916a",white:"#7a8181",brightBlack:"#7a8181",brightRed:"#f76e6e",brightGreen:"#49d0c5",brightYellow:"#dac26b",brightBlue:"#5ca7e4",brightMagenta:"#697098",brightCyan:"#00c990",brightWhite:"#989fb1",foreground:"#403f53",background:"#ffffff",cursorColor:"#403f53",cursorText:"#ffffff",selectionBackground:"#f2f2f2",selectionForeground:"#403f53"}});var shadesOfPurple;var init_shades_of_purple=__esm(()=>{shadesOfPurple={name:"shades-of-purple",dark:!0,black:"#000000",red:"#d90429",green:"#3ad900",yellow:"#ffe700",blue:"#6943ff",magenta:"#ff2c70",cyan:"#00c5c7",white:"#c7c7c7",brightBlack:"#686868",brightRed:"#f92a1c",brightGreen:"#43d426",brightYellow:"#f1d000",brightBlue:"#6871ff",brightMagenta:"#ff77ff",brightCyan:"#79e8fb",brightWhite:"#ffffff",foreground:"#ffffff",background:"#1e1d40",cursorColor:"#fad000",cursorText:"#1e1d40",selectionBackground:"#b362ff",selectionForeground:"#ffffff"}});var homebrew;var init_homebrew=__esm(()=>{homebrew={name:"homebrew",dark:!0,black:"#000000",red:"#990000",green:"#00a600",yellow:"#999900",blue:"#0000b2",magenta:"#b200b2",cyan:"#00a6b2",white:"#bfbfbf",brightBlack:"#666666",brightRed:"#e50000",brightGreen:"#00d900",brightYellow:"#e5e500",brightBlue:"#0000ff",brightMagenta:"#e500e5",brightCyan:"#00e5e5",brightWhite:"#e5e5e5",foreground:"#00ff00",background:"#000000",cursorColor:"#23ff18",cursorText:"#000000",selectionBackground:"#083905",selectionForeground:"#00ff00"}});var neon;var init_neon=__esm(()=>{neon={name:"neon",dark:!0,black:"#000000",red:"#ff3045",green:"#5ffa74",yellow:"#fffc7e",blue:"#0208cb",magenta:"#f924e7",cyan:"#00fffc",white:"#c7c7c7",brightBlack:"#686868",brightRed:"#ff5a5a",brightGreen:"#75ff88",brightYellow:"#fffd96",brightBlue:"#3c40cb",brightMagenta:"#f15be5",brightCyan:"#88fffe",brightWhite:"#ffffff",foreground:"#00fffc",background:"#14161a",cursorColor:"#c7c7c7",cursorText:"#14161a",selectionBackground:"#0013ff",selectionForeground:"#ffffff"}});var challengerDeep;var init_challenger_deep=__esm(()=>{challengerDeep={name:"challenger-deep",dark:!0,black:"#141228",red:"#ff5458",green:"#62d196",yellow:"#ffb378",blue:"#65b2ff",magenta:"#906cff",cyan:"#63f2f1",white:"#a6b3cc",brightBlack:"#565575",brightRed:"#ff8080",brightGreen:"#95ffa4",brightYellow:"#ffe9aa",brightBlue:"#91ddff",brightMagenta:"#c991e1",brightCyan:"#aaffe4",brightWhite:"#cbe3e7",foreground:"#cbe1e7",background:"#1e1c31",cursorColor:"#fbfcfc",cursorText:"#1e1c31",selectionBackground:"#cbe1e7",selectionForeground:"#1e1c31"}});var doomOne;var init_doom_one=__esm(()=>{doomOne={name:"doom-one",dark:!0,black:"#000000",red:"#ff6c6b",green:"#98be65",yellow:"#ecbe7b",blue:"#a9a1e1",magenta:"#c678dd",cyan:"#51afef",white:"#bbc2cf",brightBlack:"#000000",brightRed:"#ff6655",brightGreen:"#99bb66",brightYellow:"#ecbe7b",brightBlue:"#a9a1e1",brightMagenta:"#c678dd",brightCyan:"#51afef",brightWhite:"#bfbfbf",foreground:"#bbc2cf",background:"#282c34",cursorColor:"#51afef",cursorText:"#282c34",selectionBackground:"#42444b",selectionForeground:"#bbc2cf"}});var mariana;var init_mariana=__esm(()=>{mariana={name:"mariana",dark:!0,black:"#000000",red:"#ec5f66",green:"#99c794",yellow:"#f9ae58",blue:"#6699cc",magenta:"#c695c6",cyan:"#5fb4b4",white:"#f7f7f7",brightBlack:"#333333",brightRed:"#f97b58",brightGreen:"#acd1a8",brightYellow:"#fac761",brightBlue:"#85add6",brightMagenta:"#d8b6d8",brightCyan:"#82c4c4",brightWhite:"#ffffff",foreground:"#d8dee9",background:"#343d46",cursorColor:"#fcbb6a",cursorText:"#343d46",selectionBackground:"#4e5a65",selectionForeground:"#d8dee9"}});var darcula;var init_darcula=__esm(()=>{darcula={name:"darcula",dark:!0,black:"#000000",red:"#fa5355",green:"#126e00",yellow:"#c2c300",blue:"#4581eb",magenta:"#fa54ff",cyan:"#33c2c1",white:"#adadad",brightBlack:"#555555",brightRed:"#fb7172",brightGreen:"#67ff4f",brightYellow:"#ffff00",brightBlue:"#6d9df1",brightMagenta:"#fb82ff",brightCyan:"#60d3d1",brightWhite:"#eeeeee",foreground:"#adadad",background:"#202020",cursorColor:"#ffffff",cursorText:"#202020",selectionBackground:"#1a3272",selectionForeground:"#adadad"}});var espresso;var init_espresso=__esm(()=>{espresso={name:"espresso",dark:!0,black:"#353535",red:"#d25252",green:"#a5c261",yellow:"#ffc66d",blue:"#6c99bb",magenta:"#d197d9",cyan:"#bed6ff",white:"#eeeeec",brightBlack:"#535353",brightRed:"#f00c0c",brightGreen:"#c2e075",brightYellow:"#e1e48b",brightBlue:"#8ab7d9",brightMagenta:"#efb5f7",brightCyan:"#dcf4ff",brightWhite:"#ffffff",foreground:"#ffffff",background:"#323232",cursorColor:"#d6d6d6",cursorText:"#323232",selectionBackground:"#5b5b5b",selectionForeground:"#ffffff"}});var icebergDark,icebergLight;var init_iceberg=__esm(()=>{icebergDark={name:"iceberg-dark",dark:!0,black:"#1e2132",red:"#e27878",green:"#b4be82",yellow:"#e2a478",blue:"#84a0c6",magenta:"#a093c7",cyan:"#89b8c2",white:"#c6c8d1",brightBlack:"#6b7089",brightRed:"#e98989",brightGreen:"#c0ca8e",brightYellow:"#e9b189",brightBlue:"#91acd1",brightMagenta:"#ada0d3",brightCyan:"#95c4ce",brightWhite:"#d2d4de",foreground:"#c6c8d1",background:"#161821",cursorColor:"#c6c8d1",cursorText:"#161821",selectionBackground:"#c6c8d1",selectionForeground:"#161821"},icebergLight={name:"iceberg-light",dark:!1,black:"#dcdfe7",red:"#cc517a",green:"#668e3d",yellow:"#c57339",blue:"#2d539e",magenta:"#7759b4",cyan:"#3f83a6",white:"#33374c",brightBlack:"#8389a3",brightRed:"#cc3768",brightGreen:"#598030",brightYellow:"#b6662d",brightBlue:"#22478e",brightMagenta:"#6845ad",brightCyan:"#327698",brightWhite:"#262a3f",foreground:"#33374c",background:"#e8e9ec",cursorColor:"#33374c",cursorText:"#e8e9ec",selectionBackground:"#33374c",selectionForeground:"#e8e9ec"}});var serendipityMidnight,serendipityMorning;var init_serendipity=__esm(()=>{serendipityMidnight={name:"serendipity-midnight",dark:!0,black:"#232534",red:"#ee8679",green:"#9ccfd8",yellow:"#f8d2c9",blue:"#5ba2d0",magenta:"#a78bfa",cyan:"#94b8ff",white:"#dee0ef",brightBlack:"#8d8f9e",brightRed:"#ee8679",brightGreen:"#9ccfd8",brightYellow:"#f8d2c9",brightBlue:"#5ba2d0",brightMagenta:"#a78bfa",brightCyan:"#94b8ff",brightWhite:"#dee0ef",foreground:"#dee0ef",background:"#1c1e2d",cursorColor:"#6b6d7c",cursorText:"#1c1e2d",selectionBackground:"#2c2e3d",selectionForeground:"#dee0ef"},serendipityMorning={name:"serendipity-morning",dark:!1,black:"#f2e9de",red:"#d26a5d",green:"#77aab3",yellow:"#c8a299",blue:"#3788be",magenta:"#886cdb",cyan:"#7397de",white:"#575279",brightBlack:"#6e6a86",brightRed:"#d26a5d",brightGreen:"#77aab3",brightYellow:"#c8a299",brightBlue:"#3788be",brightMagenta:"#886cdb",brightCyan:"#7397de",brightWhite:"#575279",foreground:"#575279",background:"#fffaf3",cursorColor:"#9893a5",cursorText:"#fffaf3",selectionBackground:"#f4efea",selectionForeground:"#575279"}});var twilight;var init_twilight=__esm(()=>{twilight={name:"twilight",dark:!0,black:"#141414",red:"#c06d44",green:"#afb97a",yellow:"#c2a86c",blue:"#44474a",magenta:"#b4be7c",cyan:"#778385",white:"#ffffd4",brightBlack:"#262626",brightRed:"#de7c4c",brightGreen:"#ccd88c",brightYellow:"#e2c47e",brightBlue:"#5a5e62",brightMagenta:"#d0dc8e",brightCyan:"#8a989b",brightWhite:"#ffffd4",foreground:"#ffffd4",background:"#141414",cursorColor:"#ffffff",cursorText:"#141414",selectionBackground:"#313131",selectionForeground:"#ffffd4"}});var breeze;var init_breeze=__esm(()=>{breeze={name:"breeze",dark:!0,black:"#31363b",red:"#ed1515",green:"#11d116",yellow:"#f67400",blue:"#1d99f3",magenta:"#9b59b6",cyan:"#1abc9c",white:"#eff0f1",brightBlack:"#7f8c8d",brightRed:"#c0392b",brightGreen:"#1cdc9a",brightYellow:"#fdbc4b",brightBlue:"#3daee9",brightMagenta:"#8e44ad",brightCyan:"#16a085",brightWhite:"#fcfcfc",foreground:"#eff0f1",background:"#31363b",cursorColor:"#eff0f1",cursorText:"#31363b",selectionBackground:"#eff0f1",selectionForeground:"#31363b"}});var andromeda;var init_andromeda=__esm(()=>{andromeda={name:"andromeda",dark:!0,black:"#000000",red:"#cd3131",green:"#05bc79",yellow:"#e5e512",blue:"#2472c8",magenta:"#bc3fbc",cyan:"#0fa8cd",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#cd3131",brightGreen:"#05bc79",brightYellow:"#e5e512",brightBlue:"#2472c8",brightMagenta:"#bc3fbc",brightCyan:"#0fa8cd",brightWhite:"#e5e5e5",foreground:"#e5e5e5",background:"#262a33",cursorColor:"#f8f8f0",cursorText:"#262a33",selectionBackground:"#5a5c62",selectionForeground:"#e5e5e5"}});var relaxed;var init_relaxed=__esm(()=>{relaxed={name:"relaxed",dark:!0,black:"#151515",red:"#bc5653",green:"#909d63",yellow:"#ebc17a",blue:"#6a8799",magenta:"#b06698",cyan:"#c9dfff",white:"#d9d9d9",brightBlack:"#636363",brightRed:"#bc5653",brightGreen:"#a0ac77",brightYellow:"#ebc17a",brightBlue:"#7eaac7",brightMagenta:"#b06698",brightCyan:"#acbbd0",brightWhite:"#f7f7f7",foreground:"#d9d9d9",background:"#353a44",cursorColor:"#d9d9d9",cursorText:"#353a44",selectionBackground:"#6a7985",selectionForeground:"#d9d9d9"}});function getThemeByName(name){if(!name)return ansi16DarkTheme2;let builtin=builtinThemes[name];if(builtin)return builtin;let palette=builtinPalettes[name];if(palette)return deriveTheme(palette);return ansi16DarkTheme2}var ansi16DarkTheme2,ansi16LightTheme2,defaultDarkTheme,defaultLightTheme,builtinPalettes,builtinThemes;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"]},ansi16LightTheme2={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"]},defaultDarkTheme=deriveTheme(nord),defaultLightTheme=deriveTheme(catppuccinLatte),builtinPalettes={"catppuccin-mocha":catppuccinMocha,"catppuccin-frappe":catppuccinFrappe,"catppuccin-macchiato":catppuccinMacchiato,"catppuccin-latte":catppuccinLatte,nord,dracula,"solarized-dark":solarizedDark,"solarized-light":solarizedLight,"tokyo-night":tokyoNight,"tokyo-night-storm":tokyoNightStorm,"tokyo-night-day":tokyoNightDay,"one-dark":oneDark,"gruvbox-dark":gruvboxDark,"gruvbox-light":gruvboxLight,"rose-pine":rosePine,"rose-pine-moon":rosePineMoon,"rose-pine-dawn":rosePineDawn,"kanagawa-wave":kanagawaWave,"kanagawa-dragon":kanagawaDragon,"kanagawa-lotus":kanagawaLotus,"everforest-dark":everforestDark,"everforest-light":everforestLight,monokai,"monokai-pro":monokaiPro,snazzy,"material-dark":materialDark,"material-light":materialLight,palenight,"ayu-dark":ayuDark,"ayu-mirage":ayuMirage,"ayu-light":ayuLight,nightfox,dawnfox,horizon,moonfly,nightfly,"oxocarbon-dark":oxocarbonDark,"oxocarbon-light":oxocarbonLight,sonokai,"edge-dark":edgeDark,"edge-light":edgeLight,"modus-vivendi":modusVivendi,"modus-operandi":modusOperandi,"github-dark":githubDark,"github-light":githubLight,cobalt2,synthwave,"synthwave-84":synthwave84,"tomorrow-night":tomorrowNight,"tomorrow-night-blue":tomorrowNightBlue,"tomorrow-night-eighties":tomorrowNightEighties,zenburn,ubuntu,"tango-dark":tangoDark,"tango-light":tangoLight,cyberpunk,"vscode-dark":vscodeDark,"one-light":oneLight,"one-half-dark":oneHalfDark,"one-half-light":oneHalfLight,"night-owl-light":nightOwlLight,"shades-of-purple":shadesOfPurple,homebrew,neon,"challenger-deep":challengerDeep,"doom-one":doomOne,mariana,darcula,espresso,"iceberg-dark":icebergDark,"iceberg-light":icebergLight,"serendipity-midnight":serendipityMidnight,"serendipity-morning":serendipityMorning,twilight,breeze,andromeda,relaxed},builtinThemes={"dark-ansi16":ansi16DarkTheme2,"light-ansi16":ansi16LightTheme2,"dark-truecolor":defaultDarkTheme,"light-truecolor":defaultLightTheme,dark:defaultDarkTheme,light:defaultLightTheme,"ansi16-dark":ansi16DarkTheme2,"ansi16-light":ansi16LightTheme2}});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()});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}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)}var namedColors,borders;var init_render_helpers=__esm(()=>{init_buffer();init_state();init_resolve();init_unicode();init_helpers();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};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:"|"}}});import{createLogger as createLogger6}from"loggily";function getBgConflictMode(){return bgConflictMode}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
71
  `)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===`
68
72
  `||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(`
69
- `);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)=>truncateText2(line,width,"end",ctx));if(wrap==="truncate-start")return lines.map((line)=>truncateText2(line,width,"start",ctx));if(wrap==="truncate-middle")return lines.map((line)=>truncateText2(line,width,"middle",ctx));if(wrap==="even"){let gWidthFn=ctx?.measurer?.graphemeWidth?.bind(ctx.measurer)??graphemeWidth,analysis=buildTextAnalysis(normalizedText,gWidthFn);return optimalWrap(normalizedText,analysis,width)}if(ctx)return ctx.measurer.wrapText(normalizedText,width,!0,trim);return wrapText(normalizedText,width,!0,trim)}function truncateText2(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}}var log6,bgConflictMode,warnedBgConflicts;var init_render_text=__esm(()=>{init_buffer();init_unicode();init_render_helpers();init_prepared_text();init_pretext();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"})();warnedBgConflicts=new Set});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)}var init_render_box=__esm(()=>{init_helpers();init_render_helpers();init_render_text()});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 init_system=()=>{};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)}var cycle=0,batchDepth=0,notifyIndex=0,queuedLength=0,activeSub,queued,link,unlink,propagate,checkDirty,shallowPropagate;var init_esm=__esm(()=>{init_system();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)}})});var init_src3=__esm(()=>{init_esm();init_esm()});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)"}:
73
+ `);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)=>truncateText2(line,width,"end",ctx));if(wrap==="truncate-start")return lines.map((line)=>truncateText2(line,width,"start",ctx));if(wrap==="truncate-middle")return lines.map((line)=>truncateText2(line,width,"middle",ctx));if(wrap==="even"){let gWidthFn=ctx?.measurer?.graphemeWidth?.bind(ctx.measurer)??graphemeWidth,analysis=buildTextAnalysis(normalizedText,gWidthFn);return optimalWrap(normalizedText,analysis,width)}if(ctx)return ctx.measurer.wrapText(normalizedText,width,!0,trim);return wrapText(normalizedText,width,!0,trim)}function truncateText2(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),log7.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}}var log7,bgConflictMode,warnedBgConflicts;var init_render_text=__esm(()=>{init_buffer();init_unicode();init_render_helpers();init_prepared_text();init_pretext();log7=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"})();warnedBgConflicts=new Set});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)}var init_render_box=__esm(()=>{init_helpers();init_render_helpers();init_render_text()});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 init_system=()=>{};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)}var cycle=0,batchDepth=0,notifyIndex=0,queuedLength=0,activeSub,queued,link,unlink,propagate,checkDirty,shallowPropagate;var init_esm=__esm(()=>{init_system();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)}})});var init_src4=__esm(()=>{init_esm();init_esm()});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)"}:
70
74
  ${mismatches.join(`
71
- `)}`)}function getReactiveState(node){let state=nodeStates.get(node);if(!state)state=createReactiveNodeState(),nodeStates.set(node,state);return state}var nodeStates;var init_reactive_node=__esm(()=>{init_src3();nodeStates=new WeakMap});import{createLogger as createLogger7}from"loggily";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(hasPrevBuffer&&!isAnyDirty(root.dirtyBits,root.dirtyEpoch)&&!isCurrentEpoch(root.layoutChangedThisFrame)){if(instr.enabled)instr.stats._noopSkip=1;return advanceRenderEpoch(),prevBuffer}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);let anyLayoutChanged=isCurrentEpoch(root.layoutChangedThisFrame)||isDirty(root.dirtyBits,root.dirtyEpoch,SUBTREE_BIT);return syncPrevLayout(root,anyLayoutChanged||!hasPrevBuffer),advanceRenderEpoch(),buffer}function syncPrevLayout(root,layoutPhaseRan){if(!layoutPhaseRan)return;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"}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 contentLog,traceLog,cellLog,_instrumentEnabled,_renderPhaseStats,_renderPhaseCallCount=0,_nodeTrace,_nodeTraceEnabled,_reactiveEnabled,_reactiveVerifyEnabled;var init_render_phase=__esm(()=>{init_buffer();init_helpers();init_render_box();init_render_helpers();init_render_text();init_state();init_reactive_node();contentLog=createLogger7("silvery:content"),traceLog=createLogger7("silvery:content:trace"),cellLog=createLogger7("silvery:content:cell");_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:"",_noopSkip:0,_prevBufferNull:0,_prevBufferDimMismatch:0,_hasPrevBuffer:0,_layoutW:0,_layoutH:0,_prevW:0,_prevH:0,_callCount: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)});import{createLogger as createLogger8}from"loggily";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}]`}}}var log7,baseLog;var init_ag=__esm(()=>{init_buffer();init_unicode();init_measure_phase();init_layout_phase();init_render_phase();init_dirty_tracking();log7=createLogger8("silvery:render"),baseLog=createLogger8("@silvery/ag-react")});var init_render_phase_adapter=__esm(()=>{init_helpers();init_unicode();init_render_text()});import{createLogger as createLogger9}from"loggily";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}}var log8,baseLog2;var init_pipeline=__esm(()=>{init_unicode();init_ag();init_measure_phase();init_layout_phase();init_render_phase();init_render_phase_adapter();init_output_phase();init_render_phase_adapter();init_render_phase();init_layout_phase();init_measure_phase();init_output_phase();log8=createLogger9("silvery:render"),baseLog2=createLogger9("@silvery/ag-react")});var init_pipeline2=__esm(()=>{init_pipeline()});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}}var LAYOUT_PROPS,TEXT_CONTENT_PROPS,STYLE_PROPS,NO_CHANGES;var init_helpers2=__esm(()=>{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}});import{createLogger as createLogger10}from"loggily";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(`
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){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}var measureLog;var init_nodes=__esm(()=>{init_unicode();init_measure_stats();measureLog=createLogger10("silvery:measure")});import{createContext as createContext2}from"react";import{DefaultEventPriority,DiscreteEventPriority,NoEventPriority}from"react-reconciler/constants.js";import{createLogger as createLogger11}from"loggily";function normalizeNodeType(type){if(type==="ink-box")return"silvery-box";if(type==="ink-text")return"silvery-text";return type}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)}}function runWithDiscreteEvent(fn){let prev=currentUpdatePriority;currentUpdatePriority=DiscreteEventPriority;try{fn()}finally{currentUpdatePriority=prev}}var log9,onNodeRemovedCallback=null,hasWarnedBoxInsideText=!1,inkStrictValidation=!1,currentUpdatePriority,hostConfig;var init_host_config=__esm(()=>{init_dirty_tracking();init_helpers2();init_nodes();log9=createLogger11("silvery:reconciler");currentUpdatePriority=NoEventPriority;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)}}});import Reconciler from"react-reconciler";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}var reconciler;var init_reconciler=__esm(()=>{init_host_config();init_nodes();init_host_config();reconciler=Reconciler(hostConfig)});import Reconciler2 from"react-reconciler";var stringReconciler;var init_string_reconciler=__esm(()=>{init_host_config();stringReconciler=Reconciler2({...hostConfig,isPrimaryRenderer:!1})});var exports_render_string={};__export(exports_render_string,{renderStringSync:()=>renderStringSync,renderString:()=>renderString});import React,{act}from"react";async function ensureLayoutEngine(){if(engineInitialized||isLayoutEngineInitialized())return;let{ensureDefaultLayoutEngine:ensureDefaultLayoutEngine2}=await Promise.resolve().then(() => exports_layout_engine);await ensureDefaultLayoutEngine2(),engineInitialized=!0}async function renderString(element,options={}){return await ensureLayoutEngine(),renderStringSync(element,options)}function renderStringSync(element,options={}){if(!isLayoutEngineInitialized())throw Error("Layout engine not initialized. Use renderString() (async) or initialize with setLayoutEngine().");let{width=80,height=24,plain=!1,pipelineConfig,trimTrailingWhitespace=!0,trimEmptyLines=!0,onContentHeight,alwaysStyled=!1}=options,hadReactCommit=!1,container=createContainer(()=>{hadReactCommit=!0}),uncaughtError=null,onUncaughtError=(error)=>{uncaughtError=error},fiberRoot=stringReconciler.createContainer(container,1,null,!1,null,"",onUncaughtError,()=>{},()=>{},null),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)));if(withActEnvironment(()=>{act(()=>{stringReconciler.updateContainerSync(wrapped,fiberRoot,null,null),stringReconciler.flushSyncWork()})}),uncaughtError)throw uncaughtError instanceof Error?uncaughtError:Error(String(uncaughtError));let buffer,rootNode,MAX_ITERATIONS=5;for(let i=0;i<MAX_ITERATIONS;i++)if(hadReactCommit=!1,withActEnvironment(()=>{if(act(()=>{let root=getContainerRoot(container);rootNode=root,buffer=executeRender(root,width,height,null,void 0,pipelineConfig).buffer}),!hadReactCommit)act(()=>{stringReconciler.flushSyncWork()})}),!hadReactCommit)break;if(onContentHeight&&rootNode){let maxBottom=0,hasChildren=!1;for(let child of rootNode.children)if(child.boxRect){hasChildren=!0;let props=child.props,mb=props.marginBottom??props.marginY??props.margin??0,childBottom=child.boxRect.y+child.boxRect.height+mb;if(childBottom>maxBottom)maxBottom=childBottom}onContentHeight(hasChildren?maxBottom:0)}return withActEnvironment(()=>{act(()=>{stringReconciler.updateContainerSync(null,fiberRoot,null,null),stringReconciler.flushSyncWork()})}),plain&&!alwaysStyled?bufferToText(buffer,{trimTrailingWhitespace,trimEmptyLines}):bufferToStyledText(buffer,{trimTrailingWhitespace,trimEmptyLines})}function withActEnvironment(fn){let prev=globalThis.IS_REACT_ACT_ENVIRONMENT;globalThis.IS_REACT_ACT_ENVIRONMENT=!0;try{fn()}finally{globalThis.IS_REACT_ACT_ENVIRONMENT=prev}}var engineInitialized=!1;var init_render_string=__esm(()=>{init_ansi2();init_buffer();init_context();init_pipeline2();init_reconciler();init_string_reconciler()});var exports_devtools={};__export(exports_devtools,{isDevToolsConnected:()=>isDevToolsConnected,connectDevTools:()=>connectDevTools,autoConnectDevTools:()=>autoConnectDevTools});import{createLogger as createLogger14}from"loggily";async function connectDevTools(){if(connected)return!0;try{if(typeof globalThis.WebSocket>"u")try{let ws=await import("ws");globalThis.WebSocket=ws.default??ws}catch{return log12.warn?.("WebSocket polyfill (ws) not available. Install ws for DevTools support: bun add -d ws"),!1}if(typeof globalThis.window>"u")globalThis.window=globalThis;if(!globalThis.__REACT_DEVTOOLS_COMPONENT_FILTERS__)globalThis.__REACT_DEVTOOLS_COMPONENT_FILTERS__=[{type:1,value:7,isEnabled:!0},{type:2,value:"SilveryApp",isEnabled:!0,isValid:!0}];let devtools=await import("react-devtools-core");return devtools.initialize(),devtools.connectToDevTools(),reconciler.injectIntoDevTools(),connected=!0,!0}catch(error){let message=error instanceof Error?error.message:String(error);return log12.warn?.(`Failed to connect to React DevTools. Install react-devtools-core: bun add -d react-devtools-core
73
- Error: ${message}`),!1}}function isDevToolsConnected(){return connected}async function autoConnectDevTools(){if(process.env.DEBUG_DEVTOOLS==="1"||process.env.DEBUG_DEVTOOLS==="true")await connectDevTools()}var log12,connected=!1;var init_devtools=__esm(()=>{init_reconciler();log12=createLogger14("silvery:devtools")});init_context();import{forwardRef,useImperativeHandle,useLayoutEffect,useRef,useState}from"react";import{jsxDEV}from"react/jsx-dev-runtime";var Box=forwardRef(function(props,ref){let{children,onLayout,...restProps}=props,nodeRef=useRef(null),[node,setNode]=useState(null),lastReportedLayout=useRef(null);return useLayoutEffect(()=>{if(nodeRef.current)setNode(nodeRef.current)},[]),useLayoutEffect(()=>{if(!onLayout||!node)return;let handleLayoutChange=()=>{let layout=node.boxRect;if(!layout)return;let last=lastReportedLayout.current;if(!last||last.x!==layout.x||last.y!==layout.y||last.width!==layout.width||last.height!==layout.height)lastReportedLayout.current=layout,onLayout(layout)};if(node.layoutSubscribers.add(handleLayoutChange),node.boxRect)handleLayoutChange();return()=>{node.layoutSubscribers.delete(handleLayoutChange)}},[node,onLayout]),useImperativeHandle(ref,()=>({getNode:()=>nodeRef.current,getBoxRect:()=>nodeRef.current?.boxRect??null,getScrollRect:()=>nodeRef.current?.scrollRect??null}),[]),jsxDEV("silvery-box",{ref:nodeRef,...restProps,children:jsxDEV(NodeContext.Provider,{value:node,children},void 0,!1,void 0,this)},void 0,!1,void 0,this)});import React3,{forwardRef as forwardRef2,useCallback as useCallback3,useContext as useContext3,useEffect as useEffect4,useImperativeHandle as useImperativeHandle2,useMemo as useMemo3,useRef as useRef5,useState as useState4}from"react";import{useCallback,useEffect,useMemo,useRef as useRef2,useState as useState2}from"react";function calcEdgeBasedScrollOffset(selectedIndex,currentOffset,visibleCount,totalCount,padding=1){if(totalCount<=visibleCount)return 0;let effectivePadding=padding*2>=visibleCount?0:padding,visibleStart=currentOffset,visibleEnd=currentOffset+visibleCount-1,paddedStart=visibleStart+effectivePadding,paddedEnd=visibleEnd-effectivePadding,newOffset=currentOffset;if(selectedIndex<paddedStart)newOffset=Math.max(0,selectedIndex-effectivePadding);else if(effectivePadding===0&&selectedIndex===paddedStart&&currentOffset>0&&visibleCount>padding)newOffset=Math.max(0,selectedIndex-padding);else if(selectedIndex>paddedEnd)newOffset=Math.min(totalCount-visibleCount,selectedIndex-visibleCount+effectivePadding+1);return Math.max(0,Math.min(newOffset,totalCount-visibleCount))}var DEFAULT_SCROLL_PADDING=1,DEFAULT_OVERSCAN=5,DEFAULT_MAX_RENDERED=100;function getHeight(index,estimateHeight,measuredHeights,getItemKey,avgMeasuredHeight){if(measuredHeights&&measuredHeights.size>0){let key=getItemKey?getItemKey(index):index,measured=measuredHeights.get(key);if(measured!==void 0)return measured;if(avgMeasuredHeight!==void 0)return avgMeasuredHeight}return typeof estimateHeight==="function"?estimateHeight(index):estimateHeight}function calcAverageHeight(count,estimateHeight,measuredHeights){if(count===0)return 1;if(measuredHeights&&measuredHeights.size>0){let total2=0;for(let h of measuredHeights.values())total2+=h;return total2/measuredHeights.size}if(typeof estimateHeight==="number")return estimateHeight;let sampleSize=Math.min(count,10),total=0;for(let i=0;i<sampleSize;i++)total+=typeof estimateHeight==="function"?estimateHeight(i):estimateHeight;return total/sampleSize}function sumHeights(startIndex,endIndex,estimateHeight,gap,measuredHeights,getItemKey){let itemCount=endIndex-startIndex;if(itemCount<=0)return 0;let gapTotal=(itemCount-1)*gap;if((!measuredHeights||measuredHeights.size===0)&&typeof estimateHeight==="number")return itemCount*estimateHeight+gapTotal;let avgMeasured;if(measuredHeights&&measuredHeights.size>0){let measuredTotal=0;for(let h of measuredHeights.values())measuredTotal+=h;avgMeasured=measuredTotal/measuredHeights.size}let total=0;for(let i=startIndex;i<endIndex;i++)total+=getHeight(i,estimateHeight,measuredHeights,getItemKey,avgMeasured);return total+gapTotal}function useVirtualizer(config){let{count,estimateHeight,viewportHeight,scrollTo,scrollPadding=DEFAULT_SCROLL_PADDING,overscan=DEFAULT_OVERSCAN,maxRendered=DEFAULT_MAX_RENDERED,gap=0,getItemKey}=config,measuredHeightsRef=useRef2(new Map),[measurementVersion,setMeasurementVersion]=useState2(0),measureItem=useCallback((key,height)=>{let cache=measuredHeightsRef.current;if(cache.get(key)===height)return!1;return cache.set(key,height),setMeasurementVersion((v)=>v+1),!0},[]),measuredHeights=measuredHeightsRef.current,avgHeight=calcAverageHeight(count,estimateHeight,measuredHeights),estimatedVisibleCount=Math.max(1,Math.ceil(viewportHeight/(avgHeight+gap))),selectedIndexRef=useRef2(Math.max(0,Math.min(scrollTo??0,count-1))),scrollOffsetRef=useRef2(calcEdgeBasedScrollOffset(selectedIndexRef.current,0,estimatedVisibleCount,count,scrollPadding)),[,setScrollOffset]=useState2(()=>scrollOffsetRef.current);if(scrollTo!==void 0){let clampedIndex=Math.max(0,Math.min(scrollTo,count-1));selectedIndexRef.current=clampedIndex;let newOffset=calcEdgeBasedScrollOffset(clampedIndex,scrollOffsetRef.current,estimatedVisibleCount,count,scrollPadding);if(newOffset!==scrollOffsetRef.current)scrollOffsetRef.current=newOffset}let effectiveScrollOffset=scrollOffsetRef.current;useEffect(()=>{setScrollOffset((prev)=>prev===effectiveScrollOffset?prev:effectiveScrollOffset)},[effectiveScrollOffset]);let scrollToItem=useCallback((index)=>{let clampedIndex=Math.max(0,Math.min(index,count-1));selectedIndexRef.current=clampedIndex;let newOffset=calcEdgeBasedScrollOffset(clampedIndex,scrollOffsetRef.current,estimatedVisibleCount,count,scrollPadding);scrollOffsetRef.current=newOffset,setScrollOffset(newOffset)},[count,estimatedVisibleCount,scrollPadding]),getKey=useCallback((index)=>{return getItemKey?getItemKey(index):index},[getItemKey]),windowCalc=useMemo(()=>{if(count===0)return{startIndex:0,endIndex:0,leadingHeight:0,trailingHeight:0};let minWindowSize=estimatedVisibleCount+2*overscan;if(count<=minWindowSize)return{startIndex:0,endIndex:count,leadingHeight:0,trailingHeight:0};let renderCount=Math.min(estimatedVisibleCount+2*overscan,maxRendered),viewportCenter=selectedIndexRef.current,halfWindow=Math.floor(renderCount/2),start=Math.max(0,viewportCenter-halfWindow),end=Math.min(count,start+renderCount);if(end===count)start=Math.max(0,end-renderCount);let leadingSize=sumHeights(0,start,estimateHeight,gap,measuredHeights,getItemKey),trailingSize=sumHeights(end,count,estimateHeight,gap,measuredHeights,getItemKey);return{startIndex:start,endIndex:end,leadingHeight:leadingSize,trailingHeight:trailingSize}},[count,effectiveScrollOffset,maxRendered,overscan,estimateHeight,avgHeight,gap,measurementVersion,getItemKey]),onEndReachedRef=useRef2(config.onEndReached);onEndReachedRef.current=config.onEndReached;let firedForCountRef=useRef2(-1),threshold=config.onEndReachedThreshold??DEFAULT_OVERSCAN,{endIndex}=windowCalc;return useEffect(()=>{if(!onEndReachedRef.current||count===0)return;if(endIndex>=count-threshold&&firedForCountRef.current!==count)firedForCountRef.current=count,onEndReachedRef.current()},[endIndex,count,threshold]),{range:{startIndex:windowCalc.startIndex,endIndex:windowCalc.endIndex},leadingHeight:windowCalc.leadingHeight,trailingHeight:windowCalc.trailingHeight,hiddenBefore:windowCalc.startIndex,hiddenAfter:count-windowCalc.endIndex,scrollOffset:effectiveScrollOffset,scrollToItem,getKey,measureItem,measuredHeights}}init_context();init_keys();import{useContext,useEffect as useEffect2,useRef as useRef3}from"react";function useInput(inputHandler,options={}){let rt=useContext(RuntimeContext),{isActive=!0,onPaste,onRelease}=options,handlerRef=useRef3(inputHandler);handlerRef.current=inputHandler;let onPasteRef=useRef3(onPaste);onPasteRef.current=onPaste;let onReleaseRef=useRef3(onRelease);onReleaseRef.current=onRelease,useEffect2(()=>{if(!isActive||!rt)return;return rt.on("input",(input,key)=>{if(isModifierOnlyEvent(input,key))return;if(key.eventType==="release"){onReleaseRef.current?.(input,key);return}if(handlerRef.current(input,key)==="exit")rt.exit()})},[isActive,rt]),useEffect2(()=>{if(!isActive||!rt)return;return rt.on("paste",(text)=>{onPasteRef.current?.(text)})},[isActive,rt])}init_context();init_render_string();init_unicode();function createHistoryItem(key,ansi,width){let rows=ansi.split(`
75
+ `)}`)}function getReactiveState(node){let state=nodeStates.get(node);if(!state)state=createReactiveNodeState(),nodeStates.set(node,state);return state}var nodeStates;var init_reactive_node=__esm(()=>{init_src4();nodeStates=new WeakMap});import{createLogger as createLogger7}from"loggily";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(hasPrevBuffer&&!isAnyDirty(root.dirtyBits,root.dirtyEpoch)&&!isCurrentEpoch(root.layoutChangedThisFrame)){if(instr.enabled)instr.stats._noopSkip=1;return advanceRenderEpoch(),prevBuffer}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);let anyLayoutChanged=isCurrentEpoch(root.layoutChangedThisFrame)||isDirty(root.dirtyBits,root.dirtyEpoch,SUBTREE_BIT);return syncPrevLayout(root,anyLayoutChanged||!hasPrevBuffer),advanceRenderEpoch(),buffer}function syncPrevLayout(root,layoutPhaseRan){if(!layoutPhaseRan)return;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"}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 contentLog,traceLog,cellLog,_instrumentEnabled,_renderPhaseStats,_renderPhaseCallCount=0,_nodeTrace,_nodeTraceEnabled,_reactiveEnabled,_reactiveVerifyEnabled;var init_render_phase=__esm(()=>{init_buffer();init_helpers();init_render_box();init_render_helpers();init_render_text();init_state();init_reactive_node();contentLog=createLogger7("silvery:content"),traceLog=createLogger7("silvery:content:trace"),cellLog=createLogger7("silvery:content:cell");_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:"",_noopSkip:0,_prevBufferNull:0,_prevBufferDimMismatch:0,_hasPrevBuffer:0,_layoutW:0,_layoutH:0,_prevW:0,_prevH:0,_callCount: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)});import{createLogger as createLogger8}from"loggily";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 log8.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;log8.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;log8.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,log8.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 layoutNode2=getLayoutEngine().createNode();return{type,props,children:[],parent:null,layoutNode:layoutNode2,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}]`}}}var log8,baseLog;var init_ag=__esm(()=>{init_buffer();init_unicode();init_measure_phase();init_layout_phase();init_render_phase();init_dirty_tracking();log8=createLogger8("silvery:render"),baseLog=createLogger8("@silvery/ag-react")});var init_render_phase_adapter=__esm(()=>{init_helpers();init_unicode();init_render_text()});import{createLogger as createLogger9}from"loggily";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)log9.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,log9.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 log9.debug?.(`pipeline: layout+render=${tLayout.toFixed(1)}ms output=${tOutput.toFixed(1)}ms total=${total.toFixed(1)}ms`),{output,buffer}}var log9,baseLog2;var init_pipeline=__esm(()=>{init_unicode();init_ag();init_measure_phase();init_layout_phase();init_render_phase();init_render_phase_adapter();init_output_phase();init_render_phase_adapter();init_render_phase();init_layout_phase();init_measure_phase();init_output_phase();log9=createLogger9("silvery:render"),baseLog2=createLogger9("@silvery/ag-react")});var init_pipeline2=__esm(()=>{init_pipeline()});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}}var LAYOUT_PROPS,TEXT_CONTENT_PROPS,STYLE_PROPS,NO_CHANGES;var init_helpers2=__esm(()=>{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}});import{createLogger as createLogger10}from"loggily";function createNode(type,props,measurer){let layoutNode2=getLayoutEngine().createNode(),epoch=getRenderEpoch(),node={type,props,children:[],parent:null,layoutNode:layoutNode2,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(layoutNode2,props);if(type==="silvery-text"){let cachedText=null,measureCache=new Map;layoutNode2.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(`
76
+ `),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(layoutNode2,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("%"))layoutNode2.setWidthPercent(Number.parseFloat(props.width));else if(typeof props.width==="number")layoutNode2.setWidth(props.width);else if(props.width==="auto")layoutNode2.setWidthAuto()}else if(wasRemoved("width"))layoutNode2.setWidthAuto();if(props.height!==void 0){if(typeof props.height==="string"&&props.height.endsWith("%"))layoutNode2.setHeightPercent(Number.parseFloat(props.height));else if(typeof props.height==="number")layoutNode2.setHeight(props.height);else if(props.height==="auto")layoutNode2.setHeightAuto()}else if(wasRemoved("height"))layoutNode2.setHeightAuto();if(props.minWidth!==void 0){if(typeof props.minWidth==="string"&&props.minWidth.endsWith("%"))layoutNode2.setMinWidthPercent(Number.parseFloat(props.minWidth));else if(typeof props.minWidth==="number")layoutNode2.setMinWidth(props.minWidth)}else if(wasRemoved("minWidth"))layoutNode2.setMinWidth(0);if(props.minHeight!==void 0){if(typeof props.minHeight==="string"&&props.minHeight.endsWith("%"))layoutNode2.setMinHeightPercent(Number.parseFloat(props.minHeight));else if(typeof props.minHeight==="number")layoutNode2.setMinHeight(props.minHeight)}else if(wasRemoved("minHeight"))layoutNode2.setMinHeight(0);if(props.maxWidth!==void 0){if(typeof props.maxWidth==="string"&&props.maxWidth.endsWith("%"))layoutNode2.setMaxWidthPercent(Number.parseFloat(props.maxWidth));else if(typeof props.maxWidth==="number")layoutNode2.setMaxWidth(props.maxWidth)}else if(wasRemoved("maxWidth"))layoutNode2.setMaxWidth(Number.POSITIVE_INFINITY);if(props.maxHeight!==void 0){if(typeof props.maxHeight==="string"&&props.maxHeight.endsWith("%"))layoutNode2.setMaxHeightPercent(Number.parseFloat(props.maxHeight));else if(typeof props.maxHeight==="number")layoutNode2.setMaxHeight(props.maxHeight)}else if(wasRemoved("maxHeight"))layoutNode2.setMaxHeight(Number.POSITIVE_INFINITY);if(props.flexGrow!==void 0)layoutNode2.setFlexGrow(props.flexGrow);else if(wasRemoved("flexGrow"))layoutNode2.setFlexGrow(0);if(props.flexShrink!==void 0)layoutNode2.setFlexShrink(props.flexShrink);else if(wasRemoved("flexShrink"))layoutNode2.setFlexShrink(1);if(props.flexBasis!==void 0){if(typeof props.flexBasis==="string"&&props.flexBasis.endsWith("%"))layoutNode2.setFlexBasisPercent(Number.parseFloat(props.flexBasis));else if(props.flexBasis==="auto")layoutNode2.setFlexBasisAuto();else if(typeof props.flexBasis==="number")layoutNode2.setFlexBasis(props.flexBasis)}else if(wasRemoved("flexBasis"))layoutNode2.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};layoutNode2.setFlexDirection(directionMap[props.flexDirection]??c.FLEX_DIRECTION_ROW)}else if(wasRemoved("flexDirection"))layoutNode2.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};layoutNode2.setFlexWrap(wrapMap[props.flexWrap]??c.WRAP_NO_WRAP)}else if(wasRemoved("flexWrap"))layoutNode2.setFlexWrap(c.WRAP_NO_WRAP);if(props.alignItems!==void 0)layoutNode2.setAlignItems(alignToConstant(props.alignItems));else if(wasRemoved("alignItems"))layoutNode2.setAlignItems(c.ALIGN_STRETCH);if(props.alignSelf!==void 0)if(props.alignSelf==="auto")layoutNode2.setAlignSelf(c.ALIGN_AUTO);else layoutNode2.setAlignSelf(alignToConstant(props.alignSelf));else if(wasRemoved("alignSelf"))layoutNode2.setAlignSelf(c.ALIGN_AUTO);if(props.alignContent!==void 0)layoutNode2.setAlignContent(alignToConstant(props.alignContent));else if(wasRemoved("alignContent"))layoutNode2.setAlignContent(c.ALIGN_FLEX_START);if(props.justifyContent!==void 0)layoutNode2.setJustifyContent(justifyToConstant(props.justifyContent));else if(wasRemoved("justifyContent"))layoutNode2.setJustifyContent(c.JUSTIFY_FLEX_START);if(applySpacing(layoutNode2,"padding",props),applySpacing(layoutNode2,"margin",props),props.gap!==void 0)layoutNode2.setGap(c.GUTTER_ALL,props.gap);else if(wasRemoved("gap"))layoutNode2.setGap(c.GUTTER_ALL,0);if(props.columnGap!==void 0)layoutNode2.setGap(c.GUTTER_COLUMN,props.columnGap);else if(wasRemoved("columnGap"))layoutNode2.setGap(c.GUTTER_COLUMN,0);if(props.rowGap!==void 0)layoutNode2.setGap(c.GUTTER_ROW,props.rowGap);else if(wasRemoved("rowGap"))layoutNode2.setGap(c.GUTTER_ROW,0);if(props.display!==void 0)layoutNode2.setDisplay(props.display==="none"?c.DISPLAY_NONE:c.DISPLAY_FLEX);else if(wasRemoved("display"))layoutNode2.setDisplay(c.DISPLAY_FLEX);if(props.position!==void 0)if(props.position==="absolute")layoutNode2.setPositionType(c.POSITION_TYPE_ABSOLUTE);else if(props.position==="static")layoutNode2.setPositionType(c.POSITION_TYPE_STATIC);else layoutNode2.setPositionType(c.POSITION_TYPE_RELATIVE);else if(wasRemoved("position"))layoutNode2.setPositionType(c.POSITION_TYPE_RELATIVE);if(props.position!=="static")applyPositionOffset(layoutNode2,c.EDGE_TOP,props.top),applyPositionOffset(layoutNode2,c.EDGE_LEFT,props.left),applyPositionOffset(layoutNode2,c.EDGE_BOTTOM,props.bottom),applyPositionOffset(layoutNode2,c.EDGE_RIGHT,props.right);if(props.aspectRatio!==void 0)layoutNode2.setAspectRatio(props.aspectRatio);else if(wasRemoved("aspectRatio"))layoutNode2.setAspectRatio(NaN);let effectiveOverflow=props.overflow??(props.overflowX==="hidden"||props.overflowY==="hidden"?"hidden":void 0);if(effectiveOverflow!==void 0)if(effectiveOverflow==="hidden")layoutNode2.setOverflow(c.OVERFLOW_HIDDEN);else if(effectiveOverflow==="scroll")layoutNode2.setOverflow(c.OVERFLOW_HIDDEN);else layoutNode2.setOverflow(c.OVERFLOW_VISIBLE);else if(wasRemoved("overflow")||wasRemoved("overflowX")||wasRemoved("overflowY"))layoutNode2.setOverflow(c.OVERFLOW_VISIBLE);if(props.borderStyle){let borderWidth=getActiveLineHeight()>1?0:1;if(props.borderTop!==!1)layoutNode2.setBorder(c.EDGE_TOP,borderWidth);else layoutNode2.setBorder(c.EDGE_TOP,0);if(props.borderBottom!==!1)layoutNode2.setBorder(c.EDGE_BOTTOM,borderWidth);else layoutNode2.setBorder(c.EDGE_BOTTOM,0);if(props.borderLeft!==!1)layoutNode2.setBorder(c.EDGE_LEFT,borderWidth);else layoutNode2.setBorder(c.EDGE_LEFT,0);if(props.borderRight!==!1)layoutNode2.setBorder(c.EDGE_RIGHT,borderWidth);else layoutNode2.setBorder(c.EDGE_RIGHT,0)}else layoutNode2.setBorder(c.EDGE_TOP,0),layoutNode2.setBorder(c.EDGE_BOTTOM,0),layoutNode2.setBorder(c.EDGE_LEFT,0),layoutNode2.setBorder(c.EDGE_RIGHT,0)}function applySpacing(layoutNode2,type,props){let c=getConstants(),set=type==="padding"?layoutNode2.setPadding.bind(layoutNode2):layoutNode2.setMargin.bind(layoutNode2),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(layoutNode2,edge,value){if(value===void 0){layoutNode2.setPosition(edge,NaN);return}if(typeof value==="string"&&value.endsWith("%"))layoutNode2.setPositionPercent(edge,Number.parseFloat(value));else if(typeof value==="number")layoutNode2.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}var measureLog;var init_nodes=__esm(()=>{init_unicode();init_measure_stats();measureLog=createLogger10("silvery:measure")});import{createContext as createContext2}from"react";import{DefaultEventPriority,DiscreteEventPriority,NoEventPriority}from"react-reconciler/constants.js";import{createLogger as createLogger11}from"loggily";function normalizeNodeType(type){if(type==="ink-box")return"silvery-box";if(type==="ink-text")return"silvery-text";return type}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)}}function runWithDiscreteEvent(fn){let prev=currentUpdatePriority;currentUpdatePriority=DiscreteEventPriority;try{fn()}finally{currentUpdatePriority=prev}}var log10,onNodeRemovedCallback=null,hasWarnedBoxInsideText=!1,inkStrictValidation=!1,currentUpdatePriority,hostConfig;var init_host_config=__esm(()=>{init_dirty_tracking();init_helpers2();init_nodes();log10=createLogger11("silvery:reconciler");currentUpdatePriority=NoEventPriority;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,log10.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)}}});import Reconciler from"react-reconciler";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}var reconciler;var init_reconciler=__esm(()=>{init_host_config();init_nodes();init_host_config();reconciler=Reconciler(hostConfig)});import Reconciler2 from"react-reconciler";var stringReconciler;var init_string_reconciler=__esm(()=>{init_host_config();stringReconciler=Reconciler2({...hostConfig,isPrimaryRenderer:!1})});var exports_render_string={};__export(exports_render_string,{renderStringSync:()=>renderStringSync,renderString:()=>renderString});import React,{act}from"react";async function ensureLayoutEngine(){if(engineInitialized||isLayoutEngineInitialized())return;let{ensureDefaultLayoutEngine:ensureDefaultLayoutEngine2}=await Promise.resolve().then(() => exports_layout_engine);await ensureDefaultLayoutEngine2(),engineInitialized=!0}async function renderString(element,options={}){return await ensureLayoutEngine(),renderStringSync(element,options)}function renderStringSync(element,options={}){if(!isLayoutEngineInitialized())throw Error("Layout engine not initialized. Use renderString() (async) or initialize with setLayoutEngine().");let{width=80,height=24,plain=!1,pipelineConfig,trimTrailingWhitespace=!0,trimEmptyLines=!0,onContentHeight,alwaysStyled=!1}=options,hadReactCommit=!1,container=createContainer(()=>{hadReactCommit=!0}),uncaughtError=null,onUncaughtError=(error)=>{uncaughtError=error},fiberRoot=stringReconciler.createContainer(container,1,null,!1,null,"",onUncaughtError,()=>{},()=>{},null),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)));if(withActEnvironment(()=>{act(()=>{stringReconciler.updateContainerSync(wrapped,fiberRoot,null,null),stringReconciler.flushSyncWork()})}),uncaughtError)throw uncaughtError instanceof Error?uncaughtError:Error(String(uncaughtError));let buffer,rootNode,MAX_ITERATIONS=5;for(let i=0;i<MAX_ITERATIONS;i++)if(hadReactCommit=!1,withActEnvironment(()=>{if(act(()=>{let root=getContainerRoot(container);rootNode=root,buffer=executeRender(root,width,height,null,void 0,pipelineConfig).buffer}),!hadReactCommit)act(()=>{stringReconciler.flushSyncWork()})}),!hadReactCommit)break;if(onContentHeight&&rootNode){let maxBottom=0,hasChildren=!1;for(let child of rootNode.children)if(child.boxRect){hasChildren=!0;let props=child.props,mb=props.marginBottom??props.marginY??props.margin??0,childBottom=child.boxRect.y+child.boxRect.height+mb;if(childBottom>maxBottom)maxBottom=childBottom}onContentHeight(hasChildren?maxBottom:0)}return withActEnvironment(()=>{act(()=>{stringReconciler.updateContainerSync(null,fiberRoot,null,null),stringReconciler.flushSyncWork()})}),plain&&!alwaysStyled?bufferToText(buffer,{trimTrailingWhitespace,trimEmptyLines}):bufferToStyledText(buffer,{trimTrailingWhitespace,trimEmptyLines})}function withActEnvironment(fn){let prev=globalThis.IS_REACT_ACT_ENVIRONMENT;globalThis.IS_REACT_ACT_ENVIRONMENT=!0;try{fn()}finally{globalThis.IS_REACT_ACT_ENVIRONMENT=prev}}var engineInitialized=!1;var init_render_string=__esm(()=>{init_ansi2();init_buffer();init_context();init_pipeline2();init_reconciler();init_string_reconciler()});var exports_devtools={};__export(exports_devtools,{isDevToolsConnected:()=>isDevToolsConnected,connectDevTools:()=>connectDevTools,autoConnectDevTools:()=>autoConnectDevTools});import{createLogger as createLogger14}from"loggily";async function connectDevTools(){if(connected)return!0;try{if(typeof globalThis.WebSocket>"u")try{let ws=await import("ws");globalThis.WebSocket=ws.default??ws}catch{return log13.warn?.("WebSocket polyfill (ws) not available. Install ws for DevTools support: bun add -d ws"),!1}if(typeof globalThis.window>"u")globalThis.window=globalThis;if(!globalThis.__REACT_DEVTOOLS_COMPONENT_FILTERS__)globalThis.__REACT_DEVTOOLS_COMPONENT_FILTERS__=[{type:1,value:7,isEnabled:!0},{type:2,value:"SilveryApp",isEnabled:!0,isValid:!0}];let devtools=await import("react-devtools-core");return devtools.initialize(),devtools.connectToDevTools(),reconciler.injectIntoDevTools(),connected=!0,!0}catch(error){let message=error instanceof Error?error.message:String(error);return log13.warn?.(`Failed to connect to React DevTools. Install react-devtools-core: bun add -d react-devtools-core
77
+ Error: ${message}`),!1}}function isDevToolsConnected(){return connected}async function autoConnectDevTools(){if(process.env.DEBUG_DEVTOOLS==="1"||process.env.DEBUG_DEVTOOLS==="true")await connectDevTools()}var log13,connected=!1;var init_devtools=__esm(()=>{init_reconciler();log13=createLogger14("silvery:devtools")});init_context();import{forwardRef,useImperativeHandle,useLayoutEffect,useRef,useState}from"react";import{jsxDEV}from"react/jsx-dev-runtime";var Box=forwardRef(function(props,ref){let{children,onLayout,...restProps}=props,nodeRef=useRef(null),[node,setNode]=useState(null),lastReportedLayout=useRef(null);return useLayoutEffect(()=>{if(nodeRef.current)setNode(nodeRef.current)},[]),useLayoutEffect(()=>{if(!onLayout||!node)return;let handleLayoutChange=()=>{let layout=node.boxRect;if(!layout)return;let last=lastReportedLayout.current;if(!last||last.x!==layout.x||last.y!==layout.y||last.width!==layout.width||last.height!==layout.height)lastReportedLayout.current=layout,onLayout(layout)};if(node.layoutSubscribers.add(handleLayoutChange),node.boxRect)handleLayoutChange();return()=>{node.layoutSubscribers.delete(handleLayoutChange)}},[node,onLayout]),useImperativeHandle(ref,()=>({getNode:()=>nodeRef.current,getBoxRect:()=>nodeRef.current?.boxRect??null,getScrollRect:()=>nodeRef.current?.scrollRect??null}),[]),jsxDEV("silvery-box",{ref:nodeRef,...restProps,children:jsxDEV(NodeContext.Provider,{value:node,children},void 0,!1,void 0,this)},void 0,!1,void 0,this)});import React3,{forwardRef as forwardRef2,useCallback as useCallback3,useContext as useContext3,useEffect as useEffect4,useImperativeHandle as useImperativeHandle2,useMemo as useMemo3,useRef as useRef5,useState as useState4}from"react";import{useCallback,useEffect,useMemo,useRef as useRef2,useState as useState2}from"react";function calcEdgeBasedScrollOffset(selectedIndex,currentOffset,visibleCount,totalCount,padding=1){if(totalCount<=visibleCount)return 0;let effectivePadding=padding*2>=visibleCount?0:padding,visibleStart=currentOffset,visibleEnd=currentOffset+visibleCount-1,paddedStart=visibleStart+effectivePadding,paddedEnd=visibleEnd-effectivePadding,newOffset=currentOffset;if(selectedIndex<paddedStart)newOffset=Math.max(0,selectedIndex-effectivePadding);else if(effectivePadding===0&&selectedIndex===paddedStart&&currentOffset>0&&visibleCount>padding)newOffset=Math.max(0,selectedIndex-padding);else if(selectedIndex>paddedEnd)newOffset=Math.min(totalCount-visibleCount,selectedIndex-visibleCount+effectivePadding+1);return Math.max(0,Math.min(newOffset,totalCount-visibleCount))}var DEFAULT_SCROLL_PADDING=1,DEFAULT_OVERSCAN=5,DEFAULT_MAX_RENDERED=100;function getHeight(index,estimateHeight,measuredHeights,getItemKey,avgMeasuredHeight){if(measuredHeights&&measuredHeights.size>0){let key=getItemKey?getItemKey(index):index,measured=measuredHeights.get(key);if(measured!==void 0)return measured;if(avgMeasuredHeight!==void 0)return avgMeasuredHeight}return typeof estimateHeight==="function"?estimateHeight(index):estimateHeight}function calcAverageHeight(count,estimateHeight,measuredHeights){if(count===0)return 1;if(measuredHeights&&measuredHeights.size>0){let total2=0;for(let h of measuredHeights.values())total2+=h;return total2/measuredHeights.size}if(typeof estimateHeight==="number")return estimateHeight;let sampleSize=Math.min(count,10),total=0;for(let i=0;i<sampleSize;i++)total+=typeof estimateHeight==="function"?estimateHeight(i):estimateHeight;return total/sampleSize}function sumHeights(startIndex,endIndex,estimateHeight,gap,measuredHeights,getItemKey){let itemCount=endIndex-startIndex;if(itemCount<=0)return 0;let gapTotal=(itemCount-1)*gap;if((!measuredHeights||measuredHeights.size===0)&&typeof estimateHeight==="number")return itemCount*estimateHeight+gapTotal;let avgMeasured;if(measuredHeights&&measuredHeights.size>0){let measuredTotal=0;for(let h of measuredHeights.values())measuredTotal+=h;avgMeasured=measuredTotal/measuredHeights.size}let total=0;for(let i=startIndex;i<endIndex;i++)total+=getHeight(i,estimateHeight,measuredHeights,getItemKey,avgMeasured);return total+gapTotal}function useVirtualizer(config){let{count,estimateHeight,viewportHeight,scrollTo,scrollPadding=DEFAULT_SCROLL_PADDING,overscan=DEFAULT_OVERSCAN,maxRendered=DEFAULT_MAX_RENDERED,gap=0,getItemKey}=config,measuredHeightsRef=useRef2(new Map),[measurementVersion,setMeasurementVersion]=useState2(0),measureItem=useCallback((key,height)=>{let cache=measuredHeightsRef.current;if(cache.get(key)===height)return!1;return cache.set(key,height),setMeasurementVersion((v)=>v+1),!0},[]),measuredHeights=measuredHeightsRef.current,avgHeight=calcAverageHeight(count,estimateHeight,measuredHeights),estimatedVisibleCount=Math.max(1,Math.ceil(viewportHeight/(avgHeight+gap))),selectedIndexRef=useRef2(Math.max(0,Math.min(scrollTo??0,count-1))),scrollOffsetRef=useRef2(calcEdgeBasedScrollOffset(selectedIndexRef.current,0,estimatedVisibleCount,count,scrollPadding)),[,setScrollOffset]=useState2(()=>scrollOffsetRef.current);if(scrollTo!==void 0){let clampedIndex=Math.max(0,Math.min(scrollTo,count-1));selectedIndexRef.current=clampedIndex;let newOffset=calcEdgeBasedScrollOffset(clampedIndex,scrollOffsetRef.current,estimatedVisibleCount,count,scrollPadding);if(newOffset!==scrollOffsetRef.current)scrollOffsetRef.current=newOffset}let effectiveScrollOffset=scrollOffsetRef.current;useEffect(()=>{setScrollOffset((prev)=>prev===effectiveScrollOffset?prev:effectiveScrollOffset)},[effectiveScrollOffset]);let scrollToItem=useCallback((index)=>{let clampedIndex=Math.max(0,Math.min(index,count-1));selectedIndexRef.current=clampedIndex;let newOffset=calcEdgeBasedScrollOffset(clampedIndex,scrollOffsetRef.current,estimatedVisibleCount,count,scrollPadding);scrollOffsetRef.current=newOffset,setScrollOffset(newOffset)},[count,estimatedVisibleCount,scrollPadding]),getKey=useCallback((index)=>{return getItemKey?getItemKey(index):index},[getItemKey]),windowCalc=useMemo(()=>{if(count===0)return{startIndex:0,endIndex:0,leadingHeight:0,trailingHeight:0};let minWindowSize=estimatedVisibleCount+2*overscan;if(count<=minWindowSize)return{startIndex:0,endIndex:count,leadingHeight:0,trailingHeight:0};let renderCount=Math.min(estimatedVisibleCount+2*overscan,maxRendered),viewportCenter=selectedIndexRef.current,halfWindow=Math.floor(renderCount/2),start=Math.max(0,viewportCenter-halfWindow),end=Math.min(count,start+renderCount);if(end===count)start=Math.max(0,end-renderCount);let leadingSize=sumHeights(0,start,estimateHeight,gap,measuredHeights,getItemKey),trailingSize=sumHeights(end,count,estimateHeight,gap,measuredHeights,getItemKey);return{startIndex:start,endIndex:end,leadingHeight:leadingSize,trailingHeight:trailingSize}},[count,effectiveScrollOffset,maxRendered,overscan,estimateHeight,avgHeight,gap,measurementVersion,getItemKey]),onEndReachedRef=useRef2(config.onEndReached);onEndReachedRef.current=config.onEndReached;let firedForCountRef=useRef2(-1),threshold=config.onEndReachedThreshold??DEFAULT_OVERSCAN,{endIndex}=windowCalc;return useEffect(()=>{if(!onEndReachedRef.current||count===0)return;if(endIndex>=count-threshold&&firedForCountRef.current!==count)firedForCountRef.current=count,onEndReachedRef.current()},[endIndex,count,threshold]),{range:{startIndex:windowCalc.startIndex,endIndex:windowCalc.endIndex},leadingHeight:windowCalc.leadingHeight,trailingHeight:windowCalc.trailingHeight,hiddenBefore:windowCalc.startIndex,hiddenAfter:count-windowCalc.endIndex,scrollOffset:effectiveScrollOffset,scrollToItem,getKey,measureItem,measuredHeights}}init_context();init_keys();import{useContext,useEffect as useEffect2,useRef as useRef3}from"react";function useInput(inputHandler,options={}){let rt=useContext(RuntimeContext),{isActive=!0,onPaste,onRelease}=options,handlerRef=useRef3(inputHandler);handlerRef.current=inputHandler;let onPasteRef=useRef3(onPaste);onPasteRef.current=onPaste;let onReleaseRef=useRef3(onRelease);onReleaseRef.current=onRelease,useEffect2(()=>{if(!isActive||!rt)return;return rt.on("input",(input,key)=>{if(isModifierOnlyEvent(input,key))return;if(key.eventType==="release"){onReleaseRef.current?.(input,key);return}if(handlerRef.current(input,key)==="exit")rt.exit()})},[isActive,rt]),useEffect2(()=>{if(!isActive||!rt)return;return rt.on("paste",(text)=>{onPasteRef.current?.(text)})},[isActive,rt])}init_context();init_render_string();init_unicode();function createHistoryItem(key,ansi,width){let rows=ansi.split(`
74
78
  `),plainTextRows=rows.map((r)=>stripAnsi2(r));return{key,ansi,rows,plainTextRows,width}}function createHistoryBuffer(capacity=1e4){let items=[],_totalRows=0;function evict(){while(_totalRows>capacity&&items.length>0){let removed=items.shift();_totalRows-=removed.rows.length}}function resolveRow(row){if(row<0||row>=_totalRows)return null;let cumulative=0;for(let i=0;i<items.length;i++){let itemRows=items[i].rows.length;if(row<cumulative+itemRows)return{itemIndex:i,localRow:row-cumulative};cumulative+=itemRows}return null}return{push(item){items.push(item),_totalRows+=item.rows.length,evict()},get totalRows(){return _totalRows},get itemCount(){return items.length},get capacity(){return capacity},getRows(startRow,count){let result=[];for(let r=startRow;r<startRow+count;r++){let resolved=resolveRow(r);if(resolved)result.push(items[resolved.itemIndex].rows[resolved.localRow]);else result.push("")}return result},getPlainTextRows(startRow,count){let result=[];for(let r=startRow;r<startRow+count;r++){let resolved=resolveRow(r);if(resolved)result.push(items[resolved.itemIndex].plainTextRows[resolved.localRow]);else result.push("")}return result},search(query){if(!query)return[];let lowerQuery=query.toLowerCase(),matches=[],rowOffset=0;for(let item of items){for(let r=0;r<item.plainTextRows.length;r++)if(item.plainTextRows[r].toLowerCase().includes(lowerQuery))matches.push(rowOffset+r);rowOffset+=item.rows.length}return matches},getItemAtRow(row){let resolved=resolveRow(row);if(!resolved)return null;return{item:items[resolved.itemIndex],localRow:resolved.localRow}},clear(){items=[],_totalRows=0}}}function createListDocument(history,getLiveItems){function liveRowCount(){let total=0;for(let block of getLiveItems())total+=block.rows.length;return total}return{get totalRows(){return history.totalRows+liveRowCount()},get frozenRows(){return history.totalRows},get liveRows(){return liveRowCount()},getRows(startRow,count){let frozen=history.totalRows,result=[];for(let r=startRow;r<startRow+count;r++)if(r<0||r>=this.totalRows)result.push("");else if(r<frozen)result.push(...history.getRows(r,1));else{let liveRow=r-frozen,found=!1;for(let block of getLiveItems()){if(liveRow<block.rows.length){result.push(block.rows[liveRow]),found=!0;break}liveRow-=block.rows.length}if(!found)result.push("")}return result},getPlainTextRows(startRow,count){let frozen=history.totalRows,result=[];for(let r=startRow;r<startRow+count;r++)if(r<0||r>=this.totalRows)result.push("");else if(r<frozen)result.push(...history.getPlainTextRows(r,1));else{let liveRow=r-frozen,found=!1;for(let block of getLiveItems()){if(liveRow<block.plainTextRows.length){result.push(block.plainTextRows[liveRow]),found=!0;break}liveRow-=block.plainTextRows.length}if(!found)result.push("")}return result},getSource(row){let frozen=history.totalRows;if(row<0||row>=this.totalRows)return null;if(row<frozen){let hit=history.getItemAtRow(row);if(!hit)return null;return{type:"frozen",itemKey:hit.item.key,localRow:hit.localRow}}let liveItems=getLiveItems(),liveRow=row-frozen;for(let block of liveItems){if(liveRow<block.rows.length)return{type:"live",itemIndex:block.itemIndex,localRow:liveRow};liveRow-=block.rows.length}return null},search(query){if(!query)return[];let lowerQuery=query.toLowerCase(),matches=[],frozen=history.totalRows,frozenRowMatches=history.search(query);for(let row of frozenRowMatches){let line=history.getPlainTextRows(row,1)[0].toLowerCase(),pos=line.indexOf(lowerQuery);while(pos!==-1)matches.push({row,startCol:pos,endCol:pos+query.length}),pos=line.indexOf(lowerQuery,pos+1)}let rowOffset=0;for(let block of getLiveItems()){for(let i=0;i<block.plainTextRows.length;i++){let line=block.plainTextRows[i].toLowerCase(),pos=line.indexOf(lowerQuery);while(pos!==-1)matches.push({row:frozen+rowOffset+i,startCol:pos,endCol:pos+query.length}),pos=line.indexOf(lowerQuery,pos+1)}rowOffset+=block.plainTextRows.length}return matches}}}init_unicode();function createTextSurface(config){let listeners=new Set;function notify(){for(let fn of listeners)fn()}return{get id(){return config.id},get document(){return config.document},getText(startRow,startCol,endRow,endCol){let rows=config.document.getRows(startRow,endRow-startRow+1),lines=[];for(let i=0;i<rows.length;i++){let plain=stripAnsi2(rows[i]),row=startRow+i;if(row===startRow&&row===endRow)lines.push(plain.slice(startCol,endCol));else if(row===startRow)lines.push(plain.slice(startCol));else if(row===endRow)lines.push(plain.slice(0,endCol));else lines.push(plain)}return lines.join(`
75
79
  `)},search(query){return config.document.search(query)},hitTest(viewportRow,viewportCol){let docRow=config.viewportToDocument(viewportRow);if(docRow<0||docRow>=config.document.totalRows)return null;return{row:docRow,col:viewportCol}},reveal(row){config.onReveal(row),notify()},notifyContentChange(){notify()},subscribe(listener){return listeners.add(listener),()=>{listeners.delete(listener)}},get capabilities(){return config.capabilities}}}function composeViewport(config){let{history,viewportHeight,scrollOffset}=config,totalHistory=history.totalRows;if(scrollOffset<=0||totalHistory===0)return{overlayRows:[],overlayRowCount:0,liveRowsVisible:viewportHeight,isScrolledUp:!1,totalHeight:totalHistory+viewportHeight};let clampedOffset=Math.min(scrollOffset,totalHistory),startRow=Math.max(0,totalHistory-clampedOffset),rowsToShow=Math.min(viewportHeight,totalHistory-startRow),overlayRows=history.getRows(startRow,rowsToShow),liveRowsVisible=viewportHeight-rowsToShow;return{overlayRows,overlayRowCount:rowsToShow,liveRowsVisible,isScrolledUp:!0,totalHeight:totalHistory+viewportHeight}}init_unicode();import React2,{createContext as createContext3,useCallback as useCallback2,useContext as useContext2,useEffect as useEffect3,useMemo as useMemo2,useRef as useRef4,useState as useState3}from"react";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]}}}var SearchContext=createContext3(null);function SearchProvider({children}){let[state,setState]=useState3(createSearchState),[focusedId,setFocusedId]=useState3(null),[activeId,setActiveId]=useState3(null),searchablesRef=useRef4(new Map),getActiveSearchable=useCallback2(()=>{let id=activeId??focusedId;if(!id){let entries=searchablesRef.current;if(entries.size===1)return entries.values().next().value;return null}return searchablesRef.current.get(id)??null},[activeId,focusedId]),getSearchFn=useCallback2(()=>{let searchable=getActiveSearchable();if(!searchable)return;return(query)=>searchable.search(query)},[getActiveSearchable]),pendingEffectsRef=useRef4(null);useEffect3(()=>{let pending=pendingEffectsRef.current;if(!pending)return;pendingEffectsRef.current=null;let searchable=getActiveSearchable();if(!searchable)return;for(let eff of pending.effects)if(eff.type==="scrollTo"){let match=pending.state.currentMatch>=0?pending.state.matches[pending.state.currentMatch]:void 0;if(match)searchable.reveal(match)}});let dispatch=useCallback2((action)=>{setState((prev2)=>{let searchFn=getSearchFn(),[next2,effects]=searchUpdate(action,prev2,searchFn);if(effects.length>0)pendingEffectsRef.current={effects,state:next2};return next2})},[getSearchFn]),registerSearchable=useCallback2((id,searchable)=>{return searchablesRef.current.set(id,searchable),()=>{searchablesRef.current.delete(id)}},[]),setFocused=useCallback2((id)=>{setFocusedId(id)},[]),open=useCallback2(()=>{setActiveId(focusedId),dispatch({type:"open"})},[focusedId,dispatch]),close=useCallback2(()=>{setActiveId(null),dispatch({type:"close"})},[dispatch]),next=useCallback2(()=>{dispatch({type:"nextMatch"})},[dispatch]),prev=useCallback2(()=>{dispatch({type:"prevMatch"})},[dispatch]),input=useCallback2((char)=>{dispatch({type:"input",char})},[dispatch]),backspace=useCallback2(()=>{dispatch({type:"backspace"})},[dispatch]),cursorLeft=useCallback2(()=>{setState((prev2)=>{let[next2]=searchUpdate({type:"cursorLeft"},prev2);return next2})},[]),cursorRight=useCallback2(()=>{setState((prev2)=>{let[next2]=searchUpdate({type:"cursorRight"},prev2);return next2})},[]),cursorToStart=useCallback2(()=>{setState((prev2)=>{let[next2]=searchUpdate({type:"cursorToStart"},prev2);return next2})},[]),cursorToEnd=useCallback2(()=>{setState((prev2)=>{let[next2]=searchUpdate({type:"cursorToEnd"},prev2);return next2})},[]),deleteWordBack=useCallback2(()=>{dispatch({type:"deleteWordBack"})},[dispatch]),deleteToStart=useCallback2(()=>{dispatch({type:"deleteToStart"})},[dispatch]),value=useMemo2(()=>({isActive:state.active,query:state.query,matches:state.matches,currentMatch:state.currentMatch,cursorPosition:state.cursorPosition,open,close,next,prev,input,backspace,cursorLeft,cursorRight,cursorToStart,cursorToEnd,deleteWordBack,deleteToStart,registerSearchable,setFocused}),[state,open,close,next,prev,input,backspace,cursorLeft,cursorRight,cursorToStart,cursorToEnd,deleteWordBack,deleteToStart,registerSearchable,setFocused]);return React2.createElement(SearchContext.Provider,{value},React2.createElement(SearchBindings,{ctx:value}),children)}function SearchBindings({ctx}){return useInput((input,key)=>{if(!ctx.isActive){if(key.ctrl&&input==="f"){ctx.open();return}return}if(key.escape){ctx.close();return}if(key.return&&!key.shift){ctx.next();return}if(key.return&&key.shift){ctx.prev();return}if(key.backspace&&key.meta){ctx.deleteWordBack();return}if(key.backspace){ctx.backspace();return}if(key.ctrl&&input==="w"){ctx.deleteWordBack();return}if(key.ctrl&&input==="u"){ctx.deleteToStart();return}if(key.ctrl&&input==="a"){ctx.cursorToStart();return}if(key.ctrl&&input==="e"){ctx.cursorToEnd();return}if(key.home){ctx.cursorToStart();return}if(key.end){ctx.cursorToEnd();return}if(key.leftArrow){ctx.cursorLeft();return}if(key.rightArrow){ctx.cursorRight();return}if(input&&!key.ctrl&&!key.meta){ctx.input(input);return}},{isActive:!0}),null}function useSearch(){let ctx=useContext2(SearchContext);if(!ctx)throw Error("useSearch must be used within a SearchProvider");return ctx}function useSearchOptional(){return useContext2(SearchContext)}import{jsxDEV as jsxDEV2}from"react/jsx-dev-runtime";var DEFAULT_ESTIMATE_HEIGHT=1,DEFAULT_OVERSCAN2=5,DEFAULT_MAX_RENDERED2=100,DEFAULT_SCROLL_PADDING2=2,WHEEL_STEP=3;function MeasuredItem({itemKey,measureItem,children}){let keyRef=useRef5(itemKey);keyRef.current=itemKey;let measureRef=useRef5(measureItem);measureRef.current=measureItem;let handleLayout=useCallback3((rect)=>{if(rect.height>0)measureRef.current(keyRef.current,rect.height)},[]);return jsxDEV2(Box,{flexDirection:"column",flexShrink:0,onLayout:handleLayout,children},void 0,!1,void 0,this)}function ListViewInner({items,height,estimateHeight=DEFAULT_ESTIMATE_HEIGHT,renderItem,scrollTo:scrollToProp,overscan=DEFAULT_OVERSCAN2,maxRendered=DEFAULT_MAX_RENDERED2,scrollPadding=DEFAULT_SCROLL_PADDING2,overflowIndicator,getKey,width,gap=0,renderSeparator,onWheel:onWheelProp,onEndReached,onEndReachedThreshold,listFooter,unmounted,nav,cursorKey:cursorKeyProp,onCursor,onSelect,active,surfaceId,search:searchProp,cache:cacheProp},ref){let term2=useContext3(TermContext),cacheBackendFromContext=useContext3(CacheBackendContext),stdoutCtx=useContext3(StdoutContext),isControlled=cursorKeyProp!==void 0,[uncontrolledCursor,setUncontrolledCursor]=useState4(0),activeCursor=nav?isControlled?cursorKeyProp:uncontrolledCursor:-1,moveTo=useCallback3((next)=>{let clamped=Math.max(0,Math.min(next,items.length-1));if(!isControlled)setUncontrolledCursor(clamped);onCursor?.(clamped)},[isControlled,items.length,onCursor]);useInput((input,key)=>{if(!nav)return;let cur=activeCursor;if(input==="j"||key.downArrow)moveTo(cur+1);else if(input==="k"||key.upArrow)moveTo(cur-1);else if(input==="G"||key.end)moveTo(items.length-1);else if(key.home)moveTo(0);else if(key.pageDown||input==="d"&&key.ctrl)moveTo(cur+Math.floor(height/2));else if(key.pageUp||input==="u"&&key.ctrl)moveTo(cur-Math.floor(height/2));else if(key.return)onSelect?.(cur)},{isActive:nav&&active!==!1});let scrollTo=nav?activeCursor:scrollToProp,cacheConfig=typeof cacheProp==="object"?cacheProp:cacheProp?{mode:"auto"}:void 0,rawCacheMode=cacheConfig?.mode??"none",cacheMode=rawCacheMode==="auto"?cacheBackendFromContext==="terminal"?"terminal":"virtual":rawCacheMode,cacheBufferRef=useRef5(null);if(cacheMode==="virtual"&&!cacheBufferRef.current)cacheBufferRef.current=createHistoryBuffer(cacheConfig?.capacity??1e4);let cacheBuffer=cacheBufferRef.current,searchConfig=typeof searchProp==="object"?searchProp:searchProp?{}:void 0,getText=searchConfig?.getText??(searchConfig?(item)=>String(item):void 0),cachedCount=0;if((cacheMode==="virtual"||cacheMode==="terminal")&&cacheConfig?.isCacheable)for(let i=0;i<items.length;i++){if(!cacheConfig.isCacheable(items[i],i))break;cachedCount++}let prevCachedRef=useRef5(0);if(cachedCount>prevCachedRef.current&&(cacheMode==="virtual"||cacheMode==="terminal")){let captureWidth=width??term2?.cols??80,canCapture=isLayoutEngineInitialized();for(let i=prevCachedRef.current;i<cachedCount;i++){let item=items[i],key=getKey?.(item,i)??i,ansi;if(canCapture)try{let element=renderItem(item,i,{isCursor:!1});ansi=renderStringSync(element,{width:captureWidth,plain:!1,trimTrailingWhitespace:!0,trimEmptyLines:!1})}catch{ansi=getText?.(item)??String(item)}else ansi=getText?.(item)??String(item);if(cacheMode==="terminal"){let lineCount=ansi.split(`
76
80
  `).length;stdoutCtx?.promoteScrollback?.(`${ansi}\x1B[K\r
@@ -82,7 +86,7 @@ ${mismatches.join(`
82
86
  `)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}return this.props.children}}import{useEffect as useEffect6,useState as useState6}from"react";function useConsole(patched,debounceMs=200){let[entries,setEntries]=useState6(patched.getSnapshot);return useEffect6(()=>{let timer=null,unsub=patched.subscribe(()=>{if(timer)return;timer=setTimeout(()=>{timer=null,setEntries(patched.getSnapshot())},debounceMs)});return setEntries(patched.getSnapshot()),()=>{if(unsub(),timer)clearTimeout(timer)}},[patched,debounceMs]),entries}import{jsxDEV as jsxDEV9}from"react/jsx-dev-runtime";function formatArgs(args){return args.map((arg)=>{if(typeof arg==="string")return arg;if(typeof arg==="number"||typeof arg==="boolean")return String(arg);if(arg===null)return"null";if(arg===void 0)return"undefined";try{return JSON.stringify(arg)}catch{return String(arg)}}).join(" ")}function Console({console:patched,children,height=20,cache=!0,search=!0,surfaceId}){let entries=useConsole(patched);return jsxDEV9(ListView,{items:entries,height,scrollTo:entries.length-1,cache,search:search?{getText:(entry)=>formatArgs(entry.args)}:!1,surfaceId,renderItem:(entry,index)=>children?children(entry,index):jsxDEV9(Text,{color:entry.stream==="stderr"?"red":void 0,children:formatArgs(entry.args)},index,!1,void 0,this)},void 0,!1,void 0,this)}import{useState as useState7,useEffect as useEffect7}from"react";import{jsxDEV as jsxDEV10}from"react/jsx-dev-runtime";function getTermDims(){return{width:process.stdout.columns??80,height:process.stdout.rows??24}}function Screen({children,flexDirection="column"}){let[dims,setDims]=useState7(getTermDims);return useEffect7(()=>{let onResize=()=>setDims(getTermDims());return process.stdout.on("resize",onResize),()=>{process.stdout.off("resize",onResize)}},[]),jsxDEV10(Box,{width:dims.width,height:dims.height,flexDirection,children},void 0,!1,void 0,this)}import{useCallback as useCallback16,useImperativeHandle as useImperativeHandle4,forwardRef as forwardRef5,useState as useState10,useEffect as useEffect15,useRef as useRef14}from"react";import{useCallback as useCallback14,useRef as useRef12,useState as useState9}from"react";init_context();import{useContext as useContext7,useLayoutEffect as useLayoutEffect2,useReducer,useRef as useRef6}from"react";var EMPTY_RECT={x:0,y:0,width:0,height:0};function getInnerRect(node){let rect=node.boxRect;if(!rect)return EMPTY_RECT;let props=node.props;if(!props||node.type==="silvery-text")return rect;let pTop=props.paddingTop??props.paddingY??props.padding??0,pBottom=props.paddingBottom??props.paddingY??props.padding??0,pLeft=props.paddingLeft??props.paddingX??props.padding??0,pRight=props.paddingRight??props.paddingX??props.padding??0,bTop=0,bBottom=0,bLeft=0,bRight=0;if(props.borderStyle)bTop=props.borderTop!==!1?1:0,bBottom=props.borderBottom!==!1?1:0,bLeft=props.borderLeft!==!1?1:0,bRight=props.borderRight!==!1?1:0;return{x:rect.x+pLeft+bLeft,y:rect.y+pTop+bTop,width:Math.max(0,rect.width-pLeft-pRight-bLeft-bRight),height:Math.max(0,rect.height-pTop-pBottom-bTop-bBottom)}}function useReactiveRect(getRect){let node=useContext7(NodeContext),[,forceUpdate]=useReducer((x)=>x+1,0),prevRef=useRef6(null);if(useLayoutEffect2(()=>{if(!node)return;let handleLayoutComplete=()=>{let next=getRect(node)??null;if(!rectEqual(prevRef.current,next))prevRef.current=next,forceUpdate()};return node.layoutSubscribers.add(handleLayoutComplete),()=>{node.layoutSubscribers.delete(handleLayoutComplete)}},[node]),!node)return EMPTY_RECT;return getRect(node)??EMPTY_RECT}function useCallbackRect(getRect,callback){let node=useContext7(NodeContext),callbackRef=useRef6(callback);callbackRef.current=callback;let getRectRef=useRef6(getRect);getRectRef.current=getRect,useLayoutEffect2(()=>{if(!node)return;let handleLayoutComplete=()=>{let rect2=getRectRef.current(node);if(rect2)callbackRef.current(rect2)};node.layoutSubscribers.add(handleLayoutComplete);let rect=getRectRef.current(node);if(rect)callbackRef.current(rect);return()=>{node.layoutSubscribers.delete(handleLayoutComplete)}},[node])}function useBoxRect(callback){if(callback)return useCallbackRect((node)=>getInnerRect(node),callback);return useReactiveRect((node)=>getInnerRect(node))}function useScrollRect(callback){if(callback)return useCallbackRect((node)=>node.scrollRect,callback);return useReactiveRect((node)=>node.scrollRect)}function useScreenRect(callback){if(callback)return useCallbackRect((node)=>node.screenRect,callback);return useReactiveRect((node)=>node.screenRect)}init_context();import{useContext as useContext8,useLayoutEffect as useLayoutEffect3,useReducer as useReducer2}from"react";var EMPTY_METRICS={width:0,height:0,left:0,top:0,hasMeasured:!1};function resolveNode(refValue){if(!refValue)return null;let obj=refValue;if(typeof obj.getNode==="function")return obj.getNode();if(obj.boxRect!==void 0)return refValue;return null}function computeMetrics(node){let rect=node.boxRect;if(!rect)return EMPTY_METRICS;let parent=node.parent,parentRect=parent?.boxRect,parentProps=parent?.props,padLeft=parentProps?.paddingLeft??parentProps?.paddingX??parentProps?.padding??0,padTop=parentProps?.paddingTop??parentProps?.paddingY??parentProps?.padding??0,borderLeft=parentProps?.borderStyle?1:0,borderTop=parentProps?.borderStyle?1:0,contentX=parentRect?parentRect.x+padLeft+borderLeft:0,contentY=parentRect?parentRect.y+padTop+borderTop:0;return{width:rect.width,height:rect.height,left:parentRect?rect.x-contentX:rect.x,top:parentRect?rect.y-contentY:rect.y,hasMeasured:!0}}function useBoxMetrics(ref){let contextNode=useContext8(NodeContext),[,forceUpdate]=useReducer2((x)=>x+1,0),node=ref?resolveNode(ref.current):contextNode;if(useLayoutEffect3(()=>{if(!node)return;return node.layoutSubscribers.add(forceUpdate),()=>{node.layoutSubscribers.delete(forceUpdate)}},[node]),!node)return EMPTY_METRICS;return computeMetrics(node)}import{useEffect as useEffect8,useReducer as useReducer3,useRef as useRef7}from"react";function createScheduler(){let timers=new Map;function register(interval,callback){let entry=timers.get(interval);if(!entry)entry={handle:setInterval(()=>{let cbs=timers.get(interval)?.callbacks;if(cbs)for(let cb of cbs)cb()},interval),callbacks:new Set},timers.set(interval,entry);entry.callbacks.add(callback)}function unregister(interval,callback){let entry=timers.get(interval);if(!entry)return;if(entry.callbacks.delete(callback),entry.callbacks.size===0)clearInterval(entry.handle),timers.delete(interval)}return{register,unregister,get activeTimerCount(){return timers.size},get totalCallbackCount(){let count=0;for(let entry of timers.values())count+=entry.callbacks.size;return count}}}var _scheduler=createScheduler();init_context();import{useContext as useContext9}from"react";function useRuntime(){return useContext9(RuntimeContext)}init_context();import{useContext as useContext10}from"react";var staticResult={exit:()=>{}};function useApp(){let rt=useContext10(RuntimeContext);if(!rt)return staticResult;return{exit:rt.exit,pause:rt.pause,resume:rt.resume}}init_context();import{useContext as useContext11}from"react";function useExit(){let rt=useContext11(RuntimeContext);if(!rt)throw Error("useExit must be used within run() or createApp()");return rt.exit}init_context();import{useContext as useContext12}from"react";function useStdout(){let context=useContext12(StdoutContext);if(!context)throw Error("useStdout must be used within an Silvery application");return{stdout:context.stdout,write:context.write}}init_context();import{useContext as useContext13}from"react";function useStderr(){let context=useContext13(StderrContext);if(!context)return{stderr:process.stderr,write:(data)=>{process.stderr.write(data)}};return{stderr:context.stderr,write:context.write}}init_context();import{useCallback as useCallback5,useContext as useContext14,useEffect as useEffect9,useRef as useRef8,useSyncExternalStore as useSyncExternalStore2}from"react";var autoIdCounter=0;function useFocus(options={}){let{isActive=!0,autoFocus=!1,id}=options,fm=useContext14(FocusManagerContext),node=useContext14(NodeContext),autoIdRef=useRef8(null);if(!autoIdRef.current&&!id)autoIdRef.current=`__useFocus_${++autoIdCounter}`;let focusId=id??autoIdRef.current;useEffect9(()=>{if(!fm||!focusId)return;return fm.registerHookFocusable(focusId,{isActive,autoFocus})},[fm,focusId]),useEffect9(()=>{if(!fm||!focusId)return;fm.setHookFocusableActive(focusId,isActive)},[fm,focusId,isActive]);let subscribe=useCallback5((listener)=>{if(!fm)return()=>{};return fm.subscribe(listener)},[fm]),getSnapshot=useCallback5(()=>{if(!fm)return null;return fm.getSnapshot()},[fm]),snapshot=useSyncExternalStore2(subscribe,getSnapshot,getSnapshot),isFocused=isActive&&focusId!==null&&snapshot!==null&&snapshot.activeId===focusId,getRoot=useCallback5(()=>{if(!node)return null;let root=node;while(root.parent)root=root.parent;return root},[node]),focus=useCallback5((targetId)=>{if(!fm)return;let root=getRoot();if(root)fm.focusById(targetId,root,"programmatic")},[fm,getRoot]);return{isFocused,focus}}init_context();import{useCallback as useCallback6,useContext as useContext15,useEffect as useEffect10,useMemo as useMemo7,useSyncExternalStore as useSyncExternalStore3}from"react";function useFocusable(){let fm=useContext15(FocusManagerContext),node=useContext15(NodeContext),testID=node?node.props.testID??null:null,autoFocus=node?!!node.props.autoFocus:!1,subscribe=useCallback6((listener)=>{if(!fm)return()=>{};return fm.subscribe(listener)},[fm]),getSnapshot=useCallback6(()=>{if(!fm)return null;return fm.getSnapshot()},[fm]),snapshot=useSyncExternalStore3(subscribe,getSnapshot,getSnapshot),focused=testID!==null&&snapshot!==null&&snapshot.activeId===testID,focusOrigin=focused?snapshot.focusOrigin:null;useEffect10(()=>{if(fm&&node&&autoFocus)fm.focus(node,"programmatic")},[fm,node,autoFocus]),useEffect10(()=>{return()=>{if(fm&&fm.activeElement===node)fm.blur()}},[fm,node]);let focus=useMemo7(()=>{return()=>{if(fm&&node)fm.focus(node,"programmatic")}},[fm,node]),blur=useMemo7(()=>{return()=>{if(fm&&focused)fm.blur()}},[fm,focused]);return{focused,focus,blur,focusOrigin}}init_context();import{useCallback as useCallback7,useContext as useContext16,useSyncExternalStore as useSyncExternalStore4}from"react";function useFocusWithin(testID){let fm=useContext16(FocusManagerContext),node=useContext16(NodeContext),subscribe=useCallback7((listener)=>{if(!fm)return()=>{};return fm.subscribe(listener)},[fm]),getSnapshot=useCallback7(()=>{if(!fm)return null;return fm.getSnapshot()},[fm]);if(!useSyncExternalStore4(subscribe,getSnapshot,getSnapshot)?.activeId)return!1;if(!node)return!1;let root=node;while(root.parent)root=root.parent;return fm.hasFocusWithin(root,testID)}init_context();import{useCallback as useCallback8,useContext as useContext17,useSyncExternalStore as useSyncExternalStore5}from"react";function useFocusManager(){let fm=useContext17(FocusManagerContext),node=useContext17(NodeContext),subscribe=useCallback8((listener)=>{if(!fm)return()=>{};return fm.subscribe(listener)},[fm]),getSnapshot=useCallback8(()=>{if(!fm)return null;return fm.getSnapshot()},[fm]),snapshot=useSyncExternalStore5(subscribe,getSnapshot,getSnapshot),getRoot=useCallback8(()=>{if(!node)return null;let root=node;while(root.parent)root=root.parent;return root},[node]),focus=useCallback8((nodeOrId)=>{if(!fm)return;if(typeof nodeOrId==="string"){let root=getRoot();if(root)fm.focusById(nodeOrId,root,"programmatic")}else fm.focus(nodeOrId,"programmatic")},[fm,getRoot]),focusNext=useCallback8(()=>{if(!fm)return;let root=getRoot();if(root)fm.focusNext(root)},[fm,getRoot]),focusPrev=useCallback8(()=>{if(!fm)return;let root=getRoot();if(root)fm.focusPrev(root)},[fm,getRoot]),blur=useCallback8(()=>{if(!fm)return;fm.blur()},[fm]),activateScope=useCallback8((scopeId)=>{if(!fm)return;let root=getRoot();if(root)fm.activateScope(scopeId,root)},[fm,getRoot]),noOp=useCallback8(()=>{},[]);if(fm)return{activeElement:fm.activeElement,activeId:snapshot?.activeId??null,activeScopeId:snapshot?.activeScopeId??null,focus,focusNext,focusPrev,blur,activateScope,enableFocus:noOp,disableFocus:noOp,focusPrevious:focusPrev};return{activeElement:null,activeId:null,activeScopeId:null,focus:noOp,focusNext:noOp,focusPrev:noOp,blur:noOp,activateScope:noOp,enableFocus:noOp,disableFocus:noOp,focusPrevious:noOp}}import{createContext as createContext4,useCallback as useCallback9,useContext as useContext18,useLayoutEffect as useLayoutEffect4,useMemo as useMemo8,useRef as useRef9}from"react";import{jsxDEV as jsxDEV11}from"react/jsx-dev-runtime";var InputLayerContext=createContext4(null);function InputLayerProvider({children}){let layersRef=useRef9([]),push=useCallback9((layer)=>{let existing=layersRef.current,existingIndex=existing.findIndex((l)=>l.id===layer.id);if(existingIndex>=0){let updated=[...existing];updated[existingIndex]=layer,layersRef.current=updated}else layersRef.current=[...existing,layer]},[]),pop=useCallback9((id)=>{layersRef.current=layersRef.current.filter((l)=>l.id!==id)},[]),dispatch=useCallback9((input,key)=>{let layers=layersRef.current;for(let i=0;i<layers.length;i++)if(layers[i]?.handler(input,key))return},[]);useInput((input,key)=>{dispatch(input,key)});let contextValue=useMemo8(()=>({push,pop,dispatch}),[push,pop,dispatch]);return jsxDEV11(InputLayerContext.Provider,{value:contextValue,children},void 0,!1,void 0,this)}function useInputLayerContext(){let ctx=useContext18(InputLayerContext);if(!ctx)throw Error("useInputLayerContext must be used within an InputLayerProvider");return ctx}function useInputLayer(id,handler){let ctx=useContext18(InputLayerContext);useLayoutEffect4(()=>{if(!ctx)return;return ctx.push({id,handler}),()=>{ctx.pop(id)}},[ctx,id,handler])}import{useState as useState8,useEffect as useEffect11}from"react";function useTerminalFocused(){let[focused,setFocused]=useState8(!0),rt=useRuntime();return useEffect11(()=>{if(!rt)return;return rt.on("focus",(isFocused)=>{setFocused(isFocused)})},[rt]),focused}import{useEffect as useEffect12,useRef as useRef10}from"react";function setScrollRegion2(stdout,top,bottom){stdout.write(`\x1B[${top};${bottom}r`)}function resetScrollRegion2(stdout){stdout.write("\x1B[r")}function scrollUp2(stdout,lines=1){stdout.write(`\x1B[${lines}S`)}function scrollDown2(stdout,lines=1){stdout.write(`\x1B[${lines}T`)}function moveCursor2(stdout,row,col){stdout.write(`\x1B[${row};${col}H`)}function supportsScrollRegions(){let term2=process.env.TERM??"",termProgram=process.env.TERM_PROGRAM??"";if(termProgram==="iTerm.app"||termProgram==="WezTerm"||termProgram==="ghostty"||termProgram==="vscode")return!0;if(term2.includes("xterm")||term2.includes("screen")||term2.includes("tmux")||term2.includes("kitty"))return!0;if(term2==="linux")return!1;return term2!==""}import React6,{createContext as createContext5,useContext as useContext19}from"react";var PasteContext=createContext5(null);function PasteProvider({handler,children}){return React6.createElement(PasteContext.Provider,{value:handler},children)}function usePaste(){return useContext19(PasteContext)}init_context();import{useContext as useContext20,useEffect as useEffect13,useRef as useRef11}from"react";var internalClipboard=null;function getInternalClipboard(){return internalClipboard}function createPasteEvent(text,clipboard){if(clipboard&&clipboard.text===text)return{text,source:"internal",data:clipboard};return{text,source:"external"}}function createCopyProvider(enrichCopy){return{enrichCopy}}function usePasteEvents(){let rt=useContext20(RuntimeContext),pasteHandler=usePaste(),handlerRef=useRef11(pasteHandler);handlerRef.current=pasteHandler,useEffect13(()=>{if(!rt)return;return rt.on("paste",(text)=>{let handler=handlerRef.current;if(!handler)return;let clipboard=getInternalClipboard(),event=createPasteEvent(text,clipboard);handler.onPaste(event)})},[rt])}init_context();import{useContext as useContext21,useSyncExternalStore as useSyncExternalStore6}from"react";var SELECTION_CAPABILITY=Symbol.for("silvery.selection"),noopSubscribe2=(_listener)=>()=>{},getUndefined=()=>{return};function useSelection(){let feature=useContext21(CapabilityRegistryContext)?.get(SELECTION_CAPABILITY);return useSyncExternalStore6(feature?(listener)=>feature.subscribe(listener):noopSubscribe2,feature?()=>feature.state:getUndefined)}init_context();import{useContext as useContext22,useSyncExternalStore as useSyncExternalStore7,useCallback as useCallback10}from"react";var FIND_CAPABILITY=Symbol.for("silvery.find"),noop=()=>()=>{};function useFindState(){let feature=useContext22(CapabilityRegistryContext)?.get(FIND_CAPABILITY),subscribe=useCallback10((onStoreChange)=>{if(!feature)return noop();return feature.subscribe(onStoreChange)},[feature]),getSnapshot=useCallback10(()=>{return feature?.state},[feature]);return useSyncExternalStore7(subscribe,getSnapshot)}init_context();import{useContext as useContext23,useSyncExternalStore as useSyncExternalStore8,useCallback as useCallback11}from"react";var COPY_MODE_CAPABILITY=Symbol.for("silvery.copy-mode"),noop2=()=>()=>{};function useCopyModeState(){let feature=useContext23(CapabilityRegistryContext)?.get(COPY_MODE_CAPABILITY),subscribe=useCallback11((onStoreChange)=>{if(!feature)return noop2();return feature.subscribe(onStoreChange)},[feature]),getSnapshot=useCallback11(()=>{return feature?.state},[feature]);return useSyncExternalStore8(subscribe,getSnapshot)}init_context();import{useContext as useContext24,useSyncExternalStore as useSyncExternalStore9,useCallback as useCallback12}from"react";var DRAG_CAPABILITY=Symbol.for("silvery.drag"),noop3=()=>()=>{};function useDragState(){let feature=useContext24(CapabilityRegistryContext)?.get(DRAG_CAPABILITY),subscribe=useCallback12((onStoreChange)=>{if(!feature)return noop3();return feature.subscribe(onStoreChange)},[feature]),getSnapshot=useCallback12(()=>{if(!feature)return;return feature.state},[feature]);return useSyncExternalStore9(subscribe,getSnapshot)}init_context();import{useContext as useContext25}from"react";var DEFAULT_STATE=Object.freeze({hovered:!1,armed:!1,selected:!1,focused:!1,dropTarget:!1});function useInteractiveState(){let node=useContext25(NodeContext);if(!node?.interactiveState)return DEFAULT_STATE;return node.interactiveState}import{createContext as createContext6,useContext as useContext26,useMemo as useMemo9}from"react";import{jsxDEV as jsxDEV12}from"react/jsx-dev-runtime";var ListItemCtx=createContext6(null);function useListItem(){let ctx=useContext26(ListItemCtx);if(!ctx)throw Error("useListItem() must be used inside a ListView item");return ctx}init_context();import{useCallback as useCallback13,useContext as useContext27,useSyncExternalStore as useSyncExternalStore10}from"react";var COLOR_SCHEME_CAPABILITY=Symbol.for("silvery.color-scheme");function useColorScheme(){let detector=useContext27(CapabilityRegistryContext)?.get(COLOR_SCHEME_CAPABILITY)??null,subscribe=useCallback13((onStoreChange)=>{if(!detector)return()=>{};return detector.subscribe(onStoreChange)},[detector]),getSnapshot=useCallback13(()=>{if(!detector)return"unknown";return detector.scheme},[detector]);return useSyncExternalStore10(subscribe,getSnapshot,getSnapshot)}var killRing=[];function addToKillRing(text){if(!text)return;if(killRing.unshift(text),killRing.length>10)killRing.pop()}function findWordBoundary(value,cursor,direction){let pos=cursor,peek=direction>0?(p)=>value[p]:(p)=>value[p-1],inBounds=direction>0?(p)=>p<value.length:(p)=>p>0;while(inBounds(pos)&&/\s/.test(peek(pos)??""))pos+=direction;while(inBounds(pos)&&!/\s/.test(peek(pos)??""))pos+=direction;return pos}function findPrevWordStart(value,cursor){return findWordBoundary(value,cursor,-1)}function findNextWordEnd(value,cursor){return findWordBoundary(value,cursor,1)}function handleReadlineKey(input,key,value,cursor,yankState){if(key.leftArrow||key.ctrl&&input==="b")return{value,cursor:cursor>0?cursor-1:cursor,yankState:null};if(key.rightArrow||key.ctrl&&input==="f")return{value,cursor:cursor<value.length?cursor+1:cursor,yankState:null};if(key.meta&&input==="b")return{value,cursor:findPrevWordStart(value,cursor),yankState:null};if(key.meta&&input==="f")return{value,cursor:findNextWordEnd(value,cursor),yankState:null};if(key.ctrl&&input==="w"){if(cursor===0)return{value,cursor,yankState:null};let newCursor=findPrevWordStart(value,cursor);return addToKillRing(value.slice(newCursor,cursor)),{value:value.slice(0,newCursor)+value.slice(cursor),cursor:newCursor,yankState:null}}if(key.meta&&key.backspace){if(cursor===0)return{value,cursor,yankState:null};let newCursor=findPrevWordStart(value,cursor);return addToKillRing(value.slice(newCursor,cursor)),{value:value.slice(0,newCursor)+value.slice(cursor),cursor:newCursor,yankState:null}}if(key.meta&&input==="d"){if(cursor>=value.length)return{value,cursor,yankState:null};let newEnd=findNextWordEnd(value,cursor);return addToKillRing(value.slice(cursor,newEnd)),{value:value.slice(0,cursor)+value.slice(newEnd),cursor,yankState:null}}if(key.ctrl&&input==="y"){if(killRing.length===0)return{value,cursor,yankState};let text=killRing[0]??"",newCursor=cursor+text.length;return{value:value.slice(0,cursor)+text+value.slice(cursor),cursor:newCursor,yankState:{lastYankIndex:0,yankStart:cursor,yankEnd:newCursor}}}if(key.meta&&input==="y"){if(!yankState||killRing.length<=1)return{value,cursor,yankState};let nextIndex=(yankState.lastYankIndex+1)%killRing.length,text=killRing[nextIndex]??"",newValue=value.slice(0,yankState.yankStart)+text+value.slice(yankState.yankEnd),newCursor=yankState.yankStart+text.length;return{value:newValue,cursor:newCursor,yankState:{lastYankIndex:nextIndex,yankStart:yankState.yankStart,yankEnd:newCursor}}}if(key.ctrl&&input==="t"){if(cursor<2)return{value,cursor,yankState:null};return{value:value.slice(0,cursor-2)+value[cursor-1]+value[cursor-2]+value.slice(cursor),cursor,yankState:null}}if(key.ctrl&&input==="h"){if(cursor>0)return{value:value.slice(0,cursor-1)+value.slice(cursor),cursor:cursor-1,yankState:null};return{value,cursor,yankState:null}}if(key.backspace||key.delete){if(cursor>0)return{value:value.slice(0,cursor-1)+value.slice(cursor),cursor:cursor-1,yankState:null};return{value,cursor,yankState:null}}if(key.ctrl&&input==="d"){if(cursor<value.length)return{value:value.slice(0,cursor)+value.slice(cursor+1),cursor,yankState:null};return{value,cursor,yankState:null}}let char=key.text??input;if(char.length>=1&&char>=" ")return{value:value.slice(0,cursor)+char+value.slice(cursor),cursor:cursor+char.length,yankState:null};return null}function useReadline({initialValue="",onChange,isActive=!0,handleEnter=!1,handleEscape=!1,handleVerticalArrows=!1,onEOF,onSubmit}={}){let[state,setState]=useState9({value:initialValue,cursor:initialValue.length}),stateRef=useRef12({value:initialValue,cursor:initialValue.length});stateRef.current=state;let yankStateRef=useRef12(null),applyResult=useCallback14((result,prevValue)=>{if(yankStateRef.current=result.yankState,result.value===prevValue&&result.cursor===stateRef.current.cursor)return;let next={value:result.value,cursor:result.cursor};if(stateRef.current=next,setState(next),result.value!==prevValue)onChange?.(result.value)},[onChange]),clear=useCallback14(()=>{let next={value:"",cursor:0};stateRef.current=next,setState(next),onChange?.(""),yankStateRef.current=null},[onChange]),setValue=useCallback14((value)=>{let next={value,cursor:value.length};stateRef.current=next,setState(next),onChange?.(value),yankStateRef.current=null},[onChange]),setValueWithCursor=useCallback14((value,cursor)=>{let next={value,cursor:Math.max(0,Math.min(cursor,value.length))};stateRef.current=next,setState(next),onChange?.(value),yankStateRef.current=null},[onChange]);return useInput((input,key)=>{let{value,cursor}=stateRef.current;if(key.return&&!handleEnter)return;if(key.return&&handleEnter){onSubmit?.(value);return}if(key.escape&&!handleEscape)return;if((key.upArrow||key.downArrow)&&!handleVerticalArrows)return;if(key.ctrl&&input==="d"&&value.length===0){onEOF?.();return}if(key.ctrl&&input==="a"){applyResult({value,cursor:0,yankState:null},value);return}if(key.ctrl&&input==="e"){applyResult({value,cursor:value.length,yankState:null},value);return}if(key.ctrl&&input==="u"){if(cursor===0)return;addToKillRing(value.slice(0,cursor)),applyResult({value:value.slice(cursor),cursor:0,yankState:null},value);return}if(key.ctrl&&input==="k"){if(cursor>=value.length)return;addToKillRing(value.slice(cursor)),applyResult({value:value.slice(0,cursor),cursor,yankState:null},value);return}let result=handleReadlineKey(input,key,value,cursor,yankStateRef.current);if(result)applyResult(result,value)},{isActive}),{value:state.value,cursor:state.cursor,beforeCursor:state.value.slice(0,state.cursor),afterCursor:state.value.slice(state.cursor),clear,setValue,setValueWithCursor,killRing:[...killRing]}}init_context();import React7,{createContext as createContext7,useCallback as useCallback15,useContext as useContext28,useEffect as useEffect14,useLayoutEffect as useLayoutEffect5,useRef as useRef13}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=createContext7(null);function CursorProvider({store,children}){return React7.createElement(CursorCtx.Provider,{value:store},children)}var _globalCursorState=null,_globalCursorListeners=new Set;function globalSetCursorState(state){_globalCursorState=state;for(let listener of _globalCursorListeners)listener()}function globalGetCursorState(){return _globalCursorState}function globalSubscribeCursor(listener){return _globalCursorListeners.add(listener),()=>{_globalCursorListeners.delete(listener)}}function resetCursorState(){_globalCursorState=null,_globalCursorListeners=new Set}function useCursor(position){let{col,row,visible=!0,shape}=position,store=useContext28(CursorCtx),node=useContext28(NodeContext),set=store?store.setCursorState.bind(store):globalSetCursorState,get=store?store.accessors.getCursorState:globalGetCursorState,props=node?.props,padLeft=props?.paddingLeft??props?.paddingX??props?.padding??0,padTop=props?.paddingTop??props?.paddingY??props?.padding??0,borderLeft=props?.borderStyle?1:0,borderTop=props?.borderStyle?1:0,contentOffsetX=borderLeft+padLeft,contentOffsetY=borderTop+padTop,colRef=useRef13(col),rowRef=useRef13(row),visibleRef=useRef13(visible),shapeRef=useRef13(shape),setRef=useRef13(set),getRef=useRef13(get),lastRectRef=useRef13(null),contentOffsetXRef=useRef13(contentOffsetX),contentOffsetYRef=useRef13(contentOffsetY);colRef.current=col,rowRef.current=row,visibleRef.current=visible,shapeRef.current=shape,setRef.current=set,getRef.current=get,contentOffsetXRef.current=contentOffsetX,contentOffsetYRef.current=contentOffsetY,useScrollRect(useCallback15((rect)=>{if(lastRectRef.current=rect,!visibleRef.current)return;setRef.current({x:rect.x+contentOffsetXRef.current+colRef.current,y:rect.y+contentOffsetYRef.current+rowRef.current,visible:!0,shape:shapeRef.current})},[])),useLayoutEffect5(()=>{let rect=lastRectRef.current;if(!rect||!visible)return;set({x:rect.x+contentOffsetX+col,y:rect.y+contentOffsetY+row,visible:!0,shape})},[col,row,contentOffsetX,contentOffsetY,shape,visible,set]),useEffect14(()=>{if(!visible){if(getRef.current())setRef.current(null)}return()=>{setRef.current(null)}},[visible])}function getCursorState(){return globalGetCursorState()}function subscribeCursor(listener){return globalSubscribeCursor(listener)}import{jsxDEV as jsxDEV13,Fragment as Fragment2}from"react/jsx-dev-runtime";var TextInput=forwardRef5(function({value:controlledValue,defaultValue="",onChange,onSubmit,onEOF,placeholder="",isActive:isActiveProp,prompt="",promptColor="$control",color,cursorStyle:cursorStyle2="block",showUnderline=!1,underlineWidth=40,mask,borderStyle:borderStyleProp,borderColor:borderColorProp="$border",focusBorderColor="$focusborder",testID},ref){let{focused}=useFocusable(),isActive=isActiveProp??(testID?focused:!0),isControlled=controlledValue!==void 0,internalChangeRef=useRef14(!1),readline=useReadline({initialValue:isControlled?controlledValue??"":defaultValue,onChange:useCallback16((newValue)=>{internalChangeRef.current=!0,onChange?.(newValue)},[onChange]),isActive,handleEnter:!!onSubmit,onSubmit,onEOF}),[lastControlledValue,setLastControlledValue]=useState10(controlledValue);useEffect15(()=>{if(isControlled&&controlledValue!==lastControlledValue){if(internalChangeRef.current)internalChangeRef.current=!1;else readline.setValue(controlledValue??"");setLastControlledValue(controlledValue)}},[isControlled,controlledValue,lastControlledValue,readline]);let{value,cursor,clear,setValue,killRing:killRing2}=readline;useImperativeHandle4(ref,()=>({clear,getValue:()=>value,setValue,getKillRing:()=>killRing2}));let displayValue=mask?mask.repeat(value.length):value,displayBeforeCursor=displayValue.slice(0,cursor),displayAtCursor=displayValue[cursor]??" ",displayAfterCursor=displayValue.slice(cursor+1),showPlaceholder=!value&&placeholder,cursorEl=cursorStyle2==="underline"?jsxDEV13(Text,{underline:!0,children:displayAtCursor},void 0,!1,void 0,this):jsxDEV13(Text,{inverse:!0,children:displayAtCursor},void 0,!1,void 0,this),borderColOffset=borderStyleProp?2:0,borderRowOffset=borderStyleProp?1:0;useCursor({col:prompt.length+displayBeforeCursor.length+borderColOffset,row:borderRowOffset,visible:isActive});let handleMouseDown=useCallback16((e)=>{if(e.button!==0)return;let rect=e.currentTarget.scrollRect;if(!rect)return;let relativeX=e.clientX-rect.x-prompt.length,newCursor=Math.max(0,Math.min(relativeX,value.length));readline.setValueWithCursor(value,newCursor)},[prompt.length,value,readline]),inputContent=jsxDEV13(Text,{color,children:[prompt&&jsxDEV13(Text,{color:promptColor,children:prompt},void 0,!1,void 0,this),showPlaceholder?jsxDEV13(Fragment2,{children:[cursorStyle2==="underline"?jsxDEV13(Text,{underline:!0,dimColor:!0,children:placeholder[0]},void 0,!1,void 0,this):jsxDEV13(Text,{inverse:!0,dimColor:!0,children:placeholder[0]},void 0,!1,void 0,this),jsxDEV13(Text,{dimColor:!0,children:placeholder.slice(1)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):jsxDEV13(Fragment2,{children:[jsxDEV13(Text,{children:displayBeforeCursor},void 0,!1,void 0,this),cursorEl,jsxDEV13(Text,{children:displayAfterCursor},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(borderStyleProp)return jsxDEV13(Box,{focusable:!0,testID,flexDirection:"column",borderStyle:borderStyleProp,borderColor:isActive?focusBorderColor:borderColorProp,paddingX:1,onMouseDown:handleMouseDown,children:[inputContent,showUnderline&&jsxDEV13(Text,{dimColor:!0,children:"─".repeat(underlineWidth)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return jsxDEV13(Box,{focusable:!0,testID,flexDirection:"column",onMouseDown:handleMouseDown,children:[inputContent,showUnderline&&jsxDEV13(Text,{dimColor:!0,children:"─".repeat(underlineWidth)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{forwardRef as forwardRef6,useCallback as useCallback18,useImperativeHandle as useImperativeHandle5,useRef as useRef16}from"react";import{useCallback as useCallback17,useMemo as useMemo10,useRef as useRef15,useState as useState11}from"react";init_unicode();function cursorToRowCol(text,cursor,wrapWidth,measurer){if(wrapWidth<=0)return{row:0,col:0};return cursorToRowColFromLines(getWrappedLines(text,wrapWidth,measurer),cursor)}function cursorToRowColFromLines(lines,cursor){for(let i=0;i<lines.length;i++){let line=lines[i],lineEnd=line.startOffset+line.line.length,isLast=i===lines.length-1;if(cursor<=lineEnd||isLast){let col=Math.max(0,Math.min(cursor-line.startOffset,line.line.length));return{row:i,col}}}return{row:Math.max(0,lines.length-1),col:0}}function getWrappedLines(text,wrapWidth,measurer){if(wrapWidth<=0)return[{line:"",startOffset:0}];let logicalLines=text.split(`
83
87
  `),result=[],offset=0,wt=measurer?measurer.wrapText.bind(measurer):wrapText;for(let li=0;li<logicalLines.length;li++){let line=logicalLines[li],wrapped=wt(line,wrapWidth,!1,!0),lines=wrapped.length===0?[""]:wrapped;for(let wLine of lines){while(offset<text.length&&text[offset]===" "&&wLine.length>0&&text[offset]!==wLine[0])offset++;result.push({line:wLine,startOffset:offset}),offset+=wLine.length}while(offset<text.length&&text[offset]===" ")offset++;offset++}return result}function rowColToCursor(text,row,col,wrapWidth,measurer){let lines=getWrappedLines(text,wrapWidth,measurer);if(row<0)return 0;if(row>=lines.length)return text.length;let line=lines[row];return line.startOffset+Math.min(col,line.line.length)}function cursorMoveUp(text,cursor,wrapWidth,stickyX,measurer){if(wrapWidth<=0)return cursor>0?0:null;let lines=getWrappedLines(text,wrapWidth,measurer),{row,col}=cursorToRowColFromLines(lines,cursor);if(row===0)return null;let targetX=stickyX??col;for(let prevRow=row-1;prevRow>=0;prevRow--){let targetLine=lines[prevRow],next=targetLine.startOffset+Math.min(targetX,targetLine.line.length);if(next!==cursor)return next}return null}function cursorMoveDown(text,cursor,wrapWidth,stickyX,measurer){if(wrapWidth<=0)return cursor<text.length?text.length:null;let lines=getWrappedLines(text,wrapWidth,measurer),{row,col}=cursorToRowColFromLines(lines,cursor);if(row>=lines.length-1)return null;let targetX=stickyX??col;for(let nextRow=row+1;nextRow<lines.length;nextRow++){let targetLine=lines[nextRow],next=targetLine.startOffset+Math.min(targetX,targetLine.line.length);if(next!==cursor)return next}return null}function countVisualLines(text,wrapWidth,measurer){return getWrappedLines(text,wrapWidth,measurer).length}function clampScroll(cursorRow,currentScroll,viewportHeight,totalLines,margin){if(viewportHeight<=0)return 0;let effectiveMargin=totalLines<=viewportHeight?0:Math.min(margin,Math.floor((viewportHeight-1)/2)),scroll=currentScroll;if(cursorRow<scroll+effectiveMargin)scroll=cursorRow-effectiveMargin;if(cursorRow>=scroll+viewportHeight-effectiveMargin)scroll=cursorRow-viewportHeight+1+effectiveMargin;return Math.max(0,Math.min(scroll,Math.max(0,totalLines-viewportHeight)))}function useTextArea({value:controlledValue,defaultValue="",onChange,onSubmit,submitKey="ctrl+enter",isActive=!0,height,wrapWidth:rawWrapWidth,scrollMargin=1,disabled,maxLength}){let isControlled=controlledValue!==void 0,[uncontrolledValue,setUncontrolledValue]=useState11(defaultValue),[cursor,setCursor]=useState11(defaultValue.length),[scrollOffset,setScrollOffset]=useState11(0),stickyXRef=useRef15(null),yankStateRef=useRef15(null),[selectionAnchor,setSelectionAnchor]=useState11(null),selectionAnchorRef=useRef15(null);selectionAnchorRef.current=selectionAnchor;let value=isControlled?controlledValue??"":uncontrolledValue,wrapWidth=Math.max(1,rawWrapWidth),clampedCursor=Math.min(cursor,value.length);if(clampedCursor!==cursor)setCursor(clampedCursor);let stateRef=useRef15({value,cursor:clampedCursor});stateRef.current.value=value,stateRef.current.cursor=clampedCursor;let scrollRef=useRef15(scrollOffset);scrollRef.current=scrollOffset;let setCursorAndScroll=useCallback17((newCursor,text)=>{stateRef.current.cursor=newCursor,setCursor(newCursor);let{row}=cursorToRowCol(text,newCursor,wrapWidth),totalLines=getWrappedLines(text,wrapWidth).length,newScroll=clampScroll(row,scrollRef.current,height,totalLines,scrollMargin);if(newScroll!==scrollRef.current)setScrollOffset(newScroll)},[wrapWidth,height,scrollMargin]),updateValue=useCallback17((newValue,newCursor)=>{if(maxLength!==void 0&&newValue.length>maxLength&&newValue.length>stateRef.current.value.length)return;if(stateRef.current.value=newValue,stateRef.current.cursor=newCursor,!isControlled)setUncontrolledValue(newValue);setCursorAndScroll(newCursor,newValue),onChange?.(newValue),yankStateRef.current=null},[isControlled,maxLength,onChange,setCursorAndScroll]),getSelectionRange=useCallback17(()=>{let anchor=selectionAnchorRef.current;if(anchor===null)return null;let cur=stateRef.current.cursor;if(anchor===cur)return null;return{start:Math.min(anchor,cur),end:Math.max(anchor,cur)}},[]),deleteSelection=useCallback17(()=>{let sel=getSelectionRange();if(!sel)return null;let v=stateRef.current.value;return{newValue:v.slice(0,sel.start)+v.slice(sel.end),newCursor:sel.start}},[getSelectionRange]),moveCursor3=useCallback17((newCursor,text,shift)=>{if(shift){if(selectionAnchorRef.current===null){let anchor=stateRef.current.cursor;setSelectionAnchor(anchor),selectionAnchorRef.current=anchor}}else if(selectionAnchorRef.current!==null)setSelectionAnchor(null),selectionAnchorRef.current=null;setCursorAndScroll(newCursor,text)},[setCursorAndScroll]),replaceSelectionWith=useCallback17((insertText)=>{let sel=getSelectionRange(),{value:value2}=stateRef.current;if(sel){let newValue=value2.slice(0,sel.start)+insertText+value2.slice(sel.end),newCursor=sel.start+insertText.length;return setSelectionAnchor(null),selectionAnchorRef.current=null,updateValue(newValue,newCursor),!0}return!1},[getSelectionRange,updateValue]),wrappedLines=useMemo10(()=>getWrappedLines(value,wrapWidth),[value,wrapWidth]),{row:cursorRow,col:cursorCol}=useMemo10(()=>cursorToRowCol(value,clampedCursor,wrapWidth),[value,clampedCursor,wrapWidth]);useInput((input,key)=>{if(disabled)return;let{value:value2,cursor:cursor2}=stateRef.current,lines=getWrappedLines(value2,wrapWidth),{row:cRow,col:cCol}=cursorToRowCol(value2,cursor2,wrapWidth),hasSelection=selectionAnchorRef.current!==null&&selectionAnchorRef.current!==cursor2,clearSelection=()=>{if(selectionAnchorRef.current!==null)setSelectionAnchor(null),selectionAnchorRef.current=null};if(submitKey==="ctrl+enter"&&key.return&&key.ctrl){onSubmit?.(value2);return}if(submitKey==="enter"&&key.return&&!key.ctrl){onSubmit?.(value2);return}if(submitKey==="meta+enter"&&key.return&&key.meta){onSubmit?.(value2);return}if(key.ctrl&&input==="a"){stickyXRef.current=null,setSelectionAnchor(0),selectionAnchorRef.current=0,setCursorAndScroll(value2.length,value2),yankStateRef.current=null;return}if(key.return&&submitKey!=="enter"){if(stickyXRef.current=null,hasSelection)replaceSelectionWith(`
84
88
  `);else updateValue(value2.slice(0,cursor2)+`
85
- `+value2.slice(cursor2),cursor2+1);return}if(key.leftArrow&&key.shift){stickyXRef.current=null;let target=key.ctrl?findPrevWordStart(value2,cursor2):Math.max(0,cursor2-1);moveCursor3(target,value2,!0),yankStateRef.current=null;return}if(key.rightArrow&&key.shift){stickyXRef.current=null;let target=key.ctrl?findNextWordEnd(value2,cursor2):Math.min(value2.length,cursor2+1);moveCursor3(target,value2,!0),yankStateRef.current=null;return}if(key.upArrow&&key.shift){if(cRow>0){let targetX=stickyXRef.current??cCol;stickyXRef.current=targetX;let targetLine=lines[cRow-1];if(targetLine)moveCursor3(targetLine.startOffset+Math.min(targetX,targetLine.line.length),value2,!0)}yankStateRef.current=null;return}if(key.downArrow&&key.shift){if(cRow<lines.length-1){let targetX=stickyXRef.current??cCol;stickyXRef.current=targetX;let targetLine=lines[cRow+1];if(targetLine)moveCursor3(targetLine.startOffset+Math.min(targetX,targetLine.line.length),value2,!0)}yankStateRef.current=null;return}if(key.home&&key.shift){stickyXRef.current=null;let currentLine=lines[cRow];if(currentLine)moveCursor3(currentLine.startOffset,value2,!0);yankStateRef.current=null;return}if(key.end&&key.shift){stickyXRef.current=null;let currentLine=lines[cRow];if(currentLine)moveCursor3(currentLine.startOffset+currentLine.line.length,value2,!0);yankStateRef.current=null;return}if(key.upArrow){if(cRow>0){let targetX=stickyXRef.current??cCol;stickyXRef.current=targetX;let targetLine=lines[cRow-1];if(targetLine)moveCursor3(targetLine.startOffset+Math.min(targetX,targetLine.line.length),value2,!1)}else clearSelection();yankStateRef.current=null;return}if(key.downArrow){if(cRow<lines.length-1){let targetX=stickyXRef.current??cCol;stickyXRef.current=targetX;let targetLine=lines[cRow+1];if(targetLine)moveCursor3(targetLine.startOffset+Math.min(targetX,targetLine.line.length),value2,!1)}else clearSelection();yankStateRef.current=null;return}if(key.ctrl&&key.home){stickyXRef.current=null,moveCursor3(0,value2,!1),yankStateRef.current=null;return}if(key.ctrl&&key.end){stickyXRef.current=null,moveCursor3(value2.length,value2,!1),yankStateRef.current=null;return}if(key.home){stickyXRef.current=null;let currentLine=lines[cRow];if(currentLine)moveCursor3(currentLine.startOffset,value2,!1);yankStateRef.current=null;return}if(key.end||key.ctrl&&input==="e"){stickyXRef.current=null;let currentLine=lines[cRow];if(currentLine)moveCursor3(currentLine.startOffset+currentLine.line.length,value2,!1);yankStateRef.current=null;return}if(key.pageUp){stickyXRef.current=null;let targetLine=lines[Math.max(0,cRow-height)];if(targetLine)moveCursor3(targetLine.startOffset+Math.min(cCol,targetLine.line.length),value2,!1);yankStateRef.current=null;return}if(key.pageDown){stickyXRef.current=null;let targetLine=lines[Math.min(lines.length-1,cRow+height)];if(targetLine)moveCursor3(targetLine.startOffset+Math.min(cCol,targetLine.line.length),value2,!1);yankStateRef.current=null;return}if(key.ctrl&&input==="k"){stickyXRef.current=null,clearSelection();let currentLine=lines[cRow];if(!currentLine)return;let lineEnd=currentLine.startOffset+currentLine.line.length;if(cursor2<lineEnd)addToKillRing(value2.slice(cursor2,lineEnd)),updateValue(value2.slice(0,cursor2)+value2.slice(lineEnd),cursor2);else if(cursor2<value2.length)addToKillRing(value2.slice(cursor2,cursor2+1)),updateValue(value2.slice(0,cursor2)+value2.slice(cursor2+1),cursor2);return}if(key.ctrl&&input==="u"){stickyXRef.current=null,clearSelection();let currentLine=lines[cRow];if(!currentLine)return;let lineStart=currentLine.startOffset;if(cursor2>lineStart)addToKillRing(value2.slice(lineStart,cursor2)),updateValue(value2.slice(0,lineStart)+value2.slice(cursor2),lineStart);return}if((key.backspace||key.delete)&&hasSelection){stickyXRef.current=null;let del=deleteSelection();if(del)clearSelection(),updateValue(del.newValue,del.newCursor);yankStateRef.current=null;return}if(hasSelection&&input.length>=1&&input>=" "){stickyXRef.current=null,replaceSelectionWith(input),yankStateRef.current=null;return}let result=handleReadlineKey(input,key,value2,cursor2,yankStateRef.current);if(result){if(stickyXRef.current=null,clearSelection(),result.value===value2&&result.cursor===cursor2){yankStateRef.current=result.yankState;return}if(result.value!==value2){if(maxLength!==void 0&&result.value.length>maxLength&&result.value.length>value2.length){yankStateRef.current=result.yankState;return}if(stateRef.current.value=result.value,stateRef.current.cursor=result.cursor,!isControlled)setUncontrolledValue(result.value);setCursorAndScroll(result.cursor,result.value),onChange?.(result.value)}else setCursorAndScroll(result.cursor,value2);yankStateRef.current=result.yankState}},{isActive});let visibleCursorRow=cursorRow-scrollOffset,selection=selectionAnchor!==null&&selectionAnchor!==clampedCursor?{start:Math.min(selectionAnchor,clampedCursor),end:Math.max(selectionAnchor,clampedCursor)}:null,visibleLines=wrappedLines.slice(scrollOffset,scrollOffset+height),clear=useCallback17(()=>{updateValue("",0),setScrollOffset(0),setSelectionAnchor(null)},[updateValue]),setValue=useCallback17((v)=>{updateValue(v,v.length),setSelectionAnchor(null)},[updateValue]),setCursorFn=useCallback17((offset)=>{let clamped=Math.min(Math.max(0,offset),stateRef.current.value.length);setSelectionAnchor(null),selectionAnchorRef.current=null,setCursorAndScroll(clamped,stateRef.current.value)},[setCursorAndScroll]);return{value,cursor:clampedCursor,cursorRow,cursorCol,visibleCursorRow,scrollOffset,wrappedLines,visibleLines,selection,selectionAnchor,clear,setValue,getSelection:getSelectionRange,setCursor:setCursorFn}}import{jsxDEV as jsxDEV14}from"react/jsx-dev-runtime";var TextArea=forwardRef6(function({value:controlledValue,defaultValue="",onChange,onSubmit,submitKey="ctrl+enter",placeholder="",isActive:isActiveProp,height,cursorStyle:cursorStyle2="block",scrollMargin=1,disabled,maxLength,borderStyle:borderStyleProp,borderColor:borderColorProp="$border",focusBorderColor="$focusborder",testID},ref){let{focused}=useFocusable(),isActive=isActiveProp??(testID?focused:!0),{width:parentWidth}=useBoxRect(),contentWidth=borderStyleProp?Math.max(1,parentWidth-4):parentWidth,ta=useTextArea({value:controlledValue,defaultValue,onChange,onSubmit,submitKey,isActive,height,wrapWidth:contentWidth,scrollMargin,disabled,maxLength});useImperativeHandle5(ref,()=>({clear:ta.clear,getValue:()=>ta.value,setValue:ta.setValue,getSelection:ta.getSelection}));let wrappedLinesRef=useRef16(ta.wrappedLines);wrappedLinesRef.current=ta.wrappedLines;let scrollOffsetRef=useRef16(ta.scrollOffset);scrollOffsetRef.current=ta.scrollOffset;let handleMouseDown=useCallback18((e)=>{if(e.button!==0)return;let rect=e.currentTarget.scrollRect;if(!rect)return;let lines=wrappedLinesRef.current,scroll=scrollOffsetRef.current,row=e.clientY-rect.y+scroll,clampedRow=Math.min(Math.max(0,row),lines.length-1),wl=lines[clampedRow];if(!wl)return;let relativeX=e.clientX-rect.x,col=Math.min(Math.max(0,relativeX),wl.line.length),offset=Math.min(Math.max(0,wl.startOffset+col),ta.value.length);ta.setCursor(offset)},[ta]),showPlaceholder=!ta.value&&placeholder,borderProps=borderStyleProp?{borderStyle:borderStyleProp,borderColor:isActive?focusBorderColor:borderColorProp,paddingX:1}:{},borderColOffset=borderStyleProp?2:0,borderRowOffset=borderStyleProp?1:0;if(useCursor({col:ta.cursorCol+borderColOffset,row:ta.visibleCursorRow+borderRowOffset,visible:isActive&&!disabled&&!ta.selection}),showPlaceholder)return jsxDEV14(Box,{focusable:!0,testID,flexDirection:"column",height,...borderProps,children:jsxDEV14(Text,{dimColor:!0,children:placeholder},void 0,!1,void 0,this)},void 0,!1,void 0,this);return jsxDEV14(Box,{focusable:!0,testID,flexDirection:"column",height,...borderProps,onMouseDown:handleMouseDown,children:ta.visibleLines.map((wl,i)=>{let absoluteRow=ta.scrollOffset+i,isCursorRow=absoluteRow===ta.cursorRow,lineStart=wl.startOffset,lineEnd=lineStart+wl.line.length,hasSelectionOnLine=ta.selection&&lineStart<ta.selection.end&&lineEnd>ta.selection.start;if(disabled)return jsxDEV14(Text,{dimColor:!0,children:wl.line||" "},absoluteRow,!1,void 0,this);if(hasSelectionOnLine){let selStart=Math.max(0,ta.selection.start-lineStart),selEnd=Math.min(wl.line.length,ta.selection.end-lineStart),before=wl.line.slice(0,selStart),selected=wl.line.slice(selStart,selEnd),after=wl.line.slice(selEnd);return jsxDEV14(Text,{children:[before,jsxDEV14(Text,{inverse:!0,children:selected||(selEnd===wl.line.length&&isCursorRow?" ":"")},void 0,!1,void 0,this),after]},absoluteRow,!0,void 0,this)}if(!isCursorRow)return jsxDEV14(Text,{children:wl.line||" "},absoluteRow,!1,void 0,this);let beforeCursor=wl.line.slice(0,ta.cursorCol),atCursor=wl.line[ta.cursorCol]??" ",afterCursor=wl.line.slice(ta.cursorCol+1);return jsxDEV14(Text,{children:[beforeCursor,isActive?jsxDEV14(Text,{children:atCursor},void 0,!1,void 0,this):cursorStyle2==="block"?jsxDEV14(Text,{inverse:!0,children:atCursor},void 0,!1,void 0,this):jsxDEV14(Text,{underline:!0,children:atCursor},void 0,!1,void 0,this),afterCursor]},absoluteRow,!0,void 0,this)})},ta.scrollOffset,!1,void 0,this)});import{useCallback as useCallback19,useMemo as useMemo11,useRef as useRef17}from"react";import{jsxDEV as jsxDEV15}from"react/jsx-dev-runtime";function clampScroll2(cursorRow,currentScroll,viewportHeight){if(viewportHeight<=0)return 0;let scroll=currentScroll;if(cursorRow<scroll)scroll=cursorRow;if(cursorRow>=scroll+viewportHeight)scroll=cursorRow-viewportHeight+1;return Math.max(0,scroll)}function EditContextDisplay({value,cursor,height,wrapWidth,cursorStyle:cursorStyle2="block",placeholder="",showCursor=!0,onCursorClick}){let scrollRef=useRef17(0),effectiveWrapWidth=wrapWidth!=null&&wrapWidth>0?wrapWidth:1e4,clampedCursor=Math.min(Math.max(0,cursor),value.length),wrappedLines=useMemo11(()=>getWrappedLines(value,effectiveWrapWidth),[value,effectiveWrapWidth]),{row:cursorRow,col:cursorCol}=useMemo11(()=>cursorToRowCol(value,clampedCursor,effectiveWrapWidth),[value,clampedCursor,effectiveWrapWidth]),hasViewport=height!=null&&height>0;if(hasViewport)scrollRef.current=clampScroll2(cursorRow,scrollRef.current,height);if(!value&&placeholder){if(hasViewport)return jsxDEV15(Box,{flexDirection:"column",height,justifyContent:"center",alignItems:"center",children:jsxDEV15(Text,{dimColor:!0,children:placeholder},void 0,!1,void 0,this)},void 0,!1,void 0,this);return jsxDEV15(Box,{flexDirection:"column",children:jsxDEV15(Text,{dimColor:!0,children:placeholder},void 0,!1,void 0,this)},void 0,!1,void 0,this)}let currentScroll=hasViewport?scrollRef.current:0,visibleLines=hasViewport?wrappedLines.slice(currentScroll,currentScroll+height):wrappedLines,wrappedLinesRef=useRef17(wrappedLines);wrappedLinesRef.current=wrappedLines;let scrollRefForClick=scrollRef,handleMouseDown=useCallback19((e)=>{if(!onCursorClick||e.button!==0)return;let rect=e.currentTarget.scrollRect;if(!rect)return;let lines=wrappedLinesRef.current,scroll=scrollRefForClick.current,row=e.clientY-rect.y+scroll,clampedRow=Math.min(Math.max(0,row),lines.length-1),wl=lines[clampedRow];if(!wl)return;let relativeX=e.clientX-rect.x,col=Math.min(Math.max(0,relativeX),wl.line.length),offset=Math.min(Math.max(0,wl.startOffset+col),value.length);onCursorClick(offset)},[onCursorClick,value.length]);return jsxDEV15(Box,{flexDirection:"column",height:hasViewport?height:void 0,onMouseDown:onCursorClick?handleMouseDown:void 0,children:visibleLines.map((wl,i)=>{let absoluteRow=currentScroll+i;if(!(absoluteRow===cursorRow&&showCursor))return jsxDEV15(Text,{children:wl.line||" "},absoluteRow,!1,void 0,this);let beforeCursorText=wl.line.slice(0,cursorCol),atCursor=wl.line[cursorCol]??" ",afterCursorText=wl.line.slice(cursorCol+1);return jsxDEV15(Text,{children:[beforeCursorText,cursorStyle2==="block"?jsxDEV15(Text,{inverse:!0,children:atCursor},void 0,!1,void 0,this):jsxDEV15(Text,{underline:!0,children:atCursor},void 0,!1,void 0,this),afterCursorText]},absoluteRow,!0,void 0,this)})},currentScroll,!1,void 0,this)}import{useCallback as useCallback20}from"react";import{jsxDEV as jsxDEV16}from"react/jsx-dev-runtime";function CursorLine({beforeCursor,afterCursor,color,showCursor=!0,cursorStyle:cursorStyle2="block",onCursorClick}){let totalLength=beforeCursor.length+afterCursor.length,handleMouseDown=useCallback20((e)=>{if(!onCursorClick||e.button!==0)return;let rect=e.currentTarget.scrollRect;if(!rect)return;let relativeX=e.clientX-rect.x,offset=Math.min(Math.max(0,relativeX),totalLength);onCursorClick(offset)},[onCursorClick,totalLength]),textContent=(()=>{if(!showCursor)return jsxDEV16(Text,{color,children:[beforeCursor,afterCursor]},void 0,!0,void 0,this);let cursorChar=afterCursor[0]??" ",rest=afterCursor.slice(1);return jsxDEV16(Text,{color,children:[beforeCursor,cursorStyle2==="block"?jsxDEV16(Text,{inverse:!0,children:cursorChar},void 0,!1,void 0,this):jsxDEV16(Text,{underline:!0,children:cursorChar},void 0,!1,void 0,this),rest]},void 0,!0,void 0,this)})();if(onCursorClick)return jsxDEV16(Box,{onMouseDown:handleMouseDown,children:textContent},void 0,!1,void 0,this);return textContent}import{jsxDEV as jsxDEV17,Fragment as Fragment3}from"react/jsx-dev-runtime";function formatTitleWithHotkey(title,hotkey,color){let idx=title.toLowerCase().indexOf(hotkey.toLowerCase());if(idx>=0&&hotkey.length===1&&hotkey.toLowerCase()!==hotkey.toUpperCase()){let before=title.slice(0,idx),matched=title[idx],after=title.slice(idx+1);return jsxDEV17(Text,{color,bold:!0,children:[before,jsxDEV17(Text,{dimColor:!0,bold:!1,children:"["},void 0,!1,void 0,this),jsxDEV17(Text,{bold:!0,children:matched},void 0,!1,void 0,this),jsxDEV17(Text,{dimColor:!0,bold:!1,children:"]"},void 0,!1,void 0,this),after]},void 0,!0,void 0,this)}return jsxDEV17(Text,{color,bold:!0,children:[jsxDEV17(Text,{dimColor:!0,bold:!1,children:"["},void 0,!1,void 0,this),jsxDEV17(Text,{bold:!0,children:hotkey},void 0,!1,void 0,this),jsxDEV17(Text,{dimColor:!0,bold:!1,children:"]"},void 0,!1,void 0,this)," ",title]},void 0,!0,void 0,this)}function ModalDialog({borderColor="$border",title,titleColor,titleAlign="center",hotkey,titleRight,width,height,footer,footerAlign="center",onClose:_onClose,focusScope:_focusScope=!0,children,...boxProps}){let effectiveTitleColor=titleColor??"$primary";return jsxDEV17(Box,{flexDirection:"column",width:width??"snug-content",height,borderStyle:"double",borderColor,backgroundColor:"$popover-bg",paddingX:2,paddingY:1,userSelect:"contain",...boxProps,children:[title&&jsxDEV17(Box,{flexShrink:0,flexDirection:"column",children:[jsxDEV17(Box,{justifyContent:titleRight?"space-between":titleAlign,children:[hotkey?formatTitleWithHotkey(title,hotkey,effectiveTitleColor):jsxDEV17(Text,{color:effectiveTitleColor,bold:!0,children:title},void 0,!1,void 0,this),titleRight]},void 0,!0,void 0,this),jsxDEV17(Text,{children:" "},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jsxDEV17(Box,{flexDirection:"column",flexGrow:1,overflow:"hidden",children},void 0,!1,void 0,this),footer&&jsxDEV17(Fragment3,{children:[jsxDEV17(Text,{children:" "},void 0,!1,void 0,this),jsxDEV17(Box,{justifyContent:footerAlign,children:typeof footer==="string"?jsxDEV17(Text,{dimColor:!0,children:footer},void 0,!1,void 0,this):footer},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}import{useCallback as useCallback21,useRef as useRef18,useState as useState12}from"react";import{jsxDEV as jsxDEV18}from"react/jsx-dev-runtime";function PickerList({items,selectedIndex,renderItem,getKey,emptyMessage="No items",maxVisible=10}){if(items.length===0)return jsxDEV18(Box,{flexDirection:"column",flexGrow:1,flexShrink:1,overflow:"hidden",children:jsxDEV18(Text,{dimColor:!0,children:emptyMessage},void 0,!1,void 0,this)},void 0,!1,void 0,this);let clampedIndex=Math.min(selectedIndex,items.length-1),effectiveHeight=Math.min(maxVisible,items.length);return jsxDEV18(Box,{flexDirection:"column",flexGrow:1,flexShrink:1,overflow:"hidden",children:jsxDEV18(ListView,{items,height:effectiveHeight,nav:!0,active:!1,cursorKey:clampedIndex,getKey:(item)=>getKey(item),renderItem:(item,_index,meta)=>renderItem(item,meta.isCursor)},void 0,!1,void 0,this)},void 0,!1,void 0,this)}import{jsxDEV as jsxDEV19}from"react/jsx-dev-runtime";function PickerDialog({title,placeholder,items,renderItem,getKey,onSelect,onCancel,onChange,initialValue="",emptyMessage="No items",maxVisible=10,width,height,footer,prompt,promptColor,isActive=!0}){let[selectedIndex,setSelectedIndex]=useState12(0),onSelectRef=useRef18(onSelect);onSelectRef.current=onSelect;let onCancelRef=useRef18(onCancel);onCancelRef.current=onCancel;let itemsRef=useRef18(items);itemsRef.current=items;let selectedIndexRef=useRef18(selectedIndex);selectedIndexRef.current=selectedIndex;let readline=useReadline({initialValue,onChange:useCallback21((value)=>{onChange?.(value),setSelectedIndex(0)},[onChange]),isActive,handleEnter:!1,handleEscape:!1,handleVerticalArrows:!1}),clampedIndex=items.length>0?Math.min(selectedIndex,items.length-1):0;if(clampedIndex!==selectedIndex)setSelectedIndex(clampedIndex);let effectiveMaxVisible=Math.min(maxVisible,items.length);useInput((_input,key)=>{if(key.escape){onCancelRef.current();return}if(key.return){let currentItems=itemsRef.current,idx=selectedIndexRef.current,item=currentItems[Math.min(idx,currentItems.length-1)];if(item)onSelectRef.current(item);return}if(key.upArrow){setSelectedIndex((i)=>Math.max(0,i-1));return}if(key.downArrow){setSelectedIndex((i)=>Math.min(i+1,Math.max(0,itemsRef.current.length-1)));return}if(key.pageUp){setSelectedIndex((i)=>Math.max(0,i-effectiveMaxVisible));return}if(key.pageDown){setSelectedIndex((i)=>Math.min(i+effectiveMaxVisible,Math.max(0,itemsRef.current.length-1)));return}},{isActive});let showPlaceholder=!readline.value&&placeholder;return jsxDEV19(ModalDialog,{title,width,height,footer,children:[jsxDEV19(Box,{flexShrink:0,flexDirection:"column",children:[jsxDEV19(Box,{children:[prompt&&jsxDEV19(Text,{color:promptColor,children:prompt},void 0,!1,void 0,this),showPlaceholder?jsxDEV19(Text,{dimColor:!0,children:placeholder},void 0,!1,void 0,this):jsxDEV19(CursorLine,{beforeCursor:readline.beforeCursor,afterCursor:readline.afterCursor,showCursor:isActive},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jsxDEV19(Text,{dimColor:!0,children:"─".repeat(40)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jsxDEV19(PickerList,{items,selectedIndex:clampedIndex,renderItem,getKey,emptyMessage,maxVisible},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as jsxDEV20}from"react/jsx-dev-runtime";function Toggle({value,onChange,label,isActive,...rest}){let{focused}=useFocusable(),active=isActive??focused;return useInput((_input,key)=>{if(_input===" "&&!key.ctrl&&!key.meta&&!key.shift)onChange(!value)},{isActive:active}),jsxDEV20(Box,{focusable:!0,...rest,children:[jsxDEV20(Text,{inverse:active,children:value?"[x]":"[ ]"},void 0,!1,void 0,this),label&&jsxDEV20(Text,{children:[" ",label]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as jsxDEV21}from"react/jsx-dev-runtime";function Button({label,onPress,isActive,color,...rest}){let{focused}=useFocusable(),active=isActive??focused;return useInput((_input,key)=>{if(key.return||_input===" "&&!key.ctrl&&!key.meta&&!key.shift)onPress()},{isActive:active}),jsxDEV21(Box,{focusable:!0,...rest,children:jsxDEV21(Text,{color,inverse:active,children:["[ ",label," ]"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}import React11 from"react";function SearchBar(){let{isActive,query,matches,currentMatch}=useSearch();if(!isActive)return null;let matchInfo=matches.length>0?`[${currentMatch+1}/${matches.length}]`:query?"[no matches]":"";return React11.createElement(Box,{flexDirection:"row"},React11.createElement(Text,{inverse:!0},` / ${query} ${matchInfo} `))}import{useEffect as useEffect16,useState as useState13}from"react";import{jsxDEV as jsxDEV22}from"react/jsx-dev-runtime";var FRAMES={dots:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],line:["|","/","—","\\"],arc:["◜","◠","◝","◞","◡","◟"],bounce:["⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"]};function Spinner({type="dots",label,interval=80,...rest}){let[frameIndex,setFrameIndex]=useState13(0),frames=FRAMES[type];useEffect16(()=>{let timer=setInterval(()=>{setFrameIndex((prev)=>(prev+1)%frames.length)},interval);return()=>clearInterval(timer)},[frames.length,interval]);let frame=frames[frameIndex%frames.length];return jsxDEV22(Text,{...rest,children:[frame,label?` ${label}`:""]},void 0,!0,void 0,this)}import{useEffect as useEffect17,useState as useState14}from"react";import{jsxDEV as jsxDEV23}from"react/jsx-dev-runtime";var DEFAULT_FILL="█",DEFAULT_EMPTY="░",DEFAULT_WIDTH=30,INDETERMINATE_BLOCK_SIZE=4,INDETERMINATE_INTERVAL=100;function ProgressBar({value,width:widthProp,fillChar=DEFAULT_FILL,emptyChar=DEFAULT_EMPTY,showPercentage,label,color}){let layoutRect=useBoxRect(),contentWidth=widthProp?0:layoutRect.width,[bouncePos,setBouncePos]=useState14(0),[bounceDir,setBounceDir]=useState14(1),isDeterminate=value!==void 0,showPct=showPercentage??isDeterminate,labelWidth=label?label.length+1:0,pctWidth=showPct?5:0,availableWidth=widthProp??(contentWidth>0?contentWidth:DEFAULT_WIDTH),barWidth=Math.max(1,availableWidth-labelWidth-pctWidth);useEffect17(()=>{if(isDeterminate)return;let timer=setInterval(()=>{setBouncePos((prev)=>{let maxPos=barWidth-INDETERMINATE_BLOCK_SIZE;if(maxPos<=0)return 0;let next=prev+bounceDir;if(next>=maxPos)return setBounceDir(-1),maxPos;if(next<=0)return setBounceDir(1),0;return next})},INDETERMINATE_INTERVAL);return()=>clearInterval(timer)},[isDeterminate,barWidth,bounceDir]);let filledPart,emptyPart;if(isDeterminate){let clamped=Math.max(0,Math.min(1,value)),filled=Math.round(clamped*barWidth);filledPart=fillChar.repeat(filled),emptyPart=emptyChar.repeat(barWidth-filled)}else{let blockSize=Math.min(INDETERMINATE_BLOCK_SIZE,barWidth),pos=Math.max(0,Math.min(bouncePos,barWidth-blockSize));filledPart=emptyChar.repeat(pos)+fillChar.repeat(blockSize),emptyPart=emptyChar.repeat(barWidth-pos-blockSize)}let pct=isDeterminate?Math.round(Math.max(0,Math.min(1,value))*100):0;return jsxDEV23(Box,{children:[label&&jsxDEV23(Text,{children:[label," "]},void 0,!0,void 0,this),jsxDEV23(Text,{color,children:filledPart},void 0,!1,void 0,this),jsxDEV23(Text,{dimColor:!0,children:emptyPart},void 0,!1,void 0,this),showPct&&jsxDEV23(Text,{children:[String(pct).padStart(4),"%"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}import{useCallback as useCallback22,useState as useState15}from"react";import{jsxDEV as jsxDEV24}from"react/jsx-dev-runtime";function findNextEnabled(items,current,direction){let len=items.length;if(len===0)return current;let next=current+direction;for(let i=0;i<len;i++){if(next<0)next=len-1;if(next>=len)next=0;if(!items[next].disabled)return next;next+=direction}return current}function findFirstEnabled(items){for(let i=0;i<items.length;i++)if(!items[i].disabled)return i;return 0}function SelectList({items,highlightedIndex:controlledIndex,onHighlight,onSelect,initialIndex,maxVisible,isActive=!0,indicator="▸ "}){let isControlled=controlledIndex!==void 0,[uncontrolledIndex,setUncontrolledIndex]=useState15(initialIndex??findFirstEnabled(items)),currentIndex=isControlled?controlledIndex:uncontrolledIndex,setIndex=useCallback22((index)=>{if(!isControlled)setUncontrolledIndex(index);onHighlight?.(index)},[isControlled,onHighlight]),handleCursor=useCallback22((nextIndex)=>{if(items[nextIndex]?.disabled){let direction=nextIndex>=currentIndex?1:-1;setIndex(findNextEnabled(items,currentIndex,direction))}else setIndex(nextIndex)},[items,currentIndex,setIndex]),handleSelect=useCallback22((index)=>{let item=items[index];if(item&&!item.disabled)onSelect?.(item,index)},[items,onSelect]),renderItem=useCallback22((item,_index,meta)=>jsxDEV24(Text,{inverse:meta.isCursor,dimColor:item.disabled,children:[indicator?meta.isCursor?indicator:" ".repeat(indicator.length):"",item.label]},item.value,!0,void 0,this),[indicator]);return jsxDEV24(ListView,{items,height:maxVisible??items.length,estimateHeight:1,nav:!0,cursorKey:currentIndex,onCursor:handleCursor,onSelect:handleSelect,active:isActive,getKey:(item)=>item.value,renderItem},void 0,!1,void 0,this)}import{useMemo as useMemo12}from"react";import{jsxDEV as jsxDEV25}from"react/jsx-dev-runtime";function computeWidths(columns,data,padding){return columns.map((col)=>{if(col.width)return col.width;if(col.grow)return 0;let cellValues=data.map((item,i)=>{if(col.render){let rendered=col.render(item,i);return typeof rendered==="string"?rendered:""}return String((col.key?item[col.key]:"")??"")});return Math.max(col.header.length,...cellValues.map((v)=>v.length))+padding})}function Table({data,columns,headerColor="$primary",showHeader=!0,padding=2}){let widths=useMemo12(()=>computeWidths(columns,data,padding),[columns,data,padding]),renderCell=(col,item,index,width)=>{let rendered=col.render?col.render(item,index):null,content=rendered!=null?typeof rendered==="string"?jsxDEV25(Text,{children:rendered},void 0,!1,void 0,this):rendered:jsxDEV25(Text,{children:String((col.key?item[col.key]:"")??"")},void 0,!1,void 0,this);return col.grow?jsxDEV25(Box,{flexGrow:1,justifyContent:col.align==="right"?"flex-end":void 0,children:content},col.header,!1,void 0,this):jsxDEV25(Box,{width,justifyContent:col.align==="right"?"flex-end":void 0,children:content},col.header,!1,void 0,this)},renderRow=(item,index)=>jsxDEV25(Box,{children:columns.map((col,colIndex)=>renderCell(col,item,index,widths[colIndex]))},void 0,!1,void 0,this),viewportHeight=Math.max(data.length,1);return jsxDEV25(Box,{flexDirection:"column",children:[showHeader&&jsxDEV25(Box,{children:columns.map((col,i)=>col.grow?jsxDEV25(Box,{flexGrow:1,children:jsxDEV25(Text,{bold:!0,color:headerColor,children:col.header},void 0,!1,void 0,this)},col.header,!1,void 0,this):jsxDEV25(Box,{width:widths[i],children:jsxDEV25(Text,{bold:!0,color:headerColor,children:col.header},void 0,!1,void 0,this)},col.header,!1,void 0,this))},void 0,!1,void 0,this),data.length>0&&jsxDEV25(ListView,{items:data,height:viewportHeight,estimateHeight:1,renderItem:renderRow},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as jsxDEV26}from"react/jsx-dev-runtime";var VARIANT_COLORS={default:"$fg",primary:"$primary",success:"$success",warning:"$warning",error:"$error"};function Badge({label,variant="default",color,...rest}){let resolvedColor=color??VARIANT_COLORS[variant];return jsxDEV26(Text,{color:resolvedColor,bold:!0,...rest,children:[" ",label," "]},void 0,!0,void 0,this)}import{jsxDEV as jsxDEV27}from"react/jsx-dev-runtime";var DEFAULT_CHAR="─",DEFAULT_WIDTH2=40;function Divider({char=DEFAULT_CHAR,title,width:widthProp}){let{width:contentWidth}=useBoxRect(),totalWidth=widthProp??(contentWidth>0?contentWidth:DEFAULT_WIDTH2);if(!title)return jsxDEV27(Box,{children:jsxDEV27(Text,{dimColor:!0,children:char.repeat(totalWidth)},void 0,!1,void 0,this)},void 0,!1,void 0,this);let titleWithPad=` ${title} `,remaining=Math.max(0,totalWidth-titleWithPad.length),leftLen=Math.floor(remaining/2),rightLen=remaining-leftLen;return jsxDEV27(Box,{children:[jsxDEV27(Text,{dimColor:!0,children:char.repeat(leftLen)},void 0,!1,void 0,this),jsxDEV27(Text,{bold:!0,children:titleWithPad},void 0,!1,void 0,this),jsxDEV27(Text,{dimColor:!0,children:char.repeat(rightLen)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{createContext as createContext8,useContext as useContext29,Children as Children2,cloneElement as cloneElement2,isValidElement as isValidElement2}from"react";import{jsxDEV as jsxDEV28}from"react/jsx-dev-runtime";function H1({children,color,...rest}){return jsxDEV28(Text,{bold:!0,color:color??"$primary",...rest,children},void 0,!1,void 0,this)}function H2({children,color,...rest}){return jsxDEV28(Text,{bold:!0,color:color??"$accent",...rest,children},void 0,!1,void 0,this)}function H3({children,color,...rest}){return jsxDEV28(Text,{color:color??"$primary",...rest,children},void 0,!1,void 0,this)}function P({children,color,...rest}){return jsxDEV28(Text,{color,...rest,children},void 0,!1,void 0,this)}function Lead({children,color,...rest}){return jsxDEV28(Text,{italic:!0,color:color??"$muted",...rest,children},void 0,!1,void 0,this)}function Muted({children,color,...rest}){return jsxDEV28(Text,{color:color??"$muted",...rest,children},void 0,!1,void 0,this)}function Small({children,color,...rest}){return jsxDEV28(Text,{dimColor:!0,color:color??"$muted",...rest,children},void 0,!1,void 0,this)}function Strong({children,color,...rest}){return jsxDEV28(Text,{bold:!0,color,...rest,children},void 0,!1,void 0,this)}function Em({children,color,...rest}){return jsxDEV28(Text,{italic:!0,color,...rest,children},void 0,!1,void 0,this)}function Code({children,color,...rest}){return jsxDEV28(Text,{backgroundColor:"$mutedbg",color,...rest,children:` ${children} `},void 0,!1,void 0,this)}function Kbd({children,color,...rest}){return jsxDEV28(Text,{backgroundColor:"$mutedbg",bold:!0,color,...rest,children:` ${children} `},void 0,!1,void 0,this)}function Blockquote({children,color}){return jsxDEV28(Box,{children:[jsxDEV28(Text,{color:color??"$muted",children:"│ "},void 0,!1,void 0,this),jsxDEV28(Box,{flexShrink:1,children:jsxDEV28(Text,{italic:!0,children},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function CodeBlock({children,color}){return jsxDEV28(Box,{children:[jsxDEV28(Text,{color:color??"$border",children:"│ "},void 0,!1,void 0,this),jsxDEV28(Box,{flexShrink:1,children:jsxDEV28(Text,{children},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function HR({color,...rest}){return jsxDEV28(Text,{color:color??"$border",wrap:"truncate",...rest,children:"─".repeat(200)},void 0,!1,void 0,this)}var ListContext=createContext8({level:0,ordered:!1});function UL({children}){let parent=useContext29(ListContext);return jsxDEV28(ListContext.Provider,{value:{level:parent.level+1,ordered:!1},children:jsxDEV28(Box,{flexDirection:"column",children},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function OL({children}){let parent=useContext29(ListContext),index=0,numbered=Children2.map(children,(child)=>{if(isValidElement2(child)&&child.type===LI)return index++,cloneElement2(child,{_index:index});return child});return jsxDEV28(ListContext.Provider,{value:{level:parent.level+1,ordered:!0},children:jsxDEV28(Box,{flexDirection:"column",children:numbered},void 0,!1,void 0,this)},void 0,!1,void 0,this)}var BULLETS=["•","◦","▸","-"];function LI({children,color,_index}){let{level,ordered}=useContext29(ListContext),effectiveLevel=Math.max(level,1),indent=" ".repeat(effectiveLevel-1),bullet=BULLETS[Math.min(effectiveLevel-1,BULLETS.length-1)],marker=ordered&&_index!=null?`${_index}. `:`${bullet} `;return jsxDEV28(Box,{children:[jsxDEV28(Text,{color:color??"$muted",children:[indent,marker]},void 0,!0,void 0,this),jsxDEV28(Box,{flexShrink:1,children:jsxDEV28(Text,{color,children},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as jsxDEV29}from"react/jsx-dev-runtime";var LEVEL_SCALES={1:2,2:1.5,3:1.25,4:1,5:0.9,6:0.8},LEVEL_COLORS={1:"$primary",2:"$accent",3:"$primary",4:void 0,5:void 0,6:"$muted"};function Heading({level=1,children,color,...rest}){let scale=LEVEL_SCALES[level],defaultColor=LEVEL_COLORS[level];return jsxDEV29(Text,{bold:!0,textSize:scale,color:color??defaultColor,...rest,children},void 0,!1,void 0,this)}import{jsxDEV as jsxDEV30}from"react/jsx-dev-runtime";function Form({onSubmit:_onSubmit,gap=1,children}){return jsxDEV30(Box,{flexDirection:"column",gap,children},void 0,!1,void 0,this)}function FormField({label,error,description,required,children}){return jsxDEV30(Box,{flexDirection:"column",children:[jsxDEV30(Text,{color:"$muted",bold:!0,children:[label,required&&jsxDEV30(Text,{color:"$error",children:" *"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),description&&jsxDEV30(Text,{color:"$disabledfg",children:description},void 0,!1,void 0,this),jsxDEV30(Box,{children},void 0,!1,void 0,this),error&&jsxDEV30(Text,{color:"$error",children:error},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{useCallback as useCallback23,useEffect as useEffect18,useRef as useRef19,useState as useState16}from"react";import{jsxDEV as jsxDEV31}from"react/jsx-dev-runtime";var DEFAULT_DURATION=3000,VARIANT_COLORS2={default:"$fg",success:"$success",error:"$error",warning:"$warning",info:"$info"},VARIANT_ICONS={default:"i",success:"+",error:"x",warning:"!",info:"i"},nextToastId=0;function useToast(){let[toasts,setToasts]=useState16([]),timersRef=useRef19(new Map),dismiss=useCallback23((id)=>{setToasts((prev)=>prev.filter((t)=>t.id!==id));let timer=timersRef.current.get(id);if(timer)clearTimeout(timer),timersRef.current.delete(id)},[]),dismissAll=useCallback23(()=>{setToasts([]);for(let timer of timersRef.current.values())clearTimeout(timer);timersRef.current.clear()},[]),toast=useCallback23((options)=>{let id=`toast-${++nextToastId}`,data={id,title:options.title,description:options.description,variant:options.variant??"default",duration:options.duration??DEFAULT_DURATION};if(setToasts((prev)=>[...prev,data]),data.duration>0){let timer=setTimeout(()=>{dismiss(id)},data.duration);timersRef.current.set(id,timer)}return id},[dismiss]);return useEffect18(()=>{let timers=timersRef.current;return()=>{for(let timer of timers.values())clearTimeout(timer);timers.clear()}},[]),{toast,toasts,dismiss,dismissAll}}function ToastItem({toast,...boxProps}){let color=VARIANT_COLORS2[toast.variant],icon=VARIANT_ICONS[toast.variant];return jsxDEV31(Box,{borderStyle:"single",borderColor:"$border",paddingX:1,backgroundColor:"$popover-bg",width:"snug-content",...boxProps,children:[jsxDEV31(Text,{color,bold:!0,children:["[",icon,"]"]},void 0,!0,void 0,this),jsxDEV31(Text,{children:[" ",toast.title]},void 0,!0,void 0,this),toast.description&&jsxDEV31(Text,{color:"$muted",children:[" ",toast.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function ToastContainer({toasts,maxVisible=5,...boxProps}){let visible=toasts.slice(-maxVisible);return jsxDEV31(Box,{flexDirection:"column",...boxProps,children:visible.map((t)=>jsxDEV31(ToastItem,{toast:t},t.id,!1,void 0,this))},void 0,!1,void 0,this)}import{useCallback as useCallback24,useMemo as useMemo13,useState as useState17}from"react";import{jsxDEV as jsxDEV32}from"react/jsx-dev-runtime";function fuzzyMatch(query,text){let lower=text.toLowerCase(),q=query.toLowerCase(),qi=0;for(let i=0;i<lower.length&&qi<q.length;i++)if(lower[i]===q[qi])qi++;return qi===q.length}function CommandPalette({commands,onSelect,onClose,placeholder="Search commands...",maxVisible=10,isActive=!0}){let[query,setQuery]=useState17(""),[selectedIndex,setSelectedIndex]=useState17(0),filtered=useMemo13(()=>{if(!query)return commands;return commands.filter((cmd)=>fuzzyMatch(query,cmd.name)||cmd.description&&fuzzyMatch(query,cmd.description))},[commands,query]),visible=filtered.slice(0,maxVisible),clampIndex=useCallback24((idx)=>Math.max(0,Math.min(idx,filtered.length-1)),[filtered.length]);return useInput((input,key)=>{if(key.upArrow){setSelectedIndex((prev)=>clampIndex(prev-1));return}if(key.downArrow){setSelectedIndex((prev)=>clampIndex(prev+1));return}if(key.return){let cmd=filtered[selectedIndex];if(cmd)onSelect?.(cmd);return}if(key.escape){onClose?.();return}if(key.backspace||key.delete){setQuery((prev)=>{let next=prev.slice(0,-1);return setSelectedIndex(0),next});return}if(input&&input>=" "&&!key.ctrl&&!key.meta)setQuery((prev)=>{return setSelectedIndex(0),prev+input})},{isActive}),jsxDEV32(Box,{flexDirection:"column",borderStyle:"single",borderColor:"$border",backgroundColor:"$popover-bg",paddingX:1,children:[jsxDEV32(Box,{children:[jsxDEV32(Text,{color:"$primary",bold:!0,children:[">"," "]},void 0,!0,void 0,this),jsxDEV32(Text,{children:query||jsxDEV32(Text,{color:"$disabledfg",children:placeholder},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jsxDEV32(Box,{children:jsxDEV32(Text,{color:"$border",children:"─".repeat(30)},void 0,!1,void 0,this)},void 0,!1,void 0,this),visible.length===0?jsxDEV32(Text,{color:"$disabledfg",children:"No matching commands"},void 0,!1,void 0,this):visible.map((cmd,i)=>{let isSelected=i===selectedIndex;return jsxDEV32(Box,{gap:1,children:[jsxDEV32(Text,{inverse:isSelected,color:isSelected?"$primary":"$fg",children:[isSelected?">":" "," ",cmd.name]},void 0,!0,void 0,this),cmd.description&&jsxDEV32(Text,{color:"$muted",children:cmd.description},void 0,!1,void 0,this),cmd.shortcut&&jsxDEV32(Text,{color:"$disabledfg",bold:!0,children:cmd.shortcut},void 0,!1,void 0,this)]},cmd.name,!0,void 0,this)}),filtered.length>maxVisible&&jsxDEV32(Text,{color:"$disabledfg",children:[filtered.length-maxVisible," more..."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}import{useCallback as useCallback25,useMemo as useMemo14,useRef as useRef20,useState as useState18}from"react";import{jsxDEV as jsxDEV33}from"react/jsx-dev-runtime";function flattenTree(nodes,expanded,depth=0){let result=[];for(let node of nodes)if(result.push({node,depth}),node.children?.length&&expanded.has(node.id))result.push(...flattenTree(node.children,expanded,depth+1));return result}function collectAllIds(nodes){let ids=new Set;for(let node of nodes)if(ids.add(node.id),node.children)for(let id of collectAllIds(node.children))ids.add(id);return ids}function TreeView({data,renderNode,expandedIds:controlledExpanded,onToggle,defaultExpanded=!1,isActive=!0,indent=2,height}){let isControlled=controlledExpanded!==void 0,[uncontrolledExpanded,setUncontrolledExpanded]=useState18(()=>defaultExpanded?collectAllIds(data):new Set),expanded=isControlled?controlledExpanded:uncontrolledExpanded,cursorRef=useRef20(0),flatItems=useMemo14(()=>flattenTree(data,expanded),[data,expanded]),toggleNode=useCallback25((nodeId)=>{let wasExpanded=expanded.has(nodeId);if(!isControlled)setUncontrolledExpanded((prev)=>{let next=new Set(prev);if(wasExpanded)next.delete(nodeId);else next.add(nodeId);return next});onToggle?.(nodeId,!wasExpanded)},[expanded,isControlled,onToggle]);useInput((_input,key)=>{if(flatItems.length===0)return;let cursor=Math.min(cursorRef.current,flatItems.length-1),item=flatItems[cursor];if(!item?.node.children?.length)return;if(key.rightArrow&&!expanded.has(item.node.id))toggleNode(item.node.id);else if(key.leftArrow&&expanded.has(item.node.id))toggleNode(item.node.id)},{isActive});let handleSelect=useCallback25((index)=>{let item=flatItems[index];if(item?.node.children?.length)toggleNode(item.node.id)},[flatItems,toggleNode]),handleCursor=useCallback25((index)=>{cursorRef.current=index},[]),getKey=useCallback25((item)=>item.node.id,[]),renderTreeItem=useCallback25((item,_index,meta)=>{let hasChildren=!!item.node.children?.length,isExpanded=expanded.has(item.node.id),prefix=hasChildren?isExpanded?"v ":"> ":" ",padding=" ".repeat(item.depth*indent);return jsxDEV33(Text,{inverse:meta.isCursor,children:[padding,jsxDEV33(Text,{color:hasChildren?"$primary":"$fg",children:prefix},void 0,!1,void 0,this),renderNode?renderNode(item.node,item.depth):jsxDEV33(Text,{children:item.node.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},[expanded,indent,renderNode]);if(flatItems.length===0)return jsxDEV33(Box,{children:jsxDEV33(Text,{color:"$disabledfg",children:"No items"},void 0,!1,void 0,this)},void 0,!1,void 0,this);return jsxDEV33(ListView,{items:flatItems,height:height??flatItems.length,nav:!0,active:isActive,onCursor:handleCursor,onSelect:handleSelect,renderItem:renderTreeItem,getKey,estimateHeight:1},void 0,!1,void 0,this)}import React19 from"react";import{jsxDEV as jsxDEV34}from"react/jsx-dev-runtime";function Breadcrumb({items,separator="/"}){if(items.length===0)return jsxDEV34(Box,{},void 0,!1,void 0,this);return jsxDEV34(Box,{children:items.map((item,i)=>{let isLast=i===items.length-1;return jsxDEV34(React19.Fragment,{children:[i>0&&jsxDEV34(Text,{color:"$disabledfg",children:[" ",separator," "]},void 0,!0,void 0,this),jsxDEV34(Text,{color:isLast?"$fg":"$muted",bold:isLast,children:item.label},void 0,!1,void 0,this)]},i,!0,void 0,this)})},void 0,!1,void 0,this)}import React20,{createContext as createContext9,useCallback as useCallback26,useContext as useContext30,useState as useState19}from"react";import{jsxDEV as jsxDEV35}from"react/jsx-dev-runtime";var TabsContext=createContext9({activeValue:"",setActiveValue:()=>{},tabValues:[],registerTab:()=>{}});function useTabsContext(){return useContext30(TabsContext)}function Tabs({defaultValue,value:controlledValue,onChange,isActive=!0,children}){let isControlled=controlledValue!==void 0,[uncontrolledValue,setUncontrolledValue]=useState19(defaultValue??""),[tabValues,setTabValues]=useState19([]),activeValue=isControlled?controlledValue:uncontrolledValue,setActiveValue=useCallback26((val)=>{if(!isControlled)setUncontrolledValue(val);onChange?.(val)},[isControlled,onChange]),registerTab=useCallback26((val)=>{setTabValues((prev)=>prev.includes(val)?prev:[...prev,val])},[]);return useInput((_input,key)=>{if(tabValues.length===0)return;let currentIdx=tabValues.indexOf(activeValue);if(currentIdx<0)return;if(key.rightArrow||_input==="l"){let next=(currentIdx+1)%tabValues.length;setActiveValue(tabValues[next]);return}if(key.leftArrow||_input==="h"){let next=(currentIdx-1+tabValues.length)%tabValues.length;setActiveValue(tabValues[next]);return}},{isActive}),jsxDEV35(TabsContext.Provider,{value:{activeValue,setActiveValue,tabValues,registerTab},children:jsxDEV35(Box,{flexDirection:"column",flexGrow:1,children},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function TabList({children}){return jsxDEV35(Box,{flexDirection:"row",gap:1,borderBottom:!0,borderColor:"$border",children},void 0,!1,void 0,this)}function Tab({value,children}){let{activeValue,setActiveValue,registerTab}=useTabsContext(),isActive=activeValue===value;return React20.useEffect(()=>{registerTab(value)},[value,registerTab]),jsxDEV35(Box,{onMouseDown:()=>setActiveValue(value),children:jsxDEV35(Text,{color:isActive?"$primary":"$muted",bold:isActive,underline:isActive,children},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function TabPanel({value,children}){let{activeValue}=useTabsContext();if(activeValue!==value)return null;return jsxDEV35(Box,{flexDirection:"column",flexGrow:1,children},void 0,!1,void 0,this)}import{jsxDEV as jsxDEV36}from"react/jsx-dev-runtime";function Tooltip({content,show=!1,children,...boxProps}){return jsxDEV36(Box,{flexDirection:"column",...boxProps,children:[children,show&&jsxDEV36(Box,{width:"snug-content",children:jsxDEV36(Text,{color:"$muted",dimColor:!0,children:content},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as jsxDEV37}from"react/jsx-dev-runtime";var DEFAULT_WIDTH3=20,DEFAULT_CHAR2="░";function Skeleton({width=DEFAULT_WIDTH3,height:heightProp,char=DEFAULT_CHAR2,shape}){let resolvedShape=shape??(heightProp&&heightProp>1?"block":"line"),height=heightProp??(resolvedShape==="circle"?1:1);if(resolvedShape==="circle"){let circleWidth=Math.min(width,6),pad=Math.max(0,Math.floor((width-circleWidth)/2));return jsxDEV37(Box,{children:jsxDEV37(Text,{color:"$muted",children:[" ".repeat(pad),char.repeat(circleWidth)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}let line=char.repeat(width),rows=Array.from({length:height},(_2,i)=>i);return jsxDEV37(Box,{flexDirection:"column",children:rows.map((i)=>jsxDEV37(Text,{color:"$muted",children:line},i,!1,void 0,this))},void 0,!1,void 0,this)}import{createContext as createContext10,useContext as useContext31,useMemo as useMemo15}from"react";import{createLogger as createLogger12}from"loggily";import{jsxDEV as jsxDEV38}from"react/jsx-dev-runtime";var log10=createLogger12("silvery:position-registry");function createPositionRegistry(){let sections=new Map;return{register(sectionIndex,itemIndex,rect){let sectionMap=sections.get(sectionIndex);if(!sectionMap)sectionMap=new Map,sections.set(sectionIndex,sectionMap);sectionMap.set(itemIndex,{rect}),log10.debug?.(`register sec=${sectionIndex} item=${itemIndex} y=${rect.y} h=${rect.height}`)},unregister(sectionIndex,itemIndex){let sectionMap=sections.get(sectionIndex);if(sectionMap){if(sectionMap.delete(itemIndex),sectionMap.size===0)sections.delete(sectionIndex);log10.debug?.(`unregister sec=${sectionIndex} item=${itemIndex}`)}},getPosition(sectionIndex,itemIndex){return sections.get(sectionIndex)?.get(itemIndex)?.rect},hasSection(sectionIndex){let sectionMap=sections.get(sectionIndex);return sectionMap!==void 0&&sectionMap.size>0},getItemCount(sectionIndex){return sections.get(sectionIndex)?.size??0},findItemAtY(sectionIndex,targetY){let sectionMap=sections.get(sectionIndex);if(!sectionMap||sectionMap.size===0)return-1;for(let[idx,entry]of sectionMap){let top=entry.rect.y,bottom=top+entry.rect.height;if(targetY>=top&&targetY<bottom)return idx}let closestIdx=-1,closestDist=1/0;for(let[idx,entry]of sectionMap){let mid=entry.rect.y+entry.rect.height/2,dist=Math.abs(mid-targetY);if(dist<closestDist)closestDist=dist,closestIdx=idx}let firstEntry=sectionMap.get(0);if(firstEntry&&targetY<firstEntry.rect.y)return-1;return closestIdx},findInsertionSlot(sectionIndex,targetY){let sectionMap=sections.get(sectionIndex);if(!sectionMap||sectionMap.size===0)return 0;let sorted=Array.from(sectionMap.entries()).sort((a,b)=>a[0]-b[0]);for(let i=0;i<sorted.length;i++){let entry=sorted[i];if(targetY<entry[1].rect.y)return i}return sorted.length},clear(){sections.clear(),log10.debug?.("cleared all positions")},dump(){let lines=[];if(sections.size===0)lines.push("(no items registered)");else for(let[secIdx,sectionMap]of sections){let entries=Array.from(sectionMap.entries()).sort((a,b)=>a[0]-b[0]).map(([idx,entry])=>`${idx}:y${entry.rect.y}:h${entry.rect.height}`).join(", ");lines.push(`sec[${secIdx}]: ${entries}`)}return lines.join(`
89
+ `+value2.slice(cursor2),cursor2+1);return}if(key.leftArrow&&key.shift){stickyXRef.current=null;let target=key.ctrl?findPrevWordStart(value2,cursor2):Math.max(0,cursor2-1);moveCursor3(target,value2,!0),yankStateRef.current=null;return}if(key.rightArrow&&key.shift){stickyXRef.current=null;let target=key.ctrl?findNextWordEnd(value2,cursor2):Math.min(value2.length,cursor2+1);moveCursor3(target,value2,!0),yankStateRef.current=null;return}if(key.upArrow&&key.shift){if(cRow>0){let targetX=stickyXRef.current??cCol;stickyXRef.current=targetX;let targetLine=lines[cRow-1];if(targetLine)moveCursor3(targetLine.startOffset+Math.min(targetX,targetLine.line.length),value2,!0)}yankStateRef.current=null;return}if(key.downArrow&&key.shift){if(cRow<lines.length-1){let targetX=stickyXRef.current??cCol;stickyXRef.current=targetX;let targetLine=lines[cRow+1];if(targetLine)moveCursor3(targetLine.startOffset+Math.min(targetX,targetLine.line.length),value2,!0)}yankStateRef.current=null;return}if(key.home&&key.shift){stickyXRef.current=null;let currentLine=lines[cRow];if(currentLine)moveCursor3(currentLine.startOffset,value2,!0);yankStateRef.current=null;return}if(key.end&&key.shift){stickyXRef.current=null;let currentLine=lines[cRow];if(currentLine)moveCursor3(currentLine.startOffset+currentLine.line.length,value2,!0);yankStateRef.current=null;return}if(key.upArrow){if(cRow>0){let targetX=stickyXRef.current??cCol;stickyXRef.current=targetX;let targetLine=lines[cRow-1];if(targetLine)moveCursor3(targetLine.startOffset+Math.min(targetX,targetLine.line.length),value2,!1)}else clearSelection();yankStateRef.current=null;return}if(key.downArrow){if(cRow<lines.length-1){let targetX=stickyXRef.current??cCol;stickyXRef.current=targetX;let targetLine=lines[cRow+1];if(targetLine)moveCursor3(targetLine.startOffset+Math.min(targetX,targetLine.line.length),value2,!1)}else clearSelection();yankStateRef.current=null;return}if(key.ctrl&&key.home){stickyXRef.current=null,moveCursor3(0,value2,!1),yankStateRef.current=null;return}if(key.ctrl&&key.end){stickyXRef.current=null,moveCursor3(value2.length,value2,!1),yankStateRef.current=null;return}if(key.home){stickyXRef.current=null;let currentLine=lines[cRow];if(currentLine)moveCursor3(currentLine.startOffset,value2,!1);yankStateRef.current=null;return}if(key.end||key.ctrl&&input==="e"){stickyXRef.current=null;let currentLine=lines[cRow];if(currentLine)moveCursor3(currentLine.startOffset+currentLine.line.length,value2,!1);yankStateRef.current=null;return}if(key.pageUp){stickyXRef.current=null;let targetLine=lines[Math.max(0,cRow-height)];if(targetLine)moveCursor3(targetLine.startOffset+Math.min(cCol,targetLine.line.length),value2,!1);yankStateRef.current=null;return}if(key.pageDown){stickyXRef.current=null;let targetLine=lines[Math.min(lines.length-1,cRow+height)];if(targetLine)moveCursor3(targetLine.startOffset+Math.min(cCol,targetLine.line.length),value2,!1);yankStateRef.current=null;return}if(key.ctrl&&input==="k"){stickyXRef.current=null,clearSelection();let currentLine=lines[cRow];if(!currentLine)return;let lineEnd=currentLine.startOffset+currentLine.line.length;if(cursor2<lineEnd)addToKillRing(value2.slice(cursor2,lineEnd)),updateValue(value2.slice(0,cursor2)+value2.slice(lineEnd),cursor2);else if(cursor2<value2.length)addToKillRing(value2.slice(cursor2,cursor2+1)),updateValue(value2.slice(0,cursor2)+value2.slice(cursor2+1),cursor2);return}if(key.ctrl&&input==="u"){stickyXRef.current=null,clearSelection();let currentLine=lines[cRow];if(!currentLine)return;let lineStart=currentLine.startOffset;if(cursor2>lineStart)addToKillRing(value2.slice(lineStart,cursor2)),updateValue(value2.slice(0,lineStart)+value2.slice(cursor2),lineStart);return}if((key.backspace||key.delete)&&hasSelection){stickyXRef.current=null;let del=deleteSelection();if(del)clearSelection(),updateValue(del.newValue,del.newCursor);yankStateRef.current=null;return}if(hasSelection&&input.length>=1&&input>=" "){stickyXRef.current=null,replaceSelectionWith(input),yankStateRef.current=null;return}let result=handleReadlineKey(input,key,value2,cursor2,yankStateRef.current);if(result){if(stickyXRef.current=null,clearSelection(),result.value===value2&&result.cursor===cursor2){yankStateRef.current=result.yankState;return}if(result.value!==value2){if(maxLength!==void 0&&result.value.length>maxLength&&result.value.length>value2.length){yankStateRef.current=result.yankState;return}if(stateRef.current.value=result.value,stateRef.current.cursor=result.cursor,!isControlled)setUncontrolledValue(result.value);setCursorAndScroll(result.cursor,result.value),onChange?.(result.value)}else setCursorAndScroll(result.cursor,value2);yankStateRef.current=result.yankState}},{isActive});let visibleCursorRow=cursorRow-scrollOffset,selection=selectionAnchor!==null&&selectionAnchor!==clampedCursor?{start:Math.min(selectionAnchor,clampedCursor),end:Math.max(selectionAnchor,clampedCursor)}:null,visibleLines=wrappedLines.slice(scrollOffset,scrollOffset+height),clear=useCallback17(()=>{updateValue("",0),setScrollOffset(0),setSelectionAnchor(null)},[updateValue]),setValue=useCallback17((v)=>{updateValue(v,v.length),setSelectionAnchor(null)},[updateValue]),setCursorFn=useCallback17((offset)=>{let clamped=Math.min(Math.max(0,offset),stateRef.current.value.length);setSelectionAnchor(null),selectionAnchorRef.current=null,setCursorAndScroll(clamped,stateRef.current.value)},[setCursorAndScroll]);return{value,cursor:clampedCursor,cursorRow,cursorCol,visibleCursorRow,scrollOffset,wrappedLines,visibleLines,selection,selectionAnchor,clear,setValue,getSelection:getSelectionRange,setCursor:setCursorFn}}import{jsxDEV as jsxDEV14}from"react/jsx-dev-runtime";var TextArea=forwardRef6(function({value:controlledValue,defaultValue="",onChange,onSubmit,submitKey="ctrl+enter",placeholder="",isActive:isActiveProp,height,cursorStyle:cursorStyle2="block",scrollMargin=1,disabled,maxLength,borderStyle:borderStyleProp,borderColor:borderColorProp="$border",focusBorderColor="$focusborder",testID},ref){let{focused}=useFocusable(),isActive=isActiveProp??(testID?focused:!0),{width:parentWidth}=useBoxRect(),contentWidth=borderStyleProp?Math.max(1,parentWidth-4):parentWidth,ta=useTextArea({value:controlledValue,defaultValue,onChange,onSubmit,submitKey,isActive,height,wrapWidth:contentWidth,scrollMargin,disabled,maxLength});useImperativeHandle5(ref,()=>({clear:ta.clear,getValue:()=>ta.value,setValue:ta.setValue,getSelection:ta.getSelection}));let wrappedLinesRef=useRef16(ta.wrappedLines);wrappedLinesRef.current=ta.wrappedLines;let scrollOffsetRef=useRef16(ta.scrollOffset);scrollOffsetRef.current=ta.scrollOffset;let handleMouseDown=useCallback18((e)=>{if(e.button!==0)return;let rect=e.currentTarget.scrollRect;if(!rect)return;let lines=wrappedLinesRef.current,scroll=scrollOffsetRef.current,row=e.clientY-rect.y+scroll,clampedRow=Math.min(Math.max(0,row),lines.length-1),wl=lines[clampedRow];if(!wl)return;let relativeX=e.clientX-rect.x,col=Math.min(Math.max(0,relativeX),wl.line.length),offset=Math.min(Math.max(0,wl.startOffset+col),ta.value.length);ta.setCursor(offset)},[ta]),showPlaceholder=!ta.value&&placeholder,borderProps=borderStyleProp?{borderStyle:borderStyleProp,borderColor:isActive?focusBorderColor:borderColorProp,paddingX:1}:{},borderColOffset=borderStyleProp?2:0,borderRowOffset=borderStyleProp?1:0;if(useCursor({col:ta.cursorCol+borderColOffset,row:ta.visibleCursorRow+borderRowOffset,visible:isActive&&!disabled&&!ta.selection}),showPlaceholder)return jsxDEV14(Box,{focusable:!0,testID,flexDirection:"column",height,...borderProps,children:jsxDEV14(Text,{dimColor:!0,children:placeholder},void 0,!1,void 0,this)},void 0,!1,void 0,this);return jsxDEV14(Box,{focusable:!0,testID,flexDirection:"column",height,...borderProps,onMouseDown:handleMouseDown,children:ta.visibleLines.map((wl,i)=>{let absoluteRow=ta.scrollOffset+i,isCursorRow=absoluteRow===ta.cursorRow,lineStart=wl.startOffset,lineEnd=lineStart+wl.line.length,hasSelectionOnLine=ta.selection&&lineStart<ta.selection.end&&lineEnd>ta.selection.start;if(disabled)return jsxDEV14(Text,{dimColor:!0,children:wl.line||" "},absoluteRow,!1,void 0,this);if(hasSelectionOnLine){let selStart=Math.max(0,ta.selection.start-lineStart),selEnd=Math.min(wl.line.length,ta.selection.end-lineStart),before=wl.line.slice(0,selStart),selected=wl.line.slice(selStart,selEnd),after=wl.line.slice(selEnd);return jsxDEV14(Text,{children:[before,jsxDEV14(Text,{inverse:!0,children:selected||(selEnd===wl.line.length&&isCursorRow?" ":"")},void 0,!1,void 0,this),after]},absoluteRow,!0,void 0,this)}if(!isCursorRow)return jsxDEV14(Text,{children:wl.line||" "},absoluteRow,!1,void 0,this);let beforeCursor=wl.line.slice(0,ta.cursorCol),atCursor=wl.line[ta.cursorCol]??" ",afterCursor=wl.line.slice(ta.cursorCol+1);return jsxDEV14(Text,{children:[beforeCursor,isActive?jsxDEV14(Text,{children:atCursor},void 0,!1,void 0,this):cursorStyle2==="block"?jsxDEV14(Text,{inverse:!0,children:atCursor},void 0,!1,void 0,this):jsxDEV14(Text,{underline:!0,children:atCursor},void 0,!1,void 0,this),afterCursor]},absoluteRow,!0,void 0,this)})},ta.scrollOffset,!1,void 0,this)});import{useCallback as useCallback19,useMemo as useMemo11,useRef as useRef17}from"react";import{jsxDEV as jsxDEV15}from"react/jsx-dev-runtime";function clampScroll2(cursorRow,currentScroll,viewportHeight){if(viewportHeight<=0)return 0;let scroll=currentScroll;if(cursorRow<scroll)scroll=cursorRow;if(cursorRow>=scroll+viewportHeight)scroll=cursorRow-viewportHeight+1;return Math.max(0,scroll)}function EditContextDisplay({value,cursor,height,wrapWidth,cursorStyle:cursorStyle2="block",placeholder="",showCursor=!0,onCursorClick}){let scrollRef=useRef17(0),effectiveWrapWidth=wrapWidth!=null&&wrapWidth>0?wrapWidth:1e4,clampedCursor=Math.min(Math.max(0,cursor),value.length),wrappedLines=useMemo11(()=>getWrappedLines(value,effectiveWrapWidth),[value,effectiveWrapWidth]),{row:cursorRow,col:cursorCol}=useMemo11(()=>cursorToRowCol(value,clampedCursor,effectiveWrapWidth),[value,clampedCursor,effectiveWrapWidth]),hasViewport=height!=null&&height>0;if(hasViewport)scrollRef.current=clampScroll2(cursorRow,scrollRef.current,height);if(!value&&placeholder){if(hasViewport)return jsxDEV15(Box,{flexDirection:"column",height,justifyContent:"center",alignItems:"center",children:jsxDEV15(Text,{dimColor:!0,children:placeholder},void 0,!1,void 0,this)},void 0,!1,void 0,this);return jsxDEV15(Box,{flexDirection:"column",children:jsxDEV15(Text,{dimColor:!0,children:placeholder},void 0,!1,void 0,this)},void 0,!1,void 0,this)}let currentScroll=hasViewport?scrollRef.current:0,visibleLines=hasViewport?wrappedLines.slice(currentScroll,currentScroll+height):wrappedLines,wrappedLinesRef=useRef17(wrappedLines);wrappedLinesRef.current=wrappedLines;let scrollRefForClick=scrollRef,handleMouseDown=useCallback19((e)=>{if(!onCursorClick||e.button!==0)return;let rect=e.currentTarget.scrollRect;if(!rect)return;let lines=wrappedLinesRef.current,scroll=scrollRefForClick.current,row=e.clientY-rect.y+scroll,clampedRow=Math.min(Math.max(0,row),lines.length-1),wl=lines[clampedRow];if(!wl)return;let relativeX=e.clientX-rect.x,col=Math.min(Math.max(0,relativeX),wl.line.length),offset=Math.min(Math.max(0,wl.startOffset+col),value.length);onCursorClick(offset)},[onCursorClick,value.length]);return jsxDEV15(Box,{flexDirection:"column",height:hasViewport?height:void 0,onMouseDown:onCursorClick?handleMouseDown:void 0,children:visibleLines.map((wl,i)=>{let absoluteRow=currentScroll+i;if(!(absoluteRow===cursorRow&&showCursor))return jsxDEV15(Text,{children:wl.line||" "},absoluteRow,!1,void 0,this);let beforeCursorText=wl.line.slice(0,cursorCol),atCursor=wl.line[cursorCol]??" ",afterCursorText=wl.line.slice(cursorCol+1);return jsxDEV15(Text,{children:[beforeCursorText,cursorStyle2==="block"?jsxDEV15(Text,{inverse:!0,children:atCursor},void 0,!1,void 0,this):jsxDEV15(Text,{underline:!0,children:atCursor},void 0,!1,void 0,this),afterCursorText]},absoluteRow,!0,void 0,this)})},currentScroll,!1,void 0,this)}import{useCallback as useCallback20}from"react";import{jsxDEV as jsxDEV16}from"react/jsx-dev-runtime";function CursorLine({beforeCursor,afterCursor,color,showCursor=!0,cursorStyle:cursorStyle2="block",onCursorClick}){let totalLength=beforeCursor.length+afterCursor.length,handleMouseDown=useCallback20((e)=>{if(!onCursorClick||e.button!==0)return;let rect=e.currentTarget.scrollRect;if(!rect)return;let relativeX=e.clientX-rect.x,offset=Math.min(Math.max(0,relativeX),totalLength);onCursorClick(offset)},[onCursorClick,totalLength]),textContent=(()=>{if(!showCursor)return jsxDEV16(Text,{color,children:[beforeCursor,afterCursor]},void 0,!0,void 0,this);let cursorChar=afterCursor[0]??" ",rest=afterCursor.slice(1);return jsxDEV16(Text,{color,children:[beforeCursor,cursorStyle2==="block"?jsxDEV16(Text,{inverse:!0,children:cursorChar},void 0,!1,void 0,this):jsxDEV16(Text,{underline:!0,children:cursorChar},void 0,!1,void 0,this),rest]},void 0,!0,void 0,this)})();if(onCursorClick)return jsxDEV16(Box,{onMouseDown:handleMouseDown,children:textContent},void 0,!1,void 0,this);return textContent}import{jsxDEV as jsxDEV17,Fragment as Fragment3}from"react/jsx-dev-runtime";function formatTitleWithHotkey(title,hotkey,color){let idx=title.toLowerCase().indexOf(hotkey.toLowerCase());if(idx>=0&&hotkey.length===1&&hotkey.toLowerCase()!==hotkey.toUpperCase()){let before=title.slice(0,idx),matched=title[idx],after=title.slice(idx+1);return jsxDEV17(Text,{color,bold:!0,children:[before,jsxDEV17(Text,{dimColor:!0,bold:!1,children:"["},void 0,!1,void 0,this),jsxDEV17(Text,{bold:!0,children:matched},void 0,!1,void 0,this),jsxDEV17(Text,{dimColor:!0,bold:!1,children:"]"},void 0,!1,void 0,this),after]},void 0,!0,void 0,this)}return jsxDEV17(Text,{color,bold:!0,children:[jsxDEV17(Text,{dimColor:!0,bold:!1,children:"["},void 0,!1,void 0,this),jsxDEV17(Text,{bold:!0,children:hotkey},void 0,!1,void 0,this),jsxDEV17(Text,{dimColor:!0,bold:!1,children:"]"},void 0,!1,void 0,this)," ",title]},void 0,!0,void 0,this)}function ModalDialog({borderColor="$border",title,titleColor,titleAlign="center",hotkey,titleRight,width,height,footer,footerAlign="center",onClose:_onClose,focusScope:_focusScope=!0,children,...boxProps}){let effectiveTitleColor=titleColor??"$primary";return jsxDEV17(Box,{flexDirection:"column",width:width??"snug-content",height,borderStyle:"double",borderColor,backgroundColor:"$popover-bg",paddingX:2,paddingY:1,userSelect:"contain",...boxProps,children:[title&&jsxDEV17(Box,{flexShrink:0,flexDirection:"column",children:[jsxDEV17(Box,{justifyContent:titleRight?"space-between":titleAlign,children:[hotkey?formatTitleWithHotkey(title,hotkey,effectiveTitleColor):jsxDEV17(Text,{color:effectiveTitleColor,bold:!0,children:title},void 0,!1,void 0,this),titleRight]},void 0,!0,void 0,this),jsxDEV17(Text,{children:" "},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jsxDEV17(Box,{flexDirection:"column",flexGrow:1,overflow:"hidden",children},void 0,!1,void 0,this),footer&&jsxDEV17(Fragment3,{children:[jsxDEV17(Text,{children:" "},void 0,!1,void 0,this),jsxDEV17(Box,{justifyContent:footerAlign,children:typeof footer==="string"?jsxDEV17(Text,{dimColor:!0,children:footer},void 0,!1,void 0,this):footer},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}import{useCallback as useCallback21,useRef as useRef18,useState as useState12}from"react";import{jsxDEV as jsxDEV18}from"react/jsx-dev-runtime";function PickerList({items,selectedIndex,renderItem,getKey,emptyMessage="No items",maxVisible=10}){if(items.length===0)return jsxDEV18(Box,{flexDirection:"column",flexGrow:1,flexShrink:1,overflow:"hidden",children:jsxDEV18(Text,{dimColor:!0,children:emptyMessage},void 0,!1,void 0,this)},void 0,!1,void 0,this);let clampedIndex=Math.min(selectedIndex,items.length-1),effectiveHeight=Math.min(maxVisible,items.length);return jsxDEV18(Box,{flexDirection:"column",flexGrow:1,flexShrink:1,overflow:"hidden",children:jsxDEV18(ListView,{items,height:effectiveHeight,nav:!0,active:!1,cursorKey:clampedIndex,getKey:(item)=>getKey(item),renderItem:(item,_index,meta)=>renderItem(item,meta.isCursor)},void 0,!1,void 0,this)},void 0,!1,void 0,this)}import{jsxDEV as jsxDEV19}from"react/jsx-dev-runtime";function PickerDialog({title,placeholder,items,renderItem,getKey,onSelect,onCancel,onChange,initialValue="",emptyMessage="No items",maxVisible=10,width,height,footer,prompt,promptColor,isActive=!0}){let[selectedIndex,setSelectedIndex]=useState12(0),onSelectRef=useRef18(onSelect);onSelectRef.current=onSelect;let onCancelRef=useRef18(onCancel);onCancelRef.current=onCancel;let itemsRef=useRef18(items);itemsRef.current=items;let selectedIndexRef=useRef18(selectedIndex);selectedIndexRef.current=selectedIndex;let readline=useReadline({initialValue,onChange:useCallback21((value)=>{onChange?.(value),setSelectedIndex(0)},[onChange]),isActive,handleEnter:!1,handleEscape:!1,handleVerticalArrows:!1}),clampedIndex=items.length>0?Math.min(selectedIndex,items.length-1):0;if(clampedIndex!==selectedIndex)setSelectedIndex(clampedIndex);let effectiveMaxVisible=Math.min(maxVisible,items.length);useInput((_input,key)=>{if(key.escape){onCancelRef.current();return}if(key.return){let currentItems=itemsRef.current,idx=selectedIndexRef.current,item=currentItems[Math.min(idx,currentItems.length-1)];if(item)onSelectRef.current(item);return}if(key.upArrow){setSelectedIndex((i)=>Math.max(0,i-1));return}if(key.downArrow){setSelectedIndex((i)=>Math.min(i+1,Math.max(0,itemsRef.current.length-1)));return}if(key.pageUp){setSelectedIndex((i)=>Math.max(0,i-effectiveMaxVisible));return}if(key.pageDown){setSelectedIndex((i)=>Math.min(i+effectiveMaxVisible,Math.max(0,itemsRef.current.length-1)));return}},{isActive});let showPlaceholder=!readline.value&&placeholder;return jsxDEV19(ModalDialog,{title,width,height,footer,children:[jsxDEV19(Box,{flexShrink:0,flexDirection:"column",children:[jsxDEV19(Box,{children:[prompt&&jsxDEV19(Text,{color:promptColor,children:prompt},void 0,!1,void 0,this),showPlaceholder?jsxDEV19(Text,{dimColor:!0,children:placeholder},void 0,!1,void 0,this):jsxDEV19(CursorLine,{beforeCursor:readline.beforeCursor,afterCursor:readline.afterCursor,showCursor:isActive},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jsxDEV19(Text,{dimColor:!0,children:"─".repeat(40)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jsxDEV19(PickerList,{items,selectedIndex:clampedIndex,renderItem,getKey,emptyMessage,maxVisible},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as jsxDEV20}from"react/jsx-dev-runtime";function Toggle({value,onChange,label,isActive,...rest}){let{focused}=useFocusable(),active=isActive??focused;return useInput((_input,key)=>{if(_input===" "&&!key.ctrl&&!key.meta&&!key.shift)onChange(!value)},{isActive:active}),jsxDEV20(Box,{focusable:!0,...rest,children:[jsxDEV20(Text,{inverse:active,children:value?"[x]":"[ ]"},void 0,!1,void 0,this),label&&jsxDEV20(Text,{children:[" ",label]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as jsxDEV21}from"react/jsx-dev-runtime";function Button({label,onPress,isActive,color,...rest}){let{focused}=useFocusable(),active=isActive??focused;return useInput((_input,key)=>{if(key.return||_input===" "&&!key.ctrl&&!key.meta&&!key.shift)onPress()},{isActive:active}),jsxDEV21(Box,{focusable:!0,...rest,children:jsxDEV21(Text,{color,inverse:active,children:["[ ",label," ]"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}import React11 from"react";function SearchBar(){let{isActive,query,matches,currentMatch}=useSearch();if(!isActive)return null;let matchInfo=matches.length>0?`[${currentMatch+1}/${matches.length}]`:query?"[no matches]":"";return React11.createElement(Box,{flexDirection:"row"},React11.createElement(Text,{inverse:!0},` / ${query} ${matchInfo} `))}import{useEffect as useEffect16,useState as useState13}from"react";import{jsxDEV as jsxDEV22}from"react/jsx-dev-runtime";var FRAMES={dots:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],line:["|","/","—","\\"],arc:["◜","◠","◝","◞","◡","◟"],bounce:["⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"]};function Spinner({type="dots",label,interval=80,...rest}){let[frameIndex,setFrameIndex]=useState13(0),frames=FRAMES[type];useEffect16(()=>{let timer=setInterval(()=>{setFrameIndex((prev)=>(prev+1)%frames.length)},interval);return()=>clearInterval(timer)},[frames.length,interval]);let frame=frames[frameIndex%frames.length];return jsxDEV22(Text,{...rest,children:[frame,label?` ${label}`:""]},void 0,!0,void 0,this)}import{useEffect as useEffect17,useState as useState14}from"react";import{jsxDEV as jsxDEV23}from"react/jsx-dev-runtime";var DEFAULT_FILL="█",DEFAULT_EMPTY="░",DEFAULT_WIDTH=30,INDETERMINATE_BLOCK_SIZE=4,INDETERMINATE_INTERVAL=100;function ProgressBar({value,width:widthProp,fillChar=DEFAULT_FILL,emptyChar=DEFAULT_EMPTY,showPercentage,label,color}){let layoutRect=useBoxRect(),contentWidth=widthProp?0:layoutRect.width,[bouncePos,setBouncePos]=useState14(0),[bounceDir,setBounceDir]=useState14(1),isDeterminate=value!==void 0,showPct=showPercentage??isDeterminate,labelWidth=label?label.length+1:0,pctWidth=showPct?5:0,availableWidth=widthProp??(contentWidth>0?contentWidth:DEFAULT_WIDTH),barWidth=Math.max(1,availableWidth-labelWidth-pctWidth);useEffect17(()=>{if(isDeterminate)return;let timer=setInterval(()=>{setBouncePos((prev)=>{let maxPos=barWidth-INDETERMINATE_BLOCK_SIZE;if(maxPos<=0)return 0;let next=prev+bounceDir;if(next>=maxPos)return setBounceDir(-1),maxPos;if(next<=0)return setBounceDir(1),0;return next})},INDETERMINATE_INTERVAL);return()=>clearInterval(timer)},[isDeterminate,barWidth,bounceDir]);let filledPart,emptyPart;if(isDeterminate){let clamped=Math.max(0,Math.min(1,value)),filled=Math.round(clamped*barWidth);filledPart=fillChar.repeat(filled),emptyPart=emptyChar.repeat(barWidth-filled)}else{let blockSize=Math.min(INDETERMINATE_BLOCK_SIZE,barWidth),pos=Math.max(0,Math.min(bouncePos,barWidth-blockSize));filledPart=emptyChar.repeat(pos)+fillChar.repeat(blockSize),emptyPart=emptyChar.repeat(barWidth-pos-blockSize)}let pct=isDeterminate?Math.round(Math.max(0,Math.min(1,value))*100):0;return jsxDEV23(Box,{children:[label&&jsxDEV23(Text,{children:[label," "]},void 0,!0,void 0,this),jsxDEV23(Text,{color,children:filledPart},void 0,!1,void 0,this),jsxDEV23(Text,{dimColor:!0,children:emptyPart},void 0,!1,void 0,this),showPct&&jsxDEV23(Text,{children:[String(pct).padStart(4),"%"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}import{useCallback as useCallback22,useState as useState15}from"react";import{jsxDEV as jsxDEV24}from"react/jsx-dev-runtime";function findNextEnabled(items,current,direction){let len=items.length;if(len===0)return current;let next=current+direction;for(let i=0;i<len;i++){if(next<0)next=len-1;if(next>=len)next=0;if(!items[next].disabled)return next;next+=direction}return current}function findFirstEnabled(items){for(let i=0;i<items.length;i++)if(!items[i].disabled)return i;return 0}function SelectList({items,highlightedIndex:controlledIndex,onHighlight,onSelect,initialIndex,maxVisible,isActive=!0,indicator="▸ "}){let isControlled=controlledIndex!==void 0,[uncontrolledIndex,setUncontrolledIndex]=useState15(initialIndex??findFirstEnabled(items)),currentIndex=isControlled?controlledIndex:uncontrolledIndex,setIndex=useCallback22((index)=>{if(!isControlled)setUncontrolledIndex(index);onHighlight?.(index)},[isControlled,onHighlight]),handleCursor=useCallback22((nextIndex)=>{if(items[nextIndex]?.disabled){let direction=nextIndex>=currentIndex?1:-1;setIndex(findNextEnabled(items,currentIndex,direction))}else setIndex(nextIndex)},[items,currentIndex,setIndex]),handleSelect=useCallback22((index)=>{let item=items[index];if(item&&!item.disabled)onSelect?.(item,index)},[items,onSelect]),renderItem=useCallback22((item,_index,meta)=>jsxDEV24(Text,{inverse:meta.isCursor,dimColor:item.disabled,children:[indicator?meta.isCursor?indicator:" ".repeat(indicator.length):"",item.label]},item.value,!0,void 0,this),[indicator]);return jsxDEV24(ListView,{items,height:maxVisible??items.length,estimateHeight:1,nav:!0,cursorKey:currentIndex,onCursor:handleCursor,onSelect:handleSelect,active:isActive,getKey:(item)=>item.value,renderItem},void 0,!1,void 0,this)}import{useMemo as useMemo12}from"react";import{jsxDEV as jsxDEV25}from"react/jsx-dev-runtime";function computeWidths(columns,data,padding){return columns.map((col)=>{if(col.width)return col.width;if(col.grow)return 0;let cellValues=data.map((item,i)=>{if(col.render){let rendered=col.render(item,i);return typeof rendered==="string"?rendered:""}return String((col.key?item[col.key]:"")??"")});return Math.max(col.header.length,...cellValues.map((v)=>v.length))+padding})}function Table({data,columns,headerColor="$primary",showHeader=!0,padding=2}){let widths=useMemo12(()=>computeWidths(columns,data,padding),[columns,data,padding]),renderCell=(col,item,index,width)=>{let rendered=col.render?col.render(item,index):null,content=rendered!=null?typeof rendered==="string"?jsxDEV25(Text,{children:rendered},void 0,!1,void 0,this):rendered:jsxDEV25(Text,{children:String((col.key?item[col.key]:"")??"")},void 0,!1,void 0,this);return col.grow?jsxDEV25(Box,{flexGrow:1,justifyContent:col.align==="right"?"flex-end":void 0,children:content},col.header,!1,void 0,this):jsxDEV25(Box,{width,justifyContent:col.align==="right"?"flex-end":void 0,children:content},col.header,!1,void 0,this)},renderRow=(item,index)=>jsxDEV25(Box,{children:columns.map((col,colIndex)=>renderCell(col,item,index,widths[colIndex]))},void 0,!1,void 0,this),viewportHeight=Math.max(data.length,1);return jsxDEV25(Box,{flexDirection:"column",children:[showHeader&&jsxDEV25(Box,{children:columns.map((col,i)=>col.grow?jsxDEV25(Box,{flexGrow:1,children:jsxDEV25(Text,{bold:!0,color:headerColor,children:col.header},void 0,!1,void 0,this)},col.header,!1,void 0,this):jsxDEV25(Box,{width:widths[i],children:jsxDEV25(Text,{bold:!0,color:headerColor,children:col.header},void 0,!1,void 0,this)},col.header,!1,void 0,this))},void 0,!1,void 0,this),data.length>0&&jsxDEV25(ListView,{items:data,height:viewportHeight,estimateHeight:1,renderItem:renderRow},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as jsxDEV26}from"react/jsx-dev-runtime";var VARIANT_COLORS={default:"$fg",primary:"$primary",success:"$success",warning:"$warning",error:"$error"};function Badge({label,variant="default",color,...rest}){let resolvedColor=color??VARIANT_COLORS[variant];return jsxDEV26(Text,{color:resolvedColor,bold:!0,...rest,children:[" ",label," "]},void 0,!0,void 0,this)}import{jsxDEV as jsxDEV27}from"react/jsx-dev-runtime";var DEFAULT_CHAR="─",DEFAULT_WIDTH2=40;function Divider({char=DEFAULT_CHAR,title,width:widthProp}){let{width:contentWidth}=useBoxRect(),totalWidth=widthProp??(contentWidth>0?contentWidth:DEFAULT_WIDTH2);if(!title)return jsxDEV27(Box,{children:jsxDEV27(Text,{dimColor:!0,children:char.repeat(totalWidth)},void 0,!1,void 0,this)},void 0,!1,void 0,this);let titleWithPad=` ${title} `,remaining=Math.max(0,totalWidth-titleWithPad.length),leftLen=Math.floor(remaining/2),rightLen=remaining-leftLen;return jsxDEV27(Box,{children:[jsxDEV27(Text,{dimColor:!0,children:char.repeat(leftLen)},void 0,!1,void 0,this),jsxDEV27(Text,{bold:!0,children:titleWithPad},void 0,!1,void 0,this),jsxDEV27(Text,{dimColor:!0,children:char.repeat(rightLen)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{createContext as createContext8,useContext as useContext29,Children as Children2,cloneElement as cloneElement2,isValidElement as isValidElement2}from"react";import{jsxDEV as jsxDEV28}from"react/jsx-dev-runtime";function H1({children,color,...rest}){return jsxDEV28(Text,{bold:!0,color:color??"$primary",...rest,children},void 0,!1,void 0,this)}function H2({children,color,...rest}){return jsxDEV28(Text,{bold:!0,color:color??"$accent",...rest,children},void 0,!1,void 0,this)}function H3({children,color,...rest}){return jsxDEV28(Text,{color:color??"$primary",...rest,children},void 0,!1,void 0,this)}function P({children,color,...rest}){return jsxDEV28(Text,{color,...rest,children},void 0,!1,void 0,this)}function Lead({children,color,...rest}){return jsxDEV28(Text,{italic:!0,color:color??"$muted",...rest,children},void 0,!1,void 0,this)}function Muted({children,color,...rest}){return jsxDEV28(Text,{color:color??"$muted",...rest,children},void 0,!1,void 0,this)}function Small({children,color,...rest}){return jsxDEV28(Text,{dimColor:!0,color:color??"$muted",...rest,children},void 0,!1,void 0,this)}function Strong({children,color,...rest}){return jsxDEV28(Text,{bold:!0,color,...rest,children},void 0,!1,void 0,this)}function Em({children,color,...rest}){return jsxDEV28(Text,{italic:!0,color,...rest,children},void 0,!1,void 0,this)}function Code({children,color,...rest}){return jsxDEV28(Text,{backgroundColor:"$mutedbg",color,...rest,children:` ${children} `},void 0,!1,void 0,this)}function Kbd({children,color,...rest}){return jsxDEV28(Text,{backgroundColor:"$mutedbg",bold:!0,color,...rest,children:` ${children} `},void 0,!1,void 0,this)}function Blockquote({children,color}){return jsxDEV28(Box,{children:[jsxDEV28(Text,{color:color??"$muted",children:"│ "},void 0,!1,void 0,this),jsxDEV28(Box,{flexShrink:1,children:jsxDEV28(Text,{italic:!0,children},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function CodeBlock({children,color}){return jsxDEV28(Box,{children:[jsxDEV28(Text,{color:color??"$border",children:"│ "},void 0,!1,void 0,this),jsxDEV28(Box,{flexShrink:1,children:jsxDEV28(Text,{children},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function HR({color,...rest}){return jsxDEV28(Text,{color:color??"$border",wrap:"truncate",...rest,children:"─".repeat(200)},void 0,!1,void 0,this)}var ListContext=createContext8({level:0,ordered:!1});function UL({children}){let parent=useContext29(ListContext);return jsxDEV28(ListContext.Provider,{value:{level:parent.level+1,ordered:!1},children:jsxDEV28(Box,{flexDirection:"column",children},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function OL({children}){let parent=useContext29(ListContext),index=0,numbered=Children2.map(children,(child)=>{if(isValidElement2(child)&&child.type===LI)return index++,cloneElement2(child,{_index:index});return child});return jsxDEV28(ListContext.Provider,{value:{level:parent.level+1,ordered:!0},children:jsxDEV28(Box,{flexDirection:"column",children:numbered},void 0,!1,void 0,this)},void 0,!1,void 0,this)}var BULLETS=["•","◦","▸","-"];function LI({children,color,_index}){let{level,ordered}=useContext29(ListContext),effectiveLevel=Math.max(level,1),indent=" ".repeat(effectiveLevel-1),bullet=BULLETS[Math.min(effectiveLevel-1,BULLETS.length-1)],marker=ordered&&_index!=null?`${_index}. `:`${bullet} `;return jsxDEV28(Box,{children:[jsxDEV28(Text,{color:color??"$muted",children:[indent,marker]},void 0,!0,void 0,this),jsxDEV28(Box,{flexShrink:1,children:jsxDEV28(Text,{color,children},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as jsxDEV29}from"react/jsx-dev-runtime";var LEVEL_SCALES={1:2,2:1.5,3:1.25,4:1,5:0.9,6:0.8},LEVEL_COLORS={1:"$primary",2:"$accent",3:"$primary",4:void 0,5:void 0,6:"$muted"};function Heading({level=1,children,color,...rest}){let scale=LEVEL_SCALES[level],defaultColor=LEVEL_COLORS[level];return jsxDEV29(Text,{bold:!0,textSize:scale,color:color??defaultColor,...rest,children},void 0,!1,void 0,this)}import{jsxDEV as jsxDEV30}from"react/jsx-dev-runtime";function Form({onSubmit:_onSubmit,gap=1,children}){return jsxDEV30(Box,{flexDirection:"column",gap,children},void 0,!1,void 0,this)}function FormField({label,error,description,required,children}){return jsxDEV30(Box,{flexDirection:"column",children:[jsxDEV30(Text,{color:"$muted",bold:!0,children:[label,required&&jsxDEV30(Text,{color:"$error",children:" *"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),description&&jsxDEV30(Text,{color:"$disabledfg",children:description},void 0,!1,void 0,this),jsxDEV30(Box,{children},void 0,!1,void 0,this),error&&jsxDEV30(Text,{color:"$error",children:error},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{useCallback as useCallback23,useEffect as useEffect18,useRef as useRef19,useState as useState16}from"react";import{jsxDEV as jsxDEV31}from"react/jsx-dev-runtime";var DEFAULT_DURATION=3000,VARIANT_COLORS2={default:"$fg",success:"$success",error:"$error",warning:"$warning",info:"$info"},VARIANT_ICONS={default:"i",success:"+",error:"x",warning:"!",info:"i"},nextToastId=0;function useToast(){let[toasts,setToasts]=useState16([]),timersRef=useRef19(new Map),dismiss=useCallback23((id)=>{setToasts((prev)=>prev.filter((t)=>t.id!==id));let timer=timersRef.current.get(id);if(timer)clearTimeout(timer),timersRef.current.delete(id)},[]),dismissAll=useCallback23(()=>{setToasts([]);for(let timer of timersRef.current.values())clearTimeout(timer);timersRef.current.clear()},[]),toast=useCallback23((options)=>{let id=`toast-${++nextToastId}`,data={id,title:options.title,description:options.description,variant:options.variant??"default",duration:options.duration??DEFAULT_DURATION};if(setToasts((prev)=>[...prev,data]),data.duration>0){let timer=setTimeout(()=>{dismiss(id)},data.duration);timersRef.current.set(id,timer)}return id},[dismiss]);return useEffect18(()=>{let timers=timersRef.current;return()=>{for(let timer of timers.values())clearTimeout(timer);timers.clear()}},[]),{toast,toasts,dismiss,dismissAll}}function ToastItem({toast,...boxProps}){let color=VARIANT_COLORS2[toast.variant],icon=VARIANT_ICONS[toast.variant];return jsxDEV31(Box,{borderStyle:"single",borderColor:"$border",paddingX:1,backgroundColor:"$popover-bg",width:"snug-content",...boxProps,children:[jsxDEV31(Text,{color,bold:!0,children:["[",icon,"]"]},void 0,!0,void 0,this),jsxDEV31(Text,{children:[" ",toast.title]},void 0,!0,void 0,this),toast.description&&jsxDEV31(Text,{color:"$muted",children:[" ",toast.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function ToastContainer({toasts,maxVisible=5,...boxProps}){let visible=toasts.slice(-maxVisible);return jsxDEV31(Box,{flexDirection:"column",...boxProps,children:visible.map((t)=>jsxDEV31(ToastItem,{toast:t},t.id,!1,void 0,this))},void 0,!1,void 0,this)}import{useCallback as useCallback24,useMemo as useMemo13,useState as useState17}from"react";import{jsxDEV as jsxDEV32}from"react/jsx-dev-runtime";function fuzzyMatch(query,text){let lower=text.toLowerCase(),q=query.toLowerCase(),qi=0;for(let i=0;i<lower.length&&qi<q.length;i++)if(lower[i]===q[qi])qi++;return qi===q.length}function CommandPalette({commands,onSelect,onClose,placeholder="Search commands...",maxVisible=10,isActive=!0}){let[query,setQuery]=useState17(""),[selectedIndex,setSelectedIndex]=useState17(0),filtered=useMemo13(()=>{if(!query)return commands;return commands.filter((cmd)=>fuzzyMatch(query,cmd.name)||cmd.description&&fuzzyMatch(query,cmd.description))},[commands,query]),visible=filtered.slice(0,maxVisible),clampIndex=useCallback24((idx)=>Math.max(0,Math.min(idx,filtered.length-1)),[filtered.length]);return useInput((input,key)=>{if(key.upArrow){setSelectedIndex((prev)=>clampIndex(prev-1));return}if(key.downArrow){setSelectedIndex((prev)=>clampIndex(prev+1));return}if(key.return){let cmd=filtered[selectedIndex];if(cmd)onSelect?.(cmd);return}if(key.escape){onClose?.();return}if(key.backspace||key.delete){setQuery((prev)=>{let next=prev.slice(0,-1);return setSelectedIndex(0),next});return}if(input&&input>=" "&&!key.ctrl&&!key.meta)setQuery((prev)=>{return setSelectedIndex(0),prev+input})},{isActive}),jsxDEV32(Box,{flexDirection:"column",borderStyle:"single",borderColor:"$border",backgroundColor:"$popover-bg",paddingX:1,children:[jsxDEV32(Box,{children:[jsxDEV32(Text,{color:"$primary",bold:!0,children:[">"," "]},void 0,!0,void 0,this),jsxDEV32(Text,{children:query||jsxDEV32(Text,{color:"$disabledfg",children:placeholder},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jsxDEV32(Box,{children:jsxDEV32(Text,{color:"$border",children:"─".repeat(30)},void 0,!1,void 0,this)},void 0,!1,void 0,this),visible.length===0?jsxDEV32(Text,{color:"$disabledfg",children:"No matching commands"},void 0,!1,void 0,this):visible.map((cmd,i)=>{let isSelected=i===selectedIndex;return jsxDEV32(Box,{gap:1,children:[jsxDEV32(Text,{inverse:isSelected,color:isSelected?"$primary":"$fg",children:[isSelected?">":" "," ",cmd.name]},void 0,!0,void 0,this),cmd.description&&jsxDEV32(Text,{color:"$muted",children:cmd.description},void 0,!1,void 0,this),cmd.shortcut&&jsxDEV32(Text,{color:"$disabledfg",bold:!0,children:cmd.shortcut},void 0,!1,void 0,this)]},cmd.name,!0,void 0,this)}),filtered.length>maxVisible&&jsxDEV32(Text,{color:"$disabledfg",children:[filtered.length-maxVisible," more..."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}import{useCallback as useCallback25,useMemo as useMemo14,useRef as useRef20,useState as useState18}from"react";import{jsxDEV as jsxDEV33}from"react/jsx-dev-runtime";function flattenTree(nodes,expanded,depth=0){let result=[];for(let node of nodes)if(result.push({node,depth}),node.children?.length&&expanded.has(node.id))result.push(...flattenTree(node.children,expanded,depth+1));return result}function collectAllIds(nodes){let ids=new Set;for(let node of nodes)if(ids.add(node.id),node.children)for(let id of collectAllIds(node.children))ids.add(id);return ids}function TreeView({data,renderNode,expandedIds:controlledExpanded,onToggle,defaultExpanded=!1,isActive=!0,indent=2,height}){let isControlled=controlledExpanded!==void 0,[uncontrolledExpanded,setUncontrolledExpanded]=useState18(()=>defaultExpanded?collectAllIds(data):new Set),expanded=isControlled?controlledExpanded:uncontrolledExpanded,cursorRef=useRef20(0),flatItems=useMemo14(()=>flattenTree(data,expanded),[data,expanded]),toggleNode=useCallback25((nodeId)=>{let wasExpanded=expanded.has(nodeId);if(!isControlled)setUncontrolledExpanded((prev)=>{let next=new Set(prev);if(wasExpanded)next.delete(nodeId);else next.add(nodeId);return next});onToggle?.(nodeId,!wasExpanded)},[expanded,isControlled,onToggle]);useInput((_input,key)=>{if(flatItems.length===0)return;let cursor=Math.min(cursorRef.current,flatItems.length-1),item=flatItems[cursor];if(!item?.node.children?.length)return;if(key.rightArrow&&!expanded.has(item.node.id))toggleNode(item.node.id);else if(key.leftArrow&&expanded.has(item.node.id))toggleNode(item.node.id)},{isActive});let handleSelect=useCallback25((index)=>{let item=flatItems[index];if(item?.node.children?.length)toggleNode(item.node.id)},[flatItems,toggleNode]),handleCursor=useCallback25((index)=>{cursorRef.current=index},[]),getKey=useCallback25((item)=>item.node.id,[]),renderTreeItem=useCallback25((item,_index,meta)=>{let hasChildren=!!item.node.children?.length,isExpanded=expanded.has(item.node.id),prefix=hasChildren?isExpanded?"v ":"> ":" ",padding=" ".repeat(item.depth*indent);return jsxDEV33(Text,{inverse:meta.isCursor,children:[padding,jsxDEV33(Text,{color:hasChildren?"$primary":"$fg",children:prefix},void 0,!1,void 0,this),renderNode?renderNode(item.node,item.depth):jsxDEV33(Text,{children:item.node.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},[expanded,indent,renderNode]);if(flatItems.length===0)return jsxDEV33(Box,{children:jsxDEV33(Text,{color:"$disabledfg",children:"No items"},void 0,!1,void 0,this)},void 0,!1,void 0,this);return jsxDEV33(ListView,{items:flatItems,height:height??flatItems.length,nav:!0,active:isActive,onCursor:handleCursor,onSelect:handleSelect,renderItem:renderTreeItem,getKey,estimateHeight:1},void 0,!1,void 0,this)}import React19 from"react";import{jsxDEV as jsxDEV34}from"react/jsx-dev-runtime";function Breadcrumb({items,separator="/"}){if(items.length===0)return jsxDEV34(Box,{},void 0,!1,void 0,this);return jsxDEV34(Box,{children:items.map((item,i)=>{let isLast=i===items.length-1;return jsxDEV34(React19.Fragment,{children:[i>0&&jsxDEV34(Text,{color:"$disabledfg",children:[" ",separator," "]},void 0,!0,void 0,this),jsxDEV34(Text,{color:isLast?"$fg":"$muted",bold:isLast,children:item.label},void 0,!1,void 0,this)]},i,!0,void 0,this)})},void 0,!1,void 0,this)}import React20,{createContext as createContext9,useCallback as useCallback26,useContext as useContext30,useState as useState19}from"react";import{jsxDEV as jsxDEV35}from"react/jsx-dev-runtime";var TabsContext=createContext9({activeValue:"",setActiveValue:()=>{},tabValues:[],registerTab:()=>{}});function useTabsContext(){return useContext30(TabsContext)}function Tabs({defaultValue,value:controlledValue,onChange,isActive=!0,children}){let isControlled=controlledValue!==void 0,[uncontrolledValue,setUncontrolledValue]=useState19(defaultValue??""),[tabValues,setTabValues]=useState19([]),activeValue=isControlled?controlledValue:uncontrolledValue,setActiveValue=useCallback26((val)=>{if(!isControlled)setUncontrolledValue(val);onChange?.(val)},[isControlled,onChange]),registerTab=useCallback26((val)=>{setTabValues((prev)=>prev.includes(val)?prev:[...prev,val])},[]);return useInput((_input,key)=>{if(tabValues.length===0)return;let currentIdx=tabValues.indexOf(activeValue);if(currentIdx<0)return;if(key.rightArrow||_input==="l"){let next=(currentIdx+1)%tabValues.length;setActiveValue(tabValues[next]);return}if(key.leftArrow||_input==="h"){let next=(currentIdx-1+tabValues.length)%tabValues.length;setActiveValue(tabValues[next]);return}},{isActive}),jsxDEV35(TabsContext.Provider,{value:{activeValue,setActiveValue,tabValues,registerTab},children:jsxDEV35(Box,{flexDirection:"column",flexGrow:1,children},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function TabList({children}){return jsxDEV35(Box,{flexDirection:"row",gap:1,borderBottom:!0,borderColor:"$border",children},void 0,!1,void 0,this)}function Tab({value,children}){let{activeValue,setActiveValue,registerTab}=useTabsContext(),isActive=activeValue===value;return React20.useEffect(()=>{registerTab(value)},[value,registerTab]),jsxDEV35(Box,{onMouseDown:()=>setActiveValue(value),children:jsxDEV35(Text,{color:isActive?"$primary":"$muted",bold:isActive,underline:isActive,children},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function TabPanel({value,children}){let{activeValue}=useTabsContext();if(activeValue!==value)return null;return jsxDEV35(Box,{flexDirection:"column",flexGrow:1,children},void 0,!1,void 0,this)}import{jsxDEV as jsxDEV36}from"react/jsx-dev-runtime";function Tooltip({content,show=!1,children,...boxProps}){return jsxDEV36(Box,{flexDirection:"column",...boxProps,children:[children,show&&jsxDEV36(Box,{width:"snug-content",children:jsxDEV36(Text,{color:"$muted",dimColor:!0,children:content},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as jsxDEV37}from"react/jsx-dev-runtime";var DEFAULT_WIDTH3=20,DEFAULT_CHAR2="░";function Skeleton({width=DEFAULT_WIDTH3,height:heightProp,char=DEFAULT_CHAR2,shape}){let resolvedShape=shape??(heightProp&&heightProp>1?"block":"line"),height=heightProp??(resolvedShape==="circle"?1:1);if(resolvedShape==="circle"){let circleWidth=Math.min(width,6),pad=Math.max(0,Math.floor((width-circleWidth)/2));return jsxDEV37(Box,{children:jsxDEV37(Text,{color:"$muted",children:[" ".repeat(pad),char.repeat(circleWidth)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}let line=char.repeat(width),rows=Array.from({length:height},(_2,i)=>i);return jsxDEV37(Box,{flexDirection:"column",children:rows.map((i)=>jsxDEV37(Text,{color:"$muted",children:line},i,!1,void 0,this))},void 0,!1,void 0,this)}import{createContext as createContext10,useContext as useContext31,useMemo as useMemo15}from"react";import{createLogger as createLogger12}from"loggily";import{jsxDEV as jsxDEV38}from"react/jsx-dev-runtime";var log11=createLogger12("silvery:position-registry");function createPositionRegistry(){let sections=new Map;return{register(sectionIndex,itemIndex,rect){let sectionMap=sections.get(sectionIndex);if(!sectionMap)sectionMap=new Map,sections.set(sectionIndex,sectionMap);sectionMap.set(itemIndex,{rect}),log11.debug?.(`register sec=${sectionIndex} item=${itemIndex} y=${rect.y} h=${rect.height}`)},unregister(sectionIndex,itemIndex){let sectionMap=sections.get(sectionIndex);if(sectionMap){if(sectionMap.delete(itemIndex),sectionMap.size===0)sections.delete(sectionIndex);log11.debug?.(`unregister sec=${sectionIndex} item=${itemIndex}`)}},getPosition(sectionIndex,itemIndex){return sections.get(sectionIndex)?.get(itemIndex)?.rect},hasSection(sectionIndex){let sectionMap=sections.get(sectionIndex);return sectionMap!==void 0&&sectionMap.size>0},getItemCount(sectionIndex){return sections.get(sectionIndex)?.size??0},findItemAtY(sectionIndex,targetY){let sectionMap=sections.get(sectionIndex);if(!sectionMap||sectionMap.size===0)return-1;for(let[idx,entry]of sectionMap){let top=entry.rect.y,bottom=top+entry.rect.height;if(targetY>=top&&targetY<bottom)return idx}let closestIdx=-1,closestDist=1/0;for(let[idx,entry]of sectionMap){let mid=entry.rect.y+entry.rect.height/2,dist=Math.abs(mid-targetY);if(dist<closestDist)closestDist=dist,closestIdx=idx}let firstEntry=sectionMap.get(0);if(firstEntry&&targetY<firstEntry.rect.y)return-1;return closestIdx},findInsertionSlot(sectionIndex,targetY){let sectionMap=sections.get(sectionIndex);if(!sectionMap||sectionMap.size===0)return 0;let sorted=Array.from(sectionMap.entries()).sort((a,b)=>a[0]-b[0]);for(let i=0;i<sorted.length;i++){let entry=sorted[i];if(targetY<entry[1].rect.y)return i}return sorted.length},clear(){sections.clear(),log11.debug?.("cleared all positions")},dump(){let lines=[];if(sections.size===0)lines.push("(no items registered)");else for(let[secIdx,sectionMap]of sections){let entries=Array.from(sectionMap.entries()).sort((a,b)=>a[0]-b[0]).map(([idx,entry])=>`${idx}:y${entry.rect.y}:h${entry.rect.height}`).join(", ");lines.push(`sec[${secIdx}]: ${entries}`)}return lines.join(`
86
90
  `)}}}var PositionRegistryContext=createContext10(null);function PositionRegistryProvider({children}){let registry=useMemo15(()=>createPositionRegistry(),[]);return jsxDEV38(PositionRegistryContext.Provider,{value:registry,children},void 0,!1,void 0,this)}function usePositionRegistry(){return useContext31(PositionRegistryContext)}import{useEffect as useEffect19,useRef as useRef21}from"react";function useGridPosition(sectionIndex,itemIndex){let registry=usePositionRegistry(),sectionRef=useRef21(sectionIndex),itemRef=useRef21(itemIndex);sectionRef.current=sectionIndex,itemRef.current=itemIndex,useScrollRect((rect)=>{registry?.register(sectionRef.current,itemRef.current,rect)}),useEffect19(()=>{return()=>{registry?.unregister(sectionRef.current,itemRef.current)}},[registry]),useEffect19(()=>{return()=>{registry?.unregister(sectionIndex,itemIndex)}},[registry,sectionIndex,itemIndex])}import{jsxDEV as jsxDEV39}from"react/jsx-dev-runtime";function GridCell({sectionIndex,itemIndex,children}){return useGridPosition(sectionIndex,itemIndex),jsxDEV39(Box,{children},void 0,!1,void 0,this)}import{jsxDEV as jsxDEV40}from"react/jsx-dev-runtime";function Transform({transform,children}){if(children===void 0||children===null)return null;return jsxDEV40("silvery-text",{internal_transform:transform,children},void 0,!1,void 0,this)}import{jsxDEV as jsxDEV41}from"react/jsx-dev-runtime";function Newline({count=1}){return jsxDEV41("silvery-text",{children:`
87
91
  `.repeat(count)},void 0,!1,void 0,this)}import{jsxDEV as jsxDEV42}from"react/jsx-dev-runtime";function Spacer(){return jsxDEV42("silvery-box",{flexGrow:1},void 0,!1,void 0,this)}init_context();init_render_string();import{useContext as useContext32,useRef as useRef22}from"react";import{jsxDEV as jsxDEV43}from"react/jsx-dev-runtime";function Static({items,children,style:style2}){let stdoutCtx=useContext32(StdoutContext),term2=useContext32(TermContext),promoteScrollback=stdoutCtx?.promoteScrollback,renderedRef=useRef22([]),promotedCountRef=useRef22(0),prevCount=renderedRef.current.length;if(items.length>prevCount)for(let i=prevCount;i<items.length;i++)renderedRef.current.push(children(items[i],i));else if(items.length<prevCount){if(renderedRef.current.length=items.length,promotedCountRef.current>items.length)promotedCountRef.current=items.length}if(promoteScrollback&&isLayoutEngineInitialized()){let renderWidth=term2?.cols??80,prevPromoted=promotedCountRef.current;for(let i=prevPromoted;i<renderedRef.current.length;i++){let element=renderedRef.current[i];if(!element)continue;try{let lines=renderStringSync(element,{width:renderWidth,plain:!1,trimTrailingWhitespace:!0,trimEmptyLines:!1}).split(`
88
92
  `),frozenContent=lines.map((line)=>`${line}\x1B[K`).join(`\r
@@ -98,17 +102,17 @@ ${mismatches.join(`
98
102
  \x1B[K`;output+=`\x1B[${extraLines}A`}return output}function toPlainOutput(content,_prevLineCount){let lines=stripAnsi2(content).split(`
99
103
  `).map((line)=>line.trimEnd());while(lines.length>0&&lines[lines.length-1]==="")lines.pop();return lines.join(`
100
104
  `)}function createOutputTransformer(mode){switch(mode){case"tty":return(content)=>content;case"line-by-line":return toLineByLineOutput;case"static":return()=>"";case"plain":return toPlainOutput}}function countLines(str){if(!str)return 0;return str.split(`
101
- `).length}function copyToClipboard(stdout,text){let base64=Buffer.from(text).toString("base64");stdout.write(`\x1B]52;c;${base64}\x07`)}function requestClipboard(stdout){stdout.write("\x1B]52;c;?\x07")}function parseClipboardResponse(input){let prefixIdx=input.indexOf("\x1B]52;c;");if(prefixIdx===-1)return null;let contentStart=prefixIdx+7;if(input[contentStart]==="?")return null;let contentEnd=input.indexOf("\x07",contentStart);if(contentEnd===-1)contentEnd=input.indexOf("\x1B\\",contentStart);if(contentEnd===-1)return null;let base64=input.slice(contentStart,contentEnd);return Buffer.from(base64,"base64").toString("utf-8")}init_pipeline2();init_errors();init_errors();var log11=createLogger13("silvery:scheduler"),SYNC_UPDATE_ENABLED=process.env.SILVERY_SYNC_UPDATE==="1"||process.env.SILVERY_SYNC_UPDATE==="true";class RenderScheduler{stdout;root;debugMode;minFrameTime;slowFrameThreshold;mode;pipelineConfig;getCursorState;nonTTYMode;outputTransformer;writeOutput;log;prevBuffer=null;prevLineCount=0;staticOutput="";renderScheduled=!1;lastRenderTime=0;frameTimeout=null;resizeCleanup=null;stats={renderCount:0,skippedCount:0,lastRenderTime:0,avgRenderTime:0};disposed=!1;paused=!1;pendingWhilePaused=!1;scrollbackOffset=0;constructor(options){if(this.stdout=options.stdout,this.root=options.root,this.debugMode=options.debug??!1,this.minFrameTime=options.minFrameTime??16,this.slowFrameThreshold=options.slowFrameThreshold??50,this.mode=options.mode??"fullscreen",this.pipelineConfig=options.pipelineConfig,this.getCursorState=options.cursorAccessors?.getCursorState??getCursorState,this.writeOutput=options.writeOutput??((data)=>options.stdout.write(data)),this.log=createLogger13("silvery:scheduler"),this.nonTTYMode=resolveNonTTYMode({mode:options.nonTTYMode,stdout:this.stdout}),this.outputTransformer=createOutputTransformer(this.nonTTYMode),log11.debug?.(`non-TTY mode resolved to: ${this.nonTTYMode}`),this.nonTTYMode==="tty")this.setupResizeListener()}getNonTTYMode(){return this.nonTTYMode}scheduleRender(){if(this.disposed)return;if(this.paused){this.pendingWhilePaused=!0;return}if(this.renderScheduled){this.stats.skippedCount++,log11.debug?.(`render skipped (batched), total: ${this.stats.skippedCount}`);return}this.renderScheduled=!0,log11.debug?.("render scheduled"),queueMicrotask(()=>{if(this.renderScheduled=!1,this.disposed)return;let timeSinceLastRender=Date.now()-this.lastRenderTime;if(timeSinceLastRender<this.minFrameTime)log11.debug?.(`frame limited, delay: ${this.minFrameTime-timeSinceLastRender}ms`),this.scheduleNextFrame(this.minFrameTime-timeSinceLastRender);else this.executeRender()})}forceRender(){if(this.disposed)return;if(this.paused){this.pendingWhilePaused=!0;return}if(this.renderScheduled=!1,this.frameTimeout)clearTimeout(this.frameTimeout),this.frameTimeout=null;this.executeRender()}getStats(){return{...this.stats}}addScrollbackLines(lines){if(this.mode!=="inline"||lines<=0)return;this.scrollbackOffset+=lines}notify(message,opts){if(this.disposed)return;notify({write:(data)=>this.writeOutput(data)},message,opts)}copyToClipboard(text){if(this.disposed)return;copyToClipboard({write:(data)=>this.writeOutput(data)},text)}pause(){if(this.disposed||this.paused)return;this.paused=!0,this.pendingWhilePaused=!1,log11.debug?.("scheduler paused")}resume(){if(this.disposed||!this.paused)return;if(this.paused=!1,log11.debug?.("scheduler resumed"),this.prevBuffer=null,this.pendingWhilePaused)this.pendingWhilePaused=!1,this.executeRender()}isPaused(){return this.paused}clear(){if(this.disposed)return;this.writeOutput("\x1B[2J\x1B[H\x1B[?25l"),this.prevBuffer=null}[Symbol.dispose](){this.dispose()}dispose(){if(this.disposed)return;if(log11.info?.(`dispose: renders=${this.stats.renderCount}, skipped=${this.stats.skippedCount}, avg=${Math.round(this.stats.avgRenderTime)}ms`),this.disposed=!0,this.renderScheduled=!1,this.frameTimeout)clearTimeout(this.frameTimeout),this.frameTimeout=null;if(this.resizeCleanup)this.resizeCleanup(),this.resizeCleanup=null;if(this.nonTTYMode==="static"&&this.staticOutput)this.writeOutput(this.staticOutput),this.writeOutput(`
102
- `)}getStaticOutput(){return this.staticOutput}scheduleNextFrame(delay){if(this.frameTimeout)return;this.frameTimeout=setTimeout(()=>{if(this.frameTimeout=null,!this.disposed)this.executeRender()},delay)}executeRender(){let __stack=[];try{const render=__using(__stack,this.log.span("render"),0);let startTime=Date.now();try{let width=this.stdout.columns??80,height=this.mode==="inline"?NaN:this.stdout.rows??24;log11.debug?.(`render #${this.stats.renderCount+1}: ${width}x${height}, nonTTYMode=${this.nonTTYMode}`);let scrollbackOffset=this.scrollbackOffset;this.scrollbackOffset=0;let inlineCursor=this.mode==="inline"?this.getCursorState():void 0,{output,buffer}=executeRender(this.root,width,height,this.prevBuffer,{mode:this.mode,scrollbackOffset,termRows:this.mode==="inline"?this.stdout.rows??24:void 0,cursorPos:inlineCursor},this.pipelineConfig),transformedOutput;if(this.nonTTYMode==="tty")transformedOutput=output;else if(this.nonTTYMode==="static")this.staticOutput=stripAnsi2(output),transformedOutput="";else transformedOutput=this.outputTransformer(output,this.prevLineCount),this.prevLineCount=countLines(output);let cursorSuffix="";if(this.nonTTYMode==="tty"){let cursor=this.getCursorState();if(cursor?.visible){let shapeSeq=cursor.shape?setCursorStyle(cursor.shape):resetCursorStyle();cursorSuffix=ANSI.moveCursor(cursor.x,cursor.y)+shapeSeq+ANSI.CURSOR_SHOW}else cursorSuffix=ANSI.CURSOR_HIDE}if(transformedOutput.length>0||cursorSuffix.length>0){let fullOutput=this.nonTTYMode==="tty"&&SYNC_UPDATE_ENABLED?`${ANSI.SYNC_BEGIN}${transformedOutput}${cursorSuffix}${ANSI.SYNC_END}`:transformedOutput+cursorSuffix;if(log11.debug){let bytes=Buffer.byteLength(fullOutput);if(log11.debug?.(`stdout.write: ${bytes} bytes (${transformedOutput.length} chars output + ${cursorSuffix.length} chars cursor)`),bytes>16384)log11.debug?.(`large output: ${bytes} bytes may exceed pipe buffer (16KB on macOS), risk of mid-sequence split`)}let captureFile=process.env.SILVERY_CAPTURE_OUTPUT;if(captureFile){let fs2=__require("fs");fs2.appendFileSync(captureFile,`--- FRAME ${this.stats.renderCount+1} (${Buffer.byteLength(fullOutput)} bytes) ---
105
+ `).length}function copyToClipboard(stdout,text){let base64=Buffer.from(text).toString("base64");stdout.write(`\x1B]52;c;${base64}\x07`)}function requestClipboard(stdout){stdout.write("\x1B]52;c;?\x07")}function parseClipboardResponse(input){let prefixIdx=input.indexOf("\x1B]52;c;");if(prefixIdx===-1)return null;let contentStart=prefixIdx+7;if(input[contentStart]==="?")return null;let contentEnd=input.indexOf("\x07",contentStart);if(contentEnd===-1)contentEnd=input.indexOf("\x1B\\",contentStart);if(contentEnd===-1)return null;let base64=input.slice(contentStart,contentEnd);return Buffer.from(base64,"base64").toString("utf-8")}init_pipeline2();init_errors();init_errors();var log12=createLogger13("silvery:scheduler"),SYNC_UPDATE_ENABLED=process.env.SILVERY_SYNC_UPDATE==="1"||process.env.SILVERY_SYNC_UPDATE==="true";class RenderScheduler{stdout;root;debugMode;minFrameTime;slowFrameThreshold;mode;pipelineConfig;getCursorState;nonTTYMode;outputTransformer;writeOutput;log;prevBuffer=null;prevLineCount=0;staticOutput="";renderScheduled=!1;lastRenderTime=0;frameTimeout=null;resizeCleanup=null;stats={renderCount:0,skippedCount:0,lastRenderTime:0,avgRenderTime:0};disposed=!1;paused=!1;pendingWhilePaused=!1;scrollbackOffset=0;constructor(options){if(this.stdout=options.stdout,this.root=options.root,this.debugMode=options.debug??!1,this.minFrameTime=options.minFrameTime??16,this.slowFrameThreshold=options.slowFrameThreshold??50,this.mode=options.mode??"fullscreen",this.pipelineConfig=options.pipelineConfig,this.getCursorState=options.cursorAccessors?.getCursorState??getCursorState,this.writeOutput=options.writeOutput??((data)=>options.stdout.write(data)),this.log=createLogger13("silvery:scheduler"),this.nonTTYMode=resolveNonTTYMode({mode:options.nonTTYMode,stdout:this.stdout}),this.outputTransformer=createOutputTransformer(this.nonTTYMode),log12.debug?.(`non-TTY mode resolved to: ${this.nonTTYMode}`),this.nonTTYMode==="tty")this.setupResizeListener()}getNonTTYMode(){return this.nonTTYMode}scheduleRender(){if(this.disposed)return;if(this.paused){this.pendingWhilePaused=!0;return}if(this.renderScheduled){this.stats.skippedCount++,log12.debug?.(`render skipped (batched), total: ${this.stats.skippedCount}`);return}this.renderScheduled=!0,log12.debug?.("render scheduled"),queueMicrotask(()=>{if(this.renderScheduled=!1,this.disposed)return;let timeSinceLastRender=Date.now()-this.lastRenderTime;if(timeSinceLastRender<this.minFrameTime)log12.debug?.(`frame limited, delay: ${this.minFrameTime-timeSinceLastRender}ms`),this.scheduleNextFrame(this.minFrameTime-timeSinceLastRender);else this.executeRender()})}forceRender(){if(this.disposed)return;if(this.paused){this.pendingWhilePaused=!0;return}if(this.renderScheduled=!1,this.frameTimeout)clearTimeout(this.frameTimeout),this.frameTimeout=null;this.executeRender()}getStats(){return{...this.stats}}addScrollbackLines(lines){if(this.mode!=="inline"||lines<=0)return;this.scrollbackOffset+=lines}notify(message,opts){if(this.disposed)return;notify({write:(data)=>this.writeOutput(data)},message,opts)}copyToClipboard(text){if(this.disposed)return;copyToClipboard({write:(data)=>this.writeOutput(data)},text)}pause(){if(this.disposed||this.paused)return;this.paused=!0,this.pendingWhilePaused=!1,log12.debug?.("scheduler paused")}resume(){if(this.disposed||!this.paused)return;if(this.paused=!1,log12.debug?.("scheduler resumed"),this.prevBuffer=null,this.pendingWhilePaused)this.pendingWhilePaused=!1,this.executeRender()}isPaused(){return this.paused}clear(){if(this.disposed)return;this.writeOutput("\x1B[2J\x1B[H\x1B[?25l"),this.prevBuffer=null}[Symbol.dispose](){this.dispose()}dispose(){if(this.disposed)return;if(log12.info?.(`dispose: renders=${this.stats.renderCount}, skipped=${this.stats.skippedCount}, avg=${Math.round(this.stats.avgRenderTime)}ms`),this.disposed=!0,this.renderScheduled=!1,this.frameTimeout)clearTimeout(this.frameTimeout),this.frameTimeout=null;if(this.resizeCleanup)this.resizeCleanup(),this.resizeCleanup=null;if(this.nonTTYMode==="static"&&this.staticOutput)this.writeOutput(this.staticOutput),this.writeOutput(`
106
+ `)}getStaticOutput(){return this.staticOutput}scheduleNextFrame(delay){if(this.frameTimeout)return;this.frameTimeout=setTimeout(()=>{if(this.frameTimeout=null,!this.disposed)this.executeRender()},delay)}executeRender(){let __stack=[];try{const render=__using(__stack,this.log.span("render"),0);let startTime=Date.now();try{let width=this.stdout.columns??80,height=this.mode==="inline"?NaN:this.stdout.rows??24;log12.debug?.(`render #${this.stats.renderCount+1}: ${width}x${height}, nonTTYMode=${this.nonTTYMode}`);let scrollbackOffset=this.scrollbackOffset;this.scrollbackOffset=0;let inlineCursor=this.mode==="inline"?this.getCursorState():void 0,{output,buffer}=executeRender(this.root,width,height,this.prevBuffer,{mode:this.mode,scrollbackOffset,termRows:this.mode==="inline"?this.stdout.rows??24:void 0,cursorPos:inlineCursor},this.pipelineConfig),transformedOutput;if(this.nonTTYMode==="tty")transformedOutput=output;else if(this.nonTTYMode==="static")this.staticOutput=stripAnsi2(output),transformedOutput="";else transformedOutput=this.outputTransformer(output,this.prevLineCount),this.prevLineCount=countLines(output);let cursorSuffix="";if(this.nonTTYMode==="tty"){let cursor=this.getCursorState();if(cursor?.visible){let shapeSeq=cursor.shape?setCursorStyle(cursor.shape):resetCursorStyle();cursorSuffix=ANSI.moveCursor(cursor.x,cursor.y)+shapeSeq+ANSI.CURSOR_SHOW}else cursorSuffix=ANSI.CURSOR_HIDE}if(transformedOutput.length>0||cursorSuffix.length>0){let fullOutput=this.nonTTYMode==="tty"&&SYNC_UPDATE_ENABLED?`${ANSI.SYNC_BEGIN}${transformedOutput}${cursorSuffix}${ANSI.SYNC_END}`:transformedOutput+cursorSuffix;if(log12.debug){let bytes=Buffer.byteLength(fullOutput);if(log12.debug?.(`stdout.write: ${bytes} bytes (${transformedOutput.length} chars output + ${cursorSuffix.length} chars cursor)`),bytes>16384)log12.debug?.(`large output: ${bytes} bytes may exceed pipe buffer (16KB on macOS), risk of mid-sequence split`)}let captureFile=process.env.SILVERY_CAPTURE_OUTPUT;if(captureFile){let fs2=__require("fs");fs2.appendFileSync(captureFile,`--- FRAME ${this.stats.renderCount+1} (${Buffer.byteLength(fullOutput)} bytes) ---
103
107
  `),fs2.appendFileSync(captureFile,fullOutput),fs2.appendFileSync(captureFile,`
104
108
  `)}this.writeOutput(fullOutput)}this.prevBuffer=buffer;let strictEnv=process.env.SILVERY_STRICT;if(strictEnv&&strictEnv!=="0"&&strictEnv!=="false"&&this.stats.renderCount>0){let renderNum=this.stats.renderCount+1,{buffer:freshBuffer}=executeRender(this.root,width,height,null,{mode:this.mode==="fullscreen"?"fullscreen":"inline",skipLayoutNotifications:!0},this.pipelineConfig),found=!1;for(let y=0;y<buffer.height&&!found;y++)for(let x=0;x<buffer.width&&!found;x++){let a=buffer.getCell(x,y),b=freshBuffer.getCell(x,y);if(!cellEquals(a,b)){found=!0;let ctx=buildMismatchContext(this.root,x,y,a,b,renderNum),renderPhaseStats=globalThis.__silvery_content_detail?structuredClone(globalThis.__silvery_content_detail):void 0,debugInfo=formatMismatchContext(ctx,renderPhaseStats),incText=bufferToText(buffer),freshText=bufferToText(freshBuffer),msg=debugInfo+`--- incremental ---
105
109
  ${incText}
106
110
  --- fresh ---
107
111
  ${freshText}`;if(process.env.DEBUG_LOG)appendFileSync(process.env.DEBUG_LOG,msg+`
108
- `);throw log11.error?.(msg),new IncrementalRenderMismatchError(msg,{renderPhaseStats,mismatchContext:ctx})}}if(!found&&process.env.DEBUG_LOG)appendFileSync(process.env.DEBUG_LOG,`SILVERY_STRICT: render #${renderNum} OK
109
- `)}let renderTime=Date.now()-startTime;this.stats.renderCount++,this.stats.lastRenderTime=renderTime,this.stats.avgRenderTime=(this.stats.avgRenderTime*(this.stats.renderCount-1)+renderTime)/this.stats.renderCount,this.lastRenderTime=Date.now(),render.spanData.renderCount=this.stats.renderCount,render.spanData.renderTime=renderTime,render.spanData.bytes=transformedOutput.length,log11.debug?.(`render #${this.stats.renderCount} complete: ${renderTime}ms, output: ${transformedOutput.length} bytes`);let threshold=this.stats.renderCount<=1?this.slowFrameThreshold*5:this.slowFrameThreshold;if(threshold>0&&renderTime>threshold)log11.debug?.(`slow frame: render #${this.stats.renderCount} took ${renderTime}ms (threshold: ${this.slowFrameThreshold}ms, bytes: ${transformedOutput.length})`);if(this.debugMode)this.logDebug(`Render #${this.stats.renderCount} took ${renderTime}ms`)}catch(error){throw log11.error?.(`render error: ${error}`),this.logError("Render error:",error),error}}catch(_catch){var _err=_catch,_hasErr=1}finally{__callDispose(__stack,_err,_hasErr)}}setupResizeListener(){let resizeTimeout=null,handleResize=()=>{if(resizeTimeout)clearTimeout(resizeTimeout);resizeTimeout=setTimeout(()=>{resizeTimeout=null,this.prevBuffer=null,this.scheduleRender()},50)};this.stdout.on("resize",handleResize),this.resizeCleanup=()=>{if(this.stdout.off("resize",handleResize),resizeTimeout)clearTimeout(resizeTimeout)}}logDebug(message){log11.debug?.(message)}logError(message,error){if(error instanceof Error)log11.error?.(`${message} ${error.stack??error.message}`);else log11.error?.(`${message} ${String(error)}`)}}init_output_guard();function isTerm(value){if(!value||typeof value!=="object"&&typeof value!=="function")return!1;let obj=value;return typeof obj.hasCursor==="function"&&typeof obj.hasInput==="function"&&typeof obj.hasColor==="function"&&typeof obj.write==="function"}function isTermDef(value){if(!value||typeof value!=="object")return!1;return typeof value.hasCursor!=="function"}function resolveTermDef(def){let width=def.width??def.stdout?.columns??80,height=def.height??def.stdout?.rows??24,colors=null;if(def.colors===!0)colors=detectColorLevel(def.stdout);else if(def.colors===!1||def.colors===null)colors=null;else if(def.colors)colors=def.colors;else colors=detectColorLevel(def.stdout);let events=null;if(def.events)events=def.events;else if(def.stdin)events=createInputEvents(def.stdin);return{stdout:def.stdout??null,width,height,colors,events,isStatic:events===null}}function resolveFromTerm(term2){return{stdout:term2.stdout,width:term2.cols??80,height:term2.rows??24,colors:term2.hasColor(),events:createInputEvents(term2.stdin),isStatic:!1}}function detectColorLevel(stdout){if(process.env.NO_COLOR!==void 0)return null;if(process.env.FORCE_COLOR!==void 0){let level=Number.parseInt(process.env.FORCE_COLOR,10);if(level===0)return null;if(level===1)return"basic";if(level===2)return"256";if(level>=3)return"truecolor";return"basic"}if(process.env.COLORTERM==="truecolor"||process.env.COLORTERM==="24bit")return"truecolor";if(!stdout?.isTTY)return null;let term2=process.env.TERM??"";if(term2.includes("256color")||term2.includes("256"))return"256";return"basic"}function createInputEvents(stdin){return{[Symbol.asyncIterator](){let buffer=[],resolveNext=null,done=!1,handleData=(chunk)=>{let data=typeof chunk==="string"?chunk:chunk.toString("utf8");for(let char of data){let event={type:"key",key:char,ctrl:char.charCodeAt(0)<32&&char!=="\r"&&char!==`
110
- `&&char!=="\t"};if(resolveNext)resolveNext({value:event,done:!1}),resolveNext=null;else buffer.push(event)}},handleEnd=()=>{if(done=!0,resolveNext)resolveNext({value:void 0,done:!0}),resolveNext=null};if(stdin.isTTY&&typeof stdin.setRawMode==="function")stdin.setEncoding("utf8"),stdin.on("data",handleData),stdin.on("end",handleEnd);return{next(){let buffered=buffer.shift();if(buffered)return Promise.resolve({value:buffered,done:!1});if(done)return Promise.resolve({value:void 0,done:!0});return new Promise((resolve)=>{resolveNext=resolve})},return(){return done=!0,stdin.off("data",handleData),stdin.off("end",handleEnd),Promise.resolve({value:void 0,done:!0})}}}}}init_keys();function createSubscriberList(){return{input:new Set,paste:new Set}}init_flexily_zero_adapter();import{jsxDEV as jsxDEV46}from"react/jsx-dev-runtime";var log13=createLogger15("silvery:render");class RenderHandle{promise;constructor(promise){this.promise=promise}then(onfulfilled,onrejected){return this.promise.then(onfulfilled,onrejected)}catch(onrejected){return this.promise.catch(onrejected)}finally(onfinally){return this.promise.finally(onfinally)}async run(){await(await this.promise).waitUntilExit()}}var instances=new Map;async function ensureLayoutEngineInitialized(engineType){if(isLayoutEngineInitialized()){log13.debug?.("Layout engine already initialized");return}log13.debug?.(`Initializing layout engine (${engineType??"default"})...`);let startTime=Date.now(),{ensureDefaultLayoutEngine:ensureDefaultLayoutEngine2}=await Promise.resolve().then(() => exports_layout_engine);await ensureDefaultLayoutEngine2(engineType),log13.debug?.(`Layout engine initialized in ${Date.now()-startTime}ms`)}function SilveryApp({children,onInputSubscribe,exitOnCtrlC,stdoutWrite,stdout,onExit,onPause,onResume,onScrollback,getRoot:getRootProp,handleFocusCycling=!0}){let subscribersRef=useRef26(null);if(!subscribersRef.current)subscribersRef.current=createSubscriberList();let subscribers=subscribersRef.current,handleExit=useCallback28((error)=>{onExit(error)},[onExit]),exitOnCtrlCRef=useRef26(exitOnCtrlC);exitOnCtrlCRef.current=exitOnCtrlC;let handleExitRef=useRef26(handleExit);handleExitRef.current=handleExit;let focusManagerRef=useRef26(null),getRootRef=useRef26(getRootProp);getRootRef.current=getRootProp;let handleFocusCyclingRef=useRef26(handleFocusCycling);handleFocusCyclingRef.current=handleFocusCycling;let handleChunkRef=useRef26(null);if(handleChunkRef.current===null){let processSingleKey=function(chunk){if(log13.debug?.(`processSingleKey: ${JSON.stringify(chunk)}`),chunk==="\x03"&&exitOnCtrlCRef.current){handleExitRef.current();return}if(handleFocusCyclingRef.current){let fm=focusManagerRef.current,root=getRootRef.current?.();if(fm&&root){let[,key2]=parseKey(chunk);if(key2.tab&&!key2.shift){fm.focusNext(root),reconciler.flushSyncWork();return}if(key2.tab&&key2.shift){fm.focusPrev(root),reconciler.flushSyncWork();return}if(key2.escape&&fm.activeElement){fm.blur(),reconciler.flushSyncWork();return}}}let[input,key]=parseKey(chunk);runWithDiscreteEvent(()=>{for(let handler of subscribers.input)handler(input,key)}),reconciler.flushSyncWork()};handleChunkRef.current=(rawChunk)=>{log13.debug?.(`handleChunk: ${JSON.stringify(rawChunk)}`);let pasteResult=parseBracketedPaste(rawChunk);if(pasteResult){for(let handler of subscribers.paste)handler(pasteResult.content);return}for(let keypress of splitRawInput(rawChunk))processSingleKey(keypress)}}let handleChunk=handleChunkRef.current;useEffect22(()=>{if(!onInputSubscribe)return;return onInputSubscribe(handleChunk)},[onInputSubscribe,handleChunk]);let stdoutContextValue=useMemo17(()=>({stdout,write:stdoutWrite,notifyScrollback:onScrollback}),[stdout,stdoutWrite,onScrollback]),runtimeContextValue=useMemo17(()=>({on(event,handler){if(event==="input"){let typed=handler;return subscribers.input.add(typed),()=>{subscribers.input.delete(typed)}}if(event==="paste"){let typed=handler;return subscribers.paste.add(typed),()=>{subscribers.paste.delete(typed)}}return()=>{}},emit(){},exit:handleExit,pause:onPause,resume:onResume}),[subscribers,handleExit,onPause,onResume]),focusManager=useMemo17(()=>createFocusManager(),[]);return focusManagerRef.current=focusManager,useEffect22(()=>{return setOnNodeRemoved((removedNode)=>focusManager.handleSubtreeRemoved(removedNode)),()=>setOnNodeRemoved(null)},[focusManager]),jsxDEV46(StdoutContext.Provider,{value:stdoutContextValue,children:jsxDEV46(StderrContext.Provider,{value:{stderr:process2.stderr,write:(data)=>{process2.stderr.write(data)}},children:jsxDEV46(FocusManagerContext.Provider,{value:focusManager,children:jsxDEV46(RuntimeContext.Provider,{value:runtimeContextValue,children},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)}class SilveryInstance{stdout;stdin;exitOnCtrlC;debug;alternateScreen;mode;nonTTYMode;scheduler=null;cursorStore;container=null;fiberRoot=null;lastElement=null;isUnmounted=!1;exitPromise=null;resolveExit=null;rejectExit=null;resizeCleanup=null;signalCleanup=null;outputGuard=null;constructor(options){log13.debug?.("SilveryInstance constructor start");let startTime=Date.now();if(this.stdout=options.stdout,this.stdin=options.stdin,this.exitOnCtrlC=options.exitOnCtrlC,this.debug=options.debug,this.alternateScreen=options.alternateScreen,this.mode=options.mode,this.nonTTYMode=options.nonTTYMode,this.exitPromise=new Promise((resolve,reject)=>{this.resolveExit=resolve,this.rejectExit=reject}),this.alternateScreen)this.stdout.write(enterAlternateScreen());if(this.stdout.isTTY)this.stdout.write(enableKittyKeyboard2());if(this.stdout.isTTY)enableBracketedPaste2(this.stdout);if(this.cursorStore=createCursorStore(),this.alternateScreen&&this.stdout===process2.stdout)this.outputGuard=createOutputGuard();this.container=createContainer(()=>{this.scheduler?.scheduleRender()}),this.fiberRoot=createFiberRoot(this.container),this.scheduler=new RenderScheduler({stdout:this.stdout,root:getContainerRoot(this.container),debug:this.debug,mode:this.mode,nonTTYMode:this.nonTTYMode,cursorAccessors:this.cursorStore.accessors,writeOutput:this.outputGuard?(data)=>this.outputGuard.writeStdout(data):void 0}),this.setupResizeListener(),this.setupSignalHandlers(),log13.debug?.(`SilveryInstance constructor complete in ${Date.now()-startTime}ms`)}render(element){log13.debug?.("SilveryInstance.render() start");let startTime=Date.now();if(this.isUnmounted||!this.fiberRoot)return;this.lastElement=element;let tree=jsxDEV46(CursorProvider,{store:this.cursorStore,children:jsxDEV46(SilveryApp,{onInputSubscribe:this.subscribeToInput,exitOnCtrlC:this.exitOnCtrlC,stdoutWrite:(data)=>{if(this.outputGuard)this.outputGuard.writeStdout(data);else this.stdout.write(data)},stdout:this.stdout,onExit:this.handleExit,onPause:this.pause,onResume:this.resume,onScrollback:this.handleScrollback,getRoot:()=>this.container?getContainerRoot(this.container):null,children:element},void 0,!1,void 0,this)},void 0,!1,void 0,this);log13.debug?.("SilveryInstance.render() calling updateContainerSync"),reconciler.updateContainerSync(tree,this.fiberRoot,null,null),log13.debug?.(`SilveryInstance.render() updateContainerSync complete in ${Date.now()-startTime}ms`),log13.debug?.("SilveryInstance.render() calling flushSyncWork");let flushStart=Date.now();reconciler.flushSyncWork(),log13.debug?.(`SilveryInstance.render() flushSyncWork complete in ${Date.now()-flushStart}ms (total: ${Date.now()-startTime}ms)`)}rerender=(element)=>{this.render(element)};flush=()=>{if(this.isUnmounted||!this.lastElement)return;this.render(this.lastElement),this.scheduler?.forceRender()};[Symbol.dispose]=()=>this.unmount();unmount=()=>{if(this.isUnmounted)return;if(this.isUnmounted=!0,this.scheduler?.forceRender(),this.resizeCleanup?.(),this.signalCleanup?.(),this.outputGuard)this.outputGuard.dispose(),this.outputGuard=null;if(this.stdout.isTTY)disableBracketedPaste2(this.stdout),this.stdout.write(disableKittyKeyboard2());if(this.stdout.isTTY)resetWindowTitle(this.stdout);if(this.alternateScreen)this.stdout.write(leaveAlternateScreen());else if(this.mode==="inline")this.stdout.write(`${ANSI.SYNC_END}${ANSI.CURSOR_SHOW}
111
- `);else this.stdout.write(ANSI.SYNC_END);let{stdin}=this;if(stdin.removeAllListeners("readable"),stdin.removeAllListeners("data"),stdin.destroy(),typeof stdin.unref==="function")stdin.unref();if(this.fiberRoot)reconciler.updateContainer(null,this.fiberRoot,null,()=>{});this.scheduler?.dispose(),instances.delete(this.stdout),this.resolveExit?.()};waitUntilExit=()=>{return this.exitPromise??Promise.resolve()};clear=()=>{this.scheduler?.clear()};pause=()=>{this.scheduler?.pause()};resume=()=>{this.scheduler?.resume(),this.scheduler?.forceRender()};handleExit=(error)=>{if(this.isUnmounted)return;if(error)this.rejectExit?.(error);this.unmount()};handleScrollback=(lines)=>{this.scheduler?.addScrollbackLines(lines)};setupResizeListener(){let handleResize=()=>{this.scheduler?.clear(),this.scheduler?.forceRender()};this.stdout.on("resize",handleResize),this.resizeCleanup=()=>{this.stdout.off("resize",handleResize)}}setupSignalHandlers(){let handleSignal=()=>{this.unmount()};process2.on("SIGINT",handleSignal),process2.on("SIGTERM",handleSignal),this.signalCleanup=()=>{process2.off("SIGINT",handleSignal),process2.off("SIGTERM",handleSignal)}}subscribeToInput=(handler)=>{let{stdin}=this,isRawModeSupported=stdin.isTTY===!0;if(log13.debug?.(`subscribeToInput: stdin=${stdin===process2.stdin?"process.stdin":"other"}, isTTY=${stdin.isTTY}, isRawModeSupported=${isRawModeSupported}`),!isRawModeSupported)return log13.debug?.("subscribeToInput: raw mode not supported, skipping"),()=>{};let handleReadable=()=>{let chunk;while((chunk=stdin.read())!==null)log13.debug?.(`subscribeToInput: stdin.read() returned: ${JSON.stringify(chunk)}`),handler(chunk)};return stdin.setEncoding("utf8"),stdin.ref(),stdin.setRawMode(!0),stdin.on("readable",handleReadable),log13.debug?.(`subscribeToInput: enabled raw mode, stdin.isRaw=${stdin.isRaw}`),()=>{log13.debug?.("subscribeToInput: cleanup — disabling raw mode"),stdin.setRawMode(!1),stdin.off("readable",handleReadable),stdin.unref()}}}function render(element,termOrDef,options){return new RenderHandle(renderAsync(element,termOrDef,options))}async function renderAsync(element,termOrDef,options){let resolved,term2;if(!termOrDef)resolved=resolveTermDef({}),term2=createTerm({color:resolved.colors??void 0});else if(isTerm(termOrDef))resolved=resolveFromTerm(termOrDef),term2=termOrDef;else if(isTermDef(termOrDef))resolved=resolveTermDef(termOrDef),term2=createTerm({stdout:termOrDef.stdout,stdin:termOrDef.stdin,color:resolved.colors??void 0});else throw Error("Invalid second argument: expected Term, TermDef, or undefined");let mergedOptions={...options,stdout:options?.stdout??resolved.stdout??term2.stdout,stdin:options?.stdin??(resolved.isStatic?void 0:term2.stdin)};return renderImpl(element,mergedOptions,term2,resolved)}async function renderImpl(element,options,term2,resolved){log13.debug?.(`render() called, isStatic=${resolved.isStatic}`);let renderStart=Date.now();if(await ensureLayoutEngineInitialized(options.layoutEngine),log13.debug?.(`render(): layout engine ready in ${Date.now()-renderStart}ms`),process2.env.DEBUG_DEVTOOLS){let{autoConnectDevTools:autoConnectDevTools2}=await Promise.resolve().then(() => (init_devtools(),exports_devtools));await autoConnectDevTools2()}if(resolved.isStatic)return renderStaticImpl(element,term2,resolved);let mode=options.mode??"fullscreen",resolvedOptions={stdout:options.stdout??process2.stdout,stdin:options.stdin??process2.stdin,exitOnCtrlC:options.exitOnCtrlC??!0,debug:options.debug??!1,patchConsole:options.patchConsole??!0,alternateScreen:options.alternateScreen??mode==="fullscreen",mode,nonTTYMode:options.nonTTYMode??"auto"},instance=instances.get(resolvedOptions.stdout);if(!instance)log13.debug?.("render(): creating new SilveryInstance"),instance=new SilveryInstance(resolvedOptions),instances.set(resolvedOptions.stdout,instance),log13.debug?.(`render(): SilveryInstance created in ${Date.now()-renderStart}ms`);let wrappedElement=jsxDEV46(TermContext.Provider,{value:term2,children:element},void 0,!1,void 0,this);return log13.debug?.("render(): calling instance.render()"),instance.render(wrappedElement),log13.debug?.(`render(): instance.render() complete, total: ${Date.now()-renderStart}ms`),{rerender:(newElement)=>instance.rerender(jsxDEV46(TermContext.Provider,{value:term2,children:newElement},void 0,!1,void 0,this)),unmount:instance.unmount,[Symbol.dispose]:instance.unmount,waitUntilExit:instance.waitUntilExit,clear:instance.clear,flush:instance.flush,pause:instance.pause,resume:instance.resume}}async function renderStaticImpl(element,term2,resolved){log13.debug?.(`renderStatic() called, dimensions: ${resolved.width}x${resolved.height}`);let{renderStringSync:renderStringSync2}=await Promise.resolve().then(() => (init_render_string(),exports_render_string)),wrappedElement=jsxDEV46(TermContext.Provider,{value:term2,children:element},void 0,!1,void 0,this),output=renderStringSync2(wrappedElement,{width:resolved.width,height:resolved.height,plain:resolved.colors===null});if(resolved.stdout)resolved.stdout.write(output),resolved.stdout.write(`
112
+ `);throw log12.error?.(msg),new IncrementalRenderMismatchError(msg,{renderPhaseStats,mismatchContext:ctx})}}if(!found&&process.env.DEBUG_LOG)appendFileSync(process.env.DEBUG_LOG,`SILVERY_STRICT: render #${renderNum} OK
113
+ `)}let renderTime=Date.now()-startTime;this.stats.renderCount++,this.stats.lastRenderTime=renderTime,this.stats.avgRenderTime=(this.stats.avgRenderTime*(this.stats.renderCount-1)+renderTime)/this.stats.renderCount,this.lastRenderTime=Date.now(),render.spanData.renderCount=this.stats.renderCount,render.spanData.renderTime=renderTime,render.spanData.bytes=transformedOutput.length,log12.debug?.(`render #${this.stats.renderCount} complete: ${renderTime}ms, output: ${transformedOutput.length} bytes`);let threshold=this.stats.renderCount<=1?this.slowFrameThreshold*5:this.slowFrameThreshold;if(threshold>0&&renderTime>threshold)log12.debug?.(`slow frame: render #${this.stats.renderCount} took ${renderTime}ms (threshold: ${this.slowFrameThreshold}ms, bytes: ${transformedOutput.length})`);if(this.debugMode)this.logDebug(`Render #${this.stats.renderCount} took ${renderTime}ms`)}catch(error){throw log12.error?.(`render error: ${error}`),this.logError("Render error:",error),error}}catch(_catch){var _err=_catch,_hasErr=1}finally{__callDispose(__stack,_err,_hasErr)}}setupResizeListener(){let resizeTimeout=null,handleResize=()=>{if(resizeTimeout)clearTimeout(resizeTimeout);resizeTimeout=setTimeout(()=>{resizeTimeout=null,this.prevBuffer=null,this.scheduleRender()},50)};this.stdout.on("resize",handleResize),this.resizeCleanup=()=>{if(this.stdout.off("resize",handleResize),resizeTimeout)clearTimeout(resizeTimeout)}}logDebug(message){log12.debug?.(message)}logError(message,error){if(error instanceof Error)log12.error?.(`${message} ${error.stack??error.message}`);else log12.error?.(`${message} ${String(error)}`)}}init_output_guard();function isTerm(value){if(!value||typeof value!=="object"&&typeof value!=="function")return!1;let obj=value;return typeof obj.hasCursor==="function"&&typeof obj.hasInput==="function"&&typeof obj.hasColor==="function"&&typeof obj.write==="function"}function isTermDef(value){if(!value||typeof value!=="object")return!1;return typeof value.hasCursor!=="function"}function resolveTermDef(def){let width=def.width??def.stdout?.columns??80,height=def.height??def.stdout?.rows??24,colors=null;if(def.colors===!0)colors=detectColorLevel(def.stdout);else if(def.colors===!1||def.colors===null)colors=null;else if(def.colors)colors=def.colors;else colors=detectColorLevel(def.stdout);let events=null;if(def.events)events=def.events;else if(def.stdin)events=createInputEvents(def.stdin);return{stdout:def.stdout??null,width,height,colors,events,isStatic:events===null}}function resolveFromTerm(term2){return{stdout:term2.stdout,width:term2.cols??80,height:term2.rows??24,colors:term2.hasColor(),events:createInputEvents(term2.stdin),isStatic:!1}}function detectColorLevel(stdout){if(process.env.NO_COLOR!==void 0)return null;if(process.env.FORCE_COLOR!==void 0){let level=Number.parseInt(process.env.FORCE_COLOR,10);if(level===0)return null;if(level===1)return"basic";if(level===2)return"256";if(level>=3)return"truecolor";return"basic"}if(process.env.COLORTERM==="truecolor"||process.env.COLORTERM==="24bit")return"truecolor";if(!stdout?.isTTY)return null;let term2=process.env.TERM??"";if(term2.includes("256color")||term2.includes("256"))return"256";return"basic"}function createInputEvents(stdin){return{[Symbol.asyncIterator](){let buffer=[],resolveNext=null,done=!1,handleData=(chunk)=>{let data=typeof chunk==="string"?chunk:chunk.toString("utf8");for(let char of data){let event={type:"key",key:char,ctrl:char.charCodeAt(0)<32&&char!=="\r"&&char!==`
114
+ `&&char!=="\t"};if(resolveNext)resolveNext({value:event,done:!1}),resolveNext=null;else buffer.push(event)}},handleEnd=()=>{if(done=!0,resolveNext)resolveNext({value:void 0,done:!0}),resolveNext=null};if(stdin.isTTY&&typeof stdin.setRawMode==="function")stdin.setEncoding("utf8"),stdin.on("data",handleData),stdin.on("end",handleEnd);return{next(){let buffered=buffer.shift();if(buffered)return Promise.resolve({value:buffered,done:!1});if(done)return Promise.resolve({value:void 0,done:!0});return new Promise((resolve)=>{resolveNext=resolve})},return(){return done=!0,stdin.off("data",handleData),stdin.off("end",handleEnd),Promise.resolve({value:void 0,done:!0})}}}}}init_keys();function createSubscriberList(){return{input:new Set,paste:new Set}}await init_flexily_zero_adapter();import{jsxDEV as jsxDEV46}from"react/jsx-dev-runtime";var log14=createLogger15("silvery:render");class RenderHandle{promise;constructor(promise){this.promise=promise}then(onfulfilled,onrejected){return this.promise.then(onfulfilled,onrejected)}catch(onrejected){return this.promise.catch(onrejected)}finally(onfinally){return this.promise.finally(onfinally)}async run(){await(await this.promise).waitUntilExit()}}var instances=new Map;async function ensureLayoutEngineInitialized(engineType){if(isLayoutEngineInitialized()){log14.debug?.("Layout engine already initialized");return}log14.debug?.(`Initializing layout engine (${engineType??"default"})...`);let startTime=Date.now(),{ensureDefaultLayoutEngine:ensureDefaultLayoutEngine2}=await Promise.resolve().then(() => exports_layout_engine);await ensureDefaultLayoutEngine2(engineType),log14.debug?.(`Layout engine initialized in ${Date.now()-startTime}ms`)}function SilveryApp({children,onInputSubscribe,exitOnCtrlC,stdoutWrite,stdout,onExit,onPause,onResume,onScrollback,getRoot:getRootProp,handleFocusCycling=!0}){let subscribersRef=useRef26(null);if(!subscribersRef.current)subscribersRef.current=createSubscriberList();let subscribers=subscribersRef.current,handleExit=useCallback28((error)=>{onExit(error)},[onExit]),exitOnCtrlCRef=useRef26(exitOnCtrlC);exitOnCtrlCRef.current=exitOnCtrlC;let handleExitRef=useRef26(handleExit);handleExitRef.current=handleExit;let focusManagerRef=useRef26(null),getRootRef=useRef26(getRootProp);getRootRef.current=getRootProp;let handleFocusCyclingRef=useRef26(handleFocusCycling);handleFocusCyclingRef.current=handleFocusCycling;let handleChunkRef=useRef26(null);if(handleChunkRef.current===null){let processSingleKey=function(chunk){if(log14.debug?.(`processSingleKey: ${JSON.stringify(chunk)}`),chunk==="\x03"&&exitOnCtrlCRef.current){handleExitRef.current();return}if(handleFocusCyclingRef.current){let fm=focusManagerRef.current,root=getRootRef.current?.();if(fm&&root){let[,key2]=parseKey(chunk);if(key2.tab&&!key2.shift){fm.focusNext(root),reconciler.flushSyncWork();return}if(key2.tab&&key2.shift){fm.focusPrev(root),reconciler.flushSyncWork();return}if(key2.escape&&fm.activeElement){fm.blur(),reconciler.flushSyncWork();return}}}let[input,key]=parseKey(chunk);runWithDiscreteEvent(()=>{for(let handler of subscribers.input)handler(input,key)}),reconciler.flushSyncWork()};handleChunkRef.current=(rawChunk)=>{log14.debug?.(`handleChunk: ${JSON.stringify(rawChunk)}`);let pasteResult=parseBracketedPaste(rawChunk);if(pasteResult){for(let handler of subscribers.paste)handler(pasteResult.content);return}for(let keypress of splitRawInput(rawChunk))processSingleKey(keypress)}}let handleChunk=handleChunkRef.current;useEffect22(()=>{if(!onInputSubscribe)return;return onInputSubscribe(handleChunk)},[onInputSubscribe,handleChunk]);let stdoutContextValue=useMemo17(()=>({stdout,write:stdoutWrite,notifyScrollback:onScrollback}),[stdout,stdoutWrite,onScrollback]),runtimeContextValue=useMemo17(()=>({on(event,handler){if(event==="input"){let typed=handler;return subscribers.input.add(typed),()=>{subscribers.input.delete(typed)}}if(event==="paste"){let typed=handler;return subscribers.paste.add(typed),()=>{subscribers.paste.delete(typed)}}return()=>{}},emit(){},exit:handleExit,pause:onPause,resume:onResume}),[subscribers,handleExit,onPause,onResume]),focusManager=useMemo17(()=>createFocusManager(),[]);return focusManagerRef.current=focusManager,useEffect22(()=>{return setOnNodeRemoved((removedNode)=>focusManager.handleSubtreeRemoved(removedNode)),()=>setOnNodeRemoved(null)},[focusManager]),jsxDEV46(StdoutContext.Provider,{value:stdoutContextValue,children:jsxDEV46(StderrContext.Provider,{value:{stderr:process2.stderr,write:(data)=>{process2.stderr.write(data)}},children:jsxDEV46(FocusManagerContext.Provider,{value:focusManager,children:jsxDEV46(RuntimeContext.Provider,{value:runtimeContextValue,children},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)}class SilveryInstance{stdout;stdin;exitOnCtrlC;debug;alternateScreen;mode;nonTTYMode;scheduler=null;cursorStore;container=null;fiberRoot=null;lastElement=null;isUnmounted=!1;exitPromise=null;resolveExit=null;rejectExit=null;resizeCleanup=null;signalCleanup=null;outputGuard=null;constructor(options){log14.debug?.("SilveryInstance constructor start");let startTime=Date.now();if(this.stdout=options.stdout,this.stdin=options.stdin,this.exitOnCtrlC=options.exitOnCtrlC,this.debug=options.debug,this.alternateScreen=options.alternateScreen,this.mode=options.mode,this.nonTTYMode=options.nonTTYMode,this.exitPromise=new Promise((resolve,reject)=>{this.resolveExit=resolve,this.rejectExit=reject}),this.alternateScreen)this.stdout.write(enterAlternateScreen());if(this.stdout.isTTY)this.stdout.write(enableKittyKeyboard2());if(this.stdout.isTTY)enableBracketedPaste2(this.stdout);if(this.cursorStore=createCursorStore(),this.alternateScreen&&this.stdout===process2.stdout)this.outputGuard=createOutputGuard();this.container=createContainer(()=>{this.scheduler?.scheduleRender()}),this.fiberRoot=createFiberRoot(this.container),this.scheduler=new RenderScheduler({stdout:this.stdout,root:getContainerRoot(this.container),debug:this.debug,mode:this.mode,nonTTYMode:this.nonTTYMode,cursorAccessors:this.cursorStore.accessors,writeOutput:this.outputGuard?(data)=>this.outputGuard.writeStdout(data):void 0}),this.setupResizeListener(),this.setupSignalHandlers(),log14.debug?.(`SilveryInstance constructor complete in ${Date.now()-startTime}ms`)}render(element){log14.debug?.("SilveryInstance.render() start");let startTime=Date.now();if(this.isUnmounted||!this.fiberRoot)return;this.lastElement=element;let tree=jsxDEV46(CursorProvider,{store:this.cursorStore,children:jsxDEV46(SilveryApp,{onInputSubscribe:this.subscribeToInput,exitOnCtrlC:this.exitOnCtrlC,stdoutWrite:(data)=>{if(this.outputGuard)this.outputGuard.writeStdout(data);else this.stdout.write(data)},stdout:this.stdout,onExit:this.handleExit,onPause:this.pause,onResume:this.resume,onScrollback:this.handleScrollback,getRoot:()=>this.container?getContainerRoot(this.container):null,children:element},void 0,!1,void 0,this)},void 0,!1,void 0,this);log14.debug?.("SilveryInstance.render() calling updateContainerSync"),reconciler.updateContainerSync(tree,this.fiberRoot,null,null),log14.debug?.(`SilveryInstance.render() updateContainerSync complete in ${Date.now()-startTime}ms`),log14.debug?.("SilveryInstance.render() calling flushSyncWork");let flushStart=Date.now();reconciler.flushSyncWork(),log14.debug?.(`SilveryInstance.render() flushSyncWork complete in ${Date.now()-flushStart}ms (total: ${Date.now()-startTime}ms)`)}rerender=(element)=>{this.render(element)};flush=()=>{if(this.isUnmounted||!this.lastElement)return;this.render(this.lastElement),this.scheduler?.forceRender()};[Symbol.dispose]=()=>this.unmount();unmount=()=>{if(this.isUnmounted)return;if(this.isUnmounted=!0,this.scheduler?.forceRender(),this.resizeCleanup?.(),this.signalCleanup?.(),this.outputGuard)this.outputGuard.dispose(),this.outputGuard=null;if(this.stdout.isTTY)disableBracketedPaste2(this.stdout),this.stdout.write(disableKittyKeyboard2());if(this.stdout.isTTY)resetWindowTitle(this.stdout);if(this.alternateScreen)this.stdout.write(leaveAlternateScreen());else if(this.mode==="inline")this.stdout.write(`${ANSI.SYNC_END}${ANSI.CURSOR_SHOW}
115
+ `);else this.stdout.write(ANSI.SYNC_END);let{stdin}=this;if(stdin.removeAllListeners("readable"),stdin.removeAllListeners("data"),stdin.destroy(),typeof stdin.unref==="function")stdin.unref();if(this.fiberRoot)reconciler.updateContainer(null,this.fiberRoot,null,()=>{});this.scheduler?.dispose(),instances.delete(this.stdout),this.resolveExit?.()};waitUntilExit=()=>{return this.exitPromise??Promise.resolve()};clear=()=>{this.scheduler?.clear()};pause=()=>{this.scheduler?.pause()};resume=()=>{this.scheduler?.resume(),this.scheduler?.forceRender()};handleExit=(error)=>{if(this.isUnmounted)return;if(error)this.rejectExit?.(error);this.unmount()};handleScrollback=(lines)=>{this.scheduler?.addScrollbackLines(lines)};setupResizeListener(){let handleResize=()=>{this.scheduler?.clear(),this.scheduler?.forceRender()};this.stdout.on("resize",handleResize),this.resizeCleanup=()=>{this.stdout.off("resize",handleResize)}}setupSignalHandlers(){let handleSignal=()=>{this.unmount()};process2.on("SIGINT",handleSignal),process2.on("SIGTERM",handleSignal),this.signalCleanup=()=>{process2.off("SIGINT",handleSignal),process2.off("SIGTERM",handleSignal)}}subscribeToInput=(handler)=>{let{stdin}=this,isRawModeSupported=stdin.isTTY===!0;if(log14.debug?.(`subscribeToInput: stdin=${stdin===process2.stdin?"process.stdin":"other"}, isTTY=${stdin.isTTY}, isRawModeSupported=${isRawModeSupported}`),!isRawModeSupported)return log14.debug?.("subscribeToInput: raw mode not supported, skipping"),()=>{};let handleReadable=()=>{let chunk;while((chunk=stdin.read())!==null)log14.debug?.(`subscribeToInput: stdin.read() returned: ${JSON.stringify(chunk)}`),handler(chunk)};return stdin.setEncoding("utf8"),stdin.ref(),stdin.setRawMode(!0),stdin.on("readable",handleReadable),log14.debug?.(`subscribeToInput: enabled raw mode, stdin.isRaw=${stdin.isRaw}`),()=>{log14.debug?.("subscribeToInput: cleanup — disabling raw mode"),stdin.setRawMode(!1),stdin.off("readable",handleReadable),stdin.unref()}}}function render(element,termOrDef,options){return new RenderHandle(renderAsync(element,termOrDef,options))}async function renderAsync(element,termOrDef,options){let resolved,term2;if(!termOrDef)resolved=resolveTermDef({}),term2=createTerm({color:resolved.colors??void 0});else if(isTerm(termOrDef))resolved=resolveFromTerm(termOrDef),term2=termOrDef;else if(isTermDef(termOrDef))resolved=resolveTermDef(termOrDef),term2=createTerm({stdout:termOrDef.stdout,stdin:termOrDef.stdin,color:resolved.colors??void 0});else throw Error("Invalid second argument: expected Term, TermDef, or undefined");let mergedOptions={...options,stdout:options?.stdout??resolved.stdout??term2.stdout,stdin:options?.stdin??(resolved.isStatic?void 0:term2.stdin)};return renderImpl(element,mergedOptions,term2,resolved)}async function renderImpl(element,options,term2,resolved){log14.debug?.(`render() called, isStatic=${resolved.isStatic}`);let renderStart=Date.now();if(await ensureLayoutEngineInitialized(options.layoutEngine),log14.debug?.(`render(): layout engine ready in ${Date.now()-renderStart}ms`),process2.env.DEBUG_DEVTOOLS){let{autoConnectDevTools:autoConnectDevTools2}=await Promise.resolve().then(() => (init_devtools(),exports_devtools));await autoConnectDevTools2()}if(resolved.isStatic)return renderStaticImpl(element,term2,resolved);let mode=options.mode??"fullscreen",resolvedOptions={stdout:options.stdout??process2.stdout,stdin:options.stdin??process2.stdin,exitOnCtrlC:options.exitOnCtrlC??!0,debug:options.debug??!1,patchConsole:options.patchConsole??!0,alternateScreen:options.alternateScreen??mode==="fullscreen",mode,nonTTYMode:options.nonTTYMode??"auto"},instance=instances.get(resolvedOptions.stdout);if(!instance)log14.debug?.("render(): creating new SilveryInstance"),instance=new SilveryInstance(resolvedOptions),instances.set(resolvedOptions.stdout,instance),log14.debug?.(`render(): SilveryInstance created in ${Date.now()-renderStart}ms`);let wrappedElement=jsxDEV46(TermContext.Provider,{value:term2,children:element},void 0,!1,void 0,this);return log14.debug?.("render(): calling instance.render()"),instance.render(wrappedElement),log14.debug?.(`render(): instance.render() complete, total: ${Date.now()-renderStart}ms`),{rerender:(newElement)=>instance.rerender(jsxDEV46(TermContext.Provider,{value:term2,children:newElement},void 0,!1,void 0,this)),unmount:instance.unmount,[Symbol.dispose]:instance.unmount,waitUntilExit:instance.waitUntilExit,clear:instance.clear,flush:instance.flush,pause:instance.pause,resume:instance.resume}}async function renderStaticImpl(element,term2,resolved){log14.debug?.(`renderStatic() called, dimensions: ${resolved.width}x${resolved.height}`);let{renderStringSync:renderStringSync2}=await Promise.resolve().then(() => (init_render_string(),exports_render_string)),wrappedElement=jsxDEV46(TermContext.Provider,{value:term2,children:element},void 0,!1,void 0,this),output=renderStringSync2(wrappedElement,{width:resolved.width,height:resolved.height,plain:resolved.colors===null});if(resolved.stdout)resolved.stdout.write(output),resolved.stdout.write(`
112
116
  `);let lastFrame=output;return{rerender:(newElement)=>{let newWrapped=jsxDEV46(TermContext.Provider,{value:term2,children:newElement},void 0,!1,void 0,this);if(lastFrame=renderStringSync2(newWrapped,{width:resolved.width,height:resolved.height,plain:resolved.colors===null}),resolved.stdout)resolved.stdout.write(lastFrame),resolved.stdout.write(`
113
117
  `)},unmount:()=>{},[Symbol.dispose](){},waitUntilExit:()=>Promise.resolve(),clear:()=>{},pause:()=>{},resume:()=>{},get lastFrame(){return lastFrame}}}function renderSync(element,termOrDef,options){if(!isLayoutEngineInitialized())throw Error("Layout engine is not initialized. Call render() (async) first, or initialize manually with setLayoutEngine().");let resolved,term2;if(!termOrDef)resolved=resolveTermDef({}),term2=createTerm({color:resolved.colors??void 0});else if(isTerm(termOrDef))resolved=resolveFromTerm(termOrDef),term2=termOrDef;else if(isTermDef(termOrDef))resolved=resolveTermDef(termOrDef),term2=createTerm({stdout:termOrDef.stdout,stdin:termOrDef.stdin,color:resolved.colors??void 0});else throw Error("Invalid second argument: expected Term, TermDef, or undefined");if(resolved.isStatic){let wrappedElement2=jsxDEV46(TermContext.Provider,{value:term2,children:element},void 0,!1,void 0,this),lastFrame=renderStringSync(wrappedElement2,{width:resolved.width,height:resolved.height,plain:resolved.colors===null});if(resolved.stdout)resolved.stdout.write(lastFrame),resolved.stdout.write(`
114
118
  `);return{rerender:()=>{},unmount:()=>{},[Symbol.dispose](){},waitUntilExit:()=>Promise.resolve(),clear:()=>{},flush:()=>{},pause:()=>{},resume:()=>{}}}let mergedOptions={...options,stdout:options?.stdout??resolved.stdout??term2.stdout,stdin:options?.stdin??term2.stdin},mode=mergedOptions.mode??"fullscreen",resolvedOptions={stdout:mergedOptions.stdout??process2.stdout,stdin:mergedOptions.stdin??process2.stdin,exitOnCtrlC:mergedOptions.exitOnCtrlC??!0,debug:mergedOptions.debug??!1,patchConsole:mergedOptions.patchConsole??!0,alternateScreen:mergedOptions.alternateScreen??mode==="fullscreen",mode,nonTTYMode:mergedOptions.nonTTYMode??"auto"},instance=instances.get(resolvedOptions.stdout);if(!instance)instance=new SilveryInstance(resolvedOptions),instances.set(resolvedOptions.stdout,instance);let wrappedElement=jsxDEV46(TermContext.Provider,{value:term2,children:element},void 0,!1,void 0,this);return instance.render(wrappedElement),{rerender:(newElement)=>instance.rerender(jsxDEV46(TermContext.Provider,{value:term2,children:newElement},void 0,!1,void 0,this)),unmount:instance.unmount,[Symbol.dispose]:instance.unmount,waitUntilExit:instance.waitUntilExit,clear:instance.clear,flush:instance.flush,pause:instance.pause,resume:instance.resume}}async function renderStatic(element,options){await ensureLayoutEngineInitialized(options?.layoutEngine);let{renderStringSync:renderStringSync2}=await Promise.resolve().then(() => (init_render_string(),exports_render_string));return renderStringSync2(element,options)}init_render_string();function resolveNode2(nodeOrHandle){if(!nodeOrHandle)return null;if(typeof nodeOrHandle.getNode==="function")return nodeOrHandle.getNode();return nodeOrHandle}function measureElement(nodeOrHandle){let node=resolveNode2(nodeOrHandle);if(!node)return{width:0,height:0};if(node.boxRect)return{width:node.boxRect.width,height:node.boxRect.height};let width=node.layoutNode?.getComputedWidth()??0,height=node.layoutNode?.getComputedHeight()??0;return{width:Number.isNaN(width)?0:width,height:Number.isNaN(height)?0:height}}import React24 from"react";function renderScreenReaderOutput(node){return walkNode(node,"row")}function walkNode(node,parentDirection){if(node==null||typeof node==="boolean")return"";if(typeof node==="string"||typeof node==="number")return String(node);if(Array.isArray(node)){let parts=node.map((child)=>walkNode(child,parentDirection)).filter((s)=>s!==""),sep=parentDirection==="column"?`
@@ -261,6 +265,6 @@ ${details}`+(styleMismatches.length>5?`
261
265
  ${violations.length} violation(s):
262
266
  ${details}`+(violations.length>10?`
263
267
  ... and ${violations.length-10} more`:"")+(screenshotPath?`
264
- Screenshot saved: ${screenshotPath}`:""))}}};return Object.defineProperties(wrapped,{id:{value:command.id,enumerable:!0},name:{value:command.name,enumerable:!0},help:{value:command.help,enumerable:!0},keys:{value:command.keys,enumerable:!0}}),wrapped},has(target,prop){return Reflect.has(target,prop)},ownKeys(target){return Reflect.ownKeys(target)},getOwnPropertyDescriptor(target,prop){return Reflect.getOwnPropertyDescriptor(target,prop)}});return Object.assign(app,{cmd:wrappedCmd})}init_context();init_keys();import{useCallback as useCallback30,useId,useLayoutEffect as useLayoutEffect7,useMemo as useMemo19,useRef as useRef28}from"react";import{jsxDEV as jsxDEV47}from"react/jsx-dev-runtime";function toRawData(input,key){let name=keyToName(key);if(name){let mods=[];if(key.ctrl)mods.push("Control");if(key.shift)mods.push("Shift");if(key.meta)mods.push("Meta");if(key.super)mods.push("Super");if(key.hyper)mods.push("Hyper");return mods.push(name),keyToAnsi(mods.join("+"))}if(key.ctrl)return keyToAnsi(`Control+${input}`);return input}function InputBoundary({active,onEscape,exitKey="Escape",children}){let subscribersRef=useRef28(null);if(!subscribersRef.current)subscribersRef.current=createSubscriberList();let subscribers=subscribersRef.current,activeRef=useRef28(active);activeRef.current=active;let onEscapeRef=useRef28(onEscape);onEscapeRef.current=onEscape;let exitKeyRef=useRef28(exitKey);exitKeyRef.current=exitKey;let handler=useCallback30((input,key)=>{if(!activeRef.current)return!1;let currentExitKey=exitKeyRef.current;if(currentExitKey!==null){let name=keyToName(key);if(name===currentExitKey||!name&&input===currentExitKey)return onEscapeRef.current?.(),!0}let raw=toRawData(input,key),[parsedInput,parsedKey]=parseKey(raw);for(let h of subscribers.input)h(parsedInput,parsedKey);return!0},[subscribers]),layerId=useId();useInputLayer(`input-boundary-${layerId}`,handler);let runtimeContextValue=useMemo19(()=>({on(event,handler2){if(event==="input"){let typed=handler2;return subscribers.input.add(typed),()=>{subscribers.input.delete(typed)}}if(event==="paste"){let typed=handler2;return subscribers.paste.add(typed),()=>{subscribers.paste.delete(typed)}}return()=>{}},emit(){},exit:()=>{}}),[subscribers]);return useLayoutEffect7(()=>{return()=>{subscribers.input.clear(),subscribers.paste.clear()}},[subscribers]),jsxDEV47(RuntimeContext.Provider,{value:runtimeContextValue,children:jsxDEV47(InputLayerProvider,{children},void 0,!1,void 0,this)},void 0,!1,void 0,this)}var easings={linear:(t)=>t,ease:(t)=>t<0.5?2*t*t:-1+(4-2*t)*t,easeIn:(t)=>t*t,easeOut:(t)=>t*(2-t),easeInOut:(t)=>t<0.5?2*t*t:-1+(4-2*t)*t,easeInCubic:(t)=>t*t*t,easeOutCubic:(t)=>--t*t*t+1};function resolveEasing(easing){return typeof easing==="function"?easing:easings[easing]}import{useState as useState21,useEffect as useEffect24,useRef as useRef29,useCallback as useCallback31}from"react";var TICK_MS=33;function useAnimation2(options){let{duration,easing="linear",delay=0,onComplete,enabled=!0}=options,[value,setValue]=useState21(0),[isAnimating,setIsAnimating]=useState21(!1),startTimeRef=useRef29(0),intervalRef=useRef29(null),onCompleteRef=useRef29(onComplete);onCompleteRef.current=onComplete;let epochRef=useRef29(0),easingFn=resolveEasing(easing),stopInterval=useCallback31(()=>{if(intervalRef.current!==null)clearInterval(intervalRef.current),intervalRef.current=null},[]),startAnimation=useCallback31(()=>{stopInterval(),epochRef.current++;let epoch=epochRef.current;setValue(0),setIsAnimating(!0);let begin=()=>{if(epochRef.current!==epoch)return;startTimeRef.current=performance.now(),intervalRef.current=setInterval(()=>{if(epochRef.current!==epoch)return;let elapsed=performance.now()-startTimeRef.current,raw=Math.min(elapsed/duration,1),eased=easingFn(raw);if(setValue(eased),raw>=1)stopInterval(),setIsAnimating(!1),onCompleteRef.current?.()},TICK_MS)};if(delay>0)setTimeout(()=>begin(),delay);else begin()},[duration,delay,easingFn,stopInterval]);useEffect24(()=>{if(!enabled){stopInterval(),setValue(0),setIsAnimating(!1);return}return startAnimation(),()=>{stopInterval()}},[enabled,startAnimation,stopInterval]);let reset=useCallback31(()=>{startAnimation()},[startAnimation]);return{value,isAnimating,reset}}import{useState as useState22,useEffect as useEffect25,useRef as useRef30}from"react";var TICK_MS2=33;function useTransition(targetValue,options){let{duration=300,easing="easeOut"}=options??{},[currentValue,setCurrentValue]=useState22(targetValue),fromRef=useRef30(targetValue),toRef=useRef30(targetValue),startTimeRef=useRef30(0),intervalRef=useRef30(null),isFirstRef=useRef30(!0),easingFn=resolveEasing(easing);return useEffect25(()=>{if(isFirstRef.current){isFirstRef.current=!1;return}if(targetValue===toRef.current)return;if(fromRef.current=currentValue,toRef.current=targetValue,startTimeRef.current=performance.now(),intervalRef.current!==null)clearInterval(intervalRef.current);return intervalRef.current=setInterval(()=>{let elapsed=performance.now()-startTimeRef.current,raw=Math.min(elapsed/duration,1),eased=easingFn(raw),interpolated=fromRef.current+(toRef.current-fromRef.current)*eased;if(setCurrentValue(interpolated),raw>=1){if(setCurrentValue(toRef.current),intervalRef.current!==null)clearInterval(intervalRef.current),intervalRef.current=null}},TICK_MS2),()=>{if(intervalRef.current!==null)clearInterval(intervalRef.current),intervalRef.current=null}},[targetValue,duration,easingFn]),currentValue}import{useEffect as useEffect26,useRef as useRef31}from"react";function useInterval(callback,ms,enabled=!0){let callbackRef=useRef31(callback);callbackRef.current=callback,useEffect26(()=>{if(!enabled)return;let id=setInterval(()=>{callbackRef.current()},ms);return()=>{clearInterval(id)}},[ms,enabled])}import{useCallback as useCallback32,useEffect as useEffect27,useRef as useRef32}from"react";function useTimeout(callback,ms,enabled=!0){let callbackRef=useRef32(callback);callbackRef.current=callback;let timerRef=useRef32(null),clear=useCallback32(()=>{if(timerRef.current!==null)clearTimeout(timerRef.current),timerRef.current=null},[]),reset=useCallback32(()=>{if(clear(),enabled)timerRef.current=setTimeout(()=>{timerRef.current=null,callbackRef.current()},ms)},[ms,enabled,clear]);return useEffect27(()=>{if(!enabled){clear();return}return timerRef.current=setTimeout(()=>{timerRef.current=null,callbackRef.current()},ms),clear},[ms,enabled,clear]),{reset,clear}}import{useRef as useRef33}from"react";function useLatest(value){let ref=useRef33(value);return ref.current=value,ref}import{useCallback as useCallback33,useEffect as useEffect28,useRef as useRef34,useReducer as useReducer4}from"react";function collect(result){if(Array.isArray(result))return result;return[result,[]]}function delay(ms,msg,id){return{type:"delay",ms,msg,id}}function interval(ms,msg,id){return{type:"interval",ms,msg,id}}function cancel(id){return{type:"cancel",id}}var fx={delay,interval,cancel};function createTimerRunners(){let timers=new Map,nextAnon=0;function clearTimer(id){let existing=timers.get(id);if(existing!==void 0)clearTimeout(existing),clearInterval(existing),timers.delete(id)}let runners={delay(effect2,dispatch){let id=effect2.id??`__anon_${nextAnon++}`;clearTimer(id);let timer=setTimeout(()=>{timers.delete(id),dispatch(effect2.msg)},effect2.ms);timers.set(id,timer)},interval(effect2,dispatch){clearTimer(effect2.id);let timer=setInterval(()=>{dispatch(effect2.msg)},effect2.ms);timers.set(effect2.id,timer)},cancel(effect2){clearTimer(effect2.id)}};function cleanup(){for(let[id]of timers)clearTimer(id)}return{runners,cleanup}}function useTea(initialState,update,customRunners){let timerRef=useRef34(null);if(timerRef.current===null)timerRef.current=createTimerRunners();let{runners:timerRunners,cleanup}=timerRef.current,customRunnersRef=useRef34(customRunners);customRunnersRef.current=customRunners;let pendingEffectsRef=useRef34([]),[state,reactDispatch]=useReducer4((prevState,msg)=>{let result=update(prevState,msg),[newState,effects]=collect(result);if(effects.length>0)pendingEffectsRef.current.push(...effects);return newState},void 0,()=>typeof initialState==="function"?initialState():initialState),sendRef=useRef34(()=>{}),executeEffects=useCallback33(()=>{if(pendingEffectsRef.current.length===0)return;let effects=pendingEffectsRef.current.splice(0);for(let effect2 of effects){let timerRunner=timerRunners[effect2.type];if(timerRunner){timerRunner(effect2,sendRef.current);continue}let customRunner=customRunnersRef.current?.[effect2.type];if(customRunner)customRunner(effect2,sendRef.current)}},[timerRunners]),send=useCallback33((msg)=>{reactDispatch(msg),queueMicrotask(executeEffects)},[reactDispatch,executeEffects]);return sendRef.current=send,useEffect28(()=>{executeEffects()},[executeEffects]),useEffect28(()=>cleanup,[cleanup]),[state,send]}init_keys();init_ag();init_ag();init_output_phase();init_ag();init_reconciler();init_context();import React25 from"react";init_keys();init_buffer();init_pipeline2();init_output_phase();init_text_sizing();init_src2();init_mouse();init_unicode();init_unicode();init_errors();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_unicode();init_keys();import React26,{createContext as createContext13,Fragment as Fragment4}from"react";var InkCursorStoreCtx=createContext13(null);import React27,{createContext as createContext14,Fragment as Fragment5,useCallback as useCallback34,useEffect as useEffect29,useMemo as useMemo20,useState as useState23}from"react";var InkFocusContext=createContext14({activeId:void 0,isFocusEnabled:!0,add(){},remove(){},activate(){},deactivate(){},enableFocus(){},disableFocus(){},focusNext(){},focusPrevious(){},focus(){},blur(){}});init_term_provider();init_ansi2();init_buffer();init_context();init_pipeline2();init_reconciler();import React28 from"react";init_pipeline2();init_buffer();init_output_phase();import process3 from"node:process";import React29,{createContext as createContext15,useContext as useContext37,useEffect as useEffect30,useRef as useRef35}from"react";init_esm();init_ansi2();init_context();init_pipeline2();init_ag();init_text_sizing();init_reconciler();init_reconciler();init_keys();init_keys2();init_term_provider();init_output_guard();import{createLogger as createLogger17}from"loggily";var perfLog=createLogger17("silvery:perf");import{createLogger as createLogger18}from"loggily";import{jsxDEV as jsxDEV48}from"react/jsx-dev-runtime";var log14=createLogger18("silvery:app"),ENV=typeof process3<"u"?process3.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}})();var StoreContext=createContext15(null);init_context();import{useContext as useContext38,useEffect as useEffect31,useRef as useRef36}from"react";import{jsxDEV as jsxDEV49}from"react/jsx-dev-runtime";init_keys2();import{jsxDEV as jsxDEV50}from"react/jsx-dev-runtime";function ReactiveThemeInner({dark=defaultDarkTheme,light=defaultLightTheme,initial,children}){let scheme=useColorScheme(),theme2;if(scheme==="light")theme2=light;else if(scheme==="dark")theme2=dark;else theme2=initial??dark;return jsxDEV50(ThemeProvider,{theme:theme2,children},void 0,!1,void 0,this)}function ReactiveThemeProvider(props){return jsxDEV50(ReactiveThemeInner,{...props},void 0,!1,void 0,this)}var VERSION="0.0.1";function render3(element,termOrDef,options){if(!termOrDef&&process.stdin?.isTTY&&process.stdout?.isTTY){let ttyDef={stdin:process.stdin,stdout:process.stdout};return render(element,ttyDef,options)}return render(element,termOrDef,options)}export{writeTextTruncated,writeTextToBuffer,writeLinesToBuffer,wrapText,withRender,withMeasurer,withKeybindings,withDiagnostics,withCommands,useWindowSize,useVirtualizer,useTransition2 as useTransition,useToast,useTimeout,useTheme,useTextArea,useTerminalFocused,useTerm,useTea,useStdout,useStderr,useSelection,useSearchOptional,useSearch,useScrollRect,useScreenRect,useRuntime,useReadline,usePositionRegistry,usePasteEvents,usePaste,useMouseCursor,useModifierKeys,useListItem,useLatest,useInterval,useInteractiveState,useInputLayerContext,useInputLayer,useInput,useId2 as useId,useHitRegistry,useHitRegionCallback,useHitRegion,useGridPosition,useFocusable,useFocusWithin,useFocusManager,useFocus,useFindState,useExit,useEditContext,useDragState,useDeferredValue,useCursor,useCopyModeState,useConsole,useColorScheme,useBoxRect,useBoxMetrics,useApp,useAnimation2 as useAnimation,useTransition as useAnimatedTransition,truncateText,truncateAnsi,textSized,term,swapPanes,supportsScrollRegions,subscribeCursor,stripAnsi2 as stripAnsiUnicode,stripAnsi2 as stripAnsi,splitPane,splitGraphemes,sliceByWidthRange,sliceByWidthFromEnd,sliceByWidth,shallow,setWindowTitle,setWindowAndIconTitle,setTextSizingEnabled,setTextEmojiWide,setScrollRegion2 as setScrollRegion,setPaletteColor,setOutputCaps,setMouseCursorShape,setLayoutEngine,setForegroundColor,setCursorStyle,setCursorColor,setBackgroundColor,scrollUp2 as scrollUp,scrollDown2 as scrollDown,runWithMeasurer,runTermtest,rowColToCursor,resolveThemeColor,resolveNonTTYMode,resolveEasing,resizeSplit,resetWindowTitle,resetScrollRegion2 as resetScrollRegion,resetMouseCursorShape,resetHitRegionIdCounter,resetForegroundColor,resetCursorStyle,resetCursorState,resetCursorColor,resetBackgroundColor,requestClipboard,reportDirectory,renderSync,renderStringSync,renderString,renderStatic,renderScreenReaderOutput,render3 as render,removePane,queryTextAreaSize,queryTextAreaPixels,queryTertiaryDA,queryTerminalVersion,querySecondaryDA,queryPrimaryDA,queryPaletteColor,queryMultiplePaletteColors,queryModes,queryMode,queryKittyKeyboard,queryForegroundColor,queryDeviceAttributes,queryCursorPosition,queryCursorFromStdio,queryCursorColor,queryCellSize,queryBackgroundColor,processMouseEvent,patchConsole,parsePaletteResponse,parseMouseSequence,parseKeypress,parseKey,parseHotkey,parseFocusEvent,parseClipboardResponse,parseBracketedPaste,parseAnsiText,padText,notifyKitty,notifyITerm2,notify,normalizeText,moveCursor2 as moveCursor,mergeTextOps,measureText,measureElement,matchHotkey,lastModifierState,keyToName,keyToModifiers,isZeroWidthGrapheme,isWideGrapheme,isTextSizingLikelySupported,isTextSizingEnabled,isTerm,isTTY,isSixelSupported,isPrivateUseArea,isMouseSequence,isLikelyEmoji,isLayoutEngineInitialized,isKittyGraphicsSupported,isInspectorEnabled,isDevToolsConnected,isCJK,invertTextOp,inspectTree,inspectFrame,injectDOMStyles,initYogaEngine,hitTest,hasZeroWidthCharacters,hasWideCharacters,hasAnsi,graphemeWidth,graphemeCount,getWrappedLines,getThemeByName,getTabOrder2 as getTabOrder,getTabOrder as getSplitTabOrder,getPaneIds,getModifierState,getInternalClipboard,getFirstCodePoint,getExplicitFocusLink,getCursorState,generateTheme,fx,formatTitleWithHotkey,findSpatialTarget,findFocusableAncestor,findEnclosingScope,findByTestID,findAdjacentPane,ensureEmojiPresentation,encodeSixel,encodeKittyImage,enableMouse2 as enableMouse,enableKittyKeyboard2 as enableKittyKeyboard,enableInspector,enableFocusReporting,enableBracketedPaste2 as enableBracketedPaste,emptyKey,easings,displayWidthAnsi,displayWidth,dispatchMouseEvent,dispatchKeyEvent,dispatchFocusEvent,disableMouse2 as disableMouse,disableKittyKeyboard2 as disableKittyKeyboard,disableInspector,disableFocusReporting,disableBracketedPaste2 as disableBracketedPaste,detectTheme2 as detectTheme,detectTextSizingSupport,detectTerminalCaps,detectKittySupport,detectKittyFromStdio,detectColorScheme,deriveTheme,deleteKittyImage,defaultLightTheme,defaultDarkTheme,defaultCaps,cursorToRowCol,cursorMoveUp,cursorMoveDown,createYogaEngine,createWidthMeasurer,createWheelEvent,createTermEditContext,createTerm,createPositionRegistry,createPipeline,createPasteEvent,createOutputPhase,createMouseEventProcessor,createMouseEvent,createMeasurer,createLeaf,createKeyEvent,createInputEvents,createFocusManager,createFocusEvent,createFlexilyZeroEngine as createFlexilyEngine,createDoubleClickState,createDOMAdapter,createCursorStore,createCopyProvider,createCanvasAdapter,countVisualLines,copyToClipboard,constrainText,connectDevTools,computeEnterLeave,collect,clampScroll,checkDoubleClick,calcEdgeBasedScrollOffset,builtinThemes,autoEnableInspector,applyTextOp,ansi16LightTheme2 as ansi16LightTheme,ansi16DarkTheme2 as ansi16DarkTheme,activeEditTargetRef,activeEditContextRef,Z_INDEX,YogaLayoutEngine,VirtualTerminal,VERSION,UL,TreeView,Transform,Tooltip,Toggle,ToastItem,ToastContainer,ThemeProvider,TextInput,TextArea,Text,TermContext,Tabs,Table,TabPanel,TabList,Tab,TERMTEST_SECTIONS,Strong,StderrContext,Static,SplitView,Spinner,Spacer,Small,Skeleton,SilveryErrorBoundary,SelectList,SearchProvider,SearchBar,Screen,RuntimeContext,ReactiveThemeProvider,ProgressBar,PositionRegistryProvider,PickerList,PickerDialog,PasteProvider,PASTE_START,PASTE_END,P,OSC133,OL,Newline,Muted,ModalDialog,ListView,Link,Lead,LI,KittyFlags,Kbd,InputLayerProvider,InputLayerContext,InputBoundary,IncrementalRenderMismatchError,Image,HorizontalVirtualList,HitRegistryContext,HitRegistry,Heading,HR,H3,H2,H1,GridCell,FormField,Form,FocusManagerContext,FlexilyZeroLayoutEngine as FlexilyLayoutEngine,Fill,ErrorBoundary,Em,EditContextDisplay,Divider,DecMode,DOMRenderBuffer,CursorProvider,CursorLine,Console,CommandPalette,CodeBlock,Code,CapabilityRegistryContext,CanvasRenderBuffer,CacheBackendContext,Button,Breadcrumb,Box,Blockquote,Badge,BEL,ANSI};
268
+ Screenshot saved: ${screenshotPath}`:""))}}};return Object.defineProperties(wrapped,{id:{value:command.id,enumerable:!0},name:{value:command.name,enumerable:!0},help:{value:command.help,enumerable:!0},keys:{value:command.keys,enumerable:!0}}),wrapped},has(target,prop){return Reflect.has(target,prop)},ownKeys(target){return Reflect.ownKeys(target)},getOwnPropertyDescriptor(target,prop){return Reflect.getOwnPropertyDescriptor(target,prop)}});return Object.assign(app,{cmd:wrappedCmd})}init_context();init_keys();import{useCallback as useCallback30,useId,useLayoutEffect as useLayoutEffect7,useMemo as useMemo19,useRef as useRef28}from"react";import{jsxDEV as jsxDEV47}from"react/jsx-dev-runtime";function toRawData(input,key){let name=keyToName(key);if(name){let mods=[];if(key.ctrl)mods.push("Control");if(key.shift)mods.push("Shift");if(key.meta)mods.push("Meta");if(key.super)mods.push("Super");if(key.hyper)mods.push("Hyper");return mods.push(name),keyToAnsi(mods.join("+"))}if(key.ctrl)return keyToAnsi(`Control+${input}`);return input}function InputBoundary({active,onEscape,exitKey="Escape",children}){let subscribersRef=useRef28(null);if(!subscribersRef.current)subscribersRef.current=createSubscriberList();let subscribers=subscribersRef.current,activeRef=useRef28(active);activeRef.current=active;let onEscapeRef=useRef28(onEscape);onEscapeRef.current=onEscape;let exitKeyRef=useRef28(exitKey);exitKeyRef.current=exitKey;let handler=useCallback30((input,key)=>{if(!activeRef.current)return!1;let currentExitKey=exitKeyRef.current;if(currentExitKey!==null){let name=keyToName(key);if(name===currentExitKey||!name&&input===currentExitKey)return onEscapeRef.current?.(),!0}let raw=toRawData(input,key),[parsedInput,parsedKey]=parseKey(raw);for(let h of subscribers.input)h(parsedInput,parsedKey);return!0},[subscribers]),layerId=useId();useInputLayer(`input-boundary-${layerId}`,handler);let runtimeContextValue=useMemo19(()=>({on(event,handler2){if(event==="input"){let typed=handler2;return subscribers.input.add(typed),()=>{subscribers.input.delete(typed)}}if(event==="paste"){let typed=handler2;return subscribers.paste.add(typed),()=>{subscribers.paste.delete(typed)}}return()=>{}},emit(){},exit:()=>{}}),[subscribers]);return useLayoutEffect7(()=>{return()=>{subscribers.input.clear(),subscribers.paste.clear()}},[subscribers]),jsxDEV47(RuntimeContext.Provider,{value:runtimeContextValue,children:jsxDEV47(InputLayerProvider,{children},void 0,!1,void 0,this)},void 0,!1,void 0,this)}var easings={linear:(t)=>t,ease:(t)=>t<0.5?2*t*t:-1+(4-2*t)*t,easeIn:(t)=>t*t,easeOut:(t)=>t*(2-t),easeInOut:(t)=>t<0.5?2*t*t:-1+(4-2*t)*t,easeInCubic:(t)=>t*t*t,easeOutCubic:(t)=>--t*t*t+1};function resolveEasing(easing){return typeof easing==="function"?easing:easings[easing]}import{useState as useState21,useEffect as useEffect24,useRef as useRef29,useCallback as useCallback31}from"react";var TICK_MS=33;function useAnimation2(options){let{duration,easing="linear",delay=0,onComplete,enabled=!0}=options,[value,setValue]=useState21(0),[isAnimating,setIsAnimating]=useState21(!1),startTimeRef=useRef29(0),intervalRef=useRef29(null),onCompleteRef=useRef29(onComplete);onCompleteRef.current=onComplete;let epochRef=useRef29(0),easingFn=resolveEasing(easing),stopInterval=useCallback31(()=>{if(intervalRef.current!==null)clearInterval(intervalRef.current),intervalRef.current=null},[]),startAnimation=useCallback31(()=>{stopInterval(),epochRef.current++;let epoch=epochRef.current;setValue(0),setIsAnimating(!0);let begin=()=>{if(epochRef.current!==epoch)return;startTimeRef.current=performance.now(),intervalRef.current=setInterval(()=>{if(epochRef.current!==epoch)return;let elapsed=performance.now()-startTimeRef.current,raw=Math.min(elapsed/duration,1),eased=easingFn(raw);if(setValue(eased),raw>=1)stopInterval(),setIsAnimating(!1),onCompleteRef.current?.()},TICK_MS)};if(delay>0)setTimeout(()=>begin(),delay);else begin()},[duration,delay,easingFn,stopInterval]);useEffect24(()=>{if(!enabled){stopInterval(),setValue(0),setIsAnimating(!1);return}return startAnimation(),()=>{stopInterval()}},[enabled,startAnimation,stopInterval]);let reset=useCallback31(()=>{startAnimation()},[startAnimation]);return{value,isAnimating,reset}}import{useState as useState22,useEffect as useEffect25,useRef as useRef30}from"react";var TICK_MS2=33;function useTransition(targetValue,options){let{duration=300,easing="easeOut"}=options??{},[currentValue,setCurrentValue]=useState22(targetValue),fromRef=useRef30(targetValue),toRef=useRef30(targetValue),startTimeRef=useRef30(0),intervalRef=useRef30(null),isFirstRef=useRef30(!0),easingFn=resolveEasing(easing);return useEffect25(()=>{if(isFirstRef.current){isFirstRef.current=!1;return}if(targetValue===toRef.current)return;if(fromRef.current=currentValue,toRef.current=targetValue,startTimeRef.current=performance.now(),intervalRef.current!==null)clearInterval(intervalRef.current);return intervalRef.current=setInterval(()=>{let elapsed=performance.now()-startTimeRef.current,raw=Math.min(elapsed/duration,1),eased=easingFn(raw),interpolated=fromRef.current+(toRef.current-fromRef.current)*eased;if(setCurrentValue(interpolated),raw>=1){if(setCurrentValue(toRef.current),intervalRef.current!==null)clearInterval(intervalRef.current),intervalRef.current=null}},TICK_MS2),()=>{if(intervalRef.current!==null)clearInterval(intervalRef.current),intervalRef.current=null}},[targetValue,duration,easingFn]),currentValue}import{useEffect as useEffect26,useRef as useRef31}from"react";function useInterval(callback,ms,enabled=!0){let callbackRef=useRef31(callback);callbackRef.current=callback,useEffect26(()=>{if(!enabled)return;let id=setInterval(()=>{callbackRef.current()},ms);return()=>{clearInterval(id)}},[ms,enabled])}import{useCallback as useCallback32,useEffect as useEffect27,useRef as useRef32}from"react";function useTimeout(callback,ms,enabled=!0){let callbackRef=useRef32(callback);callbackRef.current=callback;let timerRef=useRef32(null),clear=useCallback32(()=>{if(timerRef.current!==null)clearTimeout(timerRef.current),timerRef.current=null},[]),reset=useCallback32(()=>{if(clear(),enabled)timerRef.current=setTimeout(()=>{timerRef.current=null,callbackRef.current()},ms)},[ms,enabled,clear]);return useEffect27(()=>{if(!enabled){clear();return}return timerRef.current=setTimeout(()=>{timerRef.current=null,callbackRef.current()},ms),clear},[ms,enabled,clear]),{reset,clear}}import{useRef as useRef33}from"react";function useLatest(value){let ref=useRef33(value);return ref.current=value,ref}import{useCallback as useCallback33,useEffect as useEffect28,useRef as useRef34,useReducer as useReducer4}from"react";function collect(result){if(Array.isArray(result))return result;return[result,[]]}function delay(ms,msg,id){return{type:"delay",ms,msg,id}}function interval(ms,msg,id){return{type:"interval",ms,msg,id}}function cancel(id){return{type:"cancel",id}}var fx={delay,interval,cancel};function createTimerRunners(){let timers=new Map,nextAnon=0;function clearTimer(id){let existing=timers.get(id);if(existing!==void 0)clearTimeout(existing),clearInterval(existing),timers.delete(id)}let runners={delay(effect2,dispatch){let id=effect2.id??`__anon_${nextAnon++}`;clearTimer(id);let timer=setTimeout(()=>{timers.delete(id),dispatch(effect2.msg)},effect2.ms);timers.set(id,timer)},interval(effect2,dispatch){clearTimer(effect2.id);let timer=setInterval(()=>{dispatch(effect2.msg)},effect2.ms);timers.set(effect2.id,timer)},cancel(effect2){clearTimer(effect2.id)}};function cleanup(){for(let[id]of timers)clearTimer(id)}return{runners,cleanup}}function useTea(initialState,update,customRunners){let timerRef=useRef34(null);if(timerRef.current===null)timerRef.current=createTimerRunners();let{runners:timerRunners,cleanup}=timerRef.current,customRunnersRef=useRef34(customRunners);customRunnersRef.current=customRunners;let pendingEffectsRef=useRef34([]),[state,reactDispatch]=useReducer4((prevState,msg)=>{let result=update(prevState,msg),[newState,effects]=collect(result);if(effects.length>0)pendingEffectsRef.current.push(...effects);return newState},void 0,()=>typeof initialState==="function"?initialState():initialState),sendRef=useRef34(()=>{}),executeEffects=useCallback33(()=>{if(pendingEffectsRef.current.length===0)return;let effects=pendingEffectsRef.current.splice(0);for(let effect2 of effects){let timerRunner=timerRunners[effect2.type];if(timerRunner){timerRunner(effect2,sendRef.current);continue}let customRunner=customRunnersRef.current?.[effect2.type];if(customRunner)customRunner(effect2,sendRef.current)}},[timerRunners]),send=useCallback33((msg)=>{reactDispatch(msg),queueMicrotask(executeEffects)},[reactDispatch,executeEffects]);return sendRef.current=send,useEffect28(()=>{executeEffects()},[executeEffects]),useEffect28(()=>cleanup,[cleanup]),[state,send]}init_keys();init_ag();init_ag();init_output_phase();init_ag();init_reconciler();init_context();import React25 from"react";init_keys();init_buffer();init_pipeline2();init_output_phase();init_text_sizing();init_src2();init_mouse();init_unicode();init_unicode();init_errors();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_ansi2();init_unicode();init_keys();import React26,{createContext as createContext13,Fragment as Fragment4}from"react";var InkCursorStoreCtx=createContext13(null);import React27,{createContext as createContext14,Fragment as Fragment5,useCallback as useCallback34,useEffect as useEffect29,useMemo as useMemo20,useState as useState23}from"react";var InkFocusContext=createContext14({activeId:void 0,isFocusEnabled:!0,add(){},remove(){},activate(){},deactivate(){},enableFocus(){},disableFocus(){},focusNext(){},focusPrevious(){},focus(){},blur(){}});init_term_provider();init_ansi2();init_buffer();init_context();init_pipeline2();init_reconciler();import React28 from"react";init_pipeline2();init_buffer();init_output_phase();import process3 from"node:process";import React29,{createContext as createContext15,useContext as useContext37,useEffect as useEffect30,useRef as useRef35}from"react";init_esm();init_ansi2();init_context();init_pipeline2();init_ag();init_text_sizing();init_reconciler();init_reconciler();init_keys();init_keys2();init_term_provider();init_output_guard();import{createLogger as createLogger17}from"loggily";var perfLog=createLogger17("silvery:perf");import{createLogger as createLogger18}from"loggily";import{jsxDEV as jsxDEV48}from"react/jsx-dev-runtime";var log15=createLogger18("silvery:app"),ENV=typeof process3<"u"?process3.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}})();var StoreContext=createContext15(null);init_context();import{useContext as useContext38,useEffect as useEffect31,useRef as useRef36}from"react";import{jsxDEV as jsxDEV49}from"react/jsx-dev-runtime";init_keys2();import{jsxDEV as jsxDEV50}from"react/jsx-dev-runtime";function ReactiveThemeInner({dark=defaultDarkTheme,light=defaultLightTheme,initial,children}){let scheme=useColorScheme(),theme2;if(scheme==="light")theme2=light;else if(scheme==="dark")theme2=dark;else theme2=initial??dark;return jsxDEV50(ThemeProvider,{theme:theme2,children},void 0,!1,void 0,this)}function ReactiveThemeProvider(props){return jsxDEV50(ReactiveThemeInner,{...props},void 0,!1,void 0,this)}var VERSION="0.0.1";function render3(element,termOrDef,options){if(!termOrDef&&process.stdin?.isTTY&&process.stdout?.isTTY){let ttyDef={stdin:process.stdin,stdout:process.stdout};return render(element,ttyDef,options)}return render(element,termOrDef,options)}export{writeTextTruncated,writeTextToBuffer,writeLinesToBuffer,wrapText,withRender,withMeasurer,withKeybindings,withDiagnostics,withCommands,useWindowSize,useVirtualizer,useTransition2 as useTransition,useToast,useTimeout,useTheme,useTextArea,useTerminalFocused,useTerm,useTea,useStdout,useStderr,useSelection,useSearchOptional,useSearch,useScrollRect,useScreenRect,useRuntime,useReadline,usePositionRegistry,usePasteEvents,usePaste,useMouseCursor,useModifierKeys,useListItem,useLatest,useInterval,useInteractiveState,useInputLayerContext,useInputLayer,useInput,useId2 as useId,useHitRegistry,useHitRegionCallback,useHitRegion,useGridPosition,useFocusable,useFocusWithin,useFocusManager,useFocus,useFindState,useExit,useEditContext,useDragState,useDeferredValue,useCursor,useCopyModeState,useConsole,useColorScheme,useBoxRect,useBoxMetrics,useApp,useAnimation2 as useAnimation,useTransition as useAnimatedTransition,truncateText,truncateAnsi,textSized,term,swapPanes,supportsScrollRegions,subscribeCursor,stripAnsi2 as stripAnsiUnicode,stripAnsi2 as stripAnsi,splitPane,splitGraphemes,sliceByWidthRange,sliceByWidthFromEnd,sliceByWidth,shallow,setWindowTitle,setWindowAndIconTitle,setTextSizingEnabled,setTextEmojiWide,setScrollRegion2 as setScrollRegion,setPaletteColor,setOutputCaps,setMouseCursorShape,setLayoutEngine,setForegroundColor,setCursorStyle,setCursorColor,setBackgroundColor,scrollUp2 as scrollUp,scrollDown2 as scrollDown,runWithMeasurer,runTermtest,rowColToCursor,resolveThemeColor,resolveNonTTYMode,resolveEasing,resizeSplit,resetWindowTitle,resetScrollRegion2 as resetScrollRegion,resetMouseCursorShape,resetHitRegionIdCounter,resetForegroundColor,resetCursorStyle,resetCursorState,resetCursorColor,resetBackgroundColor,requestClipboard,reportDirectory,renderSync,renderStringSync,renderString,renderStatic,renderScreenReaderOutput,render3 as render,removePane,queryTextAreaSize,queryTextAreaPixels,queryTertiaryDA,queryTerminalVersion,querySecondaryDA,queryPrimaryDA,queryPaletteColor,queryMultiplePaletteColors,queryModes,queryMode,queryKittyKeyboard,queryForegroundColor,queryDeviceAttributes,queryCursorPosition,queryCursorFromStdio,queryCursorColor,queryCellSize,queryBackgroundColor,processMouseEvent,patchConsole,parsePaletteResponse,parseMouseSequence,parseKeypress,parseKey,parseHotkey,parseFocusEvent,parseClipboardResponse,parseBracketedPaste,parseAnsiText,padText,notifyKitty,notifyITerm2,notify,normalizeText,moveCursor2 as moveCursor,mergeTextOps,measureText,measureElement,matchHotkey,lastModifierState,keyToName,keyToModifiers,isZeroWidthGrapheme,isWideGrapheme,isTextSizingLikelySupported,isTextSizingEnabled,isTerm,isTTY,isSixelSupported,isPrivateUseArea,isMouseSequence,isLikelyEmoji,isLayoutEngineInitialized,isKittyGraphicsSupported,isInspectorEnabled,isDevToolsConnected,isCJK,invertTextOp,inspectTree,inspectFrame,injectDOMStyles,initYogaEngine,hitTest,hasZeroWidthCharacters,hasWideCharacters,hasAnsi,graphemeWidth,graphemeCount,getWrappedLines,getThemeByName,getTabOrder2 as getTabOrder,getTabOrder as getSplitTabOrder,getPaneIds,getModifierState,getInternalClipboard,getFirstCodePoint,getExplicitFocusLink,getCursorState,generateTheme,fx,formatTitleWithHotkey,findSpatialTarget,findFocusableAncestor,findEnclosingScope,findByTestID,findAdjacentPane,ensureEmojiPresentation,encodeSixel,encodeKittyImage,enableMouse2 as enableMouse,enableKittyKeyboard2 as enableKittyKeyboard,enableInspector,enableFocusReporting,enableBracketedPaste2 as enableBracketedPaste,emptyKey,easings,displayWidthAnsi,displayWidth,dispatchMouseEvent,dispatchKeyEvent,dispatchFocusEvent,disableMouse2 as disableMouse,disableKittyKeyboard2 as disableKittyKeyboard,disableInspector,disableFocusReporting,disableBracketedPaste2 as disableBracketedPaste,detectTheme2 as detectTheme,detectTextSizingSupport,detectTerminalCaps,detectKittySupport,detectKittyFromStdio,detectColorScheme,deriveTheme,deleteKittyImage,defaultLightTheme,defaultDarkTheme,defaultCaps,cursorToRowCol,cursorMoveUp,cursorMoveDown,createYogaEngine,createWidthMeasurer,createWheelEvent,createTermEditContext,createTerm,createPositionRegistry,createPipeline,createPasteEvent,createOutputPhase,createMouseEventProcessor,createMouseEvent,createMeasurer,createLeaf,createKeyEvent,createInputEvents,createFocusManager,createFocusEvent,createFlexilyZeroEngine as createFlexilyEngine,createDoubleClickState,createDOMAdapter,createCursorStore,createCopyProvider,createCanvasAdapter,countVisualLines,copyToClipboard,constrainText,connectDevTools,computeEnterLeave,collect,clampScroll,checkDoubleClick,calcEdgeBasedScrollOffset,builtinThemes,autoEnableInspector,applyTextOp,ansi16LightTheme2 as ansi16LightTheme,ansi16DarkTheme2 as ansi16DarkTheme,activeEditTargetRef,activeEditContextRef,Z_INDEX,YogaLayoutEngine,VirtualTerminal,VERSION,UL,TreeView,Transform,Tooltip,Toggle,ToastItem,ToastContainer,ThemeProvider,TextInput,TextArea,Text,TermContext,Tabs,Table,TabPanel,TabList,Tab,TERMTEST_SECTIONS,Strong,StderrContext,Static,SplitView,Spinner,Spacer,Small,Skeleton,SilveryErrorBoundary,SelectList,SearchProvider,SearchBar,Screen,RuntimeContext,ReactiveThemeProvider,ProgressBar,PositionRegistryProvider,PickerList,PickerDialog,PasteProvider,PASTE_START,PASTE_END,P,OSC133,OL,Newline,Muted,ModalDialog,ListView,Link,Lead,LI,KittyFlags,Kbd,InputLayerProvider,InputLayerContext,InputBoundary,IncrementalRenderMismatchError,Image,HorizontalVirtualList,HitRegistryContext,HitRegistry,Heading,HR,H3,H2,H1,GridCell,FormField,Form,FocusManagerContext,FlexilyZeroLayoutEngine as FlexilyLayoutEngine,Fill,ErrorBoundary,Em,EditContextDisplay,Divider,DecMode,DOMRenderBuffer,CursorProvider,CursorLine,Console,CommandPalette,CodeBlock,Code,CapabilityRegistryContext,CanvasRenderBuffer,CacheBackendContext,Button,Breadcrumb,Box,Blockquote,Badge,BEL,ANSI};
265
269
 
266
- //# debugId=D6FBA0E1C1ACA8B964756E2164756E21
270
+ //# debugId=1196C50C820ED9C064756E2164756E21