silvery 0.4.0 → 0.4.1

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 ADDED
@@ -0,0 +1,340 @@
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 __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,FocusManagerContext;var init_context=__esm(()=>{TermContext=createContext(null),NodeContext=createContext(null),StdoutContext=createContext(null),StderrContext=createContext(null),RuntimeContext=createContext(null),FocusManagerContext=createContext(null)});import{forwardRef,useImperativeHandle,useLayoutEffect,useRef,useState}from"react";import{jsxDEV}from"react/jsx-dev-runtime";var Box;var init_Box=__esm(()=>{init_context();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.contentRect;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.contentRect)handleLayoutChange();return()=>{node.layoutSubscribers.delete(handleLayoutChange)}},[node,onLayout]),useImperativeHandle(ref,()=>({getNode:()=>nodeRef.current,getContentRect:()=>nodeRef.current?.contentRect??null,getScreenRect:()=>nodeRef.current?.screenRect??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)})});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))}import{useCallback,useEffect,useMemo,useRef as useRef2,useState as useState2}from"react";function getHeight(index,estimateHeight){return typeof estimateHeight==="function"?estimateHeight(index):estimateHeight}function calcAverageHeight(count,estimateHeight){if(count===0)return 1;if(typeof estimateHeight==="number")return estimateHeight;let sampleSize=Math.min(count,10),total=0;for(let i=0;i<sampleSize;i++)total+=getHeight(i,estimateHeight);return total/sampleSize}function useVirtualizer(config){let{count,estimateHeight,viewportHeight,scrollTo,scrollPadding=DEFAULT_SCROLL_PADDING,overscan=DEFAULT_OVERSCAN,maxRendered=DEFAULT_MAX_RENDERED,gap=0,getItemKey}=config,avgHeight=calcAverageHeight(count,estimateHeight),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 fixedHeight=typeof estimateHeight==="number"?estimateHeight:avgHeight,leadingSize=start*(fixedHeight+gap),trailingSize=(count-end)*(fixedHeight+gap);return{startIndex:start,endIndex:end,leadingHeight:leadingSize,trailingHeight:trailingSize}},[count,effectiveScrollOffset,maxRendered,overscan,estimateHeight,avgHeight,gap]),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}}var DEFAULT_SCROLL_PADDING=1,DEFAULT_OVERSCAN=5,DEFAULT_MAX_RENDERED=100;var init_useVirtualizer=()=>{};import{useContext,useEffect as useEffect2,useRef as useRef3}from"react";function isModifierOnlyEvent(input,key){if(input!=="")return!1;if(key.upArrow||key.downArrow||key.leftArrow||key.rightArrow||key.pageDown||key.pageUp||key.home||key.end||key.return||key.escape||key.tab||key.backspace||key.delete)return!1;return!0}function useInput(inputHandler,options={}){let rt=useContext(RuntimeContext);if(!rt)throw Error("useInput requires a runtime (run/render/createApp/test renderer). Use useRuntime() for components that work in both static and interactive modes.");let{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)return;return rt.on("input",(input,key)=>{if(isModifierOnlyEvent(input,key))return;if(key.eventType==="release"){onReleaseRef.current?.(input,key);return}handlerRef.current(input,key)})},[isActive,rt]),useEffect2(()=>{if(!isActive)return;return rt.on("paste",(text)=>{onPasteRef.current?.(text)})},[isActive,rt])}var init_useInput=__esm(()=>{init_context()});import{spawnSync}from"child_process";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{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 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
+ `;if((modifiers.includes("Alt")||modifiers.includes("Meta"))&&mainKey.length===1)return`\x1B${mainKey}`;if(modifiers.includes("Shift")&&mainKey==="Tab")return"\x1B[Z";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
+ `)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&&codepoint>=97&&codepoint<=122)key.text=String.fromCharCode(codepoint-32);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)input=keypress.text??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(input.length===1&&typeof input[0]==="string"&&/[A-Z]/.test(input[0]))key.shift=!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.key>="A"&&hotkey.key<="Z"&&!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;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)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 KEY_MAP,MODIFIER_ALIASES,MODIFIER_SYMBOLS,CODE_TO_KEY,NON_ALPHANUMERIC_KEYS,SHIFT_CODES,CTRL_CODES,META_KEY_CODE_RE,FN_KEY_RE,KITTY_RE,MODIFY_OTHER_KEYS_RE,KITTY_SPECIAL_RE,KITTY_SPECIAL_LETTER_KEYS,KITTY_SPECIAL_NUMBER_KEYS,KITTY_CODEPOINT_MAP,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(()=>{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]))/,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:"delete",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"};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_keys2=__esm(()=>{init_keys()});function parseMouseSequence(input){let m=SGR_MOUSE_RE.exec(input);if(!m)return null;let raw=parseInt(m[1]),x=parseInt(m[2])-1,y=parseInt(m[3])-1,terminator=m[4],shift=!!(raw&4),meta=!!(raw&8),ctrl=!!(raw&16),motion=!!(raw&32);if(!!(raw&64)){let wheelButton=raw&3;return{button:0,x,y,action:"wheel",delta:wheelButton===0?-1:1,shift,meta,ctrl}}return{button:raw&3,x,y,action:motion?"move":terminator==="M"?"down":"up",shift,meta,ctrl}}function isMouseSequence(input){return SGR_MOUSE_TEST_RE.test(input)}var SGR_MOUSE_RE,SGR_MOUSE_TEST_RE;var init_mouse=__esm(()=>{SGR_MOUSE_RE=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/;SGR_MOUSE_TEST_RE=/^\x1b\[<\d+;\d+;\d+[Mm]$/});function enableBracketedPaste(stdout){stdout.write("\x1B[?2004h")}function disableBracketedPaste(stdout){stdout.write("\x1B[?2004l")}function parseBracketedPaste(input){let startIdx=input.indexOf("\x1B[200~");if(startIdx===-1)return null;let contentStart=startIdx+6,endIdx=input.indexOf("\x1B[201~",contentStart);if(endIdx===-1)return null;return{type:"paste",content:input.slice(contentStart,endIdx)}}var PASTE_START="\x1B[200~",PASTE_END="\x1B[201~";function enableFocusReporting(write){write("\x1B[?1004h")}function disableFocusReporting(write){write("\x1B[?1004l")}function parseFocusEvent(input){if(input.includes("\x1B[I"))return{type:"focus-in"};if(input.includes("\x1B[O"))return{type:"focus-out"};return null}function splitRawInput2(raw){let sequences=[],i=0;while(i<raw.length)if(raw[i]==="\x1B")if(i+1>=raw.length)sequences.push("\x1B"),i++;else if(raw[i+1]==="["){let j=i+2;while(j<raw.length&&!isCSITerminator(raw[j]))j++;if(j<raw.length)j++,sequences.push(raw.slice(i,j)),i=j;else return{sequences,incomplete:raw.slice(i)}}else if(raw[i+1]==="O"){let end=Math.min(i+3,raw.length);sequences.push(raw.slice(i,end)),i=end}else if(raw[i+1]==="\x1B")if(i+2<raw.length&&raw[i+2]==="["){let j=i+3;while(j<raw.length&&!isCSITerminator(raw[j]))j++;if(j<raw.length)j++,sequences.push(raw.slice(i,j)),i=j;else return{sequences,incomplete:raw.slice(i)}}else if(i+2<raw.length&&raw[i+2]==="O"){let end=Math.min(i+4,raw.length);sequences.push(raw.slice(i,end)),i=end}else sequences.push("\x1B\x1B"),i+=2;else sequences.push(raw.slice(i,i+2)),i+=2;else sequences.push(raw[i]),i++;return{sequences,incomplete:null}}function isCSITerminator(ch){return ch>="A"&&ch<="Z"||ch>="a"&&ch<="z"||ch==="~"}function createTermProvider(stdin,stdout,options={}){let{cols=stdout.columns||80,rows=stdout.rows||24}=options,state={cols,rows},listeners=new Set,disposed=!1,controller=new AbortController,signal=controller.signal,stdinCleanup=null,onResize=()=>{state={cols:stdout.columns||80,rows:stdout.rows||24},listeners.forEach((l)=>l(state))};if(typeof stdout.setMaxListeners==="function"){if((stdout.getMaxListeners?.()??10)<50)stdout.setMaxListeners(50)}return stdout.on("resize",onResize),{getState(){return state},subscribe(listener){return listeners.add(listener),()=>listeners.delete(listener)},async*events(){if(disposed)return;if(stdin.isTTY)stdin.setRawMode(!0),stdin.resume(),stdin.setEncoding("utf8");let queue=[],eventResolve=null,onKey=(raw)=>{let focusEvent=parseFocusEvent(raw);if(focusEvent){queue.push({type:"focus",data:{focused:focusEvent.type==="focus-in"}});return}if(isMouseSequence(raw)){let parsed=parseMouseSequence(raw);if(parsed){queue.push({type:"mouse",data:parsed});return}}let[input,key]=parseKey(raw);queue.push({type:"key",data:{input,key}})},incompleteCSI=null,onChunk=(chunk)=>{if(incompleteCSI!==null)chunk=incompleteCSI+chunk,incompleteCSI=null;let pasteResult=parseBracketedPaste(chunk);if(pasteResult){if(queue.push({type:"paste",data:{text:pasteResult.content}}),eventResolve){let resolve=eventResolve;eventResolve=null,resolve()}return}let{sequences,incomplete}=splitRawInput2(chunk);for(let raw of sequences)onKey(raw);if(incompleteCSI=incomplete,eventResolve){let resolve=eventResolve;eventResolve=null,resolve()}},onResizeEvent=()=>{let event={type:"resize",data:{cols:stdout.columns||80,rows:stdout.rows||24}};if(queue.push(event),eventResolve){let resolve=eventResolve;eventResolve=null,resolve()}};if(stdin.isTTY)enableBracketedPaste(stdout);stdin.on("data",onChunk),stdout.on("resize",onResizeEvent),stdinCleanup=()=>{if(stdin.isTTY)disableBracketedPaste(stdout);if(stdin.off("data",onChunk),stdout.off("resize",onResizeEvent),stdin.isTTY)stdin.setRawMode(!1);stdin.pause()};try{while(!disposed&&!signal.aborted){if(queue.length===0)await new Promise((resolve)=>{eventResolve=resolve,signal.addEventListener("abort",()=>resolve(),{once:!0})});if(disposed||signal.aborted)break;while(queue.length>0)yield queue.shift()}}finally{if(stdinCleanup){let fn=stdinCleanup;stdinCleanup=null,fn()}}},[Symbol.dispose](){if(disposed)return;if(disposed=!0,controller.abort(),stdout.off("resize",onResize),listeners.clear(),stdinCleanup){let fn=stdinCleanup;stdinCleanup=null,fn()}}}}var init_term_provider=__esm(()=>{init_keys2();init_mouse()});import{Chalk}from"chalk";function stripAnsi(text){return text.replace(ANSI_REGEX,"")}function createTerm(first,second){if(second&&first&&isTermBackend(first)){let{createTerminal}=__require("@termless/core"),emulator=createTerminal({backend:first,...second});return createBackendTerm(emulator)}if(first&&isTermEmulator(first))return createBackendTerm(first);if(first&&isHeadlessDims(first))return createHeadlessTerm(first);return createNodeTerm(first??{})}function isTermEmulator(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;return typeof o.feed==="function"&&typeof o.screen==="object"&&o.screen!==null}function isTermBackend(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;return typeof o.init==="function"&&typeof o.name==="string"&&typeof o.destroy==="function"}function isHeadlessDims(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;return typeof o.cols==="number"&&typeof o.rows==="number"&&!("stdout"in o)&&!("stdin"in o)}function createNodeTerm(options){let stdout=options.stdout??process.stdout,stdin=options.stdin??process.stdin,cachedCursor=options.cursor??detectCursor(stdout),cachedInput=detectInput(stdin),cachedColor=options.color!==void 0?options.color:detectColor(stdout),cachedUnicode=options.unicode??detectUnicode(),detectedCaps=options.caps?{...defaultCaps(),...options.caps}:stdin.isTTY?detectTerminalCaps():void 0,chalkInstance=new Chalk({level:cachedColor===null?0:cachedColor==="basic"?1:cachedColor==="256"?2:3}),provider=null,getProvider=()=>{if(!provider)provider=createTermProvider(stdin,stdout,{cols:stdout.columns||80,rows:stdout.rows||24});return provider},termBase={hasCursor:()=>cachedCursor,hasInput:()=>cachedInput,hasColor:()=>cachedColor,hasUnicode:()=>cachedUnicode,caps:detectedCaps,stdout,stdin,write:(str)=>{stdout.write(str)},writeLine:(str)=>{stdout.write(str+`
4
+ `)},getState:()=>getProvider().getState(),subscribe:(listener)=>getProvider().subscribe(listener),events:()=>getProvider().events(),stripAnsi,[Symbol.dispose]:()=>{if(provider)provider[Symbol.dispose]()}},term=createStyleProxy(chalkInstance,termBase);return Object.defineProperty(term,"cols",{get:()=>stdout.isTTY?stdout.columns:void 0,enumerable:!0}),Object.defineProperty(term,"rows",{get:()=>stdout.isTTY?stdout.rows:void 0,enumerable:!0}),term}function createHeadlessTerm(dims){let state={cols:dims.cols,rows:dims.rows},disposed=!1,controller=new AbortController,chalkInstance=new Chalk({level:0}),termBase={hasCursor:()=>!1,hasInput:()=>!1,hasColor:()=>null,hasUnicode:()=>!1,caps:void 0,stdout:process.stdout,stdin:process.stdin,write:()=>{},writeLine:()=>{},getState:()=>state,subscribe:()=>()=>{},async*events(){if(disposed)return;await new Promise((resolve)=>{controller.signal.addEventListener("abort",()=>resolve(),{once:!0})})},stripAnsi,[Symbol.dispose]:()=>{if(disposed)return;disposed=!0,controller.abort()}},term=createStyleProxy(chalkInstance,termBase);return Object.defineProperty(term,"cols",{get:()=>dims.cols,enumerable:!0}),Object.defineProperty(term,"rows",{get:()=>dims.rows,enumerable:!0}),term}function createBackendTerm(emulator){let disposed=!1,controller=new AbortController,chalkInstance=new Chalk({level:3}),listeners=new Set,eventQueue=[],eventResolve=null,termBase={hasCursor:()=>!0,hasInput:()=>!0,hasColor:()=>"truecolor",hasUnicode:()=>!0,caps:void 0,stdout:process.stdout,stdin:process.stdin,write:(str)=>emulator.feed(str),writeLine:(str)=>emulator.feed(str+`
5
+ `),getState:()=>({cols:emulator.cols,rows:emulator.rows}),subscribe:(listener)=>{return listeners.add(listener),()=>listeners.delete(listener)},async*events(){if(disposed)return;while(!disposed&&!controller.signal.aborted){if(eventQueue.length===0)await new Promise((resolve)=>{eventResolve=resolve,controller.signal.addEventListener("abort",()=>resolve(),{once:!0})});if(disposed||controller.signal.aborted)break;while(eventQueue.length>0)yield eventQueue.shift()}},resize:(cols,rows)=>{emulator.resize(cols,rows);let state={cols,rows};if(listeners.forEach((l)=>l(state)),eventQueue.push({type:"resize",data:{cols,rows}}),eventResolve){let resolve=eventResolve;eventResolve=null,resolve()}},sendInput:(data)=>{let pasteResult=parseBracketedPaste(data);if(pasteResult)eventQueue.push({type:"paste",data:{text:pasteResult.content}});else for(let raw of splitRawInput(data)){let focusEvent=parseFocusEvent(raw);if(focusEvent){eventQueue.push({type:"focus",data:{focused:focusEvent.type==="focus-in"}});continue}if(isMouseSequence(raw)){let parsed=parseMouseSequence(raw);if(parsed)eventQueue.push({type:"mouse",data:parsed});continue}let[input,key]=parseKey(raw);eventQueue.push({type:"key",data:{input,key}})}if(eventResolve){let resolve=eventResolve;eventResolve=null,resolve()}},stripAnsi,_emulator:emulator,[Symbol.dispose]:()=>{if(disposed)return;disposed=!0,controller.abort(),listeners.clear(),emulator.close().catch(()=>{})}};return Object.defineProperty(termBase,"cols",{get:()=>emulator.cols,enumerable:!0}),Object.defineProperty(termBase,"rows",{get:()=>emulator.rows,enumerable:!0}),Object.defineProperty(termBase,"screen",{get:()=>emulator.screen,enumerable:!0}),Object.defineProperty(termBase,"scrollback",{get:()=>emulator.scrollback,enumerable:!0}),createStyleProxy(chalkInstance,termBase)}function createStyleProxy(chalkInstance,termBase){return createChainProxy(chalkInstance,termBase)}function createChainProxy(currentChalk,termBase){let handler={apply(_target,_thisArg,args){if(args.length===1&&typeof args[0]==="string")return currentChalk(args[0]);if(args.length>0&&Array.isArray(args[0])&&"raw"in args[0])return currentChalk(args[0],...args.slice(1));return currentChalk(String(args[0]??""))},get(target,prop,receiver){if(prop in termBase){let value=termBase[prop];if(typeof value==="function")return value;return value}if(typeof prop==="symbol"){if(prop===Symbol.dispose)return termBase[Symbol.dispose];return Reflect.get(target,prop,receiver)}if(prop==="rgb"||prop==="bgRgb")return(r,g,b)=>{let newChalk=currentChalk[prop](r,g,b);return createChainProxy(newChalk,termBase)};if(prop==="hex"||prop==="bgHex")return(color)=>{let newChalk=currentChalk[prop](color);return createChainProxy(newChalk,termBase)};if(prop==="ansi256"||prop==="bgAnsi256")return(code)=>{let newChalk=currentChalk[prop](code);return createChainProxy(newChalk,termBase)};let chalkProp=currentChalk[prop];if(chalkProp!==void 0){if(typeof chalkProp==="function"||typeof chalkProp==="object")return createChainProxy(chalkProp,termBase);return chalkProp}return},has(_target,prop){if(prop in termBase)return!0;if(typeof prop==="string"&&prop in currentChalk)return!0;return!1}},proxyTarget=Object.assign(function(){},currentChalk);return new Proxy(proxyTarget,handler)}var ANSI_REGEX;var init_term=__esm(()=>{init_detection();init_term_provider();init_keys();init_mouse();ANSI_REGEX=/\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 stringWidth from"string-width";var init_utils=()=>{};var init_constants=()=>{};import chalk from"chalk";var init_underline=__esm(()=>{init_constants();init_detection()});var init_hyperlink=__esm(()=>{init_constants()});var _lazyTerm,term,BG_OVERRIDE_CODE=9999;var init_ansi=__esm(()=>{init_term();init_term();init_patch_console();init_detection();init_utils();init_underline();init_hyperlink();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)}})});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}`}function isDefaultBg(color){return color!==null&&typeof color==="object"&&color.r===-1}function underlineStyleToNumber(style){switch(style){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;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}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)])}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(`
6
+ `).slice(1,6).join(`
7
+ `)??"";trap.log.push(` char="${char2}" fg=${cell.fg??"null"} bg=${cell.bg??"null"} dim=${cell.attrs?.dim} ul=${cell.attrs?.underline}
8
+ ${stack}`)}if(this._dirtyRows[y]=1,this._minDirtyRow===-1||y<this._minDirtyRow)this._minDirtyRow=y;if(y>this._maxDirtyRow)this._maxDirtyRow=y;let idx=this.index(x,y),char=cell.char??" ",fg=cell.fg??null,bg=cell.bg??null,underlineColor2=cell.underlineColor??null,attrs=cell.attrs??EMPTY_ATTRS,wide=cell.wide??!1,continuation=cell.continuation??!1;if(this.chars[idx]=char,isTrueColor(fg))this.fgColors.set(idx,fg);else this.fgColors.delete(idx);if(isTrueColor(bg))this.bgColors.set(idx,bg);else this.bgColors.delete(idx);if(underlineColor2!==null)this.underlineColors.set(idx,underlineColor2);else this.underlineColors.delete(idx);let hyperlink2=cell.hyperlink;if(hyperlink2!==void 0&&hyperlink2!=="")this.hyperlinks.set(idx,hyperlink2);else this.hyperlinks.delete(idx);let packed=0;if(packed|=colorToIndex(fg)&255,packed|=(colorToIndex(bg)&255)<<8,packed|=attrsToNumber(attrs),wide)packed|=WIDE_FLAG;if(continuation)packed|=CONTINUATION_FLAG;if(isTrueColor(fg))packed|=TRUE_COLOR_FG_FLAG;if(isTrueColor(bg))packed|=TRUE_COLOR_BG_FLAG;this.cells[idx]=packed}fill(x,y,width,height,cell){let endX=Math.min(x+width,this.width),endY=Math.min(y+height,this.height),startX=Math.max(0,x),startY=Math.max(0,y);if(startX>=endX||startY>=endY)return;let char=cell.char??" ",fg=cell.fg??null,bg=cell.bg??null,underlineColor2=cell.underlineColor??null,attrs=cell.attrs??{},wide=cell.wide??!1,continuation=cell.continuation??!1,packed=packCell({char,fg,bg,underlineColor:underlineColor2,attrs,wide,continuation}),hasTrueColorFg=isTrueColor(fg),hasTrueColorBg=isTrueColor(bg),trueColorFg=hasTrueColorFg?fg:null,trueColorBg=hasTrueColorBg?bg:null,hasUnderlineColor=underlineColor2!==null,hyperlink2=cell.hyperlink,hasHyperlink=hyperlink2!==void 0&&hyperlink2!=="";for(let cy=startY;cy<endY;cy++)this._dirtyRows[cy]=1;if(startY<endY){if(this._minDirtyRow===-1||startY<this._minDirtyRow)this._minDirtyRow=startY;if(endY-1>this._maxDirtyRow)this._maxDirtyRow=endY-1}let needFgDelete=!hasTrueColorFg&&this.fgColors.size>0,needBgDelete=!hasTrueColorBg&&this.bgColors.size>0,needUlDelete=!hasUnderlineColor&&this.underlineColors.size>0,needHlDelete=!hasHyperlink&&this.hyperlinks.size>0;for(let cy=startY;cy<endY;cy++){let rowBase=cy*this.width;for(let cx=startX;cx<endX;cx++){let idx=rowBase+cx;if(this.cells[idx]=packed,this.chars[idx]=char,hasTrueColorFg)this.fgColors.set(idx,trueColorFg);else if(needFgDelete)this.fgColors.delete(idx);if(hasTrueColorBg)this.bgColors.set(idx,trueColorBg);else if(needBgDelete)this.bgColors.delete(idx);if(hasUnderlineColor)this.underlineColors.set(idx,underlineColor2);else if(needUlDelete)this.underlineColors.delete(idx);if(hasHyperlink)this.hyperlinks.set(idx,hyperlink2);else if(needHlDelete)this.hyperlinks.delete(idx)}}}clear(){this.cells.fill(0),this.chars.fill(" "),this.fgColors.clear(),this.bgColors.clear(),this.underlineColors.clear(),this.hyperlinks.clear(),this._dirtyRows.fill(1),this._minDirtyRow=0,this._maxDirtyRow=this.height-1}copyFrom(source,srcX,srcY,destX,destY,width,height){let cell=createMutableCell();for(let dy=0;dy<height;dy++){let dstY=destY+dy;if(dstY>=0&&dstY<this.height){if(this._dirtyRows[dstY]=1,this._minDirtyRow===-1||dstY<this._minDirtyRow)this._minDirtyRow=dstY;if(dstY>this._maxDirtyRow)this._maxDirtyRow=dstY}for(let dx=0;dx<width;dx++){let sx=srcX+dx,sy=srcY+dy,dX=destX+dx;if(source.inBounds(sx,sy)&&this.inBounds(dX,dstY))source.readCellInto(sx,sy,cell),this.setCell(dX,dstY,cell)}}}scrollRegion(x,y,regionWidth,regionHeight,delta,clearCell={}){if(delta===0||regionHeight<=0||regionWidth<=0)return;let startX=Math.max(0,x),endX=Math.min(x+regionWidth,this.width),startY=Math.max(0,y),endY=Math.min(y+regionHeight,this.height),clampedWidth=endX-startX,clampedHeight=endY-startY;if(clampedWidth<=0||clampedHeight<=0)return;for(let r=startY;r<endY;r++)this._dirtyRows[r]=1;if(this._minDirtyRow===-1||startY<this._minDirtyRow)this._minDirtyRow=startY;if(endY-1>this._maxDirtyRow)this._maxDirtyRow=endY-1;if(Math.abs(delta)>=clampedHeight){this.fill(startX,startY,clampedWidth,clampedHeight,{char:clearCell.char??" ",bg:clearCell.bg??null});return}let absDelta=Math.abs(delta),w=this.width;if(delta>0){for(let row=startY;row<endY-absDelta;row++){let dstBase=row*w,srcBase=(row+absDelta)*w;this.cells.copyWithin(dstBase+startX,srcBase+startX,srcBase+endX);for(let cx=startX;cx<endX;cx++){this.chars[dstBase+cx]=this.chars[srcBase+cx];let srcIdx=srcBase+cx,dstIdx=dstBase+cx,fgc=this.fgColors.get(srcIdx);if(fgc)this.fgColors.set(dstIdx,fgc),this.fgColors.delete(srcIdx);else this.fgColors.delete(dstIdx);let bgc=this.bgColors.get(srcIdx);if(bgc)this.bgColors.set(dstIdx,bgc),this.bgColors.delete(srcIdx);else this.bgColors.delete(dstIdx);let ulc=this.underlineColors.get(srcIdx);if(ulc)this.underlineColors.set(dstIdx,ulc),this.underlineColors.delete(srcIdx);else this.underlineColors.delete(dstIdx);let hl=this.hyperlinks.get(srcIdx);if(hl)this.hyperlinks.set(dstIdx,hl),this.hyperlinks.delete(srcIdx);else this.hyperlinks.delete(dstIdx)}}this.fill(startX,endY-absDelta,clampedWidth,absDelta,{char:clearCell.char??" ",bg:clearCell.bg??null})}else{for(let row=endY-1;row>=startY+absDelta;row--){let dstBase=row*w,srcBase=(row-absDelta)*w;this.cells.copyWithin(dstBase+startX,srcBase+startX,srcBase+endX);for(let cx=startX;cx<endX;cx++){this.chars[dstBase+cx]=this.chars[srcBase+cx];let srcIdx=srcBase+cx,dstIdx=dstBase+cx,fgc=this.fgColors.get(srcIdx);if(fgc)this.fgColors.set(dstIdx,fgc),this.fgColors.delete(srcIdx);else this.fgColors.delete(dstIdx);let bgc=this.bgColors.get(srcIdx);if(bgc)this.bgColors.set(dstIdx,bgc),this.bgColors.delete(srcIdx);else this.bgColors.delete(dstIdx);let ulc=this.underlineColors.get(srcIdx);if(ulc)this.underlineColors.set(dstIdx,ulc),this.underlineColors.delete(srcIdx);else this.underlineColors.delete(dstIdx);let hl=this.hyperlinks.get(srcIdx);if(hl)this.hyperlinks.set(dstIdx,hl),this.hyperlinks.delete(srcIdx);else this.hyperlinks.delete(dstIdx)}}this.fill(startX,startY,clampedWidth,absDelta,{char:clearCell.char??" ",bg:clearCell.bg??null})}}clone(){let copy=new TerminalBuffer(this.width,this.height);return copy.cells.set(this.cells),copy.chars=[...this.chars],copy.fgColors=new Map(this.fgColors),copy.bgColors=new Map(this.bgColors),copy.underlineColors=new Map(this.underlineColors),copy.hyperlinks=new Map(this.hyperlinks),copy._dirtyRows.fill(0),copy._minDirtyRow=-1,copy._maxDirtyRow=-1,copy}isRowDirty(y){if(y<0||y>=this.height)return!1;return this._dirtyRows[y]!==0}get minDirtyRow(){return this._minDirtyRow}get maxDirtyRow(){return this._maxDirtyRow}resetDirtyRows(){this._dirtyRows.fill(0),this._minDirtyRow=-1,this._maxDirtyRow=-1}markAllRowsDirty(){this._dirtyRows.fill(1),this._minDirtyRow=0,this._maxDirtyRow=this.height-1}cellEquals(x,y,other){if(!this.inBounds(x,y)||!other.inBounds(x,y))return!1;let idx=this.index(x,y),otherIdx=other.index(x,y);if(this.cells[idx]!==other.cells[otherIdx])return!1;if(this.chars[idx]!==other.chars[otherIdx])return!1;let packed=this.cells[idx];if(unpackTrueColorFg(packed)){let a=this.fgColors.get(idx),b=other.fgColors.get(otherIdx);if(!colorEquals(a,b))return!1}if(unpackTrueColorBg(packed)){let a=this.bgColors.get(idx),b=other.bgColors.get(otherIdx);if(!colorEquals(a,b))return!1}let ulA=this.underlineColors.get(idx)??null,ulB=other.underlineColors.get(otherIdx)??null;if(!colorEquals(ulA,ulB))return!1;let hlA=this.hyperlinks.get(idx),hlB=other.hyperlinks.get(otherIdx);if(hlA!==hlB)return!1;return!0}rowMetadataEquals(y,other){if(y<0||y>=this.height||y>=other.height)return!1;let start=y*this.width,otherStart=y*other.width,w=Math.min(this.width,other.width);for(let i=0;i<w;i++)if(this.cells[start+i]!==other.cells[otherStart+i])return!1;return!0}rowCharsEquals(y,other){if(y<0||y>=this.height||y>=other.height)return!1;let start=y*this.width,otherStart=y*other.width,w=Math.min(this.width,other.width);for(let i=0;i<w;i++)if(this.chars[start+i]!==other.chars[otherStart+i])return!1;return!0}rowExtrasEquals(y,other){if(y<0||y>=this.height||y>=other.height)return!1;let start=y*this.width,w=Math.min(this.width,other.width),otherStart=y*other.width;for(let i=0;i<w;i++){let idx=start+i,otherIdx=otherStart+i,packed=this.cells[idx];if((packed&TRUE_COLOR_FG_FLAG)!==0){let a=this.fgColors.get(idx),b=other.fgColors.get(otherIdx);if(!colorEquals(a,b))return!1}if((packed&TRUE_COLOR_BG_FLAG)!==0){let a=this.bgColors.get(idx),b=other.bgColors.get(otherIdx);if(!colorEquals(a,b))return!1}let ulA=this.underlineColors.get(idx)??null,ulB=other.underlineColors.get(otherIdx)??null;if(!colorEquals(ulA,ulB))return!1;let hlA=this.hyperlinks.get(idx),hlB=other.hyperlinks.get(otherIdx);if(hlA!==hlB)return!1}return!0}}function colorEquals(a,b){if(a===b)return!0;if(a===null||a===void 0)return b===null||b===void 0;if(b===null||b===void 0)return!1;if(typeof a==="number")return a===b;if(typeof b==="number")return!1;return a.r===b.r&&a.g===b.g&&a.b===b.b}function cellEquals(a,b){return a.char===b.char&&colorEquals(a.fg,b.fg)&&colorEquals(a.bg,b.bg)&&colorEquals(a.underlineColor,b.underlineColor)&&a.wide===b.wide&&a.continuation===b.continuation&&attrsEquals(a.attrs,b.attrs)&&(a.hyperlink??void 0)===(b.hyperlink??void 0)}function attrsEquals(a,b){return Boolean(a.bold)===Boolean(b.bold)&&Boolean(a.dim)===Boolean(b.dim)&&Boolean(a.italic)===Boolean(b.italic)&&Boolean(a.underline)===Boolean(b.underline)&&(a.underlineStyle??!1)===(b.underlineStyle??!1)&&Boolean(a.blink)===Boolean(b.blink)&&Boolean(a.inverse)===Boolean(b.inverse)&&Boolean(a.hidden)===Boolean(b.hidden)&&Boolean(a.strikethrough)===Boolean(b.strikethrough)}function styleEquals(a,b){if(a===b)return!0;if(!a||!b)return!1;return colorEquals(a.fg,b.fg)&&colorEquals(a.bg,b.bg)&&colorEquals(a.underlineColor,b.underlineColor)&&attrsEquals(a.attrs,b.attrs)&&(a.hyperlink??void 0)===(b.hyperlink??void 0)}function createMutableCell(){return{char:" ",fg:null,bg:null,underlineColor:null,attrs:{},wide:!1,continuation:!1,hyperlink:void 0}}function bufferToText(buffer,options={}){let{trimTrailingWhitespace=!0,trimEmptyLines=!0}=options,lines=[];for(let y=0;y<buffer.height;y++){let line="",strOffset=0,contentEdgeStrOffset=0,contentEdge=trimTrailingWhitespace?getContentEdge(buffer,y):0;for(let x=0;x<buffer.width;x++){if(buffer.isCellContinuation(x,y))continue;if(line+=buffer.getCellChar(x,y),strOffset++,x<contentEdge)contentEdgeStrOffset=strOffset}if(trimTrailingWhitespace){let trimmed=line.trimEnd();line=trimmed.length>=contentEdgeStrOffset?trimmed:line.substring(0,contentEdgeStrOffset)}lines.push(line)}let result=lines.join(`
9
+ `);if(trimEmptyLines){while(lines.length>0&&lines[lines.length-1].length===0)lines.pop();result=lines.join(`
10
+ `)}return result}function getContentEdge(buffer,y){let FLAG_MASK=~(WIDE_FLAG|CONTINUATION_FLAG);for(let x=buffer.width-1;x>=0;x--){if(buffer.isCellContinuation(x,y))continue;if((buffer.getCellAttrs(x,y)&FLAG_MASK)!==0)return x+1;if(buffer.getCellChar(x,y)!==" ")return x+1}return 0}function bufferToStyledText(buffer,options={}){let{trimTrailingWhitespace=!0,trimEmptyLines=!0}=options,lines=[],currentStyle=null,currentHyperlink;for(let y=0;y<buffer.height;y++){let line="";for(let x=0;x<buffer.width;x++){let cell=buffer.getCell(x,y);if(cell.continuation)continue;let cellHyperlink=cell.hyperlink;if(cellHyperlink!==currentHyperlink){if(currentHyperlink)line+=emitHyperlinkClose(currentHyperlink);if(cellHyperlink)line+=emitHyperlinkOpen(cellHyperlink);currentHyperlink=cellHyperlink}let cellStyle={fg:cell.fg,bg:cell.bg,underlineColor:cell.underlineColor,attrs:cell.attrs};if(!styleEquals(currentStyle,cellStyle))line+=styleTransitionCodes(currentStyle,cellStyle),currentStyle=cellStyle;line+=cell.char}if(currentHyperlink)line+=emitHyperlinkClose(currentHyperlink),currentHyperlink=void 0;if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))line+=styleResetCodes(currentStyle),currentStyle=null;if(trimTrailingWhitespace)line=trimTrailingWhitespacePreservingAnsi(line);lines.push(line)}let result=lines.join(`
11
+ `);if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))result+=styleResetCodes(currentStyle);if(trimEmptyLines)result=result.replace(/\n+$/,"");return result}function decodeHyperlinkFormat(encoded){if(encoded.charCodeAt(0)===1){let sepIdx=encoded.indexOf("\x02");if(sepIdx>0){let tag=encoded.slice(1,sepIdx),url=encoded.slice(sepIdx+1);if(tag==="c1b")return{url,oscIntro:"",oscClose:"",closeIntro:"",closeTerminator:"\x07"};if(tag==="c1s")return{url,oscIntro:"",oscClose:"",closeIntro:"",closeTerminator:"\x1B\\"};if(tag==="e7b")return{url,oscIntro:"\x1B]",oscClose:"\x1B]",closeIntro:"\x1B]",closeTerminator:"\x07"}}}return{url:encoded,oscIntro:"\x1B]",oscClose:"\x1B]",closeIntro:"\x1B]",closeTerminator:"\x1B\\"}}function emitHyperlinkOpen(encoded){let fmt=decodeHyperlinkFormat(encoded);return`${fmt.oscIntro}8;;${fmt.url}${fmt.closeTerminator}`}function emitHyperlinkClose(encoded){let fmt=decodeHyperlinkFormat(encoded);return`${fmt.closeIntro}8;;${fmt.closeTerminator}`}function hasActiveAttrs(attrs){return!!(attrs.bold||attrs.dim||attrs.italic||attrs.underline||attrs.underlineStyle||attrs.blink||attrs.inverse||attrs.hidden||attrs.strikethrough)}function styleToAnsiCodes(style){let{fg,bg}=style,result="";if(fg!==null)result+=`\x1B[${fgColorCode(fg)}m`;if(bg!==null&&!isDefaultBg(bg))result+=`\x1B[${bgColorCode(bg)}m`;if(style.attrs.bold)result+="\x1B[1m";if(style.attrs.dim)result+="\x1B[2m";if(style.attrs.italic)result+="\x1B[3m";let underlineStyle=style.attrs.underlineStyle;if(typeof underlineStyle==="string"){let subparam={single:1,double:2,curly:3,dotted:4,dashed:5}[underlineStyle];if(subparam!==void 0&&subparam!==0)result+=`\x1B[4:${subparam}m`}else if(style.attrs.underline)result+="\x1B[4m";if(style.attrs.inverse)result+="\x1B[7m";if(style.attrs.strikethrough)result+="\x1B[9m";if(style.underlineColor!==null&&style.underlineColor!==void 0)if(typeof style.underlineColor==="number")result+=`\x1B[58;5;${style.underlineColor}m`;else result+=`\x1B[58;2;${style.underlineColor.r};${style.underlineColor.g};${style.underlineColor.b}m`;return result}function styleTransitionCodes(oldStyle,newStyle){if(!oldStyle)return styleToAnsiCodes(newStyle);if(styleEquals(oldStyle,newStyle))return"";let result="",oa=oldStyle.attrs,na=newStyle.attrs,boldChanged=Boolean(oa.bold)!==Boolean(na.bold),dimChanged=Boolean(oa.dim)!==Boolean(na.dim);if(boldChanged||dimChanged){let boldOff=boldChanged&&!na.bold,dimOff=dimChanged&&!na.dim;if(boldOff||dimOff){if(result+="\x1B[22m",na.bold)result+="\x1B[1m";if(na.dim)result+="\x1B[2m"}else{if(boldChanged&&na.bold)result+="\x1B[1m";if(dimChanged&&na.dim)result+="\x1B[2m"}}if(Boolean(oa.italic)!==Boolean(na.italic))result+=na.italic?"\x1B[3m":"\x1B[23m";let oldUl=Boolean(oa.underline),newUl=Boolean(na.underline),oldUlStyle=oa.underlineStyle??!1,newUlStyle=na.underlineStyle??!1;if(oldUl!==newUl||oldUlStyle!==newUlStyle)if(typeof na.underlineStyle==="string"){let sub={single:1,double:2,curly:3,dotted:4,dashed:5}[na.underlineStyle];if(sub!==void 0&&sub!==0)result+=`\x1B[4:${sub}m`;else if(newUl)result+="\x1B[4m";else result+="\x1B[24m"}else if(newUl)result+="\x1B[4m";else result+="\x1B[24m";if(Boolean(oa.inverse)!==Boolean(na.inverse))result+=na.inverse?"\x1B[7m":"\x1B[27m";if(Boolean(oa.strikethrough)!==Boolean(na.strikethrough))result+=na.strikethrough?"\x1B[9m":"\x1B[29m";if(!colorEquals(oldStyle.fg,newStyle.fg))if(newStyle.fg===null)result+="\x1B[39m";else result+=`\x1B[${fgColorCode(newStyle.fg)}m`;if(!colorEquals(oldStyle.bg,newStyle.bg))if(newStyle.bg===null)result+="\x1B[49m";else result+=`\x1B[${bgColorCode(newStyle.bg)}m`;if(!colorEquals(oldStyle.underlineColor,newStyle.underlineColor))if(newStyle.underlineColor===null||newStyle.underlineColor===void 0)result+="\x1B[59m";else if(typeof newStyle.underlineColor==="number")result+=`\x1B[58;5;${newStyle.underlineColor}m`;else result+=`\x1B[58;2;${newStyle.underlineColor.r};${newStyle.underlineColor.g};${newStyle.underlineColor.b}m`;return result}function styleResetCodes(style){let result="";if(style.attrs.underline||style.attrs.underlineStyle)result+="\x1B[24m";if(style.attrs.bold||style.attrs.dim)result+="\x1B[22m";if(style.attrs.italic)result+="\x1B[23m";if(style.attrs.strikethrough)result+="\x1B[29m";if(style.attrs.inverse)result+="\x1B[27m";if(style.bg!==null&&!isDefaultBg(style.bg))result+="\x1B[49m";if(style.fg!==null)result+="\x1B[39m";if(style.underlineColor!==null&&style.underlineColor!==void 0)result+="\x1B[59m";return result}function trimTrailingWhitespacePreservingAnsi(str){let lastContentIndex=-1,i=0;while(i<str.length){if(str[i]==="\x1B"){if(str[i+1]==="]"){let end2=-1;for(let j=i+2;j<str.length;j++){if(str[j]==="\x07"){end2=j;break}if(str[j]==="\x1B"&&str[j+1]==="\\"){end2=j+1;break}}if(end2!==-1){lastContentIndex=end2,i=end2+1;continue}}let end=str.indexOf("m",i);if(end!==-1){lastContentIndex=end,i=end+1;continue}}if(str[i]!==" "&&str[i]!=="\t")lastContentIndex=i;i++}return str.slice(0,lastContentIndex+1)}var DEFAULT_BG,ATTR_BOLD=65536,ATTR_DIM=131072,ATTR_ITALIC=262144,ATTR_BLINK=524288,ATTR_INVERSE=1048576,ATTR_HIDDEN=2097152,ATTR_STRIKETHROUGH=4194304,UNDERLINE_STYLE_SHIFT=24,UNDERLINE_STYLE_MASK,WIDE_FLAG=134217728,CONTINUATION_FLAG=268435456,TRUE_COLOR_FG_FLAG=536870912,TRUE_COLOR_BG_FLAG=1073741824,VISIBLE_SPACE_ATTR_MASK,EMPTY_CELL,EMPTY_ATTRS,XTERM_256_PALETTE;var init_buffer=__esm(()=>{DEFAULT_BG=Object.freeze({r:-1,g:-1,b:-1});UNDERLINE_STYLE_MASK=7<<UNDERLINE_STYLE_SHIFT,VISIBLE_SPACE_ATTR_MASK=ATTR_INVERSE|ATTR_STRIKETHROUGH|UNDERLINE_STYLE_MASK,EMPTY_CELL={char:" ",fg:null,bg:null,underlineColor:null,attrs:{},wide:!1,continuation:!1,hyperlink:void 0},EMPTY_ATTRS=Object.freeze({});XTERM_256_PALETTE=(()=>{let palette=Array(256),standard=["#000000","#cd0000","#00cd00","#cdcd00","#0000ee","#cd00cd","#00cdcd","#e5e5e5"],bright=["#7f7f7f","#ff0000","#00ff00","#ffff00","#5c5cff","#ff00ff","#00ffff","#ffffff"];for(let i=0;i<8;i++)palette[i]=standard[i],palette[i+8]=bright[i];let cubeValues=[0,95,135,175,215,255];for(let i=0;i<216;i++){let r=cubeValues[Math.floor(i/36)],g=cubeValues[Math.floor(i%36/6)],b=cubeValues[i%6];palette[16+i]="#"+r.toString(16).padStart(2,"0")+g.toString(16).padStart(2,"0")+b.toString(16).padStart(2,"0")}for(let i=0;i<24;i++){let hex=(8+i*10).toString(16).padStart(2,"0");palette[232+i]="#"+hex+hex+hex}return palette})()});function textSized(text,width){return`\x1B]66;w=${width};${text}\x07`}function isPrivateUseArea(cp){return cp>=57344&&cp<=63743||cp>=983040&&cp<=1048573||cp>=1048576&&cp<=1114109}function isTextSizingLikelySupported(){let termProgram=process.env.TERM_PROGRAM?.toLowerCase()??"",termVersion=process.env.TERM_PROGRAM_VERSION??"";if(termProgram==="kitty"){let parts=termVersion.split("."),major=Number(parts[0])||0,minor=Number(parts[1])||0;if(major>0||major===0&&minor>=40)return!0}return!1}function getTerminalFingerprint(){let program=process.env.TERM_PROGRAM??"unknown",version=process.env.TERM_PROGRAM_VERSION??"unknown";return`${program}@${version}`}function getCachedProbeResult(){return probeCache.get(getTerminalFingerprint())}function setCachedProbeResult(result){probeCache.set(getTerminalFingerprint(),result)}async function detectTextSizingSupport(write,read,timeout=1000){let cached=getCachedProbeResult();if(cached!==void 0)return cached;let testSequence="\r"+textSized(" ",2)+"\x1B[6n\r\x1B[K";write(testSequence);try{let match=(await Promise.race([read(),new Promise((_resolve,reject)=>setTimeout(()=>reject(Error("timeout")),timeout))])).match(/\x1b\[(\d+);(\d+)R/);if(match){if(Number(match[2])===3){let result2={supported:!0,widthOnly:!1};return setCachedProbeResult(result2),result2}}let result={supported:!1,widthOnly:!1};return setCachedProbeResult(result),result}catch{let result={supported:!1,widthOnly:!1};return setCachedProbeResult(result),result}}var probeCache;var init_text_sizing=__esm(()=>{probeCache=new Map});import sliceAnsi from"slice-ansi";import stringWidth2 from"string-width";class DisplayWidthCache{cache=new Map;maxSize;constructor(maxSize=1000){this.maxSize=maxSize}get(text){let cached=this.cache.get(text);if(cached!==void 0)this.cache.delete(text),this.cache.set(text,cached);return cached}set(text,width){if(this.cache.size>=this.maxSize){let firstKey=this.cache.keys().next().value;if(firstKey!==void 0)this.cache.delete(firstKey)}this.cache.set(text,width)}clear(){this.cache.clear()}}function runWithMeasurer(measurer,fn){let prev=_scopedMeasurer;_scopedMeasurer=measurer;try{return fn()}finally{_scopedMeasurer=prev}}function setTextEmojiWide(_wide){}function setTextSizingEnabled(_enabled){}function isTextSizingEnabled(){if(_scopedMeasurer)return _scopedMeasurer.textSizingEnabled;return DEFAULT_TEXT_SIZING_ENABLED}function stripOsc8ForSlice(text){return text.replace(OSC8_RE,"")}function createWidthMeasurer(caps={}){let textEmojiWide=caps.textEmojiWide??!0,textSizingEnabled=caps.textSizingEnabled??!1,cache=new DisplayWidthCache(1e4);function measuredGraphemeWidth(grapheme){let width=stringWidth2(grapheme);if(width!==1)return width;if(textEmojiWide&&isTextPresentationEmoji(grapheme))return 2;if(textSizingEnabled){let cp=grapheme.codePointAt(0);if(cp!==void 0&&isPrivateUseArea(cp))return 2}return width}function measuredDisplayWidth(text){let cached=cache.get(text);if(cached!==void 0)return cached;let width;if(!(MAY_CONTAIN_TEXT_EMOJI.test(text)||textSizingEnabled&&MAY_CONTAIN_PUA.test(text)))width=stringWidth2(text);else{let stripped=stripAnsi3(text);width=0;for(let grapheme of splitGraphemes(stripped))width+=measuredGraphemeWidth(grapheme)}return cache.set(text,width),width}function measuredDisplayWidthAnsi(text){return measuredDisplayWidth(stripAnsi3(text))}function measuredSliceByWidth(text,maxWidth){if(hasAnsi(text))return sliceAnsi(stripOsc8ForSlice(text),0,maxWidth);let width=0,result="",graphemes=splitGraphemes(text);for(let grapheme of graphemes){let gWidth=measuredGraphemeWidth(grapheme);if(width+gWidth>maxWidth)break;result+=grapheme,width+=gWidth}return result}function measuredSliceByWidthFromEnd(text,maxWidth){if(measuredDisplayWidthAnsi(text)<=maxWidth)return text;if(hasAnsi(text)){let cleaned=stripOsc8ForSlice(text),startIndex=measuredDisplayWidthAnsi(cleaned)-maxWidth;return sliceAnsi(cleaned,startIndex)}let graphemes=splitGraphemes(text),width=0,startIdx=graphemes.length;for(let i=graphemes.length-1;i>=0;i--){let gWidth=measuredGraphemeWidth(graphemes[i]);if(width+gWidth>maxWidth)break;width+=gWidth,startIdx=i}return graphemes.slice(startIdx).join("")}function measuredWrapText(text,width,trim,hard){return wrapTextWithMeasurer(text,width,measurer,trim??!1,hard??!1)}let measurer={textEmojiWide,textSizingEnabled,displayWidth:measuredDisplayWidth,displayWidthAnsi:measuredDisplayWidthAnsi,graphemeWidth:measuredGraphemeWidth,wrapText:measuredWrapText,sliceByWidth:measuredSliceByWidth,sliceByWidthFromEnd:measuredSliceByWidthFromEnd};return measurer}function getDefaultMeasurer(){if(!_defaultMeasurer)_defaultMeasurer=createWidthMeasurer();return _defaultMeasurer}function splitGraphemes(text){return[...segmenter.segment(text)].map((s)=>s.segment)}function graphemeCount(text){let count=0;for(let _ of segmenter.segment(text))count++;return count}function isTextPresentationEmoji(grapheme){let cp=grapheme.codePointAt(0);if(cp===void 0)return!1;let cached=textPresentationEmojiCache.get(cp);if(cached!==void 0)return cached;if(String.fromCodePoint(cp).length!==grapheme.length)return textPresentationEmojiCache.set(cp,!1),!1;let isExtPict=TEXT_PRESENTATION_EMOJI_REGEX.test(grapheme),isEmojiPres=EMOJI_PRESENTATION_REGEX.test(grapheme);if(!isExtPict||isEmojiPres)return textPresentationEmojiCache.set(cp,!1),!1;let withVs16=grapheme+"️",result=RGI_EMOJI_REGEX.test(withVs16);return textPresentationEmojiCache.set(cp,result),result}function ensureEmojiPresentation(char){if(char.includes("️"))return char;if(isTextPresentationEmoji(char))return char+"️";return char}function displayWidth(text){if(_scopedMeasurer)return _scopedMeasurer.displayWidth(text);let cached=displayWidthCache.get(text);if(cached!==void 0)return cached;let width;if(!(MAY_CONTAIN_TEXT_EMOJI.test(text)||DEFAULT_TEXT_SIZING_ENABLED&&MAY_CONTAIN_PUA.test(text)))width=stringWidth2(text);else{let stripped=stripAnsi3(text);width=0;for(let grapheme of splitGraphemes(stripped))width+=graphemeWidth(grapheme)}return displayWidthCache.set(text,width),width}function graphemeWidth(grapheme){if(_scopedMeasurer)return _scopedMeasurer.graphemeWidth(grapheme);let width=stringWidth2(grapheme);if(width!==1)return width;if(DEFAULT_TEXT_EMOJI_WIDE&&isTextPresentationEmoji(grapheme))return 2;if(DEFAULT_TEXT_SIZING_ENABLED){let cp=grapheme.codePointAt(0);if(cp!==void 0&&isPrivateUseArea(cp))return 2}return width}function isWideGrapheme(grapheme){return graphemeWidth(grapheme)===2}function isZeroWidthGrapheme(grapheme){return stringWidth2(grapheme)===0}function truncateText(text,maxWidth,ellipsis="…"){if(displayWidth(text)<=maxWidth)return text;let ellipsisWidth=displayWidth(ellipsis),targetWidth=maxWidth-ellipsisWidth;if(targetWidth<=0)return maxWidth>0?ellipsis.slice(0,maxWidth):"";let graphemes=hasAnsi(text)?splitGraphemesAnsiAware(text):splitGraphemes(text),result="",currentWidth=0;for(let grapheme of graphemes){let gWidth=graphemeWidth(grapheme);if(currentWidth+gWidth>targetWidth)break;result+=grapheme,currentWidth+=gWidth}return result+ellipsis}function padText(text,width,align="left",padChar=" "){let textWidth=displayWidth(text),padWidth=width-textWidth;if(padWidth<=0)return text;let padCharWidth=displayWidth(padChar);if(padCharWidth===0)return text;let padCount=Math.floor(padWidth/padCharWidth);switch(align){case"left":return text+padChar.repeat(padCount);case"right":return padChar.repeat(padCount)+text;case"center":{let leftPad=Math.floor(padCount/2),rightPad=padCount-leftPad;return padChar.repeat(leftPad)+text+padChar.repeat(rightPad)}}}function constrainText(text,width,maxLines,pad=!1,ellipsis="…"){let allLines=wrapText(text,width),truncated=allLines.length>maxLines,lines=allLines.slice(0,maxLines);if(truncated&&lines.length>0){let lastIdx=lines.length-1,lastLine=lines[lastIdx];if(lastLine){let ellipsisLen=displayWidth(ellipsis);if(displayWidth(lastLine)+ellipsisLen<=width)lines[lastIdx]=lastLine+ellipsis;else lines[lastIdx]=truncateText(lastLine,width,ellipsis)}}if(pad)lines=lines.map((line)=>padText(line,width));return{lines,truncated}}function isWordBoundary(grapheme){return grapheme===" "||grapheme==="-"||grapheme==="\t"}function isBreakBeforeOperatorWith(graphemes,spaceIndex,gWidthFn){let j=spaceIndex+1;while(j<graphemes.length&&gWidthFn(graphemes[j])===0)j++;if(j>=graphemes.length)return!1;let nextChar=graphemes[j];if(gWidthFn(nextChar)!==1)return!1;if(/^[a-zA-Z0-9\s]$/.test(nextChar))return!1;let k=j+1;while(k<graphemes.length&&gWidthFn(graphemes[k])===0)k++;if(k>=graphemes.length)return!1;return graphemes[k]===" "}function canBreakAnywhere(grapheme){return isCJK(grapheme)}function splitGraphemesAnsiAware(text){if(!hasAnsi(text))return splitGraphemes(text);let result=[],pos=0;while(pos<text.length){if(text[pos]==="\x1B"){let remaining=text.slice(pos),csi=remaining.match(ANSI_CSI_RE);if(csi){result.push(csi[0]),pos+=csi[0].length;continue}let osc=remaining.match(ANSI_OSC_RE);if(osc){result.push(osc[0]),pos+=osc[0].length;continue}let single=remaining.match(ANSI_SINGLE_RE);if(single){result.push(single[0]),pos+=single[0].length;continue}}let nextEsc=text.indexOf("\x1B",pos+1),chunk=nextEsc===-1?text.slice(pos):text.slice(pos,nextEsc);for(let g of splitGraphemes(chunk))result.push(g);pos+=chunk.length}return result}function wrapText(text,width,preserveNewlines=!0,trim=!1){return wrapTextWithMeasurer(text,width,_scopedMeasurer??void 0,trim,!1,preserveNewlines)}function wrapTextWithMeasurer(text,width,measurer,trim=!1,_hard=!1,preserveNewlines=!0){if(width<=0)return[];let gWidthFn=measurer?measurer.graphemeWidth.bind(measurer):graphemeWidth,lines=[],inputLines=preserveNewlines?text.split(`
12
+ `):[text.replace(/\n/g," ")];for(let line of inputLines){if(line===""){lines.push("");continue}let graphemes=splitGraphemesAnsiAware(line),currentLine="",currentWidth=0,isFirstLineOfParagraph=!0,lastBreakIndex=-1,lastBreakWidth=0,lastBreakGraphemeIndex=-1;for(let i=0;i<graphemes.length;i++){let grapheme=graphemes[i],gWidth=gWidthFn(grapheme);if(gWidth===0){currentLine+=grapheme;continue}if(trim&&!isFirstLineOfParagraph&&currentWidth===0&&isWordBoundary(grapheme)&&grapheme!=="-")continue;if(isWordBoundary(grapheme)){if(currentWidth+gWidth<=width){if(currentLine+=grapheme,currentWidth+=gWidth,grapheme!==" "||!isBreakBeforeOperatorWith(graphemes,i,gWidthFn))lastBreakIndex=currentLine.length,lastBreakWidth=currentWidth,lastBreakGraphemeIndex=i+1;continue}if(currentLine){let lineToAdd=currentLine;if(trim)lineToAdd=lineToAdd.trimEnd();lines.push(lineToAdd),isFirstLineOfParagraph=!1}currentLine="",currentWidth=0,lastBreakIndex=-1,lastBreakWidth=0,lastBreakGraphemeIndex=-1;continue}else if(canBreakAnywhere(grapheme))lastBreakIndex=currentLine.length,lastBreakWidth=currentWidth,lastBreakGraphemeIndex=i;if(currentWidth+gWidth>width)if(lastBreakIndex>0){let lineToAdd=currentLine.slice(0,lastBreakIndex);if(trim)lineToAdd=lineToAdd.trimEnd();lines.push(lineToAdd),isFirstLineOfParagraph=!1,currentLine=currentLine.slice(lastBreakIndex),currentWidth=currentWidth-lastBreakWidth,i=lastBreakGraphemeIndex-1,currentLine="",currentWidth=0,lastBreakIndex=-1,lastBreakWidth=0,lastBreakGraphemeIndex=-1}else{if(currentLine){if(trim)currentLine=currentLine.trimEnd();lines.push(currentLine),isFirstLineOfParagraph=!1}currentLine=grapheme,currentWidth=gWidth,lastBreakIndex=-1,lastBreakWidth=0,lastBreakGraphemeIndex=-1}else currentLine+=grapheme,currentWidth+=gWidth}if(currentLine)lines.push(currentLine)}if(text.includes("\x1B]8;;"))fixOsc8AcrossWrappedLines(lines);return lines}function fixOsc8AcrossWrappedLines(lines){let activeHref=null;for(let i=0;i<lines.length;i++){let line=lines[i];if(activeHref!==null)line=`\x1B]8;;${activeHref}\x1B\\`+line;let lineHref=activeHref,osc8Matches=line.matchAll(/\x1b\]8;;([^\x07\x1b]*)(?:\x07|\x1b\\)/g);for(let m of osc8Matches)lineHref=m[1]===""?null:m[1];if(lineHref!==null)line+="\x1B]8;;\x1B\\";lines[i]=line,activeHref=lineHref}}function sliceByWidth(text,maxWidth){return(_scopedMeasurer??getDefaultMeasurer()).sliceByWidth(text,maxWidth)}function sliceByWidthRange(text,start,end){let graphemes=splitGraphemes(text),result="",currentCol=0,endCol=end??Number.POSITIVE_INFINITY;for(let grapheme of graphemes){let gWidth=graphemeWidth(grapheme);if(currentCol+gWidth<=start){currentCol+=gWidth;continue}if(currentCol>=endCol)break;result+=grapheme,currentCol+=gWidth}return result}function sliceByWidthFromEnd(text,maxWidth){return(_scopedMeasurer??getDefaultMeasurer()).sliceByWidthFromEnd(text,maxWidth)}function writeTextToBuffer(buffer,x,y,text,style={fg:null,bg:null,attrs:{}}){let graphemes=splitGraphemes(text),col=x,combineCell=null;for(let grapheme of graphemes){let width=graphemeWidth(grapheme);if(width===0){if(col>0&&buffer.inBounds(col-1,y))combineCell??=createMutableCell(),buffer.readCellInto(col-1,y,combineCell),combineCell.char=combineCell.char+grapheme,buffer.setCell(col-1,y,combineCell)}else if(width===1){if(buffer.inBounds(col,y))buffer.setCell(col,y,{char:grapheme,fg:style.fg,bg:style.bg,attrs:style.attrs,wide:!1,continuation:!1});col++}else if(width===2){let outputChar=ensureEmojiPresentation(grapheme);if(buffer.inBounds(col,y))buffer.setCell(col,y,{char:outputChar,fg:style.fg,bg:style.bg,attrs:style.attrs,wide:!0,continuation:!1});if(buffer.inBounds(col+1,y))buffer.setCell(col+1,y,{char:"",fg:style.fg,bg:style.bg,attrs:style.attrs,wide:!1,continuation:!0});col+=2}if(col>=buffer.width)break}return col}function writeTextTruncated(buffer,x,y,text,maxWidth,style={fg:null,bg:null,attrs:{}},ellipsis="…"){if(displayWidth(text)<=maxWidth)writeTextToBuffer(buffer,x,y,text,style);else{let truncated=truncateText(text,maxWidth,ellipsis);writeTextToBuffer(buffer,x,y,truncated,style)}}function writeLinesToBuffer(buffer,x,y,lines,style={fg:null,bg:null,attrs:{}}){for(let i=0;i<lines.length;i++){if(y+i>=buffer.height)break;writeTextToBuffer(buffer,x,y+i,lines[i],style)}}function stripAnsi3(text){return text.replace(/\x1b\[[0-9;:?]*[A-Za-z]/g,"").replace(/\x9b[0-9;:?]*[A-Za-z]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x9d[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c)/g,"").replace(/\x1b[DME78]/g,"").replace(/\x1b\(B/g,"")}function displayWidthAnsi(text){return displayWidth(stripAnsi3(text))}function truncateAnsi(text,maxWidth,ellipsis="…"){let stripped=stripAnsi3(text);return truncateText(stripped,maxWidth,ellipsis)}function parseUnderlineStyle(subparam){switch(subparam){case 0:return!1;case 1:return"single";case 2:return"double";case 3:return"curly";case 4:return"dotted";case 5:return"dashed";default:return"single"}}function parseAnsiText(text){let segments=[],sanitizedText=text.replace(/\x1b\[[0-9;:]*[A-LN-Za-ln-z@`]/g,"").replace(/\x9b[0-9;:]*[A-LN-Za-ln-z@`]/g,""),oscPattern=/(?:\x1b\]|\x9d)8;;([^\x07\x1b\x9c]*)(?:\x07|\x1b\\|\x9c)/g,currentHyperlink,hyperlinkRanges=[],rangeStart=-1,cleaned="",oscMatch,oscLastIndex=0;while((oscMatch=oscPattern.exec(sanitizedText))!==null){cleaned+=sanitizedText.slice(oscLastIndex,oscMatch.index);let url=oscMatch[1],matchStr=oscMatch[0],isC1=matchStr.charCodeAt(0)===157,lastChar=matchStr.charCodeAt(matchStr.length-1),isBel=lastChar===7,isSt9c=lastChar===156;if(url===""){if(currentHyperlink&&rangeStart>=0)hyperlinkRanges.push({start:rangeStart,end:cleaned.length,url:currentHyperlink});currentHyperlink=void 0,rangeStart=-1}else{if(currentHyperlink&&rangeStart>=0)hyperlinkRanges.push({start:rangeStart,end:cleaned.length,url:currentHyperlink});let encodedUrl=url;if(isC1&&(isBel||isSt9c))encodedUrl=`\x01c1b\x02${url}`;else if(isC1)encodedUrl=`\x01c1s\x02${url}`;else if(isBel)encodedUrl=`\x01e7b\x02${url}`;currentHyperlink=encodedUrl,rangeStart=cleaned.length}oscLastIndex=oscMatch.index+oscMatch[0].length}if(cleaned+=sanitizedText.slice(oscLastIndex),currentHyperlink&&rangeStart>=0)hyperlinkRanges.push({start:rangeStart,end:cleaned.length,url:currentHyperlink});let processText=hyperlinkRanges.length>0?cleaned:sanitizedText,ansiPattern=/(?:\x1b\[|\x9b)([0-9;:]*)m/g,currentStyle={},lastIndex=0,match;function getHyperlinkAt(pos){for(let range of hyperlinkRanges)if(pos>=range.start&&pos<range.end)return range.url;return}while((match=ansiPattern.exec(processText))!==null){if(match.index>lastIndex){let content=processText.slice(lastIndex,match.index);if(content.length>0)if(hyperlinkRanges.length>0){let segStart=0;for(let ci=0;ci<content.length;ci++){let hl=getHyperlinkAt(lastIndex+ci),prevHl=ci>0?getHyperlinkAt(lastIndex+ci-1):void 0;if(ci>0&&hl!==prevHl){let sub2=content.slice(segStart,ci);if(sub2.length>0){let seg={text:sub2,...currentStyle};if(prevHl)seg.hyperlink=prevHl;segments.push(seg)}segStart=ci}}let sub=content.slice(segStart);if(sub.length>0){let hl=getHyperlinkAt(lastIndex+segStart),seg={text:sub,...currentStyle};if(hl)seg.hyperlink=hl;segments.push(seg)}}else segments.push({text:content,...currentStyle})}let params=match[1].split(";");for(let i=0;i<params.length;i++){let param=params[i];if(param.includes(":")){let subparts=param.split(":").map((s)=>s===""?0:Number(s)),mainCode=subparts[0];if(mainCode===4){let styleCode=subparts[1]??1;currentStyle.underlineStyle=parseUnderlineStyle(styleCode),currentStyle.underline=currentStyle.underlineStyle!==!1}else if(mainCode===58){if(subparts[1]===5&&subparts[2]!==void 0)currentStyle.underlineColor=subparts[2];else if(subparts[1]===2){let r=subparts[3]??subparts[2]??0,g=subparts[4]??subparts[3]??0,b=subparts[5]??subparts[4]??0;currentStyle.underlineColor=16777216|(r&255)<<16|(g&255)<<8|b&255}}else if(mainCode===38){if(subparts[1]===5&&subparts[2]!==void 0)currentStyle.fg=subparts[2],currentStyle.colonFg=!0;else if(subparts[1]===2){let r=subparts[3]??subparts[2]??0,g=subparts[4]??subparts[3]??0,b=subparts[5]??subparts[4]??0;currentStyle.fg=16777216|(r&255)<<16|(g&255)<<8|b&255,currentStyle.colonFg=!0}}else if(mainCode===48){if(subparts[1]===5&&subparts[2]!==void 0)currentStyle.bg=subparts[2],currentStyle.colonBg=!0;else if(subparts[1]===2){let r=subparts[3]??subparts[2]??0,g=subparts[4]??subparts[3]??0,b=subparts[5]??subparts[4]??0;currentStyle.bg=16777216|(r&255)<<16|(g&255)<<8|b&255,currentStyle.colonBg=!0}}continue}let code=Number(param);switch(code){case 0:currentStyle={};break;case 1:currentStyle.bold=!0;break;case 2:currentStyle.dim=!0;break;case 3:currentStyle.italic=!0;break;case 4:currentStyle.underline=!0,currentStyle.underlineStyle="single";break;case 7:currentStyle.inverse=!0;break;case 22:currentStyle.bold=!1,currentStyle.dim=!1;break;case 23:currentStyle.italic=!1;break;case 24:currentStyle.underline=!1,currentStyle.underlineStyle=!1;break;case 27:currentStyle.inverse=!1;break;case 30:case 31:case 32:case 33:case 34:case 35:case 36:case 37:currentStyle.fg=code;break;case 38:{let nextParams=params.slice(i+1).map(Number);if(currentStyle.colonFg=void 0,nextParams[0]===5&&nextParams[1]!==void 0)currentStyle.fg=nextParams[1],i+=2;else if(nextParams[0]===2&&nextParams[3]!==void 0)currentStyle.fg=16777216|(nextParams[1]&255)<<16|(nextParams[2]&255)<<8|nextParams[3]&255,i+=4;break}case 39:currentStyle.fg=null;break;case 40:case 41:case 42:case 43:case 44:case 45:case 46:case 47:currentStyle.bg=code;break;case 48:{let nextParams=params.slice(i+1).map(Number);if(currentStyle.colonBg=void 0,nextParams[0]===5&&nextParams[1]!==void 0)currentStyle.bg=nextParams[1],i+=2;else if(nextParams[0]===2&&nextParams[3]!==void 0)currentStyle.bg=16777216|(nextParams[1]&255)<<16|(nextParams[2]&255)<<8|nextParams[3]&255,i+=4;break}case 49:currentStyle.bg=null;break;case 58:{let nextParams=params.slice(i+1).map(Number);if(nextParams[0]===5&&nextParams[1]!==void 0)currentStyle.underlineColor=nextParams[1],i+=2;else if(nextParams[0]===2&&nextParams[3]!==void 0)currentStyle.underlineColor=16777216|(nextParams[1]&255)<<16|(nextParams[2]&255)<<8|nextParams[3]&255,i+=4;break}case 59:currentStyle.underlineColor=null;break;case 90:case 91:case 92:case 93:case 94:case 95:case 96:case 97:currentStyle.fg=code;break;case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:currentStyle.bg=code;break;case BG_OVERRIDE_CODE:currentStyle.bgOverride=!0;break}}lastIndex=match.index+match[0].length}if(lastIndex<processText.length){let content=processText.slice(lastIndex);if(content.length>0)if(hyperlinkRanges.length>0){let segStart=0;for(let ci=0;ci<content.length;ci++){let hl=getHyperlinkAt(lastIndex+ci),prevHl=ci>0?getHyperlinkAt(lastIndex+ci-1):void 0;if(ci>0&&hl!==prevHl){let sub2=content.slice(segStart,ci);if(sub2.length>0){let seg={text:sub2,...currentStyle};if(prevHl)seg.hyperlink=prevHl;segments.push(seg)}segStart=ci}}let sub=content.slice(segStart);if(sub.length>0){let hl=getHyperlinkAt(lastIndex+segStart),seg={text:sub,...currentStyle};if(hl)seg.hyperlink=hl;segments.push(seg)}}else segments.push({text:content,...currentStyle})}return segments}function hasAnsi(text){return ANSI_TEST_REGEX.test(text)}function measureText(text){let lines=text.split(`
13
+ `),maxWidth=0;for(let line of lines){let lineWidth=displayWidth(line);if(lineWidth>maxWidth)maxWidth=lineWidth}return{width:maxWidth,height:lines.length}}function hasWideCharacters(text){return splitGraphemes(text).some(isWideGrapheme)}function hasZeroWidthCharacters(text){return splitGraphemes(text).some(isZeroWidthGrapheme)}function normalizeText(text){return text.normalize("NFC")}function getFirstCodePoint(str){return str.codePointAt(0)??0}function isLikelyEmoji(grapheme){let cp=getFirstCodePoint(grapheme);return CHAR_RANGES.isEmoji(cp)||grapheme.includes("‍")}function isCJK(grapheme){let cp=getFirstCodePoint(grapheme);return CHAR_RANGES.isCJK(cp)||CHAR_RANGES.isJapaneseKana(cp)||CHAR_RANGES.isHangul(cp)}var segmenter,displayWidthCache,DEFAULT_TEXT_EMOJI_WIDE=!0,DEFAULT_TEXT_SIZING_ENABLED=!1,_scopedMeasurer=null,OSC8_RE,createMeasurer,_defaultMeasurer,TEXT_PRESENTATION_EMOJI_REGEX,EMOJI_PRESENTATION_REGEX,RGI_EMOJI_REGEX,textPresentationEmojiCache,MAY_CONTAIN_TEXT_EMOJI,MAY_CONTAIN_PUA,ANSI_CSI_RE,ANSI_OSC_RE,ANSI_SINGLE_RE,ANSI_TEST_REGEX,CHAR_RANGES;var init_unicode=__esm(()=>{init_ansi();init_buffer();init_text_sizing();segmenter=new Intl.Segmenter(void 0,{granularity:"grapheme"});displayWidthCache=new DisplayWidthCache(1e4);OSC8_RE=/\x1b\]8;;[^\x07\x1b]*(?:\x07|\x1b\\)/g;createMeasurer=createWidthMeasurer;TEXT_PRESENTATION_EMOJI_REGEX=/^\p{Extended_Pictographic}$/u,EMOJI_PRESENTATION_REGEX=/^\p{Emoji_Presentation}$/u,RGI_EMOJI_REGEX=/^\p{RGI_Emoji}$/v,textPresentationEmojiCache=new Map;MAY_CONTAIN_TEXT_EMOJI=/[\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]/,MAY_CONTAIN_PUA=/[\uE000-\uF8FF]/;ANSI_CSI_RE=/^\x1b\[[0-9;:?]*[A-Za-z]/,ANSI_OSC_RE=/^\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/,ANSI_SINGLE_RE=/^\x1b[DME78(B]/;ANSI_TEST_REGEX=/\x1b(?:\[[0-9;:]*[A-Za-z]|\])|\x9b[\x30-\x3f]*[\x40-\x7e]|\x9d/;CHAR_RANGES={isBasicLatin:(cp)=>cp>=32&&cp<=127,isCJK:(cp)=>cp>=19968&&cp<=40959||cp>=13312&&cp<=19903||cp>=131072&&cp<=173791||cp>=63744&&cp<=64255||cp>=194560&&cp<=195103,isJapaneseKana:(cp)=>cp>=12352&&cp<=12447||cp>=12448&&cp<=12543,isHangul:(cp)=>cp>=44032&&cp<=55203||cp>=4352&&cp<=4607,isEmoji:(cp)=>cp>=128512&&cp<=128591||cp>=127744&&cp<=128511||cp>=128640&&cp<=128767||cp>=128768&&cp<=128895||cp>=129280&&cp<=129535||cp>=9728&&cp<=9983||cp>=9984&&cp<=10175}});function createHistoryItem(key,ansi,width){let rows=ansi.split(`
14
+ `),plainTextRows=rows.map((r)=>stripAnsi3(r));return{key,ansi,rows,plainTextRows,width}}function createHistoryBuffer(maxRows=1e4){let items=[],_totalRows=0;function evict(){while(_totalRows>maxRows&&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 maxRows(){return maxRows},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}}}var init_history_buffer=__esm(()=>{init_unicode()});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}}}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=stripAnsi3(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(`
15
+ `)},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}}}var init_text_surface=__esm(()=>{init_unicode()});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}}import React,{createContext as createContext2,useCallback as useCallback2,useContext as useContext2,useMemo as useMemo2,useRef as useRef4}from"react";function SurfaceRegistryProvider({children}){let surfacesRef=useRef4(new Map),focusedRef=useRef4(null),listenersRef=useRef4(new Set),notify=useCallback2(()=>{for(let listener of listenersRef.current)listener()},[]),register=useCallback2((surface,getRect)=>{surfacesRef.current.set(surface.id,{surface,getRect}),notify()},[notify]),unregister=useCallback2((id)=>{if(surfacesRef.current.delete(id),focusedRef.current===id)focusedRef.current=null;notify()},[notify]),getSurface=useCallback2((id)=>{return surfacesRef.current.get(id)?.surface??null},[]),getFocusedSurface=useCallback2(()=>{if(!focusedRef.current)return null;return surfacesRef.current.get(focusedRef.current)?.surface??null},[]),getAllSurfaces=useCallback2(()=>{return Array.from(surfacesRef.current.values()).map((entry)=>entry.surface)},[]),setFocused=useCallback2((id)=>{focusedRef.current=id,notify()},[notify]),subscribe=useCallback2((listener)=>{return listenersRef.current.add(listener),()=>{listenersRef.current.delete(listener)}},[]),getSurfaceAt=useCallback2((x,y)=>{for(let entry of surfacesRef.current.values()){let rect=entry.getRect?.();if(rect&&x>=rect.x&&x<rect.x+rect.width&&y>=rect.y&&y<rect.y+rect.height)return entry.surface}return null},[]),value=useMemo2(()=>({register,unregister,getSurface,getFocusedSurface,getAllSurfaces,setFocused,subscribe,getSurfaceAt}),[register,unregister,getSurface,getFocusedSurface,getAllSurfaces,setFocused,subscribe,getSurfaceAt]);return React.createElement(SurfaceRegistryContext.Provider,{value},children)}function useSurfaceRegistry(){let ctx=useContext2(SurfaceRegistryContext);if(!ctx)throw Error("useSurfaceRegistry must be used within a SurfaceRegistryProvider");return ctx}function useSurfaceRegistryOptional(){return useContext2(SurfaceRegistryContext)}var SurfaceRegistryContext;var init_SurfaceRegistry=__esm(()=>{SurfaceRegistryContext=createContext2(null)});import React2,{forwardRef as forwardRef2,useCallback as useCallback3,useEffect as useEffect3,useImperativeHandle as useImperativeHandle2,useMemo as useMemo3,useRef as useRef5,useState as useState3}from"react";import{jsxDEV as jsxDEV2}from"react/jsx-dev-runtime";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,virtualized,navigable,cursorIndex:cursorIndexProp,onCursorIndexChange,onSelect,active,surfaceId,textAdapter,history},ref){let isControlled=cursorIndexProp!==void 0,[uncontrolledCursor,setUncontrolledCursor]=useState3(0),activeCursor=navigable?isControlled?cursorIndexProp:uncontrolledCursor:-1,moveTo=useCallback3((next)=>{let clamped=Math.max(0,Math.min(next,items.length-1));if(!isControlled)setUncontrolledCursor(clamped);onCursorIndexChange?.(clamped)},[isControlled,items.length,onCursorIndexChange]);useInput((input,key)=>{if(!navigable)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:navigable&&active!==!1});let scrollTo=navigable?activeCursor:scrollToProp,historyMode=history?.mode??"none",historyBufferRef=useRef5(null);if(historyMode==="virtual"&&!historyBufferRef.current)historyBufferRef.current=createHistoryBuffer(history?.maxRows??1e4);let historyBuffer=historyBufferRef.current,frozenCount=0;if(historyMode==="virtual"&&history?.freezeWhen)for(let i=0;i<items.length;i++){if(!history.freezeWhen(items[i],i))break;frozenCount++}let prevFrozenRef=useRef5(0);if(frozenCount>prevFrozenRef.current&&historyBuffer){for(let i=prevFrozenRef.current;i<frozenCount;i++){let item=items[i],text=textAdapter?.getItemText?.(item)??String(item);historyBuffer.push(createHistoryItem(getKey?.(item,i)??i,text,80))}prevFrozenRef.current=frozenCount}let effectiveVirtualized=useMemo3(()=>{if(frozenCount===0)return virtualized;if(!virtualized)return(_item,index)=>index<frozenCount;return(item,index)=>{if(index<frozenCount)return!0;return virtualized(item,index)}},[frozenCount,virtualized]),virtualizedCount=0;if(effectiveVirtualized)for(let i=0;i<items.length;i++){if(!effectiveVirtualized(items[i],i))break;virtualizedCount++}let activeItems=virtualizedCount>0?items.slice(virtualizedCount):items,adjustedScrollTo=scrollTo!==void 0?Math.max(0,scrollTo-virtualizedCount):void 0,adjustedEstimateHeight=useMemo3(()=>{if(typeof estimateHeight==="number")return estimateHeight;if(virtualizedCount>0)return(index)=>estimateHeight(index+virtualizedCount);return estimateHeight},[estimateHeight,virtualizedCount]),wrappedGetKey=useMemo3(()=>{if(!getKey)return;if(virtualizedCount===0)return(index)=>getKey(activeItems[index],index);return(index)=>getKey(activeItems[index],index+virtualizedCount)},[getKey,activeItems,virtualizedCount]),{range,leadingHeight,trailingHeight,scrollOffset,scrollToItem}=useVirtualizer({count:activeItems.length,estimateHeight:adjustedEstimateHeight,viewportHeight:height,scrollTo:adjustedScrollTo,scrollPadding,overscan,maxRendered,gap,getItemKey:wrappedGetKey,onEndReached,onEndReachedThreshold}),textSurfaceRef=useRef5(null),composedViewportRef=useRef5(null),registry=useSurfaceRegistryOptional(),itemsRef=useRef5(items);itemsRef.current=items;let virtualizedCountRef=useRef5(virtualizedCount);virtualizedCountRef.current=virtualizedCount;let textAdapterRef=useRef5(textAdapter);textAdapterRef.current=textAdapter;let getKeyRef=useRef5(getKey);if(getKeyRef.current=getKey,useEffect3(()=>{if(!surfaceId||historyMode!=="virtual"||!historyBuffer)return;let document2=createListDocument(historyBuffer,()=>{let currentItems=itemsRef.current,currentVirtualizedCount=virtualizedCountRef.current,currentTextAdapter=textAdapterRef.current,currentGetKey=getKeyRef.current,live=[];for(let i=currentVirtualizedCount;i<currentItems.length;i++){let item=currentItems[i],rows=(currentTextAdapter?.getItemText?.(item)??String(item)).split(`
16
+ `),plainTextRows=rows.map((r)=>stripAnsi3(r));live.push({key:currentGetKey?.(item,i)??i,itemIndex:i,rows,plainTextRows})}return live}),surface=createTextSurface({id:surfaceId,document:document2,viewportToDocument:(viewportRow)=>viewportRow+historyBuffer.totalRows,onReveal:()=>{},capabilities:{paneSafe:!0,searchableHistory:!0,selectableHistory:!0,overlayHistory:!0}});if(textSurfaceRef.current=surface,registry)registry.register(surface);return()=>{if(textSurfaceRef.current=null,registry)registry.unregister(surfaceId)}},[surfaceId,historyMode,historyBuffer,registry]),historyMode==="virtual"&&historyBuffer)composedViewportRef.current=composeViewport({history:historyBuffer,viewportHeight:height,scrollOffset:0});useImperativeHandle2(ref,()=>({scrollToItem(index){scrollToItem(Math.max(0,index-virtualizedCount))},getHistoryBuffer(){return historyBufferRef.current},getComposedViewport(){return composedViewportRef.current}}),[scrollToItem,virtualizedCount]);let onWheel=useMemo3(()=>{if(navigable&&active!==!1)return(e)=>{let delta=e.deltaY>0?WHEEL_STEP:-WHEEL_STEP;moveTo(activeCursor+delta)};return onWheelProp},[navigable,active,activeCursor,moveTo,onWheelProp]);if(activeItems.length===0)return jsxDEV2(Box,{flexDirection:"column",height,width},void 0,!1,void 0,this);let{startIndex,endIndex}=range,visibleItems=activeItems.slice(startIndex,endIndex),hasTopPlaceholder=leadingHeight>0,selectedIndexInSlice=(adjustedScrollTo!==void 0?Math.max(0,Math.min(adjustedScrollTo,activeItems.length-1)):scrollOffset)-startIndex,isSelectedInSlice=selectedIndexInSlice>=0&&selectedIndexInSlice<visibleItems.length,scrollToIndex=hasTopPlaceholder?selectedIndexInSlice+1:selectedIndexInSlice,boxScrollTo=isSelectedInSlice?Math.max(0,scrollToIndex):void 0;return jsxDEV2(Box,{flexDirection:"column",height,width,overflow:"scroll",scrollTo:boxScrollTo,overflowIndicator,onWheel,children:[leadingHeight>0&&jsxDEV2(Box,{height:leadingHeight,flexShrink:0},void 0,!1,void 0,this),visibleItems.map((item,i)=>{let originalIndex=startIndex+i+virtualizedCount,key=getKey?getKey(item,originalIndex):startIndex+i,isLast=i===visibleItems.length-1,meta={isCursor:originalIndex===activeCursor};return jsxDEV2(React2.Fragment,{children:[renderItem(item,originalIndex,meta),!isLast&&renderSeparator&&renderSeparator(),!isLast&&gap>0&&!renderSeparator&&jsxDEV2(Box,{height:gap,flexShrink:0},void 0,!1,void 0,this)]},key,!0,void 0,this)}),listFooter,trailingHeight>0&&jsxDEV2(Box,{height:trailingHeight,flexShrink:0},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var DEFAULT_ESTIMATE_HEIGHT=1,DEFAULT_OVERSCAN2=5,DEFAULT_MAX_RENDERED2=100,DEFAULT_SCROLL_PADDING2=2,WHEEL_STEP=3,ListView;var init_ListView=__esm(()=>{init_useVirtualizer();init_useInput();init_Box();init_history_buffer();init_text_surface();init_unicode();init_SurfaceRegistry();ListView=forwardRef2(ListViewInner)});import{forwardRef as forwardRef3,useCallback as useCallback4,useMemo as useMemo4}from"react";import{jsxDEV as jsxDEV3}from"react/jsx-dev-runtime";function VirtualListInner({items,height,itemHeight=1,scrollTo,overscan,maxRendered,renderItem,overflowIndicator,keyExtractor,width,gap,renderSeparator,virtualized,interactive,selectedIndex,onSelectionChange,onSelect,onEndReached,onEndReachedThreshold,listFooter},ref){let estimateHeight=useMemo4(()=>{if(typeof itemHeight==="number")return itemHeight;return(index)=>itemHeight(items[index],index)},[itemHeight,items]),wrappedRenderItem=useCallback4((item,index,meta)=>{let oldMeta={isSelected:meta.isCursor};return renderItem(item,index,oldMeta)},[renderItem]);return jsxDEV3(ListView,{ref,items,height,estimateHeight,renderItem:wrappedRenderItem,scrollTo,overscan,maxRendered,overflowIndicator,getKey:keyExtractor,width,gap,renderSeparator,virtualized,navigable:interactive,cursorIndex:selectedIndex,onCursorIndexChange:onSelectionChange,onSelect,onEndReached,onEndReachedThreshold,listFooter},void 0,!1,void 0,this)}var VirtualList;var init_VirtualList=__esm(()=>{init_ListView();VirtualList=forwardRef3(VirtualListInner)});import{useMemo as useMemo5}from"react";function useVirtualization(config){let{items,viewportSize,itemSize,scrollTo,scrollPadding,overscan,maxRendered,gap}=config,estimateHeight=useMemo5(()=>{if(typeof itemSize==="number")return itemSize;return(index)=>itemSize(items[index],index)},[items,itemSize]),result=useVirtualizer({count:items.length,estimateHeight,viewportHeight:viewportSize,scrollTo,scrollPadding,overscan,maxRendered,gap}),currentSelectedIndex=scrollTo!==void 0?Math.max(0,Math.min(scrollTo,items.length-1)):result.scrollOffset;return{startIndex:result.range.startIndex,endIndex:result.range.endIndex,currentSelectedIndex,scrollOffset:result.scrollOffset,leadingPlaceholderSize:result.leadingHeight,trailingPlaceholderSize:result.trailingHeight,hiddenBefore:result.hiddenBefore,hiddenAfter:result.hiddenAfter,scrollToItem:result.scrollToItem}}var init_useVirtualization=__esm(()=>{init_useVirtualizer()});import{forwardRef as forwardRef4}from"react";import{jsxDEV as jsxDEV4}from"react/jsx-dev-runtime";var Text;var init_Text=__esm(()=>{Text=forwardRef4(function(props,ref){let{children,...styleProps}=props;return jsxDEV4("silvery-text",{ref:(node)=>{if(typeof ref==="function")ref(node?{getNode:()=>node}:null);else if(ref)ref.current=node?{getNode:()=>node}:null},...styleProps,children},void 0,!1,void 0,this)})});import React4,{forwardRef as forwardRef5,useImperativeHandle as useImperativeHandle3}from"react";import{jsxDEV as jsxDEV5}from"react/jsx-dev-runtime";function calcTotalItemsWidth(items,itemWidth,gap){if(items.length===0)return 0;if(typeof itemWidth==="number")return items.length*itemWidth+(items.length-1)*gap;let total=0;for(let i=0;i<items.length;i++)total+=itemWidth(items[i],i)+(i>0?gap:0);return total}function calcActualVisibleCount(items,startFrom,viewport,itemWidth,gap){if(typeof itemWidth==="number")return Math.max(1,Math.floor((viewport+gap)/(itemWidth+gap)));let usedSize=0,count=0;for(let i=startFrom;i<items.length;i++){let sizeWithGap=itemWidth(items[i],i)+(count>0?gap:0);if(usedSize+sizeWithGap>viewport)break;usedSize+=sizeWithGap,count++}return Math.max(1,count)}function calcItemOverflow(items,scrollOffset,targetIndex,viewport,itemWidth,gap){if(targetIndex<scrollOffset||targetIndex>=items.length)return 0;let pos=0;for(let i=scrollOffset;i<=targetIndex;i++){let w=typeof itemWidth==="number"?itemWidth:itemWidth(items[i],i);pos+=w+(i>scrollOffset?gap:0)}return pos-viewport}function HorizontalVirtualListInner({items,width,itemWidth,scrollTo,overscan=DEFAULT_OVERSCAN3,maxRendered=DEFAULT_MAX_RENDERED3,renderItem,overflowIndicator,renderOverflowIndicator,overflowIndicatorWidth=0,keyExtractor,height,gap=0,renderSeparator},ref){let allItemsFit=calcTotalItemsWidth(items,itemWidth,gap)<=width,hasIndicatorRenderer=renderOverflowIndicator!=null||overflowIndicator===!0,indicatorReserved=hasIndicatorRenderer?overflowIndicatorWidth*2:0,effectiveViewport=Math.max(1,width-indicatorReserved),{startIndex,endIndex,scrollOffset,scrollToItem}=useVirtualization({items,viewportSize:effectiveViewport,itemSize:itemWidth,scrollTo,scrollPadding:SCROLL_PADDING,overscan,maxRendered,gap});if(useImperativeHandle3(ref,()=>({scrollToItem}),[scrollToItem]),items.length===0)return jsxDEV5(Box,{flexDirection:"row",width,height},void 0,!1,void 0,this);let displayScrollOffset=allItemsFit?0:scrollOffset;if(scrollTo!==void 0&&!allItemsFit&&scrollTo>=displayScrollOffset){let wouldShowLeft=hasIndicatorRenderer&&displayScrollOffset>0,prelimVisibleCount=calcActualVisibleCount(items,displayScrollOffset,effectiveViewport,itemWidth,gap),wouldShowRight=hasIndicatorRenderer&&items.length-displayScrollOffset-prelimVisibleCount>0,actualIndicatorWidth=(wouldShowLeft?overflowIndicatorWidth:0)+(wouldShowRight?overflowIndicatorWidth:0),actualViewport=Math.max(1,width-actualIndicatorWidth);if(calcItemOverflow(items,displayScrollOffset,scrollTo,actualViewport,itemWidth,gap)>0){let maxOffset=Math.max(0,items.length-1);displayScrollOffset=Math.min(maxOffset,displayScrollOffset+1)}}let visibleCount=calcActualVisibleCount(items,displayScrollOffset,effectiveViewport,itemWidth,gap),vpStart=Math.max(startIndex,displayScrollOffset),rawVpEnd=Math.min(endIndex,displayScrollOffset+visibleCount+overscan),vpEnd=vpStart,usedWidth=0;for(let i=vpStart;i<rawVpEnd;i++){let w=typeof itemWidth==="number"?itemWidth:itemWidth(items[i],i),gapWidth=vpEnd>vpStart?gap:0;if(usedWidth>0&&usedWidth+gapWidth+w>effectiveViewport)break;usedWidth+=w+gapWidth,vpEnd=i+1}let visibleItems=items.slice(vpStart,vpEnd),overflowBefore=displayScrollOffset,overflowAfter=Math.max(0,items.length-displayScrollOffset-visibleCount),hasCustomIndicator=renderOverflowIndicator!=null,showIndicators=hasCustomIndicator||overflowIndicator===!0,showLeftIndicator=showIndicators&&overflowBefore>0,showRightIndicator=showIndicators&&overflowAfter>0;return jsxDEV5(Box,{flexDirection:"row",width,height,children:[showLeftIndicator&&(hasCustomIndicator?renderOverflowIndicator("before",overflowBefore):jsxDEV5(Box,{flexShrink:0,children:jsxDEV5(Text,{color:"$inverse",backgroundColor:"$inverse-bg",children:["◀",overflowBefore]},void 0,!0,void 0,this)},void 0,!1,void 0,this)),showIndicators&&!showLeftIndicator&&overflowIndicatorWidth>0&&jsxDEV5(Box,{width:overflowIndicatorWidth,flexShrink:0},void 0,!1,void 0,this),jsxDEV5(Box,{flexGrow:1,flexDirection:"row",overflow:"hidden",children:visibleItems.map((item,i)=>{let actualIndex=vpStart+i,key=keyExtractor?keyExtractor(item,actualIndex):actualIndex,isLast=i===visibleItems.length-1;return jsxDEV5(React4.Fragment,{children:[jsxDEV5(Box,{flexShrink:0,children:renderItem(item,actualIndex)},void 0,!1,void 0,this),!isLast&&renderSeparator&&renderSeparator(),!isLast&&gap>0&&!renderSeparator&&jsxDEV5(Box,{width:gap,flexShrink:0},void 0,!1,void 0,this)]},key,!0,void 0,this)})},void 0,!1,void 0,this),showRightIndicator&&(hasCustomIndicator?renderOverflowIndicator("after",overflowAfter):jsxDEV5(Box,{flexShrink:0,children:jsxDEV5(Text,{color:"$inverse",backgroundColor:"$inverse-bg",children:[overflowAfter,"▶"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)),showIndicators&&!showRightIndicator&&overflowIndicatorWidth>0&&jsxDEV5(Box,{width:overflowIndicatorWidth,flexShrink:0},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var DEFAULT_OVERSCAN3=1,DEFAULT_MAX_RENDERED3=20,SCROLL_PADDING=1,HorizontalVirtualList;var init_HorizontalVirtualList=__esm(()=>{init_useVirtualization();init_Box();init_Text();HorizontalVirtualList=forwardRef5(HorizontalVirtualListInner)});import{jsxDEV as jsxDEV6}from"react/jsx-dev-runtime";function SplitView(props){let{layout,renderPane,focusedPaneId,showBorders=!0,focusedBorderColor=DEFAULT_FOCUSED_COLOR,unfocusedBorderColor=DEFAULT_UNFOCUSED_COLOR,renderPaneTitle}=props;return jsxDEV6(Box,{flexGrow:1,flexDirection:"column",children:jsxDEV6(LayoutNodeView,{node:layout,renderPane,focusedPaneId,showBorders,focusedBorderColor,unfocusedBorderColor,renderPaneTitle},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function LayoutNodeView(props){let{node,renderPane,focusedPaneId,showBorders,focusedBorderColor,unfocusedBorderColor,renderPaneTitle}=props;if(node.type==="leaf")return jsxDEV6(LeafPane,{id:node.id,renderPane,isFocused:focusedPaneId===node.id,showBorders,focusedBorderColor,unfocusedBorderColor,title:renderPaneTitle?.(node.id)},void 0,!1,void 0,this);let isHorizontal=node.direction==="horizontal",firstPercent=`${Math.round(node.ratio*100)}%`,secondPercent=`${100-Math.round(node.ratio*100)}%`,firstFlex=Math.round(node.ratio*100),secondFlex=100-firstFlex;return jsxDEV6(Box,{flexGrow:1,flexDirection:isHorizontal?"row":"column",children:[jsxDEV6(Box,{width:isHorizontal?firstPercent:void 0,flexGrow:isHorizontal?void 0:firstFlex,flexShrink:1,minHeight:!isHorizontal?MIN_PANE_HEIGHT:void 0,overflow:"hidden",children:jsxDEV6(LayoutNodeView,{node:node.first,renderPane,focusedPaneId,showBorders,focusedBorderColor,unfocusedBorderColor,renderPaneTitle},void 0,!1,void 0,this)},void 0,!1,void 0,this),jsxDEV6(Box,{width:isHorizontal?secondPercent:void 0,flexGrow:isHorizontal?void 0:secondFlex,flexShrink:1,minHeight:!isHorizontal?MIN_PANE_HEIGHT:void 0,overflow:"hidden",children:jsxDEV6(LayoutNodeView,{node:node.second,renderPane,focusedPaneId,showBorders,focusedBorderColor,unfocusedBorderColor,renderPaneTitle},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function LeafPane(props){let{id,renderPane,isFocused,showBorders,focusedBorderColor,unfocusedBorderColor,title}=props;if(!showBorders)return jsxDEV6(Box,{flexGrow:1,testID:`pane-${id}`,children:renderPane(id)},void 0,!1,void 0,this);return jsxDEV6(Box,{flexGrow:1,flexBasis:0,overflow:"hidden",borderStyle:"single",borderColor:isFocused?focusedBorderColor:unfocusedBorderColor,testID:`pane-${id}`,flexDirection:"column",children:[title!=null&&jsxDEV6(Box,{children:jsxDEV6(Text,{color:isFocused?focusedBorderColor:unfocusedBorderColor,children:title},void 0,!1,void 0,this)},void 0,!1,void 0,this),jsxDEV6(Box,{flexGrow:1,children:renderPane(id)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var MIN_PANE_HEIGHT=5,DEFAULT_FOCUSED_COLOR="green",DEFAULT_UNFOCUSED_COLOR="gray";var init_SplitView=__esm(()=>{init_Box();init_Text()});function createLeaf(id){return{type:"leaf",id}}function getPaneIds(layout){if(layout.type==="leaf")return[layout.id];return[...getPaneIds(layout.first),...getPaneIds(layout.second)]}function getTabOrder(layout){return getPaneIds(layout)}function splitPane(layout,targetPaneId,direction,newPaneId,ratio=0.5){let clampedRatio=clampRatio(ratio);if(layout.type==="leaf"){if(layout.id===targetPaneId)return{type:"split",direction,ratio:clampedRatio,first:{type:"leaf",id:targetPaneId},second:{type:"leaf",id:newPaneId}};return layout}let newFirst=splitPane(layout.first,targetPaneId,direction,newPaneId,ratio),newSecond=splitPane(layout.second,targetPaneId,direction,newPaneId,ratio);if(newFirst===layout.first&&newSecond===layout.second)return layout;return{...layout,first:newFirst,second:newSecond}}function removePane(layout,paneId){if(layout.type==="leaf")return layout.id===paneId?null:layout;if(layout.first.type==="leaf"&&layout.first.id===paneId)return layout.second;if(layout.second.type==="leaf"&&layout.second.id===paneId)return layout.first;let newFirst=removePane(layout.first,paneId),newSecond=removePane(layout.second,paneId);if(newFirst===null)return newSecond;if(newSecond===null)return newFirst;if(newFirst===layout.first&&newSecond===layout.second)return layout;return{...layout,first:newFirst,second:newSecond}}function swapPanes(layout,paneId1,paneId2){if(layout.type==="leaf"){if(layout.id===paneId1)return{type:"leaf",id:paneId2};if(layout.id===paneId2)return{type:"leaf",id:paneId1};return layout}let newFirst=swapPanes(layout.first,paneId1,paneId2),newSecond=swapPanes(layout.second,paneId1,paneId2);if(newFirst===layout.first&&newSecond===layout.second)return layout;return{...layout,first:newFirst,second:newSecond}}function resizeSplit(layout,paneId,delta){if(layout.type==="leaf")return layout;if(getPaneIds(layout.first).includes(paneId)){let newRatio=clampRatio(layout.ratio+delta);if(newRatio===layout.ratio)return layout;return{...layout,ratio:newRatio}}if(getPaneIds(layout.second).includes(paneId)){let newRatio=clampRatio(layout.ratio-delta);if(newRatio===layout.ratio)return layout;return{...layout,ratio:newRatio}}return layout}function findAdjacentPane(layout,paneId,direction){let path=findPath(layout,paneId);if(!path)return null;let splitDirection=direction==="left"||direction==="right"?"horizontal":"vertical",goToSecond=direction==="right"||direction==="down";for(let i=path.length-1;i>=0;i--){let step=path[i];if(step.node.type!=="split")continue;if(step.node.direction!==splitDirection)continue;if(step.side==="first"&&goToSecond)return firstLeaf(step.node.second);if(step.side==="second"&&!goToSecond)return lastLeaf(step.node.first)}return null}function clampRatio(ratio){return Math.max(0.1,Math.min(0.9,ratio))}function firstLeaf(node){if(node.type==="leaf")return node.id;return firstLeaf(node.first)}function lastLeaf(node){if(node.type==="leaf")return node.id;return lastLeaf(node.second)}function findPath(layout,paneId){if(layout.type==="leaf")return layout.id===paneId?[]:null;let firstPath=findPath(layout.first,paneId);if(firstPath!==null)return[{node:layout,side:"first"},...firstPath];let secondPath=findPath(layout.second,paneId);if(secondPath!==null)return[{node:layout,side:"second"},...secondPath];return null}import{useMemo as useMemo6,Children,isValidElement,cloneElement}from"react";import{jsxDEV as jsxDEV7,Fragment}from"react/jsx-dev-runtime";function extractText(children){let text="";return Children.forEach(children,(child)=>{if(typeof child==="string")text+=child;else if(typeof child==="number")text+=String(child);else if(isValidElement(child)&&child.props.children!=null)text+=extractText(child.props.children)}),text}function renderWithText(children,text){let firstChild=Children.toArray(children)[0];if(isValidElement(firstChild))return cloneElement(firstChild,{wrap:"clip"},text);return jsxDEV7(Fragment,{children:text},void 0,!1,void 0,this)}function Fill({children,measurer}){let repeatedText=useMemo6(()=>{let pattern=extractText(children);if(!pattern)return null;let unitWidth=(measurer?measurer.displayWidth.bind(measurer):displayWidth)(pattern);if(unitWidth<=0)return null;let count=Math.ceil(MAX_FILL_COLS/unitWidth);return pattern.repeat(count)},[children,measurer]);if(!repeatedText)return jsxDEV7(Fragment,{children},void 0,!1,void 0,this);return renderWithText(children,repeatedText)}var MAX_FILL_COLS=500;var init_Fill=__esm(()=>{init_unicode()});import{useContext as useContext3,useMemo as useMemo7,useSyncExternalStore}from"react";function getOrCreateStore(rt){let store=stores.get(rt);if(store)return store;let state=INITIAL,listeners=new Set;function notify(){for(let cb of listeners)cb()}return rt.on("input",(_input,key)=>{let next={super:!!key.super,ctrl:!!key.ctrl,alt:!!key.meta,shift:!!key.shift};if(next.super!==state.super||next.ctrl!==state.ctrl||next.alt!==state.alt||next.shift!==state.shift)state=next,lastModifierState=next,notify()}),rt.on("focus",(focused)=>{if(!focused&&(state.super||state.ctrl||state.alt||state.shift))state=INITIAL,lastModifierState=INITIAL,notify()}),store={subscribe:(cb)=>{return listeners.add(cb),()=>listeners.delete(cb)},getSnapshot:()=>state},stores.set(rt,store),store}function getModifierState(rt){let store=stores.get(rt);return store?store.getSnapshot():INITIAL}function useModifierKeys(opts){let enabled=opts?.enabled??!0,rt=useContext3(RuntimeContext),store=useMemo7(()=>rt?getOrCreateStore(rt):null,[rt]);return useSyncExternalStore(enabled&&store?store.subscribe:noopSubscribe,store?store.getSnapshot:()=>INITIAL,()=>INITIAL)}var INITIAL,lastModifierState,stores,noopUnsubscribe=()=>{},noopSubscribe=(_cb)=>noopUnsubscribe;var init_useModifierKeys=__esm(()=>{init_context();INITIAL={super:!1,ctrl:!1,alt:!1,shift:!1},lastModifierState=INITIAL,stores=new WeakMap});import{hostname}from"node:os";function moveCursor(x,y){return`${CSI}${y+1};${x+1}H`}function cursorUp(n){if(n<=0)return"";if(n===1)return`${CSI}A`;return`${CSI}${n}A`}function cursorDown(n){if(n<=0)return"";if(n===1)return`${CSI}B`;return`${CSI}${n}B`}function cursorRight(n){if(n<=0)return"";if(n===1)return`${CSI}C`;return`${CSI}${n}C`}function cursorLeft(n){if(n<=0)return"";if(n===1)return`${CSI}D`;return`${CSI}${n}D`}function cursorToColumn(x){return`${CSI}${x+1}G`}function setCursorStyle(shape,blink=!1){let code=blink?CURSOR_SHAPE_CODES[shape].blink:CURSOR_SHAPE_CODES[shape].steady;return`${CSI}${code} q`}function resetCursorStyle(){return`${CSI}0 q`}function enterAlternateScreen(){return`${CSI}?1049h${CSI}2J${CURSOR_HOME}${CURSOR_HIDE}`}function leaveAlternateScreen(){return`${SYNC_END}${CURSOR_SHOW}${CSI}?1049l`}function enableMouse2(){return`${CSI}?1003h${CSI}?1006h`}function disableMouse2(){return`${CSI}?1006l${CSI}?1003l`}function enableKittyKeyboard2(flags=KittyFlags.DISAMBIGUATE){return`${CSI}>${flags}u`}function queryKittyKeyboard(){return`${CSI}?u`}function disableKittyKeyboard2(){return`${CSI}<u`}function notifyITerm2(message){return`${ESC}]9;${message}${BEL}`}function notifyKitty(message,opts){let params=opts?.title?`;t=t;${opts.title}`:"";return`${ESC}]99;i=1:d=0${params};${message}${ESC}\\`}function notify(stdout,message,opts){let termProgram=process.env.TERM_PROGRAM??"",term2=process.env.TERM??"";if(termProgram==="iTerm.app")stdout.write(notifyITerm2(message));else if(term2==="xterm-kitty")stdout.write(notifyKitty(message,opts));else stdout.write(BEL)}function setWindowTitle(stdout,title){stdout.write(`${ESC}]2;${title}${BEL}`)}function setWindowAndIconTitle(stdout,title){stdout.write(`${ESC}]0;${title}${BEL}`)}function resetWindowTitle(stdout){stdout.write(`${ESC}]2;${BEL}`)}function reportDirectory(stdout,path){let host=hostname(),encoded=encodeURI(path).replace(/#/g,"%23");stdout.write(`${ESC}]7;file://${host}${encoded}${BEL}`)}function setMouseCursorShape(shape){return`${ESC}]22;${shape}${BEL}`}function resetMouseCursorShape(){return`${ESC}]22;default${BEL}`}var ESC="\x1B",CSI,CURSOR_HIDE,CURSOR_SHOW,CURSOR_HOME,SYNC_BEGIN,SYNC_END,RESET,SGR,CURSOR_SHAPE_CODES,KittyFlags,BEL="\x07",ANSI;var init_output=__esm(()=>{CSI=`${ESC}[`,CURSOR_HIDE=`${CSI}?25l`,CURSOR_SHOW=`${CSI}?25h`,CURSOR_HOME=`${CSI}H`,SYNC_BEGIN=`${CSI}?2026h`,SYNC_END=`${CSI}?2026l`,RESET=`${CSI}0m`,SGR={bold:1,dim:2,italic:3,underline:4,blink:5,inverse:7,hidden:8,strikethrough:9,boldOff:22,italicOff:23,underlineOff:24,blinkOff:25,inverseOff:27,hiddenOff:28,strikethroughOff:29,fgDefault:39,fgBlack:30,fgRed:31,fgGreen:32,fgYellow:33,fgBlue:34,fgMagenta:35,fgCyan:36,fgWhite:37,fgBrightBlack:90,fgBrightRed:91,fgBrightGreen:92,fgBrightYellow:93,fgBrightBlue:94,fgBrightMagenta:95,fgBrightCyan:96,fgBrightWhite:97,bgDefault:49,bgBlack:40,bgRed:41,bgGreen:42,bgYellow:43,bgBlue:44,bgMagenta:45,bgCyan:46,bgWhite:47,bgBrightBlack:100,bgBrightRed:101,bgBrightGreen:102,bgBrightYellow:103,bgBrightBlue:104,bgBrightMagenta:105,bgBrightCyan:106,bgBrightWhite:107};CURSOR_SHAPE_CODES={block:{blink:1,steady:2},underline:{blink:3,steady:4},bar:{blink:5,steady:6}};KittyFlags={DISAMBIGUATE:1,REPORT_EVENTS:2,REPORT_ALTERNATE:4,REPORT_ALL_KEYS:8,REPORT_TEXT:16};ANSI={ESC,CSI,CURSOR_HIDE,CURSOR_SHOW,CURSOR_HOME,SYNC_BEGIN,SYNC_END,RESET,SGR,moveCursor,cursorUp,cursorDown,cursorLeft,cursorRight,cursorToColumn}});import{useEffect as useEffect4,useContext as useContext4}from"react";function useMouseCursor(shape){let term2=useContext4(TermContext);useEffect4(()=>{if(!shape||!term2)return;return term2.write(setMouseCursorShape(shape)),()=>{term2.write(resetMouseCursorShape())}},[shape,term2])}var init_useMouseCursor=__esm(()=>{init_context();init_output()});import{useCallback as useCallback5,useContext as useContext5,useState as useState4}from"react";import{jsxDEV as jsxDEV8}from"react/jsx-dev-runtime";function osc8Open(href){return`\x1B]8;;${href}\x1B\\`}function Link({href,children,color="$link",variant="arm-on-cmd-hover",onClick,onMouseEnter,onMouseLeave,...rest}){let[hovered,setHovered]=useState4(!1),rt=useContext5(RuntimeContext),needsModifier=variant==="arm-on-cmd-hover",{super:cmdHeld}=useModifierKeys({enabled:hovered&&needsModifier}),armed=hovered&&(needsModifier?cmdHeld:!0);if(armed)rest.underline=!0;useMouseCursor(armed?"pointer":null);let handleClick=useCallback5((e)=>{if(armed||needsModifier&&hovered&&e.metaKey)rt?.emit("link:open",href),e.preventDefault();onClick?.(e)},[armed,needsModifier,hovered,href,onClick,rt]);return jsxDEV8(Text,{color,...rest,onClick:handleClick,onMouseEnter:(e)=>{setHovered(!0),onMouseEnter?.(e)},onMouseLeave:(e)=>{setHovered(!1),onMouseLeave?.(e)},children:[osc8Open(href),children,OSC8_CLOSE]},void 0,!0,void 0,this)}var OSC8_CLOSE="\x1B]8;;\x1B\\";var init_Link=__esm(()=>{init_Text();init_useModifierKeys();init_useMouseCursor();init_context()});import{Component}from"react";import{jsxDEV as jsxDEV9}from"react/jsx-dev-runtime";var ErrorBoundary;var init_ErrorBoundary=__esm(()=>{init_Box();init_Text();ErrorBoundary=class ErrorBoundary extends Component{state={hasError:!1,error:null,errorInfo:null};static getDerivedStateFromError(error){return{hasError:!0,error}}componentDidCatch(error,errorInfo){this.setState({errorInfo}),this.props.onError?.(error,errorInfo)}componentDidUpdate(prevProps){if(!this.state.hasError)return;let resetKeyChanged=this.props.resetKey!==void 0&&prevProps.resetKey!==this.props.resetKey,resetKeysChanged=this.props.resetKeys!==void 0&&(this.props.resetKeys.length!==prevProps.resetKeys?.length||this.props.resetKeys.some((key,i)=>key!==prevProps.resetKeys?.[i]));if(resetKeyChanged||resetKeysChanged)this.props.onReset?.(),this.setState({hasError:!1,error:null,errorInfo:null})}render(){if(this.state.hasError){let{fallback}=this.props,{error,errorInfo}=this.state;if(typeof fallback==="function"&&error)return fallback(error,errorInfo??{componentStack:null});if(fallback!==void 0)return fallback;return jsxDEV9(Box,{borderStyle:"single",borderColor:"$error",padding:1,flexDirection:"column",children:[jsxDEV9(Text,{color:"$error",bold:!0,children:"Error"},void 0,!1,void 0,this),error&&jsxDEV9(Text,{color:"$error",children:error.message},void 0,!1,void 0,this),errorInfo?.componentStack&&jsxDEV9(Text,{dim:!0,wrap:"truncate",children:errorInfo.componentStack.split(`
17
+ `).slice(0,3).join(`
18
+ `)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}return this.props.children}}});import{useEffect as useEffect5,useState as useState5}from"react";function useConsole(patched,debounceMs=200){let[entries,setEntries]=useState5(patched.getSnapshot);return useEffect5(()=>{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}var init_useConsole=()=>{};import{jsxDEV as jsxDEV10}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}){let entries=useConsole(patched);return jsxDEV10(Box,{flexDirection:"column",children:entries.map((entry,i)=>children?children(entry,i):jsxDEV10(Text,{color:entry.stream==="stderr"?"red":void 0,children:formatArgs(entry.args)},i,!1,void 0,this))},void 0,!1,void 0,this)}var init_Console=__esm(()=>{init_useConsole();init_Box();init_Text()});var OSC133;var init_osc_markers=__esm(()=>{OSC133={promptStart:"\x1B]133;A\x07",promptEnd:"\x1B]133;B\x07",commandStart:"\x1B]133;C\x07",commandEnd:(exitCode)=>`\x1B]133;D;${exitCode??0}\x07`}});import{useContext as useContext6,useLayoutEffect as useLayoutEffect2,useRef as useRef6}from"react";function countNewlines(s){let count=0;for(let i=0;i<s.length;i++)if(s.charCodeAt(i)===10)count++;return count}function resolveMarkers(markers,item,index){if(!markers)return{before:"",after:""};if(markers===!0)return{before:OSC133.promptStart,after:OSC133.commandEnd(0)};return{before:markers.before?.(item,index)??"",after:markers.after?.(item,index)??""}}function useScrollback(items,options){let{frozen,render,stdout=process.stdout,markers,width}=options,stdoutCtx=useContext6(StdoutContext),frozenCount=0;for(let i=0;i<items.length;i++){if(!frozen(items[i],i))break;frozenCount++}let prevFrozenCountRef=useRef6(0),renderedStringsRef=useRef6(new Map),prevWidthRef=useRef6(width),totalFrozenLinesRef=useRef6(0),renderRef=useRef6(render);renderRef.current=render;let itemsRef=useRef6(items);itemsRef.current=items;let markersRef=useRef6(markers);markersRef.current=markers;let frozenCountRef=useRef6(frozenCount);return frozenCountRef.current=frozenCount,useLayoutEffect2(()=>{let prev=prevFrozenCountRef.current;if(frozenCount>prev)if(stdoutCtx?.promoteScrollback){let frozenContent="",linesWritten=0;for(let i=prev;i<frozenCount;i++){let{before,after}=resolveMarkers(markers,items[i],i);if(before)frozenContent+=before;let text=render(items[i],i)+`
19
+ `;if(frozenContent+=text.replace(/\n/g,`\x1B[K\r
20
+ `),linesWritten+=countNewlines(text),renderedStringsRef.current.set(i,text),after)frozenContent+=after}totalFrozenLinesRef.current+=linesWritten,stdoutCtx.promoteScrollback(frozenContent,linesWritten)}else{let linesWritten=0;for(let i=prev;i<frozenCount;i++){let{before,after}=resolveMarkers(markers,items[i],i);if(before)stdout.write(before);let text=render(items[i],i)+`
21
+ `;if(stdout.write(text.replace(/\n/g,`\r
22
+ `)),linesWritten+=countNewlines(text),renderedStringsRef.current.set(i,text),after)stdout.write(after)}totalFrozenLinesRef.current+=linesWritten,stdoutCtx?.notifyScrollback?.(linesWritten)}prevFrozenCountRef.current=frozenCount},[frozenCount,items,render,stdout,stdoutCtx,markers]),useLayoutEffect2(()=>{if(width===void 0)return;let prevWidth=prevWidthRef.current;if(prevWidthRef.current=width,prevWidth===void 0||width===prevWidth)return;let currentFrozenCount=frozenCountRef.current;if(currentFrozenCount===0)return;let currentItems=itemsRef.current,currentRender=renderRef.current,currentMarkers=markersRef.current;stdoutCtx?.resetInlineCursor?.(),stdout.write("\x1B[3J\x1B[H\x1B[2J");let linesWritten=0;for(let i=0;i<currentFrozenCount;i++){let{before,after}=resolveMarkers(currentMarkers,currentItems[i],i);if(before)stdout.write(before);let text=currentRender(currentItems[i],i)+`
23
+ `;if(stdout.write(text.replace(/\n/g,`\r
24
+ `)),linesWritten+=countNewlines(text),renderedStringsRef.current.set(i,text),after)stdout.write(after)}totalFrozenLinesRef.current=linesWritten,prevFrozenCountRef.current=currentFrozenCount},[width,stdout,stdoutCtx]),frozenCount}var init_useScrollback=__esm(()=>{init_context();init_osc_markers()});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()+`
25
+ `+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 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 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)return{top:0,bottom:0,left:0,right:0};return{top:props.borderTop!==!1?1:0,bottom:props.borderBottom!==!1?1:0,left:props.borderLeft!==!1?1:0,right:props.borderRight!==!1?1:0}}function measurePhase(root,ctx){traverseTree(root,(node)=>{if(!node.layoutNode)return;let props=node.props;if(props.width==="fit-content"||props.height==="fit-content"){let availableWidth;if(props.height==="fit-content"&&props.width!=="fit-content"&&typeof props.width==="number"){let padding=getPadding(props);if(availableWidth=props.width-padding.left-padding.right,props.borderStyle){let border=getBorderSize(props);availableWidth-=border.left+border.right}if(availableWidth<1)availableWidth=1}let intrinsicSize=measureIntrinsicSize(node,ctx,availableWidth);if(props.width==="fit-content")node.layoutNode.setWidth(intrinsicSize.width);if(props.height==="fit-content")node.layoutNode.setHeight(intrinsicSize.height)}})}function measureIntrinsicSize(node,ctx,availableWidth){let props=node.props;if(props.display==="none")return{width:0,height:0};if(node.type==="silvery-text"){let textProps=props,text=collectPlainText(node),transform=textProps.internal_transform,lines;if(availableWidth!==void 0&&availableWidth>0&&isWrapEnabled(textProps.wrap))lines=ctx?ctx.measurer.wrapText(text,availableWidth,!0,!0):wrapText(text,availableWidth,!0,!0);else lines=text.split(`
26
+ `);if(transform)lines=lines.map((line,index)=>transform(line,index));return{width:Math.max(...lines.map((line)=>getTextWidth(line,ctx))),height:lines.length}}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===!0||wrap===void 0}function traverseTree(node,callback){callback(node);for(let child of node.children)traverseTree(child,callback)}function getTextWidth(text,ctx){if(ctx)return ctx.measurer.displayWidthAnsi(text);return displayWidthAnsi(text)}var init_measure_phase=__esm(()=>{init_unicode()});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}import{createLogger}from"loggily";function layoutPhase(root,width,height){let prevLayout=root.contentRect;if(!(prevLayout&&(prevLayout.width!==width||prevLayout.height!==height))&&!hasLayoutDirtyNodes(root))return;if(root.layoutNode){let nodeCount=countNodes(root);measureStats.reset();let t0=Date.now();root.layoutNode.calculateLayout(width,height);let elapsed=Date.now()-t0;log.debug?.(`calculateLayout: ${elapsed}ms (${nodeCount} nodes) measure: calls=${measureStats.calls} hits=${measureStats.cacheHits} collects=${measureStats.textCollects} displayWidth=${measureStats.displayWidthCalls}`)}propagateLayout(root,0,0)}function countNodes(node){let count=1;for(let child of node.children)count+=countNodes(child);return count}function hasLayoutDirtyNodes(node,path="root"){if(node.layoutDirty){let props=node.props;return log.debug?.(`dirty node found: ${path} (id=${props.id??"?"}, type=${node.type})`),!0}for(let i=0;i<node.children.length;i++)if(hasLayoutDirtyNodes(node.children[i],`${path}[${i}]`))return!0;return!1}function propagateLayout(node,parentX,parentY){if(node.prevLayout=node.contentRect,!node.layoutNode){let rect2={x:parentX,y:parentY,width:0,height:0};node.contentRect=rect2,node.layoutDirty=!1;for(let child of node.children)propagateLayout(child,parentX,parentY);return}let rect={x:parentX+node.layoutNode.getComputedLeft(),y:parentY+node.layoutNode.getComputedTop(),width:node.layoutNode.getComputedWidth(),height:node.layoutNode.getComputedHeight()};if(node.contentRect=rect,node.layoutDirty=!1,node.layoutChangedThisFrame=!!(node.prevLayout&&!rectEqual(node.prevLayout,node.contentRect)),process.env.SILVERY_STRICT&&node.layoutChangedThisFrame){if(rectEqual(node.prevLayout,node.contentRect)){let props=node.props;throw Error(`[SILVERY_STRICT] layoutChangedThisFrame=true but prevLayout equals contentRect (node: ${props.id??node.type}, rect: ${JSON.stringify(node.contentRect)})`)}}if(node.layoutChangedThisFrame){let ancestor=node.parent;while(ancestor&&!ancestor.subtreeDirty)ancestor.subtreeDirty=!0,ancestor=ancestor.parent}for(let child of node.children)propagateLayout(child,rect.x,rect.y)}function notifyLayoutSubscribers(node){let contentChanged=!rectEqual(node.prevLayout,node.contentRect),screenChanged=!rectEqual(node.prevScreenRect,node.screenRect),renderChanged=!rectEqual(node.prevRenderRect,node.renderRect);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.contentRect;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.contentRect)continue;let childTop=child.contentRect.y-layout.y-border.top-padding.top,childBottom=childTop+child.contentRect.height,childProps=child.props;childPositions.push({child,top:childTop,bottom:childBottom,index:i,isSticky:childProps.position==="sticky",stickyTop:childProps.stickyTop,stickyBottom:childProps.stickyBottom}),contentHeight=Math.max(contentHeight,childBottom)}let viewportHeight=rawViewportHeight,showBorderlessIndicator=props.overflowIndicator===!0&&!props.borderStyle,hasOverflow=contentHeight>rawViewportHeight,indicatorReserve=showBorderlessIndicator&&hasOverflow?1:0,prevOffset=node.scrollState?.offset,scrollOffset=props.scrollOffset??prevOffset??0,scrollTo=props.scrollTo;if(scrollTo!==void 0&&scrollTo>=0&&scrollTo<childPositions.length){let target=childPositions.find((c)=>c.index===scrollTo);if(target){let effectiveHeight=viewportHeight-indicatorReserve,visibleTop2=scrollOffset,visibleBottom2=scrollOffset+effectiveHeight;if(target.top<visibleTop2)scrollOffset=target.top;else if(target.bottom>visibleBottom2)scrollOffset=target.bottom-effectiveHeight;scrollOffset=Math.max(0,scrollOffset),scrollOffset=Math.min(scrollOffset,Math.max(0,contentHeight-viewportHeight))}}let visibleTop=scrollOffset,visibleBottom=scrollOffset+viewportHeight-indicatorReserve,firstVisible=-1,lastVisible=-1,hiddenAbove=0,hiddenBelow=0;for(let cp of childPositions){if(cp.isSticky){if(firstVisible===-1)firstVisible=cp.index;lastVisible=Math.max(lastVisible,cp.index);continue}if(cp.top===cp.bottom)continue;if(cp.bottom<=visibleTop)hiddenAbove++;else if(cp.top>=visibleBottom)hiddenBelow++;else if(cp.top<visibleTop){if(firstVisible===-1)firstVisible=cp.index;lastVisible=Math.max(lastVisible,cp.index)}else if(cp.bottom>visibleBottom){if(firstVisible===-1)firstVisible=cp.index;if(lastVisible=cp.index,indicatorReserve>0)hiddenBelow++}else{if(firstVisible===-1)firstVisible=cp.index;lastVisible=cp.index}}let stickyChildren=[];for(let cp of childPositions){if(!cp.isSticky)continue;let childHeight=cp.bottom-cp.top,stickyTop=cp.stickyTop??0,stickyBottom=cp.stickyBottom,naturalRenderY=cp.top-scrollOffset,renderOffset;if(stickyBottom!==void 0){let bottomPinPosition=viewportHeight-stickyBottom-childHeight;renderOffset=Math.min(naturalRenderY,bottomPinPosition)}else if(naturalRenderY>=stickyTop)renderOffset=naturalRenderY;else if(childHeight>viewportHeight)renderOffset=Math.max(viewportHeight-childHeight,naturalRenderY);else renderOffset=stickyTop;if(renderOffset!==naturalRenderY)if(childHeight>viewportHeight)renderOffset=Math.max(viewportHeight-childHeight,renderOffset);else renderOffset=Math.max(0,Math.min(renderOffset,viewportHeight-childHeight));if(renderOffset+childHeight<=0||renderOffset>=viewportHeight)continue;stickyChildren.push({index:cp.index,renderOffset,naturalTop:cp.top,height:childHeight})}if(skipStateUpdates)return;let prevFirstVisible=node.scrollState?.firstVisibleChild??firstVisible,prevLastVisible=node.scrollState?.lastVisibleChild??lastVisible;if(scrollOffset!==prevOffset||firstVisible!==prevFirstVisible||lastVisible!==prevLastVisible)node.subtreeDirty=!0;node.scrollState={offset:scrollOffset,prevOffset:prevOffset??scrollOffset,contentHeight,viewportHeight,firstVisibleChild:firstVisible,lastVisibleChild:lastVisible,prevFirstVisibleChild:prevFirstVisible,prevLastVisibleChild:prevLastVisible,hiddenAbove,hiddenBelow,stickyChildren:stickyChildren.length>0?stickyChildren:void 0}}function stickyPhase(root){traverseTree2(root,(node)=>{let props=node.props;if(props.overflow==="scroll")return;let hasStickyChildren=!1;for(let child of node.children){let childProps=child.props;if(childProps.position==="sticky"&&childProps.stickyBottom!==void 0){hasStickyChildren=!0;break}}if(!hasStickyChildren){if(node.stickyChildren!==void 0)node.stickyChildren=void 0,node.subtreeDirty=!0;return}let layout=node.contentRect;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.contentRect)continue;let naturalY=child.contentRect.y-layout.y-border.top-padding.top,childHeight=child.contentRect.height,stickyBottom=childProps.stickyBottom,bottomPin=parentContentHeight-stickyBottom-childHeight,renderOffset=Math.max(naturalY,bottomPin);newStickyChildren.push({index:i,renderOffset,naturalTop:naturalY,height:childHeight})}let prev=node.stickyChildren,next=newStickyChildren.length>0?newStickyChildren:void 0,changed=!stickyChildrenEqual(prev,next);if(node.stickyChildren=next,changed)node.subtreeDirty=!0})}function stickyChildrenEqual(a,b){if(a===b)return!0;if(!a||!b)return!1;if(a.length!==b.length)return!1;for(let i=0;i<a.length;i++){let ai=a[i],bi=b[i];if(ai.index!==bi.index||ai.renderOffset!==bi.renderOffset||ai.naturalTop!==bi.naturalTop||ai.height!==bi.height)return!1}return!0}function traverseTree2(node,callback){callback(node);for(let child of node.children)traverseTree2(child,callback)}function screenRectPhase(root){propagateScreenRect(root,0)}function propagateScreenRect(node,ancestorScrollOffset){node.prevScreenRect=node.screenRect,node.prevRenderRect=node.renderRect;let content=node.contentRect;if(!content){node.screenRect=null,node.renderRect=null;for(let child of node.children)propagateScreenRect(child,ancestorScrollOffset);return}node.screenRect={x:content.x,y:content.y-ancestorScrollOffset,width:content.width,height:content.height},node.renderRect=node.screenRect;let scrollOffset=node.scrollState?.offset??0,childScrollOffset=ancestorScrollOffset+scrollOffset;computeStickyRenderRects(node);for(let child of node.children)propagateScreenRect(child,childScrollOffset)}function computeStickyRenderRects(parent){let stickyList=parent.scrollState?.stickyChildren??parent.stickyChildren;if(!stickyList||stickyList.length===0)return;let parentScreenRect=parent.screenRect;if(!parentScreenRect)return;let props=parent.props,border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},padding=getPadding(props),contentOriginY=parentScreenRect.y+border.top+padding.top;for(let sticky of stickyList){let child=parent.children[sticky.index];if(!child?.screenRect)continue;child.renderRect={x:child.screenRect.x,y:contentOriginY+sticky.renderOffset,width:child.screenRect.width,height:child.screenRect.height}}}var log;var init_layout_phase=__esm(()=>{init_measure_stats();log=createLogger("silvery:layout")});function hexToRgb(hex){let match=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex);if(!match)return null;return[parseInt(match[1],16),parseInt(match[2],16),parseInt(match[3],16)]}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 contrastFg(bg){let rgb=hexToRgb(bg);if(!rgb)return"#FFFFFF";let[r,g,b]=rgb.map((c)=>{let s=c/255;return s<=0.03928?s/12.92:Math.pow((s+0.055)/1.055,2.4)});return 0.2126*r+0.7152*g+0.0722*b>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 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 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=()=>{};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_contrast()});var catppuccinMocha,catppuccinFrappe,catppuccinMacchiato,catppuccinLatte;var init_catppuccin=__esm(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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(()=>{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"}});function getThemeByName(name){if(!name)return ansi16DarkTheme;let builtin=builtinThemes[name];if(builtin)return builtin;let palette=builtinPalettes[name];if(palette)return deriveTheme(palette);return ansi16DarkTheme}var ansi16DarkTheme,ansi16LightTheme,defaultDarkTheme,defaultLightTheme,builtinPalettes,builtinThemes;var init_palettes=__esm(()=>{init_derive();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_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();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"]},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},builtinThemes={"dark-ansi16":ansi16DarkTheme,"light-ansi16":ansi16LightTheme,"dark-truecolor":defaultDarkTheme,"light-truecolor":defaultLightTheme,dark:defaultDarkTheme,light:defaultLightTheme,"ansi16-dark":ansi16DarkTheme,"ansi16-light":ansi16LightTheme}});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=ansi16DarkTheme;_contextStack=[]});function resolveThemeColor(color,theme){if(!color)return;if(!color.startsWith("$"))return color;let token=color.slice(1);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:color}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(style){if(style&&typeof style==="object"){let obj=style,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[style??"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_unicode();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:"|"}}});function getBgConflictMode(){return bgConflictMode}function clearBgConflictWarnings(){warnedBgConflicts.clear()}function styleToAnsi(style){let codes=[];if(style.color){let color=parseColor(style.color);if(color!==null)if(typeof color==="number")codes.push(38,5,color);else codes.push(38,2,color.r,color.g,color.b)}if(style.bold)codes.push(1);if(style.dim)codes.push(2);if(style.italic)codes.push(3);if(style.underline)codes.push(4);if(style.inverse)codes.push(7);if(style.strikethrough)codes.push(9);if(codes.length===0)return"";return`\x1B[${codes.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??parent.underline,inverse:childProps.inverse??parent.inverse,strikethrough:childProps.strikethrough??parent.strikethrough}}function applyTextStyleAnsi(text,childStyle,parentStyle){if(!text)return text;let childAnsi=styleToAnsi(childStyle),parentAnsi=styleToAnsi(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]===`
27
+ `)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===`
28
+ `||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(`
29
+ `);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===!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(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){if(hasAnsi(text))return renderAnsiTextLineReturn(buffer,x,y,text,baseStyle,maxCol,inheritedBg,ctx);return renderGraphemes(buffer,splitGraphemes(text),x,y,baseStyle,maxCol,inheritedBg,ctx)}function renderGraphemes(buffer,graphemes,startCol,y,style,maxCol,inheritedBg,ctx){let col=startCol,rightEdge=maxCol!==void 0?Math.min(maxCol,buffer.width):buffer.width,gWidthFn=ctx?ctx.measurer.graphemeWidth:graphemeWidth;for(let grapheme of graphemes){if(col>=rightEdge)break;let width=gWidthFn(grapheme);if(width===0)continue;let existingBg=style.bg!==null?style.bg:inheritedBg!==void 0?inheritedBg:buffer.getCellBg(col,y);if(width===2&&col+1>=rightEdge){buffer.setCell(col,y,{char:" ",fg:style.fg,bg:existingBg,underlineColor:style.underlineColor??null,attrs:style.attrs,wide:!1,continuation:!1,hyperlink:style.hyperlink}),col+=1;continue}let outputChar=width===2?ensureEmojiPresentation(grapheme):grapheme;if(buffer.setCell(col,y,{char:outputChar,fg:style.fg,bg:existingBg,underlineColor:style.underlineColor??null,attrs:style.attrs,wide:width===2,continuation:!1,hyperlink:style.hyperlink}),width===2&&col+1<buffer.width){let existingBg2=style.bg!==null?style.bg:inheritedBg!==void 0?inheritedBg:buffer.getCellBg(col+1,y);buffer.setCell(col+1,y,{char:"",fg:style.fg,bg:existingBg2,underlineColor:style.underlineColor??null,attrs:style.attrs,wide:!1,continuation:!0,hyperlink:style.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){let segments=parseAnsiText(text),col=x;for(let segment of segments){let style=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),msg=`[silvery] Background conflict: chalk.bg* on text that already has silvery background. Chalk bg will override only text characters, causing visual gaps in padding. Use ansi.bgOverride() to suppress if intentional. Text: "${preview}${segment.text.length>30?"...":""}"`;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),console.warn(msg)}}col=renderGraphemes(buffer,splitGraphemes(segment.text),col,y,style,maxCol,inheritedBg,ctx)}return col}function mergeStyles(base,overlay,options={}){let{preserveDecorations=!0,preserveEmphasis=!0}=options,baseAttrs=base.attrs??{},overlayAttrs=overlay.attrs??{},attrs={};if(preserveDecorations){let hasBaseUnderline=baseAttrs.underline||baseAttrs.underlineStyle,hasOverlayUnderline=overlayAttrs.underline||overlayAttrs.underlineStyle;if(hasBaseUnderline||hasOverlayUnderline)attrs.underline=!0,attrs.underlineStyle=overlayAttrs.underlineStyle??baseAttrs.underlineStyle??"single";attrs.strikethrough=overlayAttrs.strikethrough||baseAttrs.strikethrough}else attrs.underline=overlayAttrs.underline??baseAttrs.underline,attrs.underlineStyle=overlayAttrs.underlineStyle??baseAttrs.underlineStyle,attrs.strikethrough=overlayAttrs.strikethrough??baseAttrs.strikethrough;if(preserveEmphasis)attrs.bold=overlayAttrs.bold||baseAttrs.bold,attrs.dim=overlayAttrs.dim||baseAttrs.dim,attrs.italic=overlayAttrs.italic||baseAttrs.italic;else attrs.bold=overlayAttrs.bold??baseAttrs.bold,attrs.dim=overlayAttrs.dim??baseAttrs.dim,attrs.italic=overlayAttrs.italic??baseAttrs.italic;return attrs.inverse=overlayAttrs.inverse,attrs.hidden=overlayAttrs.hidden,attrs.blink=overlayAttrs.blink,{fg:overlay.fg??base.fg,bg:overlay.bg??base.bg,underlineColor:overlay.underlineColor??base.underlineColor,attrs}}function mergeAnsiStyle(base,segment,options={}){let{preserveDecorations=!0,preserveEmphasis=!0}=options,fg=base.fg,bg=base.bg,underlineColor2=base.underlineColor??null;if(segment.fg!==void 0&&segment.fg!==null)fg=ansiColorToColor(segment.fg);if(segment.bg!==void 0&&segment.bg!==null)bg=ansiColorToColor(segment.bg);if(segment.underlineColor!==void 0&&segment.underlineColor!==null)underlineColor2=ansiColorToColor(segment.underlineColor);let overlayAttrs={};if(segment.bold!==void 0)overlayAttrs.bold=segment.bold;if(segment.dim!==void 0)overlayAttrs.dim=segment.dim;if(segment.italic!==void 0)overlayAttrs.italic=segment.italic;if(segment.underline!==void 0)overlayAttrs.underline=segment.underline;if(segment.underlineStyle!==void 0)overlayAttrs.underlineStyle=segment.underlineStyle;if(segment.inverse!==void 0)overlayAttrs.inverse=segment.inverse;let merged=mergeStyles(base,{fg,bg,underlineColor:underlineColor2,attrs:overlayAttrs},{preserveDecorations,preserveEmphasis});if(segment.hyperlink)merged.hyperlink=segment.hyperlink;return merged}function ansiColorToColor(code){if(code>=16777216){let r=code>>16&255,g=code>>8&255,b=code&255;return{r,g,b}}if(code<30||code>=38&&code<40||code>=48&&code<90)return code;if(code>=30&&code<=37)return code-30;if(code>=40&&code<=47)return code-40;if(code>=90&&code<=97)return code-90+8;if(code>=100&&code<=107)return code-100+8;return null}function renderText(node,buffer,layout,props,nodeState,inheritedBg,inheritedFg,ctx){let{scrollOffset,clipBounds}=nodeState,{x,width,height}=layout,{y}=layout;if(y-=scrollOffset,props.backgroundColor==="")inheritedBg=null;if(clipBounds){if(y+height<=clipBounds.top||y>=clipBounds.bottom)return;if(clipBounds.left!==void 0&&clipBounds.right!==void 0){if(x+width<=clipBounds.left||x>=clipBounds.right)return}}let maxDisplayWidth;if((props.wrap===!1||props.wrap==="truncate-end"||props.wrap==="truncate"||props.wrap==="clip")&&width>0){let lineCount=(collectPlainText(node).match(/\n/g)?.length??0)+1;maxDisplayWidth=(width+1)*lineCount}let{text,bgSegments,childSpans}=collectTextWithBg(node,{},0,maxDisplayWidth,ctx),style=getTextStyle(props);if(style.fg===null&&inheritedFg!==void 0)style.fg=inheritedFg;let hasBg=style.bg!==null||bgSegments.length>0||inheritedBg!==void 0&&inheritedBg!==null,lines=formatTextLines(text,width,props.wrap,ctx,!hasBg),internalTransform=props.internal_transform;if(internalTransform)lines=lines.map((line,index)=>internalTransform(line,index));let lineOffsets=bgSegments.length>0||childSpans.length>0?mapLinesToCharOffsets(text,lines,ctx):[];for(let lineIdx=0;lineIdx<lines.length&&lineIdx<height;lineIdx++){let lineY=y+lineIdx;if(clipBounds&&(lineY<clipBounds.top||lineY>=clipBounds.bottom))continue;let line=lines[lineIdx],layoutRight=internalTransform?buffer.width:x+width,maxCol=clipBounds&&"right"in clipBounds&&clipBounds.right!==void 0?Math.min(layoutRight,clipBounds.right):layoutRight,endCol=renderTextLineReturn(buffer,x,lineY,line,style,maxCol,inheritedBg,ctx);if(endCol<maxCol){let clearBg=inheritedBg??null;for(let cx=endCol;cx<maxCol&&cx<buffer.width;cx++)buffer.setCell(cx,lineY,{char:" ",fg:style.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 bgConflictMode,warnedBgConflicts;var init_render_text=__esm(()=>{init_buffer();init_unicode();init_render_helpers();bgConflictMode=(()=>{let env=process.env.SILVERY_BG_CONFLICT?.toLowerCase();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){let{scrollOffset,clipBounds}=nodeState,{x,width,height}=layout,y=layout.y-scrollOffset;if(clipBounds){if(y+height<=clipBounds.top||y>=clipBounds.bottom)return;if(clipBounds.left!==void 0&&clipBounds.right!==void 0){if(x+width<=clipBounds.left||x>=clipBounds.right)return}}let effectiveBgStr=getEffectiveBg(props);if(effectiveBgStr&&!skipBgFill){let bg=parseColor(effectiveBgStr);if(clipBounds){let clippedY=Math.max(y,clipBounds.top),clippedHeight=Math.min(y+height,clipBounds.bottom)-clippedY,clippedX=x,clippedWidth=width;if(clipBounds.left!==void 0&&clipBounds.right!==void 0)clippedX=Math.max(x,clipBounds.left),clippedWidth=Math.min(x+width,clipBounds.right)-clippedX;if(clippedHeight>0&&clippedWidth>0)buffer.fill(clippedX,clippedY,clippedWidth,clippedHeight,{bg})}else buffer.fill(x,y,width,height,{bg})}if(props.borderStyle)renderBorder(buffer,x,y,width,height,props,clipBounds,inheritedBg)}function renderBorder(buffer,x,y,width,height,props,clipBounds,inheritedBg){let chars=getBorderChars(props.borderStyle??"single"),color=props.borderColor?parseColor(props.borderColor):null,bg=props.backgroundColor?parseColor(props.backgroundColor):inheritedBg??null,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});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});if(showRight&&x+width-1<buffer.width&&isColVisible(x+width-1))buffer.setCell(x+width-1,y,{char:chars.topRight,fg:color,bg})}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});if(showRight&&x+width-1<buffer.width&&isColVisible(x+width-1))buffer.setCell(x+width-1,row,{char:rightVertical,fg:color,bg})}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});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});if(showRight&&x+width-1<buffer.width&&isColVisible(x+width-1))buffer.setCell(x+width-1,bottomY,{char:chars.bottomRight,fg:color,bg})}}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_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,contentAreaAffected=contentDirty||layoutChanged||childPositionChanged||childrenDirty||bgDirty||isTextNode&&stylePropsDirty||absoluteChildMutated||descendantOverflowChanged,bgRefillNeeded=hasPrevBuffer&&!contentAreaAffected&&subtreeDirty&&hasBgColor;return{canSkipEntireSubtree,contentAreaAffected,bgRefillNeeded,contentRegionCleared:(hasPrevBuffer||ancestorCleared)&&contentAreaAffected&&!hasBgColor,skipBgFill:hasPrevBuffer&&!ancestorCleared&&!contentAreaAffected&&!bgRefillNeeded,childrenNeedFreshRender:(hasPrevBuffer||ancestorCleared)&&(contentAreaAffected||bgRefillNeeded)}}import{createLogger as createLogger2}from"loggily";function contentPhase(root,prevBuffer,ctx){let layout=root.contentRect;if(!layout)throw Error("contentPhase called before layout phase");let instrumentEnabled=ctx?.instrumentEnabled??_instrumentEnabled,stats=ctx?.stats??_contentPhaseStats,nodeTrace=ctx?.nodeTrace??_nodeTrace,nodeTraceEnabled=ctx?.nodeTraceEnabled??_nodeTraceEnabled,hasPrevBuffer=prevBuffer&&prevBuffer.width===layout.width&&prevBuffer.height===layout.height;if(instrumentEnabled)_contentPhaseCallCount++,stats._prevBufferNull=prevBuffer==null?1:0,stats._prevBufferDimMismatch=prevBuffer&&!hasPrevBuffer?1:0,stats._hasPrevBuffer=hasPrevBuffer?1:0,stats._layoutW=layout.width,stats._layoutH=layout.height,stats._prevW=prevBuffer?.width??0,stats._prevH=prevBuffer?.height??0,stats._callCount=_contentPhaseCallCount;let t0=instrumentEnabled?performance.now():0,buffer=hasPrevBuffer?prevBuffer.clone():new TerminalBuffer(layout.width,layout.height),tClone=instrumentEnabled?performance.now()-t0:0,t1=instrumentEnabled?performance.now():0;renderNodeToBuffer(root,buffer,{scrollOffset:0,clipBounds:void 0,hasPrevBuffer:!!hasPrevBuffer,ancestorCleared:!1,bufferIsCloned:!!hasPrevBuffer,ancestorLayoutChanged:!1},ctx);let tRender=instrumentEnabled?performance.now()-t1:0;if(instrumentEnabled){let snap={clone:tClone,render:tRender,...structuredClone(stats)};globalThis.__silvery_content_detail=snap,(globalThis.__silvery_content_all??=[]).push(snap),contentLog.debug?.(`frame ${snap._callCount}: ${snap.nodesRendered}/${snap.nodesVisited} rendered, ${snap.nodesSkipped} skipped (${tClone.toFixed(1)}ms clone, ${tRender.toFixed(1)}ms render)`);for(let key of Object.keys(stats))stats[key]=0;stats.cascadeMinDepth=999,stats.cascadeNodes="",stats.scrollClearReason="",stats.normalRepaintReason=""}if(nodeTraceEnabled&&nodeTrace.length>0)(globalThis.__silvery_node_trace??=[]).push([...nodeTrace]),traceLog.debug?.(`${nodeTrace.length} nodes traced`),nodeTrace.length=0;return syncPrevLayout(root),buffer}function syncPrevLayout(root){let stack=[root];while(stack.length>0){let node=stack.pop();node.prevLayout=node.contentRect;let children=node.children;for(let i=children.length-1;i>=0;i--)stack.push(children[i])}}function _getNodeDepth(node){let depth=0,n=node.parent;while(n)depth++,n=n.parent;return depth}function renderNodeToBuffer(node,buffer,nodeState,ctx){let{scrollOffset,clipBounds,hasPrevBuffer,ancestorCleared,bufferIsCloned,ancestorLayoutChanged=!1}=nodeState,instrumentEnabled=ctx?.instrumentEnabled??_instrumentEnabled,stats=ctx?.stats??_contentPhaseStats,nodeTrace=ctx?.nodeTrace??_nodeTrace,nodeTraceEnabled=ctx?.nodeTraceEnabled??_nodeTraceEnabled;if(instrumentEnabled)stats.nodesVisited++;let layout=node.contentRect;if(!layout)return;if(!node.layoutNode){clearVirtualTextFlags(node);return}if(node.hidden){clearDirtyFlags(node);return}let props=node.props;if(props.display==="none"){clearDirtyFlags(node);return}let screenY=layout.y-scrollOffset;if(screenY>=buffer.height||screenY+layout.height<=0)return;let layoutChanged=node.layoutChangedThisFrame,childPositionChanged=!!(hasPrevBuffer&&!layoutChanged&&hasChildPositionChanged(node)),scrollOffsetChanged=!!(node.scrollState&&node.scrollState.offset!==node.scrollState.prevOffset),canSkipEntireSubtree=hasPrevBuffer&&!node.contentDirty&&!node.stylePropsDirty&&!layoutChanged&&!node.subtreeDirty&&!node.childrenDirty&&!childPositionChanged&&!ancestorLayoutChanged&&!scrollOffsetChanged,_nodeId=instrumentEnabled?props.id??"":"",_traceThis=instrumentEnabled&&nodeTraceEnabled&&_nodeId,_cellDbg=globalThis.__silvery_cell_debug,_coversCellNow=_cellDbg&&layout.x<=_cellDbg.x&&layout.x+layout.width>_cellDbg.x&&screenY<=_cellDbg.y&&screenY+layout.height>_cellDbg.y,_coversCellPrev=_cellDbg&&node.prevLayout&&node.prevLayout.x<=_cellDbg.x&&node.prevLayout.x+node.prevLayout.width>_cellDbg.x&&node.prevLayout.y-scrollOffset<=_cellDbg.y&&node.prevLayout.y-scrollOffset+node.prevLayout.height>_cellDbg.y;if(canSkipEntireSubtree){if(_cellDbg&&(_coversCellNow||_coversCellPrev)){let id=props.id??node.type,depth=_getNodeDepth(node),prev=node.prevLayout,msg=`SKIP ${id}@${depth} rect=${layout.x},${screenY} ${layout.width}x${layout.height} prev=${prev?`${prev.x},${prev.y-scrollOffset} ${prev.width}x${prev.height}`:"null"} coversNow=${_coversCellNow} coversPrev=${_coversCellPrev}`;_cellDbg.log.push(msg),cellLog.debug?.(msg)}if(instrumentEnabled){if(stats.nodesSkipped++,_traceThis)nodeTrace.push({id:_nodeId,type:node.type,depth:_getNodeDepth(node),rect:`${layout.x},${layout.y} ${layout.width}x${layout.height}`,prevLayout:node.prevLayout?`${node.prevLayout.x},${node.prevLayout.y} ${node.prevLayout.width}x${node.prevLayout.height}`:"null",hasPrev:hasPrevBuffer,ancestorCleared,flags:"",decision:"SKIPPED",layoutChanged})}clearDirtyFlags(node);return}if(instrumentEnabled){if(stats.nodesRendered++,!hasPrevBuffer)stats.noPrevBuffer++;if(node.contentDirty)stats.flagContentDirty++;if(node.stylePropsDirty)stats.flagStylePropsDirty++;if(layoutChanged)stats.flagLayoutChanged++;if(node.subtreeDirty)stats.flagSubtreeDirty++;if(node.childrenDirty)stats.flagChildrenDirty++;if(childPositionChanged)stats.flagChildPositionChanged++;if(ancestorLayoutChanged)stats.flagAncestorLayoutChanged++}let nodeTheme=props.theme;if(nodeTheme)pushContextTheme(nodeTheme);try{let isScrollContainer=props.overflow==="scroll"&&node.scrollState,{absoluteChildMutated,descendantOverflowChanged}=buildCascadeInputs(node,hasPrevBuffer),cascade=computeCascade({hasPrevBuffer,contentDirty:node.contentDirty,stylePropsDirty:node.stylePropsDirty,layoutChanged,subtreeDirty:node.subtreeDirty,childrenDirty:node.childrenDirty,childPositionChanged,ancestorLayoutChanged,ancestorCleared,bgDirty:node.bgDirty,isTextNode:node.type==="silvery-text",hasBgColor:!!getEffectiveBg(props),absoluteChildMutated,descendantOverflowChanged}),{contentRegionCleared,skipBgFill,childrenNeedFreshRender}=cascade;if(instrumentEnabled||_cellDbg&&(_coversCellNow||_coversCellPrev))traceRenderDecision(node,props,layout,screenY,scrollOffset,hasPrevBuffer,ancestorCleared,layoutChanged,childPositionChanged,cascade,_nodeId,_traceThis,_cellDbg,_coversCellNow,_coversCellPrev,instrumentEnabled,stats,nodeTrace);executeRegionClearing(node,buffer,layout,scrollOffset,clipBounds,bufferIsCloned,layoutChanged,contentRegionCleared,descendantOverflowChanged,instrumentEnabled,stats);let needsOwnRepaint=!hasPrevBuffer||ancestorCleared||ancestorLayoutChanged||cascade.contentAreaAffected||node.stylePropsDirty||cascade.bgRefillNeeded,boxInheritedBg=node.type==="silvery-box"&&!getEffectiveBg(props)?findInheritedBg(node).color:void 0;if(needsOwnRepaint)renderOwnContent(node,buffer,layout,props,nodeState,skipBgFill,instrumentEnabled,stats,ctx);if(isScrollContainer)renderScrollContainerChildren(node,buffer,props,nodeState,contentRegionCleared,childrenNeedFreshRender,ctx),renderScrollIndicators(node,buffer,layout,props,node.scrollState,ctx);else renderNormalChildren(node,buffer,props,nodeState,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()}}function buildCascadeInputs(node,hasPrevBuffer){if(!hasPrevBuffer||!node.subtreeDirty||node.children===void 0)return{absoluteChildMutated:!1,descendantOverflowChanged:!1};let absoluteChildMutated=node.children.some((child)=>{return child.props.position==="absolute"&&(child.childrenDirty||child.layoutChangedThisFrame||hasChildPositionChanged(child))}),descendantOverflowChanged=hasDescendantOverflowChanged(node);return{absoluteChildMutated,descendantOverflowChanged}}function traceRenderDecision(node,props,layout,screenY,scrollOffset,hasPrevBuffer,ancestorCleared,layoutChanged,childPositionChanged,cascade,_nodeId,_traceThis,_cellDbg,_coversCellNow,_coversCellPrev,instrumentEnabled,stats,nodeTrace){let{contentAreaAffected,contentRegionCleared,skipBgFill,childrenNeedFreshRender}=cascade;if(instrumentEnabled){if(_traceThis){let flagStr=[node.contentDirty&&"C",node.stylePropsDirty&&"P",node.bgDirty&&"B",node.subtreeDirty&&"S",node.childrenDirty&&"Ch",childPositionChanged&&"CP"].filter(Boolean).join(","),childHasPrev_=node.childrenDirty||childPositionChanged||childrenNeedFreshRender?!1:hasPrevBuffer,childAncestorCleared_=contentRegionCleared||ancestorCleared&&!getEffectiveBg(props);nodeTrace.push({id:_nodeId,type:node.type,depth:_getNodeDepth(node),rect:`${layout.x},${layout.y} ${layout.width}x${layout.height}`,prevLayout:node.prevLayout?`${node.prevLayout.x},${node.prevLayout.y} ${node.prevLayout.width}x${node.prevLayout.height}`:"null",hasPrev:hasPrevBuffer,ancestorCleared,flags:flagStr,decision:"RENDER",layoutChanged,contentAreaAffected,contentRegionCleared,childrenNeedFreshRender,childHasPrev:childHasPrev_,childAncestorCleared:childAncestorCleared_,skipBgFill,bgColor:props.backgroundColor})}if(childrenNeedFreshRender&&node.children.length>0){let depth=_getNodeDepth(node);if(depth<stats.cascadeMinDepth)stats.cascadeMinDepth=depth;let id=node.props.id??node.type,flags=[node.contentDirty&&"C",node.stylePropsDirty&&"P",node.childrenDirty&&"Ch",layoutChanged&&"L",childPositionChanged&&"CP"].filter(Boolean).join(""),entry=`${id}@${depth}[${flags}:${node.children.length}ch]`;stats.cascadeNodes+=(stats.cascadeNodes?" ":"")+entry}}if(_cellDbg&&(_coversCellNow||_coversCellPrev)){let id=props.id??node.type,depth=_getNodeDepth(node),prev=node.prevLayout,flags=[node.contentDirty&&"C",node.stylePropsDirty&&"P",layoutChanged&&"L",node.subtreeDirty&&"S",node.childrenDirty&&"Ch",childPositionChanged&&"CP",node.bgDirty&&"B"].filter(Boolean).join(","),msg=`RENDER ${id}@${depth} rect=${layout.x},${screenY} ${layout.width}x${layout.height} prev=${prev?`${prev.x},${prev.y-scrollOffset} ${prev.width}x${prev.height}`:"null"} flags=[${flags}] hasPrev=${hasPrevBuffer} ancClr=${ancestorCleared} caa=${contentAreaAffected} prc=${contentRegionCleared} prm=${childrenNeedFreshRender} coversNow=${_coversCellNow} coversPrev=${_coversCellPrev} bg=${props.backgroundColor??"none"}`;_cellDbg.log.push(msg),cellLog.debug?.(msg)}}function executeRegionClearing(node,buffer,layout,scrollOffset,clipBounds,bufferIsCloned,layoutChanged,contentRegionCleared,descendantOverflowChanged,instrumentEnabled,stats){if(contentRegionCleared){if(instrumentEnabled)stats.clearOps++;clearNodeRegion(node,buffer,layout,scrollOffset,clipBounds,layoutChanged)}else if(bufferIsCloned&&layoutChanged&&node.prevLayout)clearExcessArea(node,buffer,layout,scrollOffset,clipBounds,layoutChanged);if(descendantOverflowChanged)clearDescendantOverflowRegions(node,buffer,layout,scrollOffset,clipBounds)}function renderOwnContent(node,buffer,layout,props,nodeState,skipBgFill,instrumentEnabled,stats,ctx){let boxInheritedBg=node.type==="silvery-box"&&!getEffectiveBg(props)?findInheritedBg(node).color:void 0;if(node.type==="silvery-box"){if(instrumentEnabled)stats.boxNodes++;renderBox(node,buffer,layout,props,nodeState,skipBgFill,boxInheritedBg)}else if(node.type==="silvery-text"){if(instrumentEnabled)stats.textNodes++;let textInheritedBg=findInheritedBg(node).color,textInheritedFg=findInheritedFg(node);renderText(node,buffer,layout,props,nodeState,textInheritedBg,textInheritedFg,ctx)}return boxInheritedBg}function planScrollRender(inputs){let{scrollOffsetChanged,visibleRangeChanged,hasStickyChildren,childrenNeedFreshRender,childrenDirty,hasPrevBuffer,ancestorCleared,contentRegionCleared,scrollBg}=inputs,scrollOnly=hasPrevBuffer&&scrollOffsetChanged&&!childrenDirty&&!childrenNeedFreshRender&&!hasStickyChildren&&!visibleRangeChanged,needsViewportClear=hasPrevBuffer&&!scrollOnly&&(scrollOffsetChanged||childrenDirty||childrenNeedFreshRender||visibleRangeChanged),stickyForceRefresh=hasStickyChildren&&hasPrevBuffer&&!needsViewportClear,reasons=[];if(scrollOnly)reasons.push("SHIFT");if(needsViewportClear){if(scrollOffsetChanged)reasons.push("scrollOffset");if(childrenDirty)reasons.push("childrenDirty");if(childrenNeedFreshRender)reasons.push("childrenNeedFreshRender");if(visibleRangeChanged)reasons.push("visibleRangeChanged")}if(stickyForceRefresh)reasons.push("stickyForceRefresh");return{tier:scrollOnly?"shift":needsViewportClear?"clear":"subtree-only",clearBg:scrollOnly||needsViewportClear?scrollBg:null,childHasPrev:needsViewportClear?!1:hasPrevBuffer,childAncestorCleared:needsViewportClear?!0:ancestorCleared||contentRegionCleared,stickyForceRefresh,reasons}}function renderScrollContainerChildren(node,buffer,props,nodeState,contentRegionCleared=!1,childrenNeedFreshRender=!1,ctx){let{clipBounds,hasPrevBuffer,ancestorCleared,bufferIsCloned,ancestorLayoutChanged}=nodeState,instrumentEnabled=ctx?.instrumentEnabled??_instrumentEnabled,stats=ctx?.stats??_contentPhaseStats,layout=node.contentRect,ss=node.scrollState;if(!layout||!ss)return;let border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},padding=getPadding(props),childClipBounds=computeChildClipBounds(layout,props,clipBounds,0,!1,!0),scrollOffsetChanged=ss.offset!==ss.prevOffset,hasStickyChildren=!!(ss.stickyChildren&&ss.stickyChildren.length>0),visibleRangeChanged=ss.firstVisibleChild!==ss.prevFirstVisibleChild||ss.lastVisibleChild!==ss.prevLastVisibleChild,clearY=childClipBounds.top,clearHeight=childClipBounds.bottom-childClipBounds.top,contentX=layout.x+border.left+padding.left,contentWidth=layout.width-border.left-border.right-padding.left-padding.right,scrollBg=scrollOffsetChanged||node.childrenDirty||childrenNeedFreshRender||visibleRangeChanged?getEffectiveBg(props)?parseColor(getEffectiveBg(props)):findInheritedBg(node).color:null,plan=planScrollRender({scrollOffsetChanged,visibleRangeChanged,hasStickyChildren,childrenNeedFreshRender,childrenDirty:node.childrenDirty,hasPrevBuffer,ancestorCleared,contentRegionCleared,scrollBg}),{tier,stickyForceRefresh}=plan,defaultChildHasPrev=plan.childHasPrev,defaultChildAncestorCleared=plan.childAncestorCleared;if(instrumentEnabled){if(stats.scrollContainerCount++,tier!=="subtree-only"||stickyForceRefresh){stats.scrollViewportCleared++;let reasons=[...plan.reasons];if(scrollOffsetChanged)reasons.push(`scrollOffset(${ss.prevOffset}->${ss.offset})`);reasons.push(`vp=${ss.viewportHeight} content=${ss.contentHeight} vis=${ss.firstVisibleChild}-${ss.lastVisibleChild}`),stats.scrollClearReason=reasons.join("+")}}if(process.env.SILVERY_STRICT&&tier==="shift"&&hasStickyChildren)throw Error(`[SILVERY_STRICT] Scroll Tier 1 (buffer shift) activated with sticky children (node: ${props.id??node.type}, stickyCount: ${ss.stickyChildren?.length??0})`);let scrollDelta=ss.offset-(ss.prevOffset??ss.offset);if(tier==="shift"&&clearHeight>0){if(props.overflowIndicator===!0&&!border.top&&!border.bottom){let topIndicatorY=clearY,bottomIndicatorY=clearY+clearHeight-1;if(ss.prevOffset!=null&&ss.prevOffset>0)buffer.fill(contentX,topIndicatorY,contentWidth,1,{char:" ",bg:plan.clearBg});buffer.fill(contentX,bottomIndicatorY,contentWidth,1,{char:" ",bg:plan.clearBg})}buffer.scrollRegion(contentX,clearY,contentWidth,clearHeight,scrollDelta,{char:" ",bg:plan.clearBg})}if(tier==="clear"&&clearHeight>0)buffer.fill(contentX,clearY,contentWidth,clearHeight,{char:" ",bg:plan.clearBg});if(stickyForceRefresh&&clearHeight>0)buffer.fill(contentX,clearY,contentWidth,clearHeight,{char:" ",bg:null});let childAncestorLayoutChanged=node.layoutChangedThisFrame||!!ancestorLayoutChanged,prevVisTop=ss.prevOffset??ss.offset,prevVisBottom=prevVisTop+ss.viewportHeight;for(let i=0;i<node.children.length;i++){let child=node.children[i];if(!child)continue;if(child.props.position==="sticky")continue;if(i<ss.firstVisibleChild||i>ss.lastVisibleChild)continue;let thisChildHasPrev=defaultChildHasPrev,thisChildAncestorCleared=defaultChildAncestorCleared;if(tier==="shift"){let childRect=child.contentRect;if(childRect){let childTop=childRect.y-layout.y-border.top-padding.top,childBottom=childTop+childRect.height,wasFullyVisible=childTop>=prevVisTop&&childBottom<=prevVisBottom;thisChildHasPrev=wasFullyVisible,thisChildAncestorCleared=wasFullyVisible?ancestorCleared||contentRegionCleared:!0}}if(stickyForceRefresh&&thisChildHasPrev)thisChildHasPrev=!1,thisChildAncestorCleared=!1;renderNodeToBuffer(child,buffer,{scrollOffset:ss.offset,clipBounds:childClipBounds,hasPrevBuffer:thisChildHasPrev,ancestorCleared:thisChildAncestorCleared,bufferIsCloned,ancestorLayoutChanged:childAncestorLayoutChanged},ctx)}if(ss.stickyChildren)for(let sticky of ss.stickyChildren){let child=node.children[sticky.index];if(!child?.contentRect)continue;let stickyScrollOffset=sticky.naturalTop-sticky.renderOffset;renderNodeToBuffer(child,buffer,{scrollOffset:stickyScrollOffset,clipBounds:childClipBounds,hasPrevBuffer:!1,ancestorCleared:!1,bufferIsCloned,ancestorLayoutChanged:childAncestorLayoutChanged},ctx)}}function renderNormalChildren(node,buffer,props,nodeState,childPositionChanged=!1,contentRegionCleared=!1,childrenNeedFreshRender=!1,ctx){let{scrollOffset,clipBounds,hasPrevBuffer,ancestorCleared,bufferIsCloned,ancestorLayoutChanged}=nodeState,instrumentEnabled=ctx?.instrumentEnabled??_instrumentEnabled,stats=ctx?.stats??_contentPhaseStats,layout=node.contentRect;if(!layout)return;let clipX=(props.overflowX??props.overflow)==="hidden",clipY=(props.overflowY??props.overflow)==="hidden",effectiveClipBounds=clipX||clipY?computeChildClipBounds(layout,props,clipBounds,scrollOffset,clipX,clipY):clipBounds,hasStickyChildren=!!(node.stickyChildren&&node.stickyChildren.length>0),stickyForceRefresh=hasStickyChildren&&hasPrevBuffer;if(stickyForceRefresh){let border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},padding=getPadding(props),clearX=layout.x+border.left+padding.left,clearY=layout.y-scrollOffset+border.top+padding.top,clearW=layout.width-border.left-border.right-padding.left-padding.right,clearH=layout.height-border.top-border.bottom-padding.top-padding.bottom;if(clipBounds){let{top:clipTop,bottom:clipBottom}=clipBounds;if(clearY<clipTop)clearH-=clipTop-clearY,clearY=clipTop;if(clearY+clearH>clipBottom)clearH=clipBottom-clearY;if(clipBounds.left!==void 0&&clearX<clipBounds.left)clearW-=clipBounds.left-clearX,clearX=clipBounds.left;if(clipBounds.right!==void 0&&clearX+clearW>clipBounds.right)clearW=clipBounds.right-clearX}if(clearW>0&&clearH>0)buffer.fill(clearX,clearY,clearW,clearH,{char:" ",bg:null})}let childrenNeedRepaint=node.childrenDirty||childPositionChanged||childrenNeedFreshRender;if(instrumentEnabled&&childrenNeedRepaint&&hasPrevBuffer){stats.normalChildrenRepaint++;let reasons=[];if(node.childrenDirty)reasons.push("childrenDirty");if(childPositionChanged)reasons.push("childPositionChanged");if(childrenNeedFreshRender)reasons.push("childrenNeedFreshRender");stats.normalRepaintReason=reasons.join("+")}let childHasPrev=childrenNeedRepaint?!1:hasPrevBuffer,childAncestorCleared=contentRegionCleared||ancestorCleared&&!getEffectiveBg(props),childAncestorLayoutChanged=node.layoutChangedThisFrame||!!ancestorLayoutChanged;if(stickyForceRefresh)childHasPrev=!1,childAncestorCleared=!1;let hasAbsoluteChildren=!1;for(let child of node.children){let childProps=child.props;if(childProps.position==="absolute"){hasAbsoluteChildren=!0;continue}if(hasStickyChildren&&childProps.position==="sticky")continue;renderNodeToBuffer(child,buffer,{scrollOffset,clipBounds:effectiveClipBounds,hasPrevBuffer:childHasPrev,ancestorCleared:childAncestorCleared,bufferIsCloned,ancestorLayoutChanged:childAncestorLayoutChanged},ctx)}if(node.stickyChildren)for(let sticky of node.stickyChildren){let child=node.children[sticky.index];if(!child?.contentRect)continue;let stickyScrollOffset=sticky.naturalTop-sticky.renderOffset;renderNodeToBuffer(child,buffer,{scrollOffset:stickyScrollOffset,clipBounds:effectiveClipBounds,hasPrevBuffer:!1,ancestorCleared:!1,bufferIsCloned,ancestorLayoutChanged:childAncestorLayoutChanged},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},ctx)}}function clearNodeDirtyFlags(node){node.contentDirty=!1,node.stylePropsDirty=!1,node.bgDirty=!1,node.subtreeDirty=!1,node.childrenDirty=!1,node.layoutChangedThisFrame=!1}function clearDirtyFlags(node){clearNodeDirtyFlags(node);for(let child of node.children)if(child.layoutNode)clearDirtyFlags(child);else clearVirtualTextFlags(child)}function clearVirtualTextFlags(node){clearNodeDirtyFlags(node);for(let child of node.children)clearVirtualTextFlags(child)}function hasChildPositionChanged(node){for(let child of node.children)if(child.contentRect&&child.prevLayout){if(child.contentRect.x!==child.prevLayout.x||child.contentRect.y!==child.prevLayout.y)return!0}return!1}function hasDescendantOverflowChanged(node){let rect=node.contentRect;return _checkDescendantOverflow(node.children,rect.x,rect.y,rect.x+rect.width,rect.y+rect.height)}function _checkDescendantOverflow(children,nodeLeft,nodeTop,nodeRight,nodeBottom){for(let child of children){if(child.prevLayout&&child.layoutChangedThisFrame){let prev=child.prevLayout;if(prev.x+prev.width>nodeRight||prev.y+prev.height>nodeBottom||prev.x<nodeLeft||prev.y<nodeTop)return!0}if(child.subtreeDirty&&child.children!==void 0){if(_checkDescendantOverflow(child.children,nodeLeft,nodeTop,nodeRight,nodeBottom))return!0}}return!1}function computeChildClipBounds(layout,props,parentClip,scrollOffset=0,horizontal=!0,vertical=!0){let border=props.borderStyle?getBorderSize(props):{top:0,bottom:0,left:0,right:0},padding=getPadding(props),adjustedY=layout.y-scrollOffset,nodeClip=vertical?{top:adjustedY+border.top+padding.top,bottom:adjustedY+layout.height-border.bottom-padding.bottom}:{top:-1/0,bottom:1/0};if(horizontal)nodeClip.left=layout.x+border.left+padding.left,nodeClip.right=layout.x+layout.width-border.right-padding.right;if(!parentClip)return nodeClip;let result={top:vertical?Math.max(parentClip.top,nodeClip.top):parentClip.top,bottom:vertical?Math.min(parentClip.bottom,nodeClip.bottom):parentClip.bottom};if(horizontal&&nodeClip.left!==void 0&&nodeClip.right!==void 0)result.left=Math.max(parentClip.left??0,nodeClip.left),result.right=Math.min(parentClip.right??1/0,nodeClip.right);else if(parentClip.left!==void 0&&parentClip.right!==void 0)result.left=parentClip.left,result.right=parentClip.right;return result}function findInheritedBg(node){let current=node.parent;while(current){let props=current.props;if(props.backgroundColor)return{color:parseColor(props.backgroundColor),ancestorRect:current.contentRect};if(props.theme){let theme=props.theme;return{color:parseColor(theme.bg),ancestorRect:current.contentRect}}current=current.parent}return{color:null,ancestorRect:null}}function findInheritedFg(node){let current=node.parent;while(current){let props=current.props;if(props.color)return parseColor(props.color);if(props.theme){let theme=props.theme;return parseColor(theme.fg)}current=current.parent}return null}function clearDescendantOverflowRegions(node,buffer,layout,scrollOffset,clipBounds){let clearBg=findInheritedBg(node).color,nodeRight=layout.x+layout.width,nodeBottom=layout.y-scrollOffset+layout.height,nodeLeft=layout.x,nodeTop=layout.y-scrollOffset;_clearDescendantOverflow(node.children,buffer,nodeLeft,nodeTop,nodeRight,nodeBottom,scrollOffset,clipBounds,clearBg)}function _clearDescendantOverflow(children,buffer,nodeLeft,nodeTop,nodeRight,nodeBottom,scrollOffset,clipBounds,clearBg){for(let child of children){if(child.prevLayout&&child.layoutChangedThisFrame){let prev=child.prevLayout,prevRight=prev.x+prev.width,prevBottom=prev.y-scrollOffset+prev.height,prevTop=prev.y-scrollOffset;if(prevRight>nodeRight){let overflowX=nodeRight,overflowWidth=Math.min(prevRight,buffer.width)-overflowX,overflowTop=Math.max(prevTop,clipBounds?.top??0),overflowBottom=Math.min(prevBottom,clipBounds?.bottom??buffer.height);if(overflowWidth>0&&overflowBottom>overflowTop)buffer.fill(overflowX,overflowTop,overflowWidth,overflowBottom-overflowTop,{char:" ",bg:clearBg})}if(prevBottom>nodeBottom){let overflowTop=Math.max(nodeBottom,clipBounds?.top??0),overflowBottom=Math.min(prevBottom,clipBounds?.bottom??buffer.height),overflowX=Math.max(prev.x,clipBounds?.left??0),overflowWidth=Math.min(prevRight,clipBounds?.right??buffer.width)-overflowX;if(overflowWidth>0&&overflowBottom>overflowTop)buffer.fill(overflowX,overflowTop,overflowWidth,overflowBottom-overflowTop,{char:" ",bg:clearBg})}if(prev.x<nodeLeft){let overflowX=Math.max(prev.x,0),overflowWidth=Math.min(nodeLeft,buffer.width)-overflowX,overflowTop=Math.max(prevTop,clipBounds?.top??0),overflowBottom=Math.min(prevBottom,clipBounds?.bottom??buffer.height);if(overflowWidth>0&&overflowBottom>overflowTop)buffer.fill(overflowX,overflowTop,overflowWidth,overflowBottom-overflowTop,{char:" ",bg:clearBg})}if(prevTop<nodeTop){let overflowTop=Math.max(prevTop,clipBounds?.top??0),overflowBottom=Math.min(nodeTop,clipBounds?.bottom??buffer.height),overflowX=Math.max(prev.x,clipBounds?.left??0),overflowWidth=Math.min(prevRight,clipBounds?.right??buffer.width)-overflowX;if(overflowWidth>0&&overflowBottom>overflowTop)buffer.fill(overflowX,overflowTop,overflowWidth,overflowBottom-overflowTop,{char:" ",bg:clearBg})}}if(child.subtreeDirty&&child.children!==void 0)_clearDescendantOverflow(child.children,buffer,nodeLeft,nodeTop,nodeRight,nodeBottom,scrollOffset,clipBounds,clearBg)}}function clearNodeRegion(node,buffer,layout,scrollOffset,clipBounds,layoutChanged){let inherited=findInheritedBg(node),clearBg=inherited.color,screenY=layout.y-scrollOffset,parentRect=node.parent?.contentRect,parentBottom=parentRect?parentRect.y-scrollOffset+parentRect.height:void 0,clearY=clipBounds?Math.max(screenY,clipBounds.top):screenY,clearBottom=clipBounds?Math.min(screenY+layout.height,clipBounds.bottom):screenY+layout.height;if(parentBottom!==void 0)clearBottom=Math.min(clearBottom,parentBottom);let{x:clearX,width:clearWidth}=layout;if(clipBounds?.left!==void 0&&clipBounds.right!==void 0){if(clearX<clipBounds.left)clearWidth-=clipBounds.left-clearX,clearX=clipBounds.left;if(clearX+clearWidth>clipBounds.right)clearWidth=Math.max(0,clipBounds.right-clearX)}if(inherited.ancestorRect){let ancestorRight=inherited.ancestorRect.x+inherited.ancestorRect.width,ancestorLeft=inherited.ancestorRect.x;if(clearX<ancestorLeft)clearWidth-=ancestorLeft-clearX,clearX=ancestorLeft;if(clearX+clearWidth>ancestorRight)clearWidth=Math.max(0,ancestorRight-clearX)}let clearHeight=clearBottom-clearY;if(clearHeight>0&&clearWidth>0){let _cellDbg2=globalThis.__silvery_cell_debug;if(_cellDbg2){if(clearX<=_cellDbg2.x&&clearX+clearWidth>_cellDbg2.x&&clearY<=_cellDbg2.y&&clearY+clearHeight>_cellDbg2.y){let msg=`CLEAR_REGION ${node.props.id??node.type} fill=${clearX},${clearY} ${clearWidth}x${clearHeight} bg=${String(clearBg)} COVERS TARGET`;_cellDbg2.log.push(msg),cellLog.debug?.(msg)}}buffer.fill(clearX,clearY,clearWidth,clearHeight,{char:" ",bg:clearBg})}clearExcessArea(node,buffer,layout,scrollOffset,clipBounds,layoutChanged,inherited)}function clearExcessArea(node,buffer,layout,scrollOffset,clipBounds,layoutChanged,inherited){if(!layoutChanged||!node.prevLayout)return;let prev=node.prevLayout,_cellDbg3=globalThis.__silvery_cell_debug,_prevCoversCell3=_cellDbg3&&prev.x<=_cellDbg3.x&&prev.x+prev.width>_cellDbg3.x&&prev.y-scrollOffset<=_cellDbg3.y&&prev.y-scrollOffset+prev.height>_cellDbg3.y;if(prev.width<=layout.width&&prev.height<=layout.height){if(_cellDbg3&&_prevCoversCell3){let msg=`EXCESS_SKIP_NO_SHRINK ${node.props.id??node.type} prev=${prev.x},${prev.y-scrollOffset} ${prev.width}x${prev.height} now=${layout.x},${layout.y-scrollOffset} ${layout.width}x${layout.height}`;_cellDbg3.log.push(msg),cellLog.debug?.(msg)}return}if(prev.x!==layout.x||prev.y!==layout.y){if(_cellDbg3&&_prevCoversCell3){let msg=`EXCESS_SKIP_MOVED ${node.props.id??node.type} prev=${prev.x},${prev.y-scrollOffset} ${prev.width}x${prev.height} now=${layout.x},${layout.y-scrollOffset} ${layout.width}x${layout.height} (dx=${layout.x-prev.x} dy=${layout.y-prev.y})`;_cellDbg3.log.push(msg),cellLog.debug?.(msg)}return}if(!inherited)inherited=findInheritedBg(node);let clearBg=inherited.color,screenY=layout.y-scrollOffset,prevScreenY=prev.y-scrollOffset,clipRect=inherited.ancestorRect??node.parent?.contentRect;if(!clipRect)return;let clipRectBottom=clipRect.y-scrollOffset+clipRect.height,clipRectRight=clipRect.x+clipRect.width,parent=node.parent;if(parent?.contentRect){let parentProps=parent.props,border=getBorderSize(parentProps),padding=getPadding(parentProps),parentRight=parent.contentRect.x+parent.contentRect.width-border.right-padding.right,parentBottom=parent.contentRect.y-scrollOffset+parent.contentRect.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,_contentPhaseStats,_contentPhaseCallCount=0,_nodeTrace,_nodeTraceEnabled;var init_content_phase=__esm(()=>{init_buffer();init_render_box();init_render_helpers();init_render_text();init_state();contentLog=createLogger2("silvery:content"),traceLog=createLogger2("silvery:content:trace"),cellLog=createLogger2("silvery:content:cell");_instrumentEnabled=typeof process<"u"&&!!(process.env?.SILVERY_STRICT||process.env?.SILVERY_INSTRUMENT),_contentPhaseStats={nodesVisited:0,nodesRendered:0,nodesSkipped:0,textNodes:0,boxNodes:0,clearOps:0,noPrevBuffer:0,flagContentDirty:0,flagStylePropsDirty:0,flagLayoutChanged:0,flagSubtreeDirty:0,flagChildrenDirty:0,flagChildPositionChanged:0,flagAncestorLayoutChanged:0,scrollContainerCount:0,scrollViewportCleared:0,scrollClearReason:"",normalChildrenRepaint:0,normalRepaintReason:"",cascadeMinDepth:999,cascadeNodes:"",_prevBufferNull:0,_prevBufferDimMismatch:0,_hasPrevBuffer:0,_layoutW:0,_layoutH:0,_prevW:0,_prevH:0,_callCount:0},_nodeTrace=[],_nodeTraceEnabled=typeof process<"u"&&!!process.env?.SILVERY_STRICT});var IncrementalRenderMismatchError;var init_errors=__esm(()=>{IncrementalRenderMismatchError=class IncrementalRenderMismatchError extends Error{contentPhaseStats;mismatchContext;constructor(message,data){super(message);this.name="IncrementalRenderMismatchError",this.contentPhaseStats=data?.contentPhaseStats,this.mismatchContext=data?.mismatchContext}}});function createEmptyCellChange(){return{x:0,y:0,cell:{char:" ",fg:null,bg:null,underlineColor:null,attrs:{},wide:!1,continuation:!1,hyperlink:void 0}}}function ensureDiffPoolCapacity(capacity){if(capacity<=diffPoolCapacity)return;for(let i=diffPoolCapacity;i<capacity;i++)diffPool.push(createEmptyCellChange());diffPoolCapacity=capacity}function writeCellChange(change,x,y,buffer){change.x=x,change.y=y,buffer.readCellInto(x,y,change.cell)}function writeEmptyCellChange(change,x,y){change.x=x,change.y=y;let cell=change.cell;cell.char=" ",cell.fg=null,cell.bg=null,cell.underlineColor=null;let attrs=cell.attrs;attrs.bold=void 0,attrs.dim=void 0,attrs.italic=void 0,attrs.underline=void 0,attrs.underlineStyle=void 0,attrs.blink=void 0,attrs.inverse=void 0,attrs.hidden=void 0,attrs.strikethrough=void 0,cell.wide=!1,cell.continuation=!1,cell.hyperlink=void 0}function diffBuffers(prev,next){let cells=Math.max(prev.width,next.width)*Math.max(prev.height,next.height),maxChanges=cells+(cells>>1);ensureDiffPoolCapacity(maxChanges);let changeCount=0,height=Math.min(prev.height,next.height),width=Math.min(prev.width,next.width),startRow=next.minDirtyRow===-1?0:next.minDirtyRow,endRow=next.maxDirtyRow===-1?-1:Math.min(next.maxDirtyRow,height-1);for(let y=startRow;y<=endRow;y++){if(!next.isRowDirty(y))continue;if(next.rowMetadataEquals(y,prev)&&next.rowCharsEquals(y,prev)&&next.rowExtrasEquals(y,prev))continue;for(let x=0;x<width;x++)if(!next.cellEquals(x,y,prev)){if(writeCellChange(diffPool[changeCount],x,y,next),changeCount++,x+1<width&&prev.isCellWide(x,y)&&!next.isCellWide(x,y))writeCellChange(diffPool[changeCount],x+1,y,next),changeCount++}}let widthGrew=next.width>prev.width;if(widthGrew)for(let y=0;y<next.height;y++)for(let x=prev.width;x<next.width;x++)writeCellChange(diffPool[changeCount],x,y,next),changeCount++;if(next.height>prev.height){let xEnd=widthGrew?prev.width:next.width;for(let y=prev.height;y<next.height;y++)for(let x=0;x<xEnd;x++)writeCellChange(diffPool[changeCount],x,y,next),changeCount++}if(prev.width>next.width)for(let y=0;y<height;y++)for(let x=next.width;x<prev.width;x++)writeEmptyCellChange(diffPool[changeCount],x,y),changeCount++;if(prev.height>next.height)for(let y=next.height;y<prev.height;y++)for(let x=0;x<prev.width;x++)writeEmptyCellChange(diffPool[changeCount],x,y),changeCount++;if(changeCount>maxChanges)throw Error(`diffBuffers: changeCount ${changeCount} exceeds pool capacity ${maxChanges} (prev ${prev.width}x${prev.height}, next ${next.width}x${next.height})`);return diffResult.pool=diffPool,diffResult.count=changeCount,diffResult}var diffPool,diffPoolCapacity=0,diffResult;var init_diff_buffers=__esm(()=>{diffPool=[];diffResult={pool:diffPool,count:0}});function setOutputCaps(_caps){}function outputGraphemeWidth(g,ctx){return ctx.measurer?ctx.measurer.graphemeWidth(g):graphemeWidth(g)}function outputTextSizingEnabled(ctx){return ctx.measurer?ctx.measurer.textSizingEnabled:isTextSizingEnabled()}function createOutputPhase(caps,measurer){let ctx={caps:{underlineStyles:caps.underlineStyles??!0,underlineColor:caps.underlineColor??!0,colorLevel:caps.colorLevel??"truecolor"},measurer:measurer??null,sgrCache:new Map,transitionCache:new Map,mode:"fullscreen",termRows:void 0},inlineState=createInlineCursorState(),accState={accumulatedAnsi:"",accumulateWidth:0,accumulateHeight:0,accumulateFrameCount:0},tvState=createTerminalVerifyState(),pendingPromotion=null,fn=function(prev,next,mode="fullscreen",scrollbackOffset=0,termRows,cursorPos){if(ctx.mode=mode,ctx.termRows=termRows,pendingPromotion&&mode==="inline"){let promo=pendingPromotion;return pendingPromotion=null,handleScrollbackPromotion(inlineState,promo.frozenContent,promo.frozenLineCount,next,cursorPos,ctx)}return outputPhase(prev,next,mode,scrollbackOffset,termRows,cursorPos,inlineState,ctx,accState,tvState)};return fn.resetInlineState=()=>{Object.assign(inlineState,createInlineCursorState()),inlineState.forceFirstRender=!0,pendingPromotion=null},fn.getInlineCursorRow=()=>inlineState.prevCursorRow,fn.promoteScrollback=(frozenContent,frozenLineCount)=>{if(pendingPromotion)pendingPromotion.frozenContent+=frozenContent,pendingPromotion.frozenLineCount+=frozenLineCount;else pendingPromotion={frozenContent,frozenLineCount}},fn}function handleScrollbackPromotion(state,frozenContent,frozenLineCount,next,cursorPos,ctx){let{termRows}=ctx,output="";if(state.prevCursorRow>0)output+=`\x1B[${state.prevCursorRow}A`;output+="\r",output+=frozenContent;let nextContentLines=findLastContentLine(next)+1,maxOutputLines=termRows!=null?Math.min(nextContentLines,termRows):nextContentLines;output+=bufferToAnsi(next,ctx,maxOutputLines);let totalOnScreen=frozenLineCount+maxOutputLines,oldTotalLines=state.prevOutputLines,nextLastLine=totalOnScreen-1,terminalScroll=termRows!=null?Math.max(0,totalOnScreen-termRows):0,lastOccupied=Math.max(oldTotalLines-1-terminalScroll,0);if(lastOccupied>nextLastLine){for(let y=nextLastLine+1;y<=lastOccupied;y++)output+=`
30
+ \r\x1B[K`;let up=lastOccupied-nextLastLine;if(up>0)output+=`\x1B[${up}A`}output+=inlineCursorSuffix(cursorPos??null,next,ctx);let startLine=0;if(termRows!=null&&nextContentLines>termRows)startLine=nextContentLines-termRows;if(state.prevBuffer=next,cursorPos?.visible){let visibleRow=cursorPos.y-startLine;state.prevCursorRow=visibleRow>=0&&visibleRow<maxOutputLines?visibleRow:maxOutputLines-1}else state.prevCursorRow=maxOutputLines-1;return state.prevOutputLines=maxOutputLines,output}function isStrictOutput(){return!!process.env.SILVERY_STRICT}function isStrictAccumulate(){return!!process.env.SILVERY_STRICT_ACCUMULATE}function strictTerminalBackends(){let val=(process.env.SILVERY_STRICT_TERMINAL??"").toLowerCase().trim();if(!val)return[];if(val==="all")return["vt100","xterm","ghostty"];let backends=val.split(",").map((s)=>s.trim()).filter(Boolean),valid=new Set(["vt100","xterm","ghostty"]);for(let b of backends)if(!valid.has(b))console.warn(`SILVERY_STRICT_TERMINAL: unknown backend '${b}', ignoring`);return backends.filter((b)=>valid.has(b))}function createTerminalVerifyState(){let allBackends=strictTerminalBackends();return{terminal:null,ghosttyTerminal:null,width:0,height:0,frameCount:0,backends:allBackends.filter((b)=>b!=="vt100"),hasVt100:allBackends.includes("vt100")}}function createInlineCursorState(){return{prevCursorRow:-1,prevOutputLines:0,prevBuffer:null,forceFirstRender:!1}}function updateInlineCursorRow(state,cursorPos,maxOutputLines,startLine){if(cursorPos?.visible){let visibleRow=cursorPos.y-startLine;state.prevCursorRow=visibleRow>=0&&visibleRow<maxOutputLines?visibleRow:maxOutputLines-1}else state.prevCursorRow=maxOutputLines-1;state.prevOutputLines=maxOutputLines}function wrapTextSizing(char,wide,ctx){if(!wide||!outputTextSizingEnabled(ctx))return char;return textSized(char,2)}function styleToKey(style){let{fg,bg,attrs}=style,key="";if(fg===null)key="n";else if(typeof fg==="number")key=`${fg}`;else key=`r${fg.r},${fg.g},${fg.b}`;if(key+="|",bg===null)key+="n";else if(typeof bg==="number")key+=`${bg}`;else key+=`r${bg.r},${bg.g},${bg.b}`;let attrBits=0;if(attrs.bold)attrBits|=1;if(attrs.dim)attrBits|=2;if(attrs.italic)attrBits|=4;if(attrs.underline)attrBits|=8;if(attrs.inverse)attrBits|=16;if(attrs.strikethrough)attrBits|=32;if(attrs.blink)attrBits|=64;if(attrs.hidden)attrBits|=128;if(key+=`|${attrBits}`,attrs.underlineStyle)key+=`|u${attrs.underlineStyle}`;let ul=style.underlineColor;if(ul!==null&&ul!==void 0)if(typeof ul==="number")key+=`|l${ul}`;else key+=`|lr${ul.r},${ul.g},${ul.b}`;if(style.hyperlink)key+=`|h${style.hyperlink}`;return key}function cachedStyleToAnsi(style,ctx){let key=styleToKey(style),sgr=ctx.sgrCache.get(key);if(sgr!==void 0)return sgr;if(sgr=styleToAnsi2(style,ctx),ctx.sgrCache.set(key,sgr),ctx.sgrCache.size>1000)ctx.sgrCache.clear();return sgr}function styleTransition(oldStyle,newStyle,ctx){if(!oldStyle)return cachedStyleToAnsi(newStyle,ctx);if(styleEquals(oldStyle,newStyle))return"";let oldKey=styleToKey(oldStyle),newKey=styleToKey(newStyle),cacheKey=`${oldKey}\x00${newKey}`,cached=ctx.transitionCache.get(cacheKey);if(cached!==void 0)return cached;let codes=[],oa=oldStyle.attrs,na=newStyle.attrs,boldChanged=Boolean(oa.bold)!==Boolean(na.bold),dimChanged=Boolean(oa.dim)!==Boolean(na.dim);if(boldChanged||dimChanged){let boldOff=boldChanged&&!na.bold,dimOff=dimChanged&&!na.dim;if(boldOff||dimOff){if(codes.push("22"),na.bold)codes.push("1");if(na.dim)codes.push("2")}else{if(boldChanged&&na.bold)codes.push("1");if(dimChanged&&na.dim)codes.push("2")}}if(Boolean(oa.italic)!==Boolean(na.italic))codes.push(na.italic?"3":"23");let oldUl=Boolean(oa.underline),newUl=Boolean(na.underline),oldUlStyle=oa.underlineStyle??!1,newUlStyle=na.underlineStyle??!1;if(oldUl!==newUl||oldUlStyle!==newUlStyle)if(!ctx.caps.underlineStyles)codes.push(newUl||na.underlineStyle?"4":"24");else{let sgrSub=underlineStyleToSgr(na.underlineStyle);if(sgrSub!==null&&sgrSub!==0)codes.push(`4:${sgrSub}`);else if(newUl)codes.push("4");else codes.push("24")}if(Boolean(oa.inverse)!==Boolean(na.inverse))codes.push(na.inverse?"7":"27");if(Boolean(oa.hidden)!==Boolean(na.hidden))codes.push(na.hidden?"8":"28");if(Boolean(oa.strikethrough)!==Boolean(na.strikethrough))codes.push(na.strikethrough?"9":"29");if(Boolean(oa.blink)!==Boolean(na.blink))codes.push(na.blink?"5":"25");if(!colorEquals(oldStyle.fg,newStyle.fg))if(newStyle.fg===null)codes.push("39");else codes.push(fgColorCode(newStyle.fg));if(!colorEquals(oldStyle.bg,newStyle.bg))if(newStyle.bg===null)codes.push("49");else codes.push(bgColorCode(newStyle.bg));if(ctx.caps.underlineColor&&!colorEquals(oldStyle.underlineColor,newStyle.underlineColor))if(newStyle.underlineColor===null||newStyle.underlineColor===void 0)codes.push("59");else if(typeof newStyle.underlineColor==="number")codes.push(`58;5;${newStyle.underlineColor}`);else codes.push(`58;2;${newStyle.underlineColor.r};${newStyle.underlineColor.g};${newStyle.underlineColor.b}`);let result;if(codes.length===0)result=cachedStyleToAnsi(newStyle,ctx);else result=`\x1B[${codes.join(";")}m`;if(ctx.transitionCache.set(cacheKey,result),ctx.transitionCache.size>1000)ctx.transitionCache.clear();return result}function underlineStyleToSgr(style){switch(style){case!1:return 0;case"single":return 1;case"double":return 2;case"curly":return 3;case"dotted":return 4;case"dashed":return 5;default:return null}}function outputPhase(prev,next,mode="fullscreen",scrollbackOffset=0,termRows,cursorPos,_inlineState,_ctx,_accState,_tvState){let inlineState=_inlineState??createInlineCursorState(),ctx=_ctx??defaultContext,accState=_accState??defaultAccState;ctx.mode=mode,ctx.termRows=termRows;let tvState=_tvState??defaultTerminalVerifyState;if(mode==="inline"&&inlineState.forceFirstRender)inlineState.forceFirstRender=!1,prev=null;if(!prev){if(mode==="inline"&&inlineState.prevBuffer&&inlineState.prevCursorRow>=0){let stored=inlineState.prevBuffer;if(stored.width===next.width&&stored.height===next.height)return inlineState.prevBuffer=next,inlineIncrementalRender(inlineState,stored,next,scrollbackOffset,cursorPos,ctx,tvState)}let firstOutput=bufferToAnsi(next,ctx,termRows);if(mode==="inline"){let firstContentLines=findLastContentLine(next)+1,firstMaxOutput=termRows!=null?Math.min(firstContentLines,termRows):firstContentLines,firstStartLine=0;if(termRows!=null&&firstContentLines>termRows)firstStartLine=firstContentLines-termRows;let prefix="";if(inlineState.prevCursorRow>=0){let clearDistance=termRows??Math.max(inlineState.prevCursorRow,inlineState.prevOutputLines-1);if(clearDistance>0)prefix+=`\x1B[${clearDistance}A`;prefix+="\r\x1B[J"}return inlineState.prevBuffer=next,updateInlineCursorRow(inlineState,cursorPos,firstMaxOutput,firstStartLine),prefix+firstOutput+inlineCursorSuffix(cursorPos??null,next,ctx)}if(isStrictAccumulate())accState.accumulatedAnsi=firstOutput,accState.accumulateWidth=next.width,accState.accumulateHeight=next.height,accState.accumulateFrameCount=0;if(tvState.backends.length>0)initTerminalVerifyState(tvState,next.width,next.height,firstOutput);if(CAPTURE_RAW)try{let fs=__require("fs");_captureRawFrameCount=0,fs.writeFileSync("/tmp/silvery-raw.ansi",firstOutput),fs.writeFileSync("/tmp/silvery-raw-frames.jsonl",JSON.stringify({frame:0,type:"full",bytes:firstOutput.length,width:next.width,height:next.height})+`
31
+ `)}catch{}return firstOutput}if(mode==="inline")return inlineState.prevBuffer=next,inlineIncrementalRender(inlineState,prev,next,scrollbackOffset,cursorPos,ctx,tvState);if(FULL_RENDER)return bufferToAnsi(next,ctx,termRows);if(prev.width!==next.width||prev.height!==next.height)return bufferToAnsi(next,ctx,termRows);let{pool,count:rawCount}=diffBuffers(prev,next),count=rawCount;if(termRows!=null){let writeIdx=0;for(let i=0;i<rawCount;i++)if(pool[i].y<termRows)pool[writeIdx++]=pool[i];count=writeIdx}if(DEBUG_OUTPUT){console.error(`[SILVERY_DEBUG_OUTPUT] diffBuffers: ${count} changes${rawCount!==count?` (${rawCount-count} clamped beyond termRows)`:""}`);let debugLimit=Math.min(count,10);for(let i=0;i<debugLimit;i++){let change=pool[i];console.error(` (${change.x},${change.y}): "${change.cell.char}"`)}if(count>10)console.error(` ... and ${count-10} more`)}if(count===0)return"";let incrOutput=changesToAnsi(pool,count,ctx,next).output;if(DEBUG_OUTPUT||isStrictAccumulate()){let bytes=Buffer.byteLength(incrOutput);try{__require("fs").appendFileSync("/tmp/silvery-sizes.log",`changesToAnsi: ${count} changes, ${bytes} bytes
32
+ `)}catch{}}if(DEBUG_CAPTURE){_debugFrameCount++;try{let fs=__require("fs"),freshOutput=bufferToAnsi(next,ctx),freshPrev=prev?bufferToAnsi(prev,ctx):"",w=Math.max(prev?.width??next.width,next.width),h=Math.max(prev?.height??next.height,next.height),screenIncr=replayAnsiWithStyles(w,h,freshPrev+incrOutput,ctx),screenFresh=replayAnsiWithStyles(w,h,freshOutput,ctx),mismatchInfo="";for(let y=0;y<h&&!mismatchInfo;y++)for(let x=0;x<w&&!mismatchInfo;x++){let ic=screenIncr[y]?.[x],fc=screenFresh[y]?.[x];if(ic&&fc&&(ic.char!==fc.char||!sgrColorEquals(ic.fg,fc.fg)||!sgrColorEquals(ic.bg,fc.bg))){mismatchInfo=`MISMATCH at (${x},${y}): incr='${ic.char}' fresh='${fc.char}' incrFg=${formatColor(ic.fg)} freshFg=${formatColor(fc.fg)} incrBg=${formatColor(ic.bg)} freshBg=${formatColor(fc.bg)}`;let incrRow=screenIncr[y].map((c)=>c.char).join(""),freshRow=screenFresh[y].map((c)=>c.char).join("");mismatchInfo+=`
33
+ incr row ${y}: ${incrRow.slice(Math.max(0,x-20),x+40)}
34
+ fresh row ${y}: ${freshRow.slice(Math.max(0,x-20),x+40)}`}}let status=mismatchInfo||"MATCH";if(fs.appendFileSync("/tmp/silvery-capture.log",`Frame ${_debugFrameCount}: ${count} changes, ${status}
35
+ `),mismatchInfo)fs.writeFileSync(`/tmp/silvery-incr-${_debugFrameCount}.ansi`,freshPrev+incrOutput),fs.writeFileSync(`/tmp/silvery-fresh-${_debugFrameCount}.ansi`,freshOutput),fs.appendFileSync("/tmp/silvery-capture.log",` Saved ANSI files: /tmp/silvery-incr-${_debugFrameCount}.ansi and /tmp/silvery-fresh-${_debugFrameCount}.ansi
36
+ `)}catch(e){try{__require("fs").appendFileSync("/tmp/silvery-capture.log",`Frame ${_debugFrameCount}: ERROR ${e}
37
+ `)}catch{}}}if(isStrictOutput()||tvState.hasVt100)verifyOutputEquivalence(prev,next,incrOutput,ctx);if(isStrictAccumulate())accState.accumulatedAnsi+=incrOutput,accState.accumulateFrameCount++,verifyAccumulatedOutput(next,ctx,accState);if(tvState.backends.length>0&&(tvState.terminal||tvState.ghosttyTerminal))tvState.frameCount++,verifyTerminalEquivalence(tvState,incrOutput,next,ctx);if(CAPTURE_RAW)try{let fs=__require("fs");_captureRawFrameCount++,fs.appendFileSync("/tmp/silvery-raw.ansi",incrOutput);let freshOutput=bufferToAnsi(next,ctx);fs.writeFileSync(`/tmp/silvery-raw-fresh-${_captureRawFrameCount}.ansi`,freshOutput),fs.appendFileSync("/tmp/silvery-raw-frames.jsonl",JSON.stringify({frame:_captureRawFrameCount,type:"incremental",changes:count,bytes:incrOutput.length,width:next.width,height:next.height})+`
38
+ `)}catch{}return incrOutput}function lineHasContent(buffer,y){for(let x=0;x<buffer.width;x++){let ch=buffer.getCellChar(x,y);if(ch!==" "&&ch!=="")return!0;if(buffer.getCellBg(x,y)!==null)return!0;if(buffer.getCellAttrs(x,y)&VISIBLE_SPACE_ATTR_MASK)return!0}return!1}function findLastContentLine(buffer){for(let y=buffer.height-1;y>=0;y--)if(lineHasContent(buffer,y))return y;return 0}function inlineCursorSuffix(cursorPos,buffer,ctx){let{termRows}=ctx;if(!cursorPos?.visible)return"\x1B[?25l";let lastContentLine=findLastContentLine(buffer),maxLine=lastContentLine,startLine=0,maxOutputLines=termRows!=null?Math.min(lastContentLine+1,termRows):lastContentLine+1;if(termRows!=null&&maxLine>=termRows)startLine=maxLine-termRows+1;let visibleRow=cursorPos.y-startLine;if(visibleRow<0||visibleRow>=maxOutputLines)return"\x1B[?25l";let rowDelta=maxOutputLines-1-visibleRow,suffix="";if(rowDelta>0)suffix+=`\x1B[${rowDelta}A`;if(suffix+="\r",cursorPos.x>0)suffix+=`\x1B[${cursorPos.x}C`;return suffix+="\x1B[?25h",suffix}function inlineIncrementalRender(state,prev,next,scrollbackOffset,cursorPos,ctx=defaultContext,tvState){let{termRows}=ctx;if(scrollbackOffset>0||prev.width!==next.width||prev.height!==next.height||state.prevCursorRow<0)return inlineFullRender(state,prev,next,scrollbackOffset,cursorPos,ctx);let nextContentLines=findLastContentLine(next)+1,prevContentLines=findLastContentLine(prev)+1,prevMaxOutputLines=termRows!=null?Math.min(prevContentLines,termRows):prevContentLines,maxOutputLines=termRows!=null?Math.min(nextContentLines,termRows):nextContentLines,prevStartLine=0;if(termRows!=null&&prevContentLines>termRows)prevStartLine=prevContentLines-termRows;let startLine=0;if(termRows!=null&&nextContentLines>termRows)startLine=nextContentLines-termRows;if(startLine!==prevStartLine)return inlineFullRender(state,prev,next,scrollbackOffset,cursorPos,ctx);let{pool,count}=diffBuffers(prev,next);if(count===0&&nextContentLines===prevContentLines){let suffix=inlineCursorSuffix(cursorPos??null,next,ctx);return updateInlineCursorRow(state,cursorPos,maxOutputLines,startLine),suffix}let output="";if(state.prevCursorRow>0)output+=`\x1B[${state.prevCursorRow}A`;output+="\r",output+="\x1B[?25l";let effectiveOutputLines=Math.max(prevMaxOutputLines,maxOutputLines),changes=changesToAnsi(pool,count,ctx,next,startLine,effectiveOutputLines);output+=changes.output;let finalY=changes.finalY,prevBottomRow=prevMaxOutputLines-1,bottomRow=maxOutputLines-1;if(maxOutputLines>prevMaxOutputLines){let fromRow=finalY>=0?finalY:0;if(fromRow>=bottomRow);else if(fromRow>=prevBottomRow){let remainingRows=bottomRow-fromRow;for(let i=0;i<remainingRows;i++)output+=`\r
39
+ `}else{if(fromRow<prevBottomRow){let dy=prevBottomRow-fromRow;output+=dy===1?`\r
40
+ `:`\r\x1B[${dy}B`}let newRows=bottomRow-prevBottomRow;for(let i=0;i<newRows;i++)output+=`\r
41
+ `}}else if(maxOutputLines<prevMaxOutputLines){let fromRow=finalY>=0?finalY:0;if(fromRow<bottomRow){let dy=bottomRow-fromRow;output+=dy===1?`\r
42
+ `:`\r\x1B[${dy}B`}else if(fromRow>bottomRow)output+=`\x1B[${fromRow-bottomRow}A`;let orphanCount=prevMaxOutputLines-maxOutputLines;for(let y=0;y<orphanCount;y++)output+=`
43
+ \r\x1B[K`;if(orphanCount>0)output+=`\x1B[${orphanCount}A`}else if(finalY>=0&&finalY<bottomRow){let dy=bottomRow-finalY;output+=dy===1?`\r
44
+ `:`\r\x1B[${dy}B`}if(output+=inlineCursorSuffix(cursorPos??null,next,ctx),isStrictOutput()||tvState?.hasVt100){let savedMode=ctx.mode;ctx.mode="fullscreen";let fsIncrOutput=changesToAnsi(pool,count,ctx,next).output;verifyOutputEquivalence(prev,next,fsIncrOutput,ctx),ctx.mode=savedMode}return updateInlineCursorRow(state,cursorPos,maxOutputLines,startLine),output}function inlineFullRender(state,prev,next,scrollbackOffset,cursorPos,ctx=defaultContext){let{termRows}=ctx,nextContentLines=findLastContentLine(next)+1,prevOutputLines,cursorRowInRegion;if(state.prevCursorRow>=0)prevOutputLines=state.prevOutputLines,cursorRowInRegion=state.prevCursorRow;else{let prevContentLines=findLastContentLine(prev)+1;prevOutputLines=termRows!=null?Math.min(prevContentLines,termRows):prevContentLines,cursorRowInRegion=prevOutputLines-1}let rawCursorOffset=cursorRowInRegion+scrollbackOffset,cursorOffset=termRows!=null&&!isStrictOutput()?Math.min(rawCursorOffset,termRows-1):rawCursorOffset,maxOutputLines=termRows!=null?Math.min(nextContentLines,termRows):nextContentLines;if(scrollbackOffset===0){let{count}=diffBuffers(prev,next);if(count===0)return""}let prefix="";if(cursorOffset>0)prefix=`\x1B[${cursorOffset}A\r`;let output=prefix+bufferToAnsi(next,ctx,maxOutputLines),terminalScroll=termRows!=null?Math.max(0,rawCursorOffset-(termRows-1)):0,lastOccupiedLine=Math.max(prevOutputLines-1-terminalScroll,0),nextLastLine=maxOutputLines-1;if(lastOccupiedLine>nextLastLine){for(let y=nextLastLine+1;y<=lastOccupiedLine;y++)output+=`
45
+ \r\x1B[K`;let up=lastOccupiedLine-nextLastLine;if(up>0)output+=`\x1B[${up}A`}output+=inlineCursorSuffix(cursorPos??null,next,ctx);let startLine=0;if(termRows!=null&&nextContentLines>termRows)startLine=nextContentLines-termRows;return updateInlineCursorRow(state,cursorPos,maxOutputLines,startLine),output}function bufferToAnsi(buffer,ctx=defaultContext,maxRows){let{mode}=ctx,output="",currentStyle=null,currentHyperlink,maxLine=mode==="inline"?findLastContentLine(buffer):buffer.height-1,startLine=0;if(maxRows!=null&&maxLine>=maxRows)if(mode==="fullscreen")maxLine=maxRows-1;else startLine=maxLine-maxRows+1;if(mode==="fullscreen")output+="\x1B[H";else output+="\x1B[?25l";let cell=createMutableCell(),cellStyle={fg:null,bg:null,underlineColor:null,attrs:{}};for(let y=startLine;y<=maxLine;y++){if(mode==="inline")output+="\r";else if(y>startLine)output+=`\x1B[${y+1};1H`;for(let x=0;x<buffer.width;x++){buffer.readCellInto(x,y,cell);let cellHyperlink=cell.hyperlink;if(cellHyperlink!==currentHyperlink){if(currentHyperlink)output+="\x1B]8;;\x1B\\";if(cellHyperlink)output+=`\x1B]8;;${cellHyperlink}\x1B\\`;currentHyperlink=cellHyperlink}if(cellStyle.fg=cell.fg,cellStyle.bg=cell.bg,cellStyle.underlineColor=cell.underlineColor,cellStyle.attrs=cell.attrs,!styleEquals(currentStyle,cellStyle)){let saved={fg:cell.fg,bg:cell.bg,underlineColor:cell.underlineColor,attrs:{...cell.attrs}};output+=styleTransition(currentStyle,saved,ctx),currentStyle=saved}let char=cell.char||" ";if(output+=wrapTextSizing(char,cell.wide,ctx),cell.wide)if(x++,mode==="fullscreen")output+=`\x1B[${y-startLine+1};${x+2}H`;else{if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;let nextCol=x+1;if(output+="\r",nextCol>0)output+=nextCol===1?"\x1B[C":`\x1B[${nextCol}C`}}if(currentHyperlink)output+="\x1B]8;;\x1B\\",currentHyperlink=void 0;if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;if(output+="\x1B[K",y<maxLine){if(mode==="inline")output+=`\r
46
+ `}}if(currentHyperlink)output+="\x1B]8;;\x1B\\";return output+="\x1B[0m",output}function sortPoolByPosition(pool,count){for(let i=1;i<count;i++){let item=pool[i],iy=item.y,ix=item.x,j=i-1;while(j>=0&&(pool[j].y>iy||pool[j].y===iy&&pool[j].x>ix))pool[j+1]=pool[j],j--;pool[j+1]=item}}function changesToAnsi(pool,count,ctx=defaultContext,buffer,startLine=0,maxOutputLines=1/0){let{mode}=ctx;if(count===0)return{output:"",finalY:-1};sortPoolByPosition(pool,count);let output="",currentStyle=null,currentHyperlink,isInline=mode==="inline",endLine=startLine+maxOutputLines,finalY=-1,cursorX=-1,cursorY=-1,prevY=-1,lastEmittedX=-1,lastEmittedY=-1;for(let i=0;i<count;i++){let change=pool[i],x=change.x,y=change.y,cell=change.cell;if(isInline&&(y<startLine||y>=endLine))continue;if(cell.continuation){if(lastEmittedX===x-1&&lastEmittedY===y)continue;if(buffer&&x>0){if(x=x-1,buffer.readCellInto(x,y,wideCharLookupCell),cell=wideCharLookupCell,cell.continuation||!cell.wide)continue}else continue}let renderY=isInline?y-startLine:y;if(y!==prevY&&currentHyperlink)output+="\x1B]8;;\x1B\\",currentHyperlink=void 0;if(prevY=y,renderY!==cursorY||x!==cursorX)if(cursorY>=0&&renderY===cursorY+1&&x===0){if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;output+=`\r
47
+ `}else if(cursorY>=0&&renderY===cursorY&&x>cursorX){if(currentStyle&&currentStyle.bg!==null)output+="\x1B[0m",currentStyle=null;let dx=x-cursorX;output+=dx===1?"\x1B[C":`\x1B[${dx}C`}else if(cursorY>=0&&renderY>cursorY&&x===0){let dy=renderY-cursorY;if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;output+=dy===1?`\r
48
+ `:`\r\x1B[${dy}B`}else if(isInline){if(currentStyle&&(currentStyle.bg!==null||hasActiveAttrs(currentStyle.attrs)))output+="\x1B[0m",currentStyle=null;let fromRow=cursorY>=0?cursorY:0;if(renderY>fromRow)output+=`\x1B[${renderY-fromRow}B\r`;else if(renderY<fromRow)output+=`\x1B[${fromRow-renderY}A\r`;else output+="\r";if(x>0)output+=x===1?"\x1B[C":`\x1B[${x}C`}else output+=`\x1B[${renderY+1};${x+1}H`;let cellHyperlink=cell.hyperlink;if(cellHyperlink!==currentHyperlink){if(currentHyperlink)output+="\x1B]8;;\x1B\\";if(cellHyperlink)output+=`\x1B]8;;${cellHyperlink}\x1B\\`;currentHyperlink=cellHyperlink}if(reusableCellStyle.fg=cell.fg,reusableCellStyle.bg=cell.bg,reusableCellStyle.underlineColor=cell.underlineColor,reusableCellStyle.attrs=cell.attrs,!styleEquals(currentStyle,reusableCellStyle)){let prevStyle=currentStyle;currentStyle={fg:cell.fg,bg:cell.bg,underlineColor:cell.underlineColor,attrs:{...cell.attrs}},output+=styleTransition(prevStyle,currentStyle,ctx)}let char=cell.char||" ";if(output+=wrapTextSizing(char,cell.wide,ctx),cursorX=x+(cell.wide?2:1),cursorY=renderY,lastEmittedX=x,lastEmittedY=y,cell.wide)if(isInline){if(currentStyle&&currentStyle.bg!==null)output+="\x1B[0m",currentStyle=null;if(output+="\r",cursorX>0)output+=cursorX===1?"\x1B[C":`\x1B[${cursorX}C`}else output+=`\x1B[${cursorY+1};${cursorX+1}H`}if(finalY=cursorY,currentHyperlink)output+="\x1B]8;;\x1B\\";if(currentStyle)output+="\x1B[0m";return{output,finalY}}function styleToAnsi2(style,ctx=defaultContext){let{fg,bg}=style,result="";if(fg!==null)result+=`\x1B[${fgColorCode(fg)}m`;if(bg!==null&&!isDefaultBg(bg))result+=`\x1B[${bgColorCode(bg)}m`;if(style.attrs.bold)result+="\x1B[1m";if(style.attrs.dim)result+="\x1B[2m";if(style.attrs.italic)result+="\x1B[3m";if(!ctx.caps.underlineStyles){if(style.attrs.underline||style.attrs.underlineStyle)result+="\x1B[4m"}else{let underlineStyle=style.attrs.underlineStyle,sgrSubparam=underlineStyleToSgr(underlineStyle);if(sgrSubparam!==null&&sgrSubparam!==0)result+=`\x1B[4:${sgrSubparam}m`;else if(style.attrs.underline)result+="\x1B[4m"}if(style.attrs.blink)result+="\x1B[5m";if(style.attrs.inverse)result+="\x1B[7m";if(style.attrs.hidden)result+="\x1B[8m";if(style.attrs.strikethrough)result+="\x1B[9m";if(ctx.caps.underlineColor&&style.underlineColor!==null&&style.underlineColor!==void 0)if(typeof style.underlineColor==="number")result+=`\x1B[58;5;${style.underlineColor}m`;else result+=`\x1B[58;2;${style.underlineColor.r};${style.underlineColor.g};${style.underlineColor.b}m`;return result}function createDefaultSgr(){return{fg:null,bg:null,bold:!1,dim:!1,italic:!1,underline:!1,blink:!1,inverse:!1,hidden:!1,strikethrough:!1}}function createDefaultStyledCell(){return{char:" ",fg:null,bg:null,bold:!1,dim:!1,italic:!1,underline:!1,blink:!1,inverse:!1,hidden:!1,strikethrough:!1}}function applySgrParams(params,sgr){if(params===""||params==="0"){sgr.fg=null,sgr.bg=null,sgr.bold=!1,sgr.dim=!1,sgr.italic=!1,sgr.underline=!1,sgr.blink=!1,sgr.inverse=!1,sgr.hidden=!1,sgr.strikethrough=!1;return}let parts=params.split(";"),i=0;while(i<parts.length){let code=parts[i],colonIdx=code.indexOf(":");if(colonIdx>=0){if(parseInt(code.substring(0,colonIdx))===4){let sub=parseInt(code.substring(colonIdx+1));sgr.underline=sub>0}i++;continue}let n=parseInt(code);if(n===0)sgr.fg=null,sgr.bg=null,sgr.bold=!1,sgr.dim=!1,sgr.italic=!1,sgr.underline=!1,sgr.blink=!1,sgr.inverse=!1,sgr.hidden=!1,sgr.strikethrough=!1;else if(n===1)sgr.bold=!0;else if(n===2)sgr.dim=!0;else if(n===3)sgr.italic=!0;else if(n===4)sgr.underline=!0;else if(n===5||n===6)sgr.blink=!0;else if(n===7)sgr.inverse=!0;else if(n===8)sgr.hidden=!0;else if(n===9)sgr.strikethrough=!0;else if(n===22)sgr.bold=!1,sgr.dim=!1;else if(n===23)sgr.italic=!1;else if(n===24)sgr.underline=!1;else if(n===25)sgr.blink=!1;else if(n===27)sgr.inverse=!1;else if(n===28)sgr.hidden=!1;else if(n===29)sgr.strikethrough=!1;else if(n>=30&&n<=37)sgr.fg=n-30;else if(n===38){if(i+1<parts.length&&parts[i+1]==="5"&&i+2<parts.length)sgr.fg=parseInt(parts[i+2]),i+=2;else if(i+1<parts.length&&parts[i+1]==="2"&&i+4<parts.length)sgr.fg={r:parseInt(parts[i+2]),g:parseInt(parts[i+3]),b:parseInt(parts[i+4])},i+=4}else if(n===39)sgr.fg=null;else if(n>=40&&n<=47)sgr.bg=n-40;else if(n===48){if(i+1<parts.length&&parts[i+1]==="5"&&i+2<parts.length)sgr.bg=parseInt(parts[i+2]),i+=2;else if(i+1<parts.length&&parts[i+1]==="2"&&i+4<parts.length)sgr.bg={r:parseInt(parts[i+2]),g:parseInt(parts[i+3]),b:parseInt(parts[i+4])},i+=4}else if(n===49)sgr.bg=null;else if(n>=90&&n<=97)sgr.fg=n-90+8;else if(n>=100&&n<=107)sgr.bg=n-100+8;i++}}function replayAnsiWithStyles(width,height,ansi,ctx=defaultContext){let screen=Array.from({length:height},()=>Array.from({length:width},()=>createDefaultStyledCell())),cx=0,cy=0,sgr=createDefaultSgr(),i=0;while(i<ansi.length)if(ansi[i]==="\x1B")if(ansi[i+1]==="["){i+=2;let params="";while(i<ansi.length&&(ansi[i]>="0"&&ansi[i]<="9"||ansi[i]===";"||ansi[i]==="?"||ansi[i]===":"))params+=ansi[i],i++;let cmd=ansi[i];if(i++,cmd==="H")if(params==="")cx=0,cy=0;else{let cmdParts=params.split(";");cy=Math.min(height-1,Math.max(0,(parseInt(cmdParts[0])||1)-1)),cx=Math.min(width-1,Math.max(0,(parseInt(cmdParts[1])||1)-1))}else if(cmd==="K"){if(cy>=height)continue;for(let x=cx;x<width;x++){let cell=screen[cy][x];cell.char=" ",cell.fg=null,cell.bg=sgr.bg,cell.bold=!1,cell.dim=!1,cell.italic=!1,cell.underline=!1,cell.blink=!1,cell.inverse=!1,cell.hidden=!1,cell.strikethrough=!1}}else if(cmd==="A")cy=Math.max(0,cy-(parseInt(params)||1));else if(cmd==="B")cy=Math.min(height-1,cy+(parseInt(params)||1));else if(cmd==="C")cx=Math.min(width-1,cx+(parseInt(params)||1));else if(cmd==="D")cx=Math.max(0,cx-(parseInt(params)||1));else if(cmd==="G")cx=Math.max(0,(parseInt(params)||1)-1);else if(cmd==="J"){if(params==="2")for(let y=0;y<height;y++)for(let x=0;x<width;x++)screen[y][x]=createDefaultStyledCell()}else if(cmd==="m")applySgrParams(params,sgr)}else if(ansi[i+1]==="]"){i+=2;let oscPayload="";while(i<ansi.length){if(ansi[i]==="\x1B"&&ansi[i+1]==="\\"){i+=2;break}if(ansi[i]==="\x07"){i++;break}oscPayload+=ansi[i],i++}if(oscPayload.startsWith("66;")){let semiIdx=oscPayload.indexOf(";",3);if(semiIdx!==-1){let text=oscPayload.slice(semiIdx+1),widthParam=oscPayload.slice(3,semiIdx),declaredWidth=widthParam.startsWith("w=")?parseInt(widthParam.slice(2))||1:1;if(cy<height&&cx<width){let cell=screen[cy][cx];if(cell.char=text,cell.fg=sgr.fg,cell.bg=sgr.bg,cell.bold=sgr.bold,cell.dim=sgr.dim,cell.italic=sgr.italic,cell.underline=sgr.underline,cell.blink=sgr.blink,cell.inverse=sgr.inverse,cell.hidden=sgr.hidden,cell.strikethrough=sgr.strikethrough,declaredWidth>1&&cx+1<width){let cont=screen[cy][cx+1];cont.char=" ",cont.fg=null,cont.bg=sgr.bg,cont.bold=!1,cont.dim=!1,cont.italic=!1,cont.underline=!1,cont.blink=!1,cont.inverse=!1,cont.hidden=!1,cont.strikethrough=!1}cx+=declaredWidth}}}}else if(ansi[i+1]===">"){i+=2;while(i<ansi.length&&ansi[i]!=="\x1B")i++}else i+=2;else if(ansi[i]==="\r")cx=0,i++;else if(ansi[i]===`
49
+ `)cy=Math.min(height-1,cy+1),i++;else{let cp=ansi.codePointAt(i),cpLen=cp>65535?2:1,grapheme=String.fromCodePoint(cp),j=i+cpLen,prevWasZwj=!1;while(j<ansi.length){let nextCp=ansi.codePointAt(j);if(!(prevWasZwj||nextCp>=768&&nextCp<=879||nextCp>=8400&&nextCp<=8447||nextCp>=65024&&nextCp<=65039||nextCp===65038||nextCp===65039||nextCp===8205||nextCp>=917760&&nextCp<=917999||nextCp>=127995&&nextCp<=127999||cp>=127462&&cp<=127487&&nextCp>=127462&&nextCp<=127487))break;prevWasZwj=nextCp===8205;let nextLen=nextCp>65535?2:1;grapheme+=String.fromCodePoint(nextCp),j+=nextLen}if(cy<height&&cx<width){let charWidth=outputGraphemeWidth(grapheme,ctx)||1,cell=screen[cy][cx];if(cell.char=grapheme,cell.fg=sgr.fg,cell.bg=sgr.bg,cell.bold=sgr.bold,cell.dim=sgr.dim,cell.italic=sgr.italic,cell.underline=sgr.underline,cell.blink=sgr.blink,cell.inverse=sgr.inverse,cell.hidden=sgr.hidden,cell.strikethrough=sgr.strikethrough,charWidth>1&&cx+1<width){let cont=screen[cy][cx+1];cont.char=" ",cont.fg=null,cont.bg=sgr.bg,cont.bold=!1,cont.dim=!1,cont.italic=!1,cont.underline=!1,cont.blink=!1,cont.inverse=!1,cont.hidden=!1,cont.strikethrough=!1}cx+=charWidth}i=j}return screen}function formatColor(c){if(c===null)return"default";if(typeof c==="number")return`${c}`;return`rgb(${c.r},${c.g},${c.b})`}function captureStrictFailureArtifacts(opts){try{let fs=__require("fs"),path=__require("path"),dir=`/tmp/silvery-strict-failure-${Date.now()}`;fs.mkdirSync(dir,{recursive:!0});let meta={source:opts.source,timestamp:new Date().toISOString(),frameCount:opts.frameCount,prevSize:opts.prev?{width:opts.prev.width,height:opts.prev.height}:null,nextSize:opts.next?{width:opts.next.width,height:opts.next.height}:null,incrOutputLength:opts.incrOutput?.length,freshOutputLength:opts.freshOutput?.length,testName:globalThis.__vitest_worker__?.current?.name};if(fs.writeFileSync(path.join(dir,"meta.json"),JSON.stringify(meta,null,2)),fs.writeFileSync(path.join(dir,"error.txt"),opts.errorMessage),opts.incrOutput)fs.writeFileSync(path.join(dir,"incremental.ansi"),opts.incrOutput);if(opts.freshOutput)fs.writeFileSync(path.join(dir,"fresh.ansi"),opts.freshOutput);if(opts.prev){let rows=[];for(let y=0;y<opts.prev.height;y++){let row="";for(let x=0;x<opts.prev.width;x++){let cell=opts.prev.getCell(x,y);row+=cell.char||" "}rows.push(row.trimEnd())}fs.writeFileSync(path.join(dir,"prev-buffer.txt"),rows.join(`
50
+ `))}if(opts.next){let rows=[];for(let y=0;y<opts.next.height;y++){let row="";for(let x=0;x<opts.next.width;x++){let cell=opts.next.getCell(x,y);row+=cell.char||" "}rows.push(row.trimEnd())}fs.writeFileSync(path.join(dir,"next-buffer.txt"),rows.join(`
51
+ `))}if(opts.prev&&opts.ctx){let freshPrev=bufferToAnsi(opts.prev,opts.ctx);fs.writeFileSync(path.join(dir,"fresh-prev.ansi"),freshPrev)}return dir}catch{return"(artifact capture failed)"}}function verifyOutputEquivalence(prev,next,incrOutput,ctx=defaultContext){let{mode}=ctx,w=Math.max(prev.width,next.width),vtHeight=Math.max(prev.height,next.height),compareHeight=next.height;if(process.env.SILVERY_DEBUG_OUTPUT)console.error(`[VERIFY] prev=${prev.width}x${prev.height} next=${next.width}x${next.height} vtSize=${w}x${vtHeight}`);let freshPrev=bufferToAnsi(prev,ctx);if(process.env.SILVERY_DEBUG_OUTPUT){console.error(`[VERIFY] freshPrev len=${freshPrev.length} incrOutput len=${incrOutput.length}`);let escaped=incrOutput.replace(/\x1b/g,"\\e").replace(/\r/g,"\\r").replace(/\n/g,"\\n");console.error(`[VERIFY] incrOutput: ${escaped.slice(0,500)}`)}let screenIncr=replayAnsiWithStyles(w,vtHeight,freshPrev+incrOutput,ctx),freshNext=bufferToAnsi(next,ctx),screenFresh=replayAnsiWithStyles(w,vtHeight,freshNext,ctx),_dumpRowWideCells=(buf,row)=>{let parts=[];for(let cx=0;cx<buf.width;cx++){let c=buf.getCell(cx,row),cp=c.char?[...c.char].map((ch)=>"U+"+(ch.codePointAt(0)??0).toString(16).toUpperCase().padStart(4,"0")).join(","):"empty";if(c.wide)parts.push(`W@${cx}:${cp}(gw=${outputGraphemeWidth(c.char,ctx)})`);if(c.continuation)parts.push(`C@${cx}`);let charToWrite=c.char||" ",vtWidth=outputGraphemeWidth(charToWrite,ctx),bufWidth=c.wide?2:1;if(!c.continuation&&vtWidth!==bufWidth)parts.push(`MISMATCH@${cx}:${cp}(vtW=${vtWidth},bufW=${bufWidth},tse=${outputTextSizingEnabled(ctx)})`)}return parts.join(" ")};for(let y=0;y<vtHeight;y++)for(let x=0;x<w;x++){let incr=screenIncr[y][x],fresh=screenFresh[y][x];if(incr.char!==fresh.char){let incrRow=screenIncr[y].map((c)=>c.char).join(""),freshRow=screenFresh[y].map((c)=>c.char).join(""),prevRow=screenIncr[y].map((_2,cx)=>{return prev.getCell(cx,y).char}).join(""),nextCell=next.getCell(x,y),prevCell=prev.getCell(x,y),contextStart=Math.max(0,x-5),contextEnd=Math.min(w,x+10),colDetails=[];for(let cx=contextStart;cx<contextEnd;cx++){let ic=screenIncr[y][cx],fc=screenFresh[y][cx],pc=prev.getCell(cx,y),nc=next.getCell(cx,y),marker=cx===x?" <<<":ic.char!==fc.char?" !!!":"";colDetails.push(` col ${cx}: prev='${pc.char}'(w=${pc.wide},c=${pc.continuation}) next='${nc.char}' incr='${ic.char}' fresh='${fc.char}' wide=${nc.wide} cont=${nc.continuation}${marker}`)}let msg=`STRICT_OUTPUT char mismatch at (${x},${y}): incremental='${incr.char}' fresh='${fresh.char}'
52
+ prev buffer cell: char='${prevCell.char}' bg=${prevCell.bg} wide=${prevCell.wide} cont=${prevCell.continuation}
53
+ next buffer cell: char='${nextCell.char}' bg=${nextCell.bg} wide=${nextCell.wide} cont=${nextCell.continuation}
54
+ incr row: ${incrRow}
55
+ fresh row: ${freshRow}
56
+ prev row: ${prevRow}
57
+ Wide/cont cells on row ${y} (next buffer): ${_dumpRowWideCells(next,y)}
58
+ Wide/cont cells on row ${y} (prev buffer): ${_dumpRowWideCells(prev,y)}
59
+ Column detail around mismatch:
60
+ ${colDetails.join(`
61
+ `)}`,artifactDir=captureStrictFailureArtifacts({source:"STRICT_OUTPUT",errorMessage:msg,prev,next,incrOutput,freshOutput:freshNext,ctx}),fullMsg=`${msg}
62
+ Artifacts: ${artifactDir}`;throw console.error(fullMsg),new IncrementalRenderMismatchError(fullMsg)}let diffs=[];if(!sgrColorEquals(incr.fg,fresh.fg))diffs.push(`fg: ${formatColor(incr.fg)} vs ${formatColor(fresh.fg)}`);if(!sgrColorEquals(incr.bg,fresh.bg))diffs.push(`bg: ${formatColor(incr.bg)} vs ${formatColor(fresh.bg)}`);if(incr.bold!==fresh.bold)diffs.push(`bold: ${incr.bold} vs ${fresh.bold}`);if(incr.dim!==fresh.dim)diffs.push(`dim: ${incr.dim} vs ${fresh.dim}`);if(incr.italic!==fresh.italic)diffs.push(`italic: ${incr.italic} vs ${fresh.italic}`);if(incr.underline!==fresh.underline)diffs.push(`underline: ${incr.underline} vs ${fresh.underline}`);if(incr.inverse!==fresh.inverse)diffs.push(`inverse: ${incr.inverse} vs ${fresh.inverse}`);if(incr.strikethrough!==fresh.strikethrough)diffs.push(`strikethrough: ${incr.strikethrough} vs ${fresh.strikethrough}`);if(diffs.length>0){let msg=`STRICT_OUTPUT style mismatch at (${x},${y}) char='${incr.char}': `+diffs.join(", ")+`
63
+ incremental: fg=${formatColor(incr.fg)} bg=${formatColor(incr.bg)} bold=${incr.bold} dim=${incr.dim}
64
+ fresh: fg=${formatColor(fresh.fg)} bg=${formatColor(fresh.bg)} bold=${fresh.bold} dim=${fresh.dim}`,artifactDir2=captureStrictFailureArtifacts({source:"STRICT_OUTPUT",errorMessage:msg,prev,next,incrOutput,freshOutput:freshNext,ctx});throw new IncrementalRenderMismatchError(`${msg}
65
+ Artifacts: ${artifactDir2}`)}}}function verifyAccumulatedOutput(currentBuffer,ctx=defaultContext,accState=defaultAccState){let{mode}=ctx,w=accState.accumulateWidth,h=accState.accumulateHeight,screenAccumulated=replayAnsiWithStyles(w,h,accState.accumulatedAnsi,ctx),freshOutput=bufferToAnsi(currentBuffer,ctx),screenFresh=replayAnsiWithStyles(w,h,freshOutput,ctx);for(let y=0;y<h;y++)for(let x=0;x<w;x++){let accum=screenAccumulated[y][x],fresh=screenFresh[y][x];if(accum.char!==fresh.char){let msg=`SILVERY_STRICT_ACCUMULATE char mismatch at (${x},${y}) after ${accState.accumulateFrameCount} frames: accumulated='${accum.char}' fresh='${fresh.char}'`,dir=captureStrictFailureArtifacts({source:"STRICT_ACCUMULATE",errorMessage:msg,next:currentBuffer,incrOutput:accState.accumulatedAnsi,freshOutput,ctx,frameCount:accState.accumulateFrameCount});throw console.error(`${msg}
66
+ Artifacts: ${dir}`),new IncrementalRenderMismatchError(`${msg}
67
+ Artifacts: ${dir}`)}let diffs=[];if(!sgrColorEquals(accum.fg,fresh.fg))diffs.push(`fg: ${formatColor(accum.fg)} vs ${formatColor(fresh.fg)}`);if(!sgrColorEquals(accum.bg,fresh.bg))diffs.push(`bg: ${formatColor(accum.bg)} vs ${formatColor(fresh.bg)}`);if(accum.bold!==fresh.bold)diffs.push(`bold: ${accum.bold} vs ${fresh.bold}`);if(accum.dim!==fresh.dim)diffs.push(`dim: ${accum.dim} vs ${fresh.dim}`);if(accum.italic!==fresh.italic)diffs.push(`italic: ${accum.italic} vs ${fresh.italic}`);if(accum.underline!==fresh.underline)diffs.push(`underline: ${accum.underline} vs ${fresh.underline}`);if(accum.inverse!==fresh.inverse)diffs.push(`inverse: ${accum.inverse} vs ${fresh.inverse}`);if(accum.strikethrough!==fresh.strikethrough)diffs.push(`strikethrough: ${accum.strikethrough} vs ${fresh.strikethrough}`);if(diffs.length>0){let msg=`SILVERY_STRICT_ACCUMULATE style mismatch at (${x},${y}) char='${accum.char}' after ${accState.accumulateFrameCount} frames: `+diffs.join(", "),dir2=captureStrictFailureArtifacts({source:"STRICT_ACCUMULATE",errorMessage:msg,next:currentBuffer,freshOutput,ctx,frameCount:accState.accumulateFrameCount});throw console.error(`${msg}
68
+ Artifacts: ${dir2}`),new IncrementalRenderMismatchError(`${msg}
69
+ Artifacts: ${dir2}`)}}}function loadTermless(){if(!_createTerminal||!_createXtermBackend)_createTerminal=__require("@termless/core").createTerminal,_createXtermBackend=__require("@termless/xtermjs").createXtermBackend;return{createTerminal:_createTerminal,createXtermBackend:_createXtermBackend}}function loadGhosttyBackend(){if(!_createGhosttyBackend){let mod=__require("@termless/ghostty");if(_createGhosttyBackend=mod.createGhosttyBackend,!_ghosttyInitPromise)_ghosttyInitPromise=mod.initGhostty()}return _createGhosttyBackend}function initTerminalVerifyState(state,width,height,initialAnsi){if(state.terminal)state.terminal.close();if(state.ghosttyTerminal)state.ghosttyTerminal.close();if(state.backends.includes("xterm")){let{createTerminal,createXtermBackend}=loadTermless();state.terminal=createTerminal({backend:createXtermBackend(),cols:width,rows:height}),state.terminal.feed(initialAnsi)}else state.terminal=null;if(state.backends.includes("ghostty")){let{createTerminal}=loadTermless(),createGhostty=loadGhosttyBackend();state.ghosttyTerminal=createTerminal({backend:createGhostty(),cols:width,rows:height}),state.ghosttyTerminal.feed(initialAnsi)}else state.ghosttyTerminal=null;state.width=width,state.height=height,state.frameCount=0}function verifyTerminalEquivalence(state,incrOutput,nextBuffer,ctx){if(nextBuffer.width!==state.width||nextBuffer.height!==state.height){let freshAnsi2=bufferToAnsi(nextBuffer,ctx);initTerminalVerifyState(state,nextBuffer.width,nextBuffer.height,freshAnsi2),state.frameCount++;return}let freshAnsi=bufferToAnsi(nextBuffer,ctx);if(state.terminal){state.terminal.feed(incrOutput);let{createTerminal,createXtermBackend}=loadTermless(),freshTerm=createTerminal({backend:createXtermBackend(),cols:state.width,rows:state.height});freshTerm.feed(freshAnsi);try{compareTerminals(state.terminal,freshTerm,state,"xterm")}catch(e){if(e instanceof IncrementalRenderMismatchError){let dir=captureStrictFailureArtifacts({source:"STRICT_TERMINAL[xterm]",errorMessage:e.message,next:nextBuffer,incrOutput,freshOutput:freshAnsi,ctx,frameCount:state.frameCount});throw new IncrementalRenderMismatchError(`${e.message}
70
+ Artifacts: ${dir}`)}throw e}finally{freshTerm.close()}}if(state.ghosttyTerminal){state.ghosttyTerminal.feed(incrOutput);let{createTerminal}=loadTermless(),createGhostty=loadGhosttyBackend(),freshTerm=createTerminal({backend:createGhostty(),cols:state.width,rows:state.height});freshTerm.feed(freshAnsi);try{compareTerminals(state.ghosttyTerminal,freshTerm,state,"ghostty")}catch(e){if(e instanceof IncrementalRenderMismatchError){let dir=captureStrictFailureArtifacts({source:"STRICT_TERMINAL[ghostty]",errorMessage:e.message,next:nextBuffer,incrOutput,freshOutput:freshAnsi,ctx,frameCount:state.frameCount});throw new IncrementalRenderMismatchError(`${e.message}
71
+ Artifacts: ${dir}`)}throw e}finally{freshTerm.close()}}}function compareTerminals(incrTerm,freshTerm,state,backendName){let{width:w,height:h}=state,prefix=`SILVERY_STRICT_TERMINAL[${backendName}]`;for(let y=0;y<h;y++)for(let x=0;x<w;x++){let incrCell=incrTerm.getCell(y,x),freshCell=freshTerm.getCell(y,x),incrChar=incrCell.char||" ",freshChar=freshCell.char||" ";if(incrChar!==freshChar){let incrRow=Array.from({length:w},(_2,cx)=>incrTerm.getCell(y,cx).char||" ").join(""),freshRow=Array.from({length:w},(_2,cx)=>freshTerm.getCell(y,cx).char||" ").join(""),msg=`${prefix} char mismatch at (${x},${y}) frame ${state.frameCount}: incremental='${incrChar}' fresh='${freshChar}'
72
+ incr row: ${incrRow.trimEnd()}
73
+ fresh row: ${freshRow.trimEnd()}`;throw console.error(msg),new IncrementalRenderMismatchError(msg)}if(!rgbEquals(incrCell.fg,freshCell.fg)){let msg=`${prefix} fg color mismatch at (${x},${y}) char='${incrChar}' frame ${state.frameCount}: incremental=${formatRgb(incrCell.fg)} fresh=${formatRgb(freshCell.fg)}`;throw console.error(msg),new IncrementalRenderMismatchError(msg)}if(!rgbEquals(incrCell.bg,freshCell.bg)){let msg=`${prefix} bg color mismatch at (${x},${y}) char='${incrChar}' frame ${state.frameCount}: incremental=${formatRgb(incrCell.bg)} fresh=${formatRgb(freshCell.bg)}`;throw console.error(msg),new IncrementalRenderMismatchError(msg)}let attrDiffs=[];if(incrCell.bold!==freshCell.bold)attrDiffs.push(`bold: ${incrCell.bold} vs ${freshCell.bold}`);if(incrCell.dim!==freshCell.dim)attrDiffs.push(`dim: ${incrCell.dim} vs ${freshCell.dim}`);if(incrCell.italic!==freshCell.italic)attrDiffs.push(`italic: ${incrCell.italic} vs ${freshCell.italic}`);if(incrCell.inverse!==freshCell.inverse)attrDiffs.push(`inverse: ${incrCell.inverse} vs ${freshCell.inverse}`);if(incrCell.strikethrough!==freshCell.strikethrough)attrDiffs.push(`strikethrough: ${incrCell.strikethrough} vs ${freshCell.strikethrough}`);if(attrDiffs.length>0){let msg=`${prefix} attr mismatch at (${x},${y}) char='${incrChar}' frame ${state.frameCount}: `+attrDiffs.join(", ");throw console.error(msg),new IncrementalRenderMismatchError(msg)}}}function rgbEquals(a,b){if(a===b)return!0;if(a===null||b===null)return!1;return a.r===b.r&&a.g===b.g&&a.b===b.b}function formatRgb(c){if(c===null)return"null";return`rgb(${c.r},${c.g},${c.b})`}function sgrColorEquals(a,b){if(a===b)return!0;if(a===null||b===null)return!1;if(typeof a==="number"||typeof b==="number")return a===b;return a.r===b.r&&a.g===b.g&&a.b===b.b}var DEBUG_OUTPUT,FULL_RENDER,DEBUG_CAPTURE,CAPTURE_RAW,_debugFrameCount=0,_captureRawFrameCount=0,defaultContext,defaultAccState,defaultTerminalVerifyState,reusableCellStyle,wideCharLookupCell,_createTerminal=null,_createXtermBackend=null,_createGhosttyBackend=null,_ghosttyInitPromise=null;var init_output_phase=__esm(()=>{init_buffer();init_errors();init_text_sizing();init_unicode();init_diff_buffers();DEBUG_OUTPUT=!!process.env.SILVERY_DEBUG_OUTPUT,FULL_RENDER=!!process.env.SILVERY_FULL_RENDER,DEBUG_CAPTURE=!!process.env.SILVERY_DEBUG_CAPTURE,CAPTURE_RAW=!!process.env.SILVERY_CAPTURE_RAW;defaultContext={caps:{underlineStyles:!0,underlineColor:!0,colorLevel:"truecolor"},measurer:null,sgrCache:new Map,transitionCache:new Map,mode:"fullscreen",termRows:void 0};defaultAccState={accumulatedAnsi:"",accumulateWidth:0,accumulateHeight:0,accumulateFrameCount:0};defaultTerminalVerifyState=createTerminalVerifyState();reusableCellStyle={fg:null,bg:null,underlineColor:null,attrs:{}},wideCharLookupCell=createMutableCell()});var exports_terminal_adapter={};__export(exports_terminal_adapter,{terminalMeasurer:()=>terminalMeasurer,terminalAdapter:()=>terminalAdapter,createTerminalMeasurer:()=>createTerminalMeasurer,TerminalRenderBuffer:()=>TerminalRenderBuffer});function createTerminalMeasurer(measurer){let dw=measurer?measurer.displayWidth.bind(measurer):displayWidth;return{measureText(text,_style){return{width:dw(text),height:1}},getLineHeight(_style){return 1}}}class TerminalRenderBuffer{buffer;dw;constructor(width,height,measurer){this.buffer=new TerminalBuffer(width,height),this.dw=measurer?measurer.displayWidth.bind(measurer):displayWidth}get width(){return this.buffer.width}get height(){return this.buffer.height}getTerminalBuffer(){return this.buffer}fillRect(x,y,width,height,style){let cellStyle=this.convertStyle(style);for(let row=y;row<y+height;row++)for(let col=x;col<x+width;col++)if(this.buffer.inBounds(col,row))this.buffer.setCell(col,row,{char:" ",...cellStyle})}drawText(x,y,text,style){let cellStyle=this.convertStyle(style),col=x;for(let char of text){if(!this.buffer.inBounds(col,y))break;let charWidth=this.dw(char);this.buffer.setCell(col,y,{char,...cellStyle,wide:charWidth>1});for(let i=1;i<charWidth;i++)if(this.buffer.inBounds(col+i,y))this.buffer.setCell(col+i,y,{char:"",...cellStyle,continuation:!0});col+=charWidth}}drawChar(x,y,char,style){if(this.buffer.inBounds(x,y))this.buffer.setCell(x,y,{char,...this.convertStyle(style)})}inBounds(x,y){return this.buffer.inBounds(x,y)}convertStyle(style){return{fg:this.parseColor(style.fg),bg:this.parseColor(style.bg),underlineColor:this.parseColor(style.attrs?.underlineColor),attrs:{bold:style.attrs?.bold,dim:style.attrs?.dim,italic:style.attrs?.italic,underline:style.attrs?.underline,underlineStyle:style.attrs?.underlineStyle,strikethrough:style.attrs?.strikethrough,inverse:style.attrs?.inverse}}}parseColor(color){if(!color)return null;if(color.startsWith("#")){let hex=color.slice(1);if(hex.length===6)return{r:Number.parseInt(hex.slice(0,2),16),g:Number.parseInt(hex.slice(2,4),16),b:Number.parseInt(hex.slice(4,6),16)};if(hex.length===3)return{r:Number.parseInt(hex[0]+hex[0],16),g:Number.parseInt(hex[1]+hex[1],16),b:Number.parseInt(hex[2]+hex[2],16)}}let rgbMatch=color.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);if(rgbMatch)return{r:Number.parseInt(rgbMatch[1],10),g:Number.parseInt(rgbMatch[2],10),b:Number.parseInt(rgbMatch[3],10)};let namedColors2={black:0,red:1,green:2,yellow:3,blue:4,magenta:5,cyan:6,white:7,gray:8,grey:8,brightblack:8,brightred:9,brightgreen:10,brightyellow:11,brightblue:12,brightmagenta:13,brightcyan:14,brightwhite:15},normalized=color.toLowerCase().replace(/[^a-z]/g,""),index=namedColors2[normalized];if(index!==void 0)return index;return null}}var BORDER_CHARS,terminalMeasurer,terminalAdapter;var init_terminal_adapter=__esm(()=>{init_buffer();init_output_phase();init_unicode();BORDER_CHARS={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:"|"}};terminalMeasurer=createTerminalMeasurer();terminalAdapter={name:"terminal",measurer:terminalMeasurer,createBuffer(width,height){return new TerminalRenderBuffer(width,height)},flush(buffer,prevBuffer){let termBuffer=buffer.getTerminalBuffer(),prevTermBuffer=prevBuffer?prevBuffer.getTerminalBuffer():null;return outputPhase(prevTermBuffer,termBuffer)},getBorderChars(style){return BORDER_CHARS[style]??BORDER_CHARS.single}}});function setRenderAdapter(adapter){currentAdapter=adapter}function getRenderAdapter(){if(!currentAdapter)throw Error("No render adapter set. Call setRenderAdapter() first.");return currentAdapter}function hasRenderAdapter(){return currentAdapter!==null}function getTextMeasurer(){return getRenderAdapter().measurer}async function ensureRenderAdapterInitialized(){if(hasRenderAdapter())return;let{terminalAdapter:terminalAdapter2}=await Promise.resolve().then(() => (init_terminal_adapter(),exports_terminal_adapter));setRenderAdapter(terminalAdapter2)}var currentAdapter=null;var init_content_phase_adapter=__esm(()=>{init_unicode();init_render_text()});import{createLogger as createLogger3}from"loggily";function executeRender(root,width,height,prevBuffer,options="fullscreen",config){let ctx=config?.measurer?{measurer:config.measurer}:void 0;if(config?.measurer)return runWithMeasurer(config.measurer,()=>{return executeRenderCore(root,width,height,prevBuffer,options,config,ctx)});return executeRenderCore(root,width,height,prevBuffer,options,config,ctx)}function executeRenderCore(root,width,height,prevBuffer,options="fullscreen",config,ctx){let __stack8=[];try{let opts=typeof options==="string"?{mode:options}:options;let{mode="fullscreen",skipLayoutNotifications=!1,skipScrollStateUpdates=!1,scrollbackOffset=0,termRows,cursorPos}=opts;if(process?.env?.SILVERY_DEV&&prevBuffer===null&&root.prevLayout!==null&&!skipLayoutNotifications)console.warn("[silvery] 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();const render=__using(__stack8,baseLog.span("pipeline",{width,height,mode}),0);clearBgConflictWarnings();let tMeasure;{let __stack=[];try{const _measure=__using(__stack,render.span("measure"),0);let t1=performance.now();measurePhase(root,ctx);tMeasure=performance.now()-t1;log2.debug?.(`measure: ${tMeasure.toFixed(2)}ms`)}catch(_catch){var _err=_catch,_hasErr=1}finally{__callDispose(__stack,_err,_hasErr)}}let tLayout;{let __stack2=[];try{const _layout=__using(__stack2,render.span("layout"),0);let t2=performance.now();layoutPhase(root,width,height);tLayout=performance.now()-t2;log2.debug?.(`layout: ${tLayout.toFixed(2)}ms`)}catch(_catch2){var _err2=_catch2,_hasErr2=1}finally{__callDispose(__stack2,_err2,_hasErr2)}}let tScroll;{let __stack3=[];try{const _scroll=__using(__stack3,render.span("scroll"),0);let t2s=performance.now();scrollPhase(root,{skipStateUpdates:skipScrollStateUpdates});tScroll=performance.now()-t2s}catch(_catch3){var _err3=_catch3,_hasErr3=1}finally{__callDispose(__stack3,_err3,_hasErr3)}}stickyPhase(root);let tScreenRect;{let __stack4=[];try{const _screenRect=__using(__stack4,render.span("screenRect"),0);let t2r=performance.now();screenRectPhase(root);tScreenRect=performance.now()-t2r}catch(_catch4){var _err4=_catch4,_hasErr4=1}finally{__callDispose(__stack4,_err4,_hasErr4)}}let tNotify=0;if(!skipLayoutNotifications){let __stack5=[];try{const _notify=__using(__stack5,render.span("notify"),0);let t2n=performance.now();notifyLayoutSubscribers(root);tNotify=performance.now()-t2n}catch(_catch5){var _err5=_catch5,_hasErr5=1}finally{__callDispose(__stack5,_err5,_hasErr5)}}let buffer;let tContent;{let __stack6=[];try{const _content=__using(__stack6,render.span("content"),0);let t3=performance.now();buffer=contentPhase(root,prevBuffer,ctx);tContent=performance.now()-t3;log2.debug?.(`content: ${tContent.toFixed(2)}ms`)}catch(_catch6){var _err6=_catch6,_hasErr6=1}finally{__callDispose(__stack6,_err6,_hasErr6)}}let output;let tOutput;{let __stack7=[];try{const outputSpan=__using(__stack7,render.span("output"),0);let t4=performance.now();let 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;outputSpan.spanData.bytes=output.length;log2.debug?.(`output: ${tOutput.toFixed(2)}ms (${output.length} bytes)`)}catch(_catch7){var _err7=_catch7,_hasErr7=1}finally{__callDispose(__stack7,_err7,_hasErr7)}}let total=performance.now()-start;log2.debug?.(`total pipeline: ${total.toFixed(2)}ms`);let pipelineTimings={measure:tMeasure,layout:tLayout,scroll:tScroll,screenRect:tScreenRect,notify:tNotify,content:tContent,output:tOutput,total,incremental:prevBuffer!==null};globalThis.__silvery_last_pipeline=pipelineTimings;globalThis.__silvery_render_count=(globalThis.__silvery_render_count??0)+1;log2.debug?.(`pipeline: measure=${tMeasure.toFixed(1)}ms layout=${tLayout.toFixed(1)}ms content=${tContent.toFixed(1)}ms output=${tOutput.toFixed(1)}ms total=${total.toFixed(1)}ms`);return{output,buffer}}catch(_catch8){var _err8=_catch8,_hasErr8=1}finally{__callDispose(__stack8,_err8,_hasErr8)}}var log2,baseLog;var init_pipeline=__esm(()=>{init_unicode();init_measure_phase();init_layout_phase();init_content_phase();init_content_phase_adapter();init_output_phase();init_content_phase_adapter();init_content_phase();init_layout_phase();init_measure_phase();init_output_phase();log2=createLogger3("silvery:pipeline"),baseLog=createLogger3("@silvery/ag-react")});var init_pipeline2=__esm(()=>{init_pipeline()});function layoutPropsChanged(oldProps,newProps){for(let prop of LAYOUT_PROPS)if(oldProps[prop]!==newProps[prop])return!0;return!1}function contentPropsChanged(oldProps,newProps){let oldChildren=oldProps.children,newChildren=newProps.children;if(oldChildren!==newChildren){if(typeof oldChildren==="string"||typeof oldChildren==="number"||(typeof newChildren==="string"||typeof newChildren==="number"))return"text"}let contentProps=["wrap","internal_transform"];for(let prop of contentProps)if(oldProps[prop]!==newProps[prop])return"text";let styleProps=["color","backgroundColor","bold","dim","dimColor","italic","underline","underlineStyle","underlineColor","strikethrough","inverse","borderColor","borderStyle","outlineStyle","outlineColor","outlineDimColor","outlineTop","outlineBottom","outlineLeft","outlineRight","theme"];for(let prop of styleProps)if(oldProps[prop]!==newProps[prop])return"style";return!1}function propsEqual(a,b){let keysA=Object.keys(a),keysB=Object.keys(b);if(keysA.length!==keysB.length)return!1;for(let key of keysA)if(a[key]!==b[key])return!1;return!0}var LAYOUT_PROPS;var init_helpers=__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"])});import{createLogger as createLogger4}from"loggily";function createNode(type,props,measurer){let layoutNode=getLayoutEngine().createNode(),node={type,props,children:[],parent:null,layoutNode,contentRect:null,screenRect:null,renderRect:null,prevLayout:null,prevScreenRect:null,prevRenderRect:null,layoutChangedThisFrame:!1,layoutDirty:!0,contentDirty:!0,stylePropsDirty:!0,bgDirty:!0,subtreeDirty:!0,childrenDirty:!0,layoutSubscribers:new Set};if(type==="silvery-box")applyBoxProps(layoutNode,props);if(type==="silvery-text"){let cachedText=null,measureCache=new Map;layoutNode.setMeasureFunc((width,widthMode,height,heightMode)=>{measureStats.calls++,measureLog.debug?.(`measure "${collectPlainTextSkipHidden(node).slice(0,40)}" width=${width} widthMode=${widthMode} height=${height} heightMode=${heightMode}`);let cacheKey=`${width}|${widthMode}|${height}|${heightMode}`,cached=measureCache.get(cacheKey);if(cached&&cachedText!==null&&!node.contentDirty)return measureStats.cacheHits++,cached;let text;if(cachedText!==null&&!node.contentDirty)text=cachedText;else{measureStats.textCollects++;let newText=collectPlainTextSkipHidden(node);if(newText!==cachedText)measureCache.clear();text=newText,cachedText=text,node.contentDirty=!1}if(!text)return{width:0,height:0};let cachedAfterCollect=measureCache.get(cacheKey);if(cachedAfterCollect)return measureStats.cacheHits++,cachedAfterCollect;let lines=text.split(`
74
+ `),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,totalHeight=0,actualWidth=0,dw=measurer?measurer.displayWidth.bind(measurer):displayWidth,wt=measurer?measurer.wrapText.bind(measurer):wrapText;for(let line of lines){measureStats.displayWidthCalls++;let lineWidth=dw(line);if(isTruncate||lineWidth<=maxWidth)totalHeight+=1,actualWidth=Math.max(actualWidth,isTruncate?Math.min(lineWidth,maxWidth):lineWidth);else{let wrapped=wt(line,maxWidth,!1,!0);totalHeight+=wrapped.length;for(let wl of wrapped)actualWidth=Math.max(actualWidth,dw(wl))}}let resultHeight=Math.max(1,totalHeight);if(heightMode==="exactly"&&Number.isFinite(height))resultHeight=height;else if(heightMode==="at-most"&&Number.isFinite(height))resultHeight=Math.min(resultHeight,height);let result={width:Math.min(actualWidth,maxWidth),height:resultHeight};return measureCache.set(cacheKey,result),result})}return node}function createRootNode(){let node=createNode("silvery-root",{}),c=getConstants();return node.layoutNode.setFlexDirection(c.FLEX_DIRECTION_COLUMN),node}function createVirtualTextNode(props){return{type:"silvery-text",props,children:[],parent:null,layoutNode:null,contentRect:null,screenRect:null,renderRect:null,prevLayout:null,prevScreenRect:null,prevRenderRect:null,layoutChangedThisFrame:!1,layoutDirty:!1,contentDirty:!0,stylePropsDirty:!0,bgDirty:!0,subtreeDirty:!0,childrenDirty:!1,layoutSubscribers:new Set,isRawText:!1,inlineRects:null}}function applyBoxProps(layoutNode,props,oldProps){let c=getConstants(),wasRemoved=(prop)=>oldProps?.[prop]!==void 0&&props[prop]===void 0;if(props.width!==void 0){if(typeof props.width==="string"&&props.width.endsWith("%"))layoutNode.setWidthPercent(Number.parseFloat(props.width));else if(typeof props.width==="number")layoutNode.setWidth(props.width);else if(props.width==="auto")layoutNode.setWidthAuto()}else if(wasRemoved("width"))layoutNode.setWidthAuto();if(props.height!==void 0){if(typeof props.height==="string"&&props.height.endsWith("%"))layoutNode.setHeightPercent(Number.parseFloat(props.height));else if(typeof props.height==="number")layoutNode.setHeight(props.height);else if(props.height==="auto")layoutNode.setHeightAuto()}else if(wasRemoved("height"))layoutNode.setHeightAuto();if(props.minWidth!==void 0){if(typeof props.minWidth==="string"&&props.minWidth.endsWith("%"))layoutNode.setMinWidthPercent(Number.parseFloat(props.minWidth));else if(typeof props.minWidth==="number")layoutNode.setMinWidth(props.minWidth)}else if(wasRemoved("minWidth"))layoutNode.setMinWidth(0);if(props.minHeight!==void 0){if(typeof props.minHeight==="string"&&props.minHeight.endsWith("%"))layoutNode.setMinHeightPercent(Number.parseFloat(props.minHeight));else if(typeof props.minHeight==="number")layoutNode.setMinHeight(props.minHeight)}else if(wasRemoved("minHeight"))layoutNode.setMinHeight(0);if(props.maxWidth!==void 0){if(typeof props.maxWidth==="string"&&props.maxWidth.endsWith("%"))layoutNode.setMaxWidthPercent(Number.parseFloat(props.maxWidth));else if(typeof props.maxWidth==="number")layoutNode.setMaxWidth(props.maxWidth)}else if(wasRemoved("maxWidth"))layoutNode.setMaxWidth(Number.POSITIVE_INFINITY);if(props.maxHeight!==void 0){if(typeof props.maxHeight==="string"&&props.maxHeight.endsWith("%"))layoutNode.setMaxHeightPercent(Number.parseFloat(props.maxHeight));else if(typeof props.maxHeight==="number")layoutNode.setMaxHeight(props.maxHeight)}else if(wasRemoved("maxHeight"))layoutNode.setMaxHeight(Number.POSITIVE_INFINITY);if(props.flexGrow!==void 0)layoutNode.setFlexGrow(props.flexGrow);else if(wasRemoved("flexGrow"))layoutNode.setFlexGrow(0);if(props.flexShrink!==void 0)layoutNode.setFlexShrink(props.flexShrink);else if(wasRemoved("flexShrink"))layoutNode.setFlexShrink(1);if(props.flexBasis!==void 0){if(typeof props.flexBasis==="string"&&props.flexBasis.endsWith("%"))layoutNode.setFlexBasisPercent(Number.parseFloat(props.flexBasis));else if(props.flexBasis==="auto")layoutNode.setFlexBasisAuto();else if(typeof props.flexBasis==="number")layoutNode.setFlexBasis(props.flexBasis)}else if(wasRemoved("flexBasis"))layoutNode.setFlexBasisAuto();if(props.flexDirection!==void 0){let directionMap={row:c.FLEX_DIRECTION_ROW,column:c.FLEX_DIRECTION_COLUMN,"row-reverse":c.FLEX_DIRECTION_ROW_REVERSE,"column-reverse":c.FLEX_DIRECTION_COLUMN_REVERSE};layoutNode.setFlexDirection(directionMap[props.flexDirection]??c.FLEX_DIRECTION_ROW)}else if(wasRemoved("flexDirection"))layoutNode.setFlexDirection(c.FLEX_DIRECTION_ROW);if(props.flexWrap!==void 0){let wrapMap={nowrap:c.WRAP_NO_WRAP,wrap:c.WRAP_WRAP,"wrap-reverse":c.WRAP_WRAP_REVERSE};layoutNode.setFlexWrap(wrapMap[props.flexWrap]??c.WRAP_NO_WRAP)}else if(wasRemoved("flexWrap"))layoutNode.setFlexWrap(c.WRAP_NO_WRAP);if(props.alignItems!==void 0)layoutNode.setAlignItems(alignToConstant(props.alignItems));else if(wasRemoved("alignItems"))layoutNode.setAlignItems(c.ALIGN_STRETCH);if(props.alignSelf!==void 0)if(props.alignSelf==="auto")layoutNode.setAlignSelf(c.ALIGN_AUTO);else layoutNode.setAlignSelf(alignToConstant(props.alignSelf));else if(wasRemoved("alignSelf"))layoutNode.setAlignSelf(c.ALIGN_AUTO);if(props.alignContent!==void 0)layoutNode.setAlignContent(alignToConstant(props.alignContent));else if(wasRemoved("alignContent"))layoutNode.setAlignContent(c.ALIGN_FLEX_START);if(props.justifyContent!==void 0)layoutNode.setJustifyContent(justifyToConstant(props.justifyContent));else if(wasRemoved("justifyContent"))layoutNode.setJustifyContent(c.JUSTIFY_FLEX_START);if(applySpacing(layoutNode,"padding",props),applySpacing(layoutNode,"margin",props),props.gap!==void 0)layoutNode.setGap(c.GUTTER_ALL,props.gap);else if(wasRemoved("gap"))layoutNode.setGap(c.GUTTER_ALL,0);if(props.columnGap!==void 0)layoutNode.setGap(c.GUTTER_COLUMN,props.columnGap);else if(wasRemoved("columnGap"))layoutNode.setGap(c.GUTTER_COLUMN,0);if(props.rowGap!==void 0)layoutNode.setGap(c.GUTTER_ROW,props.rowGap);else if(wasRemoved("rowGap"))layoutNode.setGap(c.GUTTER_ROW,0);if(props.display!==void 0)layoutNode.setDisplay(props.display==="none"?c.DISPLAY_NONE:c.DISPLAY_FLEX);else if(wasRemoved("display"))layoutNode.setDisplay(c.DISPLAY_FLEX);if(props.position!==void 0)if(props.position==="absolute")layoutNode.setPositionType(c.POSITION_TYPE_ABSOLUTE);else if(props.position==="static")layoutNode.setPositionType(c.POSITION_TYPE_STATIC);else layoutNode.setPositionType(c.POSITION_TYPE_RELATIVE);else if(wasRemoved("position"))layoutNode.setPositionType(c.POSITION_TYPE_RELATIVE);if(props.position!=="static")applyPositionOffset(layoutNode,c.EDGE_TOP,props.top),applyPositionOffset(layoutNode,c.EDGE_LEFT,props.left),applyPositionOffset(layoutNode,c.EDGE_BOTTOM,props.bottom),applyPositionOffset(layoutNode,c.EDGE_RIGHT,props.right);if(props.aspectRatio!==void 0)layoutNode.setAspectRatio(props.aspectRatio);else if(wasRemoved("aspectRatio"))layoutNode.setAspectRatio(NaN);let effectiveOverflow=props.overflow??(props.overflowX==="hidden"||props.overflowY==="hidden"?"hidden":void 0);if(effectiveOverflow!==void 0)if(effectiveOverflow==="hidden")layoutNode.setOverflow(c.OVERFLOW_HIDDEN);else if(effectiveOverflow==="scroll")layoutNode.setOverflow(c.OVERFLOW_SCROLL);else layoutNode.setOverflow(c.OVERFLOW_VISIBLE);else if(wasRemoved("overflow")||wasRemoved("overflowX")||wasRemoved("overflowY"))layoutNode.setOverflow(c.OVERFLOW_VISIBLE);if(props.borderStyle){if(props.borderTop!==!1)layoutNode.setBorder(c.EDGE_TOP,1);else layoutNode.setBorder(c.EDGE_TOP,0);if(props.borderBottom!==!1)layoutNode.setBorder(c.EDGE_BOTTOM,1);else layoutNode.setBorder(c.EDGE_BOTTOM,0);if(props.borderLeft!==!1)layoutNode.setBorder(c.EDGE_LEFT,1);else layoutNode.setBorder(c.EDGE_LEFT,0);if(props.borderRight!==!1)layoutNode.setBorder(c.EDGE_RIGHT,1);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=createLogger4("silvery:measure")});import{createContext as createContext3}from"react";import{DefaultEventPriority,DiscreteEventPriority,NoEventPriority}from"react-reconciler/constants.js";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){while(node&&!node.subtreeDirty)node.subtreeDirty=!0,node=node.parent}function markLayoutAncestorDirty(node){if(node.layoutNode)return;let ancestor=node.parent;while(ancestor&&!ancestor.layoutNode)ancestor=ancestor.parent;if(ancestor?.layoutNode)ancestor.contentDirty=!0,ancestor.stylePropsDirty=!0,ancestor.layoutDirty=!0,ancestor.layoutNode.markDirty()}function runWithDiscreteEvent(fn){let prev=currentUpdatePriority;currentUpdatePriority=DiscreteEventPriority;try{fn()}finally{currentUpdatePriority=prev}}var onNodeRemovedCallback=null,hasWarnedBoxInsideText=!1,inkStrictValidation=!1,currentUpdatePriority,hostConfig;var init_host_config=__esm(()=>{init_helpers();init_nodes();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,console.warn("Warning: <Box> cannot be nested inside <Text>. This produces undefined layout behavior.")}if(type==="silvery-text"&&hostContext.isInsideText)return createVirtualTextNode(props);return createNode(type,props)},createTextInstance(text,_rootContainer,hostContext){if(inkStrictValidation&&!hostContext.isInsideText&&text.trim().length>0)throw Error(`Text string "${text}" must be rendered inside <Text> component`);return{type:"silvery-text",props:{children:text},children:[],parent:null,layoutNode:null,contentRect:null,screenRect:null,renderRect:null,prevLayout:null,prevScreenRect:null,prevRenderRect:null,layoutChangedThisFrame:!1,layoutDirty:!1,contentDirty:!0,stylePropsDirty:!0,bgDirty:!0,subtreeDirty:!0,childrenDirty:!1,layoutSubscribers:new Set,textContent:text,isRawText:!0}},appendChild(parentInstance,child){let existingIndex=parentInstance.children.indexOf(child);if(existingIndex!==-1){if(parentInstance.children.splice(existingIndex,1),parentInstance.layoutNode&&child.layoutNode)parentInstance.layoutNode.removeChild(child.layoutNode)}if(child.parent=parentInstance,parentInstance.children.push(child),parentInstance.layoutNode&&child.layoutNode){let layoutIndex=parentInstance.children.filter((c)=>c.layoutNode!==null).length-1;parentInstance.layoutNode.insertChild(child.layoutNode,layoutIndex)}parentInstance.childrenDirty=!0,parentInstance.contentDirty=!0,parentInstance.layoutDirty=!0,parentInstance.layoutNode?.markDirty(),markLayoutAncestorDirty(parentInstance),markSubtreeDirty(parentInstance)},appendInitialChild(parentInstance,child){if(child.parent=parentInstance,parentInstance.children.push(child),parentInstance.layoutNode&&child.layoutNode){let layoutIndex=parentInstance.children.filter((c)=>c.layoutNode!==null).length-1;parentInstance.layoutNode.insertChild(child.layoutNode,layoutIndex)}},appendChildToContainer(container,child){let existingIndex=container.root.children.indexOf(child);if(existingIndex!==-1){if(container.root.children.splice(existingIndex,1),container.root.layoutNode&&child.layoutNode)container.root.layoutNode.removeChild(child.layoutNode)}if(child.parent=container.root,container.root.children.push(child),container.root.layoutNode&&child.layoutNode){let layoutIndex=container.root.children.filter((c)=>c.layoutNode!==null).length-1;container.root.layoutNode.insertChild(child.layoutNode,layoutIndex)}container.root.childrenDirty=!0,container.root.contentDirty=!0,container.root.layoutDirty=!0,container.root.layoutNode?.markDirty(),markSubtreeDirty(container.root)},removeChild(parentInstance,child){let index=parentInstance.children.indexOf(child);if(index!==-1){if(onNodeRemovedCallback?.(child),parentInstance.children.splice(index,1),parentInstance.layoutNode&&child.layoutNode)parentInstance.layoutNode.removeChild(child.layoutNode),child.layoutNode.free();child.parent=null,parentInstance.childrenDirty=!0,parentInstance.contentDirty=!0,parentInstance.layoutDirty=!0,parentInstance.layoutNode?.markDirty(),markLayoutAncestorDirty(parentInstance),markSubtreeDirty(parentInstance)}},removeChildFromContainer(container,child){let index=container.root.children.indexOf(child);if(index!==-1){if(onNodeRemovedCallback?.(child),container.root.children.splice(index,1),container.root.layoutNode&&child.layoutNode)container.root.layoutNode.removeChild(child.layoutNode),child.layoutNode.free();child.parent=null,container.root.childrenDirty=!0,container.root.contentDirty=!0,container.root.layoutDirty=!0,container.root.layoutNode?.markDirty(),markSubtreeDirty(container.root)}},insertBefore(parentInstance,child,beforeChild){let existingIndex=parentInstance.children.indexOf(child);if(existingIndex!==-1){if(parentInstance.children.splice(existingIndex,1),parentInstance.layoutNode&&child.layoutNode)parentInstance.layoutNode.removeChild(child.layoutNode)}let beforeIndex=parentInstance.children.indexOf(beforeChild);if(beforeIndex!==-1){if(child.parent=parentInstance,parentInstance.children.splice(beforeIndex,0,child),parentInstance.layoutNode&&child.layoutNode){let layoutIndex=parentInstance.children.slice(0,beforeIndex).filter((c)=>c.layoutNode!==null).length;parentInstance.layoutNode.insertChild(child.layoutNode,layoutIndex)}parentInstance.childrenDirty=!0,parentInstance.contentDirty=!0,parentInstance.layoutDirty=!0,parentInstance.layoutNode?.markDirty(),markLayoutAncestorDirty(parentInstance),markSubtreeDirty(parentInstance)}},insertInContainerBefore(container,child,beforeChild){let existingIndex=container.root.children.indexOf(child);if(existingIndex!==-1){if(container.root.children.splice(existingIndex,1),container.root.layoutNode&&child.layoutNode)container.root.layoutNode.removeChild(child.layoutNode)}let beforeIndex=container.root.children.indexOf(beforeChild);if(beforeIndex!==-1){if(child.parent=container.root,container.root.children.splice(beforeIndex,0,child),container.root.layoutNode&&child.layoutNode){let layoutIndex=container.root.children.slice(0,beforeIndex).filter((c)=>c.layoutNode!==null).length;container.root.layoutNode.insertChild(child.layoutNode,layoutIndex)}container.root.childrenDirty=!0,container.root.contentDirty=!0,container.root.layoutDirty=!0,container.root.layoutNode?.markDirty(),markSubtreeDirty(container.root)}},prepareUpdate(_instance,_type,oldProps,newProps){return!propsEqual(oldProps,newProps)},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};if(propsEqual(oldProps,newProps)){instance.props=newProps;return}if(layoutPropsChanged(oldProps,newProps)){if(instance.layoutNode)applyBoxProps(instance.layoutNode,newProps,oldProps),instance.layoutNode.markDirty();instance.layoutDirty=!0}let contentChanged=contentPropsChanged(oldProps,newProps);if(contentChanged){if(instance.stylePropsDirty=!0,contentChanged==="text"){if(instance.contentDirty=!0,instance.layoutNode)instance.layoutNode.markDirty()}if(oldProps.backgroundColor!==newProps.backgroundColor)instance.bgDirty=!0;if(oldProps.borderStyle&&!newProps.borderStyle)instance.bgDirty=!0;if(oldProps.outlineStyle&&!newProps.outlineStyle)instance.bgDirty=!0;if(oldProps.theme!==newProps.theme)instance.bgDirty=!0}instance.props=newProps;let scrollToChanged=oldProps.scrollTo!==newProps.scrollTo,scrollOffsetChanged=oldProps.scrollOffset!==newProps.scrollOffset;if(instance.layoutDirty||contentChanged||scrollToChanged||scrollOffsetChanged)markLayoutAncestorDirty(instance),markSubtreeDirty(instance)},commitTextUpdate(textInstance,_oldText,newText){textInstance.textContent=newText,textInstance.props={children:newText},textInstance.contentDirty=!0,textInstance.stylePropsDirty=!0,markLayoutAncestorDirty(textInstance),markSubtreeDirty(textInstance)},finalizeInitialChildren(){return!1},prepareForCommit(){return null},resetAfterCommit(container){container.onRender()},getPublicInstance(instance){return instance},shouldSetTextContent(){return!1},clearContainer(container){for(let child of container.root.children)onNodeRemovedCallback?.(child);for(let child of container.root.children)if(container.root.layoutNode&&child.layoutNode)container.root.layoutNode.removeChild(child.layoutNode),child.layoutNode.free();container.root.children=[],container.root.childrenDirty=!0,container.root.contentDirty=!0,container.root.layoutDirty=!0,container.root.layoutNode?.markDirty(),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:createContext3(null),resetFormInstance(){},requestPostPaintCallback(){},shouldAttemptEagerTransition(){return!1},trackSchedulerEvent(){},resolveEventType(){return null},resolveEventTimeStamp(){return-1.1},preloadInstance(){return!0},startSuspendingCommit(){},suspendInstance(){},waitForCommitToBeReady(){return null},hideInstance(instance){if(instance.hidden=!0,instance.contentDirty=!0,instance.stylePropsDirty=!0,instance.layoutDirty=!0,instance.layoutNode)instance.layoutNode.markDirty();if(instance.parent)instance.parent.contentDirty=!0;markLayoutAncestorDirty(instance),markSubtreeDirty(instance)},unhideInstance(instance,_props){if(instance.hidden=!1,instance.contentDirty=!0,instance.stylePropsDirty=!0,instance.layoutDirty=!0,instance.layoutNode)instance.layoutNode.markDirty();if(instance.parent)instance.parent.contentDirty=!0;markLayoutAncestorDirty(instance),markSubtreeDirty(instance)},hideTextInstance(textInstance){if(textInstance.hidden=!0,textInstance.contentDirty=!0,textInstance.stylePropsDirty=!0,textInstance.parent)textInstance.parent.contentDirty=!0;markLayoutAncestorDirty(textInstance),markSubtreeDirty(textInstance)},unhideTextInstance(textInstance,_text){if(textInstance.hidden=!1,textInstance.contentDirty=!0,textInstance.stylePropsDirty=!0,textInstance.parent)textInstance.parent.contentDirty=!0;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 React6,{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=React6.createElement(TermContext.Provider,{value:mockTerm},React6.createElement(StdoutContext.Provider,{value:{stdout:mockStdout,write:()=>{}}},React6.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.contentRect){hasChildren=!0;let props=child.props,mb=props.marginBottom??props.marginY??props.margin??0,childBottom=child.contentRect.y+child.contentRect.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_ansi();init_buffer();init_context();init_pipeline2();init_reconciler();init_string_reconciler()});import{createContext as createContext4,useContext as useContext7,useMemo as useMemo8}from"react";import{jsxDEV as jsxDEV11}from"react/jsx-dev-runtime";function useScrollbackItem(){let ctx=useContext7(ScrollbackItemCtx);if(!ctx)throw Error("useScrollbackItem() must be used inside a ScrollbackList item");return ctx}function ScrollbackItemProvider({children,freeze,isFrozen,index,nearScrollback}){let value=useMemo8(()=>({freeze,isFrozen,index,nearScrollback}),[freeze,isFrozen,index,nearScrollback]);return jsxDEV11(ScrollbackItemCtx.Provider,{value,children},void 0,!1,void 0,this)}var ScrollbackItemCtx;var init_useScrollbackItem=__esm(()=>{ScrollbackItemCtx=createContext4(null)});import{memo,useCallback as useCallback6,useEffect as useEffect6,useLayoutEffect as useLayoutEffect3,useMemo as useMemo9,useRef as useRef7,useState as useState6}from"react";import{jsxDEV as jsxDEV12}from"react/jsx-dev-runtime";function getTermCols(){return process.stdout.columns??80}function ScrollbackView({items,children,renderItem,keyExtractor,isFrozen:isFrozenProp,footer,footerHeight:_footerHeight,maxHistory:_maxHistory=1e4,markers,width,stdout=process.stdout,onRecovery}){let[termWidth,setTermWidth]=useState6(getTermCols);useEffect6(()=>{if(width!==void 0)return;let stream=stdout;if(!stream?.on||!stream?.columns)return;let onResize=()=>setTermWidth(stream.columns??80);return stream.on("resize",onResize),()=>{stream.off?.("resize",onResize)}},[width,stdout]);let effectiveWidth=width??termWidth,outerNodeRef=useRef7(null),[layoutInfo,setLayoutInfo]=useState6(null),hPaddingRef=useRef7(0),prevLayoutInfoRef=useRef7(null);if(useLayoutEffect3(()=>{let node=outerNodeRef.current;if(!node)return;let update=()=>{let rect=node.contentRect;if(rect&&rect.width>0)setLayoutInfo((prev)=>{if(prev&&prev.width===rect.width&&prev.x===rect.x)return prev;return{width:rect.width,x:rect.x}})};return update(),node.layoutSubscribers.add(update),()=>{node.layoutSubscribers.delete(update)}},[]),layoutInfo!==prevLayoutInfoRef.current){if(prevLayoutInfoRef.current=layoutInfo,layoutInfo&&layoutInfo.width>0&&width===void 0){let padding=effectiveWidth-layoutInfo.width;if(padding>=0)hPaddingRef.current=padding}}let frozenWidth=width??Math.max(1,effectiveWidth-hPaddingRef.current),frozenLeftPad=layoutInfo?.x??0,render=renderItem??children;if(!render)throw Error("ScrollbackView requires either a `renderItem` prop or `children` render function");let[frozenKeys,setFrozenKeys]=useState6(()=>new Set),snapshotRef=useRef7(new Map),freezeCache=useRef7(new Map),getFreeze=useCallback6((key)=>{let fn=freezeCache.current.get(key);if(!fn)fn=(snapshot)=>{if(snapshot)snapshotRef.current.set(key,snapshot);setFrozenKeys((prev)=>{if(prev.has(key))return prev;let next=new Set(prev);return next.add(key),next})},freezeCache.current.set(key,fn);return fn},[]),frozenPredicate=useCallback6((item,index)=>{if(isFrozenProp?.(item,index))return!0;let key=keyExtractor(item,index);return frozenKeys.has(key)},[frozenKeys,keyExtractor,isFrozenProp]),renderFrozen=useCallback6((item,index)=>{let key=keyExtractor(item,index),snapshot=snapshotRef.current.get(key),noop=()=>{},inner=snapshot??render(item,index),element=jsxDEV12(ScrollbackItemProvider,{freeze:noop,isFrozen:!0,index,nearScrollback:!1,children:inner},void 0,!1,void 0,this);try{let text=renderStringSync(element,{width:frozenWidth,plain:!1});if(frozenLeftPad>0){let pad=" ".repeat(frozenLeftPad);text=text.split(`
75
+ `).map((line)=>pad+line).join(`
76
+ `)}return text}catch{return`[frozen item ${index}]`}},[render,keyExtractor,frozenWidth,frozenLeftPad]),frozenCount=useScrollback(items,{frozen:frozenPredicate,render:renderFrozen,stdout,markers,width:effectiveWidth});useEffect6(()=>{if(frozenCount>0)for(let i=0;i<frozenCount;i++){let key=keyExtractor(items[i],i);snapshotRef.current.delete(key)}},[frozenCount,items,keyExtractor]),useEffect6(()=>{if(frozenKeys.size===0)return;let currentKeys=new Set(items.map((item,i)=>keyExtractor(item,i))),hasStale=!1;for(let key of frozenKeys)if(!currentKeys.has(key)){hasStale=!0;break}if(hasStale){setFrozenKeys((prev)=>{let next=new Set;for(let key of prev)if(currentKeys.has(key))next.add(key);return next});for(let key of freezeCache.current.keys())if(!currentKeys.has(key))freezeCache.current.delete(key);onRecovery?.()}},[items,keyExtractor,frozenKeys,onRecovery]);let liveItems=useMemo9(()=>{let result=[];for(let i=frozenCount;i<items.length;i++){let key=keyExtractor(items[i],i);result.push({item:items[i],index:i,key})}return result},[items,frozenCount,keyExtractor]);return jsxDEV12("silvery-box",{ref:outerNodeRef,flexDirection:"column",flexGrow:1,children:[jsxDEV12("silvery-box",{flexDirection:"column",flexGrow:1,children:liveItems.map(({item,index,key})=>jsxDEV12(MemoItem,{item,index,freeze:getFreeze(key),renderFn:render},key,!1,void 0,this))},void 0,!1,void 0,this),footer!=null&&jsxDEV12("silvery-box",{flexDirection:"column",flexShrink:0,children:footer},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var MemoItem;var init_ScrollbackView=__esm(()=>{init_useScrollback();init_render_string();init_useScrollbackItem();MemoItem=memo(function({item,index,freeze,renderFn}){return jsxDEV12(ScrollbackItemProvider,{freeze,isFrozen:!1,index,nearScrollback:!1,children:renderFn(item,index)},void 0,!1,void 0,this)})});import{jsxDEV as jsxDEV13}from"react/jsx-dev-runtime";function ScrollbackList(props){return jsxDEV13(ScrollbackView,{...props},void 0,!1,void 0,this)}var init_ScrollbackList=__esm(()=>{init_ScrollbackView()});import{useState as useState7,useEffect as useEffect7}from"react";import{jsxDEV as jsxDEV14}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)}},[]),jsxDEV14(Box,{width:dims.width,height:dims.height,flexDirection,children},void 0,!1,void 0,this)}var init_Screen=__esm(()=>{init_Box()});import{forwardRef as forwardRef6,useCallback as useCallback7}from"react";import{jsxDEV as jsxDEV15}from"react/jsx-dev-runtime";function VirtualViewInner({items,height,estimateHeight,renderItem,scrollTo,overscan,maxRendered,scrollPadding,overflowIndicator,keyExtractor,width,gap,renderSeparator,onWheel,onEndReached,onEndReachedThreshold,listFooter},ref){let wrappedRenderItem=useCallback7((item,index,_meta)=>{return renderItem(item,index)},[renderItem]);return jsxDEV15(ListView,{ref,items,height,estimateHeight,renderItem:wrappedRenderItem,scrollTo,overscan,maxRendered,scrollPadding,overflowIndicator,getKey:keyExtractor,width,gap,renderSeparator,onWheel,onEndReached,onEndReachedThreshold,listFooter},void 0,!1,void 0,this)}var VirtualView;var init_VirtualView=__esm(()=>{init_ListView();VirtualView=forwardRef6(VirtualViewInner)});import{useContext as useContext8,useLayoutEffect as useLayoutEffect4,useReducer,useRef as useRef8}from"react";function useContentRect(){let node=useContext8(NodeContext),[,forceUpdate]=useReducer((x)=>x+1,0);return useLayoutEffect4(()=>{if(!node)return;let handleLayoutComplete=()=>{if(!rectEqual(node.prevLayout,node.contentRect))forceUpdate()};return node.layoutSubscribers.add(handleLayoutComplete),()=>{node.layoutSubscribers.delete(handleLayoutComplete)}},[node]),node?.contentRect??{x:0,y:0,width:0,height:0}}function useContentRectCallback(callback){let node=useContext8(NodeContext),callbackRef=useRef8(callback);callbackRef.current=callback,useLayoutEffect4(()=>{if(!node)return;let handleLayoutComplete=()=>{if(node.contentRect)callbackRef.current(node.contentRect)};if(node.layoutSubscribers.add(handleLayoutComplete),node.contentRect)callbackRef.current(node.contentRect);return()=>{node.layoutSubscribers.delete(handleLayoutComplete)}},[node])}function useScreenRect(){let node=useContext8(NodeContext),[,forceUpdate]=useReducer((x)=>x+1,0),prevScreenRectRef=useRef8(null);return useLayoutEffect4(()=>{if(!node)return;let handleLayoutComplete=()=>{if(!rectEqual(prevScreenRectRef.current,node.screenRect))prevScreenRectRef.current=node.screenRect,forceUpdate()};return node.layoutSubscribers.add(handleLayoutComplete),()=>{node.layoutSubscribers.delete(handleLayoutComplete)}},[node]),node?.screenRect??{x:0,y:0,width:0,height:0}}function useScreenRectCallback(callback){let node=useContext8(NodeContext),callbackRef=useRef8(callback);callbackRef.current=callback,useLayoutEffect4(()=>{if(!node)return;let handleLayoutComplete=()=>{if(node.screenRect)callbackRef.current(node.screenRect)};if(node.layoutSubscribers.add(handleLayoutComplete),node.screenRect)callbackRef.current(node.screenRect);return()=>{node.layoutSubscribers.delete(handleLayoutComplete)}},[node])}function useRenderRect(){let node=useContext8(NodeContext),[,forceUpdate]=useReducer((x)=>x+1,0),prevRenderRectRef=useRef8(null);return useLayoutEffect4(()=>{if(!node)return;let handleLayoutComplete=()=>{if(!rectEqual(prevRenderRectRef.current,node.renderRect))prevRenderRectRef.current=node.renderRect,forceUpdate()};return node.layoutSubscribers.add(handleLayoutComplete),()=>{node.layoutSubscribers.delete(handleLayoutComplete)}},[node]),node?.renderRect??{x:0,y:0,width:0,height:0}}function useRenderRectCallback(callback){let node=useContext8(NodeContext),callbackRef=useRef8(callback);callbackRef.current=callback,useLayoutEffect4(()=>{if(!node)return;let handleLayoutComplete=()=>{if(node.renderRect)callbackRef.current(node.renderRect)};if(node.layoutSubscribers.add(handleLayoutComplete),node.renderRect)callbackRef.current(node.renderRect);return()=>{node.layoutSubscribers.delete(handleLayoutComplete)}},[node])}var init_useLayout=__esm(()=>{init_context()});import{useContext as useContext9}from"react";function useRuntime(){return useContext9(RuntimeContext)}var init_useRuntime=__esm(()=>{init_context()});import{useContext as useContext10}from"react";function useApp(){let rt=useContext10(RuntimeContext);if(!rt)return staticResult;return{exit:rt.exit,pause:rt.pause,resume:rt.resume}}var staticResult;var init_useApp=__esm(()=>{init_context();staticResult={exit:()=>{}}});import{useContext as useContext11}from"react";function useStdout(){let context=useContext11(StdoutContext);if(!context)throw Error("useStdout must be used within an Silvery application");return{stdout:context.stdout,write:context.write}}var init_useStdout=__esm(()=>{init_context()});import{useContext as useContext12}from"react";function useStderr(){let context=useContext12(StderrContext);if(!context)return{stderr:process.stderr,write:(data)=>{process.stderr.write(data)}};return{stderr:context.stderr,write:context.write}}var init_useStderr=__esm(()=>{init_context()});import{useCallback as useCallback8,useContext as useContext13,useEffect as useEffect8,useMemo as useMemo10,useSyncExternalStore as useSyncExternalStore2}from"react";function useFocusable(){let fm=useContext13(FocusManagerContext),node=useContext13(NodeContext),testID=node?node.props.testID??null:null,autoFocus=node?!!node.props.autoFocus:!1,subscribe=useCallback8((listener)=>{if(!fm)return()=>{};return fm.subscribe(listener)},[fm]),getSnapshot=useCallback8(()=>{if(!fm)return null;return fm.getSnapshot()},[fm]),snapshot=useSyncExternalStore2(subscribe,getSnapshot,getSnapshot),focused=testID!==null&&snapshot!==null&&snapshot.activeId===testID,focusOrigin=focused?snapshot.focusOrigin:null;useEffect8(()=>{if(fm&&node&&autoFocus)fm.focus(node,"programmatic")},[fm,node,autoFocus]),useEffect8(()=>{return()=>{if(fm&&fm.activeElement===node)fm.blur()}},[fm,node]);let focus=useMemo10(()=>{return()=>{if(fm&&node)fm.focus(node,"programmatic")}},[fm,node]),blur=useMemo10(()=>{return()=>{if(fm&&focused)fm.blur()}},[fm,focused]);return{focused,focus,blur,focusOrigin}}var init_useFocusable=__esm(()=>{init_context()});import{useCallback as useCallback9,useContext as useContext14,useSyncExternalStore as useSyncExternalStore3}from"react";function useFocusWithin(testID){let fm=useContext14(FocusManagerContext),node=useContext14(NodeContext),subscribe=useCallback9((listener)=>{if(!fm)return()=>{};return fm.subscribe(listener)},[fm]),getSnapshot=useCallback9(()=>{if(!fm)return null;return fm.getSnapshot()},[fm]);if(!useSyncExternalStore3(subscribe,getSnapshot,getSnapshot)?.activeId)return!1;if(!node)return!1;let root=node;while(root.parent)root=root.parent;return fm.hasFocusWithin(root,testID)}var init_useFocusWithin=__esm(()=>{init_context()});import{useCallback as useCallback10,useContext as useContext15,useSyncExternalStore as useSyncExternalStore4}from"react";function useFocusManager(){let fm=useContext15(FocusManagerContext),node=useContext15(NodeContext),subscribe=useCallback10((listener)=>{if(!fm)return()=>{};return fm.subscribe(listener)},[fm]),getSnapshot=useCallback10(()=>{if(!fm)return null;return fm.getSnapshot()},[fm]),snapshot=useSyncExternalStore4(subscribe,getSnapshot,getSnapshot),getRoot=useCallback10(()=>{if(!node)return null;let root=node;while(root.parent)root=root.parent;return root},[node]),focus=useCallback10((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=useCallback10(()=>{if(!fm)return;let root=getRoot();if(root)fm.focusNext(root)},[fm,getRoot]),focusPrev=useCallback10(()=>{if(!fm)return;let root=getRoot();if(root)fm.focusPrev(root)},[fm,getRoot]),blur=useCallback10(()=>{if(!fm)return;fm.blur()},[fm]),activateScope=useCallback10((scopeId)=>{if(!fm)return;let root=getRoot();if(root)fm.activateScope(scopeId,root)},[fm,getRoot]),noOp=useCallback10(()=>{},[]);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}}var init_useFocusManager=__esm(()=>{init_context()});import{createContext as createContext5,useCallback as useCallback11,useContext as useContext16,useLayoutEffect as useLayoutEffect5,useMemo as useMemo11,useRef as useRef9}from"react";import{jsxDEV as jsxDEV16}from"react/jsx-dev-runtime";function InputLayerProvider({children}){let layersRef=useRef9([]),push=useCallback11((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=useCallback11((id)=>{layersRef.current=layersRef.current.filter((l)=>l.id!==id)},[]),dispatch=useCallback11((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=useMemo11(()=>({push,pop,dispatch}),[push,pop,dispatch]);return jsxDEV16(InputLayerContext.Provider,{value:contextValue,children},void 0,!1,void 0,this)}function useInputLayerContext(){let ctx=useContext16(InputLayerContext);if(!ctx)throw Error("useInputLayerContext must be used within an InputLayerProvider");return ctx}function useInputLayer(id,handler){let ctx=useContext16(InputLayerContext);useLayoutEffect5(()=>{if(!ctx)return;return ctx.push({id,handler}),()=>{ctx.pop(id)}},[ctx,id,handler])}var InputLayerContext;var init_InputLayerContext=__esm(()=>{init_useInput();InputLayerContext=createContext5(null)});var init_useInputLayer=__esm(()=>{init_InputLayerContext()});import{useState as useState8,useEffect as useEffect9}from"react";function useTerminalFocused(){let[focused,setFocused]=useState8(!0),rt=useRuntime();return useEffect9(()=>{if(!rt)return;return rt.on("focus",(isFocused)=>{setFocused(isFocused)})},[rt]),focused}var init_useTerminalFocused=__esm(()=>{init_useRuntime()});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{useEffect as useEffect10,useRef as useRef10}from"react";var init_useScrollRegion=()=>{};function createSelectionState(){return{range:null,selecting:!1}}function selectionUpdate(action,state){switch(action.type){case"start":{let pos={col:action.col,row:action.row};return[{range:{anchor:pos,head:pos},selecting:!0},[{type:"render"}]]}case"extend":{if(!state.selecting)return[state,[]];let head={col:action.col,row:action.row};return[{range:{anchor:state.range.anchor,head},selecting:!0},[{type:"render"}]]}case"finish":{if(!state.range)return[{...state,selecting:!1},[]];return[{range:state.range,selecting:!1},[]]}case"clear":{let hadRange=state.range!==null;return[createSelectionState(),hadRange?[{type:"render"}]:[]]}}}function normalizeRange(range){let{anchor,head}=range;if(anchor.row<head.row||anchor.row===head.row&&anchor.col<=head.col)return{startRow:anchor.row,startCol:anchor.col,endRow:head.row,endCol:head.col};return{startRow:head.row,startCol:head.col,endRow:anchor.row,endCol:anchor.col}}function extractText2(buffer,range){let{startRow,startCol,endRow,endCol}=normalizeRange(range),lines=[];for(let row=startRow;row<=endRow;row++){let colStart=row===startRow?startCol:0,colEnd=row===endRow?endCol:buffer.width-1,line="";for(let col=colStart;col<=colEnd;col++)line+=buffer.getCell(col,row).char;if(line=line.replace(/\s+$/,""),line.length>0)lines.push(line)}return lines.join(`
77
+ `)}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(OSC52_PREFIX);if(prefixIdx===-1)return null;let contentStart=prefixIdx+OSC52_PREFIX.length;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")}var OSC52_PREFIX="\x1B]52;c;";import React8,{createContext as createContext6,useCallback as useCallback12,useContext as useContext17,useState as useState9}from"react";function SelectionProvider({children}){let[state,setState]=useState9(createSelectionState),handleMouseDown=useCallback12((col,row)=>{setState((prev)=>selectionUpdate({type:"start",col,row},prev)[0])},[]),handleMouseMove=useCallback12((col,row)=>{setState((prev)=>selectionUpdate({type:"extend",col,row},prev)[0])},[]),handleMouseUp=useCallback12((col,row,buffer,stdout)=>{setState((prev)=>{let[next]=selectionUpdate({type:"finish"},prev);if(next.range){let text=extractText2(buffer,next.range);if(text.length>0)copyToClipboard(stdout,text)}return next})},[]),clearSelection=useCallback12(()=>{setState((prev)=>selectionUpdate({type:"clear"},prev)[0])},[]),value={selection:state.range,isSelecting:state.selecting,handleMouseDown,handleMouseMove,handleMouseUp,clearSelection};return React8.createElement(SelectionCtx.Provider,{value},children)}function useSelectionContext(){let ctx=useContext17(SelectionCtx);if(!ctx)throw Error("useSelectionContext must be used within a SelectionProvider");return ctx}var SelectionCtx,useSelection;var init_useSelection=__esm(()=>{SelectionCtx=createContext6(null);useSelection=useSelectionContext});function useListItem(){return useScrollbackItem()}var init_useListItem=__esm(()=>{init_useScrollbackItem();init_useScrollbackItem()});var init_hooks=__esm(()=>{init_useLayout();init_useInput();init_useRuntime();init_useApp();init_useStdout();init_useStderr();init_useFocusable();init_useFocusWithin();init_useFocusManager();init_useInputLayer();init_useTerminalFocused();init_useScrollRegion();init_useSelection();init_useListItem()});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}}if(input.length>=1&&input>=" ")return{value:value.slice(0,cursor)+input+value.slice(cursor),cursor:cursor+input.length,yankState:null};return null}var killRing;var init_readline_ops=__esm(()=>{killRing=[]});import{useCallback as useCallback13,useRef as useRef11,useState as useState10}from"react";function useReadline({initialValue="",onChange,isActive=!0,handleEnter=!1,handleEscape=!1,handleVerticalArrows=!1,onEOF,onSubmit}={}){let[state,setState]=useState10({value:initialValue,cursor:initialValue.length}),stateRef=useRef11({value:initialValue,cursor:initialValue.length});stateRef.current=state;let yankStateRef=useRef11(null),applyResult=useCallback13((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=useCallback13(()=>{let next={value:"",cursor:0};stateRef.current=next,setState(next),onChange?.(""),yankStateRef.current=null},[onChange]),setValue=useCallback13((value)=>{let next={value,cursor:value.length};stateRef.current=next,setState(next),onChange?.(value),yankStateRef.current=null},[onChange]),setValueWithCursor=useCallback13((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]}}var init_useReadline=__esm(()=>{init_hooks();init_readline_ops()});import React9,{createContext as createContext7,useCallback as useCallback14,useContext as useContext18,useEffect as useEffect11,useLayoutEffect as useLayoutEffect6,useRef as useRef12}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}function CursorProvider({store,children}){return React9.createElement(CursorCtx.Provider,{value:store},children)}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=useContext18(CursorCtx),set=store?store.setCursorState.bind(store):globalSetCursorState,get=store?store.accessors.getCursorState:globalGetCursorState,colRef=useRef12(col),rowRef=useRef12(row),visibleRef=useRef12(visible),shapeRef=useRef12(shape),setRef=useRef12(set),getRef=useRef12(get),lastRectRef=useRef12(null);colRef.current=col,rowRef.current=row,visibleRef.current=visible,shapeRef.current=shape,setRef.current=set,getRef.current=get,useScreenRectCallback(useCallback14((rect)=>{if(lastRectRef.current=rect,!visibleRef.current)return;setRef.current({x:rect.x+colRef.current,y:rect.y+rowRef.current,visible:!0,shape:shapeRef.current})},[])),useLayoutEffect6(()=>{let rect=lastRectRef.current;if(!rect||!visible)return;set({x:rect.x+col,y:rect.y+row,visible:!0,shape})},[col,row,shape,visible,set]),useEffect11(()=>{if(!visible){if(getRef.current())setRef.current(null)}return()=>{setRef.current(null)}},[visible])}function getCursorState(){return globalGetCursorState()}function subscribeCursor(listener){return globalSubscribeCursor(listener)}var CursorCtx,_globalCursorState=null,_globalCursorListeners;var init_useCursor=__esm(()=>{init_useLayout();CursorCtx=createContext7(null);_globalCursorListeners=new Set});import{useCallback as useCallback15,useImperativeHandle as useImperativeHandle4,forwardRef as forwardRef7,useState as useState11,useEffect as useEffect12,useRef as useRef13}from"react";import{jsxDEV as jsxDEV17,Fragment as Fragment2}from"react/jsx-dev-runtime";var TextInput;var init_TextInput=__esm(()=>{init_Box();init_Text();init_useReadline();init_useFocusable();init_useCursor();TextInput=forwardRef7(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=useRef13(!1),readline=useReadline({initialValue:isControlled?controlledValue??"":defaultValue,onChange:useCallback15((newValue)=>{internalChangeRef.current=!0,onChange?.(newValue)},[onChange]),isActive,handleEnter:!!onSubmit,onSubmit,onEOF}),[lastControlledValue,setLastControlledValue]=useState11(controlledValue);useEffect12(()=>{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"?jsxDEV17(Text,{underline:!0,children:displayAtCursor},void 0,!1,void 0,this):jsxDEV17(Text,{inverse:!0,children:displayAtCursor},void 0,!1,void 0,this);useCursor({col:prompt.length+displayBeforeCursor.length,row:0,visible:isActive});let handleMouseDown=useCallback15((e)=>{if(e.button!==0)return;let rect=e.currentTarget.screenRect;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=jsxDEV17(Text,{color,children:[prompt&&jsxDEV17(Text,{color:promptColor,children:prompt},void 0,!1,void 0,this),showPlaceholder?jsxDEV17(Fragment2,{children:[cursorStyle2==="underline"?jsxDEV17(Text,{underline:!0,dimColor:!0,children:placeholder[0]},void 0,!1,void 0,this):jsxDEV17(Text,{inverse:!0,dimColor:!0,children:placeholder[0]},void 0,!1,void 0,this),jsxDEV17(Text,{dimColor:!0,children:placeholder.slice(1)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):jsxDEV17(Fragment2,{children:[jsxDEV17(Text,{children:displayBeforeCursor},void 0,!1,void 0,this),cursorEl,jsxDEV17(Text,{children:displayAfterCursor},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(borderStyleProp)return jsxDEV17(Box,{focusable:!0,testID,flexDirection:"column",borderStyle:borderStyleProp,borderColor:isActive?focusBorderColor:borderColorProp,paddingX:1,onMouseDown:handleMouseDown,children:[inputContent,showUnderline&&jsxDEV17(Text,{dimColor:!0,children:"─".repeat(underlineWidth)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return jsxDEV17(Box,{focusable:!0,testID,flexDirection:"column",onMouseDown:handleMouseDown,children:[inputContent,showUnderline&&jsxDEV17(Text,{dimColor:!0,children:"─".repeat(underlineWidth)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)})});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(`
78
+ `),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}var init_text_cursor=__esm(()=>{init_unicode()});import{useCallback as useCallback16,useMemo as useMemo12,useRef as useRef14,useState as useState12}from"react";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]=useState12(defaultValue),[cursor,setCursor]=useState12(defaultValue.length),[scrollOffset,setScrollOffset]=useState12(0),stickyXRef=useRef14(null),yankStateRef=useRef14(null),[selectionAnchor,setSelectionAnchor]=useState12(null),selectionAnchorRef=useRef14(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=useRef14({value,cursor:clampedCursor});stateRef.current.value=value,stateRef.current.cursor=clampedCursor;let scrollRef=useRef14(scrollOffset);scrollRef.current=scrollOffset;let setCursorAndScroll=useCallback16((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=useCallback16((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=useCallback16(()=>{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=useCallback16(()=>{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=useCallback16((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=useCallback16((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=useMemo12(()=>getWrappedLines(value,wrapWidth),[value,wrapWidth]),{row:cursorRow,col:cursorCol}=useMemo12(()=>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(`
79
+ `);else updateValue(value2.slice(0,cursor2)+`
80
+ `+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=useCallback16(()=>{updateValue("",0),setScrollOffset(0),setSelectionAnchor(null)},[updateValue]),setValue=useCallback16((v)=>{updateValue(v,v.length),setSelectionAnchor(null)},[updateValue]),setCursorFn=useCallback16((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}}var init_useTextArea=__esm(()=>{init_useInput();init_readline_ops();init_text_cursor()});import{forwardRef as forwardRef8,useCallback as useCallback17,useImperativeHandle as useImperativeHandle5,useRef as useRef15}from"react";import{jsxDEV as jsxDEV18}from"react/jsx-dev-runtime";var TextArea;var init_TextArea=__esm(()=>{init_useLayout();init_useFocusable();init_useCursor();init_Box();init_Text();init_useTextArea();TextArea=forwardRef8(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}=useContentRect(),ta=useTextArea({value:controlledValue,defaultValue,onChange,onSubmit,submitKey,isActive,height,wrapWidth:width,scrollMargin,disabled,maxLength});useImperativeHandle5(ref,()=>({clear:ta.clear,getValue:()=>ta.value,setValue:ta.setValue,getSelection:ta.getSelection}));let wrappedLinesRef=useRef15(ta.wrappedLines);wrappedLinesRef.current=ta.wrappedLines;let scrollOffsetRef=useRef15(ta.scrollOffset);scrollOffsetRef.current=ta.scrollOffset;let handleMouseDown=useCallback17((e)=>{if(e.button!==0)return;let rect=e.currentTarget.screenRect;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]);useCursor({col:ta.cursorCol,row:ta.visibleCursorRow,visible:isActive&&!disabled&&!ta.selection});let showPlaceholder=!ta.value&&placeholder,borderProps=borderStyleProp?{borderStyle:borderStyleProp,borderColor:isActive?focusBorderColor:borderColorProp,paddingX:1}:{};if(showPlaceholder)return jsxDEV18(Box,{focusable:!0,testID,flexDirection:"column",height,justifyContent:"center",alignItems:"center",...borderProps,children:jsxDEV18(Text,{dimColor:!0,children:placeholder},void 0,!1,void 0,this)},void 0,!1,void 0,this);return jsxDEV18(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 jsxDEV18(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 jsxDEV18(Text,{children:[before,jsxDEV18(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 jsxDEV18(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 jsxDEV18(Text,{children:[beforeCursor,isActive?jsxDEV18(Text,{children:atCursor},void 0,!1,void 0,this):cursorStyle2==="block"?jsxDEV18(Text,{inverse:!0,children:atCursor},void 0,!1,void 0,this):jsxDEV18(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 useCallback18,useMemo as useMemo13,useRef as useRef16}from"react";import{jsxDEV as jsxDEV19}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=useRef16(0),effectiveWrapWidth=wrapWidth!=null&&wrapWidth>0?wrapWidth:1e4,clampedCursor=Math.min(Math.max(0,cursor),value.length),wrappedLines=useMemo13(()=>getWrappedLines(value,effectiveWrapWidth),[value,effectiveWrapWidth]),{row:cursorRow,col:cursorCol}=useMemo13(()=>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 jsxDEV19(Box,{flexDirection:"column",height,justifyContent:"center",alignItems:"center",children:jsxDEV19(Text,{dimColor:!0,children:placeholder},void 0,!1,void 0,this)},void 0,!1,void 0,this);return jsxDEV19(Box,{flexDirection:"column",children:jsxDEV19(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=useRef16(wrappedLines);wrappedLinesRef.current=wrappedLines;let scrollRefForClick=scrollRef,handleMouseDown=useCallback18((e)=>{if(!onCursorClick||e.button!==0)return;let rect=e.currentTarget.screenRect;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 jsxDEV19(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 jsxDEV19(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 jsxDEV19(Text,{children:[beforeCursorText,cursorStyle2==="block"?jsxDEV19(Text,{inverse:!0,children:atCursor},void 0,!1,void 0,this):jsxDEV19(Text,{underline:!0,children:atCursor},void 0,!1,void 0,this),afterCursorText]},absoluteRow,!0,void 0,this)})},currentScroll,!1,void 0,this)}var init_EditContextDisplay=__esm(()=>{init_text_cursor();init_Box();init_Text()});import{useCallback as useCallback19}from"react";import{jsxDEV as jsxDEV20}from"react/jsx-dev-runtime";function CursorLine({beforeCursor,afterCursor,color,showCursor=!0,cursorStyle:cursorStyle2="block",onCursorClick}){let totalLength=beforeCursor.length+afterCursor.length,handleMouseDown=useCallback19((e)=>{if(!onCursorClick||e.button!==0)return;let rect=e.currentTarget.screenRect;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 jsxDEV20(Text,{color,children:[beforeCursor,afterCursor]},void 0,!0,void 0,this);let cursorChar=afterCursor[0]??" ",rest=afterCursor.slice(1);return jsxDEV20(Text,{color,children:[beforeCursor,cursorStyle2==="block"?jsxDEV20(Text,{inverse:!0,children:cursorChar},void 0,!1,void 0,this):jsxDEV20(Text,{underline:!0,children:cursorChar},void 0,!1,void 0,this),rest]},void 0,!0,void 0,this)})();if(onCursorClick)return jsxDEV20(Box,{onMouseDown:handleMouseDown,children:textContent},void 0,!1,void 0,this);return textContent}var init_CursorLine=__esm(()=>{init_Box();init_Text()});import{jsxDEV as jsxDEV21,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 jsxDEV21(Text,{color,bold:!0,children:[before,jsxDEV21(Text,{dimColor:!0,bold:!1,children:"["},void 0,!1,void 0,this),jsxDEV21(Text,{bold:!0,children:matched},void 0,!1,void 0,this),jsxDEV21(Text,{dimColor:!0,bold:!1,children:"]"},void 0,!1,void 0,this),after]},void 0,!0,void 0,this)}return jsxDEV21(Text,{color,bold:!0,children:[jsxDEV21(Text,{dimColor:!0,bold:!1,children:"["},void 0,!1,void 0,this),jsxDEV21(Text,{bold:!0,children:hotkey},void 0,!1,void 0,this),jsxDEV21(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}){let effectiveTitleColor=titleColor??"$primary";return jsxDEV21(Box,{flexDirection:"column",width,height,borderStyle:"double",borderColor,backgroundColor:"$surface-bg",paddingX:2,paddingY:1,children:[title&&jsxDEV21(Box,{flexShrink:0,flexDirection:"column",children:[jsxDEV21(Box,{justifyContent:titleRight?"space-between":titleAlign,children:[hotkey?formatTitleWithHotkey(title,hotkey,effectiveTitleColor):jsxDEV21(Text,{color:effectiveTitleColor,bold:!0,children:title},void 0,!1,void 0,this),titleRight]},void 0,!0,void 0,this),jsxDEV21(Text,{children:" "},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jsxDEV21(Box,{flexDirection:"column",flexGrow:1,overflow:"hidden",children},void 0,!1,void 0,this),footer&&jsxDEV21(Fragment3,{children:[jsxDEV21(Text,{children:" "},void 0,!1,void 0,this),jsxDEV21(Box,{justifyContent:footerAlign,children:typeof footer==="string"?jsxDEV21(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)}var init_ModalDialog=__esm(()=>{init_Box();init_Text()});import React12 from"react";import{jsxDEV as jsxDEV22}from"react/jsx-dev-runtime";function PickerList({items,selectedIndex,renderItem,keyExtractor,emptyMessage="No items",maxVisible=10}){let clampedIndex=items.length>0?Math.min(selectedIndex,items.length-1):0,effectiveMaxVisible=Math.min(maxVisible,items.length),scrollOffset=items.length>effectiveMaxVisible?Math.max(0,Math.min(clampedIndex-Math.floor(effectiveMaxVisible/2),items.length-effectiveMaxVisible)):0,visibleItems=items.slice(scrollOffset,scrollOffset+effectiveMaxVisible);return jsxDEV22(Box,{flexDirection:"column",flexGrow:1,flexShrink:1,overflow:"hidden",children:items.length===0?jsxDEV22(Text,{dimColor:!0,children:emptyMessage},void 0,!1,void 0,this):visibleItems.map((item,i)=>{let isSelected=scrollOffset+i===clampedIndex;return jsxDEV22(React12.Fragment,{children:renderItem(item,isSelected)},keyExtractor(item),!1,void 0,this)})},void 0,!1,void 0,this)}var init_PickerList=__esm(()=>{init_Box();init_Text()});import{useCallback as useCallback20,useRef as useRef17,useState as useState13}from"react";import{jsxDEV as jsxDEV23}from"react/jsx-dev-runtime";function PickerDialog({title,placeholder,items,renderItem,keyExtractor,onSelect,onCancel,onChange,initialValue="",emptyMessage="No items",maxVisible=10,width,height,footer,prompt,promptColor,isActive=!0}){let[selectedIndex,setSelectedIndex]=useState13(0),onSelectRef=useRef17(onSelect);onSelectRef.current=onSelect;let onCancelRef=useRef17(onCancel);onCancelRef.current=onCancel;let itemsRef=useRef17(items);itemsRef.current=items;let selectedIndexRef=useRef17(selectedIndex);selectedIndexRef.current=selectedIndex;let readline=useReadline({initialValue,onChange:useCallback20((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 jsxDEV23(ModalDialog,{title,width,height,footer,children:[jsxDEV23(Box,{flexShrink:0,flexDirection:"column",children:[jsxDEV23(Box,{children:[prompt&&jsxDEV23(Text,{color:promptColor,children:prompt},void 0,!1,void 0,this),showPlaceholder?jsxDEV23(Text,{dimColor:!0,children:placeholder},void 0,!1,void 0,this):jsxDEV23(CursorLine,{beforeCursor:readline.beforeCursor,afterCursor:readline.afterCursor,showCursor:isActive},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jsxDEV23(Text,{dimColor:!0,children:"─".repeat(40)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jsxDEV23(PickerList,{items,selectedIndex:clampedIndex,renderItem,keyExtractor,emptyMessage,maxVisible},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var init_PickerDialog=__esm(()=>{init_useInput();init_Box();init_Text();init_CursorLine();init_ModalDialog();init_PickerList();init_useReadline()});import{jsxDEV as jsxDEV24}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}),jsxDEV24(Box,{focusable:!0,...rest,children:[jsxDEV24(Text,{inverse:active,children:value?"[x]":"[ ]"},void 0,!1,void 0,this),label&&jsxDEV24(Text,{children:[" ",label]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var init_Toggle=__esm(()=>{init_useFocusable();init_useInput();init_Box();init_Text()});import{jsxDEV as jsxDEV25}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}),jsxDEV25(Box,{focusable:!0,...rest,children:jsxDEV25(Text,{color,inverse:active,children:["[ ",label," ]"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}var init_Button=__esm(()=>{init_useFocusable();init_useInput();init_Box();init_Text()});import{useEffect as useEffect13,useState as useState14}from"react";import{jsxDEV as jsxDEV26}from"react/jsx-dev-runtime";function Spinner({type="dots",label,interval=80,...rest}){let[frameIndex,setFrameIndex]=useState14(0),frames=FRAMES[type];useEffect13(()=>{let timer=setInterval(()=>{setFrameIndex((prev)=>(prev+1)%frames.length)},interval);return()=>clearInterval(timer)},[frames.length,interval]);let frame=frames[frameIndex%frames.length];return jsxDEV26(Text,{...rest,children:[frame,label?` ${label}`:""]},void 0,!0,void 0,this)}var FRAMES;var init_Spinner=__esm(()=>{init_Text();FRAMES={dots:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],line:["|","/","—","\\"],arc:["◜","◠","◝","◞","◡","◟"],bounce:["⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"]}});import{useEffect as useEffect14,useState as useState15}from"react";import{jsxDEV as jsxDEV27}from"react/jsx-dev-runtime";function ProgressBar({value,width:widthProp,fillChar=DEFAULT_FILL,emptyChar=DEFAULT_EMPTY,showPercentage,label,color}){let{width:contentWidth}=useContentRect(),[bouncePos,setBouncePos]=useState15(0),[bounceDir,setBounceDir]=useState15(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);useEffect14(()=>{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 jsxDEV27(Box,{children:[label&&jsxDEV27(Text,{children:[label," "]},void 0,!0,void 0,this),jsxDEV27(Text,{color,children:filledPart},void 0,!1,void 0,this),jsxDEV27(Text,{dimColor:!0,children:emptyPart},void 0,!1,void 0,this),showPct&&jsxDEV27(Text,{children:[" ",pct,"%"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var DEFAULT_FILL="█",DEFAULT_EMPTY="░",DEFAULT_WIDTH=30,INDETERMINATE_BLOCK_SIZE=4,INDETERMINATE_INTERVAL=100;var init_ProgressBar=__esm(()=>{init_useLayout();init_Box();init_Text()});import{useCallback as useCallback21,useState as useState16}from"react";import{jsxDEV as jsxDEV28}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 findLastEnabled(items){for(let i=items.length-1;i>=0;i--)if(!items[i].disabled)return i;return 0}function SelectList({items,highlightedIndex:controlledIndex,onHighlight,onSelect,initialIndex,maxVisible,isActive=!0}){let isControlled=controlledIndex!==void 0,[uncontrolledIndex,setUncontrolledIndex]=useState16(initialIndex??findFirstEnabled(items)),currentIndex=isControlled?controlledIndex:uncontrolledIndex,setIndex=useCallback21((index)=>{if(!isControlled)setUncontrolledIndex(index);onHighlight?.(index)},[isControlled,onHighlight]);useInput((input,key)=>{if(items.length===0)return;if(key.upArrow||input==="k"){setIndex(findNextEnabled(items,currentIndex,-1));return}if(key.downArrow||input==="j"){setIndex(findNextEnabled(items,currentIndex,1));return}if(key.return){let item=items[currentIndex];if(item&&!item.disabled)onSelect?.(item,currentIndex);return}if(key.ctrl&&input==="a"){setIndex(findFirstEnabled(items));return}if(key.ctrl&&input==="e"){setIndex(findLastEnabled(items));return}},{isActive});let showAll=!maxVisible||items.length<=maxVisible,startIdx=0,visibleItems=items;if(!showAll){let half=Math.floor(maxVisible/2);startIdx=Math.max(0,Math.min(currentIndex-half,items.length-maxVisible)),visibleItems=items.slice(startIdx,startIdx+maxVisible)}return jsxDEV28(Box,{flexDirection:"column",children:visibleItems.map((item,i)=>{let isHighlighted=(showAll?i:startIdx+i)===currentIndex;return jsxDEV28(Text,{inverse:isHighlighted,dimColor:item.disabled,children:[isHighlighted?"▸ ":" ",item.label]},item.value,!0,void 0,this)})},void 0,!1,void 0,this)}var init_SelectList=__esm(()=>{init_useInput();init_Box();init_Text()});import{jsxDEV as jsxDEV29,Fragment as Fragment4}from"react/jsx-dev-runtime";function getCellValue(row,col,colIndex){if(Array.isArray(row)){let val=row[colIndex];return val==null?"":String(val)}if(col.key){let val=row[col.key];return val==null?"":String(val)}return""}function alignText(text,width,align="left"){if(text.length>=width)return text.slice(0,width);let pad=width-text.length;switch(align){case"right":return" ".repeat(pad)+text;case"center":{let leftPad=Math.floor(pad/2),rightPad=pad-leftPad;return" ".repeat(leftPad)+text+" ".repeat(rightPad)}default:return text+" ".repeat(pad)}}function Table({columns,data,showHeader=!0,separator=" │ ",headerBold=!0}){let colWidths=columns.map((col,colIndex)=>{if(col.width)return col.width;let maxWidth=col.header.length;for(let row of data){let cellText=getCellValue(row,col,colIndex);maxWidth=Math.max(maxWidth,cellText.length)}return maxWidth}),headerLine=columns.map((col,i)=>alignText(col.header,colWidths[i],col.align)).join(separator),separatorLine=colWidths.map((w)=>"─".repeat(w)).join(separator.replace(/[^│]/g,"─").replace(/│/g,"┼")),dataRows=data.map((row)=>{return columns.map((col,i)=>{let value=getCellValue(row,col,i);return alignText(value,colWidths[i],col.align)}).join(separator)});return jsxDEV29(Box,{flexDirection:"column",children:[showHeader&&jsxDEV29(Fragment4,{children:[jsxDEV29(Text,{bold:headerBold,dimColor:!0,children:headerLine},void 0,!1,void 0,this),jsxDEV29(Text,{dimColor:!0,children:separatorLine},void 0,!1,void 0,this)]},void 0,!0,void 0,this),dataRows.map((row,i)=>jsxDEV29(Text,{children:row},i,!1,void 0,this))]},void 0,!0,void 0,this)}var init_Table=__esm(()=>{init_Box();init_Text()});import{jsxDEV as jsxDEV30}from"react/jsx-dev-runtime";function Badge({label,variant="default",color,...rest}){let resolvedColor=color??VARIANT_COLORS[variant];return jsxDEV30(Text,{color:resolvedColor,bold:!0,...rest,children:[" ",label," "]},void 0,!0,void 0,this)}var VARIANT_COLORS;var init_Badge=__esm(()=>{init_Text();VARIANT_COLORS={default:"$fg",primary:"$primary",success:"$success",warning:"$warning",error:"$error"}});import{jsxDEV as jsxDEV31}from"react/jsx-dev-runtime";function Divider({char=DEFAULT_CHAR,title,width:widthProp}){let{width:contentWidth}=useContentRect(),totalWidth=widthProp??(contentWidth>0?contentWidth:DEFAULT_WIDTH2);if(!title)return jsxDEV31(Box,{children:jsxDEV31(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 jsxDEV31(Box,{children:[jsxDEV31(Text,{dimColor:!0,children:char.repeat(leftLen)},void 0,!1,void 0,this),jsxDEV31(Text,{bold:!0,children:titleWithPad},void 0,!1,void 0,this),jsxDEV31(Text,{dimColor:!0,children:char.repeat(rightLen)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var DEFAULT_CHAR="─",DEFAULT_WIDTH2=40;var init_Divider=__esm(()=>{init_useLayout();init_Box();init_Text()});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},[]]}}import React17,{createContext as createContext8,useCallback as useCallback22,useContext as useContext19,useMemo as useMemo14,useState as useState17}from"react";function SearchProvider({children}){let[state,setState]=useState17(createSearchState),[activeSurfaceId,setActiveSurfaceId]=useState17(null),registry=useSurfaceRegistry(),getSearchFn=useCallback22(()=>{let surface=activeSurfaceId?registry.getSurface(activeSurfaceId):registry.getFocusedSurface();if(!surface)return;return(query)=>surface.search(query)},[registry,activeSurfaceId]),handleEffects=useCallback22((effects)=>{let surface=activeSurfaceId?registry.getSurface(activeSurfaceId):registry.getFocusedSurface();if(!surface)return;for(let eff of effects)if(eff.type==="scrollTo"&&eff.row!==void 0)surface.reveal(eff.row)},[registry,activeSurfaceId]),open=useCallback22(()=>{let surface=registry.getFocusedSurface();if(surface)setActiveSurfaceId(surface.id);setState((prev2)=>{let[next2]=searchUpdate({type:"open"},prev2);return next2})},[registry]),close=useCallback22(()=>{setActiveSurfaceId(null),setState((prev2)=>{let[next2]=searchUpdate({type:"close"},prev2);return next2})},[]),next=useCallback22(()=>{setState((prev2)=>{let searchFn=getSearchFn(),[next2,effects]=searchUpdate({type:"nextMatch"},prev2,searchFn);return handleEffects(effects),next2})},[getSearchFn,handleEffects]),prev=useCallback22(()=>{setState((prev2)=>{let searchFn=getSearchFn(),[next2,effects]=searchUpdate({type:"prevMatch"},prev2,searchFn);return handleEffects(effects),next2})},[getSearchFn,handleEffects]),input=useCallback22((char)=>{setState((prev2)=>{let searchFn=getSearchFn(),[next2,effects]=searchUpdate({type:"input",char},prev2,searchFn);return handleEffects(effects),next2})},[getSearchFn,handleEffects]),backspace=useCallback22(()=>{setState((prev2)=>{let searchFn=getSearchFn(),[next2,effects]=searchUpdate({type:"backspace"},prev2,searchFn);return handleEffects(effects),next2})},[getSearchFn,handleEffects]),cursorLeft2=useCallback22(()=>{setState((prev2)=>{let[next2]=searchUpdate({type:"cursorLeft"},prev2);return next2})},[]),cursorRight2=useCallback22(()=>{setState((prev2)=>{let[next2]=searchUpdate({type:"cursorRight"},prev2);return next2})},[]),value=useMemo14(()=>({isActive:state.active,query:state.query,matches:state.matches,currentMatch:state.currentMatch,cursorPosition:state.cursorPosition,open,close,next,prev,input,backspace,cursorLeft:cursorLeft2,cursorRight:cursorRight2}),[state,open,close,next,prev,input,backspace,cursorLeft2,cursorRight2]);return React17.createElement(SearchContext.Provider,{value},React17.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){ctx.backspace();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=useContext19(SearchContext);if(!ctx)throw Error("useSearch must be used within a SearchProvider");return ctx}var SearchContext;var init_SearchProvider=__esm(()=>{init_useInput();init_SurfaceRegistry();SearchContext=createContext8(null)});import React18 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 React18.createElement(Box,{flexDirection:"row"},React18.createElement(Text,{inverse:!0},` / ${query} ${matchInfo} `))}var init_SearchBar=__esm(()=>{init_src3();init_SearchProvider()});import{createContext as createContext9,useContext as useContext20,Children as Children2,cloneElement as cloneElement2,isValidElement as isValidElement2}from"react";import{jsxDEV as jsxDEV32}from"react/jsx-dev-runtime";function H1({children,color,...rest}){return jsxDEV32(Text,{bold:!0,color:color??"$primary",...rest,children},void 0,!1,void 0,this)}function H2({children,color,...rest}){return jsxDEV32(Text,{bold:!0,color:color??"$accent",...rest,children},void 0,!1,void 0,this)}function H3({children,color,...rest}){return jsxDEV32(Text,{color:color??"$primary",...rest,children},void 0,!1,void 0,this)}function P({children,color,...rest}){return jsxDEV32(Text,{color,...rest,children},void 0,!1,void 0,this)}function Lead({children,color,...rest}){return jsxDEV32(Text,{italic:!0,color:color??"$muted",...rest,children},void 0,!1,void 0,this)}function Muted({children,color,...rest}){return jsxDEV32(Text,{color:color??"$muted",...rest,children},void 0,!1,void 0,this)}function Small({children,color,...rest}){return jsxDEV32(Text,{dimColor:!0,color:color??"$muted",...rest,children},void 0,!1,void 0,this)}function Strong({children,color,...rest}){return jsxDEV32(Text,{bold:!0,color,...rest,children},void 0,!1,void 0,this)}function Em({children,color,...rest}){return jsxDEV32(Text,{italic:!0,color,...rest,children},void 0,!1,void 0,this)}function Code({children,color,...rest}){return jsxDEV32(Text,{backgroundColor:"$mutedbg",color,...rest,children:` ${children} `},void 0,!1,void 0,this)}function Kbd({children,color,...rest}){return jsxDEV32(Text,{backgroundColor:"$mutedbg",bold:!0,color,...rest,children:` ${children} `},void 0,!1,void 0,this)}function Blockquote({children,color}){return jsxDEV32(Box,{children:[jsxDEV32(Text,{color:color??"$muted",children:"│ "},void 0,!1,void 0,this),jsxDEV32(Box,{flexShrink:1,children:jsxDEV32(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 jsxDEV32(Box,{children:[jsxDEV32(Text,{color:color??"$border",children:"│ "},void 0,!1,void 0,this),jsxDEV32(Box,{flexShrink:1,children:jsxDEV32(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 jsxDEV32(Text,{color:color??"$border",wrap:"truncate",...rest,children:"─".repeat(200)},void 0,!1,void 0,this)}function UL({children}){let parent=useContext20(ListContext);return jsxDEV32(ListContext.Provider,{value:{level:parent.level+1,ordered:!1},children:jsxDEV32(Box,{flexDirection:"column",children},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function OL({children}){let parent=useContext20(ListContext),index=0,numbered=Children2.map(children,(child)=>{if(isValidElement2(child)&&child.type===LI)return index++,cloneElement2(child,{_index:index});return child});return jsxDEV32(ListContext.Provider,{value:{level:parent.level+1,ordered:!0},children:jsxDEV32(Box,{flexDirection:"column",children:numbered},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function LI({children,color,_index}){let{level,ordered}=useContext20(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 jsxDEV32(Box,{children:[jsxDEV32(Text,{color:color??"$muted",children:[indent,marker]},void 0,!0,void 0,this),jsxDEV32(Box,{flexShrink:1,children:jsxDEV32(Text,{color,children},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var ListContext,BULLETS;var init_Typography=__esm(()=>{init_Box();init_Text();ListContext=createContext9({level:0,ordered:!1});BULLETS=["•","◦","▸","-"]});import{jsxDEV as jsxDEV33}from"react/jsx-dev-runtime";function Form({onSubmit:_onSubmit,gap=1,children}){return jsxDEV33(Box,{flexDirection:"column",gap,children},void 0,!1,void 0,this)}function FormField({label,error,description,required,children}){return jsxDEV33(Box,{flexDirection:"column",children:[jsxDEV33(Text,{color:"$muted",bold:!0,children:[label,required&&jsxDEV33(Text,{color:"$error",children:" *"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),description&&jsxDEV33(Text,{color:"$disabledfg",children:description},void 0,!1,void 0,this),jsxDEV33(Box,{children},void 0,!1,void 0,this),error&&jsxDEV33(Text,{color:"$error",children:error},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var init_Form=__esm(()=>{init_Box();init_Text()});import{useCallback as useCallback23,useEffect as useEffect15,useRef as useRef18,useState as useState18}from"react";import{jsxDEV as jsxDEV34}from"react/jsx-dev-runtime";function useToast(){let[toasts,setToasts]=useState18([]),timersRef=useRef18(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 useEffect15(()=>{let timers=timersRef.current;return()=>{for(let timer of timers.values())clearTimeout(timer);timers.clear()}},[]),{toast,toasts,dismiss,dismissAll}}function ToastItem({toast}){let color=VARIANT_COLORS2[toast.variant],icon=VARIANT_ICONS[toast.variant];return jsxDEV34(Box,{borderStyle:"single",borderColor:"$border",paddingX:1,backgroundColor:"$surface-bg",children:[jsxDEV34(Text,{color,bold:!0,children:["[",icon,"]"]},void 0,!0,void 0,this),jsxDEV34(Text,{children:[" ",toast.title]},void 0,!0,void 0,this),toast.description&&jsxDEV34(Text,{color:"$muted",children:[" ",toast.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function ToastContainer({toasts,maxVisible=5}){let visible=toasts.slice(-maxVisible);return jsxDEV34(Box,{flexDirection:"column",children:visible.map((t)=>jsxDEV34(ToastItem,{toast:t},t.id,!1,void 0,this))},void 0,!1,void 0,this)}var DEFAULT_DURATION=3000,VARIANT_COLORS2,VARIANT_ICONS,nextToastId=0;var init_Toast=__esm(()=>{init_Box();init_Text();VARIANT_COLORS2={default:"$fg",success:"$success",error:"$error",warning:"$warning",info:"$info"},VARIANT_ICONS={default:"i",success:"+",error:"x",warning:"!",info:"i"}});import{useCallback as useCallback24,useMemo as useMemo15,useState as useState19}from"react";import{jsxDEV as jsxDEV35}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]=useState19(""),[selectedIndex,setSelectedIndex]=useState19(0),filtered=useMemo15(()=>{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}),jsxDEV35(Box,{flexDirection:"column",borderStyle:"single",borderColor:"$border",backgroundColor:"$surface-bg",paddingX:1,children:[jsxDEV35(Box,{children:[jsxDEV35(Text,{color:"$primary",bold:!0,children:[">"," "]},void 0,!0,void 0,this),jsxDEV35(Text,{children:query||jsxDEV35(Text,{color:"$disabledfg",children:placeholder},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jsxDEV35(Box,{children:jsxDEV35(Text,{color:"$border",children:"─".repeat(30)},void 0,!1,void 0,this)},void 0,!1,void 0,this),visible.length===0?jsxDEV35(Text,{color:"$disabledfg",children:"No matching commands"},void 0,!1,void 0,this):visible.map((cmd,i)=>{let isSelected=i===selectedIndex;return jsxDEV35(Box,{gap:1,children:[jsxDEV35(Text,{inverse:isSelected,color:isSelected?"$primary":"$fg",children:[isSelected?">":" "," ",cmd.name]},void 0,!0,void 0,this),cmd.description&&jsxDEV35(Text,{color:"$muted",children:cmd.description},void 0,!1,void 0,this),cmd.shortcut&&jsxDEV35(Text,{color:"$disabledfg",bold:!0,children:cmd.shortcut},void 0,!1,void 0,this)]},cmd.name,!0,void 0,this)}),filtered.length>maxVisible&&jsxDEV35(Text,{color:"$disabledfg",children:[filtered.length-maxVisible," more..."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var init_CommandPalette=__esm(()=>{init_useInput();init_Box();init_Text()});import{useCallback as useCallback25,useState as useState20}from"react";import{jsxDEV as jsxDEV36}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&&node.children.length>0&&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}){let isControlled=controlledExpanded!==void 0,[uncontrolledExpanded,setUncontrolledExpanded]=useState20(()=>defaultExpanded?collectAllIds(data):new Set),expanded=isControlled?controlledExpanded:uncontrolledExpanded,[cursorIndex,setCursorIndex]=useState20(0),flatItems=flattenTree(data,expanded),toggleNode=useCallback25((nodeId)=>{let isExpanded=expanded.has(nodeId);if(!isControlled)setUncontrolledExpanded((prev)=>{let next=new Set(prev);if(isExpanded)next.delete(nodeId);else next.add(nodeId);return next});onToggle?.(nodeId,!isExpanded)},[expanded,isControlled,onToggle]);if(useInput((input,key)=>{if(flatItems.length===0)return;if(key.upArrow||input==="k"){setCursorIndex((prev)=>Math.max(0,prev-1));return}if(key.downArrow||input==="j"){setCursorIndex((prev)=>Math.min(flatItems.length-1,prev+1));return}if(key.return||key.rightArrow){let item=flatItems[cursorIndex];if(item?.node?.children&&item.node.children.length>0){if(!expanded.has(item.node.id))toggleNode(item.node.id);else if(key.return)toggleNode(item.node.id)}return}if(key.leftArrow){let item=flatItems[cursorIndex];if(item&&expanded.has(item.node.id))toggleNode(item.node.id);return}},{isActive}),flatItems.length===0)return jsxDEV36(Box,{children:jsxDEV36(Text,{color:"$disabledfg",children:"No items"},void 0,!1,void 0,this)},void 0,!1,void 0,this);return jsxDEV36(Box,{flexDirection:"column",children:flatItems.map(({node,depth},i)=>{let isCursor=i===cursorIndex,hasChildren=node.children&&node.children.length>0,isExpanded=expanded.has(node.id),prefix=hasChildren?isExpanded?"v ":"> ":" ",padding=" ".repeat(depth*indent);return jsxDEV36(Text,{inverse:isCursor,children:[padding,jsxDEV36(Text,{color:hasChildren?"$primary":"$fg",children:prefix},void 0,!1,void 0,this),renderNode?renderNode(node,depth):jsxDEV36(Text,{children:node.label},void 0,!1,void 0,this)]},node.id,!0,void 0,this)})},void 0,!1,void 0,this)}var init_TreeView=__esm(()=>{init_useInput();init_Box();init_Text()});import React22 from"react";import{jsxDEV as jsxDEV37}from"react/jsx-dev-runtime";function Breadcrumb({items,separator="/"}){if(items.length===0)return jsxDEV37(Box,{},void 0,!1,void 0,this);return jsxDEV37(Box,{children:items.map((item,i)=>{let isLast=i===items.length-1;return jsxDEV37(React22.Fragment,{children:[i>0&&jsxDEV37(Text,{color:"$disabledfg",children:[" ",separator," "]},void 0,!0,void 0,this),jsxDEV37(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)}var init_Breadcrumb=__esm(()=>{init_Box();init_Text()});import React23,{createContext as createContext10,useCallback as useCallback26,useContext as useContext21,useState as useState21}from"react";import{jsxDEV as jsxDEV38}from"react/jsx-dev-runtime";function useTabsContext(){return useContext21(TabsContext)}function Tabs({defaultValue,value:controlledValue,onChange,isActive=!0,children}){let isControlled=controlledValue!==void 0,[uncontrolledValue,setUncontrolledValue]=useState21(defaultValue??""),[tabValues,setTabValues]=useState21([]),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}),jsxDEV38(TabsContext.Provider,{value:{activeValue,setActiveValue,tabValues,registerTab},children:jsxDEV38(Box,{flexDirection:"column",children},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function TabList({children}){return jsxDEV38(Box,{flexDirection:"row",gap:1,borderBottom:!0,borderColor:"$border",children},void 0,!1,void 0,this)}function Tab({value,children}){let{activeValue,registerTab}=useTabsContext(),isActive=activeValue===value;return React23.useEffect(()=>{registerTab(value)},[value,registerTab]),jsxDEV38(Box,{children:jsxDEV38(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 jsxDEV38(Box,{flexDirection:"column",children},void 0,!1,void 0,this)}var TabsContext;var init_Tabs=__esm(()=>{init_useInput();init_Box();init_Text();TabsContext=createContext10({activeValue:"",setActiveValue:()=>{},tabValues:[],registerTab:()=>{}})});import{jsxDEV as jsxDEV39}from"react/jsx-dev-runtime";function Tooltip({content,show=!1,children}){return jsxDEV39(Box,{flexDirection:"column",children:[children,show&&jsxDEV39(Box,{children:jsxDEV39(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)}var init_Tooltip=__esm(()=>{init_Box();init_Text()});import{jsxDEV as jsxDEV40}from"react/jsx-dev-runtime";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 jsxDEV40(Box,{children:jsxDEV40(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 jsxDEV40(Box,{flexDirection:"column",children:rows.map((i)=>jsxDEV40(Text,{color:"$muted",children:line},i,!1,void 0,this))},void 0,!1,void 0,this)}var DEFAULT_WIDTH3=20,DEFAULT_CHAR2="░";var init_Skeleton=__esm(()=>{init_Box();init_Text()});import{createContext as createContext11,useContext as useContext22,useMemo as useMemo16}from"react";import{createLogger as createLogger5}from"loggily";import{jsxDEV as jsxDEV41}from"react/jsx-dev-runtime";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}),log3.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);log3.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(),log3.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(`
81
+ `)}}}function PositionRegistryProvider({children}){let registry=useMemo16(()=>createPositionRegistry(),[]);return jsxDEV41(PositionRegistryContext.Provider,{value:registry,children},void 0,!1,void 0,this)}function usePositionRegistry(){return useContext22(PositionRegistryContext)}var log3,PositionRegistryContext;var init_usePositionRegistry=__esm(()=>{log3=createLogger5("silvery:position-registry");PositionRegistryContext=createContext11(null)});import{useEffect as useEffect16,useRef as useRef19}from"react";function useGridPosition(sectionIndex,itemIndex){let registry=usePositionRegistry(),sectionRef=useRef19(sectionIndex),itemRef=useRef19(itemIndex);sectionRef.current=sectionIndex,itemRef.current=itemIndex,useScreenRectCallback((rect)=>{registry?.register(sectionRef.current,itemRef.current,rect)}),useEffect16(()=>{return()=>{registry?.unregister(sectionRef.current,itemRef.current)}},[registry]),useEffect16(()=>{return()=>{registry?.unregister(sectionIndex,itemIndex)}},[registry,sectionIndex,itemIndex])}var init_useGridPosition=__esm(()=>{init_useLayout();init_usePositionRegistry()});import{jsxDEV as jsxDEV42}from"react/jsx-dev-runtime";function GridCell({sectionIndex,itemIndex,children}){return useGridPosition(sectionIndex,itemIndex),jsxDEV42(Box,{children},void 0,!1,void 0,this)}var init_GridCell=__esm(()=>{init_Box();init_useGridPosition()});var init_components=__esm(()=>{init_ListView();init_VirtualList();init_HorizontalVirtualList();init_SplitView();init_Fill();init_Link();init_ErrorBoundary();init_Console();init_ScrollbackList();init_Screen();init_ScrollbackView();init_VirtualView();init_TextInput();init_TextArea();init_useTextArea();init_EditContextDisplay();init_CursorLine();init_ModalDialog();init_PickerDialog();init_PickerList();init_Toggle();init_Button();init_useReadline();init_Spinner();init_ProgressBar();init_SelectList();init_Table();init_Badge();init_Divider();init_SearchBar();init_Typography();init_Form();init_Toast();init_CommandPalette();init_TreeView();init_Breadcrumb();init_Tabs();init_Tooltip();init_Skeleton();init_usePositionRegistry();init_useGridPosition();init_GridCell()});import{jsxDEV as jsxDEV43}from"react/jsx-dev-runtime";function Transform({transform,children}){if(children===void 0||children===null)return null;return jsxDEV43("silvery-text",{internal_transform:transform,children},void 0,!1,void 0,this)}var init_Transform=()=>{};import{jsxDEV as jsxDEV44}from"react/jsx-dev-runtime";function Newline({count=1}){return jsxDEV44("silvery-text",{children:`
82
+ `.repeat(count)},void 0,!1,void 0,this)}var init_Newline=()=>{};import{jsxDEV as jsxDEV45}from"react/jsx-dev-runtime";function Spacer(){return jsxDEV45("silvery-box",{flexGrow:1},void 0,!1,void 0,this)}var init_Spacer=()=>{};import{useContext as useContext23,useRef as useRef20}from"react";import{jsxDEV as jsxDEV46}from"react/jsx-dev-runtime";function Static({items,children,style}){let stdoutCtx=useContext23(StdoutContext),term2=useContext23(TermContext),useInlineScrollback=!!stdoutCtx?.promoteScrollback,renderedRef=useRef20([]),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)renderedRef.current.length=items.length;let frozenCount=useScrollback(items,{frozen:()=>useInlineScrollback,render:(_item,index)=>{let element=renderedRef.current[index];if(!element)return"";try{return renderStringSync(element,{width:term2?.cols??80,plain:!1})}catch{return`[static item ${index}]`}},width:useInlineScrollback?term2?.cols??80:void 0});if(useInlineScrollback){let liveElements=renderedRef.current.slice(frozenCount);if(liveElements.length===0)return jsxDEV46("silvery-box",{flexDirection:"column",...style},void 0,!1,void 0,this);return jsxDEV46("silvery-box",{flexDirection:"column",...style,children:liveElements},void 0,!1,void 0,this)}return jsxDEV46("silvery-box",{flexDirection:"column",...style,children:renderedRef.current},void 0,!1,void 0,this)}var init_Static=__esm(()=>{init_context();init_useScrollback();init_render_string()});import*as fs from"node:fs";import React24,{Component as Component2}from"react";function parseStackLine(line){let trimmed=line.trim();if(!trimmed.startsWith("at "))return null;let rest=trimmed.slice(3),match1=rest.match(/^(.+?)\s+\((.+?):(\d+):(\d+)\)$/);if(match1)return{function:match1[1],file:match1[2],line:Number(match1[3]),column:Number(match1[4])};let match2=rest.match(/^(.+?):(\d+):(\d+)$/);if(match2)return{file:match2[1],line:Number(match2[2]),column:Number(match2[3])};return null}function cleanupPath(filePath){if(!filePath)return filePath;let p=filePath,cwdPath=process.cwd();p=p.replace(/^file:\/\//,"");for(let prefix of[cwdPath,`/private${cwdPath}`])if(p.startsWith(`${prefix}/`)){p=p.slice(prefix.length+1);break}return p}function getCodeExcerpt(filePath,line){try{if(!fs.existsSync(filePath))return null;let lines=fs.readFileSync(filePath,"utf8").split(`
83
+ `),start=Math.max(0,line-4),end=Math.min(lines.length,line+3),result=[];for(let i=start;i<end;i++)result.push({line:i+1,value:(lines[i]??"").replace(/\t/g," ")});return result}catch{return null}}var SilveryErrorBoundary;var init_error_boundary=__esm(()=>{SilveryErrorBoundary=class SilveryErrorBoundary extends Component2{state={error:null};static getDerivedStateFromError(error){return{error}}componentDidCatch(error){this.props.onError?.(error)}render(){if(this.state.error){let err=this.state.error,stack=err.stack?err.stack.split(`
84
+ `).slice(1):[],origin=stack.length>0?parseStackLine(stack[0]):null,filePath=cleanupPath(origin?.file),excerpt=null,lineWidth=0;if(filePath&&origin?.line){if(excerpt=getCodeExcerpt(filePath,origin.line),excerpt)for(let{line}of excerpt)lineWidth=Math.max(lineWidth,String(line).length)}let children=[];if(children.push(React24.createElement("silvery-box",{key:"header"},React24.createElement("silvery-text",{backgroundColor:"red",color:"white"}," ERROR "),React24.createElement("silvery-text",{},` ${err.message}`))),filePath&&origin)children.push(React24.createElement("silvery-box",{key:"location",marginTop:1},React24.createElement("silvery-text",{dimColor:!0},`${filePath}:${origin.line}:${origin.column}`)));if(excerpt&&origin){let codeLines=excerpt.map(({line,value})=>{let lineNum=String(line).padStart(lineWidth," ");return React24.createElement("silvery-box",{key:`code-${line}`},React24.createElement("silvery-text",{dimColor:line!==origin.line,backgroundColor:line===origin.line?"red":void 0,color:line===origin.line?"white":void 0},`${lineNum}:`),React24.createElement("silvery-text",{backgroundColor:line===origin.line?"red":void 0,color:line===origin.line?"white":void 0},` ${value}`))});children.push(React24.createElement("silvery-box",{key:"code",marginTop:1,flexDirection:"column"},...codeLines))}if(stack.length>0){let stackLines=stack.map((line,i)=>{let parsed=parseStackLine(line);if(!parsed)return React24.createElement("silvery-box",{key:`stack-${i}`},React24.createElement("silvery-text",{dimColor:!0},`- ${line.trim()}`));let cleanFile=cleanupPath(parsed.file);return React24.createElement("silvery-box",{key:`stack-${i}`},React24.createElement("silvery-text",{dimColor:!0},"- "),React24.createElement("silvery-text",{dimColor:!0,bold:!0},parsed.function??""),React24.createElement("silvery-text",{dimColor:!0,color:"gray"},` (${cleanFile??""}:${parsed.line}:${parsed.column})`))});children.push(React24.createElement("silvery-box",{key:"stack",marginTop:1,flexDirection:"column"},...stackLines))}return React24.createElement("silvery-box",{flexDirection:"column",padding:1},...children)}return this.props.children}}});function encodeKittyImage(pngData,opts){let b64=pngData.toString("base64"),chunks=splitIntoChunks(b64,4096);if(chunks.length===0)return`\x1B_G${buildParams(opts,0)};\x1B\\`;if(chunks.length===1)return`\x1B_G${buildParams(opts,0)};${chunks[0]}\x1B\\`;let parts=[];parts.push(`\x1B_G${buildParams(opts,1)};${chunks[0]}\x1B\\`);for(let i=1;i<chunks.length-1;i++)parts.push(`\x1B_Gm=1;${chunks[i]}\x1B\\`);return parts.push(`\x1B_Gm=0;${chunks[chunks.length-1]}\x1B\\`),parts.join("")}function deleteKittyImage(id){return`\x1B_Ga=d,d=i,i=${id}\x1B\\`}function isKittyGraphicsSupported(){let term2=process.env.TERM??"",termProgram=process.env.TERM_PROGRAM??"";if(term2==="xterm-kitty"||termProgram==="kitty")return!0;if(termProgram==="WezTerm")return!0;if(termProgram==="ghostty")return!0;if(termProgram==="konsole")return!0;return!1}function buildParams(opts,more){let parts=["a=T","f=100",`m=${more}`];if(opts?.width!=null)parts.push(`s=${opts.width}`);if(opts?.height!=null)parts.push(`v=${opts.height}`);if(opts?.id!=null)parts.push(`i=${opts.id}`);return parts.join(",")}function splitIntoChunks(str,size){if(str.length===0)return[];let chunks=[];for(let i=0;i<str.length;i+=size)chunks.push(str.slice(i,i+size));return chunks}function encodeSixel(imageData){let{width,height,data}=imageData;if(width===0||height===0||data.length===0)return"\x1BPq\x1B\\";let palette=new Map,pixelColors=new Uint16Array(width*height),nextColorIndex=1;for(let y=0;y<height;y++)for(let x=0;x<width;x++){let offset=(y*width+x)*4,r=data[offset],g=data[offset+1],b=data[offset+2];if(data[offset+3]<128)continue;let qr=r>>2&63,qg=g>>2&63,qb=b>>2&63,key=`${qr},${qg},${qb}`,idx=palette.get(key);if(idx==null)if(nextColorIndex>=256)idx=1;else idx=nextColorIndex++,palette.set(key,idx);pixelColors[y*width+x]=idx}let parts=[];parts.push(`"1;1;${width};${height}`);for(let[key,idx]of palette){let[qr,qg,qb]=key.split(",").map(Number),rPct=Math.round(qr/63*100),gPct=Math.round(qg/63*100),bPct=Math.round(qb/63*100);parts.push(`#${idx};2;${rPct};${gPct};${bPct}`)}for(let bandY=0;bandY<height;bandY+=6){if(bandY>0)parts.push("-");let bandColors=new Set;for(let dy=0;dy<6&&bandY+dy<height;dy++)for(let x=0;x<width;x++){let ci=pixelColors[(bandY+dy)*width+x];if(ci>0)bandColors.add(ci)}let first=!0;for(let colorIdx of bandColors){if(!first)parts.push("$");first=!1,parts.push(`#${colorIdx}`);for(let x=0;x<width;x++){let sixelBits=0;for(let dy=0;dy<6;dy++){let y=bandY+dy;if(y<height&&pixelColors[y*width+x]===colorIdx)sixelBits|=1<<dy}parts.push(String.fromCharCode(sixelBits+63))}}}return`\x1BPq${parts.join("")}\x1B\\`}function isSixelSupported(){let term2=process.env.TERM??"",termProgram=process.env.TERM_PROGRAM??"";if(termProgram==="mlterm"||term2.startsWith("mlterm"))return!0;if(termProgram==="foot"||term2==="foot"||term2==="foot-extra")return!0;if(termProgram==="WezTerm")return!0;if(termProgram==="mintty")return!0;return!1}import{readFileSync as readFileSync2}from"node:fs";import{useContext as useContext24,useEffect as useEffect17,useMemo as useMemo17,useRef as useRef21}from"react";import{jsxDEV as jsxDEV47}from"react/jsx-dev-runtime";function detectProtocol(preferred){if(preferred==="kitty")return isKittyGraphicsSupported()?"kitty":null;if(preferred==="sixel")return isSixelSupported()?"sixel":null;if(isKittyGraphicsSupported())return"kitty";if(isSixelSupported())return"sixel";return null}function Image({src,width:requestedWidth,height:requestedHeight,fallback="[image]",protocol:preferredProtocol="auto"}){let contentRect=useContentRect(),stdoutCtx=useContext24(StdoutContext),imageIdRef=useRef21(null),pngData=useMemo17(()=>{if(Buffer.isBuffer(src))return src;try{return readFileSync2(src)}catch{return null}},[src]),effectiveWidth=requestedWidth??contentRect.width,effectiveHeight=requestedHeight??Math.max(1,Math.floor(effectiveWidth/2)),activeProtocol=useMemo17(()=>detectProtocol(preferredProtocol),[preferredProtocol]);if(activeProtocol==="kitty"&&imageIdRef.current==null)imageIdRef.current=nextImageId++;if(useEffect17(()=>{if(!pngData||!stdoutCtx||!activeProtocol)return;if(effectiveWidth<=0||effectiveHeight<=0)return;let{write}=stdoutCtx;if(activeProtocol==="kitty"){let seq=encodeKittyImage(pngData,{width:effectiveWidth,height:effectiveHeight,id:imageIdRef.current??void 0});write(seq)}},[pngData,stdoutCtx,activeProtocol,effectiveWidth,effectiveHeight]),useEffect17(()=>{let id=imageIdRef.current;if(activeProtocol!=="kitty"||id==null||!stdoutCtx)return;return()=>{stdoutCtx.write(deleteKittyImage(id))}},[activeProtocol,stdoutCtx]),!activeProtocol||!pngData)return jsxDEV47("silvery-box",{width:effectiveWidth,height:effectiveHeight,children:jsxDEV47("silvery-text",{children:fallback},void 0,!1,void 0,this)},void 0,!1,void 0,this);let spaceLine=" ".repeat(Math.max(0,effectiveWidth)),spaceContent=Array.from({length:Math.max(0,effectiveHeight)},()=>spaceLine).join(`
85
+ `);return jsxDEV47("silvery-box",{width:effectiveWidth,height:effectiveHeight,children:jsxDEV47("silvery-text",{children:spaceContent},void 0,!1,void 0,this)},void 0,!1,void 0,this)}var nextImageId=1;var init_Image=__esm(()=>{init_context();init_useLayout()});var init_image=__esm(()=>{init_Image()});function isFocusable(node){if(node.hidden)return!1;let props=node.props;return Boolean(props.focusable)&&props.display!=="none"}function isFocusScope(node){let props=node.props;return Boolean(props.focusScope)}function findFocusableAncestor(node){let current=node;while(current){if(isFocusable(current))return current;current=current.parent}return null}function getTabOrder2(root,scope){let result=[],walkRoot=scope??root;function walk(node){if(node.hidden)return;if(node.props.display==="none")return;if(node!==walkRoot&&isFocusScope(node)){if(isFocusable(node))result.push(node);return}if(isFocusable(node))result.push(node);for(let child of node.children)walk(child)}return walk(walkRoot),result}function findEnclosingScope(node){let current=node;while(current){if(isFocusScope(current)){let props=current.props;return typeof props.testID==="string"?props.testID:null}current=current.parent}return null}function findByTestID(root,testID){if(root.props.testID===testID)return root;for(let child of root.children){let found=findByTestID(child,testID);if(found)return found}return null}function rectCenter(rect){return{cx:rect.x+rect.width/2,cy:rect.y+rect.height/2}}function isInCone(source,candidate,direction){let dx=candidate.cx-source.cx,dy=candidate.cy-source.cy;switch(direction){case"up":if(dy>=0)return!1;return Math.abs(dx)<=Math.abs(dy);case"down":if(dy<=0)return!1;return Math.abs(dx)<=Math.abs(dy);case"left":if(dx>=0)return!1;return Math.abs(dy)<=Math.abs(dx);case"right":if(dx<=0)return!1;return Math.abs(dy)<=Math.abs(dx)}}function distance(a,b){let dx=a.cx-b.cx,dy=a.cy-b.cy;return Math.sqrt(dx*dx+dy*dy)}function findSpatialTarget(from,direction,candidates,layoutFn){let sourceRect=layoutFn(from);if(!sourceRect)return null;let source=rectCenter(sourceRect),best=null,bestDist=1/0;for(let candidate of candidates){if(candidate===from)continue;let candidateRect=layoutFn(candidate);if(!candidateRect)continue;let target=rectCenter(candidateRect);if(!isInCone(source,target,direction))continue;let dist=distance(source,target);if(dist<bestDist)bestDist=dist,best=candidate}return best}function getExplicitFocusLink(node,direction){let props=node.props,propName=`nextFocus${direction.charAt(0).toUpperCase()}${direction.slice(1)}`,value=props[propName];return typeof value==="string"?value:null}function createFocusManager(options){let onFocusChange=options?.onFocusChange,activeElement=null,activeId=null,previousElement=null,previousId=null,focusOrigin=null,scopeStack=[],scopeMemory={},activeScopeId=null,listeners=new Set,snapshot=null,notifyCount=0;function notify2(){snapshot=null,notifyCount++;for(let listener of listeners)listener()}function getTestID(node){let props=node.props;return typeof props.testID==="string"?props.testID:null}function focus(node,origin="programmatic"){if(activeElement===node){if(focusOrigin!==origin)focusOrigin=origin,notify2();return}let oldElement=activeElement;if(previousElement=activeElement,previousId=activeId,activeElement=node,activeId=getTestID(node),focusOrigin=origin,activeId&&scopeStack.length>0)scopeMemory[scopeStack[scopeStack.length-1]]=activeId;notify2(),onFocusChange?.(oldElement,node,origin)}function focusById(id,root,origin="programmatic"){let node=findByTestID(root,id);if(node){let focusable=findFocusableAncestor(node);if(focusable){focus(focusable,origin);return}}let oldElement=activeElement;previousElement=activeElement,previousId=activeId,activeElement=null,activeId=id,focusOrigin=origin,notify2(),onFocusChange?.(oldElement,null,origin)}function blur(){if(!activeElement&&!activeId)return;let oldElement=activeElement;previousElement=activeElement,previousId=activeId,activeElement=null,activeId=null,focusOrigin=null,notify2(),onFocusChange?.(oldElement,null,null)}function subtreeContains(subtreeRoot,target){if(subtreeRoot===target)return!0;for(let child of subtreeRoot.children)if(subtreeContains(child,target))return!0;return!1}function handleSubtreeRemoved(removedRoot){let changed=!1;if(activeElement&&subtreeContains(removedRoot,activeElement)){let oldElement=activeElement;previousElement=activeElement,previousId=activeId,activeElement=null,activeId=null,focusOrigin=null,changed=!0,onFocusChange?.(oldElement,null,null)}if(previousElement&&subtreeContains(removedRoot,previousElement))previousElement=null,previousId=null,changed=!0;if(changed)notify2()}function enterScope(scopeId){scopeStack.push(scopeId),notify2()}function exitScope(){if(scopeStack.pop()===void 0)return;notify2()}function activateScope(scopeId,root){if(activeScopeId&&activeId)scopeMemory[activeScopeId]=activeId;activeScopeId=scopeId;let countBefore=notifyCount,remembered=scopeMemory[scopeId];if(remembered)focusById(remembered,root,"programmatic");else{let scopeNode=findByTestID(root,scopeId);if(scopeNode){let order=getTabOrder2(root,scopeNode);if(order.length>0)focus(order[0],"programmatic")}}if(notifyCount===countBefore)notify2()}function getFocusPath(root){if(!activeElement)return[];let path=[],current=activeElement;while(current&&current!==root.parent){let id=getTestID(current);if(id)path.push(id);current=current.parent}return path}function hasFocusWithin(root,testID){if(!activeElement)return!1;let target=findByTestID(root,testID);if(!target)return!1;let current=activeElement;while(current){if(current===target)return!0;current=current.parent}return!1}function resolveScope(root,explicitScope){if(explicitScope)return explicitScope;if(scopeStack.length>0){let scopeId=scopeStack[scopeStack.length-1],scopeNode=findByTestID(root,scopeId);if(scopeNode)return scopeNode}return}function focusNext(root,scope){let effectiveScope=resolveScope(root,scope),order=getTabOrder2(root,effectiveScope);if(order.length===0)return;if(!activeElement){focus(order[0],"keyboard");return}let currentIndex=order.indexOf(activeElement),nextIndex=currentIndex===-1?0:(currentIndex+1)%order.length;focus(order[nextIndex],"keyboard")}function focusPrev(root,scope){let effectiveScope=resolveScope(root,scope),order=getTabOrder2(root,effectiveScope);if(order.length===0)return;if(!activeElement){focus(order[order.length-1],"keyboard");return}let currentIndex=order.indexOf(activeElement),prevIndex=currentIndex<=0?order.length-1:currentIndex-1;focus(order[prevIndex],"keyboard")}function focusDirection(root,direction,layoutFn){if(!activeElement)return;let explicitTarget=getExplicitFocusLink(activeElement,direction);if(explicitTarget){focusById(explicitTarget,root,"keyboard");return}let candidates=getTabOrder2(root),target=findSpatialTarget(activeElement,direction,candidates,layoutFn??((node)=>node.screenRect));if(target)focus(target,"keyboard")}function subscribe(listener){return listeners.add(listener),()=>{listeners.delete(listener)}}function getSnapshot(){if(!snapshot)snapshot={activeId,previousId,focusOrigin,scopeStack:[...scopeStack],activeScopeId};return snapshot}return{get activeElement(){return activeElement},get activeId(){return activeId},get previousElement(){return previousElement},get previousId(){return previousId},get focusOrigin(){return focusOrigin},get scopeStack(){return[...scopeStack]},get scopeMemory(){return scopeMemory},get activeScopeId(){return activeScopeId},focus,focusById,blur,handleSubtreeRemoved,enterScope,exitScope,activateScope,getFocusPath,hasFocusWithin,focusNext,focusPrev,focusDirection,subscribe,getSnapshot}}var init_focus_manager=()=>{};function getAncestorPath(node){let path=[],current=node;while(current)path.push(current),current=current.parent;return path}function pointInRect(x,y,rect){return x>=rect.x&&x<rect.x+rect.width&&y>=rect.y&&y<rect.y+rect.height}function createKeyEvent(input,key,target){let propagationStopped=!1,defaultPrevented=!1;return{key:input,input,ctrl:key.ctrl,meta:key.meta,shift:key.shift,super:key.super,hyper:key.hyper,eventType:key.eventType,target,currentTarget:target,nativeEvent:{input,key},get propagationStopped(){return propagationStopped},get defaultPrevented(){return defaultPrevented},stopPropagation(){propagationStopped=!0},preventDefault(){defaultPrevented=!0}}}function createFocusEvent(type,target,relatedTarget){let propagationStopped=!1;return{type,target,relatedTarget,currentTarget:target,get propagationStopped(){return propagationStopped},stopPropagation(){propagationStopped=!0}}}function dispatchKeyEvent(event,dispatch){let path=getAncestorPath(event.target),mutableEvent=event;for(let i=path.length-1;i>0;i--){if(event.propagationStopped)return;let node=path[i],handler=node.props.onKeyDownCapture;if(handler)mutableEvent.currentTarget=node,handler(event)}if(!event.propagationStopped){let target=path[0];mutableEvent.currentTarget=target;let handler=target.props.onKeyDown;if(handler)handler(event,dispatch)}for(let i=1;i<path.length;i++){if(event.propagationStopped)return;let node=path[i],handler=node.props.onKeyDown;if(handler)mutableEvent.currentTarget=node,handler(event,dispatch)}}function dispatchFocusEvent(event){let handlerProp=event.type==="focus"?"onFocus":"onBlur",path=getAncestorPath(event.target),mutableEvent=event;for(let node of path){if(event.propagationStopped)break;let handler=node.props[handlerProp];if(handler)mutableEvent.currentTarget=node,handler(event)}}var init_focus_events=()=>{};import{useCallback as useCallback27,useContext as useContext25,useRef as useRef22,useSyncExternalStore as useSyncExternalStore5}from"react";function shallow(a,b){if(Object.is(a,b))return!0;if(typeof a!=="object"||typeof b!=="object"||a===null||b===null)return!1;let keysA=Object.keys(a),keysB=Object.keys(b);if(keysA.length!==keysB.length)return!1;for(let key of keysA)if(!Object.is(a[key],b[key]))return!1;return!0}function useTerm(selector,equalityFn){let term2=useContext25(TermContext);if(!term2)throw Error("useTerm must be used within a render(element, term) context");if(!selector)return term2;return useTermSelector(term2,selector,equalityFn)}function useTermSelector(term2,selector,equalityFn){let prevRef=useRef22(void 0),isEqual=equalityFn??Object.is,subscribe=useCallback27((listener)=>term2.subscribe(listener),[term2]),getSnapshot=useCallback27(()=>{let next=selector(term2);if(prevRef.current!==void 0&&isEqual(prevRef.current,next))return prevRef.current;return prevRef.current=next,next},[term2,selector,isEqual]);return useSyncExternalStore5(subscribe,getSnapshot,getSnapshot)}var init_useTerm=__esm(()=>{init_context()});function useWindowSize(){return useTerm((t)=>{let s=t.getState();return{columns:s.cols,rows:s.rows}},shallow)}var init_useWindowSize=__esm(()=>{init_useTerm()});import React25,{createContext as createContext12,useContext as useContext26}from"react";function useTheme(){return useContext26(ThemeContext)}var ThemeContext;var init_ThemeContext=__esm(()=>{init_state();init_palettes();ThemeContext=createContext12(defaultDarkTheme)});import{jsxDEV as jsxDEV48}from"react/jsx-dev-runtime";function ThemeProvider({theme,children}){return jsxDEV48(ThemeContext.Provider,{value:theme,children},void 0,!1,void 0,this)}var init_ThemeProvider=__esm(()=>{init_ThemeContext()});var init_types=()=>{};function generateTheme(primary,dark){return{name:`${dark?"dark":"light"}-${primary}`,bg:"",fg:dark?"whiteBright":"black",muted:dark?"white":"blackBright",mutedbg:dark?"black":"white",surface:dark?"whiteBright":"black",surfacebg:dark?"black":"white",popover:dark?"whiteBright":"black",popoverbg:dark?"black":"white",inverse:dark?"black":"whiteBright",inversebg:dark?"whiteBright":"black",cursor:"black",cursorbg:primary,selection:"black",selectionbg:primary,primary,primaryfg:"black",secondary:primary,secondaryfg:"black",accent:primary,accentfg:"black",error:dark?"redBright":"red",errorfg:"black",warning:primary,warningfg:"black",success:dark?"greenBright":"green",successfg:"black",info:dark?"cyanBright":"cyan",infofg:"black",border:"gray",inputborder:"gray",focusborder:dark?"blueBright":"blue",link:"blueBright",disabledfg:"gray",palette:["black","red","green","yellow","blue","magenta","cyan","white","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"]}}var init_types2=()=>{};var init_base16=__esm(()=>{init_types2()});var init_generators=__esm(()=>{init_base16();init_palettes()});var init_builder=__esm(()=>{init_derive();init_generators();init_palettes()});var init_validate=__esm(()=>{init_types()});var THEME_TOKEN_KEYS,ALL_KNOWN_KEYS;var init_validate_theme=__esm(()=>{THEME_TOKEN_KEYS=["bg","fg","muted","mutedbg","surface","surfacebg","popover","popoverbg","inverse","inversebg","cursor","cursorbg","selection","selectionbg","primary","primaryfg","secondary","secondaryfg","accent","accentfg","error","errorfg","warning","warningfg","success","successfg","info","infofg","border","inputborder","focusborder","link","disabledfg"],ALL_KNOWN_KEYS=new Set([...THEME_TOKEN_KEYS,"name","palette"])});var init_css=__esm(()=>{init_validate_theme()});var init_auto_generate=__esm(()=>{init_generators();init_derive()});var init_base162=()=>{};async function getSilvery(){if(!_silvery)try{_silvery=await Promise.resolve().then(() => (init_src3(),exports_src))}catch{throw Error("Terminal palette detection requires '@silvery/ag-term' to be installed")}return _silvery}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)}),silvery=await getSilvery(),bg=await silvery.queryBackgroundColor(write,read,timeoutMs),fg=await silvery.queryForegroundColor(write,read,timeoutMs),ansi=Array(16).fill(null);silvery.queryMultiplePaletteColors(Array.from({length:16},(_2,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=silvery.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)}}async function detectTheme(opts={}){let colorLevel=opts.caps?.colorLevel;if(colorLevel==="none"||colorLevel==="basic")return opts.caps?.darkBackground??!0?ansi16DarkTheme:ansi16LightTheme;let detected=await detectTerminalPalette(opts.timeoutMs),isDark=detected?.dark??opts.caps?.darkBackground??!0,fallback=opts.fallback??(isDark?nord:catppuccinLatte);if(!detected)return deriveTheme(fallback);let merged={...fallback,...stripNulls(detected.palette)};return deriveTheme(merged)}function stripNulls(partial){let result={};for(let[k,v]of Object.entries(partial))if(v!=null)result[k]=v;return result}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 _silvery=null;var init_detect=__esm(()=>{init_derive();init_nord();init_catppuccin();init_palettes()});var init_theme=__esm(()=>{init_ThemeContext();init_types();init_derive();init_builder();init_generators();init_state();init_validate();init_validate_theme();init_contrast();init_css();init_auto_generate();init_base16();init_base162();init_detect();init_palettes();init_palettes()});var init_src=__esm(()=>{init_ThemeContext();init_theme()});class HitRegistry{regions=new Map;register(id,region){this.regions.set(id,region)}unregister(id){this.regions.delete(id)}clear(){this.regions.clear()}get size(){return this.regions.size}hitTest(screenX,screenY){let bestMatch=null;for(let region of this.regions.values())if(screenX>=region.x&&screenX<region.x+region.width&&screenY>=region.y&&screenY<region.y+region.height){if(!bestMatch||region.zIndex>bestMatch.zIndex)bestMatch=region}return bestMatch?.target??null}hitTestAll(screenX,screenY){let matches=[];for(let region of this.regions.values())if(screenX>=region.x&&screenX<region.x+region.width&&screenY>=region.y&&screenY<region.y+region.height)matches.push(region);return matches.sort((a,b)=>b.zIndex-a.zIndex)}getAllRegions(){return new Map(this.regions)}}function generateHitRegionId(){return`hit-${++hitRegionIdCounter}`}function resetHitRegionIdCounter(){hitRegionIdCounter=0}var hitRegionIdCounter=0,Z_INDEX;var init_hit_registry_core=__esm(()=>{Z_INDEX={BACKGROUND:0,COLUMN_HEADER:5,CARD:10,FOLD_TOGGLE:15,LINK:20,FLOATING:50,DIALOG:100,DROPDOWN:150,TOOLTIP:200}});import{createContext as createContext13,useContext as useContext27,useEffect as useEffect18,useRef as useRef23}from"react";function useHitRegistry(){return useContext27(HitRegistryContext)}function useHitRegion(target,rect,zIndex=0,enabled=!0){let registry=useContext27(HitRegistryContext),idRef=useRef23(null);if(idRef.current===null)idRef.current=generateHitRegionId();useEffect18(()=>{if(!registry||!rect||!enabled){if(idRef.current&&registry)registry.unregister(idRef.current);return}let id=idRef.current;return registry.register(id,{x:rect.x,y:rect.y,width:rect.width,height:rect.height,target,zIndex}),()=>{registry.unregister(id)}},[registry,rect?.x,rect?.y,rect?.width,rect?.height,target,zIndex,enabled])}function useHitRegionCallback(target,zIndex=0,enabled=!0){let registry=useContext27(HitRegistryContext),idRef=useRef23(null);if(idRef.current===null)idRef.current=generateHitRegionId();return useEffect18(()=>{let id=idRef.current;return()=>{if(id&&registry)registry.unregister(id)}},[registry]),(rect)=>{if(!registry||!enabled){if(idRef.current&&registry)registry.unregister(idRef.current);return}registry.register(idRef.current,{x:rect.x,y:rect.y,width:rect.width,height:rect.height,target,zIndex})}}var HitRegistryContext;var init_hit_registry=__esm(()=>{init_hit_registry_core();init_hit_registry_core();HitRegistryContext=createContext13(null)});function findNodeAtPosition(root,x,y){let result=null;function visit(node){let rect=node.screenRect;if(!rect)return;if(x>=rect.x&&x<rect.x+rect.width&&y>=rect.y&&y<rect.y+rect.height){result=node;for(let child of node.children)visit(child)}}return visit(root),result}function findAllContainingNodes(root,x,y){let result=[];function visit(node){let rect=node.screenRect;if(!rect)return;if(x>=rect.x&&x<rect.x+rect.width&&y>=rect.y&&y<rect.y+rect.height){result.push(node);for(let child of node.children)visit(child)}}return visit(root),result}function getNodePath(node){let parts=[],current=node;while(current){let props=current.props;if(props.id)parts.unshift(`#${props.id}`);else if(current.parent){let idx=current.parent.children.indexOf(current);parts.unshift(`[${idx}]`)}else parts.unshift("root");current=current.parent}return parts.join(" > ")}function rectChanged(a,b){if(a===b)return!1;if(!a||!b)return!0;return a.x!==b.x||a.y!==b.y||a.width!==b.width||a.height!==b.height}function getNodeDebugInfo(node){let props=node.props,childIndex=null;if(node.parent)childIndex=node.parent.children.indexOf(node);return{id:props.id,type:node.type,path:getNodePath(node),childIndex,dirtyFlags:{contentDirty:node.contentDirty,stylePropsDirty:node.stylePropsDirty,subtreeDirty:node.subtreeDirty,childrenDirty:node.childrenDirty,layoutDirty:node.layoutDirty},layout:{prevLayout:node.prevLayout,contentRect:node.contentRect,screenRect:node.screenRect,layoutChanged:rectChanged(node.prevLayout,node.contentRect)},scroll:node.scrollState?{offset:node.scrollState.offset,prevOffset:node.scrollState.prevOffset,offsetChanged:node.scrollState.offset!==node.scrollState.prevOffset,contentHeight:node.scrollState.contentHeight,viewportHeight:node.scrollState.viewportHeight,hiddenAbove:node.scrollState.hiddenAbove,hiddenBelow:node.scrollState.hiddenBelow,firstVisibleChild:node.scrollState.firstVisibleChild,lastVisibleChild:node.scrollState.lastVisibleChild}:void 0,backgroundColor:props.backgroundColor,childCount:node.children.length,hidden:node.hidden??!1}}function findScrollAncestors(node){let result=[],current=node.parent;while(current){if(current.scrollState)result.push(current);current=current.parent}return result}function analyzeFastPath(node,scrollAncestors){let analysis=[];if(!node)return analysis.push("⚠ No node found at mismatch position - possible virtualization issue"),analysis;let flags=node;if(!flags.contentDirty&&!flags.stylePropsDirty&&!flags.subtreeDirty&&!flags.childrenDirty&&!flags.layoutDirty)analysis.push("⚠ ALL DIRTY FLAGS FALSE - fast-path likely skipped this node");let scrollParent=scrollAncestors[0];if(scrollParent?.scrollState){let ss=scrollParent.scrollState,childIndex=node.parent?node.parent.children.indexOf(node):-1,inVisibleRange=childIndex>=ss.firstVisibleChild&&childIndex<=ss.lastVisibleChild;if(!inVisibleRange&&childIndex>=0)analysis.push(`⚠ Node index ${childIndex} is OUTSIDE visible range [${ss.firstVisibleChild}..${ss.lastVisibleChild}]`),analysis.push(" → Node should have been skipped, but mismatch suggests it should render");else if(inVisibleRange)analysis.push(`✓ Node index ${childIndex} is in visible range [${ss.firstVisibleChild}..${ss.lastVisibleChild}]`);if(ss.offset===ss.prevOffset)analysis.push("✓ Scroll offset unchanged (fast-path enabled for children)");else analysis.push(`⚠ Scroll offset CHANGED: ${ss.prevOffset} → ${ss.offset}`);if(ss.firstVisibleChild!==0||ss.lastVisibleChild!==scrollParent.children.length-1)analysis.push(` Visible range is partial: [${ss.firstVisibleChild}..${ss.lastVisibleChild}] of ${scrollParent.children.length} children`),analysis.push(" → If visible range changed, newly visible children need rendering")}if(!rectChanged(node.prevLayout,node.contentRect)&&node.prevLayout)analysis.push("✓ Layout unchanged (prevLayout matches contentRect)");else if(!node.prevLayout)analysis.push("⚠ prevLayout is NULL - node may never have been rendered before");else analysis.push("⚠ Layout CHANGED but node still skipped - dirty flag not set?");if(node.parent&&node.parent.children.length>1){let siblingMoved=!1;for(let sibling of node.parent.children)if(sibling!==node&&sibling.contentRect&&sibling.prevLayout){if(sibling.contentRect.x!==sibling.prevLayout.x||sibling.contentRect.y!==sibling.prevLayout.y){siblingMoved=!0;break}}if(siblingMoved)analysis.push("⚠ SIBLING POSITION CHANGED - parent should have detected this")}if(node.hidden)analysis.push("⚠ Node is HIDDEN (Suspense) - should not be rendered");return analysis}function buildMismatchContext(root,x,y,incrementalCell,freshCell,renderNum){let innermost=findNodeAtPosition(root,x,y),containing=findAllContainingNodes(root,x,y),scrollAncestorNodes=innermost?findScrollAncestors(innermost):[];return{position:{x,y},cells:{incremental:incrementalCell,fresh:freshCell},renderNum,node:innermost?getNodeDebugInfo(innermost):null,scrollAncestors:scrollAncestorNodes.map(getNodeDebugInfo),containingNodes:containing.map(getNodeDebugInfo),fastPathAnalysis:analyzeFastPath(innermost,scrollAncestorNodes)}}function formatMismatchContext(ctx,contentPhaseStats){let lines=[];lines.push(`SILVERY_STRICT: MISMATCH at (${ctx.position.x}, ${ctx.position.y}) on render #${ctx.renderNum}`),lines.push("");let{incremental,fresh}=ctx.cells;if(lines.push("CELL VALUES:"),lines.push(` incremental: char=${JSON.stringify(incremental.char)} fg=${JSON.stringify(incremental.fg)} bg=${JSON.stringify(incremental.bg)} attrs=${JSON.stringify(incremental.attrs)}`),lines.push(` fresh: char=${JSON.stringify(fresh.char)} fg=${JSON.stringify(fresh.fg)} bg=${JSON.stringify(fresh.bg)} attrs=${JSON.stringify(fresh.attrs)}`),lines.push(""),ctx.node){if(lines.push("INNERMOST NODE:"),lines.push(` path: ${ctx.node.path}`),lines.push(` type: ${ctx.node.type}`),ctx.node.backgroundColor)lines.push(` backgroundColor: ${ctx.node.backgroundColor}`);lines.push("");let flags=ctx.node.dirtyFlags,activeFlags=Object.entries(flags).filter(([,v])=>v).map(([k])=>k);if(lines.push("DIRTY FLAGS:"),activeFlags.length>0)lines.push(` active: ${activeFlags.join(", ")}`);else lines.push(" active: (none - node was clean)");lines.push(` all: contentDirty=${flags.contentDirty} stylePropsDirty=${flags.stylePropsDirty} subtreeDirty=${flags.subtreeDirty} childrenDirty=${flags.childrenDirty} layoutDirty=${flags.layoutDirty}`),lines.push("");let{layout}=ctx.node;if(lines.push("LAYOUT:"),layout.layoutChanged)lines.push(" ⚠ LAYOUT CHANGED:"),lines.push(` prevLayout: ${formatRect(layout.prevLayout)}`),lines.push(` contentRect: ${formatRect(layout.contentRect)}`);else lines.push(` contentRect: ${formatRect(layout.contentRect)}`);if(lines.push(` screenRect: ${formatRect(layout.screenRect)}`),lines.push(""),ctx.node.scroll)lines.push("SCROLL STATE (this node):"),formatScrollState(lines,ctx.node.scroll),lines.push("")}else lines.push("INNERMOST NODE: (none found at this position)"),lines.push("");if(ctx.scrollAncestors.length>0){lines.push("SCROLL ANCESTORS:");for(let ancestor of ctx.scrollAncestors)if(lines.push(` ${ancestor.path}:`),ancestor.scroll)formatScrollState(lines,ancestor.scroll," ");lines.push("")}if(ctx.containingNodes.length>1){lines.push("ALL CONTAINING NODES (outermost to innermost):");for(let node of ctx.containingNodes){let flags=Object.entries(node.dirtyFlags).filter(([,v])=>v).map(([k])=>k.replace("Dirty","")).join(","),flagStr=flags?` [${flags}]`:" [clean]",bgStr=node.backgroundColor?` bg=${node.backgroundColor}`:"",childStr=node.childIndex!==null?` child[${node.childIndex}]`:"";lines.push(` ${node.path}${flagStr}${bgStr}${childStr}`)}lines.push("")}if(ctx.fastPathAnalysis.length>0){lines.push("FAST-PATH ANALYSIS:");for(let line of ctx.fastPathAnalysis)lines.push(` ${line}`);lines.push("")}if(contentPhaseStats){let s=contentPhaseStats;lines.push("CONTENT PHASE STATS:"),lines.push(` nodesVisited: ${s.nodesVisited} nodesRendered: ${s.nodesRendered} nodesSkipped: ${s.nodesSkipped}`),lines.push(` textNodes: ${s.textNodes} boxNodes: ${s.boxNodes} clearOps: ${s.clearOps}`);let flagLines=[];if(s.noPrevBuffer)flagLines.push(`noPrevBuffer=${s.noPrevBuffer}`);if(s.flagContentDirty)flagLines.push(`contentDirty=${s.flagContentDirty}`);if(s.flagStylePropsDirty)flagLines.push(`stylePropsDirty=${s.flagStylePropsDirty}`);if(s.flagLayoutChanged)flagLines.push(`layoutChanged=${s.flagLayoutChanged}`);if(s.flagSubtreeDirty)flagLines.push(`subtreeDirty=${s.flagSubtreeDirty}`);if(s.flagChildrenDirty)flagLines.push(`childrenDirty=${s.flagChildrenDirty}`);if(s.flagChildPositionChanged)flagLines.push(`childPositionChanged=${s.flagChildPositionChanged}`);if(flagLines.length>0)lines.push(` render reasons: ${flagLines.join(", ")}`);if(s.scrollContainerCount>0){if(lines.push(` scrollContainers: ${s.scrollContainerCount} viewportCleared: ${s.scrollViewportCleared}`),s.scrollClearReason)lines.push(` scrollClearReason: ${s.scrollClearReason}`)}if(s.normalChildrenRepaint>0){if(lines.push(` normalChildrenRepaint: ${s.normalChildrenRepaint}`),s.normalRepaintReason)lines.push(` normalRepaintReason: ${s.normalRepaintReason}`)}if(s.cascadeMinDepth<999){if(lines.push(` cascadeMinDepth: ${s.cascadeMinDepth}`),s.cascadeNodes)lines.push(` cascadeNodes: ${s.cascadeNodes}`)}lines.push("")}return lines.join(`
86
+ `)}function formatRect(rect){if(!rect)return"(null)";return`{x:${rect.x}, y:${rect.y}, w:${rect.width}, h:${rect.height}}`}function formatScrollState(lines,scroll,indent=" "){if(scroll.offsetChanged)lines.push(`${indent}⚠ SCROLL CHANGED: offset ${scroll.prevOffset} → ${scroll.offset}`);else lines.push(`${indent}offset: ${scroll.offset}`);lines.push(`${indent}viewport: ${scroll.viewportHeight}/${scroll.contentHeight} (hidden: ▲${scroll.hiddenAbove} ▼${scroll.hiddenBelow})`),lines.push(`${indent}visibleRange: [${scroll.firstVisibleChild}..${scroll.lastVisibleChild}]`)}function isTTY(stdout=process.stdout){if(!stdout.isTTY)return!1;if(process.env.TERM==="dumb")return!1;if(process.env.CI||process.env.GITHUB_ACTIONS||process.env.GITLAB_CI||process.env.JENKINS_URL||process.env.BUILDKITE||process.env.CIRCLECI||process.env.TRAVIS)return!1;return!0}function resolveNonTTYMode(options={}){let{mode="auto",stdout=process.stdout}=options;if(mode!=="auto")return mode;return isTTY(stdout)?"tty":"line-by-line"}function toLineByLineOutput(content,prevLineCount){let lines=content.split(`
87
+ `),output="";if(prevLineCount>0){if(output+="\r",prevLineCount>1)output+=`\x1B[${prevLineCount-1}A`}for(let i=0;i<lines.length;i++){if(i>0)output+=`
88
+ `;output+=lines[i],output+="\x1B[K"}let extraLines=prevLineCount-lines.length;if(extraLines>0){for(let i=0;i<extraLines;i++)output+=`
89
+ \x1B[K`;output+=`\x1B[${extraLines}A`}return output}function toPlainOutput(content,_prevLineCount){let lines=stripAnsi3(content).split(`
90
+ `).map((line)=>line.trimEnd());while(lines.length>0&&lines[lines.length-1]==="")lines.pop();return lines.join(`
91
+ `)}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(`
92
+ `).length}var init_non_tty=__esm(()=>{init_unicode();init_unicode()});import{appendFileSync}from"node:fs";import{createLogger as createLogger6}from"loggily";var log4,SYNC_UPDATE_ENABLED,RenderScheduler;var init_scheduler=__esm(()=>{init_buffer();init_non_tty();init_useCursor();init_output();init_pipeline2();init_errors();init_errors();log4=createLogger6("silvery:scheduler"),SYNC_UPDATE_ENABLED=process.env.SILVERY_SYNC_UPDATE==="1"||process.env.SILVERY_SYNC_UPDATE==="true";RenderScheduler=class RenderScheduler{stdout;root;debugMode;minFrameTime;slowFrameThreshold;mode;pipelineConfig;getCursorState;nonTTYMode;outputTransformer;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.log=createLogger6("silvery:scheduler"),this.nonTTYMode=resolveNonTTYMode({mode:options.nonTTYMode,stdout:this.stdout}),this.outputTransformer=createOutputTransformer(this.nonTTYMode),log4.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++,log4.debug?.(`render skipped (batched), total: ${this.stats.skippedCount}`);return}this.renderScheduled=!0,log4.debug?.("render scheduled"),queueMicrotask(()=>{if(this.renderScheduled=!1,this.disposed)return;let timeSinceLastRender=Date.now()-this.lastRenderTime;if(timeSinceLastRender<this.minFrameTime)log4.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(this.stdout,message,opts)}copyToClipboard(text){if(this.disposed)return;copyToClipboard(this.stdout,text)}pause(){if(this.disposed||this.paused)return;this.paused=!0,this.pendingWhilePaused=!1,log4.debug?.("scheduler paused")}resume(){if(this.disposed||!this.paused)return;if(this.paused=!1,log4.debug?.("scheduler resumed"),this.prevBuffer=null,this.pendingWhilePaused)this.pendingWhilePaused=!1,this.executeRender()}isPaused(){return this.paused}clear(){if(this.disposed)return;this.stdout.write("\x1B[2J\x1B[H\x1B[?25l"),this.prevBuffer=null}[Symbol.dispose](){this.dispose()}dispose(){if(this.disposed)return;if(log4.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.stdout.write(this.staticOutput),this.stdout.write(`
93
+ `)}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;log4.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=stripAnsi3(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(log4.debug){let bytes=Buffer.byteLength(fullOutput);if(log4.debug?.(`stdout.write: ${bytes} bytes (${transformedOutput.length} chars output + ${cursorSuffix.length} chars cursor)`),bytes>16384)log4.warn?.(`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) ---
94
+ `),fs2.appendFileSync(captureFile,fullOutput),fs2.appendFileSync(captureFile,`
95
+ `)}this.stdout.write(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),contentPhaseStats=globalThis.__silvery_content_detail?structuredClone(globalThis.__silvery_content_detail):void 0,debugInfo=formatMismatchContext(ctx,contentPhaseStats),incText=bufferToText(buffer),freshText=bufferToText(freshBuffer),msg=debugInfo+`--- incremental ---
96
+ ${incText}
97
+ --- fresh ---
98
+ ${freshText}`;if(process.env.DEBUG_LOG)appendFileSync(process.env.DEBUG_LOG,msg+`
99
+ `);throw log4.error?.(msg),new IncrementalRenderMismatchError(msg,{contentPhaseStats,mismatchContext:ctx})}}if(!found&&process.env.DEBUG_LOG)appendFileSync(process.env.DEBUG_LOG,`SILVERY_STRICT: render #${renderNum} OK
100
+ `)}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,log4.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)log4.warn?.(`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 log4.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){process.stderr.write(`[Silvery Debug] ${message}
101
+ `)}logError(message,error){if(process.stderr.write(`[Silvery Error] ${message}
102
+ `),error instanceof Error)process.stderr.write(`${error.stack??error.message}
103
+ `);else process.stderr.write(`${String(error)}
104
+ `)}}});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!==`
105
+ `&&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})}}}}}var require_constants=__commonJS((exports,module)=>{var BINARY_TYPES=["nodebuffer","arraybuffer","fragments"],hasBlob=typeof Blob<"u";if(hasBlob)BINARY_TYPES.push("blob");module.exports={BINARY_TYPES,CLOSE_TIMEOUT:30000,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var require_buffer_util=__commonJS((exports,module)=>{var{EMPTY_BUFFER}=require_constants(),FastBuffer=Buffer[Symbol.species];function concat(list,totalLength){if(list.length===0)return EMPTY_BUFFER;if(list.length===1)return list[0];let target=Buffer.allocUnsafe(totalLength),offset=0;for(let i=0;i<list.length;i++){let buf=list[i];target.set(buf,offset),offset+=buf.length}if(offset<totalLength)return new FastBuffer(target.buffer,target.byteOffset,offset);return target}function _mask(source,mask,output,offset,length){for(let i=0;i<length;i++)output[offset+i]=source[i]^mask[i&3]}function _unmask(buffer,mask){for(let i=0;i<buffer.length;i++)buffer[i]^=mask[i&3]}function toArrayBuffer(buf){if(buf.length===buf.buffer.byteLength)return buf.buffer;return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.length)}function toBuffer(data){if(toBuffer.readOnly=!0,Buffer.isBuffer(data))return data;let buf;if(data instanceof ArrayBuffer)buf=new FastBuffer(data);else if(ArrayBuffer.isView(data))buf=new FastBuffer(data.buffer,data.byteOffset,data.byteLength);else buf=Buffer.from(data),toBuffer.readOnly=!1;return buf}module.exports={concat,mask:_mask,toArrayBuffer,toBuffer,unmask:_unmask};if(!process.env.WS_NO_BUFFER_UTIL)try{let bufferUtil=(()=>{throw new Error("Cannot require module "+"bufferutil");})();module.exports.mask=function(source,mask,output,offset,length){if(length<48)_mask(source,mask,output,offset,length);else bufferUtil.mask(source,mask,output,offset,length)},module.exports.unmask=function(buffer,mask){if(buffer.length<32)_unmask(buffer,mask);else bufferUtil.unmask(buffer,mask)}}catch(e){}});var require_limiter=__commonJS((exports,module)=>{var kDone=Symbol("kDone"),kRun=Symbol("kRun");class Limiter{constructor(concurrency){this[kDone]=()=>{this.pending--,this[kRun]()},this.concurrency=concurrency||1/0,this.jobs=[],this.pending=0}add(job){this.jobs.push(job),this[kRun]()}[kRun](){if(this.pending===this.concurrency)return;if(this.jobs.length){let job=this.jobs.shift();this.pending++,job(this[kDone])}}}module.exports=Limiter});var require_permessage_deflate=__commonJS((exports,module)=>{var zlib=__require("zlib"),bufferUtil=require_buffer_util(),Limiter=require_limiter(),{kStatusCode}=require_constants(),FastBuffer=Buffer[Symbol.species],TRAILER=Buffer.from([0,0,255,255]),kPerMessageDeflate=Symbol("permessage-deflate"),kTotalLength=Symbol("total-length"),kCallback=Symbol("callback"),kBuffers=Symbol("buffers"),kError=Symbol("error"),zlibLimiter;class PerMessageDeflate{constructor(options){if(this._options=options||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!zlibLimiter){let concurrency=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){let params={};if(this._options.serverNoContextTakeover)params.server_no_context_takeover=!0;if(this._options.clientNoContextTakeover)params.client_no_context_takeover=!0;if(this._options.serverMaxWindowBits)params.server_max_window_bits=this._options.serverMaxWindowBits;if(this._options.clientMaxWindowBits)params.client_max_window_bits=this._options.clientMaxWindowBits;else if(this._options.clientMaxWindowBits==null)params.client_max_window_bits=!0;return params}accept(configurations){return configurations=this.normalizeParams(configurations),this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations),this.params}cleanup(){if(this._inflate)this._inflate.close(),this._inflate=null;if(this._deflate){let callback=this._deflate[kCallback];if(this._deflate.close(),this._deflate=null,callback)callback(Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(offers){let opts=this._options,accepted=offers.find((params)=>{if(opts.serverNoContextTakeover===!1&&params.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===!1||typeof opts.serverMaxWindowBits==="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits==="number"&&!params.client_max_window_bits)return!1;return!0});if(!accepted)throw Error("None of the extension offers can be accepted");if(opts.serverNoContextTakeover)accepted.server_no_context_takeover=!0;if(opts.clientNoContextTakeover)accepted.client_no_context_takeover=!0;if(typeof opts.serverMaxWindowBits==="number")accepted.server_max_window_bits=opts.serverMaxWindowBits;if(typeof opts.clientMaxWindowBits==="number")accepted.client_max_window_bits=opts.clientMaxWindowBits;else if(accepted.client_max_window_bits===!0||opts.clientMaxWindowBits===!1)delete accepted.client_max_window_bits;return accepted}acceptAsClient(response){let params=response[0];if(this._options.clientNoContextTakeover===!1&&params.client_no_context_takeover)throw Error('Unexpected parameter "client_no_context_takeover"');if(!params.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number")params.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==="number"&&params.client_max_window_bits>this._options.clientMaxWindowBits)throw Error('Unexpected or invalid parameter "client_max_window_bits"');return params}normalizeParams(configurations){return configurations.forEach((params)=>{Object.keys(params).forEach((key)=>{let value=params[key];if(value.length>1)throw Error(`Parameter "${key}" must have only a single value`);if(value=value[0],key==="client_max_window_bits"){if(value!==!0){let num=+value;if(!Number.isInteger(num)||num<8||num>15)throw TypeError(`Invalid value for parameter "${key}": ${value}`);value=num}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${key}": ${value}`)}else if(key==="server_max_window_bits"){let num=+value;if(!Number.isInteger(num)||num<8||num>15)throw TypeError(`Invalid value for parameter "${key}": ${value}`);value=num}else if(key==="client_no_context_takeover"||key==="server_no_context_takeover"){if(value!==!0)throw TypeError(`Invalid value for parameter "${key}": ${value}`)}else throw Error(`Unknown parameter "${key}"`);params[key]=value})}),configurations}decompress(data,fin,callback){zlibLimiter.add((done)=>{this._decompress(data,fin,(err,result)=>{done(),callback(err,result)})})}compress(data,fin,callback){zlibLimiter.add((done)=>{this._compress(data,fin,(err,result)=>{done(),callback(err,result)})})}_decompress(data,fin,callback){let endpoint=this._isServer?"client":"server";if(!this._inflate){let key=`${endpoint}_max_window_bits`,windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._inflate=zlib.createInflateRaw({...this._options.zlibInflateOptions,windowBits}),this._inflate[kPerMessageDeflate]=this,this._inflate[kTotalLength]=0,this._inflate[kBuffers]=[],this._inflate.on("error",inflateOnError),this._inflate.on("data",inflateOnData)}if(this._inflate[kCallback]=callback,this._inflate.write(data),fin)this._inflate.write(TRAILER);this._inflate.flush(()=>{let err=this._inflate[kError];if(err){this._inflate.close(),this._inflate=null,callback(err);return}let data2=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);if(this._inflate._readableState.endEmitted)this._inflate.close(),this._inflate=null;else if(this._inflate[kTotalLength]=0,this._inflate[kBuffers]=[],fin&&this.params[`${endpoint}_no_context_takeover`])this._inflate.reset();callback(null,data2)})}_compress(data,fin,callback){let endpoint=this._isServer?"server":"client";if(!this._deflate){let key=`${endpoint}_max_window_bits`,windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._deflate=zlib.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits}),this._deflate[kTotalLength]=0,this._deflate[kBuffers]=[],this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback,this._deflate.write(data),this._deflate.flush(zlib.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let data2=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);if(fin)data2=new FastBuffer(data2.buffer,data2.byteOffset,data2.length-4);if(this._deflate[kCallback]=null,this._deflate[kTotalLength]=0,this._deflate[kBuffers]=[],fin&&this.params[`${endpoint}_no_context_takeover`])this._deflate.reset();callback(null,data2)})}}module.exports=PerMessageDeflate;function deflateOnData(chunk){this[kBuffers].push(chunk),this[kTotalLength]+=chunk.length}function inflateOnData(chunk){if(this[kTotalLength]+=chunk.length,this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=RangeError("Max payload size exceeded"),this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[kError][kStatusCode]=1009,this.removeListener("data",inflateOnData),this.reset()}function inflateOnError(err){if(this[kPerMessageDeflate]._inflate=null,this[kError]){this[kCallback](this[kError]);return}err[kStatusCode]=1007,this[kCallback](err)}});var require_validation=__commonJS((exports,module)=>{var{isUtf8}=__require("buffer"),{hasBlob}=require_constants(),tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(code){return code>=1000&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3000&&code<=4999}function _isValidUTF8(buf){let len=buf.length,i=0;while(i<len)if((buf[i]&128)===0)i++;else if((buf[i]&224)===192){if(i+1===len||(buf[i+1]&192)!==128||(buf[i]&254)===192)return!1;i+=2}else if((buf[i]&240)===224){if(i+2>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||buf[i]===224&&(buf[i+1]&224)===128||buf[i]===237&&(buf[i+1]&224)===160)return!1;i+=3}else if((buf[i]&248)===240){if(i+3>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||(buf[i+3]&192)!==128||buf[i]===240&&(buf[i+1]&240)===128||buf[i]===244&&buf[i+1]>143||buf[i]>244)return!1;i+=4}else return!1;return!0}function isBlob(value){return hasBlob&&typeof value==="object"&&typeof value.arrayBuffer==="function"&&typeof value.type==="string"&&typeof value.stream==="function"&&(value[Symbol.toStringTag]==="Blob"||value[Symbol.toStringTag]==="File")}module.exports={isBlob,isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8)module.exports.isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let isValidUTF8=(()=>{throw new Error("Cannot require module "+"utf-8-validate");})();module.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch(e){}});var require_receiver=__commonJS((exports,module)=>{var{Writable}=__require("stream"),PerMessageDeflate=require_permessage_deflate(),{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants(),{concat,toArrayBuffer,unmask}=require_buffer_util(),{isValidStatusCode,isValidUTF8}=require_validation(),FastBuffer=Buffer[Symbol.species];class Receiver extends Writable{constructor(options={}){super();this._allowSynchronousEvents=options.allowSynchronousEvents!==void 0?options.allowSynchronousEvents:!0,this._binaryType=options.binaryType||BINARY_TYPES[0],this._extensions=options.extensions||{},this._isServer=!!options.isServer,this._maxPayload=options.maxPayload|0,this._skipUTF8Validation=!!options.skipUTF8Validation,this[kWebSocket]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==0)return cb();this._bufferedBytes+=chunk.length,this._buffers.push(chunk),this.startLoop(cb)}consume(n){if(this._bufferedBytes-=n,n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){let buf=this._buffers[0];return this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n),new FastBuffer(buf.buffer,buf.byteOffset,n)}let dst=Buffer.allocUnsafe(n);do{let buf=this._buffers[0],offset=dst.length-n;if(n>=buf.length)dst.set(this._buffers.shift(),offset);else dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset),this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n);n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=!0;do switch(this._state){case 0:this.getInfo(cb);break;case 1:this.getPayloadLength16(cb);break;case 2:this.getPayloadLength64(cb);break;case 3:this.getMask();break;case 4:this.getData(cb);break;case 5:case 6:this._loop=!1;return}while(this._loop);if(!this._errored)cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=!1;return}let buf=this.consume(2);if((buf[0]&48)!==0){let error=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error);return}let compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate.extensionName]){let error=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._fin=(buf[0]&128)===128,this._opcode=buf[0]&15,this._payloadLength=buf[1]&127,this._opcode===0){if(compressed){let error=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(!this._fragmented){let error=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let error=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let error=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");cb(error);return}if(compressed){let error=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let error=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error);return}}else{let error=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;if(this._masked=(buf[1]&128)===128,this._isServer){if(!this._masked){let error=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");cb(error);return}}else if(this._masked){let error=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");cb(error);return}if(this._payloadLength===126)this._state=1;else if(this._payloadLength===127)this._state=2;else this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=!1;return}let buf=this.consume(8),num=buf.readUInt32BE(0);if(num>Math.pow(2,21)-1){let error=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error);return}this._payloadLength=num*Math.pow(2,32)+buf.readUInt32BE(4),this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8){if(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){let error=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}}if(this._masked)this._state=3;else this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}if(data=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0)unmask(data,this._mask)}if(this._opcode>7){this.controlMessage(data,cb);return}if(this._compressed){this._state=5,this.decompress(data,cb);return}if(data.length)this._messageLength=this._totalPayloadLength,this._fragments.push(data);this.dataMessage(cb)}decompress(data,cb){this._extensions[PerMessageDeflate.extensionName].decompress(data,this._fin,(err,buf)=>{if(err)return cb(err);if(buf.length){if(this._messageLength+=buf.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let error=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}this._fragments.push(buf)}if(this.dataMessage(cb),this._state===0)this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=0;return}let messageLength=this._messageLength,fragments=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let data;if(this._binaryType==="nodebuffer")data=concat(fragments,messageLength);else if(this._binaryType==="arraybuffer")data=toArrayBuffer(concat(fragments,messageLength));else if(this._binaryType==="blob")data=new Blob(fragments);else data=fragments;if(this._allowSynchronousEvents)this.emit("message",data,!0),this._state=0;else this._state=6,setImmediate(()=>{this.emit("message",data,!0),this._state=0,this.startLoop(cb)})}else{let buf=concat(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){let error=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");cb(error);return}if(this._state===5||this._allowSynchronousEvents)this.emit("message",buf,!1),this._state=0;else this._state=6,setImmediate(()=>{this.emit("message",buf,!1),this._state=0,this.startLoop(cb)})}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0)this._loop=!1,this.emit("conclude",1005,EMPTY_BUFFER),this.end();else{let code=data.readUInt16BE(0);if(!isValidStatusCode(code)){let error=this.createError(RangeError,`invalid status code ${code}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");cb(error);return}let buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){let error=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._loop=!1,this.emit("conclude",code,buf),this.end()}this._state=0;return}if(this._allowSynchronousEvents)this.emit(this._opcode===9?"ping":"pong",data),this._state=0;else this._state=6,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",data),this._state=0,this.startLoop(cb)})}createError(ErrorCtor,message,prefix,statusCode,errorCode){this._loop=!1,this._errored=!0;let err=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message}`:message);return Error.captureStackTrace(err,this.createError),err.code=errorCode,err[kStatusCode]=statusCode,err}}module.exports=Receiver});var require_sender=__commonJS((exports,module)=>{var{Duplex}=__require("stream"),{randomFillSync}=__require("crypto"),PerMessageDeflate=require_permessage_deflate(),{EMPTY_BUFFER,kWebSocket,NOOP}=require_constants(),{isBlob,isValidStatusCode}=require_validation(),{mask:applyMask,toBuffer}=require_buffer_util(),kByteLength=Symbol("kByteLength"),maskBuffer=Buffer.alloc(4),randomPool,randomPoolPointer=8192,DEFAULT=0,DEFLATING=1,GET_BLOB_DATA=2;class Sender{constructor(socket,extensions,generateMask){if(this._extensions=extensions||{},generateMask)this._generateMask=generateMask,this._maskBuffer=Buffer.alloc(4);this._socket=socket,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=DEFAULT,this.onerror=NOOP,this[kWebSocket]=void 0}static frame(data,options){let mask,merge=!1,offset=2,skipMasking=!1;if(options.mask){if(mask=options.maskBuffer||maskBuffer,options.generateMask)options.generateMask(mask);else{if(randomPoolPointer===8192){if(randomPool===void 0)randomPool=Buffer.alloc(8192);randomFillSync(randomPool,0,8192),randomPoolPointer=0}mask[0]=randomPool[randomPoolPointer++],mask[1]=randomPool[randomPoolPointer++],mask[2]=randomPool[randomPoolPointer++],mask[3]=randomPool[randomPoolPointer++]}skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0,offset=6}let dataLength;if(typeof data==="string")if((!options.mask||skipMasking)&&options[kByteLength]!==void 0)dataLength=options[kByteLength];else data=Buffer.from(data),dataLength=data.length;else dataLength=data.length,merge=options.mask&&options.readOnly&&!skipMasking;let payloadLength=dataLength;if(dataLength>=65536)offset+=8,payloadLength=127;else if(dataLength>125)offset+=2,payloadLength=126;let target=Buffer.allocUnsafe(merge?dataLength+offset:offset);if(target[0]=options.fin?options.opcode|128:options.opcode,options.rsv1)target[0]|=64;if(target[1]=payloadLength,payloadLength===126)target.writeUInt16BE(dataLength,2);else if(payloadLength===127)target[2]=target[3]=0,target.writeUIntBE(dataLength,4,6);if(!options.mask)return[target,data];if(target[1]|=128,target[offset-4]=mask[0],target[offset-3]=mask[1],target[offset-2]=mask[2],target[offset-1]=mask[3],skipMasking)return[target,data];if(merge)return applyMask(data,mask,target,offset,dataLength),[target];return applyMask(data,mask,data,0,dataLength),[target,data]}close(code,data,mask,cb){let buf;if(code===void 0)buf=EMPTY_BUFFER;else if(typeof code!=="number"||!isValidStatusCode(code))throw TypeError("First argument must be a valid error code number");else if(data===void 0||!data.length)buf=Buffer.allocUnsafe(2),buf.writeUInt16BE(code,0);else{let length=Buffer.byteLength(data);if(length>123)throw RangeError("The message must not be greater than 123 bytes");if(buf=Buffer.allocUnsafe(2+length),buf.writeUInt16BE(code,0),typeof data==="string")buf.write(data,2);else buf.set(data,2)}let options={[kByteLength]:buf.length,fin:!0,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};if(this._state!==DEFAULT)this.enqueue([this.dispatch,buf,!1,options,cb]);else this.sendFrame(Sender.frame(buf,options),cb)}ping(data,mask,cb){let byteLength,readOnly;if(typeof data==="string")byteLength=Buffer.byteLength(data),readOnly=!1;else if(isBlob(data))byteLength=data.size,readOnly=!1;else data=toBuffer(data),byteLength=data.length,readOnly=toBuffer.readOnly;if(byteLength>125)throw RangeError("The data size must not be greater than 125 bytes");let options={[kByteLength]:byteLength,fin:!0,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:!1};if(isBlob(data))if(this._state!==DEFAULT)this.enqueue([this.getBlobData,data,!1,options,cb]);else this.getBlobData(data,!1,options,cb);else if(this._state!==DEFAULT)this.enqueue([this.dispatch,data,!1,options,cb]);else this.sendFrame(Sender.frame(data,options),cb)}pong(data,mask,cb){let byteLength,readOnly;if(typeof data==="string")byteLength=Buffer.byteLength(data),readOnly=!1;else if(isBlob(data))byteLength=data.size,readOnly=!1;else data=toBuffer(data),byteLength=data.length,readOnly=toBuffer.readOnly;if(byteLength>125)throw RangeError("The data size must not be greater than 125 bytes");let options={[kByteLength]:byteLength,fin:!0,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:!1};if(isBlob(data))if(this._state!==DEFAULT)this.enqueue([this.getBlobData,data,!1,options,cb]);else this.getBlobData(data,!1,options,cb);else if(this._state!==DEFAULT)this.enqueue([this.dispatch,data,!1,options,cb]);else this.sendFrame(Sender.frame(data,options),cb)}send(data,options,cb){let perMessageDeflate=this._extensions[PerMessageDeflate.extensionName],opcode=options.binary?2:1,rsv1=options.compress,byteLength,readOnly;if(typeof data==="string")byteLength=Buffer.byteLength(data),readOnly=!1;else if(isBlob(data))byteLength=data.size,readOnly=!1;else data=toBuffer(data),byteLength=data.length,readOnly=toBuffer.readOnly;if(this._firstFragment){if(this._firstFragment=!1,rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"])rsv1=byteLength>=perMessageDeflate._threshold;this._compress=rsv1}else rsv1=!1,opcode=0;if(options.fin)this._firstFragment=!0;let opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};if(isBlob(data))if(this._state!==DEFAULT)this.enqueue([this.getBlobData,data,this._compress,opts,cb]);else this.getBlobData(data,this._compress,opts,cb);else if(this._state!==DEFAULT)this.enqueue([this.dispatch,data,this._compress,opts,cb]);else this.dispatch(data,this._compress,opts,cb)}getBlobData(blob,compress,options,cb){this._bufferedBytes+=options[kByteLength],this._state=GET_BLOB_DATA,blob.arrayBuffer().then((arrayBuffer)=>{if(this._socket.destroyed){let err=Error("The socket was closed while the blob was being read");process.nextTick(callCallbacks,this,err,cb);return}this._bufferedBytes-=options[kByteLength];let data=toBuffer(arrayBuffer);if(!compress)this._state=DEFAULT,this.sendFrame(Sender.frame(data,options),cb),this.dequeue();else this.dispatch(data,compress,options,cb)}).catch((err)=>{process.nextTick(onError,this,err,cb)})}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(Sender.frame(data,options),cb);return}let perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];this._bufferedBytes+=options[kByteLength],this._state=DEFLATING,perMessageDeflate.compress(data,options.fin,(_2,buf)=>{if(this._socket.destroyed){let err=Error("The socket was closed while data was being compressed");callCallbacks(this,err,cb);return}this._bufferedBytes-=options[kByteLength],this._state=DEFAULT,options.readOnly=!1,this.sendFrame(Sender.frame(buf,options),cb),this.dequeue()})}dequeue(){while(this._state===DEFAULT&&this._queue.length){let params=this._queue.shift();this._bufferedBytes-=params[3][kByteLength],Reflect.apply(params[0],this,params.slice(1))}}enqueue(params){this._bufferedBytes+=params[3][kByteLength],this._queue.push(params)}sendFrame(list,cb){if(list.length===2)this._socket.cork(),this._socket.write(list[0]),this._socket.write(list[1],cb),this._socket.uncork();else this._socket.write(list[0],cb)}}module.exports=Sender;function callCallbacks(sender,err,cb){if(typeof cb==="function")cb(err);for(let i=0;i<sender._queue.length;i++){let params=sender._queue[i],callback=params[params.length-1];if(typeof callback==="function")callback(err)}}function onError(sender,err,cb){callCallbacks(sender,err,cb),sender.onerror(err)}});var require_event_target=__commonJS((exports,module)=>{var{kForOnEventAttribute,kListener}=require_constants(),kCode=Symbol("kCode"),kData=Symbol("kData"),kError=Symbol("kError"),kMessage=Symbol("kMessage"),kReason=Symbol("kReason"),kTarget=Symbol("kTarget"),kType=Symbol("kType"),kWasClean=Symbol("kWasClean");class Event{constructor(type){this[kTarget]=null,this[kType]=type}get target(){return this[kTarget]}get type(){return this[kType]}}Object.defineProperty(Event.prototype,"target",{enumerable:!0});Object.defineProperty(Event.prototype,"type",{enumerable:!0});class CloseEvent extends Event{constructor(type,options={}){super(type);this[kCode]=options.code===void 0?0:options.code,this[kReason]=options.reason===void 0?"":options.reason,this[kWasClean]=options.wasClean===void 0?!1:options.wasClean}get code(){return this[kCode]}get reason(){return this[kReason]}get wasClean(){return this[kWasClean]}}Object.defineProperty(CloseEvent.prototype,"code",{enumerable:!0});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:!0});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:!0});class ErrorEvent extends Event{constructor(type,options={}){super(type);this[kError]=options.error===void 0?null:options.error,this[kMessage]=options.message===void 0?"":options.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:!0});class MessageEvent extends Event{constructor(type,options={}){super(type);this[kData]=options.data===void 0?null:options.data}get data(){return this[kData]}}Object.defineProperty(MessageEvent.prototype,"data",{enumerable:!0});var EventTarget={addEventListener(type,handler,options={}){for(let listener of this.listeners(type))if(!options[kForOnEventAttribute]&&listener[kListener]===handler&&!listener[kForOnEventAttribute])return;let wrapper;if(type==="message")wrapper=function(data,isBinary){let event=new MessageEvent("message",{data:isBinary?data:data.toString()});event[kTarget]=this,callListener(handler,this,event)};else if(type==="close")wrapper=function(code,message){let event=new CloseEvent("close",{code,reason:message.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});event[kTarget]=this,callListener(handler,this,event)};else if(type==="error")wrapper=function(error){let event=new ErrorEvent("error",{error,message:error.message});event[kTarget]=this,callListener(handler,this,event)};else if(type==="open")wrapper=function(){let event=new Event("open");event[kTarget]=this,callListener(handler,this,event)};else return;if(wrapper[kForOnEventAttribute]=!!options[kForOnEventAttribute],wrapper[kListener]=handler,options.once)this.once(type,wrapper);else this.on(type,wrapper)},removeEventListener(type,handler){for(let listener of this.listeners(type))if(listener[kListener]===handler&&!listener[kForOnEventAttribute]){this.removeListener(type,listener);break}}};module.exports={CloseEvent,ErrorEvent,Event,EventTarget,MessageEvent};function callListener(listener,thisArg,event){if(typeof listener==="object"&&listener.handleEvent)listener.handleEvent.call(listener,event);else listener.call(thisArg,event)}});var require_extension=__commonJS((exports,module)=>{var{tokenChars}=require_validation();function push(dest,name,elem){if(dest[name]===void 0)dest[name]=[elem];else dest[name].push(elem)}function parse(header){let offers=Object.create(null),params=Object.create(null),mustUnescape=!1,isEscaping=!1,inQuotes=!1,extensionName,paramName,start=-1,code=-1,end=-1,i=0;for(;i<header.length;i++)if(code=header.charCodeAt(i),extensionName===void 0)if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1)throw SyntaxError(`Unexpected character at index ${i}`);if(end===-1)end=i;let name=header.slice(start,end);if(code===44)push(offers,name,params),params=Object.create(null);else extensionName=name;start=end=-1}else throw SyntaxError(`Unexpected character at index ${i}`);else if(paramName===void 0)if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(code===32||code===9){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1)throw SyntaxError(`Unexpected character at index ${i}`);if(end===-1)end=i;if(push(params,header.slice(start,end),!0),code===44)push(offers,extensionName,params),params=Object.create(null),extensionName=void 0;start=end=-1}else if(code===61&&start!==-1&&end===-1)paramName=header.slice(start,i),start=end=-1;else throw SyntaxError(`Unexpected character at index ${i}`);else if(isEscaping){if(tokenChars[code]!==1)throw SyntaxError(`Unexpected character at index ${i}`);if(start===-1)start=i;else if(!mustUnescape)mustUnescape=!0;isEscaping=!1}else if(inQuotes)if(tokenChars[code]===1){if(start===-1)start=i}else if(code===34&&start!==-1)inQuotes=!1,end=i;else if(code===92)isEscaping=!0;else throw SyntaxError(`Unexpected character at index ${i}`);else if(code===34&&header.charCodeAt(i-1)===61)inQuotes=!0;else if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(start!==-1&&(code===32||code===9)){if(end===-1)end=i}else if(code===59||code===44){if(start===-1)throw SyntaxError(`Unexpected character at index ${i}`);if(end===-1)end=i;let value=header.slice(start,end);if(mustUnescape)value=value.replace(/\\/g,""),mustUnescape=!1;if(push(params,paramName,value),code===44)push(offers,extensionName,params),params=Object.create(null),extensionName=void 0;paramName=void 0,start=end=-1}else throw SyntaxError(`Unexpected character at index ${i}`);if(start===-1||inQuotes||code===32||code===9)throw SyntaxError("Unexpected end of input");if(end===-1)end=i;let token=header.slice(start,end);if(extensionName===void 0)push(offers,token,params);else{if(paramName===void 0)push(params,token,!0);else if(mustUnescape)push(params,paramName,token.replace(/\\/g,""));else push(params,paramName,token);push(offers,extensionName,params)}return offers}function format(extensions){return Object.keys(extensions).map((extension)=>{let configurations=extensions[extension];if(!Array.isArray(configurations))configurations=[configurations];return configurations.map((params)=>{return[extension].concat(Object.keys(params).map((k)=>{let values=params[k];if(!Array.isArray(values))values=[values];return values.map((v)=>v===!0?k:`${k}=${v}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}module.exports={format,parse}});var require_websocket=__commonJS((exports,module)=>{var EventEmitter=__require("events"),https=__require("https"),http=__require("http"),net=__require("net"),tls=__require("tls"),{randomBytes,createHash}=__require("crypto"),{Duplex,Readable}=__require("stream"),{URL:URL2}=__require("url"),PerMessageDeflate=require_permessage_deflate(),Receiver=require_receiver(),Sender=require_sender(),{isBlob}=require_validation(),{BINARY_TYPES,CLOSE_TIMEOUT,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants(),{EventTarget:{addEventListener,removeEventListener}}=require_event_target(),{format,parse}=require_extension(),{toBuffer}=require_buffer_util(),kAborted=Symbol("kAborted"),protocolVersions=[8,13],readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"],subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class WebSocket extends EventEmitter{constructor(address,protocols,options){super();if(this._binaryType=BINARY_TYPES[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=EMPTY_BUFFER,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=WebSocket.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,address!==null){if(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,protocols===void 0)protocols=[];else if(!Array.isArray(protocols))if(typeof protocols==="object"&&protocols!==null)options=protocols,protocols=[];else protocols=[protocols];initAsClient(this,address,protocols,options)}else this._autoPong=options.autoPong,this._closeTimeout=options.closeTimeout,this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(type){if(!BINARY_TYPES.includes(type))return;if(this._binaryType=type,this._receiver)this._receiver._binaryType=type}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){let receiver=new Receiver({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation}),sender=new Sender(socket,this._extensions,options.generateMask);if(this._receiver=receiver,this._sender=sender,this._socket=socket,receiver[kWebSocket]=this,sender[kWebSocket]=this,socket[kWebSocket]=this,receiver.on("conclude",receiverOnConclude),receiver.on("drain",receiverOnDrain),receiver.on("error",receiverOnError),receiver.on("message",receiverOnMessage),receiver.on("ping",receiverOnPing),receiver.on("pong",receiverOnPong),sender.onerror=senderOnError,socket.setTimeout)socket.setTimeout(0);if(socket.setNoDelay)socket.setNoDelay();if(head.length>0)socket.unshift(head);socket.on("close",socketOnClose),socket.on("data",socketOnData),socket.on("end",socketOnEnd),socket.on("error",socketOnError),this._readyState=WebSocket.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=WebSocket.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[PerMessageDeflate.extensionName])this._extensions[PerMessageDeflate.extensionName].cleanup();this._receiver.removeAllListeners(),this._readyState=WebSocket.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){abortHandshake(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===WebSocket.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted))this._socket.end();return}this._readyState=WebSocket.CLOSING,this._sender.close(code,data,!this._isServer,(err)=>{if(err)return;if(this._closeFrameSent=!0,this._closeFrameReceived||this._receiver._writableState.errorEmitted)this._socket.end()}),setCloseTimer(this)}pause(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED)return;this._paused=!0,this._socket.pause()}ping(data,mask,cb){if(this.readyState===WebSocket.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof data==="function")cb=data,data=mask=void 0;else if(typeof mask==="function")cb=mask,mask=void 0;if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===WebSocket.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof data==="function")cb=data,data=mask=void 0;else if(typeof mask==="function")cb=mask,mask=void 0;if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED)return;if(this._paused=!1,!this._receiver._writableState.needDrain)this._socket.resume()}send(data,options,cb){if(this.readyState===WebSocket.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof options==="function")cb=options,options={};if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}let opts={binary:typeof data!=="string",mask:!this._isServer,compress:!0,fin:!0,...options};if(!this._extensions[PerMessageDeflate.extensionName])opts.compress=!1;this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){abortHandshake(this,this._req,"WebSocket was closed before the connection was established");return}if(this._socket)this._readyState=WebSocket.CLOSING,this._socket.destroy()}}Object.defineProperty(WebSocket,"CONNECTING",{enumerable:!0,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket.prototype,"CONNECTING",{enumerable:!0,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket,"OPEN",{enumerable:!0,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket.prototype,"OPEN",{enumerable:!0,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket,"CLOSING",{enumerable:!0,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket.prototype,"CLOSING",{enumerable:!0,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket,"CLOSED",{enumerable:!0,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket.prototype,"CLOSED",{enumerable:!0,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((property)=>{Object.defineProperty(WebSocket.prototype,property,{enumerable:!0})});["open","error","close","message"].forEach((method)=>{Object.defineProperty(WebSocket.prototype,`on${method}`,{enumerable:!0,get(){for(let listener of this.listeners(method))if(listener[kForOnEventAttribute])return listener[kListener];return null},set(handler){for(let listener of this.listeners(method))if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}if(typeof handler!=="function")return;this.addEventListener(method,handler,{[kForOnEventAttribute]:!0})}})});WebSocket.prototype.addEventListener=addEventListener;WebSocket.prototype.removeEventListener=removeEventListener;module.exports=WebSocket;function initAsClient(websocket,address,protocols,options){let opts={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...options,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(websocket._autoPong=opts.autoPong,websocket._closeTimeout=opts.closeTimeout,!protocolVersions.includes(opts.protocolVersion))throw RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);let parsedUrl;if(address instanceof URL2)parsedUrl=address;else try{parsedUrl=new URL2(address)}catch{throw SyntaxError(`Invalid URL: ${address}`)}if(parsedUrl.protocol==="http:")parsedUrl.protocol="ws:";else if(parsedUrl.protocol==="https:")parsedUrl.protocol="wss:";websocket._url=parsedUrl.href;let isSecure=parsedUrl.protocol==="wss:",isIpcUrl=parsedUrl.protocol==="ws+unix:",invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl)invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;else if(isIpcUrl&&!parsedUrl.pathname)invalidUrlMessage="The URL's pathname is empty";else if(parsedUrl.hash)invalidUrlMessage="The URL contains a fragment identifier";if(invalidUrlMessage){let err=SyntaxError(invalidUrlMessage);if(websocket._redirects===0)throw err;else{emitErrorAndClose(websocket,err);return}}let defaultPort=isSecure?443:80,key=randomBytes(16).toString("base64"),request=isSecure?https.request:http.request,protocolSet=new Set,perMessageDeflate;if(opts.createConnection=opts.createConnection||(isSecure?tlsConnect:netConnect),opts.defaultPort=opts.defaultPort||defaultPort,opts.port=parsedUrl.port||defaultPort,opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname,opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"},opts.path=parsedUrl.pathname+parsedUrl.search,opts.timeout=opts.handshakeTimeout,opts.perMessageDeflate)perMessageDeflate=new PerMessageDeflate({...opts.perMessageDeflate,isServer:!1,maxPayload:opts.maxPayload}),opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate.extensionName]:perMessageDeflate.offer()});if(protocols.length){for(let protocol of protocols){if(typeof protocol!=="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol))throw SyntaxError("An invalid or duplicated subprotocol was specified");protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin)if(opts.protocolVersion<13)opts.headers["Sec-WebSocket-Origin"]=opts.origin;else opts.headers.Origin=opts.origin;if(parsedUrl.username||parsedUrl.password)opts.auth=`${parsedUrl.username}:${parsedUrl.password}`;if(isIpcUrl){let parts=opts.path.split(":");opts.socketPath=parts[0],opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl,websocket._originalSecure=isSecure,websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;let headers=options&&options.headers;if(options={...options,headers:{}},headers)for(let[key2,value]of Object.entries(headers))options.headers[key2.toLowerCase()]=value}else if(websocket.listenerCount("redirect")===0){let isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:!1:websocket._originalIpc?!1:parsedUrl.host===websocket._originalHostOrSocketPath;if(!isSameHost||websocket._originalSecure&&!isSecure){if(delete opts.headers.authorization,delete opts.headers.cookie,!isSameHost)delete opts.headers.host;opts.auth=void 0}}if(opts.auth&&!options.headers.authorization)options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64");if(req=websocket._req=request(opts),websocket._redirects)websocket.emit("redirect",websocket.url,req)}else req=websocket._req=request(opts);if(opts.timeout)req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")});if(req.on("error",(err)=>{if(req===null||req[kAborted])return;req=websocket._req=null,emitErrorAndClose(websocket,err)}),req.on("response",(res)=>{let location=res.headers.location,statusCode=res.statusCode;if(location&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location,address)}catch(e){let err=SyntaxError(`Invalid URL: ${location}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else if(!websocket.emit("unexpected-response",req,res))abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}),req.on("upgrade",(res,socket,head)=>{if(websocket.emit("upgrade",res),websocket.readyState!==WebSocket.CONNECTING)return;req=websocket._req=null;let upgrade=res.headers.upgrade;if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}let digest=createHash("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}let serverProt=res.headers["sec-websocket-protocol"],protError;if(serverProt!==void 0){if(!protocolSet.size)protError="Server sent a subprotocol but none was requested";else if(!protocolSet.has(serverProt))protError="Server sent an invalid subprotocol"}else if(protocolSet.size)protError="Server sent no subprotocol";if(protError){abortHandshake(websocket,socket,protError);return}if(serverProt)websocket._protocol=serverProt;let secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==void 0){if(!perMessageDeflate){abortHandshake(websocket,socket,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let extensions;try{extensions=parse(secWebSocketExtensions)}catch(err){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Extensions header");return}let extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate.extensionName){abortHandshake(websocket,socket,"Server indicated an extension that was not requested");return}try{perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName])}catch(err){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Extensions header");return}websocket._extensions[PerMessageDeflate.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})}),opts.finishRequest)opts.finishRequest(req,websocket);else req.end()}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket.CLOSING,websocket._errorEmitted=!0,websocket.emit("error",err),websocket.emitClose()}function netConnect(options){return options.path=options.socketPath,net.connect(options)}function tlsConnect(options){if(options.path=void 0,!options.servername&&options.servername!=="")options.servername=net.isIP(options.host)?"":options.host;return tls.connect(options)}function abortHandshake(websocket,stream,message){websocket._readyState=WebSocket.CLOSING;let err=Error(message);if(Error.captureStackTrace(err,abortHandshake),stream.setHeader){if(stream[kAborted]=!0,stream.abort(),stream.socket&&!stream.socket.destroyed)stream.socket.destroy();process.nextTick(emitErrorAndClose,websocket,err)}else stream.destroy(err),stream.once("error",websocket.emit.bind(websocket,"error")),stream.once("close",websocket.emitClose.bind(websocket))}function sendAfterClose(websocket,data,cb){if(data){let length=isBlob(data)?data.size:toBuffer(data).length;if(websocket._socket)websocket._sender._bufferedBytes+=length;else websocket._bufferedAmount+=length}if(cb){let err=Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){let websocket=this[kWebSocket];if(websocket._closeFrameReceived=!0,websocket._closeMessage=reason,websocket._closeCode=code,websocket._socket[kWebSocket]===void 0)return;if(websocket._socket.removeListener("data",socketOnData),process.nextTick(resume,websocket._socket),code===1005)websocket.close();else websocket.close(code,reason)}function receiverOnDrain(){let websocket=this[kWebSocket];if(!websocket.isPaused)websocket._socket.resume()}function receiverOnError(err){let websocket=this[kWebSocket];if(websocket._socket[kWebSocket]!==void 0)websocket._socket.removeListener("data",socketOnData),process.nextTick(resume,websocket._socket),websocket.close(err[kStatusCode]);if(!websocket._errorEmitted)websocket._errorEmitted=!0,websocket.emit("error",err)}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){let websocket=this[kWebSocket];if(websocket._autoPong)websocket.pong(data,!this._isServer,NOOP);websocket.emit("ping",data)}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream){stream.resume()}function senderOnError(err){let websocket=this[kWebSocket];if(websocket.readyState===WebSocket.CLOSED)return;if(websocket.readyState===WebSocket.OPEN)websocket._readyState=WebSocket.CLOSING,setCloseTimer(websocket);if(this._socket.end(),!websocket._errorEmitted)websocket._errorEmitted=!0,websocket.emit("error",err)}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),websocket._closeTimeout)}function socketOnClose(){let websocket=this[kWebSocket];if(this.removeListener("close",socketOnClose),this.removeListener("data",socketOnData),this.removeListener("end",socketOnEnd),websocket._readyState=WebSocket.CLOSING,!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){let chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}if(websocket._receiver.end(),this[kWebSocket]=void 0,clearTimeout(websocket._closeTimer),websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted)websocket.emitClose();else websocket._receiver.on("error",receiverOnFinish),websocket._receiver.on("finish",receiverOnFinish)}function socketOnData(chunk){if(!this[kWebSocket]._receiver.write(chunk))this.pause()}function socketOnEnd(){let websocket=this[kWebSocket];websocket._readyState=WebSocket.CLOSING,websocket._receiver.end(),this.end()}function socketOnError(){let websocket=this[kWebSocket];if(this.removeListener("error",socketOnError),this.on("error",NOOP),websocket)websocket._readyState=WebSocket.CLOSING,this.destroy()}});var require_stream=__commonJS((exports,module)=>{var WebSocket=require_websocket(),{Duplex}=__require("stream");function emitClose(stream){stream.emit("close")}function duplexOnEnd(){if(!this.destroyed&&this._writableState.finished)this.destroy()}function duplexOnError(err){if(this.removeListener("error",duplexOnError),this.destroy(),this.listenerCount("error")===0)this.emit("error",err)}function createWebSocketStream(ws,options){let terminateOnDestroy=!0,duplex=new Duplex({...options,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return ws.on("message",function(msg,isBinary){let data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;if(!duplex.push(data))ws.pause()}),ws.once("error",function(err){if(duplex.destroyed)return;terminateOnDestroy=!1,duplex.destroy(err)}),ws.once("close",function(){if(duplex.destroyed)return;duplex.push(null)}),duplex._destroy=function(err,callback){if(ws.readyState===ws.CLOSED){callback(err),process.nextTick(emitClose,duplex);return}let called=!1;if(ws.once("error",function(err2){called=!0,callback(err2)}),ws.once("close",function(){if(!called)callback(err);process.nextTick(emitClose,duplex)}),terminateOnDestroy)ws.terminate()},duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function(){duplex._final(callback)});return}if(ws._socket===null)return;if(ws._socket._writableState.finished){if(callback(),duplex._readableState.endEmitted)duplex.destroy()}else ws._socket.once("finish",function(){callback()}),ws.close()},duplex._read=function(){if(ws.isPaused)ws.resume()},duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)},duplex.on("end",duplexOnEnd),duplex.on("error",duplexOnError),duplex}module.exports=createWebSocketStream});var require_subprotocol=__commonJS((exports,module)=>{var{tokenChars}=require_validation();function parse(header){let protocols=new Set,start=-1,end=-1,i=0;for(i;i<header.length;i++){let code=header.charCodeAt(i);if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===44){if(start===-1)throw SyntaxError(`Unexpected character at index ${i}`);if(end===-1)end=i;let protocol2=header.slice(start,end);if(protocols.has(protocol2))throw SyntaxError(`The "${protocol2}" subprotocol is duplicated`);protocols.add(protocol2),start=end=-1}else throw SyntaxError(`Unexpected character at index ${i}`)}if(start===-1||end!==-1)throw SyntaxError("Unexpected end of input");let protocol=header.slice(start,i);if(protocols.has(protocol))throw SyntaxError(`The "${protocol}" subprotocol is duplicated`);return protocols.add(protocol),protocols}module.exports={parse}});var require_websocket_server=__commonJS((exports,module)=>{var EventEmitter=__require("events"),http=__require("http"),{Duplex}=__require("stream"),{createHash}=__require("crypto"),extension=require_extension(),PerMessageDeflate=require_permessage_deflate(),subprotocol=require_subprotocol(),WebSocket=require_websocket(),{CLOSE_TIMEOUT,GUID,kWebSocket}=require_constants(),keyRegex=/^[+/0-9A-Za-z]{22}==$/;class WebSocketServer extends EventEmitter{constructor(options,callback){super();if(options={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:CLOSE_TIMEOUT,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket,...options},options.port==null&&!options.server&&!options.noServer||options.port!=null&&(options.server||options.noServer)||options.server&&options.noServer)throw TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(options.port!=null)this._server=http.createServer((req,res)=>{let body=http.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"}),res.end(body)}),this._server.listen(options.port,options.host,options.backlog,callback);else if(options.server)this._server=options.server;if(this._server){let emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}if(options.perMessageDeflate===!0)options.perMessageDeflate={};if(options.clientTracking)this.clients=new Set,this._shouldEmitClose=!1;this.options=options,this._state=0}address(){if(this.options.noServer)throw Error('The server is operating in "noServer" mode');if(!this._server)return null;return this._server.address()}close(cb){if(this._state===2){if(cb)this.once("close",()=>{cb(Error("The server is not running"))});process.nextTick(emitClose,this);return}if(cb)this.once("close",cb);if(this._state===1)return;if(this._state=1,this.options.noServer||this.options.server){if(this._server)this._removeListeners(),this._removeListeners=this._server=null;if(this.clients)if(!this.clients.size)process.nextTick(emitClose,this);else this._shouldEmitClose=!0;else process.nextTick(emitClose,this)}else{let server=this._server;this._removeListeners(),this._removeListeners=this._server=null,server.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){let index=req.url.indexOf("?");if((index!==-1?req.url.slice(0,index):req.url)!==this.options.path)return!1}return!0}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);let key=req.headers["sec-websocket-key"],upgrade=req.headers.upgrade,version=+req.headers["sec-websocket-version"];if(req.method!=="GET"){abortHandshakeOrEmitwsClientError(this,req,socket,405,"Invalid HTTP method");return}if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshakeOrEmitwsClientError(this,req,socket,400,"Invalid Upgrade header");return}if(key===void 0||!keyRegex.test(key)){abortHandshakeOrEmitwsClientError(this,req,socket,400,"Missing or invalid Sec-WebSocket-Key header");return}if(version!==13&&version!==8){abortHandshakeOrEmitwsClientError(this,req,socket,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}let secWebSocketProtocol=req.headers["sec-websocket-protocol"],protocols=new Set;if(secWebSocketProtocol!==void 0)try{protocols=subprotocol.parse(secWebSocketProtocol)}catch(err){abortHandshakeOrEmitwsClientError(this,req,socket,400,"Invalid Sec-WebSocket-Protocol header");return}let secWebSocketExtensions=req.headers["sec-websocket-extensions"],extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==void 0){let perMessageDeflate=new PerMessageDeflate({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let offers=extension.parse(secWebSocketExtensions);if(offers[PerMessageDeflate.extensionName])perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]),extensions[PerMessageDeflate.extensionName]=perMessageDeflate}catch(err){abortHandshakeOrEmitwsClientError(this,req,socket,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let info={origin:req.headers[`${version===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified)return abortHandshake(socket,code||401,message,headers);this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}completeUpgrade(extensions,key,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket])throw Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return abortHandshake(socket,503);let headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${createHash("sha1").update(key+GUID).digest("base64")}`],ws=new this.options.WebSocket(null,void 0,this.options);if(protocols.size){let protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;if(protocol)headers.push(`Sec-WebSocket-Protocol: ${protocol}`),ws._protocol=protocol}if(extensions[PerMessageDeflate.extensionName]){let params=extensions[PerMessageDeflate.extensionName].params,value=extension.format({[PerMessageDeflate.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`),ws._extensions=extensions}if(this.emit("headers",headers,req),socket.write(headers.concat(`\r
106
+ `).join(`\r
107
+ `)),socket.removeListener("error",socketOnError),ws.setSocket(socket,head,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients)this.clients.add(ws),ws.on("close",()=>{if(this.clients.delete(ws),this._shouldEmitClose&&!this.clients.size)process.nextTick(emitClose,this)});cb(ws,req)}}module.exports=WebSocketServer;function addListeners(server,map){for(let event of Object.keys(map))server.on(event,map[event]);return function(){for(let event of Object.keys(map))server.removeListener(event,map[event])}}function emitClose(server){server._state=2,server.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(socket,code,message,headers){message=message||http.STATUS_CODES[code],headers={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(message),...headers},socket.once("finish",socket.destroy),socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
108
+ `+Object.keys(headers).map((h)=>`${h}: ${headers[h]}`).join(`\r
109
+ `)+`\r
110
+ \r
111
+ `+message)}function abortHandshakeOrEmitwsClientError(server,req,socket,code,message,headers){if(server.listenerCount("wsClientError")){let err=Error(message);Error.captureStackTrace(err,abortHandshakeOrEmitwsClientError),server.emit("wsClientError",err,socket,req)}else abortHandshake(socket,code,message,headers)}});var exports_wrapper={};__export(exports_wrapper,{subprotocol:()=>import_subprotocol.default,extension:()=>import_extension.default,default:()=>wrapper_default,createWebSocketStream:()=>import_stream.default,WebSocketServer:()=>import_websocket_server.default,WebSocket:()=>import_websocket.default,Sender:()=>import_sender.default,Receiver:()=>import_receiver.default,PerMessageDeflate:()=>import_permessage_deflate.default});var import_stream,import_extension,import_permessage_deflate,import_receiver,import_sender,import_subprotocol,import_websocket,import_websocket_server,wrapper_default;var init_wrapper=__esm(()=>{import_stream=__toESM(require_stream(),1),import_extension=__toESM(require_extension(),1),import_permessage_deflate=__toESM(require_permessage_deflate(),1),import_receiver=__toESM(require_receiver(),1),import_sender=__toESM(require_sender(),1),import_subprotocol=__toESM(require_subprotocol(),1),import_websocket=__toESM(require_websocket(),1),import_websocket_server=__toESM(require_websocket_server(),1),wrapper_default=import_websocket.default});var require_backend=__commonJS((exports,module)=>{(function(root,factory){if(typeof exports==="object"&&typeof module==="object")module.exports=factory();else if(typeof define==="function"&&define.amd)define([],factory);else if(typeof exports==="object")exports.ReactDevToolsBackend=factory();else root.ReactDevToolsBackend=factory()})(self,()=>{return(()=>{var __webpack_modules__={786:(__unused_webpack_module,exports2,__webpack_require__2)=>{var __webpack_unused_export__;function _typeof(o){return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},_typeof(o)}var ErrorStackParser=__webpack_require__2(206),React26=__webpack_require__2(189),assign=Object.assign,ReactSharedInternals=React26.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,REACT_CONTEXT_TYPE=Symbol.for("react.context"),REACT_MEMO_CACHE_SENTINEL=Symbol.for("react.memo_cache_sentinel"),hasOwnProperty=Object.prototype.hasOwnProperty,hookLog=[],primitiveStackCache=null;function getPrimitiveStackCache(){if(primitiveStackCache===null){var cache=new Map;try{if(Dispatcher.useContext({_currentValue:null}),Dispatcher.useState(null),Dispatcher.useReducer(function(s){return s},null),Dispatcher.useRef(null),typeof Dispatcher.useCacheRefresh==="function"&&Dispatcher.useCacheRefresh(),Dispatcher.useLayoutEffect(function(){}),Dispatcher.useInsertionEffect(function(){}),Dispatcher.useEffect(function(){}),Dispatcher.useImperativeHandle(void 0,function(){return null}),Dispatcher.useDebugValue(null),Dispatcher.useCallback(function(){}),Dispatcher.useTransition(),Dispatcher.useSyncExternalStore(function(){return function(){}},function(){return null},function(){return null}),Dispatcher.useDeferredValue(null),Dispatcher.useMemo(function(){return null}),Dispatcher.useOptimistic(null,function(s){return s}),Dispatcher.useFormState(function(s){return s},null),Dispatcher.useActionState(function(s){return s},null),Dispatcher.useHostTransitionStatus(),typeof Dispatcher.useMemoCache==="function"&&Dispatcher.useMemoCache(0),typeof Dispatcher.use==="function"){Dispatcher.use({$$typeof:REACT_CONTEXT_TYPE,_currentValue:null}),Dispatcher.use({then:function(){},status:"fulfilled",value:null});try{Dispatcher.use({then:function(){}})}catch(x){}}Dispatcher.useId(),typeof Dispatcher.useEffectEvent==="function"&&Dispatcher.useEffectEvent(function(){})}finally{var readHookLog=hookLog;hookLog=[]}for(var i=0;i<readHookLog.length;i++){var hook=readHookLog[i];cache.set(hook.primitive,ErrorStackParser.parse(hook.stackError))}primitiveStackCache=cache}return primitiveStackCache}var currentFiber=null,currentHook=null,currentContextDependency=null,currentThenableIndex=0,currentThenableState=null;function nextHook(){var hook=currentHook;return hook!==null&&(currentHook=hook.next),hook}function readContext(context){if(currentFiber===null)return context._currentValue;if(currentContextDependency===null)throw Error("Context reads do not line up with context dependencies. This is a bug in React Debug Tools.");return hasOwnProperty.call(currentContextDependency,"memoizedValue")?(context=currentContextDependency.memoizedValue,currentContextDependency=currentContextDependency.next):context=context._currentValue,context}var SuspenseException=Error("Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`."),Dispatcher={readContext,use:function(usable){if(usable!==null&&_typeof(usable)==="object"){if(typeof usable.then==="function"){switch(usable=currentThenableState!==null&&currentThenableIndex<currentThenableState.length?currentThenableState[currentThenableIndex++]:usable,usable.status){case"fulfilled":var fulfilledValue=usable.value;return hookLog.push({displayName:null,primitive:"Promise",stackError:Error(),value:fulfilledValue,debugInfo:usable._debugInfo===void 0?null:usable._debugInfo,dispatcherHookName:"Use"}),fulfilledValue;case"rejected":throw usable.reason}throw hookLog.push({displayName:null,primitive:"Unresolved",stackError:Error(),value:usable,debugInfo:usable._debugInfo===void 0?null:usable._debugInfo,dispatcherHookName:"Use"}),SuspenseException}if(usable.$$typeof===REACT_CONTEXT_TYPE)return fulfilledValue=readContext(usable),hookLog.push({displayName:usable.displayName||"Context",primitive:"Context (use)",stackError:Error(),value:fulfilledValue,debugInfo:null,dispatcherHookName:"Use"}),fulfilledValue}throw Error("An unsupported type was passed to use(): "+String(usable))},useCallback:function(callback){var hook=nextHook();return hookLog.push({displayName:null,primitive:"Callback",stackError:Error(),value:hook!==null?hook.memoizedState[0]:callback,debugInfo:null,dispatcherHookName:"Callback"}),callback},useContext:function(context){var value=readContext(context);return hookLog.push({displayName:context.displayName||null,primitive:"Context",stackError:Error(),value,debugInfo:null,dispatcherHookName:"Context"}),value},useEffect:function(create){nextHook(),hookLog.push({displayName:null,primitive:"Effect",stackError:Error(),value:create,debugInfo:null,dispatcherHookName:"Effect"})},useImperativeHandle:function(ref){nextHook();var instance=void 0;ref!==null&&_typeof(ref)==="object"&&(instance=ref.current),hookLog.push({displayName:null,primitive:"ImperativeHandle",stackError:Error(),value:instance,debugInfo:null,dispatcherHookName:"ImperativeHandle"})},useLayoutEffect:function(create){nextHook(),hookLog.push({displayName:null,primitive:"LayoutEffect",stackError:Error(),value:create,debugInfo:null,dispatcherHookName:"LayoutEffect"})},useInsertionEffect:function(create){nextHook(),hookLog.push({displayName:null,primitive:"InsertionEffect",stackError:Error(),value:create,debugInfo:null,dispatcherHookName:"InsertionEffect"})},useMemo:function(nextCreate){var hook=nextHook();return nextCreate=hook!==null?hook.memoizedState[0]:nextCreate(),hookLog.push({displayName:null,primitive:"Memo",stackError:Error(),value:nextCreate,debugInfo:null,dispatcherHookName:"Memo"}),nextCreate},useReducer:function(reducer,initialArg,init){return reducer=nextHook(),initialArg=reducer!==null?reducer.memoizedState:init!==void 0?init(initialArg):initialArg,hookLog.push({displayName:null,primitive:"Reducer",stackError:Error(),value:initialArg,debugInfo:null,dispatcherHookName:"Reducer"}),[initialArg,function(){}]},useRef:function(initialValue){var hook=nextHook();return initialValue=hook!==null?hook.memoizedState:{current:initialValue},hookLog.push({displayName:null,primitive:"Ref",stackError:Error(),value:initialValue.current,debugInfo:null,dispatcherHookName:"Ref"}),initialValue},useState:function(initialState){var hook=nextHook();return initialState=hook!==null?hook.memoizedState:typeof initialState==="function"?initialState():initialState,hookLog.push({displayName:null,primitive:"State",stackError:Error(),value:initialState,debugInfo:null,dispatcherHookName:"State"}),[initialState,function(){}]},useDebugValue:function(value,formatterFn){hookLog.push({displayName:null,primitive:"DebugValue",stackError:Error(),value:typeof formatterFn==="function"?formatterFn(value):value,debugInfo:null,dispatcherHookName:"DebugValue"})},useDeferredValue:function(value){var hook=nextHook();return value=hook!==null?hook.memoizedState:value,hookLog.push({displayName:null,primitive:"DeferredValue",stackError:Error(),value,debugInfo:null,dispatcherHookName:"DeferredValue"}),value},useTransition:function(){var stateHook=nextHook();return nextHook(),stateHook=stateHook!==null?stateHook.memoizedState:!1,hookLog.push({displayName:null,primitive:"Transition",stackError:Error(),value:stateHook,debugInfo:null,dispatcherHookName:"Transition"}),[stateHook,function(){}]},useSyncExternalStore:function(subscribe,getSnapshot){return nextHook(),nextHook(),subscribe=getSnapshot(),hookLog.push({displayName:null,primitive:"SyncExternalStore",stackError:Error(),value:subscribe,debugInfo:null,dispatcherHookName:"SyncExternalStore"}),subscribe},useId:function(){var hook=nextHook();return hook=hook!==null?hook.memoizedState:"",hookLog.push({displayName:null,primitive:"Id",stackError:Error(),value:hook,debugInfo:null,dispatcherHookName:"Id"}),hook},useHostTransitionStatus:function(){var status=readContext({_currentValue:null});return hookLog.push({displayName:null,primitive:"HostTransitionStatus",stackError:Error(),value:status,debugInfo:null,dispatcherHookName:"HostTransitionStatus"}),status},useFormState:function(action,initialState){var hook=nextHook();nextHook(),nextHook(),action=Error();var debugInfo=null,error=null;if(hook!==null)if(initialState=hook.memoizedState,_typeof(initialState)==="object"&&initialState!==null&&typeof initialState.then==="function")switch(initialState.status){case"fulfilled":var value=initialState.value;debugInfo=initialState._debugInfo===void 0?null:initialState._debugInfo;break;case"rejected":error=initialState.reason;break;default:error=SuspenseException,debugInfo=initialState._debugInfo===void 0?null:initialState._debugInfo,value=initialState}else value=initialState;else value=initialState;if(hookLog.push({displayName:null,primitive:"FormState",stackError:action,value,debugInfo,dispatcherHookName:"FormState"}),error!==null)throw error;return[value,function(){},!1]},useActionState:function(action,initialState){var hook=nextHook();nextHook(),nextHook(),action=Error();var debugInfo=null,error=null;if(hook!==null)if(initialState=hook.memoizedState,_typeof(initialState)==="object"&&initialState!==null&&typeof initialState.then==="function")switch(initialState.status){case"fulfilled":var value=initialState.value;debugInfo=initialState._debugInfo===void 0?null:initialState._debugInfo;break;case"rejected":error=initialState.reason;break;default:error=SuspenseException,debugInfo=initialState._debugInfo===void 0?null:initialState._debugInfo,value=initialState}else value=initialState;else value=initialState;if(hookLog.push({displayName:null,primitive:"ActionState",stackError:action,value,debugInfo,dispatcherHookName:"ActionState"}),error!==null)throw error;return[value,function(){},!1]},useOptimistic:function(passthrough){var hook=nextHook();return passthrough=hook!==null?hook.memoizedState:passthrough,hookLog.push({displayName:null,primitive:"Optimistic",stackError:Error(),value:passthrough,debugInfo:null,dispatcherHookName:"Optimistic"}),[passthrough,function(){}]},useMemoCache:function(size){var fiber=currentFiber;if(fiber==null)return[];if(fiber=fiber.updateQueue!=null?fiber.updateQueue.memoCache:null,fiber==null)return[];var data=fiber.data[fiber.index];if(data===void 0){data=fiber.data[fiber.index]=Array(size);for(var i=0;i<size;i++)data[i]=REACT_MEMO_CACHE_SENTINEL}return fiber.index++,data},useCacheRefresh:function(){var hook=nextHook();return hookLog.push({displayName:null,primitive:"CacheRefresh",stackError:Error(),value:hook!==null?hook.memoizedState:function(){},debugInfo:null,dispatcherHookName:"CacheRefresh"}),function(){}},useEffectEvent:function(callback){return nextHook(),hookLog.push({displayName:null,primitive:"EffectEvent",stackError:Error(),value:callback,debugInfo:null,dispatcherHookName:"EffectEvent"}),callback}},DispatcherProxyHandler={get:function(target,prop){if(target.hasOwnProperty(prop))return target[prop];throw target=Error("Missing method in Dispatcher: "+prop),target.name="ReactDebugToolsUnsupportedHookError",target}},DispatcherProxy=typeof Proxy>"u"?Dispatcher:new Proxy(Dispatcher,DispatcherProxyHandler),mostLikelyAncestorIndex=0;function findSharedIndex(hookStack,rootStack,rootIndex){var source=rootStack[rootIndex].source,i=0;a:for(;i<hookStack.length;i++)if(hookStack[i].source===source){for(var a=rootIndex+1,b=i+1;a<rootStack.length&&b<hookStack.length;a++,b++)if(hookStack[b].source!==rootStack[a].source)continue a;return i}return-1}function isReactWrapper(functionName,wrapperName){return functionName=parseHookName(functionName),wrapperName==="HostTransitionStatus"?functionName===wrapperName||functionName==="FormStatus":functionName===wrapperName}function parseHookName(functionName){if(!functionName)return"";var startIndex=functionName.lastIndexOf("[as ");if(startIndex!==-1)return parseHookName(functionName.slice(startIndex+4,-1));if(startIndex=functionName.lastIndexOf("."),startIndex=startIndex===-1?0:startIndex+1,functionName.slice(startIndex).startsWith("unstable_")&&(startIndex+=9),functionName.slice(startIndex).startsWith("experimental_")&&(startIndex+=13),functionName.slice(startIndex,startIndex+3)==="use"){if(functionName.length-startIndex===3)return"Use";startIndex+=3}return functionName.slice(startIndex)}function buildTree(rootStack$jscomp$0,readHookLog){for(var rootChildren=[],prevStack=null,levelChildren=rootChildren,nativeHookID=0,stackOfChildren=[],i=0;i<readHookLog.length;i++){var hook=readHookLog[i],rootStack=rootStack$jscomp$0,JSCompiler_inline_result=ErrorStackParser.parse(hook.stackError);b:{var hookStack=JSCompiler_inline_result,rootIndex=findSharedIndex(hookStack,rootStack,mostLikelyAncestorIndex);if(rootIndex!==-1)rootStack=rootIndex;else{for(var i$jscomp$0=0;i$jscomp$0<rootStack.length&&5>i$jscomp$0;i$jscomp$0++)if(rootIndex=findSharedIndex(hookStack,rootStack,i$jscomp$0),rootIndex!==-1){mostLikelyAncestorIndex=i$jscomp$0,rootStack=rootIndex;break b}rootStack=-1}}b:{if(hookStack=JSCompiler_inline_result,rootIndex=getPrimitiveStackCache().get(hook.primitive),rootIndex!==void 0){for(i$jscomp$0=0;i$jscomp$0<rootIndex.length&&i$jscomp$0<hookStack.length;i$jscomp$0++)if(rootIndex[i$jscomp$0].source!==hookStack[i$jscomp$0].source){i$jscomp$0<hookStack.length-1&&isReactWrapper(hookStack[i$jscomp$0].functionName,hook.dispatcherHookName)&&i$jscomp$0++,i$jscomp$0<hookStack.length-1&&isReactWrapper(hookStack[i$jscomp$0].functionName,hook.dispatcherHookName)&&i$jscomp$0++,hookStack=i$jscomp$0;break b}}hookStack=-1}if(JSCompiler_inline_result=rootStack===-1||hookStack===-1||2>rootStack-hookStack?hookStack===-1?[null,null]:[JSCompiler_inline_result[hookStack-1],null]:[JSCompiler_inline_result[hookStack-1],JSCompiler_inline_result.slice(hookStack,rootStack-1)],hookStack=JSCompiler_inline_result[0],JSCompiler_inline_result=JSCompiler_inline_result[1],rootStack=hook.displayName,rootStack===null&&hookStack!==null&&(rootStack=parseHookName(hookStack.functionName)||parseHookName(hook.dispatcherHookName)),JSCompiler_inline_result!==null){if(hookStack=0,prevStack!==null){for(;hookStack<JSCompiler_inline_result.length&&hookStack<prevStack.length&&JSCompiler_inline_result[JSCompiler_inline_result.length-hookStack-1].source===prevStack[prevStack.length-hookStack-1].source;)hookStack++;for(prevStack=prevStack.length-1;prevStack>hookStack;prevStack--)levelChildren=stackOfChildren.pop()}for(prevStack=JSCompiler_inline_result.length-hookStack-1;1<=prevStack;prevStack--)hookStack=[],rootIndex=JSCompiler_inline_result[prevStack],rootIndex={id:null,isStateEditable:!1,name:parseHookName(JSCompiler_inline_result[prevStack-1].functionName),value:void 0,subHooks:hookStack,debugInfo:null,hookSource:{lineNumber:rootIndex.lineNumber===void 0?null:rootIndex.lineNumber,columnNumber:rootIndex.columnNumber===void 0?null:rootIndex.columnNumber,functionName:rootIndex.functionName===void 0?null:rootIndex.functionName,fileName:rootIndex.fileName===void 0?null:rootIndex.fileName}},levelChildren.push(rootIndex),stackOfChildren.push(levelChildren),levelChildren=hookStack;prevStack=JSCompiler_inline_result}hookStack=hook.primitive,rootIndex=hook.debugInfo,hook={id:hookStack==="Context"||hookStack==="Context (use)"||hookStack==="DebugValue"||hookStack==="Promise"||hookStack==="Unresolved"||hookStack==="HostTransitionStatus"?null:nativeHookID++,isStateEditable:hookStack==="Reducer"||hookStack==="State",name:rootStack||hookStack,value:hook.value,subHooks:[],debugInfo:rootIndex,hookSource:null},rootStack={lineNumber:null,functionName:null,fileName:null,columnNumber:null},JSCompiler_inline_result&&1<=JSCompiler_inline_result.length&&(JSCompiler_inline_result=JSCompiler_inline_result[0],rootStack.lineNumber=JSCompiler_inline_result.lineNumber===void 0?null:JSCompiler_inline_result.lineNumber,rootStack.functionName=JSCompiler_inline_result.functionName===void 0?null:JSCompiler_inline_result.functionName,rootStack.fileName=JSCompiler_inline_result.fileName===void 0?null:JSCompiler_inline_result.fileName,rootStack.columnNumber=JSCompiler_inline_result.columnNumber===void 0?null:JSCompiler_inline_result.columnNumber),hook.hookSource=rootStack,levelChildren.push(hook)}return processDebugValues(rootChildren,null),rootChildren}function processDebugValues(hooksTree,parentHooksNode){for(var debugValueHooksNodes=[],i=0;i<hooksTree.length;i++){var hooksNode=hooksTree[i];hooksNode.name==="DebugValue"&&hooksNode.subHooks.length===0?(hooksTree.splice(i,1),i--,debugValueHooksNodes.push(hooksNode)):processDebugValues(hooksNode.subHooks,hooksNode)}parentHooksNode!==null&&(debugValueHooksNodes.length===1?parentHooksNode.value=debugValueHooksNodes[0].value:1<debugValueHooksNodes.length&&(parentHooksNode.value=debugValueHooksNodes.map(function(_ref){return _ref.value})))}function handleRenderFunctionError(error){if(error!==SuspenseException){if(error instanceof Error&&error.name==="ReactDebugToolsUnsupportedHookError")throw error;var wrapperError=Error("Error rendering inspected component",{cause:error});throw wrapperError.name="ReactDebugToolsRenderError",wrapperError.cause=error,wrapperError}}function inspectHooks(renderFunction,props,currentDispatcher){currentDispatcher==null&&(currentDispatcher=ReactSharedInternals);var previousDispatcher=currentDispatcher.H;currentDispatcher.H=DispatcherProxy;try{var ancestorStackError=Error();renderFunction(props)}catch(error){handleRenderFunctionError(error)}finally{renderFunction=hookLog,hookLog=[],currentDispatcher.H=previousDispatcher}return currentDispatcher=ancestorStackError===void 0?[]:ErrorStackParser.parse(ancestorStackError),buildTree(currentDispatcher,renderFunction)}function restoreContexts(contextMap){contextMap.forEach(function(value,context){return context._currentValue=value})}__webpack_unused_export__=inspectHooks,exports2.inspectHooksOfFiber=function(fiber,currentDispatcher){if(currentDispatcher==null&&(currentDispatcher=ReactSharedInternals),fiber.tag!==0&&fiber.tag!==15&&fiber.tag!==11)throw Error("Unknown Fiber. Needs to be a function component to inspect hooks.");getPrimitiveStackCache(),currentHook=fiber.memoizedState,currentFiber=fiber;var thenableState=fiber.dependencies&&fiber.dependencies._debugThenableState;if(thenableState=thenableState?thenableState.thenables||thenableState:null,currentThenableState=Array.isArray(thenableState)?thenableState:null,currentThenableIndex=0,hasOwnProperty.call(currentFiber,"dependencies"))thenableState=currentFiber.dependencies,currentContextDependency=thenableState!==null?thenableState.firstContext:null;else if(hasOwnProperty.call(currentFiber,"dependencies_old"))thenableState=currentFiber.dependencies_old,currentContextDependency=thenableState!==null?thenableState.firstContext:null;else if(hasOwnProperty.call(currentFiber,"dependencies_new"))thenableState=currentFiber.dependencies_new,currentContextDependency=thenableState!==null?thenableState.firstContext:null;else if(hasOwnProperty.call(currentFiber,"contextDependencies"))thenableState=currentFiber.contextDependencies,currentContextDependency=thenableState!==null?thenableState.first:null;else throw Error("Unsupported React version. This is a bug in React Debug Tools.");thenableState=fiber.type;var props=fiber.memoizedProps;if(thenableState!==fiber.elementType&&thenableState&&thenableState.defaultProps){props=assign({},props);var defaultProps=thenableState.defaultProps;for(propName in defaultProps)props[propName]===void 0&&(props[propName]=defaultProps[propName])}var propName=new Map;try{if(currentContextDependency!==null&&!hasOwnProperty.call(currentContextDependency,"memoizedValue"))for(defaultProps=fiber;defaultProps;){if(defaultProps.tag===10){var context=defaultProps.type;context._context!==void 0&&(context=context._context),propName.has(context)||(propName.set(context,context._currentValue),context._currentValue=defaultProps.memoizedProps.value)}defaultProps=defaultProps.return}if(fiber.tag===11){var renderFunction=thenableState.render;context=props;var ref=fiber.ref;fiber=currentDispatcher;var previousDispatcher=fiber.H;fiber.H=DispatcherProxy;try{var ancestorStackError=Error();renderFunction(context,ref)}catch(error){handleRenderFunctionError(error)}finally{var readHookLog=hookLog;hookLog=[],fiber.H=previousDispatcher}var rootStack=ancestorStackError===void 0?[]:ErrorStackParser.parse(ancestorStackError);return buildTree(rootStack,readHookLog)}return inspectHooks(thenableState,props,currentDispatcher)}finally{currentThenableState=currentContextDependency=currentHook=currentFiber=null,currentThenableIndex=0,restoreContexts(propName)}}},987:(module2,__unused_webpack_exports,__webpack_require__2)=>{module2.exports=__webpack_require__2(786)},126:(__unused_webpack_module,exports2,__webpack_require__2)=>{var process2=__webpack_require__2(169);function _typeof(o){return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},_typeof(o)}var REACT_ELEMENT_TYPE=Symbol.for("react.transitional.element"),REACT_PORTAL_TYPE=Symbol.for("react.portal"),REACT_FRAGMENT_TYPE=Symbol.for("react.fragment"),REACT_STRICT_MODE_TYPE=Symbol.for("react.strict_mode"),REACT_PROFILER_TYPE=Symbol.for("react.profiler"),REACT_CONSUMER_TYPE=Symbol.for("react.consumer"),REACT_CONTEXT_TYPE=Symbol.for("react.context"),REACT_FORWARD_REF_TYPE=Symbol.for("react.forward_ref"),REACT_SUSPENSE_TYPE=Symbol.for("react.suspense"),REACT_SUSPENSE_LIST_TYPE=Symbol.for("react.suspense_list"),REACT_MEMO_TYPE=Symbol.for("react.memo"),REACT_LAZY_TYPE=Symbol.for("react.lazy"),REACT_ACTIVITY_TYPE=Symbol.for("react.activity"),REACT_POSTPONE_TYPE=Symbol.for("react.postpone"),REACT_VIEW_TRANSITION_TYPE=Symbol.for("react.view_transition"),MAYBE_ITERATOR_SYMBOL=Symbol.iterator;function getIteratorFn(maybeIterable){if(maybeIterable===null||_typeof(maybeIterable)!=="object")return null;return maybeIterable=MAYBE_ITERATOR_SYMBOL&&maybeIterable[MAYBE_ITERATOR_SYMBOL]||maybeIterable["@@iterator"],typeof maybeIterable==="function"?maybeIterable:null}var ReactNoopUpdateQueue={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},assign=Object.assign,emptyObject={};function Component3(props,context,updater){this.props=props,this.context=context,this.refs=emptyObject,this.updater=updater||ReactNoopUpdateQueue}Component3.prototype.isReactComponent={},Component3.prototype.setState=function(partialState,callback){if(_typeof(partialState)!=="object"&&typeof partialState!=="function"&&partialState!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,partialState,callback,"setState")},Component3.prototype.forceUpdate=function(callback){this.updater.enqueueForceUpdate(this,callback,"forceUpdate")};function ComponentDummy(){}ComponentDummy.prototype=Component3.prototype;function PureComponent(props,context,updater){this.props=props,this.context=context,this.refs=emptyObject,this.updater=updater||ReactNoopUpdateQueue}var pureComponentPrototype=PureComponent.prototype=new ComponentDummy;pureComponentPrototype.constructor=PureComponent,assign(pureComponentPrototype,Component3.prototype),pureComponentPrototype.isPureReactComponent=!0;var isArrayImpl=Array.isArray;function noop(){}var ReactSharedInternals={H:null,A:null,T:null,S:null,G:null},hasOwnProperty=Object.prototype.hasOwnProperty;function ReactElement(type,key,props){var refProp=props.ref;return{$$typeof:REACT_ELEMENT_TYPE,type,key,ref:refProp!==void 0?refProp:null,props}}function cloneAndReplaceKey(oldElement,newKey){return ReactElement(oldElement.type,newKey,oldElement.props)}function isValidElement3(object){return _typeof(object)==="object"&&object!==null&&object.$$typeof===REACT_ELEMENT_TYPE}function escape(key){var escaperLookup={"=":"=0",":":"=2"};return"$"+key.replace(/[=:]/g,function(match){return escaperLookup[match]})}var userProvidedKeyEscapeRegex=/\/+/g;function getElementKey(element,index){return _typeof(element)==="object"&&element!==null&&element.key!=null?escape(""+element.key):index.toString(36)}function resolveThenable(thenable){switch(thenable.status){case"fulfilled":return thenable.value;case"rejected":throw thenable.reason;default:switch(typeof thenable.status==="string"?thenable.then(noop,noop):(thenable.status="pending",thenable.then(function(fulfilledValue){thenable.status==="pending"&&(thenable.status="fulfilled",thenable.value=fulfilledValue)},function(error){thenable.status==="pending"&&(thenable.status="rejected",thenable.reason=error)})),thenable.status){case"fulfilled":return thenable.value;case"rejected":throw thenable.reason}}throw thenable}function mapIntoArray(children,array,escapedPrefix,nameSoFar,callback){var type=_typeof(children);if(type==="undefined"||type==="boolean")children=null;var invokeCallback=!1;if(children===null)invokeCallback=!0;else switch(type){case"bigint":case"string":case"number":invokeCallback=!0;break;case"object":switch(children.$$typeof){case REACT_ELEMENT_TYPE:case REACT_PORTAL_TYPE:invokeCallback=!0;break;case REACT_LAZY_TYPE:return invokeCallback=children._init,mapIntoArray(invokeCallback(children._payload),array,escapedPrefix,nameSoFar,callback)}}if(invokeCallback)return callback=callback(children),invokeCallback=nameSoFar===""?"."+getElementKey(children,0):nameSoFar,isArrayImpl(callback)?(escapedPrefix="",invokeCallback!=null&&(escapedPrefix=invokeCallback.replace(userProvidedKeyEscapeRegex,"$&/")+"/"),mapIntoArray(callback,array,escapedPrefix,"",function(c){return c})):callback!=null&&(isValidElement3(callback)&&(callback=cloneAndReplaceKey(callback,escapedPrefix+(callback.key==null||children&&children.key===callback.key?"":(""+callback.key).replace(userProvidedKeyEscapeRegex,"$&/")+"/")+invokeCallback)),array.push(callback)),1;invokeCallback=0;var nextNamePrefix=nameSoFar===""?".":nameSoFar+":";if(isArrayImpl(children))for(var i=0;i<children.length;i++)nameSoFar=children[i],type=nextNamePrefix+getElementKey(nameSoFar,i),invokeCallback+=mapIntoArray(nameSoFar,array,escapedPrefix,type,callback);else if(i=getIteratorFn(children),typeof i==="function")for(children=i.call(children),i=0;!(nameSoFar=children.next()).done;)nameSoFar=nameSoFar.value,type=nextNamePrefix+getElementKey(nameSoFar,i++),invokeCallback+=mapIntoArray(nameSoFar,array,escapedPrefix,type,callback);else if(type==="object"){if(typeof children.then==="function")return mapIntoArray(resolveThenable(children),array,escapedPrefix,nameSoFar,callback);throw array=String(children),Error("Objects are not valid as a React child (found: "+(array==="[object Object]"?"object with keys {"+Object.keys(children).join(", ")+"}":array)+"). If you meant to render a collection of children, use an array instead.")}return invokeCallback}function mapChildren(children,func,context){if(children==null)return children;var result=[],count=0;return mapIntoArray(children,result,"","",function(child){return func.call(context,child,count++)}),result}function lazyInitializer(payload){if(payload._status===-1){var ctor=payload._result;ctor=ctor(),ctor.then(function(moduleObject){if(payload._status===0||payload._status===-1)payload._status=1,payload._result=moduleObject},function(error){if(payload._status===0||payload._status===-1)payload._status=2,payload._result=error}),payload._status===-1&&(payload._status=0,payload._result=ctor)}if(payload._status===1)return payload._result.default;throw payload._result}function useOptimistic(passthrough,reducer){return ReactSharedInternals.H.useOptimistic(passthrough,reducer)}var reportGlobalError=typeof reportError==="function"?reportError:function(error){if((typeof window>"u"?"undefined":_typeof(window))==="object"&&typeof window.ErrorEvent==="function"){var event=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:_typeof(error)==="object"&&error!==null&&typeof error.message==="string"?String(error.message):String(error),error});if(!window.dispatchEvent(event))return}else if((typeof process2>"u"?"undefined":_typeof(process2))==="object"&&typeof process2.emit==="function"){process2.emit("uncaughtException",error);return}console.error(error)};function startTransition(scope){var prevTransition=ReactSharedInternals.T,currentTransition={};currentTransition.types=prevTransition!==null?prevTransition.types:null,currentTransition.gesture=null,ReactSharedInternals.T=currentTransition;try{var returnValue=scope(),onStartTransitionFinish=ReactSharedInternals.S;onStartTransitionFinish!==null&&onStartTransitionFinish(currentTransition,returnValue),_typeof(returnValue)==="object"&&returnValue!==null&&typeof returnValue.then==="function"&&returnValue.then(noop,reportGlobalError)}catch(error){reportGlobalError(error)}finally{prevTransition!==null&&currentTransition.types!==null&&(prevTransition.types=currentTransition.types),ReactSharedInternals.T=prevTransition}}function addTransitionType(type){var transition=ReactSharedInternals.T;if(transition!==null){var transitionTypes=transition.types;transitionTypes===null?transition.types=[type]:transitionTypes.indexOf(type)===-1&&transitionTypes.push(type)}else startTransition(addTransitionType.bind(null,type))}var Children3={map:mapChildren,forEach:function(children,forEachFunc,forEachContext){mapChildren(children,function(){forEachFunc.apply(this,arguments)},forEachContext)},count:function(children){var n=0;return mapChildren(children,function(){n++}),n},toArray:function(children){return mapChildren(children,function(child){return child})||[]},only:function(children){if(!isValidElement3(children))throw Error("React.Children.only expected to receive a single React element child.");return children}};exports2.Activity=REACT_ACTIVITY_TYPE,exports2.Children=Children3,exports2.Component=Component3,exports2.Fragment=REACT_FRAGMENT_TYPE,exports2.Profiler=REACT_PROFILER_TYPE,exports2.PureComponent=PureComponent,exports2.StrictMode=REACT_STRICT_MODE_TYPE,exports2.Suspense=REACT_SUSPENSE_TYPE,exports2.ViewTransition=REACT_VIEW_TRANSITION_TYPE,exports2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=ReactSharedInternals,exports2.__COMPILER_RUNTIME={__proto__:null,c:function(size){return ReactSharedInternals.H.useMemoCache(size)}},exports2.addTransitionType=addTransitionType,exports2.cache=function(fn){return function(){return fn.apply(null,arguments)}},exports2.cacheSignal=function(){return null},exports2.cloneElement=function(element,config,children){if(element===null||element===void 0)throw Error("The argument must be a React element, but you passed "+element+".");var props=assign({},element.props),key=element.key;if(config!=null)for(propName in config.key!==void 0&&(key=""+config.key),config)!hasOwnProperty.call(config,propName)||propName==="key"||propName==="__self"||propName==="__source"||propName==="ref"&&config.ref===void 0||(props[propName]=config[propName]);var propName=arguments.length-2;if(propName===1)props.children=children;else if(1<propName){for(var childArray=Array(propName),i=0;i<propName;i++)childArray[i]=arguments[i+2];props.children=childArray}return ReactElement(element.type,key,props)},exports2.createContext=function(defaultValue){return defaultValue={$$typeof:REACT_CONTEXT_TYPE,_currentValue:defaultValue,_currentValue2:defaultValue,_threadCount:0,Provider:null,Consumer:null},defaultValue.Provider=defaultValue,defaultValue.Consumer={$$typeof:REACT_CONSUMER_TYPE,_context:defaultValue},defaultValue},exports2.createElement=function(type,config,children){var propName,props={},key=null;if(config!=null)for(propName in config.key!==void 0&&(key=""+config.key),config)hasOwnProperty.call(config,propName)&&propName!=="key"&&propName!=="__self"&&propName!=="__source"&&(props[propName]=config[propName]);var childrenLength=arguments.length-2;if(childrenLength===1)props.children=children;else if(1<childrenLength){for(var childArray=Array(childrenLength),i=0;i<childrenLength;i++)childArray[i]=arguments[i+2];props.children=childArray}if(type&&type.defaultProps)for(propName in childrenLength=type.defaultProps,childrenLength)props[propName]===void 0&&(props[propName]=childrenLength[propName]);return ReactElement(type,key,props)},exports2.createRef=function(){return{current:null}},exports2.experimental_useOptimistic=function(passthrough,reducer){return useOptimistic(passthrough,reducer)},exports2.forwardRef=function(render){return{$$typeof:REACT_FORWARD_REF_TYPE,render}},exports2.isValidElement=isValidElement3,exports2.lazy=function(ctor){return{$$typeof:REACT_LAZY_TYPE,_payload:{_status:-1,_result:ctor},_init:lazyInitializer}},exports2.memo=function(type,compare){return{$$typeof:REACT_MEMO_TYPE,type,compare:compare===void 0?null:compare}},exports2.startTransition=startTransition,exports2.unstable_Activity=REACT_ACTIVITY_TYPE,exports2.unstable_SuspenseList=REACT_SUSPENSE_LIST_TYPE,exports2.unstable_getCacheForType=function(resourceType){var dispatcher=ReactSharedInternals.A;return dispatcher?dispatcher.getCacheForType(resourceType):resourceType()},exports2.unstable_postpone=function(reason){throw reason=Error(reason),reason.$$typeof=REACT_POSTPONE_TYPE,reason},exports2.unstable_startGestureTransition=function(provider,scope,options){if(provider==null)throw Error("A Timeline is required as the first argument to startGestureTransition.");var prevTransition=ReactSharedInternals.T,currentTransition={types:null};currentTransition.gesture=provider,ReactSharedInternals.T=currentTransition;try{scope();var onStartGestureTransitionFinish=ReactSharedInternals.G;if(onStartGestureTransitionFinish!==null)return onStartGestureTransitionFinish(currentTransition,provider,options)}catch(error){reportGlobalError(error)}finally{ReactSharedInternals.T=prevTransition}return noop},exports2.unstable_useCacheRefresh=function(){return ReactSharedInternals.H.useCacheRefresh()},exports2.use=function(usable){return ReactSharedInternals.H.use(usable)},exports2.useActionState=function(action,initialState,permalink){return ReactSharedInternals.H.useActionState(action,initialState,permalink)},exports2.useCallback=function(callback,deps){return ReactSharedInternals.H.useCallback(callback,deps)},exports2.useContext=function(Context){return ReactSharedInternals.H.useContext(Context)},exports2.useDebugValue=function(){},exports2.useDeferredValue=function(value,initialValue){return ReactSharedInternals.H.useDeferredValue(value,initialValue)},exports2.useEffect=function(create,deps){return ReactSharedInternals.H.useEffect(create,deps)},exports2.useEffectEvent=function(callback){return ReactSharedInternals.H.useEffectEvent(callback)},exports2.useId=function(){return ReactSharedInternals.H.useId()},exports2.useImperativeHandle=function(ref,create,deps){return ReactSharedInternals.H.useImperativeHandle(ref,create,deps)},exports2.useInsertionEffect=function(create,deps){return ReactSharedInternals.H.useInsertionEffect(create,deps)},exports2.useLayoutEffect=function(create,deps){return ReactSharedInternals.H.useLayoutEffect(create,deps)},exports2.useMemo=function(create,deps){return ReactSharedInternals.H.useMemo(create,deps)},exports2.useOptimistic=useOptimistic,exports2.useReducer=function(reducer,initialArg,init){return ReactSharedInternals.H.useReducer(reducer,initialArg,init)},exports2.useRef=function(initialValue){return ReactSharedInternals.H.useRef(initialValue)},exports2.useState=function(initialState){return ReactSharedInternals.H.useState(initialState)},exports2.useSyncExternalStore=function(subscribe,getSnapshot,getServerSnapshot){return ReactSharedInternals.H.useSyncExternalStore(subscribe,getSnapshot,getServerSnapshot)},exports2.useTransition=function(){return ReactSharedInternals.H.useTransition()},exports2.version="19.3.0-experimental-3cde211b-20251020"},189:(module2,__unused_webpack_exports,__webpack_require__2)=>{module2.exports=__webpack_require__2(126)},206:function(module2,exports2,__webpack_require__2){var __WEBPACK_AMD_DEFINE_FACTORY__,__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;function _typeof(o){return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},_typeof(o)}(function(root,factory){__WEBPACK_AMD_DEFINE_ARRAY__=[__webpack_require__2(430)],__WEBPACK_AMD_DEFINE_FACTORY__=factory,__WEBPACK_AMD_DEFINE_RESULT__=typeof __WEBPACK_AMD_DEFINE_FACTORY__==="function"?__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports2,__WEBPACK_AMD_DEFINE_ARRAY__):__WEBPACK_AMD_DEFINE_FACTORY__,__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module2.exports=__WEBPACK_AMD_DEFINE_RESULT__)})(this,function(StackFrame){var FIREFOX_SAFARI_STACK_REGEXP=/(^|@)\S+:\d+/,CHROME_IE_STACK_REGEXP=/^\s*at .*(\S+:\d+|\(native\))/m,SAFARI_NATIVE_CODE_REGEXP=/^(eval@)?(\[native code])?$/;return{parse:function(error){if(typeof error.stacktrace<"u"||typeof error["opera#sourceloc"]<"u")return this.parseOpera(error);else if(error.stack&&error.stack.match(CHROME_IE_STACK_REGEXP))return this.parseV8OrIE(error);else if(error.stack)return this.parseFFOrSafari(error);else throw Error("Cannot parse given Error object")},extractLocation:function(urlLike){if(urlLike.indexOf(":")===-1)return[urlLike];var regExp=/(.+?)(?::(\d+))?(?::(\d+))?$/,parts=regExp.exec(urlLike.replace(/[()]/g,""));return[parts[1],parts[2]||void 0,parts[3]||void 0]},parseV8OrIE:function(error){var filtered=error.stack.split(`
112
+ `).filter(function(line){return!!line.match(CHROME_IE_STACK_REGEXP)},this);return filtered.map(function(line){if(line.indexOf("(eval ")>-1)line=line.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(\),.*$)/g,"");var sanitizedLine=line.replace(/^\s+/,"").replace(/\(eval code/g,"("),location=sanitizedLine.match(/ (\((.+):(\d+):(\d+)\)$)/);sanitizedLine=location?sanitizedLine.replace(location[0],""):sanitizedLine;var tokens=sanitizedLine.split(/\s+/).slice(1),locationParts=this.extractLocation(location?location[1]:tokens.pop()),functionName=tokens.join(" ")||void 0,fileName=["eval","<anonymous>"].indexOf(locationParts[0])>-1?void 0:locationParts[0];return new StackFrame({functionName,fileName,lineNumber:locationParts[1],columnNumber:locationParts[2],source:line})},this)},parseFFOrSafari:function(error){var filtered=error.stack.split(`
113
+ `).filter(function(line){return!line.match(SAFARI_NATIVE_CODE_REGEXP)},this);return filtered.map(function(line){if(line.indexOf(" > eval")>-1)line=line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1");if(line.indexOf("@")===-1&&line.indexOf(":")===-1)return new StackFrame({functionName:line});else{var functionNameRegex=/((.*".+"[^@]*)?[^@]*)(?:@)/,matches=line.match(functionNameRegex),functionName=matches&&matches[1]?matches[1]:void 0,locationParts=this.extractLocation(line.replace(functionNameRegex,""));return new StackFrame({functionName,fileName:locationParts[0],lineNumber:locationParts[1],columnNumber:locationParts[2],source:line})}},this)},parseOpera:function(e){if(!e.stacktrace||e.message.indexOf(`
114
+ `)>-1&&e.message.split(`
115
+ `).length>e.stacktrace.split(`
116
+ `).length)return this.parseOpera9(e);else if(!e.stack)return this.parseOpera10(e);else return this.parseOpera11(e)},parseOpera9:function(e){var lineRE=/Line (\d+).*script (?:in )?(\S+)/i,lines=e.message.split(`
117
+ `),result=[];for(var i=2,len=lines.length;i<len;i+=2){var match=lineRE.exec(lines[i]);if(match)result.push(new StackFrame({fileName:match[2],lineNumber:match[1],source:lines[i]}))}return result},parseOpera10:function(e){var lineRE=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i,lines=e.stacktrace.split(`
118
+ `),result=[];for(var i=0,len=lines.length;i<len;i+=2){var match=lineRE.exec(lines[i]);if(match)result.push(new StackFrame({functionName:match[3]||void 0,fileName:match[2],lineNumber:match[1],source:lines[i]}))}return result},parseOpera11:function(error){var filtered=error.stack.split(`
119
+ `).filter(function(line){return!!line.match(FIREFOX_SAFARI_STACK_REGEXP)&&!line.match(/^Error created at/)},this);return filtered.map(function(line){var tokens=line.split("@"),locationParts=this.extractLocation(tokens.pop()),functionCall=tokens.shift()||"",functionName=functionCall.replace(/<anonymous function(: (\w+))?>/,"$2").replace(/\([^)]*\)/g,"")||void 0,argsRaw;if(functionCall.match(/\(([^)]*)\)/))argsRaw=functionCall.replace(/^[^(]+\(([^)]*)\)$/,"$1");var args=argsRaw===void 0||argsRaw==="[arguments not available]"?void 0:argsRaw.split(",");return new StackFrame({functionName,args,fileName:locationParts[0],lineNumber:locationParts[1],columnNumber:locationParts[2],source:line})},this)}}})},730:(module2,__unused_webpack_exports,__webpack_require__2)=>{function _typeof(o){return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},_typeof(o)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];if(descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor)descriptor.writable=!0;Object.defineProperty(target,_toPropertyKey(descriptor.key),descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Object.defineProperty(Constructor,"prototype",{writable:!1}),Constructor}function _toPropertyKey(t){var i=_toPrimitive(t,"string");return _typeof(i)=="symbol"?i:i+""}function _toPrimitive(t,r){if(_typeof(t)!="object"||!t)return t;var e=t[Symbol.toPrimitive];if(e!==void 0){var i=e.call(t,r||"default");if(_typeof(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(t)}var Yallist=__webpack_require__2(695),MAX=Symbol("max"),LENGTH=Symbol("length"),LENGTH_CALCULATOR=Symbol("lengthCalculator"),ALLOW_STALE=Symbol("allowStale"),MAX_AGE=Symbol("maxAge"),DISPOSE=Symbol("dispose"),NO_DISPOSE_ON_SET=Symbol("noDisposeOnSet"),LRU_LIST=Symbol("lruList"),CACHE=Symbol("cache"),UPDATE_AGE_ON_GET=Symbol("updateAgeOnGet"),naiveLength=function(){return 1},LRUCache=function(){function LRUCache2(options){if(_classCallCheck(this,LRUCache2),typeof options==="number")options={max:options};if(!options)options={};if(options.max&&(typeof options.max!=="number"||options.max<0))throw TypeError("max must be a non-negative number");var max=this[MAX]=options.max||1/0,lc=options.length||naiveLength;if(this[LENGTH_CALCULATOR]=typeof lc!=="function"?naiveLength:lc,this[ALLOW_STALE]=options.stale||!1,options.maxAge&&typeof options.maxAge!=="number")throw TypeError("maxAge must be a number");this[MAX_AGE]=options.maxAge||0,this[DISPOSE]=options.dispose,this[NO_DISPOSE_ON_SET]=options.noDisposeOnSet||!1,this[UPDATE_AGE_ON_GET]=options.updateAgeOnGet||!1,this.reset()}return _createClass(LRUCache2,[{key:"max",get:function(){return this[MAX]},set:function(mL){if(typeof mL!=="number"||mL<0)throw TypeError("max must be a non-negative number");this[MAX]=mL||1/0,trim(this)}},{key:"allowStale",get:function(){return this[ALLOW_STALE]},set:function(allowStale){this[ALLOW_STALE]=!!allowStale}},{key:"maxAge",get:function(){return this[MAX_AGE]},set:function(mA){if(typeof mA!=="number")throw TypeError("maxAge must be a non-negative number");this[MAX_AGE]=mA,trim(this)}},{key:"lengthCalculator",get:function(){return this[LENGTH_CALCULATOR]},set:function(lC){var _this=this;if(typeof lC!=="function")lC=naiveLength;if(lC!==this[LENGTH_CALCULATOR])this[LENGTH_CALCULATOR]=lC,this[LENGTH]=0,this[LRU_LIST].forEach(function(hit){hit.length=_this[LENGTH_CALCULATOR](hit.value,hit.key),_this[LENGTH]+=hit.length});trim(this)}},{key:"length",get:function(){return this[LENGTH]}},{key:"itemCount",get:function(){return this[LRU_LIST].length}},{key:"rforEach",value:function(fn,thisp){thisp=thisp||this;for(var walker=this[LRU_LIST].tail;walker!==null;){var prev=walker.prev;forEachStep(this,fn,walker,thisp),walker=prev}}},{key:"forEach",value:function(fn,thisp){thisp=thisp||this;for(var walker=this[LRU_LIST].head;walker!==null;){var next=walker.next;forEachStep(this,fn,walker,thisp),walker=next}}},{key:"keys",value:function(){return this[LRU_LIST].toArray().map(function(k){return k.key})}},{key:"values",value:function(){return this[LRU_LIST].toArray().map(function(k){return k.value})}},{key:"reset",value:function(){var _this2=this;if(this[DISPOSE]&&this[LRU_LIST]&&this[LRU_LIST].length)this[LRU_LIST].forEach(function(hit){return _this2[DISPOSE](hit.key,hit.value)});this[CACHE]=new Map,this[LRU_LIST]=new Yallist,this[LENGTH]=0}},{key:"dump",value:function(){var _this3=this;return this[LRU_LIST].map(function(hit){return isStale(_this3,hit)?!1:{k:hit.key,v:hit.value,e:hit.now+(hit.maxAge||0)}}).toArray().filter(function(h){return h})}},{key:"dumpLru",value:function(){return this[LRU_LIST]}},{key:"set",value:function(key,value,maxAge){if(maxAge=maxAge||this[MAX_AGE],maxAge&&typeof maxAge!=="number")throw TypeError("maxAge must be a number");var now=maxAge?Date.now():0,len=this[LENGTH_CALCULATOR](value,key);if(this[CACHE].has(key)){if(len>this[MAX])return _del(this,this[CACHE].get(key)),!1;var node=this[CACHE].get(key),item=node.value;if(this[DISPOSE]){if(!this[NO_DISPOSE_ON_SET])this[DISPOSE](key,item.value)}return item.now=now,item.maxAge=maxAge,item.value=value,this[LENGTH]+=len-item.length,item.length=len,this.get(key),trim(this),!0}var hit=new Entry(key,value,len,now,maxAge);if(hit.length>this[MAX]){if(this[DISPOSE])this[DISPOSE](key,value);return!1}return this[LENGTH]+=hit.length,this[LRU_LIST].unshift(hit),this[CACHE].set(key,this[LRU_LIST].head),trim(this),!0}},{key:"has",value:function(key){if(!this[CACHE].has(key))return!1;var hit=this[CACHE].get(key).value;return!isStale(this,hit)}},{key:"get",value:function(key){return _get(this,key,!0)}},{key:"peek",value:function(key){return _get(this,key,!1)}},{key:"pop",value:function(){var node=this[LRU_LIST].tail;if(!node)return null;return _del(this,node),node.value}},{key:"del",value:function(key){_del(this,this[CACHE].get(key))}},{key:"load",value:function(arr){this.reset();var now=Date.now();for(var l=arr.length-1;l>=0;l--){var hit=arr[l],expiresAt=hit.e||0;if(expiresAt===0)this.set(hit.k,hit.v);else{var maxAge=expiresAt-now;if(maxAge>0)this.set(hit.k,hit.v,maxAge)}}}},{key:"prune",value:function(){var _this4=this;this[CACHE].forEach(function(value,key){return _get(_this4,key,!1)})}}])}(),_get=function(self2,key,doUse){var node=self2[CACHE].get(key);if(node){var hit=node.value;if(isStale(self2,hit)){if(_del(self2,node),!self2[ALLOW_STALE])return}else if(doUse){if(self2[UPDATE_AGE_ON_GET])node.value.now=Date.now();self2[LRU_LIST].unshiftNode(node)}return hit.value}},isStale=function(self2,hit){if(!hit||!hit.maxAge&&!self2[MAX_AGE])return!1;var diff=Date.now()-hit.now;return hit.maxAge?diff>hit.maxAge:self2[MAX_AGE]&&diff>self2[MAX_AGE]},trim=function(self2){if(self2[LENGTH]>self2[MAX])for(var walker=self2[LRU_LIST].tail;self2[LENGTH]>self2[MAX]&&walker!==null;){var prev=walker.prev;_del(self2,walker),walker=prev}},_del=function(self2,node){if(node){var hit=node.value;if(self2[DISPOSE])self2[DISPOSE](hit.key,hit.value);self2[LENGTH]-=hit.length,self2[CACHE].delete(hit.key),self2[LRU_LIST].removeNode(node)}},Entry=_createClass(function Entry2(key,value,length,now,maxAge){_classCallCheck(this,Entry2),this.key=key,this.value=value,this.length=length,this.now=now,this.maxAge=maxAge||0}),forEachStep=function(self2,fn,node,thisp){var hit=node.value;if(isStale(self2,hit)){if(_del(self2,node),!self2[ALLOW_STALE])hit=void 0}if(hit)fn.call(thisp,hit.value,hit.key,self2)};module2.exports=LRUCache},169:(module2)=>{var process2=module2.exports={},cachedSetTimeout,cachedClearTimeout;function defaultSetTimout(){throw Error("setTimeout has not been defined")}function defaultClearTimeout(){throw Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function")cachedSetTimeout=setTimeout;else cachedSetTimeout=defaultSetTimout}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function")cachedClearTimeout=clearTimeout;else cachedClearTimeout=defaultClearTimeout}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e2){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e2){return cachedClearTimeout.call(this,marker)}}}var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue)return;if(draining=!1,currentQueue.length)queue=currentQueue.concat(queue);else queueIndex=-1;if(queue.length)drainQueue()}function drainQueue(){if(draining)return;var timeout=runTimeout(cleanUpNextTick);draining=!0;var len=queue.length;while(len){currentQueue=queue,queue=[];while(++queueIndex<len)if(currentQueue)currentQueue[queueIndex].run();queueIndex=-1,len=queue.length}currentQueue=null,draining=!1,runClearTimeout(timeout)}process2.nextTick=function(fun){var args=Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)args[i-1]=arguments[i];if(queue.push(new Item(fun,args)),queue.length===1&&!draining)runTimeout(drainQueue)};function Item(fun,array){this.fun=fun,this.array=array}Item.prototype.run=function(){this.fun.apply(null,this.array)},process2.title="browser",process2.browser=!0,process2.env={},process2.argv=[],process2.version="",process2.versions={};function noop(){}process2.on=noop,process2.addListener=noop,process2.once=noop,process2.off=noop,process2.removeListener=noop,process2.removeAllListeners=noop,process2.emit=noop,process2.prependListener=noop,process2.prependOnceListener=noop,process2.listeners=function(name){return[]},process2.binding=function(name){throw Error("process.binding is not supported")},process2.cwd=function(){return"/"},process2.chdir=function(dir){throw Error("process.chdir is not supported")},process2.umask=function(){return 0}},430:function(module2,exports2){var __WEBPACK_AMD_DEFINE_FACTORY__,__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;function _typeof(o){return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},_typeof(o)}(function(root,factory){__WEBPACK_AMD_DEFINE_ARRAY__=[],__WEBPACK_AMD_DEFINE_FACTORY__=factory,__WEBPACK_AMD_DEFINE_RESULT__=typeof __WEBPACK_AMD_DEFINE_FACTORY__==="function"?__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports2,__WEBPACK_AMD_DEFINE_ARRAY__):__WEBPACK_AMD_DEFINE_FACTORY__,__WEBPACK_AMD_DEFINE_RESULT__!==void 0&&(module2.exports=__WEBPACK_AMD_DEFINE_RESULT__)})(this,function(){function _isNumber(n){return!isNaN(parseFloat(n))&&isFinite(n)}function _capitalize(str){return str.charAt(0).toUpperCase()+str.substring(1)}function _getter(p){return function(){return this[p]}}var booleanProps=["isConstructor","isEval","isNative","isToplevel"],numericProps=["columnNumber","lineNumber"],stringProps=["fileName","functionName","source"],arrayProps=["args"],props=booleanProps.concat(numericProps,stringProps,arrayProps);function StackFrame(obj){if(!obj)return;for(var i2=0;i2<props.length;i2++)if(obj[props[i2]]!==void 0)this["set"+_capitalize(props[i2])](obj[props[i2]])}StackFrame.prototype={getArgs:function(){return this.args},setArgs:function(v){if(Object.prototype.toString.call(v)!=="[object Array]")throw TypeError("Args must be an Array");this.args=v},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(v){if(v instanceof StackFrame)this.evalOrigin=v;else if(v instanceof Object)this.evalOrigin=new StackFrame(v);else throw TypeError("Eval Origin must be an Object or StackFrame")},toString:function(){var fileName=this.getFileName()||"",lineNumber=this.getLineNumber()||"",columnNumber=this.getColumnNumber()||"",functionName=this.getFunctionName()||"";if(this.getIsEval()){if(fileName)return"[eval] ("+fileName+":"+lineNumber+":"+columnNumber+")";return"[eval]:"+lineNumber+":"+columnNumber}if(functionName)return functionName+" ("+fileName+":"+lineNumber+":"+columnNumber+")";return fileName+":"+lineNumber+":"+columnNumber}},StackFrame.fromString=function(str){var argsStartIndex=str.indexOf("("),argsEndIndex=str.lastIndexOf(")"),functionName=str.substring(0,argsStartIndex),args=str.substring(argsStartIndex+1,argsEndIndex).split(","),locationString=str.substring(argsEndIndex+1);if(locationString.indexOf("@")===0)var parts=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(locationString,""),fileName=parts[1],lineNumber=parts[2],columnNumber=parts[3];return new StackFrame({functionName,args:args||void 0,fileName,lineNumber:lineNumber||void 0,columnNumber:columnNumber||void 0})};for(var i=0;i<booleanProps.length;i++)StackFrame.prototype["get"+_capitalize(booleanProps[i])]=_getter(booleanProps[i]),StackFrame.prototype["set"+_capitalize(booleanProps[i])]=function(p){return function(v){this[p]=Boolean(v)}}(booleanProps[i]);for(var j=0;j<numericProps.length;j++)StackFrame.prototype["get"+_capitalize(numericProps[j])]=_getter(numericProps[j]),StackFrame.prototype["set"+_capitalize(numericProps[j])]=function(p){return function(v){if(!_isNumber(v))throw TypeError(p+" must be a Number");this[p]=Number(v)}}(numericProps[j]);for(var k=0;k<stringProps.length;k++)StackFrame.prototype["get"+_capitalize(stringProps[k])]=_getter(stringProps[k]),StackFrame.prototype["set"+_capitalize(stringProps[k])]=function(p){return function(v){this[p]=String(v)}}(stringProps[k]);return StackFrame})},476:(module2)=>{function _typeof(o){return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},_typeof(o)}function _regeneratorRuntime(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */_regeneratorRuntime=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t2,e2,r2){t2[e2]=r2.value},i=typeof Symbol=="function"?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function define2(t2,e2,r2){return Object.defineProperty(t2,e2,{value:r2,enumerable:!0,configurable:!0,writable:!0}),t2[e2]}try{define2({},"")}catch(t2){define2=function(t3,e2,r2){return t3[e2]=r2}}function wrap(t2,e2,r2,n2){var i2=e2&&e2.prototype instanceof Generator?e2:Generator,a2=Object.create(i2.prototype),c2=new Context(n2||[]);return o(a2,"_invoke",{value:makeInvokeMethod(t2,r2,c2)}),a2}function tryCatch(t2,e2,r2){try{return{type:"normal",arg:t2.call(e2,r2)}}catch(t3){return{type:"throw",arg:t3}}}e.wrap=wrap;var h="suspendedStart",l="suspendedYield",f="executing",s="completed",y={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var p={};define2(p,a,function(){return this});var d=Object.getPrototypeOf,v=d&&d(d(values([])));v&&v!==r&&n.call(v,a)&&(p=v);var g=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(p);function defineIteratorMethods(t2){["next","throw","return"].forEach(function(e2){define2(t2,e2,function(t3){return this._invoke(e2,t3)})})}function AsyncIterator(t2,e2){function invoke(r3,o2,i2,a2){var c2=tryCatch(t2[r3],t2,o2);if(c2.type!=="throw"){var u2=c2.arg,h2=u2.value;return h2&&_typeof(h2)=="object"&&n.call(h2,"__await")?e2.resolve(h2.__await).then(function(t3){invoke("next",t3,i2,a2)},function(t3){invoke("throw",t3,i2,a2)}):e2.resolve(h2).then(function(t3){u2.value=t3,i2(u2)},function(t3){return invoke("throw",t3,i2,a2)})}a2(c2.arg)}var r2;o(this,"_invoke",{value:function(t3,n2){function callInvokeWithMethodAndArg(){return new e2(function(e3,r3){invoke(t3,n2,e3,r3)})}return r2=r2?r2.then(callInvokeWithMethodAndArg,callInvokeWithMethodAndArg):callInvokeWithMethodAndArg()}})}function makeInvokeMethod(e2,r2,n2){var o2=h;return function(i2,a2){if(o2===f)throw Error("Generator is already running");if(o2===s){if(i2==="throw")throw a2;return{value:t,done:!0}}for(n2.method=i2,n2.arg=a2;;){var c2=n2.delegate;if(c2){var u2=maybeInvokeDelegate(c2,n2);if(u2){if(u2===y)continue;return u2}}if(n2.method==="next")n2.sent=n2._sent=n2.arg;else if(n2.method==="throw"){if(o2===h)throw o2=s,n2.arg;n2.dispatchException(n2.arg)}else n2.method==="return"&&n2.abrupt("return",n2.arg);o2=f;var p2=tryCatch(e2,r2,n2);if(p2.type==="normal"){if(o2=n2.done?s:l,p2.arg===y)continue;return{value:p2.arg,done:n2.done}}p2.type==="throw"&&(o2=s,n2.method="throw",n2.arg=p2.arg)}}}function maybeInvokeDelegate(e2,r2){var n2=r2.method,o2=e2.iterator[n2];if(o2===t)return r2.delegate=null,n2==="throw"&&e2.iterator.return&&(r2.method="return",r2.arg=t,maybeInvokeDelegate(e2,r2),r2.method==="throw")||n2!=="return"&&(r2.method="throw",r2.arg=TypeError("The iterator does not provide a '"+n2+"' method")),y;var i2=tryCatch(o2,e2.iterator,r2.arg);if(i2.type==="throw")return r2.method="throw",r2.arg=i2.arg,r2.delegate=null,y;var a2=i2.arg;return a2?a2.done?(r2[e2.resultName]=a2.value,r2.next=e2.nextLoc,r2.method!=="return"&&(r2.method="next",r2.arg=t),r2.delegate=null,y):a2:(r2.method="throw",r2.arg=TypeError("iterator result is not an object"),r2.delegate=null,y)}function pushTryEntry(t2){var e2={tryLoc:t2[0]};1 in t2&&(e2.catchLoc=t2[1]),2 in t2&&(e2.finallyLoc=t2[2],e2.afterLoc=t2[3]),this.tryEntries.push(e2)}function resetTryEntry(t2){var e2=t2.completion||{};e2.type="normal",delete e2.arg,t2.completion=e2}function Context(t2){this.tryEntries=[{tryLoc:"root"}],t2.forEach(pushTryEntry,this),this.reset(!0)}function values(e2){if(e2||e2===""){var r2=e2[a];if(r2)return r2.call(e2);if(typeof e2.next=="function")return e2;if(!isNaN(e2.length)){var o2=-1,i2=function next(){for(;++o2<e2.length;)if(n.call(e2,o2))return next.value=e2[o2],next.done=!1,next;return next.value=t,next.done=!0,next};return i2.next=i2}}throw TypeError(_typeof(e2)+" is not iterable")}return GeneratorFunction.prototype=GeneratorFunctionPrototype,o(g,"constructor",{value:GeneratorFunctionPrototype,configurable:!0}),o(GeneratorFunctionPrototype,"constructor",{value:GeneratorFunction,configurable:!0}),GeneratorFunction.displayName=define2(GeneratorFunctionPrototype,u,"GeneratorFunction"),e.isGeneratorFunction=function(t2){var e2=typeof t2=="function"&&t2.constructor;return!!e2&&(e2===GeneratorFunction||(e2.displayName||e2.name)==="GeneratorFunction")},e.mark=function(t2){return Object.setPrototypeOf?Object.setPrototypeOf(t2,GeneratorFunctionPrototype):(t2.__proto__=GeneratorFunctionPrototype,define2(t2,u,"GeneratorFunction")),t2.prototype=Object.create(g),t2},e.awrap=function(t2){return{__await:t2}},defineIteratorMethods(AsyncIterator.prototype),define2(AsyncIterator.prototype,c,function(){return this}),e.AsyncIterator=AsyncIterator,e.async=function(t2,r2,n2,o2,i2){i2===void 0&&(i2=Promise);var a2=new AsyncIterator(wrap(t2,r2,n2,o2),i2);return e.isGeneratorFunction(r2)?a2:a2.next().then(function(t3){return t3.done?t3.value:a2.next()})},defineIteratorMethods(g),define2(g,u,"Generator"),define2(g,a,function(){return this}),define2(g,"toString",function(){return"[object Generator]"}),e.keys=function(t2){var e2=Object(t2),r2=[];for(var n2 in e2)r2.push(n2);return r2.reverse(),function next(){for(;r2.length;){var t3=r2.pop();if(t3 in e2)return next.value=t3,next.done=!1,next}return next.done=!0,next}},e.values=values,Context.prototype={constructor:Context,reset:function(e2){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(resetTryEntry),!e2)for(var r2 in this)r2.charAt(0)==="t"&&n.call(this,r2)&&!isNaN(+r2.slice(1))&&(this[r2]=t)},stop:function(){this.done=!0;var t2=this.tryEntries[0].completion;if(t2.type==="throw")throw t2.arg;return this.rval},dispatchException:function(e2){if(this.done)throw e2;var r2=this;function handle(n2,o3){return a2.type="throw",a2.arg=e2,r2.next=n2,o3&&(r2.method="next",r2.arg=t),!!o3}for(var o2=this.tryEntries.length-1;o2>=0;--o2){var i2=this.tryEntries[o2],a2=i2.completion;if(i2.tryLoc==="root")return handle("end");if(i2.tryLoc<=this.prev){var c2=n.call(i2,"catchLoc"),u2=n.call(i2,"finallyLoc");if(c2&&u2){if(this.prev<i2.catchLoc)return handle(i2.catchLoc,!0);if(this.prev<i2.finallyLoc)return handle(i2.finallyLoc)}else if(c2){if(this.prev<i2.catchLoc)return handle(i2.catchLoc,!0)}else{if(!u2)throw Error("try statement without catch or finally");if(this.prev<i2.finallyLoc)return handle(i2.finallyLoc)}}}},abrupt:function(t2,e2){for(var r2=this.tryEntries.length-1;r2>=0;--r2){var o2=this.tryEntries[r2];if(o2.tryLoc<=this.prev&&n.call(o2,"finallyLoc")&&this.prev<o2.finallyLoc){var i2=o2;break}}i2&&(t2==="break"||t2==="continue")&&i2.tryLoc<=e2&&e2<=i2.finallyLoc&&(i2=null);var a2=i2?i2.completion:{};return a2.type=t2,a2.arg=e2,i2?(this.method="next",this.next=i2.finallyLoc,y):this.complete(a2)},complete:function(t2,e2){if(t2.type==="throw")throw t2.arg;return t2.type==="break"||t2.type==="continue"?this.next=t2.arg:t2.type==="return"?(this.rval=this.arg=t2.arg,this.method="return",this.next="end"):t2.type==="normal"&&e2&&(this.next=e2),y},finish:function(t2){for(var e2=this.tryEntries.length-1;e2>=0;--e2){var r2=this.tryEntries[e2];if(r2.finallyLoc===t2)return this.complete(r2.completion,r2.afterLoc),resetTryEntry(r2),y}},catch:function(t2){for(var e2=this.tryEntries.length-1;e2>=0;--e2){var r2=this.tryEntries[e2];if(r2.tryLoc===t2){var n2=r2.completion;if(n2.type==="throw"){var o2=n2.arg;resetTryEntry(r2)}return o2}}throw Error("illegal catch attempt")},delegateYield:function(e2,r2,n2){return this.delegate={iterator:values(e2),resultName:r2,nextLoc:n2},this.method==="next"&&(this.arg=t),y}},e}module2.exports=function(Yallist){Yallist.prototype[Symbol.iterator]=_regeneratorRuntime().mark(function _callee(){var walker;return _regeneratorRuntime().wrap(function(_context){while(!0)switch(_context.prev=_context.next){case 0:walker=this.head;case 1:if(!walker){_context.next=7;break}return _context.next=4,walker.value;case 4:walker=walker.next,_context.next=1;break;case 7:case"end":return _context.stop()}},_callee,this)})}},695:(module2,__unused_webpack_exports,__webpack_require__2)=>{module2.exports=Yallist,Yallist.Node=Node2,Yallist.create=Yallist;function Yallist(list){var self2=this;if(!(self2 instanceof Yallist))self2=new Yallist;if(self2.tail=null,self2.head=null,self2.length=0,list&&typeof list.forEach==="function")list.forEach(function(item){self2.push(item)});else if(arguments.length>0)for(var i=0,l=arguments.length;i<l;i++)self2.push(arguments[i]);return self2}Yallist.prototype.removeNode=function(node){if(node.list!==this)throw Error("removing node which does not belong to this list");var{next,prev}=node;if(next)next.prev=prev;if(prev)prev.next=next;if(node===this.head)this.head=next;if(node===this.tail)this.tail=prev;return node.list.length--,node.next=null,node.prev=null,node.list=null,next},Yallist.prototype.unshiftNode=function(node){if(node===this.head)return;if(node.list)node.list.removeNode(node);var head=this.head;if(node.list=this,node.next=head,head)head.prev=node;if(this.head=node,!this.tail)this.tail=node;this.length++},Yallist.prototype.pushNode=function(node){if(node===this.tail)return;if(node.list)node.list.removeNode(node);var tail=this.tail;if(node.list=this,node.prev=tail,tail)tail.next=node;if(this.tail=node,!this.head)this.head=node;this.length++},Yallist.prototype.push=function(){for(var i=0,l=arguments.length;i<l;i++)push(this,arguments[i]);return this.length},Yallist.prototype.unshift=function(){for(var i=0,l=arguments.length;i<l;i++)unshift(this,arguments[i]);return this.length},Yallist.prototype.pop=function(){if(!this.tail)return;var res=this.tail.value;if(this.tail=this.tail.prev,this.tail)this.tail.next=null;else this.head=null;return this.length--,res},Yallist.prototype.shift=function(){if(!this.head)return;var res=this.head.value;if(this.head=this.head.next,this.head)this.head.prev=null;else this.tail=null;return this.length--,res},Yallist.prototype.forEach=function(fn,thisp){thisp=thisp||this;for(var walker=this.head,i=0;walker!==null;i++)fn.call(thisp,walker.value,i,this),walker=walker.next},Yallist.prototype.forEachReverse=function(fn,thisp){thisp=thisp||this;for(var walker=this.tail,i=this.length-1;walker!==null;i--)fn.call(thisp,walker.value,i,this),walker=walker.prev},Yallist.prototype.get=function(n){for(var i=0,walker=this.head;walker!==null&&i<n;i++)walker=walker.next;if(i===n&&walker!==null)return walker.value},Yallist.prototype.getReverse=function(n){for(var i=0,walker=this.tail;walker!==null&&i<n;i++)walker=walker.prev;if(i===n&&walker!==null)return walker.value},Yallist.prototype.map=function(fn,thisp){thisp=thisp||this;var res=new Yallist;for(var walker=this.head;walker!==null;)res.push(fn.call(thisp,walker.value,this)),walker=walker.next;return res},Yallist.prototype.mapReverse=function(fn,thisp){thisp=thisp||this;var res=new Yallist;for(var walker=this.tail;walker!==null;)res.push(fn.call(thisp,walker.value,this)),walker=walker.prev;return res},Yallist.prototype.reduce=function(fn,initial){var acc,walker=this.head;if(arguments.length>1)acc=initial;else if(this.head)walker=this.head.next,acc=this.head.value;else throw TypeError("Reduce of empty list with no initial value");for(var i=0;walker!==null;i++)acc=fn(acc,walker.value,i),walker=walker.next;return acc},Yallist.prototype.reduceReverse=function(fn,initial){var acc,walker=this.tail;if(arguments.length>1)acc=initial;else if(this.tail)walker=this.tail.prev,acc=this.tail.value;else throw TypeError("Reduce of empty list with no initial value");for(var i=this.length-1;walker!==null;i--)acc=fn(acc,walker.value,i),walker=walker.prev;return acc},Yallist.prototype.toArray=function(){var arr=Array(this.length);for(var i=0,walker=this.head;walker!==null;i++)arr[i]=walker.value,walker=walker.next;return arr},Yallist.prototype.toArrayReverse=function(){var arr=Array(this.length);for(var i=0,walker=this.tail;walker!==null;i++)arr[i]=walker.value,walker=walker.prev;return arr},Yallist.prototype.slice=function(from,to){if(to=to||this.length,to<0)to+=this.length;if(from=from||0,from<0)from+=this.length;var ret=new Yallist;if(to<from||to<0)return ret;if(from<0)from=0;if(to>this.length)to=this.length;for(var i=0,walker=this.head;walker!==null&&i<from;i++)walker=walker.next;for(;walker!==null&&i<to;i++,walker=walker.next)ret.push(walker.value);return ret},Yallist.prototype.sliceReverse=function(from,to){if(to=to||this.length,to<0)to+=this.length;if(from=from||0,from<0)from+=this.length;var ret=new Yallist;if(to<from||to<0)return ret;if(from<0)from=0;if(to>this.length)to=this.length;for(var i=this.length,walker=this.tail;walker!==null&&i>to;i--)walker=walker.prev;for(;walker!==null&&i>from;i--,walker=walker.prev)ret.push(walker.value);return ret},Yallist.prototype.splice=function(start,deleteCount){if(start>this.length)start=this.length-1;if(start<0)start=this.length+start;for(var i=0,walker=this.head;walker!==null&&i<start;i++)walker=walker.next;var ret=[];for(var i=0;walker&&i<deleteCount;i++)ret.push(walker.value),walker=this.removeNode(walker);if(walker===null)walker=this.tail;if(walker!==this.head&&walker!==this.tail)walker=walker.prev;for(var i=2;i<arguments.length;i++)walker=insert(this,walker,arguments[i]);return ret},Yallist.prototype.reverse=function(){var head=this.head,tail=this.tail;for(var walker=head;walker!==null;walker=walker.prev){var p=walker.prev;walker.prev=walker.next,walker.next=p}return this.head=tail,this.tail=head,this};function insert(self2,node,value){var inserted=node===self2.head?new Node2(value,null,node,self2):new Node2(value,node,node.next,self2);if(inserted.next===null)self2.tail=inserted;if(inserted.prev===null)self2.head=inserted;return self2.length++,inserted}function push(self2,item){if(self2.tail=new Node2(item,self2.tail,null,self2),!self2.head)self2.head=self2.tail;self2.length++}function unshift(self2,item){if(self2.head=new Node2(item,null,self2.head,self2),!self2.tail)self2.tail=self2.head;self2.length++}function Node2(value,prev,next,list){if(!(this instanceof Node2))return new Node2(value,prev,next,list);if(this.list=list,this.value=value,prev)prev.next=this,this.prev=prev;else this.prev=null;if(next)next.prev=this,this.next=next;else this.next=null}try{__webpack_require__2(476)(Yallist)}catch(er){}}},__webpack_module_cache__={};function __webpack_require__(moduleId){var cachedModule=__webpack_module_cache__[moduleId];if(cachedModule!==void 0)return cachedModule.exports;var module2=__webpack_module_cache__[moduleId]={exports:{}};return __webpack_modules__[moduleId].call(module2.exports,module2,module2.exports,__webpack_require__),module2.exports}(()=>{__webpack_require__.n=(module2)=>{var getter=module2&&module2.__esModule?()=>module2.default:()=>module2;return __webpack_require__.d(getter,{a:getter}),getter}})(),(()=>{__webpack_require__.d=(exports2,definition)=>{for(var key in definition)if(__webpack_require__.o(definition,key)&&!__webpack_require__.o(exports2,key))Object.defineProperty(exports2,key,{enumerable:!0,get:definition[key]})}})(),(()=>{__webpack_require__.o=(obj,prop)=>Object.prototype.hasOwnProperty.call(obj,prop)})(),(()=>{__webpack_require__.r=(exports2)=>{if(typeof Symbol<"u"&&Symbol.toStringTag)Object.defineProperty(exports2,Symbol.toStringTag,{value:"Module"});Object.defineProperty(exports2,"__esModule",{value:!0})}})();var __webpack_exports__={};return(()=>{__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{connectToDevTools:()=>connectToDevTools,connectWithCustomMessagingProtocol:()=>connectWithCustomMessagingProtocol,initialize:()=>backend_initialize});function _typeof(o){return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},_typeof(o)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];if(descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor)descriptor.writable=!0;Object.defineProperty(target,_toPropertyKey(descriptor.key),descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Object.defineProperty(Constructor,"prototype",{writable:!1}),Constructor}function _defineProperty(obj,key,value){if(key=_toPropertyKey(key),key in obj)Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0});else obj[key]=value;return obj}function _toPropertyKey(t){var i=_toPrimitive(t,"string");return _typeof(i)=="symbol"?i:i+""}function _toPrimitive(t,r){if(_typeof(t)!="object"||!t)return t;var e=t[Symbol.toPrimitive];if(e!==void 0){var i=e.call(t,r||"default");if(_typeof(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(t)}var EventEmitter=function(){function EventEmitter2(){_classCallCheck(this,EventEmitter2),_defineProperty(this,"listenersMap",new Map)}return _createClass(EventEmitter2,[{key:"addListener",value:function(event,listener){var listeners=this.listenersMap.get(event);if(listeners===void 0)this.listenersMap.set(event,[listener]);else{var index=listeners.indexOf(listener);if(index<0)listeners.push(listener)}}},{key:"emit",value:function(event){var listeners=this.listenersMap.get(event);if(listeners!==void 0){for(var _len=arguments.length,args=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)args[_key-1]=arguments[_key];if(listeners.length===1){var listener=listeners[0];listener.apply(null,args)}else{var didThrow=!1,caughtError=null,clonedListeners=Array.from(listeners);for(var i=0;i<clonedListeners.length;i++){var _listener=clonedListeners[i];try{_listener.apply(null,args)}catch(error){if(caughtError===null)didThrow=!0,caughtError=error}}if(didThrow)throw caughtError}}}},{key:"removeAllListeners",value:function(){this.listenersMap.clear()}},{key:"removeListener",value:function(event,listener){var listeners=this.listenersMap.get(event);if(listeners!==void 0){var index=listeners.indexOf(listener);if(index>=0)listeners.splice(index,1)}}}])}(),CHROME_WEBSTORE_EXTENSION_ID="fmkadmapgofadopljbjfkapdkoienihi",INTERNAL_EXTENSION_ID="dnjnjgbfilfphmojnmhliehogmojhclc",LOCAL_EXTENSION_ID="ikiahnapldjmdmpkmfhjdjilojjhgcbf",__DEBUG__=!1,__PERFORMANCE_PROFILE__=!1,TREE_OPERATION_ADD=1,TREE_OPERATION_REMOVE=2,TREE_OPERATION_REORDER_CHILDREN=3,TREE_OPERATION_UPDATE_TREE_BASE_DURATION=4,TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS=5,TREE_OPERATION_REMOVE_ROOT=6,TREE_OPERATION_SET_SUBTREE_MODE=7,SUSPENSE_TREE_OPERATION_ADD=8,SUSPENSE_TREE_OPERATION_REMOVE=9,SUSPENSE_TREE_OPERATION_REORDER_CHILDREN=10,SUSPENSE_TREE_OPERATION_RESIZE=11,SUSPENSE_TREE_OPERATION_SUSPENDERS=12,PROFILING_FLAG_BASIC_SUPPORT=1,PROFILING_FLAG_TIMELINE_SUPPORT=2,PROFILING_FLAG_PERFORMANCE_TRACKS_SUPPORT=4,UNKNOWN_SUSPENDERS_NONE=0,UNKNOWN_SUSPENDERS_REASON_PRODUCTION=1,UNKNOWN_SUSPENDERS_REASON_OLD_VERSION=2,UNKNOWN_SUSPENDERS_REASON_THROWN_PROMISE=3,LOCAL_STORAGE_DEFAULT_TAB_KEY="React::DevTools::defaultTab",constants_LOCAL_STORAGE_COMPONENT_FILTER_PREFERENCES_KEY="React::DevTools::componentFilters",SESSION_STORAGE_LAST_SELECTION_KEY="React::DevTools::lastSelection",constants_LOCAL_STORAGE_OPEN_IN_EDITOR_URL="React::DevTools::openInEditorUrl",constants_LOCAL_STORAGE_OPEN_IN_EDITOR_URL_PRESET="React::DevTools::openInEditorUrlPreset",constants_LOCAL_STORAGE_ALWAYS_OPEN_IN_EDITOR="React::DevTools::alwaysOpenInEditor",LOCAL_STORAGE_PARSE_HOOK_NAMES_KEY="React::DevTools::parseHookNames",constants_SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY="React::DevTools::recordChangeDescriptions",constants_SESSION_STORAGE_RECORD_TIMELINE_KEY="React::DevTools::recordTimeline",constants_SESSION_STORAGE_RELOAD_AND_PROFILE_KEY="React::DevTools::reloadAndProfile",LOCAL_STORAGE_BROWSER_THEME="React::DevTools::theme",LOCAL_STORAGE_TRACE_UPDATES_ENABLED_KEY="React::DevTools::traceUpdatesEnabled",LOCAL_STORAGE_SUPPORTS_PROFILING_KEY="React::DevTools::supportsProfiling",PROFILER_EXPORT_VERSION=5,FIREFOX_CONSOLE_DIMMING_COLOR="color: rgba(124, 124, 124, 0.75)",ANSI_STYLE_DIMMING_TEMPLATE="\x1B[2;38;2;124;124;124m%s\x1B[0m",ANSI_STYLE_DIMMING_TEMPLATE_WITH_COMPONENT_STACK="\x1B[2;38;2;124;124;124m%s %o\x1B[0m";function esm_typeof(o){return esm_typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},esm_typeof(o)}function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest()}function _nonIterableRest(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
120
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function _iterableToArrayLimit(r,l){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,l===0){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r2){o=!0,n=r2}finally{try{if(!f&&t.return!=null&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}function _arrayWithHoles(arr){if(Array.isArray(arr))return arr}var compareVersions=function(v1,v2){var n1=validateAndParse(v1),n2=validateAndParse(v2),p1=n1.pop(),p2=n2.pop(),r=compareSegments(n1,n2);if(r!==0)return r;if(p1&&p2)return compareSegments(p1.split("."),p2.split("."));else if(p1||p2)return p1?-1:1;return 0},validate=function(version){return typeof version==="string"&&/^[v\d]/.test(version)&&semver.test(version)},compare=function(v1,v2,operator){assertValidOperator(operator);var res=compareVersions(v1,v2);return operatorResMap[operator].includes(res)},satisfies=function(version,range){var m=range.match(/^([<>=~^]+)/),op=m?m[1]:"=";if(op!=="^"&&op!=="~")return compare(version,range,op);var _validateAndParse=validateAndParse(version),_validateAndParse2=_slicedToArray(_validateAndParse,5),v1=_validateAndParse2[0],v2=_validateAndParse2[1],v3=_validateAndParse2[2],vp=_validateAndParse2[4],_validateAndParse3=validateAndParse(range),_validateAndParse4=_slicedToArray(_validateAndParse3,5),r1=_validateAndParse4[0],r2=_validateAndParse4[1],r3=_validateAndParse4[2],rp=_validateAndParse4[4],v=[v1,v2,v3],r=[r1,r2!==null&&r2!==void 0?r2:"x",r3!==null&&r3!==void 0?r3:"x"];if(rp){if(!vp)return!1;if(compareSegments(v,r)!==0)return!1;if(compareSegments(vp.split("."),rp.split("."))===-1)return!1}var nonZero=r.findIndex(function(v4){return v4!=="0"})+1,i=op==="~"?2:nonZero>1?nonZero:1;if(compareSegments(v.slice(0,i),r.slice(0,i))!==0)return!1;if(compareSegments(v.slice(i),r.slice(i))===-1)return!1;return!0},semver=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,validateAndParse=function(version){if(typeof version!=="string")throw TypeError("Invalid argument expected string");var match=version.match(semver);if(!match)throw Error("Invalid argument not valid semver ('".concat(version,"' received)"));return match.shift(),match},isWildcard=function(s){return s==="*"||s==="x"||s==="X"},tryParse=function(v){var n=parseInt(v,10);return isNaN(n)?v:n},forceType=function(a,b){return esm_typeof(a)!==esm_typeof(b)?[String(a),String(b)]:[a,b]},compareStrings=function(a,b){if(isWildcard(a)||isWildcard(b))return 0;var _forceType=forceType(tryParse(a),tryParse(b)),_forceType2=_slicedToArray(_forceType,2),ap=_forceType2[0],bp=_forceType2[1];if(ap>bp)return 1;if(ap<bp)return-1;return 0},compareSegments=function(a,b){for(var i=0;i<Math.max(a.length,b.length);i++){var r=compareStrings(a[i]||"0",b[i]||"0");if(r!==0)return r}return 0},operatorResMap={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1]},allowedOperators=Object.keys(operatorResMap),assertValidOperator=function(op){if(typeof op!=="string")throw TypeError("Invalid operator type, expected string but got ".concat(esm_typeof(op)));if(allowedOperators.indexOf(op)===-1)throw Error("Invalid operator, expected one of ".concat(allowedOperators.join("|")))},lru_cache=__webpack_require__(730),lru_cache_default=__webpack_require__.n(lru_cache),enableHydrationLaneScheduling=!0,disableSchedulerTimeoutInWorkLoop=!1,enableSuspenseCallback=!1,enableScopeAPI=!1,enableCreateEventHandleAPI=!1,enableLegacyFBSupport=!1,enableYieldingBeforePassive=!1,enableThrottledScheduling=!1,enableLegacyCache=null,enableAsyncIterableChildren=null,enableTaint=null,enablePostpone=null,enableHalt=!0,enableViewTransition=!0,enableGestureTransition=null,enableScrollEndPolyfill=null,enableSuspenseyImages=!1,enableFizzBlockingRender=null,enableSrcObject=null,enableHydrationChangeEvent=null,enableDefaultTransitionIndicator=null,enableObjectFiber=!1,enableTransitionTracing=!1,enableLegacyHidden=!1,enableSuspenseAvoidThisFallback=!1,enableCPUSuspense=null,enableNoCloningMemoCache=!1,enableUseEffectEventHook=!0,enableFizzExternalRuntime=null,alwaysThrottleRetries=!0,passChildrenWhenCloningPersistedNodes=!1,enableEagerAlternateStateNodeCleanup=!0,enableRetryLaneExpiration=!1,retryLaneExpirationMs=5000,syncLaneExpirationMs=250,transitionLaneExpirationMs=5000,enableInfiniteRenderLoopDetection=!1,enableFragmentRefs=!0,enableFragmentRefsScrollIntoView=!0,renameElementSymbol=!0,enableHiddenSubtreeInsertionEffectCleanup=!0,disableLegacyContext=!0,disableLegacyContextForFunctionComponents=!0,enableMoveBefore=!1,disableClientCache=!0,enableReactTestRendererWarning=!0,disableLegacyMode=!0,disableCommentsAsDOMContainers=!0,enableTrustedTypesIntegration=!1,disableInputAttributeSyncing=!1,disableTextareaChildren=!1,enableProfilerTimer=null,enableComponentPerformanceTrack=!0,enableSchedulingProfiler=!enableComponentPerformanceTrack&&!1,enableProfilerCommitHooks=null,enableProfilerNestedUpdatePhase=null,enableAsyncDebugInfo=!0,enableUpdaterTracking=null,ownerStackLimit=1e4;function ReactSymbols_typeof(o){return ReactSymbols_typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},ReactSymbols_typeof(o)}var REACT_LEGACY_ELEMENT_TYPE=Symbol.for("react.element"),REACT_ELEMENT_TYPE=renameElementSymbol?Symbol.for("react.transitional.element"):REACT_LEGACY_ELEMENT_TYPE,REACT_PORTAL_TYPE=Symbol.for("react.portal"),REACT_FRAGMENT_TYPE=Symbol.for("react.fragment"),REACT_STRICT_MODE_TYPE=Symbol.for("react.strict_mode"),REACT_PROFILER_TYPE=Symbol.for("react.profiler"),REACT_CONSUMER_TYPE=Symbol.for("react.consumer"),REACT_CONTEXT_TYPE=Symbol.for("react.context"),REACT_FORWARD_REF_TYPE=Symbol.for("react.forward_ref"),REACT_SUSPENSE_TYPE=Symbol.for("react.suspense"),REACT_SUSPENSE_LIST_TYPE=Symbol.for("react.suspense_list"),REACT_MEMO_TYPE=Symbol.for("react.memo"),REACT_LAZY_TYPE=Symbol.for("react.lazy"),REACT_SCOPE_TYPE=Symbol.for("react.scope"),REACT_ACTIVITY_TYPE=Symbol.for("react.activity"),REACT_LEGACY_HIDDEN_TYPE=Symbol.for("react.legacy_hidden"),REACT_TRACING_MARKER_TYPE=Symbol.for("react.tracing_marker"),REACT_MEMO_CACHE_SENTINEL=Symbol.for("react.memo_cache_sentinel"),REACT_POSTPONE_TYPE=Symbol.for("react.postpone"),REACT_VIEW_TRANSITION_TYPE=Symbol.for("react.view_transition"),MAYBE_ITERATOR_SYMBOL=Symbol.iterator,FAUX_ITERATOR_SYMBOL="@@iterator";function getIteratorFn(maybeIterable){if(maybeIterable===null||ReactSymbols_typeof(maybeIterable)!=="object")return null;var maybeIterator=MAYBE_ITERATOR_SYMBOL&&maybeIterable[MAYBE_ITERATOR_SYMBOL]||maybeIterable[FAUX_ITERATOR_SYMBOL];if(typeof maybeIterator==="function")return maybeIterator;return null}var ASYNC_ITERATOR=Symbol.asyncIterator,types_ElementTypeClass=1,ElementTypeContext=2,types_ElementTypeFunction=5,types_ElementTypeForwardRef=6,ElementTypeHostComponent=7,types_ElementTypeMemo=8,ElementTypeOtherOrUnknown=9,ElementTypeProfiler=10,ElementTypeRoot=11,ElementTypeSuspense=12,ElementTypeSuspenseList=13,ElementTypeTracingMarker=14,types_ElementTypeVirtual=15,ElementTypeViewTransition=16,ElementTypeActivity=17,ComponentFilterElementType=1,ComponentFilterDisplayName=2,ComponentFilterLocation=3,ComponentFilterHOC=4,ComponentFilterEnvironmentName=5,StrictMode=1,isArray=Array.isArray;let src_isArray=isArray;var process2=__webpack_require__(169);function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r2){return Object.getOwnPropertyDescriptor(e,r2).enumerable})),t.push.apply(t,o)}return t}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=arguments[r]!=null?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r2){utils_defineProperty(e,r2,t[r2])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r2){Object.defineProperty(e,r2,Object.getOwnPropertyDescriptor(t,r2))})}return e}function utils_defineProperty(obj,key,value){if(key=utils_toPropertyKey(key),key in obj)Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0});else obj[key]=value;return obj}function utils_toPropertyKey(t){var i=utils_toPrimitive(t,"string");return utils_typeof(i)=="symbol"?i:i+""}function utils_toPrimitive(t,r){if(utils_typeof(t)!="object"||!t)return t;var e=t[Symbol.toPrimitive];if(e!==void 0){var i=e.call(t,r||"default");if(utils_typeof(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(t)}function utils_typeof(o){return utils_typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},utils_typeof(o)}function _toConsumableArray(arr){return _arrayWithoutHoles(arr)||_iterableToArray(arr)||utils_unsupportedIterableToArray(arr)||_nonIterableSpread()}function _nonIterableSpread(){throw TypeError(`Invalid attempt to spread non-iterable instance.
121
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function utils_unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return utils_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return utils_arrayLikeToArray(o,minLen)}function _iterableToArray(iter){if(typeof Symbol<"u"&&iter[Symbol.iterator]!=null||iter["@@iterator"]!=null)return Array.from(iter)}function _arrayWithoutHoles(arr){if(Array.isArray(arr))return utils_arrayLikeToArray(arr)}function utils_arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=Array(len);i<len;i++)arr2[i]=arr[i];return arr2}var utils_hasOwnProperty=Object.prototype.hasOwnProperty,cachedDisplayNames=new WeakMap,encodedStringCache=new(lru_cache_default())({max:1000}),LEGACY_REACT_PROVIDER_TYPE=Symbol.for("react.provider");function alphaSortKeys(a,b){if(a.toString()>b.toString())return 1;else if(b.toString()>a.toString())return-1;else return 0}function getAllEnumerableKeys(obj){var keys=new Set,current=obj,_loop=function(){var currentKeys=[].concat(_toConsumableArray(Object.keys(current)),_toConsumableArray(Object.getOwnPropertySymbols(current))),descriptors=Object.getOwnPropertyDescriptors(current);currentKeys.forEach(function(key){if(descriptors[key].enumerable)keys.add(key)}),current=Object.getPrototypeOf(current)};while(current!=null)_loop();return keys}function getWrappedDisplayName(outerType,innerType,wrapperName,fallbackName){var displayName=outerType===null||outerType===void 0?void 0:outerType.displayName;return displayName||"".concat(wrapperName,"(").concat(getDisplayName(innerType,fallbackName),")")}function getDisplayName(type){var fallbackName=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Anonymous",nameFromCache=cachedDisplayNames.get(type);if(nameFromCache!=null)return nameFromCache;var displayName=fallbackName;if(typeof type.displayName==="string")displayName=type.displayName;else if(typeof type.name==="string"&&type.name!=="")displayName=type.name;return cachedDisplayNames.set(type,displayName),displayName}var uidCounter=0;function getUID(){return++uidCounter}function utfDecodeStringWithRanges(array,left,right){var string="";for(var i=left;i<=right;i++)string+=String.fromCodePoint(array[i]);return string}function surrogatePairToCodePoint(charCode1,charCode2){return((charCode1&1023)<<10)+(charCode2&1023)+65536}function utfEncodeString(string){var cached=encodedStringCache.get(string);if(cached!==void 0)return cached;var encoded=[],i=0,charCode;while(i<string.length){if(charCode=string.charCodeAt(i),(charCode&63488)===55296)encoded.push(surrogatePairToCodePoint(charCode,string.charCodeAt(++i)));else encoded.push(charCode);++i}return encodedStringCache.set(string,encoded),encoded}function printOperationsArray(operations){var rendererID=operations[0],rootID=operations[1],logs=["operations for renderer:".concat(rendererID," and root:").concat(rootID)],i=2,stringTable=[null],stringTableSize=operations[i++],stringTableEnd=i+stringTableSize;while(i<stringTableEnd){var nextLength=operations[i++],nextString=utfDecodeStringWithRanges(operations,i,i+nextLength-1);stringTable.push(nextString),i+=nextLength}while(i<operations.length){var operation=operations[i];switch(operation){case TREE_OPERATION_ADD:{var id=operations[i+1],type=operations[i+2];if(i+=3,type===ElementTypeRoot)logs.push("Add new root node ".concat(id)),i++,i++,i++,i++;else{var parentID=operations[i];i++,i++;var displayNameStringID=operations[i],displayName=stringTable[displayNameStringID];i++,i++,i++,logs.push("Add node ".concat(id," (").concat(displayName||"null",") as child of ").concat(parentID))}break}case TREE_OPERATION_REMOVE:{var removeLength=operations[i+1];i+=2;for(var removeIndex=0;removeIndex<removeLength;removeIndex++){var _id=operations[i];i+=1,logs.push("Remove node ".concat(_id))}break}case TREE_OPERATION_REMOVE_ROOT:{i+=1,logs.push("Remove root ".concat(rootID));break}case TREE_OPERATION_SET_SUBTREE_MODE:{var _id2=operations[i+1],mode=operations[i+2];i+=3,logs.push("Mode ".concat(mode," set for subtree with root ").concat(_id2));break}case TREE_OPERATION_REORDER_CHILDREN:{var _id3=operations[i+1],numChildren=operations[i+2];i+=3;var children=operations.slice(i,i+numChildren);i+=numChildren,logs.push("Re-order node ".concat(_id3," children ").concat(children.join(",")));break}case TREE_OPERATION_UPDATE_TREE_BASE_DURATION:i+=3;break;case TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS:{var _id4=operations[i+1],numErrors=operations[i+2],numWarnings=operations[i+3];i+=4,logs.push("Node ".concat(_id4," has ").concat(numErrors," errors and ").concat(numWarnings," warnings"));break}case SUSPENSE_TREE_OPERATION_ADD:{var fiberID=operations[i+1],_parentID=operations[i+2],nameStringID=operations[i+3],isSuspended=operations[i+4],numRects=operations[i+5];i+=6;var name=stringTable[nameStringID],rects=void 0;if(numRects===-1)rects="null";else{rects="[";for(var rectIndex=0;rectIndex<numRects;rectIndex++){var offset=i+rectIndex*4,x=operations[offset+0],y=operations[offset+1],width=operations[offset+2],height=operations[offset+3];if(rectIndex>0)rects+=", ";rects+="(".concat(x,", ").concat(y,", ").concat(width,", ").concat(height,")"),i+=4}rects+="]"}logs.push("Add suspense node ".concat(fiberID," (").concat(String(name),",rects={").concat(rects,"}) under ").concat(_parentID," suspended ").concat(isSuspended));break}case SUSPENSE_TREE_OPERATION_REMOVE:{var _removeLength=operations[i+1];i+=2;for(var _removeIndex=0;_removeIndex<_removeLength;_removeIndex++){var _id5=operations[i];i+=1,logs.push("Remove suspense node ".concat(_id5))}break}case SUSPENSE_TREE_OPERATION_REORDER_CHILDREN:{var _id6=operations[i+1],_numChildren=operations[i+2];i+=3;var _children=operations.slice(i,i+_numChildren);i+=_numChildren,logs.push("Re-order suspense node ".concat(_id6," children ").concat(_children.join(",")));break}case SUSPENSE_TREE_OPERATION_RESIZE:{var _id7=operations[i+1],_numRects=operations[i+2];if(i+=3,_numRects===-1)logs.push("Resize suspense node ".concat(_id7," to null"));else{var line="Resize suspense node ".concat(_id7," to [");for(var _rectIndex=0;_rectIndex<_numRects;_rectIndex++){var _x=operations[i+0],_y=operations[i+1],_width=operations[i+2],_height=operations[i+3];if(_rectIndex>0)line+=", ";line+="(".concat(_x,", ").concat(_y,", ").concat(_width,", ").concat(_height,")"),i+=4}logs.push(line+"]")}break}case SUSPENSE_TREE_OPERATION_SUSPENDERS:{i++;var changeLength=operations[i++];for(var changeIndex=0;changeIndex<changeLength;changeIndex++){var _id8=operations[i++],hasUniqueSuspenders=operations[i++]===1,_isSuspended=operations[i++]===1,environmentNamesLength=operations[i++];i+=environmentNamesLength,logs.push("Suspense node ".concat(_id8," unique suspenders set to ").concat(String(hasUniqueSuspenders)," is suspended set to ").concat(String(_isSuspended)," with ").concat(String(environmentNamesLength)," environments"))}break}default:throw Error('Unsupported Bridge operation "'.concat(operation,'"'))}}console.log(logs.join(`
122
+ `))}function getDefaultComponentFilters(){return[{type:ComponentFilterElementType,value:ElementTypeHostComponent,isEnabled:!0}]}function getSavedComponentFilters(){try{var raw=localStorageGetItem(LOCAL_STORAGE_COMPONENT_FILTER_PREFERENCES_KEY);if(raw!=null){var parsedFilters=JSON.parse(raw);return filterOutLocationComponentFilters(parsedFilters)}}catch(error){}return getDefaultComponentFilters()}function setSavedComponentFilters(componentFilters){localStorageSetItem(LOCAL_STORAGE_COMPONENT_FILTER_PREFERENCES_KEY,JSON.stringify(filterOutLocationComponentFilters(componentFilters)))}function filterOutLocationComponentFilters(componentFilters){if(!Array.isArray(componentFilters))return componentFilters;return componentFilters.filter(function(f){return f.type!==ComponentFilterLocation})}var vscodeFilepath="vscode://file/{path}:{line}:{column}";function getDefaultPreset(){return typeof process2.env.EDITOR_URL==="string"?"custom":"vscode"}function getDefaultOpenInEditorURL(){return typeof process2.env.EDITOR_URL==="string"?process2.env.EDITOR_URL:vscodeFilepath}function getOpenInEditorURL(){try{var rawPreset=localStorageGetItem(LOCAL_STORAGE_OPEN_IN_EDITOR_URL_PRESET);switch(rawPreset){case'"vscode"':return vscodeFilepath}var raw=localStorageGetItem(LOCAL_STORAGE_OPEN_IN_EDITOR_URL);if(raw!=null)return JSON.parse(raw)}catch(error){}return getDefaultOpenInEditorURL()}function getAlwaysOpenInEditor(){try{var raw=localStorageGetItem(LOCAL_STORAGE_ALWAYS_OPEN_IN_EDITOR);return raw==="true"}catch(error){}return!1}function parseElementDisplayNameFromBackend(displayName,type){if(displayName===null)return{formattedDisplayName:null,hocDisplayNames:null,compiledWithForget:!1};if(displayName.startsWith("Forget(")){var displayNameWithoutForgetWrapper=displayName.slice(7,displayName.length-1),_parseElementDisplayN=parseElementDisplayNameFromBackend(displayNameWithoutForgetWrapper,type),formattedDisplayName=_parseElementDisplayN.formattedDisplayName,_hocDisplayNames=_parseElementDisplayN.hocDisplayNames;return{formattedDisplayName,hocDisplayNames:_hocDisplayNames,compiledWithForget:!0}}var hocDisplayNames=null;switch(type){case ElementTypeClass:case ElementTypeForwardRef:case ElementTypeFunction:case ElementTypeMemo:case ElementTypeVirtual:if(displayName.indexOf("(")>=0){var matches=displayName.match(/[^()]+/g);if(matches!=null)displayName=matches.pop(),hocDisplayNames=matches}break;default:break}return{formattedDisplayName:displayName,hocDisplayNames,compiledWithForget:!1}}function shallowDiffers(prev,next){for(var attribute in prev)if(!(attribute in next))return!0;for(var _attribute in next)if(prev[_attribute]!==next[_attribute])return!0;return!1}function utils_getInObject(object,path){return path.reduce(function(reduced,attr){if(reduced){if(utils_hasOwnProperty.call(reduced,attr))return reduced[attr];if(typeof reduced[Symbol.iterator]==="function")return Array.from(reduced)[attr]}return null},object)}function deletePathInObject(object,path){var length=path.length,last=path[length-1];if(object!=null){var parent=utils_getInObject(object,path.slice(0,length-1));if(parent)if(src_isArray(parent))parent.splice(last,1);else delete parent[last]}}function renamePathInObject(object,oldPath,newPath){var length=oldPath.length;if(object!=null){var parent=utils_getInObject(object,oldPath.slice(0,length-1));if(parent){var lastOld=oldPath[length-1],lastNew=newPath[length-1];if(parent[lastNew]=parent[lastOld],src_isArray(parent))parent.splice(lastOld,1);else delete parent[lastOld]}}}function utils_setInObject(object,path,value){var length=path.length,last=path[length-1];if(object!=null){var parent=utils_getInObject(object,path.slice(0,length-1));if(parent)parent[last]=value}}function isError(data){if("name"in data&&"message"in data)while(data){if(Object.prototype.toString.call(data)==="[object Error]")return!0;data=Object.getPrototypeOf(data)}return!1}function getDataType(data){if(data===null)return"null";else if(data===void 0)return"undefined";if(typeof HTMLElement<"u"&&data instanceof HTMLElement)return"html_element";var type=utils_typeof(data);switch(type){case"bigint":return"bigint";case"boolean":return"boolean";case"function":return"function";case"number":if(Number.isNaN(data))return"nan";else if(!Number.isFinite(data))return"infinity";else return"number";case"object":switch(data.$$typeof){case REACT_ELEMENT_TYPE:case REACT_LEGACY_ELEMENT_TYPE:return"react_element";case REACT_LAZY_TYPE:return"react_lazy"}if(src_isArray(data))return"array";else if(ArrayBuffer.isView(data))return utils_hasOwnProperty.call(data.constructor,"BYTES_PER_ELEMENT")?"typed_array":"data_view";else if(data.constructor&&data.constructor.name==="ArrayBuffer")return"array_buffer";else if(typeof data[Symbol.iterator]==="function"){var iterator=data[Symbol.iterator]();if(!iterator);else return iterator===data?"opaque_iterator":"iterator"}else if(data.constructor&&data.constructor.name==="RegExp")return"regexp";else if(typeof data.then==="function")return"thenable";else if(isError(data))return"error";else{var toStringValue=Object.prototype.toString.call(data);if(toStringValue==="[object Date]")return"date";else if(toStringValue==="[object HTMLAllCollection]")return"html_all_collection"}if(!isPlainObject(data))return"class_instance";return"object";case"string":return"string";case"symbol":return"symbol";case"undefined":if(Object.prototype.toString.call(data)==="[object HTMLAllCollection]")return"html_all_collection";return"undefined";default:return"unknown"}}function typeOfWithLegacyElementSymbol(object){if(utils_typeof(object)==="object"&&object!==null){var $$typeof=object.$$typeof;switch($$typeof){case REACT_ELEMENT_TYPE:case REACT_LEGACY_ELEMENT_TYPE:var type=object.type;switch(type){case REACT_FRAGMENT_TYPE:case REACT_PROFILER_TYPE:case REACT_STRICT_MODE_TYPE:case REACT_SUSPENSE_TYPE:case REACT_SUSPENSE_LIST_TYPE:case REACT_VIEW_TRANSITION_TYPE:return type;default:var $$typeofType=type&&type.$$typeof;switch($$typeofType){case REACT_CONTEXT_TYPE:case REACT_FORWARD_REF_TYPE:case REACT_LAZY_TYPE:case REACT_MEMO_TYPE:return $$typeofType;case REACT_CONSUMER_TYPE:return $$typeofType;default:return $$typeof}}case REACT_PORTAL_TYPE:return $$typeof}}return}function getDisplayNameForReactElement(element){var elementType=typeOfWithLegacyElementSymbol(element);switch(elementType){case REACT_CONSUMER_TYPE:return"ContextConsumer";case LEGACY_REACT_PROVIDER_TYPE:return"ContextProvider";case REACT_CONTEXT_TYPE:return"Context";case REACT_FORWARD_REF_TYPE:return"ForwardRef";case REACT_FRAGMENT_TYPE:return"Fragment";case REACT_LAZY_TYPE:return"Lazy";case REACT_MEMO_TYPE:return"Memo";case REACT_PORTAL_TYPE:return"Portal";case REACT_PROFILER_TYPE:return"Profiler";case REACT_STRICT_MODE_TYPE:return"StrictMode";case REACT_SUSPENSE_TYPE:return"Suspense";case REACT_SUSPENSE_LIST_TYPE:return"SuspenseList";case REACT_VIEW_TRANSITION_TYPE:return"ViewTransition";case REACT_TRACING_MARKER_TYPE:return"TracingMarker";default:var type=element.type;if(typeof type==="string")return type;else if(typeof type==="function")return getDisplayName(type,"Anonymous");else if(type!=null)return"NotImplementedInDevtools";else return"Element"}}var MAX_PREVIEW_STRING_LENGTH=50;function truncateForDisplay(string){var length=arguments.length>1&&arguments[1]!==void 0?arguments[1]:MAX_PREVIEW_STRING_LENGTH;if(string.length>length)return string.slice(0,length)+"…";else return string}function formatDataForPreview(data,showFormattedValue){if(data!=null&&utils_hasOwnProperty.call(data,meta.type))return showFormattedValue?data[meta.preview_long]:data[meta.preview_short];var type=getDataType(data);switch(type){case"html_element":return"<".concat(truncateForDisplay(data.tagName.toLowerCase())," />");case"function":if(typeof data.name==="function"||data.name==="")return"() => {}";return"".concat(truncateForDisplay(data.name),"() {}");case"string":return'"'.concat(data,'"');case"bigint":return truncateForDisplay(data.toString()+"n");case"regexp":return truncateForDisplay(data.toString());case"symbol":return truncateForDisplay(data.toString());case"react_element":return"<".concat(truncateForDisplay(getDisplayNameForReactElement(data)||"Unknown")," />");case"react_lazy":var payload=data._payload;if(payload!==null&&utils_typeof(payload)==="object"){if(payload._status===0)return"pending lazy()";if(payload._status===1&&payload._result!=null)if(showFormattedValue){var formatted=formatDataForPreview(payload._result.default,!1);return"fulfilled lazy() {".concat(truncateForDisplay(formatted),"}")}else return"fulfilled lazy() {…}";if(payload._status===2)if(showFormattedValue){var _formatted=formatDataForPreview(payload._result,!1);return"rejected lazy() {".concat(truncateForDisplay(_formatted),"}")}else return"rejected lazy() {…}";if(payload.status==="pending"||payload.status==="blocked")return"pending lazy()";if(payload.status==="fulfilled")if(showFormattedValue){var _formatted2=formatDataForPreview(payload.value,!1);return"fulfilled lazy() {".concat(truncateForDisplay(_formatted2),"}")}else return"fulfilled lazy() {…}";if(payload.status==="rejected")if(showFormattedValue){var _formatted3=formatDataForPreview(payload.reason,!1);return"rejected lazy() {".concat(truncateForDisplay(_formatted3),"}")}else return"rejected lazy() {…}"}return"lazy()";case"array_buffer":return"ArrayBuffer(".concat(data.byteLength,")");case"data_view":return"DataView(".concat(data.buffer.byteLength,")");case"array":if(showFormattedValue){var _formatted4="";for(var i=0;i<data.length;i++){if(i>0)_formatted4+=", ";if(_formatted4+=formatDataForPreview(data[i],!1),_formatted4.length>MAX_PREVIEW_STRING_LENGTH)break}return"[".concat(truncateForDisplay(_formatted4),"]")}else{var length=utils_hasOwnProperty.call(data,meta.size)?data[meta.size]:data.length;return"Array(".concat(length,")")}case"typed_array":var shortName="".concat(data.constructor.name,"(").concat(data.length,")");if(showFormattedValue){var _formatted5="";for(var _i=0;_i<data.length;_i++){if(_i>0)_formatted5+=", ";if(_formatted5+=data[_i],_formatted5.length>MAX_PREVIEW_STRING_LENGTH)break}return"".concat(shortName," [").concat(truncateForDisplay(_formatted5),"]")}else return shortName;case"iterator":var name=data.constructor.name;if(showFormattedValue){var array=Array.from(data),_formatted6="";for(var _i2=0;_i2<array.length;_i2++){var entryOrEntries=array[_i2];if(_i2>0)_formatted6+=", ";if(src_isArray(entryOrEntries)){var key=formatDataForPreview(entryOrEntries[0],!0),value=formatDataForPreview(entryOrEntries[1],!1);_formatted6+="".concat(key," => ").concat(value)}else _formatted6+=formatDataForPreview(entryOrEntries,!1);if(_formatted6.length>MAX_PREVIEW_STRING_LENGTH)break}return"".concat(name,"(").concat(data.size,") {").concat(truncateForDisplay(_formatted6),"}")}else return"".concat(name,"(").concat(data.size,")");case"opaque_iterator":return data[Symbol.toStringTag];case"date":return data.toString();case"class_instance":try{var resolvedConstructorName=data.constructor.name;if(typeof resolvedConstructorName==="string")return resolvedConstructorName;if(resolvedConstructorName=Object.getPrototypeOf(data).constructor.name,typeof resolvedConstructorName==="string")return resolvedConstructorName;try{return truncateForDisplay(String(data))}catch(error){return"unserializable"}}catch(error){return"unserializable"}case"thenable":var displayName;if(isPlainObject(data))displayName="Thenable";else{var _resolvedConstructorName=data.constructor.name;if(typeof _resolvedConstructorName!=="string")_resolvedConstructorName=Object.getPrototypeOf(data).constructor.name;if(typeof _resolvedConstructorName==="string")displayName=_resolvedConstructorName;else displayName="Thenable"}switch(data.status){case"pending":return"pending ".concat(displayName);case"fulfilled":if(showFormattedValue){var _formatted7=formatDataForPreview(data.value,!1);return"fulfilled ".concat(displayName," {").concat(truncateForDisplay(_formatted7),"}")}else return"fulfilled ".concat(displayName," {…}");case"rejected":if(showFormattedValue){var _formatted8=formatDataForPreview(data.reason,!1);return"rejected ".concat(displayName," {").concat(truncateForDisplay(_formatted8),"}")}else return"rejected ".concat(displayName," {…}");default:return displayName}case"object":if(showFormattedValue){var keys=Array.from(getAllEnumerableKeys(data)).sort(alphaSortKeys),_formatted9="";for(var _i3=0;_i3<keys.length;_i3++){var _key=keys[_i3];if(_i3>0)_formatted9+=", ";if(_formatted9+="".concat(_key.toString(),": ").concat(formatDataForPreview(data[_key],!1)),_formatted9.length>MAX_PREVIEW_STRING_LENGTH)break}return"{".concat(truncateForDisplay(_formatted9),"}")}else return"{…}";case"error":return truncateForDisplay(String(data));case"boolean":case"number":case"infinity":case"nan":case"null":case"undefined":return String(data);default:try{return truncateForDisplay(String(data))}catch(error){return"unserializable"}}}var isPlainObject=function(object){var objectPrototype=Object.getPrototypeOf(object);if(!objectPrototype)return!0;var objectParentPrototype=Object.getPrototypeOf(objectPrototype);return!objectParentPrototype};function backendToFrontendSerializedElementMapper(element){var _parseElementDisplayN2=parseElementDisplayNameFromBackend(element.displayName,element.type),formattedDisplayName=_parseElementDisplayN2.formattedDisplayName,hocDisplayNames=_parseElementDisplayN2.hocDisplayNames,compiledWithForget=_parseElementDisplayN2.compiledWithForget;return _objectSpread(_objectSpread({},element),{},{displayName:formattedDisplayName,hocDisplayNames,compiledWithForget})}function normalizeUrlIfValid(url){try{return new URL(url).toString()}catch(_unused){return url}}function getIsReloadAndProfileSupported(){var isBackendStorageAPISupported=!1;try{localStorage.getItem("test"),isBackendStorageAPISupported=!0}catch(error){}return isBackendStorageAPISupported&&isSynchronousXHRSupported()}function getIfReloadedAndProfiling(){return sessionStorageGetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY)==="true"}function getProfilingSettings(){return{recordChangeDescriptions:sessionStorageGetItem(SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY)==="true",recordTimeline:sessionStorageGetItem(SESSION_STORAGE_RECORD_TIMELINE_KEY)==="true"}}function onReloadAndProfile(recordChangeDescriptions,recordTimeline){sessionStorageSetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY,"true"),sessionStorageSetItem(SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY,recordChangeDescriptions?"true":"false"),sessionStorageSetItem(SESSION_STORAGE_RECORD_TIMELINE_KEY,recordTimeline?"true":"false")}function onReloadAndProfileFlagsReset(){sessionStorageRemoveItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY),sessionStorageRemoveItem(SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY),sessionStorageRemoveItem(SESSION_STORAGE_RECORD_TIMELINE_KEY)}function unionOfTwoArrays(a,b){var result=a;for(var i=0;i<b.length;i++){var value=b[i];if(a.indexOf(value)===-1){if(result===a)result=a.slice(0);result.push(value)}}return result}function noop(){}function hydration_ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r2){return Object.getOwnPropertyDescriptor(e,r2).enumerable})),t.push.apply(t,o)}return t}function hydration_objectSpread(e){for(var r=1;r<arguments.length;r++){var t=arguments[r]!=null?arguments[r]:{};r%2?hydration_ownKeys(Object(t),!0).forEach(function(r2){hydration_defineProperty(e,r2,t[r2])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):hydration_ownKeys(Object(t)).forEach(function(r2){Object.defineProperty(e,r2,Object.getOwnPropertyDescriptor(t,r2))})}return e}function hydration_defineProperty(obj,key,value){if(key=hydration_toPropertyKey(key),key in obj)Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0});else obj[key]=value;return obj}function hydration_toPropertyKey(t){var i=hydration_toPrimitive(t,"string");return hydration_typeof(i)=="symbol"?i:i+""}function hydration_toPrimitive(t,r){if(hydration_typeof(t)!="object"||!t)return t;var e=t[Symbol.toPrimitive];if(e!==void 0){var i=e.call(t,r||"default");if(hydration_typeof(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(t)}function hydration_typeof(o){return hydration_typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},hydration_typeof(o)}var meta={inspectable:Symbol("inspectable"),inspected:Symbol("inspected"),name:Symbol("name"),preview_long:Symbol("preview_long"),preview_short:Symbol("preview_short"),readonly:Symbol("readonly"),size:Symbol("size"),type:Symbol("type"),unserializable:Symbol("unserializable")},LEVEL_THRESHOLD=2;function createDehydrated(type,inspectable,data,cleaned,path){cleaned.push(path);var dehydrated={inspectable,type,preview_long:formatDataForPreview(data,!0),preview_short:formatDataForPreview(data,!1),name:typeof data.constructor!=="function"||typeof data.constructor.name!=="string"||data.constructor.name==="Object"?"":data.constructor.name};if(type==="array"||type==="typed_array")dehydrated.size=data.length;else if(type==="object")dehydrated.size=Object.keys(data).length;if(type==="iterator"||type==="typed_array")dehydrated.readonly=!0;return dehydrated}function dehydrate(data,cleaned,unserializable,path,isPathAllowed){var level=arguments.length>5&&arguments[5]!==void 0?arguments[5]:0,type=getDataType(data),isPathAllowedCheck;switch(type){case"html_element":return cleaned.push(path),{inspectable:!1,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:data.tagName,type};case"function":return cleaned.push(path),{inspectable:!1,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:typeof data.name==="function"||!data.name?"function":data.name,type};case"string":if(isPathAllowedCheck=isPathAllowed(path),isPathAllowedCheck)return data;else return data.length<=500?data:data.slice(0,500)+"...";case"bigint":return cleaned.push(path),{inspectable:!1,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:data.toString(),type};case"symbol":return cleaned.push(path),{inspectable:!1,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:data.toString(),type};case"react_element":{if(isPathAllowedCheck=isPathAllowed(path),level>=LEVEL_THRESHOLD&&!isPathAllowedCheck)return cleaned.push(path),{inspectable:!0,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:getDisplayNameForReactElement(data)||"Unknown",type};var unserializableValue={unserializable:!0,type,readonly:!0,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:getDisplayNameForReactElement(data)||"Unknown"};if(unserializableValue.key=dehydrate(data.key,cleaned,unserializable,path.concat(["key"]),isPathAllowed,isPathAllowedCheck?1:level+1),data.$$typeof===REACT_LEGACY_ELEMENT_TYPE)unserializableValue.ref=dehydrate(data.ref,cleaned,unserializable,path.concat(["ref"]),isPathAllowed,isPathAllowedCheck?1:level+1);return unserializableValue.props=dehydrate(data.props,cleaned,unserializable,path.concat(["props"]),isPathAllowed,isPathAllowedCheck?1:level+1),unserializable.push(path),unserializableValue}case"react_lazy":{isPathAllowedCheck=isPathAllowed(path);var payload=data._payload;if(level>=LEVEL_THRESHOLD&&!isPathAllowedCheck){cleaned.push(path);var inspectable=payload!==null&&hydration_typeof(payload)==="object"&&(payload._status===1||payload._status===2||payload.status==="fulfilled"||payload.status==="rejected");return{inspectable,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:"lazy()",type}}var _unserializableValue={unserializable:!0,type,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:"lazy()"};return _unserializableValue._payload=dehydrate(payload,cleaned,unserializable,path.concat(["_payload"]),isPathAllowed,isPathAllowedCheck?1:level+1),unserializable.push(path),_unserializableValue}case"array_buffer":case"data_view":return cleaned.push(path),{inspectable:!1,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:type==="data_view"?"DataView":"ArrayBuffer",size:data.byteLength,type};case"array":if(isPathAllowedCheck=isPathAllowed(path),level>=LEVEL_THRESHOLD&&!isPathAllowedCheck)return createDehydrated(type,!0,data,cleaned,path);var arr=[];for(var i=0;i<data.length;i++)arr[i]=dehydrateKey(data,i,cleaned,unserializable,path.concat([i]),isPathAllowed,isPathAllowedCheck?1:level+1);return arr;case"html_all_collection":case"typed_array":case"iterator":if(isPathAllowedCheck=isPathAllowed(path),level>=LEVEL_THRESHOLD&&!isPathAllowedCheck)return createDehydrated(type,!0,data,cleaned,path);else{var _unserializableValue2={unserializable:!0,type,readonly:!0,size:type==="typed_array"?data.length:void 0,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:typeof data.constructor!=="function"||typeof data.constructor.name!=="string"||data.constructor.name==="Object"?"":data.constructor.name};return Array.from(data).forEach(function(item,i2){return _unserializableValue2[i2]=dehydrate(item,cleaned,unserializable,path.concat([i2]),isPathAllowed,isPathAllowedCheck?1:level+1)}),unserializable.push(path),_unserializableValue2}case"opaque_iterator":return cleaned.push(path),{inspectable:!1,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:data[Symbol.toStringTag],type};case"date":return cleaned.push(path),{inspectable:!1,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:data.toString(),type};case"regexp":return cleaned.push(path),{inspectable:!1,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:data.toString(),type};case"thenable":if(isPathAllowedCheck=isPathAllowed(path),level>=LEVEL_THRESHOLD&&!isPathAllowedCheck)return cleaned.push(path),{inspectable:data.status==="fulfilled"||data.status==="rejected",preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:data.toString(),type};if(data.status==="resolved_model"||data.status==="resolve_module")data.then(noop);switch(data.status){case"fulfilled":{var _unserializableValue3={unserializable:!0,type,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:"fulfilled Thenable"};return _unserializableValue3.value=dehydrate(data.value,cleaned,unserializable,path.concat(["value"]),isPathAllowed,isPathAllowedCheck?1:level+1),unserializable.push(path),_unserializableValue3}case"rejected":{var _unserializableValue4={unserializable:!0,type,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:"rejected Thenable"};return _unserializableValue4.reason=dehydrate(data.reason,cleaned,unserializable,path.concat(["reason"]),isPathAllowed,isPathAllowedCheck?1:level+1),unserializable.push(path),_unserializableValue4}default:return cleaned.push(path),{inspectable:!1,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:data.toString(),type}}case"object":if(isPathAllowedCheck=isPathAllowed(path),level>=LEVEL_THRESHOLD&&!isPathAllowedCheck)return createDehydrated(type,!0,data,cleaned,path);else{var object={};return getAllEnumerableKeys(data).forEach(function(key){var name=key.toString();object[name]=dehydrateKey(data,key,cleaned,unserializable,path.concat([name]),isPathAllowed,isPathAllowedCheck?1:level+1)}),object}case"class_instance":{if(isPathAllowedCheck=isPathAllowed(path),level>=LEVEL_THRESHOLD&&!isPathAllowedCheck)return createDehydrated(type,!0,data,cleaned,path);var value={unserializable:!0,type,readonly:!0,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:typeof data.constructor!=="function"||typeof data.constructor.name!=="string"?"":data.constructor.name};return getAllEnumerableKeys(data).forEach(function(key){var keyAsString=key.toString();value[keyAsString]=dehydrate(data[key],cleaned,unserializable,path.concat([keyAsString]),isPathAllowed,isPathAllowedCheck?1:level+1)}),unserializable.push(path),value}case"error":{if(isPathAllowedCheck=isPathAllowed(path),level>=LEVEL_THRESHOLD&&!isPathAllowedCheck)return createDehydrated(type,!0,data,cleaned,path);var _value={unserializable:!0,type,readonly:!0,preview_short:formatDataForPreview(data,!1),preview_long:formatDataForPreview(data,!0),name:data.name};if(_value.message=dehydrate(data.message,cleaned,unserializable,path.concat(["message"]),isPathAllowed,isPathAllowedCheck?1:level+1),_value.stack=dehydrate(data.stack,cleaned,unserializable,path.concat(["stack"]),isPathAllowed,isPathAllowedCheck?1:level+1),"cause"in data)_value.cause=dehydrate(data.cause,cleaned,unserializable,path.concat(["cause"]),isPathAllowed,isPathAllowedCheck?1:level+1);return getAllEnumerableKeys(data).forEach(function(key){var keyAsString=key.toString();_value[keyAsString]=dehydrate(data[key],cleaned,unserializable,path.concat([keyAsString]),isPathAllowed,isPathAllowedCheck?1:level+1)}),unserializable.push(path),_value}case"infinity":case"nan":case"undefined":return cleaned.push(path),{type};default:return data}}function dehydrateKey(parent,key,cleaned,unserializable,path,isPathAllowed){var level=arguments.length>6&&arguments[6]!==void 0?arguments[6]:0;try{return dehydrate(parent[key],cleaned,unserializable,path,isPathAllowed,level)}catch(error){var preview="";if(hydration_typeof(error)==="object"&&error!==null&&typeof error.stack==="string")preview=error.stack;else if(typeof error==="string")preview=error;return cleaned.push(path),{inspectable:!1,preview_short:"[Exception]",preview_long:preview?"[Exception: "+preview+"]":"[Exception]",name:preview,type:"unknown"}}}function fillInPath(object,data,path,value){var target=getInObject(object,path);if(target!=null){if(!target[meta.unserializable])delete target[meta.inspectable],delete target[meta.inspected],delete target[meta.name],delete target[meta.preview_long],delete target[meta.preview_short],delete target[meta.readonly],delete target[meta.size],delete target[meta.type]}if(value!==null&&data.unserializable.length>0){var unserializablePath=data.unserializable[0],isMatch=unserializablePath.length===path.length;for(var i=0;i<path.length;i++)if(path[i]!==unserializablePath[i]){isMatch=!1;break}if(isMatch)upgradeUnserializable(value,value)}setInObject(object,path,value)}function hydrate(object,cleaned,unserializable){return cleaned.forEach(function(path){var length=path.length,last=path[length-1],parent=getInObject(object,path.slice(0,length-1));if(!parent||!parent.hasOwnProperty(last))return;var value=parent[last];if(!value)return;else if(value.type==="infinity")parent[last]=1/0;else if(value.type==="nan")parent[last]=NaN;else if(value.type==="undefined")parent[last]=void 0;else{var replaced={};replaced[meta.inspectable]=!!value.inspectable,replaced[meta.inspected]=!1,replaced[meta.name]=value.name,replaced[meta.preview_long]=value.preview_long,replaced[meta.preview_short]=value.preview_short,replaced[meta.size]=value.size,replaced[meta.readonly]=!!value.readonly,replaced[meta.type]=value.type,parent[last]=replaced}}),unserializable.forEach(function(path){var length=path.length,last=path[length-1],parent=getInObject(object,path.slice(0,length-1));if(!parent||!parent.hasOwnProperty(last))return;var node=parent[last],replacement=hydration_objectSpread({},node);upgradeUnserializable(replacement,node),parent[last]=replacement}),object}function upgradeUnserializable(destination,source){Object.defineProperties(destination,hydration_defineProperty(hydration_defineProperty(hydration_defineProperty(hydration_defineProperty(hydration_defineProperty(hydration_defineProperty(hydration_defineProperty(hydration_defineProperty({},meta.inspected,{configurable:!0,enumerable:!1,value:!!source.inspected}),meta.name,{configurable:!0,enumerable:!1,value:source.name}),meta.preview_long,{configurable:!0,enumerable:!1,value:source.preview_long}),meta.preview_short,{configurable:!0,enumerable:!1,value:source.preview_short}),meta.size,{configurable:!0,enumerable:!1,value:source.size}),meta.readonly,{configurable:!0,enumerable:!1,value:!!source.readonly}),meta.type,{configurable:!0,enumerable:!1,value:source.type}),meta.unserializable,{configurable:!0,enumerable:!1,value:!!source.unserializable})),delete destination.inspected,delete destination.name,delete destination.preview_long,delete destination.preview_short,delete destination.size,delete destination.readonly,delete destination.type,delete destination.unserializable}var isArrayImpl=Array.isArray;function isArray_isArray(a){return isArrayImpl(a)}let shared_isArray=isArray_isArray;function backend_utils_typeof(o){return backend_utils_typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},backend_utils_typeof(o)}function utils_ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r2){return Object.getOwnPropertyDescriptor(e,r2).enumerable})),t.push.apply(t,o)}return t}function utils_objectSpread(e){for(var r=1;r<arguments.length;r++){var t=arguments[r]!=null?arguments[r]:{};r%2?utils_ownKeys(Object(t),!0).forEach(function(r2){backend_utils_defineProperty(e,r2,t[r2])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):utils_ownKeys(Object(t)).forEach(function(r2){Object.defineProperty(e,r2,Object.getOwnPropertyDescriptor(t,r2))})}return e}function backend_utils_defineProperty(obj,key,value){if(key=backend_utils_toPropertyKey(key),key in obj)Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0});else obj[key]=value;return obj}function backend_utils_toPropertyKey(t){var i=backend_utils_toPrimitive(t,"string");return backend_utils_typeof(i)=="symbol"?i:i+""}function backend_utils_toPrimitive(t,r){if(backend_utils_typeof(t)!="object"||!t)return t;var e=t[Symbol.toPrimitive];if(e!==void 0){var i=e.call(t,r||"default");if(backend_utils_typeof(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(t)}var FIRST_DEVTOOLS_BACKEND_LOCKSTEP_VER="999.9.9";function hasAssignedBackend(version){if(version==null||version==="")return!1;return gte(version,FIRST_DEVTOOLS_BACKEND_LOCKSTEP_VER)}function cleanForBridge(data,isPathAllowed){var path=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];if(data!==null){var cleanedPaths=[],unserializablePaths=[],cleanedData=dehydrate(data,cleanedPaths,unserializablePaths,path,isPathAllowed);return{data:cleanedData,cleaned:cleanedPaths,unserializable:unserializablePaths}}else return null}function copyWithDelete(obj,path){var index=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,key=path[index],updated=shared_isArray(obj)?obj.slice():utils_objectSpread({},obj);if(index+1===path.length)if(shared_isArray(updated))updated.splice(key,1);else delete updated[key];else updated[key]=copyWithDelete(obj[key],path,index+1);return updated}function copyWithRename(obj,oldPath,newPath){var index=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,oldKey=oldPath[index],updated=shared_isArray(obj)?obj.slice():utils_objectSpread({},obj);if(index+1===oldPath.length){var newKey=newPath[index];if(updated[newKey]=updated[oldKey],shared_isArray(updated))updated.splice(oldKey,1);else delete updated[oldKey]}else updated[oldKey]=copyWithRename(obj[oldKey],oldPath,newPath,index+1);return updated}function copyWithSet(obj,path,value){var index=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0;if(index>=path.length)return value;var key=path[index],updated=shared_isArray(obj)?obj.slice():utils_objectSpread({},obj);return updated[key]=copyWithSet(obj[key],path,value,index+1),updated}function getEffectDurations(root){var effectDuration=null,passiveEffectDuration=null,hostRoot=root.current;if(hostRoot!=null){var stateNode=hostRoot.stateNode;if(stateNode!=null)effectDuration=stateNode.effectDuration!=null?stateNode.effectDuration:null,passiveEffectDuration=stateNode.passiveEffectDuration!=null?stateNode.passiveEffectDuration:null}return{effectDuration,passiveEffectDuration}}function serializeToString(data){if(data===void 0)return"undefined";if(typeof data==="function")return data.toString();var cache=new Set;return JSON.stringify(data,function(key,value){if(backend_utils_typeof(value)==="object"&&value!==null){if(cache.has(value))return;cache.add(value)}if(typeof value==="bigint")return value.toString()+"n";return value},2)}function safeToString(val){try{return String(val)}catch(err){if(backend_utils_typeof(val)==="object")return"[object Object]";throw err}}function formatConsoleArgumentsToSingleString(maybeMessage){for(var _len=arguments.length,inputArgs=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)inputArgs[_key-1]=arguments[_key];var args=inputArgs.slice(),formatted=safeToString(maybeMessage);if(typeof maybeMessage==="string"){if(args.length){var REGEXP=/(%?)(%([jds]))/g;formatted=formatted.replace(REGEXP,function(match,escaped,ptn,flag){var arg=args.shift();switch(flag){case"s":arg+="";break;case"d":case"i":arg=parseInt(arg,10).toString();break;case"f":arg=parseFloat(arg).toString();break}if(!escaped)return arg;return args.unshift(arg),match})}}if(args.length)for(var i=0;i<args.length;i++)formatted+=" "+safeToString(args[i]);return formatted=formatted.replace(/%{2,2}/g,"%"),String(formatted)}function isSynchronousXHRSupported(){return!!(window.document&&window.document.featurePolicy&&window.document.featurePolicy.allowsFeature("sync-xhr"))}function gt(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";return compareVersions(a,b)===1}function gte(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";return compareVersions(a,b)>-1}var isReactNativeEnvironment=function(){return window.document==null};function formatDurationToMicrosecondsGranularity(duration){return Math.round(duration*1000)/1000}function utils_slicedToArray(arr,i){return utils_arrayWithHoles(arr)||utils_iterableToArrayLimit(arr,i)||views_utils_unsupportedIterableToArray(arr,i)||utils_nonIterableRest()}function utils_nonIterableRest(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
123
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function views_utils_unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return views_utils_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return views_utils_arrayLikeToArray(o,minLen)}function views_utils_arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function utils_iterableToArrayLimit(r,l){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,l===0){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r2){o=!0,n=r2}finally{try{if(!f&&t.return!=null&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}function utils_arrayWithHoles(arr){if(Array.isArray(arr))return arr}function getOwnerWindow(node){if(!node.ownerDocument)return null;return node.ownerDocument.defaultView}function getOwnerIframe(node){var nodeWindow=getOwnerWindow(node);if(nodeWindow)return nodeWindow.frameElement;return null}function getBoundingClientRectWithBorderOffset(node){var dimensions=getElementDimensions(node);return mergeRectOffsets([node.getBoundingClientRect(),{top:dimensions.borderTop,left:dimensions.borderLeft,bottom:dimensions.borderBottom,right:dimensions.borderRight,width:0,height:0}])}function mergeRectOffsets(rects){return rects.reduce(function(previousRect,rect){if(previousRect==null)return rect;return{top:previousRect.top+rect.top,left:previousRect.left+rect.left,width:previousRect.width,height:previousRect.height,bottom:previousRect.bottom+rect.bottom,right:previousRect.right+rect.right}})}function getNestedBoundingClientRect(node,boundaryWindow){var ownerIframe=getOwnerIframe(node);if(ownerIframe&&ownerIframe!==boundaryWindow){var rects=[node.getBoundingClientRect()],currentIframe=ownerIframe,onlyOneMore=!1;while(currentIframe){var rect=getBoundingClientRectWithBorderOffset(currentIframe);if(rects.push(rect),currentIframe=getOwnerIframe(currentIframe),onlyOneMore)break;if(currentIframe&&getOwnerWindow(currentIframe)===boundaryWindow)onlyOneMore=!0}return mergeRectOffsets(rects)}else return node.getBoundingClientRect()}function getElementDimensions(domElement){var calculatedStyle=window.getComputedStyle(domElement);return{borderLeft:parseInt(calculatedStyle.borderLeftWidth,10),borderRight:parseInt(calculatedStyle.borderRightWidth,10),borderTop:parseInt(calculatedStyle.borderTopWidth,10),borderBottom:parseInt(calculatedStyle.borderBottomWidth,10),marginLeft:parseInt(calculatedStyle.marginLeft,10),marginRight:parseInt(calculatedStyle.marginRight,10),marginTop:parseInt(calculatedStyle.marginTop,10),marginBottom:parseInt(calculatedStyle.marginBottom,10),paddingLeft:parseInt(calculatedStyle.paddingLeft,10),paddingRight:parseInt(calculatedStyle.paddingRight,10),paddingTop:parseInt(calculatedStyle.paddingTop,10),paddingBottom:parseInt(calculatedStyle.paddingBottom,10)}}function extractHOCNames(displayName){if(!displayName)return{baseComponentName:"",hocNames:[]};var hocRegex=/([A-Z][a-zA-Z0-9]*?)\((.*)\)/g,hocNames=[],baseComponentName=displayName,match;while((match=hocRegex.exec(baseComponentName))!=null)if(Array.isArray(match)){var _match=match,_match2=utils_slicedToArray(_match,3),hocName=_match2[1],inner=_match2[2];hocNames.push(hocName),baseComponentName=inner}return{baseComponentName,hocNames}}function Overlay_typeof(o){return Overlay_typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},Overlay_typeof(o)}function Overlay_classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw TypeError("Cannot call a class as a function")}function Overlay_defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];if(descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor)descriptor.writable=!0;Object.defineProperty(target,Overlay_toPropertyKey(descriptor.key),descriptor)}}function Overlay_createClass(Constructor,protoProps,staticProps){if(protoProps)Overlay_defineProperties(Constructor.prototype,protoProps);if(staticProps)Overlay_defineProperties(Constructor,staticProps);return Object.defineProperty(Constructor,"prototype",{writable:!1}),Constructor}function Overlay_toPropertyKey(t){var i=Overlay_toPrimitive(t,"string");return Overlay_typeof(i)=="symbol"?i:i+""}function Overlay_toPrimitive(t,r){if(Overlay_typeof(t)!="object"||!t)return t;var e=t[Symbol.toPrimitive];if(e!==void 0){var i=e.call(t,r||"default");if(Overlay_typeof(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(t)}var Overlay_assign=Object.assign,OverlayRect=function(){function OverlayRect2(doc,container){Overlay_classCallCheck(this,OverlayRect2),this.node=doc.createElement("div"),this.border=doc.createElement("div"),this.padding=doc.createElement("div"),this.content=doc.createElement("div"),this.border.style.borderColor=overlayStyles.border,this.padding.style.borderColor=overlayStyles.padding,this.content.style.backgroundColor=overlayStyles.background,Overlay_assign(this.node.style,{borderColor:overlayStyles.margin,pointerEvents:"none",position:"fixed"}),this.node.style.zIndex="10000000",this.node.appendChild(this.border),this.border.appendChild(this.padding),this.padding.appendChild(this.content),container.appendChild(this.node)}return Overlay_createClass(OverlayRect2,[{key:"remove",value:function(){if(this.node.parentNode)this.node.parentNode.removeChild(this.node)}},{key:"update",value:function(box,dims){boxWrap(dims,"margin",this.node),boxWrap(dims,"border",this.border),boxWrap(dims,"padding",this.padding),Overlay_assign(this.content.style,{height:box.height-dims.borderTop-dims.borderBottom-dims.paddingTop-dims.paddingBottom+"px",width:box.width-dims.borderLeft-dims.borderRight-dims.paddingLeft-dims.paddingRight+"px"}),Overlay_assign(this.node.style,{top:box.top-dims.marginTop+"px",left:box.left-dims.marginLeft+"px"})}}])}(),OverlayTip=function(){function OverlayTip2(doc,container){Overlay_classCallCheck(this,OverlayTip2),this.tip=doc.createElement("div"),Overlay_assign(this.tip.style,{display:"flex",flexFlow:"row nowrap",backgroundColor:"#333740",borderRadius:"2px",fontFamily:'"SFMono-Regular", Consolas, "Liberation Mono", Menlo, Courier, monospace',fontWeight:"bold",padding:"3px 5px",pointerEvents:"none",position:"fixed",fontSize:"12px",whiteSpace:"nowrap"}),this.nameSpan=doc.createElement("span"),this.tip.appendChild(this.nameSpan),Overlay_assign(this.nameSpan.style,{color:"#ee78e6",borderRight:"1px solid #aaaaaa",paddingRight:"0.5rem",marginRight:"0.5rem"}),this.dimSpan=doc.createElement("span"),this.tip.appendChild(this.dimSpan),Overlay_assign(this.dimSpan.style,{color:"#d7d7d7"}),this.tip.style.zIndex="10000000",container.appendChild(this.tip)}return Overlay_createClass(OverlayTip2,[{key:"remove",value:function(){if(this.tip.parentNode)this.tip.parentNode.removeChild(this.tip)}},{key:"updateText",value:function(name,width,height){this.nameSpan.textContent=name,this.dimSpan.textContent=Math.round(width)+"px × "+Math.round(height)+"px"}},{key:"updatePosition",value:function(dims,bounds){var tipRect=this.tip.getBoundingClientRect(),tipPos=findTipPos(dims,bounds,{width:tipRect.width,height:tipRect.height});Overlay_assign(this.tip.style,tipPos.style)}}])}(),Overlay=function(){function Overlay2(agent2){Overlay_classCallCheck(this,Overlay2);var currentWindow=window.__REACT_DEVTOOLS_TARGET_WINDOW__||window;this.window=currentWindow;var tipBoundsWindow=window.__REACT_DEVTOOLS_TARGET_WINDOW__||window;this.tipBoundsWindow=tipBoundsWindow;var doc=currentWindow.document;this.container=doc.createElement("div"),this.container.style.zIndex="10000000",this.tip=new OverlayTip(doc,this.container),this.rects=[],this.agent=agent2,doc.body.appendChild(this.container)}return Overlay_createClass(Overlay2,[{key:"remove",value:function(){if(this.tip.remove(),this.rects.forEach(function(rect){rect.remove()}),this.rects.length=0,this.container.parentNode)this.container.parentNode.removeChild(this.container)}},{key:"inspect",value:function(nodes,name){var _this=this,elements=nodes.filter(function(node2){return node2.nodeType===Node.ELEMENT_NODE});while(this.rects.length>elements.length){var rect=this.rects.pop();rect.remove()}if(elements.length===0)return;while(this.rects.length<elements.length)this.rects.push(new OverlayRect(this.window.document,this.container));var outerBox={top:Number.POSITIVE_INFINITY,right:Number.NEGATIVE_INFINITY,bottom:Number.NEGATIVE_INFINITY,left:Number.POSITIVE_INFINITY};if(elements.forEach(function(element,index){var box=getNestedBoundingClientRect(element,_this.window),dims=getElementDimensions(element);outerBox.top=Math.min(outerBox.top,box.top-dims.marginTop),outerBox.right=Math.max(outerBox.right,box.left+box.width+dims.marginRight),outerBox.bottom=Math.max(outerBox.bottom,box.top+box.height+dims.marginBottom),outerBox.left=Math.min(outerBox.left,box.left-dims.marginLeft);var rect2=_this.rects[index];rect2.update(box,dims)}),!name){name=elements[0].nodeName.toLowerCase();var node=elements[0],ownerName=this.agent.getComponentNameForHostInstance(node);if(ownerName)name+=" (in "+ownerName+")"}this.tip.updateText(name,outerBox.right-outerBox.left,outerBox.bottom-outerBox.top);var tipBounds=getNestedBoundingClientRect(this.tipBoundsWindow.document.documentElement,this.window);this.tip.updatePosition({top:outerBox.top,left:outerBox.left,height:outerBox.bottom-outerBox.top,width:outerBox.right-outerBox.left},{top:tipBounds.top+this.tipBoundsWindow.scrollY,left:tipBounds.left+this.tipBoundsWindow.scrollX,height:this.tipBoundsWindow.innerHeight,width:this.tipBoundsWindow.innerWidth})}}])}();function findTipPos(dims,bounds,tipSize){var tipHeight=Math.max(tipSize.height,20),tipWidth=Math.max(tipSize.width,60),margin=5,top;if(dims.top+dims.height+tipHeight<=bounds.top+bounds.height)if(dims.top+dims.height<bounds.top+0)top=bounds.top+margin;else top=dims.top+dims.height+margin;else if(dims.top-tipHeight<=bounds.top+bounds.height)if(dims.top-tipHeight-margin<bounds.top+margin)top=bounds.top+margin;else top=dims.top-tipHeight-margin;else top=bounds.top+bounds.height-tipHeight-margin;var left=dims.left+margin;if(dims.left<bounds.left)left=bounds.left+margin;if(dims.left+tipWidth>bounds.left+bounds.width)left=bounds.left+bounds.width-tipWidth-margin;return top+="px",left+="px",{style:{top,left}}}function boxWrap(dims,what,node){Overlay_assign(node.style,{borderTopWidth:dims[what+"Top"]+"px",borderLeftWidth:dims[what+"Left"]+"px",borderRightWidth:dims[what+"Right"]+"px",borderBottomWidth:dims[what+"Bottom"]+"px",borderStyle:"solid"})}var overlayStyles={background:"rgba(120, 170, 210, 0.7)",padding:"rgba(77, 200, 0, 0.3)",margin:"rgba(255, 155, 0, 0.3)",border:"rgba(255, 200, 50, 0.3)"},SHOW_DURATION=2000,timeoutID=null,overlay=null;function hideOverlayNative(agent2){agent2.emit("hideNativeHighlight")}function hideOverlayWeb(){if(timeoutID=null,overlay!==null)overlay.remove(),overlay=null}function hideOverlay(agent2){return isReactNativeEnvironment()?hideOverlayNative(agent2):hideOverlayWeb()}function showOverlayNative(elements,agent2){agent2.emit("showNativeHighlight",elements)}function showOverlayWeb(elements,componentName,agent2,hideAfterTimeout){if(timeoutID!==null)clearTimeout(timeoutID);if(overlay===null)overlay=new Overlay(agent2);if(overlay.inspect(elements,componentName),hideAfterTimeout)timeoutID=setTimeout(function(){return hideOverlay(agent2)},SHOW_DURATION)}function showOverlay(elements,componentName,agent2,hideAfterTimeout){return isReactNativeEnvironment()?showOverlayNative(elements,agent2):showOverlayWeb(elements,componentName,agent2,hideAfterTimeout)}var iframesListeningTo=new Set,inspectOnlySuspenseNodes=!1;function setupHighlighter(bridge,agent2){bridge.addListener("clearHostInstanceHighlight",clearHostInstanceHighlight),bridge.addListener("highlightHostInstance",highlightHostInstance),bridge.addListener("highlightHostInstances",highlightHostInstances),bridge.addListener("scrollToHostInstance",scrollToHostInstance),bridge.addListener("shutdown",stopInspectingHost),bridge.addListener("startInspectingHost",startInspectingHost),bridge.addListener("stopInspectingHost",stopInspectingHost);function startInspectingHost(onlySuspenseNodes){inspectOnlySuspenseNodes=onlySuspenseNodes,registerListenersOnWindow(window)}function registerListenersOnWindow(window2){if(window2&&typeof window2.addEventListener==="function")window2.addEventListener("click",onClick,!0),window2.addEventListener("mousedown",onMouseEvent,!0),window2.addEventListener("mouseover",onMouseEvent,!0),window2.addEventListener("mouseup",onMouseEvent,!0),window2.addEventListener("pointerdown",onPointerDown,!0),window2.addEventListener("pointermove",onPointerMove,!0),window2.addEventListener("pointerup",onPointerUp,!0);else agent2.emit("startInspectingNative")}function stopInspectingHost(){hideOverlay(agent2),removeListenersOnWindow(window),iframesListeningTo.forEach(function(frame){try{removeListenersOnWindow(frame.contentWindow)}catch(error){}}),iframesListeningTo=new Set}function removeListenersOnWindow(window2){if(window2&&typeof window2.removeEventListener==="function")window2.removeEventListener("click",onClick,!0),window2.removeEventListener("mousedown",onMouseEvent,!0),window2.removeEventListener("mouseover",onMouseEvent,!0),window2.removeEventListener("mouseup",onMouseEvent,!0),window2.removeEventListener("pointerdown",onPointerDown,!0),window2.removeEventListener("pointermove",onPointerMove,!0),window2.removeEventListener("pointerup",onPointerUp,!0);else agent2.emit("stopInspectingNative")}function clearHostInstanceHighlight(){hideOverlay(agent2)}function highlightHostInstance(_ref){var{displayName,hideAfterTimeout,id,openBuiltinElementsPanel,rendererID,scrollIntoView}=_ref,renderer=agent2.rendererInterfaces[rendererID];if(renderer==null){console.warn('Invalid renderer id "'.concat(rendererID,'" for element "').concat(id,'"')),hideOverlay(agent2);return}if(!renderer.hasElementWithId(id)){hideOverlay(agent2);return}var nodes=renderer.findHostInstancesForElementID(id);if(nodes!=null)for(var i=0;i<nodes.length;i++){var node=nodes[i];if(node===null)continue;var nodeRects=typeof node.getClientRects==="function"?node.getClientRects():[];if(nodeRects.length>0&&(nodeRects.length>2||nodeRects[0].width>0||nodeRects[0].height>0)){if(scrollIntoView&&typeof node.scrollIntoView==="function"){if(scrollDelayTimer)clearTimeout(scrollDelayTimer),scrollDelayTimer=null;node.scrollIntoView({block:"nearest",inline:"nearest"})}if(showOverlay(nodes,displayName,agent2,hideAfterTimeout),openBuiltinElementsPanel)window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0=node,bridge.send("syncSelectionToBuiltinElementsPanel");return}}hideOverlay(agent2)}function highlightHostInstances(_ref2){var{displayName,hideAfterTimeout,elements,scrollIntoView}=_ref2,nodes=[];for(var i=0;i<elements.length;i++){var _elements$i=elements[i],id=_elements$i.id,rendererID=_elements$i.rendererID,renderer=agent2.rendererInterfaces[rendererID];if(renderer==null){console.warn('Invalid renderer id "'.concat(rendererID,'" for element "').concat(id,'"'));continue}if(!renderer.hasElementWithId(id))continue;var hostInstances=renderer.findHostInstancesForElementID(id);if(hostInstances!==null)for(var j=0;j<hostInstances.length;j++)nodes.push(hostInstances[j])}if(nodes.length>0){var node=nodes[0];if(scrollIntoView&&typeof node.scrollIntoView==="function")node.scrollIntoView({block:"nearest",inline:"nearest"})}showOverlay(nodes,displayName,agent2,hideAfterTimeout)}function attemptScrollToHostInstance(renderer,id){var nodes=renderer.findHostInstancesForElementID(id);if(nodes!=null)for(var i=0;i<nodes.length;i++){var node=nodes[i];if(node===null)continue;var nodeRects=typeof node.getClientRects==="function"?node.getClientRects():[];if(nodeRects.length>0&&(nodeRects.length>2||nodeRects[0].width>0||nodeRects[0].height>0)){if(typeof node.scrollIntoView==="function")return node.scrollIntoView({block:"nearest",inline:"nearest",behavior:"smooth"}),!0}}return!1}var scrollDelayTimer=null;function scrollToHostInstance(_ref3){var{id,rendererID}=_ref3;if(hideOverlay(agent2),scrollDelayTimer)clearTimeout(scrollDelayTimer),scrollDelayTimer=null;var renderer=agent2.rendererInterfaces[rendererID];if(renderer==null){console.warn('Invalid renderer id "'.concat(rendererID,'" for element "').concat(id,'"'));return}if(!renderer.hasElementWithId(id))return;if(attemptScrollToHostInstance(renderer,id))return;var rects=renderer.findLastKnownRectsForID(id);if(rects!==null&&rects.length>0){var x=1/0,y=1/0;for(var i=0;i<rects.length;i++){var rect=rects[i];if(rect.x<x)x=rect.x;if(rect.y<y)y=rect.y}var element=document.documentElement;if(!element)return;if(x<window.scrollX||y<window.scrollY||x>window.scrollX+element.clientWidth||y>window.scrollY+element.clientHeight)window.scrollTo({top:y,left:x,behavior:"smooth"});scrollDelayTimer=setTimeout(function(){attemptScrollToHostInstance(renderer,id)},100)}}function onClick(event){event.preventDefault(),event.stopPropagation(),stopInspectingHost(),bridge.send("stopInspectingHost",!0)}function onMouseEvent(event){event.preventDefault(),event.stopPropagation()}function onPointerDown(event){event.preventDefault(),event.stopPropagation(),selectElementForNode(getEventTarget(event))}var lastHoveredNode=null;function onPointerMove(event){event.preventDefault(),event.stopPropagation();var target=getEventTarget(event);if(lastHoveredNode===target)return;if(lastHoveredNode=target,target.tagName==="IFRAME"){var iframe=target;try{if(!iframesListeningTo.has(iframe)){var _window=iframe.contentWindow;registerListenersOnWindow(_window),iframesListeningTo.add(iframe)}}catch(error){}}if(inspectOnlySuspenseNodes){var match=agent2.getIDForHostInstance(target,inspectOnlySuspenseNodes);if(match!==null){var renderer=agent2.rendererInterfaces[match.rendererID];if(renderer==null){console.warn('Invalid renderer id "'.concat(match.rendererID,'" for element "').concat(match.id,'"'));return}highlightHostInstance({displayName:renderer.getDisplayNameForElementID(match.id),hideAfterTimeout:!1,id:match.id,openBuiltinElementsPanel:!1,rendererID:match.rendererID,scrollIntoView:!1})}}else showOverlay([target],null,agent2,!1)}function onPointerUp(event){event.preventDefault(),event.stopPropagation()}var selectElementForNode=function(node){var match=agent2.getIDForHostInstance(node,inspectOnlySuspenseNodes);if(match!==null)bridge.send("selectElement",match.id)};function getEventTarget(event){if(event.composed)return event.composedPath()[0];return event.target}}function canvas_toConsumableArray(arr){return canvas_arrayWithoutHoles(arr)||canvas_iterableToArray(arr)||canvas_unsupportedIterableToArray(arr)||canvas_nonIterableSpread()}function canvas_nonIterableSpread(){throw TypeError(`Invalid attempt to spread non-iterable instance.
124
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function canvas_unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return canvas_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return canvas_arrayLikeToArray(o,minLen)}function canvas_iterableToArray(iter){if(typeof Symbol<"u"&&iter[Symbol.iterator]!=null||iter["@@iterator"]!=null)return Array.from(iter)}function canvas_arrayWithoutHoles(arr){if(Array.isArray(arr))return canvas_arrayLikeToArray(arr)}function canvas_arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=Array(len);i<len;i++)arr2[i]=arr[i];return arr2}var COLORS=["#37afa9","#63b19e","#80b393","#97b488","#abb67d","#beb771","#cfb965","#dfba57","#efbb49","#febc38"],canvas=null;function drawNative(nodeToData2,agent2){var nodesToDraw=[];iterateNodes(nodeToData2,function(_ref){var{color,node}=_ref;nodesToDraw.push({node,color})}),agent2.emit("drawTraceUpdates",nodesToDraw);var mergedNodes=groupAndSortNodes(nodeToData2);agent2.emit("drawGroupedTraceUpdatesWithNames",mergedNodes)}function drawWeb(nodeToData2){if(canvas===null)initialize();var dpr=window.devicePixelRatio||1,canvasFlow=canvas;canvasFlow.width=window.innerWidth*dpr,canvasFlow.height=window.innerHeight*dpr,canvasFlow.style.width="".concat(window.innerWidth,"px"),canvasFlow.style.height="".concat(window.innerHeight,"px");var context=canvasFlow.getContext("2d");context.scale(dpr,dpr),context.clearRect(0,0,canvasFlow.width/dpr,canvasFlow.height/dpr);var mergedNodes=groupAndSortNodes(nodeToData2);if(mergedNodes.forEach(function(group){drawGroupBorders(context,group),drawGroupLabel(context,group)}),canvas!==null){if(nodeToData2.size===0&&canvas.matches(":popover-open")){canvas.hidePopover();return}if(canvas.matches(":popover-open"))canvas.hidePopover();canvas.showPopover()}}function groupAndSortNodes(nodeToData2){var positionGroups=new Map;return iterateNodes(nodeToData2,function(_ref2){var _positionGroups$get,rect=_ref2.rect,color=_ref2.color,displayName=_ref2.displayName,count=_ref2.count;if(!rect)return;var key="".concat(rect.left,",").concat(rect.top);if(!positionGroups.has(key))positionGroups.set(key,[]);(_positionGroups$get=positionGroups.get(key))===null||_positionGroups$get===void 0||_positionGroups$get.push({rect,color,displayName,count})}),Array.from(positionGroups.values()).sort(function(groupA,groupB){var maxCountA=Math.max.apply(Math,canvas_toConsumableArray(groupA.map(function(item){return item.count}))),maxCountB=Math.max.apply(Math,canvas_toConsumableArray(groupB.map(function(item){return item.count})));return maxCountA-maxCountB})}function drawGroupBorders(context,group){group.forEach(function(_ref3){var{color,rect}=_ref3;context.beginPath(),context.strokeStyle=color,context.rect(rect.left,rect.top,rect.width-1,rect.height-1),context.stroke()})}function drawGroupLabel(context,group){var mergedName=group.map(function(_ref4){var{displayName,count}=_ref4;return displayName?"".concat(displayName).concat(count>1?" x".concat(count):""):""}).filter(Boolean).join(", ");if(mergedName)drawLabel(context,group[0].rect,mergedName,group[0].color)}function draw(nodeToData2,agent2){return isReactNativeEnvironment()?drawNative(nodeToData2,agent2):drawWeb(nodeToData2)}function iterateNodes(nodeToData2,execute){nodeToData2.forEach(function(data,node){var colorIndex=Math.min(COLORS.length-1,data.count-1),color=COLORS[colorIndex];execute({color,node,count:data.count,displayName:data.displayName,expirationTime:data.expirationTime,lastMeasuredAt:data.lastMeasuredAt,rect:data.rect})})}function drawLabel(context,rect,text,color){var{left,top}=rect;context.font="10px monospace",context.textBaseline="middle",context.textAlign="center";var padding=2,textHeight=14,metrics=context.measureText(text),backgroundWidth=metrics.width+padding*2,backgroundHeight=textHeight,labelX=left,labelY=top-backgroundHeight;context.fillStyle=color,context.fillRect(labelX,labelY,backgroundWidth,backgroundHeight),context.fillStyle="#000000",context.fillText(text,labelX+backgroundWidth/2,labelY+backgroundHeight/2)}function destroyNative(agent2){agent2.emit("disableTraceUpdates")}function destroyWeb(){if(canvas!==null){if(canvas.matches(":popover-open"))canvas.hidePopover();if(canvas.parentNode!=null)canvas.parentNode.removeChild(canvas);canvas=null}}function destroy(agent2){return isReactNativeEnvironment()?destroyNative(agent2):destroyWeb()}function initialize(){canvas=window.document.createElement("canvas"),canvas.setAttribute("popover","manual"),canvas.style.cssText=`
125
+ xx-background-color: red;
126
+ xx-opacity: 0.5;
127
+ bottom: 0;
128
+ left: 0;
129
+ pointer-events: none;
130
+ position: fixed;
131
+ right: 0;
132
+ top: 0;
133
+ background-color: transparent;
134
+ outline: none;
135
+ box-shadow: none;
136
+ border: none;
137
+ `;var root=window.document.documentElement;root.insertBefore(canvas,root.firstChild)}function TraceUpdates_typeof(o){return TraceUpdates_typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},TraceUpdates_typeof(o)}var DISPLAY_DURATION=250,MAX_DISPLAY_DURATION=3000,REMEASUREMENT_AFTER_DURATION=250,HOC_MARKERS=new Map([["Forget","✨"],["Memo","\uD83E\uDDE0"]]),getCurrentTime=(typeof performance>"u"?"undefined":TraceUpdates_typeof(performance))==="object"&&typeof performance.now==="function"?function(){return performance.now()}:function(){return Date.now()},nodeToData=new Map,agent=null,drawAnimationFrameID=null,isEnabled=!1,redrawTimeoutID=null;function TraceUpdates_initialize(injectedAgent){agent=injectedAgent,agent.addListener("traceUpdates",traceUpdates)}function toggleEnabled(value){if(isEnabled=value,!isEnabled){if(nodeToData.clear(),drawAnimationFrameID!==null)cancelAnimationFrame(drawAnimationFrameID),drawAnimationFrameID=null;if(redrawTimeoutID!==null)clearTimeout(redrawTimeoutID),redrawTimeoutID=null;destroy(agent)}}function traceUpdates(nodes){if(!isEnabled)return;if(nodes.forEach(function(node){var data=nodeToData.get(node),now=getCurrentTime(),lastMeasuredAt=data!=null?data.lastMeasuredAt:0,rect=data!=null?data.rect:null;if(rect===null||lastMeasuredAt+REMEASUREMENT_AFTER_DURATION<now)lastMeasuredAt=now,rect=measureNode(node);var displayName=agent.getComponentNameForHostInstance(node);if(displayName){var _extractHOCNames=extractHOCNames(displayName),baseComponentName=_extractHOCNames.baseComponentName,hocNames=_extractHOCNames.hocNames,markers=hocNames.map(function(hoc){return HOC_MARKERS.get(hoc)||""}).join(""),enhancedDisplayName=markers?"".concat(markers).concat(baseComponentName):baseComponentName;displayName=enhancedDisplayName}nodeToData.set(node,{count:data!=null?data.count+1:1,expirationTime:data!=null?Math.min(now+MAX_DISPLAY_DURATION,data.expirationTime+DISPLAY_DURATION):now+DISPLAY_DURATION,lastMeasuredAt,rect,displayName})}),redrawTimeoutID!==null)clearTimeout(redrawTimeoutID),redrawTimeoutID=null;if(drawAnimationFrameID===null)drawAnimationFrameID=requestAnimationFrame(prepareToDraw)}function prepareToDraw(){drawAnimationFrameID=null,redrawTimeoutID=null;var now=getCurrentTime(),earliestExpiration=Number.MAX_VALUE;if(nodeToData.forEach(function(data,node){if(data.expirationTime<now)nodeToData.delete(node);else earliestExpiration=Math.min(earliestExpiration,data.expirationTime)}),draw(nodeToData,agent),earliestExpiration!==Number.MAX_VALUE)redrawTimeoutID=setTimeout(prepareToDraw,earliestExpiration-now)}function measureNode(node){if(!node||typeof node.getBoundingClientRect!=="function")return null;var currentWindow=window.__REACT_DEVTOOLS_TARGET_WINDOW__||window;return getNestedBoundingClientRect(node,currentWindow)}function bridge_typeof(o){return bridge_typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},bridge_typeof(o)}function bridge_toConsumableArray(arr){return bridge_arrayWithoutHoles(arr)||bridge_iterableToArray(arr)||bridge_unsupportedIterableToArray(arr)||bridge_nonIterableSpread()}function bridge_nonIterableSpread(){throw TypeError(`Invalid attempt to spread non-iterable instance.
138
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function bridge_unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return bridge_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return bridge_arrayLikeToArray(o,minLen)}function bridge_iterableToArray(iter){if(typeof Symbol<"u"&&iter[Symbol.iterator]!=null||iter["@@iterator"]!=null)return Array.from(iter)}function bridge_arrayWithoutHoles(arr){if(Array.isArray(arr))return bridge_arrayLikeToArray(arr)}function bridge_arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function bridge_classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw TypeError("Cannot call a class as a function")}function bridge_defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];if(descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor)descriptor.writable=!0;Object.defineProperty(target,bridge_toPropertyKey(descriptor.key),descriptor)}}function bridge_createClass(Constructor,protoProps,staticProps){if(protoProps)bridge_defineProperties(Constructor.prototype,protoProps);if(staticProps)bridge_defineProperties(Constructor,staticProps);return Object.defineProperty(Constructor,"prototype",{writable:!1}),Constructor}function _callSuper(t,o,e){return o=_getPrototypeOf(o),_possibleConstructorReturn(t,_isNativeReflectConstruct()?Reflect.construct(o,e||[],_getPrototypeOf(t).constructor):o.apply(t,e))}function _possibleConstructorReturn(self2,call){if(call&&(bridge_typeof(call)==="object"||typeof call==="function"))return call;else if(call!==void 0)throw TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized(self2)}function _assertThisInitialized(self2){if(self2===void 0)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return self2}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t2){}return(_isNativeReflectConstruct=function(){return!!t})()}function _getPrototypeOf(o){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(o2){return o2.__proto__||Object.getPrototypeOf(o2)},_getPrototypeOf(o)}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null)throw TypeError("Super expression must either be null or a function");if(subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:!0,configurable:!0}}),Object.defineProperty(subClass,"prototype",{writable:!1}),superClass)_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(o2,p2){return o2.__proto__=p2,o2},_setPrototypeOf(o,p)}function bridge_defineProperty(obj,key,value){if(key=bridge_toPropertyKey(key),key in obj)Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0});else obj[key]=value;return obj}function bridge_toPropertyKey(t){var i=bridge_toPrimitive(t,"string");return bridge_typeof(i)=="symbol"?i:i+""}function bridge_toPrimitive(t,r){if(bridge_typeof(t)!="object"||!t)return t;var e=t[Symbol.toPrimitive];if(e!==void 0){var i=e.call(t,r||"default");if(bridge_typeof(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(t)}var BRIDGE_PROTOCOL=[{version:0,minNpmVersion:'"<4.11.0"',maxNpmVersion:'"<4.11.0"'},{version:1,minNpmVersion:"4.13.0",maxNpmVersion:"4.21.0"},{version:2,minNpmVersion:"4.22.0",maxNpmVersion:null}],currentBridgeProtocol=BRIDGE_PROTOCOL[BRIDGE_PROTOCOL.length-1],Bridge=function(_EventEmitter){function Bridge2(wall){var _this;return bridge_classCallCheck(this,Bridge2),_this=_callSuper(this,Bridge2),bridge_defineProperty(_this,"_isShutdown",!1),bridge_defineProperty(_this,"_messageQueue",[]),bridge_defineProperty(_this,"_scheduledFlush",!1),bridge_defineProperty(_this,"_wallUnlisten",null),bridge_defineProperty(_this,"_flush",function(){try{if(_this._messageQueue.length){for(var i=0;i<_this._messageQueue.length;i+=2){var _this$_wall;(_this$_wall=_this._wall).send.apply(_this$_wall,[_this._messageQueue[i]].concat(bridge_toConsumableArray(_this._messageQueue[i+1])))}_this._messageQueue.length=0}}finally{_this._scheduledFlush=!1}}),bridge_defineProperty(_this,"overrideValueAtPath",function(_ref){var{id,path,rendererID,type,value}=_ref;switch(type){case"context":_this.send("overrideContext",{id,path,rendererID,wasForwarded:!0,value});break;case"hooks":_this.send("overrideHookState",{id,path,rendererID,wasForwarded:!0,value});break;case"props":_this.send("overrideProps",{id,path,rendererID,wasForwarded:!0,value});break;case"state":_this.send("overrideState",{id,path,rendererID,wasForwarded:!0,value});break}}),_this._wall=wall,_this._wallUnlisten=wall.listen(function(message){if(message&&message.event)_this.emit(message.event,message.payload)})||null,_this.addListener("overrideValueAtPath",_this.overrideValueAtPath),_this}return _inherits(Bridge2,_EventEmitter),bridge_createClass(Bridge2,[{key:"wall",get:function(){return this._wall}},{key:"send",value:function(event){if(this._isShutdown){console.warn('Cannot send message "'.concat(event,'" through a Bridge that has been shutdown.'));return}for(var _len=arguments.length,payload=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)payload[_key-1]=arguments[_key];if(this._messageQueue.push(event,payload),!this._scheduledFlush)if(this._scheduledFlush=!0,typeof devtoolsJestTestScheduler==="function")devtoolsJestTestScheduler(this._flush);else queueMicrotask(this._flush)}},{key:"shutdown",value:function(){if(this._isShutdown){console.warn("Bridge was already shutdown.");return}this.emit("shutdown"),this.send("shutdown"),this._isShutdown=!0,this.addListener=function(){},this.emit=function(){},this.removeAllListeners();var wallUnlisten=this._wallUnlisten;if(wallUnlisten)wallUnlisten();do this._flush();while(this._messageQueue.length)}}])}(EventEmitter);let src_bridge=Bridge;function storage_localStorageGetItem(key){try{return localStorage.getItem(key)}catch(error){return null}}function localStorageRemoveItem(key){try{localStorage.removeItem(key)}catch(error){}}function storage_localStorageSetItem(key,value){try{return localStorage.setItem(key,value)}catch(error){}}function storage_sessionStorageGetItem(key){try{return sessionStorage.getItem(key)}catch(error){return null}}function storage_sessionStorageRemoveItem(key){try{sessionStorage.removeItem(key)}catch(error){}}function storage_sessionStorageSetItem(key,value){try{return sessionStorage.setItem(key,value)}catch(error){}}function agent_typeof(o){return agent_typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},agent_typeof(o)}function agent_classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw TypeError("Cannot call a class as a function")}function agent_defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];if(descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor)descriptor.writable=!0;Object.defineProperty(target,agent_toPropertyKey(descriptor.key),descriptor)}}function agent_createClass(Constructor,protoProps,staticProps){if(protoProps)agent_defineProperties(Constructor.prototype,protoProps);if(staticProps)agent_defineProperties(Constructor,staticProps);return Object.defineProperty(Constructor,"prototype",{writable:!1}),Constructor}function agent_callSuper(t,o,e){return o=agent_getPrototypeOf(o),agent_possibleConstructorReturn(t,agent_isNativeReflectConstruct()?Reflect.construct(o,e||[],agent_getPrototypeOf(t).constructor):o.apply(t,e))}function agent_possibleConstructorReturn(self2,call){if(call&&(agent_typeof(call)==="object"||typeof call==="function"))return call;else if(call!==void 0)throw TypeError("Derived constructors may only return object or undefined");return agent_assertThisInitialized(self2)}function agent_assertThisInitialized(self2){if(self2===void 0)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return self2}function agent_isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t2){}return(agent_isNativeReflectConstruct=function(){return!!t})()}function agent_getPrototypeOf(o){return agent_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(o2){return o2.__proto__||Object.getPrototypeOf(o2)},agent_getPrototypeOf(o)}function agent_inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null)throw TypeError("Super expression must either be null or a function");if(subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:!0,configurable:!0}}),Object.defineProperty(subClass,"prototype",{writable:!1}),superClass)agent_setPrototypeOf(subClass,superClass)}function agent_setPrototypeOf(o,p){return agent_setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(o2,p2){return o2.__proto__=p2,o2},agent_setPrototypeOf(o,p)}function agent_defineProperty(obj,key,value){if(key=agent_toPropertyKey(key),key in obj)Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0});else obj[key]=value;return obj}function agent_toPropertyKey(t){var i=agent_toPrimitive(t,"string");return agent_typeof(i)=="symbol"?i:i+""}function agent_toPrimitive(t,r){if(agent_typeof(t)!="object"||!t)return t;var e=t[Symbol.toPrimitive];if(e!==void 0){var i=e.call(t,r||"default");if(agent_typeof(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(t)}var debug=function(methodName){if(__DEBUG__){var _console;for(var _len=arguments.length,args=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)args[_key-1]=arguments[_key];(_console=console).log.apply(_console,["%cAgent %c".concat(methodName),"color: purple; font-weight: bold;","font-weight: bold;"].concat(args))}};function createEmptyInspectedScreen(arbitraryRootID,type){var suspendedBy={cleaned:[],data:[],unserializable:[]};return{id:arbitraryRootID,type,isErrored:!1,errors:[],warnings:[],suspendedBy,suspendedByRange:null,unknownSuspenders:UNKNOWN_SUSPENDERS_NONE,rootType:null,plugins:{stylex:null},nativeTag:null,env:null,source:null,stack:null,rendererPackageName:null,rendererVersion:null,key:null,canEditFunctionProps:!1,canEditHooks:!1,canEditFunctionPropsDeletePaths:!1,canEditFunctionPropsRenamePaths:!1,canEditHooksAndDeletePaths:!1,canEditHooksAndRenamePaths:!1,canToggleError:!1,canToggleSuspense:!1,isSuspended:!1,hasLegacyContext:!1,context:null,hooks:null,props:null,state:null,owners:null}}function mergeRoots(left,right,suspendedByOffset){var leftSuspendedByRange=left.suspendedByRange,rightSuspendedByRange=right.suspendedByRange;if(right.isErrored)left.isErrored=!0;for(var i=0;i<right.errors.length;i++)left.errors.push(right.errors[i]);for(var _i=0;_i<right.warnings.length;_i++)left.warnings.push(right.warnings[_i]);var leftSuspendedBy=left.suspendedBy,_ref=right.suspendedBy,data=_ref.data,cleaned=_ref.cleaned,unserializable=_ref.unserializable,leftSuspendedByData=leftSuspendedBy.data,rightSuspendedByData=data;for(var _i2=0;_i2<rightSuspendedByData.length;_i2++)leftSuspendedByData.push(rightSuspendedByData[_i2]);for(var _i3=0;_i3<cleaned.length;_i3++)leftSuspendedBy.cleaned.push([suspendedByOffset+cleaned[_i3][0]].concat(cleaned[_i3].slice(1)));for(var _i4=0;_i4<unserializable.length;_i4++)leftSuspendedBy.unserializable.push([suspendedByOffset+unserializable[_i4][0]].concat(unserializable[_i4].slice(1)));if(rightSuspendedByRange!==null)if(leftSuspendedByRange===null)left.suspendedByRange=[rightSuspendedByRange[0],rightSuspendedByRange[1]];else{if(rightSuspendedByRange[0]<leftSuspendedByRange[0])leftSuspendedByRange[0]=rightSuspendedByRange[0];if(rightSuspendedByRange[1]>leftSuspendedByRange[1])leftSuspendedByRange[1]=rightSuspendedByRange[1]}}var Agent=function(_EventEmitter){function Agent2(bridge){var _this,isProfiling=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,onReloadAndProfile2=arguments.length>2?arguments[2]:void 0;agent_classCallCheck(this,Agent2),_this=agent_callSuper(this,Agent2),agent_defineProperty(_this,"_isProfiling",!1),agent_defineProperty(_this,"_rendererInterfaces",{}),agent_defineProperty(_this,"_persistedSelection",null),agent_defineProperty(_this,"_persistedSelectionMatch",null),agent_defineProperty(_this,"_traceUpdatesEnabled",!1),agent_defineProperty(_this,"clearErrorsAndWarnings",function(_ref2){var rendererID=_ref2.rendererID,renderer=_this._rendererInterfaces[rendererID];if(renderer==null)console.warn('Invalid renderer id "'.concat(rendererID,'"'));else renderer.clearErrorsAndWarnings()}),agent_defineProperty(_this,"clearErrorsForElementID",function(_ref3){var{id,rendererID}=_ref3,renderer=_this._rendererInterfaces[rendererID];if(renderer==null)console.warn('Invalid renderer id "'.concat(rendererID,'"'));else renderer.clearErrorsForElementID(id)}),agent_defineProperty(_this,"clearWarningsForElementID",function(_ref4){var{id,rendererID}=_ref4,renderer=_this._rendererInterfaces[rendererID];if(renderer==null)console.warn('Invalid renderer id "'.concat(rendererID,'"'));else renderer.clearWarningsForElementID(id)}),agent_defineProperty(_this,"copyElementPath",function(_ref5){var{id,path,rendererID}=_ref5,renderer=_this._rendererInterfaces[rendererID];if(renderer==null)console.warn('Invalid renderer id "'.concat(rendererID,'" for element "').concat(id,'"'));else{var value=renderer.getSerializedElementValueByPath(id,path);if(value!=null)_this._bridge.send("saveToClipboard",value);else console.warn('Unable to obtain serialized value for element "'.concat(id,'"'))}}),agent_defineProperty(_this,"deletePath",function(_ref6){var{hookID,id,path,rendererID,type}=_ref6,renderer=_this._rendererInterfaces[rendererID];if(renderer==null)console.warn('Invalid renderer id "'.concat(rendererID,'" for element "').concat(id,'"'));else renderer.deletePath(type,id,hookID,path)}),agent_defineProperty(_this,"getBackendVersion",function(){var version="7.0.1-3cde211b0c";if(version)_this._bridge.send("backendVersion",version)}),agent_defineProperty(_this,"getBridgeProtocol",function(){_this._bridge.send("bridgeProtocol",currentBridgeProtocol)}),agent_defineProperty(_this,"getProfilingData",function(_ref7){var rendererID=_ref7.rendererID,renderer=_this._rendererInterfaces[rendererID];if(renderer==null)console.warn('Invalid renderer id "'.concat(rendererID,'"'));_this._bridge.send("profilingData",renderer.getProfilingData())}),agent_defineProperty(_this,"getProfilingStatus",function(){_this._bridge.send("profilingStatus",_this._isProfiling)}),agent_defineProperty(_this,"getOwnersList",function(_ref8){var{id,rendererID}=_ref8,renderer=_this._rendererInterfaces[rendererID];if(renderer==null)console.warn('Invalid renderer id "'.concat(rendererID,'" for element "').concat(id,'"'));else{var owners=renderer.getOwnersList(id);_this._bridge.send("ownersList",{id,owners})}}),agent_defineProperty(_this,"inspectElement",function(_ref9){var{forceFullData,id,path,rendererID,requestID}=_ref9,renderer=_this._rendererInterfaces[rendererID];if(renderer==null)console.warn('Invalid renderer id "'.concat(rendererID,'" for element "').concat(id,'"'));else if(_this._bridge.send("inspectedElement",renderer.inspectElement(requestID,id,path,forceFullData)),_this._persistedSelectionMatch===null||_this._persistedSelectionMatch.id!==id){if(_this._persistedSelection=null,_this._persistedSelectionMatch=null,renderer.setTrackedPath(null),_this._lastSelectedElementID=id,_this._lastSelectedRendererID=rendererID,!_this._persistSelectionTimerScheduled)_this._persistSelectionTimerScheduled=!0,setTimeout(_this._persistSelection,1000)}}),agent_defineProperty(_this,"inspectScreen",function(_ref10){var{requestID,id,forceFullData,path:screenPath}=_ref10,inspectedScreen=null,found=!1,suspendedByOffset=0,suspendedByPathIndex=null,rendererPath=null;if(screenPath!==null&&screenPath.length>1){var secondaryCategory=screenPath[0];if(secondaryCategory!=="suspendedBy")throw Error("Only hydrating suspendedBy paths is supported. This is a bug.");if(typeof screenPath[1]!=="number")throw Error("Expected suspendedBy index to be a number. Received '".concat(screenPath[1],"' instead. This is a bug."));suspendedByPathIndex=screenPath[1],rendererPath=screenPath.slice(2)}for(var rendererID in _this._rendererInterfaces){var renderer=_this._rendererInterfaces[rendererID],path=null;if(suspendedByPathIndex!==null&&rendererPath!==null){var suspendedByPathRendererIndex=suspendedByPathIndex-suspendedByOffset,rendererHasRequestedSuspendedByPath=renderer.getElementAttributeByPath(id,["suspendedBy",suspendedByPathRendererIndex])!==void 0;if(rendererHasRequestedSuspendedByPath)path=["suspendedBy",suspendedByPathRendererIndex].concat(rendererPath)}var inspectedRootsPayload=renderer.inspectElement(requestID,id,path,forceFullData);switch(inspectedRootsPayload.type){case"hydrated-path":if(inspectedRootsPayload.path[1]+=suspendedByOffset,inspectedRootsPayload.value!==null)for(var i=0;i<inspectedRootsPayload.value.cleaned.length;i++)inspectedRootsPayload.value.cleaned[i][1]+=suspendedByOffset;_this._bridge.send("inspectedScreen",inspectedRootsPayload);return;case"full-data":var inspectedRoots=inspectedRootsPayload.value;if(inspectedScreen===null)inspectedScreen=createEmptyInspectedScreen(inspectedRoots.id,inspectedRoots.type);mergeRoots(inspectedScreen,inspectedRoots,suspendedByOffset);var dehydratedSuspendedBy=inspectedRoots.suspendedBy,suspendedBy=dehydratedSuspendedBy.data;suspendedByOffset+=suspendedBy.length,found=!0;break;case"no-change":found=!0;var rootsSuspendedBy=renderer.getElementAttributeByPath(id,["suspendedBy"]);suspendedByOffset+=rootsSuspendedBy.length;break;case"not-found":break;case"error":_this._bridge.send("inspectedScreen",inspectedRootsPayload);return}}if(inspectedScreen===null)if(found)_this._bridge.send("inspectedScreen",{type:"no-change",responseID:requestID,id});else _this._bridge.send("inspectedScreen",{type:"not-found",responseID:requestID,id});else _this._bridge.send("inspectedScreen",{type:"full-data",responseID:requestID,id,value:inspectedScreen})}),agent_defineProperty(_this,"logElementToConsole",function(_ref11){var{id,rendererID}=_ref11,renderer=_this._rendererInterfaces[rendererID];if(renderer==null)console.warn('Invalid renderer id "'.concat(rendererID,'" for element "').concat(id,'"'));else renderer.logElementToConsole(id)}),agent_defineProperty(_this,"overrideError",function(_ref12){var{id,rendererID,forceError}=_ref12,renderer=_this._rendererInterfaces[rendererID];if(renderer==null)console.warn('Invalid renderer id "'.concat(rendererID,'" for element "').concat(id,'"'));else renderer.overrideError(id,forceError)}),agent_defineProperty(_this,"overrideSuspense",function(_ref13){var{id,rendererID,forceFallback}=_ref13,renderer=_this._rendererInterfaces[rendererID];if(renderer==null)console.warn('Invalid renderer id "'.concat(rendererID,'" for element "').concat(id,'"'));else renderer.overrideSuspense(id,forceFallback)}),agent_defineProperty(_this,"overrideSuspenseMilestone",function(_ref14){var suspendedSet=_ref14.suspendedSet;for(var rendererID in _this._rendererInterfaces){var renderer=_this._rendererInterfaces[rendererID];if(renderer.supportsTogglingSuspense)renderer.overrideSuspenseMilestone(suspendedSet)}}),agent_defineProperty(_this,"overrideValueAtPath",function(_ref15){var{hookID,id,path,rendererID,type,value}=_ref15,renderer=_this._rendererInterfaces[rendererID];if(renderer==null)console.warn('Invalid renderer id "'.concat(rendererID,'" for element "').concat(id,'"'));else renderer.overrideValueAtPath(type,id,hookID,path,value)}),agent_defineProperty(_this,"overrideContext",function(_ref16){var{id,path,rendererID,wasForwarded,value}=_ref16;if(!wasForwarded)_this.overrideValueAtPath({id,path,rendererID,type:"context",value})}),agent_defineProperty(_this,"overrideHookState",function(_ref17){var{id,hookID,path,rendererID,wasForwarded,value}=_ref17;if(!wasForwarded)_this.overrideValueAtPath({id,path,rendererID,type:"hooks",value})}),agent_defineProperty(_this,"overrideProps",function(_ref18){var{id,path,rendererID,wasForwarded,value}=_ref18;if(!wasForwarded)_this.overrideValueAtPath({id,path,rendererID,type:"props",value})}),agent_defineProperty(_this,"overrideState",function(_ref19){var{id,path,rendererID,wasForwarded,value}=_ref19;if(!wasForwarded)_this.overrideValueAtPath({id,path,rendererID,type:"state",value})}),agent_defineProperty(_this,"onReloadAndProfileSupportedByHost",function(){_this._bridge.send("isReloadAndProfileSupportedByBackend",!0)}),agent_defineProperty(_this,"reloadAndProfile",function(_ref20){var{recordChangeDescriptions,recordTimeline}=_ref20;if(typeof _this._onReloadAndProfile==="function")_this._onReloadAndProfile(recordChangeDescriptions,recordTimeline);_this._bridge.send("reloadAppForProfiling")}),agent_defineProperty(_this,"renamePath",function(_ref21){var{hookID,id,newPath,oldPath,rendererID,type}=_ref21,renderer=_this._rendererInterfaces[rendererID];if(renderer==null)console.warn('Invalid renderer id "'.concat(rendererID,'" for element "').concat(id,'"'));else renderer.renamePath(type,id,hookID,oldPath,newPath)}),agent_defineProperty(_this,"setTraceUpdatesEnabled",function(traceUpdatesEnabled){_this._traceUpdatesEnabled=traceUpdatesEnabled,toggleEnabled(traceUpdatesEnabled);for(var rendererID in _this._rendererInterfaces){var renderer=_this._rendererInterfaces[rendererID];renderer.setTraceUpdatesEnabled(traceUpdatesEnabled)}}),agent_defineProperty(_this,"syncSelectionFromBuiltinElementsPanel",function(){var target=window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0;if(target==null)return;_this.selectNode(target)}),agent_defineProperty(_this,"shutdown",function(){_this.emit("shutdown"),_this._bridge.removeAllListeners(),_this.removeAllListeners()}),agent_defineProperty(_this,"startProfiling",function(_ref22){var{recordChangeDescriptions,recordTimeline}=_ref22;_this._isProfiling=!0;for(var rendererID in _this._rendererInterfaces){var renderer=_this._rendererInterfaces[rendererID];renderer.startProfiling(recordChangeDescriptions,recordTimeline)}_this._bridge.send("profilingStatus",_this._isProfiling)}),agent_defineProperty(_this,"stopProfiling",function(){_this._isProfiling=!1;for(var rendererID in _this._rendererInterfaces){var renderer=_this._rendererInterfaces[rendererID];renderer.stopProfiling()}_this._bridge.send("profilingStatus",_this._isProfiling)}),agent_defineProperty(_this,"stopInspectingNative",function(selected){_this._bridge.send("stopInspectingHost",selected)}),agent_defineProperty(_this,"storeAsGlobal",function(_ref23){var{count,id,path,rendererID}=_ref23,renderer=_this._rendererInterfaces[rendererID];if(renderer==null)console.warn('Invalid renderer id "'.concat(rendererID,'" for element "').concat(id,'"'));else renderer.storeAsGlobal(id,path,count)}),agent_defineProperty(_this,"updateHookSettings",function(settings){_this.emit("updateHookSettings",settings)}),agent_defineProperty(_this,"getHookSettings",function(){_this.emit("getHookSettings")}),agent_defineProperty(_this,"onHookSettings",function(settings){_this._bridge.send("hookSettings",settings)}),agent_defineProperty(_this,"updateComponentFilters",function(componentFilters){for(var rendererIDString in _this._rendererInterfaces){var rendererID=+rendererIDString,renderer=_this._rendererInterfaces[rendererID];if(_this._lastSelectedRendererID===rendererID){var path=renderer.getPathForElement(_this._lastSelectedElementID);if(path!==null)renderer.setTrackedPath(path),_this._persistedSelection={rendererID,path}}renderer.updateComponentFilters(componentFilters)}}),agent_defineProperty(_this,"getEnvironmentNames",function(){var accumulatedNames=null;for(var rendererID in _this._rendererInterfaces){var renderer=_this._rendererInterfaces[+rendererID],names=renderer.getEnvironmentNames();if(accumulatedNames===null)accumulatedNames=names;else for(var i=0;i<names.length;i++)if(accumulatedNames.indexOf(names[i])===-1)accumulatedNames.push(names[i])}_this._bridge.send("environmentNames",accumulatedNames||[])}),agent_defineProperty(_this,"onTraceUpdates",function(nodes){_this.emit("traceUpdates",nodes)}),agent_defineProperty(_this,"onFastRefreshScheduled",function(){if(__DEBUG__)debug("onFastRefreshScheduled");_this._bridge.send("fastRefreshScheduled")}),agent_defineProperty(_this,"onHookOperations",function(operations){if(__DEBUG__)debug("onHookOperations","(".concat(operations.length,") [").concat(operations.join(", "),"]"));if(_this._bridge.send("operations",operations),_this._persistedSelection!==null){var rendererID=operations[0];if(_this._persistedSelection.rendererID===rendererID){var renderer=_this._rendererInterfaces[rendererID];if(renderer==null)console.warn('Invalid renderer id "'.concat(rendererID,'"'));else{var prevMatch=_this._persistedSelectionMatch,nextMatch=renderer.getBestMatchForTrackedPath();_this._persistedSelectionMatch=nextMatch;var prevMatchID=prevMatch!==null?prevMatch.id:null,nextMatchID=nextMatch!==null?nextMatch.id:null;if(prevMatchID!==nextMatchID){if(nextMatchID!==null)_this._bridge.send("selectElement",nextMatchID)}if(nextMatch!==null&&nextMatch.isFullMatch)_this._persistedSelection=null,_this._persistedSelectionMatch=null,renderer.setTrackedPath(null)}}}}),agent_defineProperty(_this,"getIfHasUnsupportedRendererVersion",function(){_this.emit("getIfHasUnsupportedRendererVersion")}),agent_defineProperty(_this,"_persistSelectionTimerScheduled",!1),agent_defineProperty(_this,"_lastSelectedRendererID",-1),agent_defineProperty(_this,"_lastSelectedElementID",-1),agent_defineProperty(_this,"_persistSelection",function(){_this._persistSelectionTimerScheduled=!1;var{_lastSelectedRendererID:rendererID,_lastSelectedElementID:id}=_this,renderer=_this._rendererInterfaces[rendererID],path=renderer!=null?renderer.getPathForElement(id):null;if(path!==null)storage_sessionStorageSetItem(SESSION_STORAGE_LAST_SELECTION_KEY,JSON.stringify({rendererID,path}));else storage_sessionStorageRemoveItem(SESSION_STORAGE_LAST_SELECTION_KEY)}),_this._isProfiling=isProfiling,_this._onReloadAndProfile=onReloadAndProfile2;var persistedSelectionString=storage_sessionStorageGetItem(SESSION_STORAGE_LAST_SELECTION_KEY);if(persistedSelectionString!=null)_this._persistedSelection=JSON.parse(persistedSelectionString);if(_this._bridge=bridge,bridge.addListener("clearErrorsAndWarnings",_this.clearErrorsAndWarnings),bridge.addListener("clearErrorsForElementID",_this.clearErrorsForElementID),bridge.addListener("clearWarningsForElementID",_this.clearWarningsForElementID),bridge.addListener("copyElementPath",_this.copyElementPath),bridge.addListener("deletePath",_this.deletePath),bridge.addListener("getBackendVersion",_this.getBackendVersion),bridge.addListener("getBridgeProtocol",_this.getBridgeProtocol),bridge.addListener("getProfilingData",_this.getProfilingData),bridge.addListener("getProfilingStatus",_this.getProfilingStatus),bridge.addListener("getOwnersList",_this.getOwnersList),bridge.addListener("inspectElement",_this.inspectElement),bridge.addListener("inspectScreen",_this.inspectScreen),bridge.addListener("logElementToConsole",_this.logElementToConsole),bridge.addListener("overrideError",_this.overrideError),bridge.addListener("overrideSuspense",_this.overrideSuspense),bridge.addListener("overrideSuspenseMilestone",_this.overrideSuspenseMilestone),bridge.addListener("overrideValueAtPath",_this.overrideValueAtPath),bridge.addListener("reloadAndProfile",_this.reloadAndProfile),bridge.addListener("renamePath",_this.renamePath),bridge.addListener("setTraceUpdatesEnabled",_this.setTraceUpdatesEnabled),bridge.addListener("startProfiling",_this.startProfiling),bridge.addListener("stopProfiling",_this.stopProfiling),bridge.addListener("storeAsGlobal",_this.storeAsGlobal),bridge.addListener("syncSelectionFromBuiltinElementsPanel",_this.syncSelectionFromBuiltinElementsPanel),bridge.addListener("shutdown",_this.shutdown),bridge.addListener("updateHookSettings",_this.updateHookSettings),bridge.addListener("getHookSettings",_this.getHookSettings),bridge.addListener("updateComponentFilters",_this.updateComponentFilters),bridge.addListener("getEnvironmentNames",_this.getEnvironmentNames),bridge.addListener("getIfHasUnsupportedRendererVersion",_this.getIfHasUnsupportedRendererVersion),bridge.addListener("overrideContext",_this.overrideContext),bridge.addListener("overrideHookState",_this.overrideHookState),bridge.addListener("overrideProps",_this.overrideProps),bridge.addListener("overrideState",_this.overrideState),setupHighlighter(bridge,_this),TraceUpdates_initialize(_this),bridge.send("backendInitialized"),_this._isProfiling)bridge.send("profilingStatus",!0);return _this}return agent_inherits(Agent2,_EventEmitter),agent_createClass(Agent2,[{key:"rendererInterfaces",get:function(){return this._rendererInterfaces}},{key:"getInstanceAndStyle",value:function(_ref24){var{id,rendererID}=_ref24,renderer=this._rendererInterfaces[rendererID];if(renderer==null)return console.warn('Invalid renderer id "'.concat(rendererID,'"')),null;return renderer.getInstanceAndStyle(id)}},{key:"getIDForHostInstance",value:function(target,onlySuspenseNodes){if(isReactNativeEnvironment()||typeof target.nodeType!=="number"){for(var rendererID in this._rendererInterfaces){var renderer=this._rendererInterfaces[rendererID];try{var id=onlySuspenseNodes?renderer.getSuspenseNodeIDForHostInstance(target):renderer.getElementIDForHostInstance(target);if(id!==null)return{id,rendererID:+rendererID}}catch(error){}}return null}else{var bestMatch=null,bestRenderer=null,bestRendererID=0;for(var _rendererID in this._rendererInterfaces){var _renderer=this._rendererInterfaces[_rendererID],nearestNode=_renderer.getNearestMountedDOMNode(target);if(nearestNode!==null){if(nearestNode===target){bestMatch=nearestNode,bestRenderer=_renderer,bestRendererID=+_rendererID;break}if(bestMatch===null||bestMatch.contains(nearestNode))bestMatch=nearestNode,bestRenderer=_renderer,bestRendererID=+_rendererID}}if(bestRenderer!=null&&bestMatch!=null)try{var _id=onlySuspenseNodes?bestRenderer.getSuspenseNodeIDForHostInstance(bestMatch):bestRenderer.getElementIDForHostInstance(bestMatch);if(_id!==null)return{id:_id,rendererID:bestRendererID}}catch(error){}return null}}},{key:"getComponentNameForHostInstance",value:function(target){var match=this.getIDForHostInstance(target);if(match!==null){var renderer=this._rendererInterfaces[match.rendererID];return renderer.getDisplayNameForElementID(match.id)}return null}},{key:"selectNode",value:function(target){var match=this.getIDForHostInstance(target);if(match!==null)this._bridge.send("selectElement",match.id)}},{key:"registerRendererInterface",value:function(rendererID,rendererInterface){this._rendererInterfaces[rendererID]=rendererInterface,rendererInterface.setTraceUpdatesEnabled(this._traceUpdatesEnabled);var renderer=rendererInterface.renderer;if(renderer!==null){var devRenderer=renderer.bundleType===1,enableSuspenseTab=devRenderer&&gte(renderer.version,"19.3.0-canary");if(enableSuspenseTab)this._bridge.send("enableSuspenseTab")}var selection=this._persistedSelection;if(selection!==null&&selection.rendererID===rendererID)rendererInterface.setTrackedPath(selection.path)}},{key:"onUnsupportedRenderer",value:function(){this._bridge.send("unsupportedRendererVersion")}}])}(EventEmitter);function DevToolsConsolePatching_typeof(o){return DevToolsConsolePatching_typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},DevToolsConsolePatching_typeof(o)}function DevToolsConsolePatching_ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r2){return Object.getOwnPropertyDescriptor(e,r2).enumerable})),t.push.apply(t,o)}return t}function DevToolsConsolePatching_objectSpread(e){for(var r=1;r<arguments.length;r++){var t=arguments[r]!=null?arguments[r]:{};r%2?DevToolsConsolePatching_ownKeys(Object(t),!0).forEach(function(r2){DevToolsConsolePatching_defineProperty(e,r2,t[r2])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):DevToolsConsolePatching_ownKeys(Object(t)).forEach(function(r2){Object.defineProperty(e,r2,Object.getOwnPropertyDescriptor(t,r2))})}return e}function DevToolsConsolePatching_defineProperty(obj,key,value){if(key=DevToolsConsolePatching_toPropertyKey(key),key in obj)Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0});else obj[key]=value;return obj}function DevToolsConsolePatching_toPropertyKey(t){var i=DevToolsConsolePatching_toPrimitive(t,"string");return DevToolsConsolePatching_typeof(i)=="symbol"?i:i+""}function DevToolsConsolePatching_toPrimitive(t,r){if(DevToolsConsolePatching_typeof(t)!="object"||!t)return t;var e=t[Symbol.toPrimitive];if(e!==void 0){var i=e.call(t,r||"default");if(DevToolsConsolePatching_typeof(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(t)}var disabledDepth=0,prevLog,prevInfo,prevWarn,prevError,prevGroup,prevGroupCollapsed,prevGroupEnd;function disabledLog(){}disabledLog.__reactDisabledLog=!0;function disableLogs(){if(disabledDepth===0){prevLog=console.log,prevInfo=console.info,prevWarn=console.warn,prevError=console.error,prevGroup=console.group,prevGroupCollapsed=console.groupCollapsed,prevGroupEnd=console.groupEnd;var props={configurable:!0,enumerable:!0,value:disabledLog,writable:!0};Object.defineProperties(console,{info:props,log:props,warn:props,error:props,group:props,groupCollapsed:props,groupEnd:props})}disabledDepth++}function reenableLogs(){if(disabledDepth--,disabledDepth===0){var props={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:DevToolsConsolePatching_objectSpread(DevToolsConsolePatching_objectSpread({},props),{},{value:prevLog}),info:DevToolsConsolePatching_objectSpread(DevToolsConsolePatching_objectSpread({},props),{},{value:prevInfo}),warn:DevToolsConsolePatching_objectSpread(DevToolsConsolePatching_objectSpread({},props),{},{value:prevWarn}),error:DevToolsConsolePatching_objectSpread(DevToolsConsolePatching_objectSpread({},props),{},{value:prevError}),group:DevToolsConsolePatching_objectSpread(DevToolsConsolePatching_objectSpread({},props),{},{value:prevGroup}),groupCollapsed:DevToolsConsolePatching_objectSpread(DevToolsConsolePatching_objectSpread({},props),{},{value:prevGroupCollapsed}),groupEnd:DevToolsConsolePatching_objectSpread(DevToolsConsolePatching_objectSpread({},props),{},{value:prevGroupEnd})})}if(disabledDepth<0)console.error("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}function DevToolsComponentStackFrame_slicedToArray(arr,i){return DevToolsComponentStackFrame_arrayWithHoles(arr)||DevToolsComponentStackFrame_iterableToArrayLimit(arr,i)||DevToolsComponentStackFrame_unsupportedIterableToArray(arr,i)||DevToolsComponentStackFrame_nonIterableRest()}function DevToolsComponentStackFrame_nonIterableRest(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
139
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function DevToolsComponentStackFrame_unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return DevToolsComponentStackFrame_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return DevToolsComponentStackFrame_arrayLikeToArray(o,minLen)}function DevToolsComponentStackFrame_arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function DevToolsComponentStackFrame_iterableToArrayLimit(r,l){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,l===0){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r2){o=!0,n=r2}finally{try{if(!f&&t.return!=null&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}function DevToolsComponentStackFrame_arrayWithHoles(arr){if(Array.isArray(arr))return arr}function DevToolsComponentStackFrame_typeof(o){return DevToolsComponentStackFrame_typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},DevToolsComponentStackFrame_typeof(o)}var prefix;function describeBuiltInComponentFrame(name){if(prefix===void 0)try{throw Error()}catch(x){var match=x.stack.trim().match(/\n( *(at )?)/);prefix=match&&match[1]||""}var suffix="";return suffix=" (<anonymous>)",`
140
+ `+prefix+name+suffix}function describeDebugInfoFrame(name,env){return describeBuiltInComponentFrame(name+(env?" ["+env+"]":""))}var reentry=!1,componentFrameCache;if(!1)var PossiblyWeakMap;function describeNativeComponentFrame(fn,construct,currentDispatcherRef){if(!fn||reentry)return"";if(!1)var frame;var previousPrepareStackTrace=Error.prepareStackTrace;Error.prepareStackTrace=void 0,reentry=!0;var previousDispatcher=currentDispatcherRef.H;currentDispatcherRef.H=null,disableLogs();try{var RunInRootFrame={DetermineComponentFrameRoot:function(){var control;try{if(construct){var Fake=function(){throw Error()};if(Object.defineProperty(Fake.prototype,"props",{set:function(){throw Error()}}),(typeof Reflect>"u"?"undefined":DevToolsComponentStackFrame_typeof(Reflect))==="object"&&Reflect.construct){try{Reflect.construct(Fake,[])}catch(x){control=x}Reflect.construct(fn,[],Fake)}else{try{Fake.call()}catch(x){control=x}fn.call(Fake.prototype)}}else{try{throw Error()}catch(x){control=x}var maybePromise=fn();if(maybePromise&&typeof maybePromise.catch==="function")maybePromise.catch(function(){})}}catch(sample){if(sample&&control&&typeof sample.stack==="string")return[sample.stack,control.stack]}return[null,null]}};RunInRootFrame.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var namePropDescriptor=Object.getOwnPropertyDescriptor(RunInRootFrame.DetermineComponentFrameRoot,"name");if(namePropDescriptor&&namePropDescriptor.configurable)Object.defineProperty(RunInRootFrame.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var _RunInRootFrame$Deter=RunInRootFrame.DetermineComponentFrameRoot(),_RunInRootFrame$Deter2=DevToolsComponentStackFrame_slicedToArray(_RunInRootFrame$Deter,2),sampleStack=_RunInRootFrame$Deter2[0],controlStack=_RunInRootFrame$Deter2[1];if(sampleStack&&controlStack){var sampleLines=sampleStack.split(`
141
+ `),controlLines=controlStack.split(`
142
+ `),s=0,c=0;while(s<sampleLines.length&&!sampleLines[s].includes("DetermineComponentFrameRoot"))s++;while(c<controlLines.length&&!controlLines[c].includes("DetermineComponentFrameRoot"))c++;if(s===sampleLines.length||c===controlLines.length){s=sampleLines.length-1,c=controlLines.length-1;while(s>=1&&c>=0&&sampleLines[s]!==controlLines[c])c--}for(;s>=1&&c>=0;s--,c--)if(sampleLines[s]!==controlLines[c]){if(s!==1||c!==1)do if(s--,c--,c<0||sampleLines[s]!==controlLines[c]){var _frame=`
143
+ `+sampleLines[s].replace(" at new "," at ");if(fn.displayName&&_frame.includes("<anonymous>"))_frame=_frame.replace("<anonymous>",fn.displayName);return _frame}while(s>=1&&c>=0);break}}}finally{reentry=!1,Error.prepareStackTrace=previousPrepareStackTrace,currentDispatcherRef.H=previousDispatcher,reenableLogs()}var name=fn?fn.displayName||fn.name:"",syntheticFrame=name?describeBuiltInComponentFrame(name):"";return syntheticFrame}function describeClassComponentFrame(ctor,currentDispatcherRef){return describeNativeComponentFrame(ctor,!0,currentDispatcherRef)}function describeFunctionComponentFrame(fn,currentDispatcherRef){return describeNativeComponentFrame(fn,!1,currentDispatcherRef)}function formatOwnerStack(error){var prevPrepareStackTrace=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var stack=error.stack;if(Error.prepareStackTrace=prevPrepareStackTrace,stack.startsWith(`Error: react-stack-top-frame
144
+ `))stack=stack.slice(29);var idx=stack.indexOf(`
145
+ `);if(idx!==-1)stack=stack.slice(idx+1);if(idx=stack.indexOf("react_stack_bottom_frame"),idx===-1)idx=stack.indexOf("react-stack-bottom-frame");if(idx!==-1)idx=stack.lastIndexOf(`
146
+ `,idx);if(idx!==-1)stack=stack.slice(0,idx);else return"";return stack}function getOwnerStackByComponentInfoInDev(componentInfo){try{var info="";if(!componentInfo.owner&&typeof componentInfo.name==="string")return describeBuiltInComponentFrame(componentInfo.name);var owner=componentInfo;while(owner){var ownerStack=owner.debugStack;if(ownerStack!=null){if(owner=owner.owner,owner)info+=`
147
+ `+formatOwnerStack(ownerStack)}else break}return info}catch(x){return`
148
+ Error generating stack: `+x.message+`
149
+ `+x.stack}}var componentInfoToComponentLogsMap=new WeakMap;function renderer_toConsumableArray(arr){return renderer_arrayWithoutHoles(arr)||renderer_iterableToArray(arr)||renderer_unsupportedIterableToArray(arr)||renderer_nonIterableSpread()}function renderer_nonIterableSpread(){throw TypeError(`Invalid attempt to spread non-iterable instance.
150
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function renderer_unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return renderer_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return renderer_arrayLikeToArray(o,minLen)}function renderer_iterableToArray(iter){if(typeof Symbol<"u"&&iter[Symbol.iterator]!=null||iter["@@iterator"]!=null)return Array.from(iter)}function renderer_arrayWithoutHoles(arr){if(Array.isArray(arr))return renderer_arrayLikeToArray(arr)}function renderer_arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function supportsConsoleTasks(componentInfo){return!!componentInfo.debugTask}function attach(hook,rendererID,renderer,global){var getCurrentComponentInfo=renderer.getCurrentComponentInfo;function getComponentStack(topFrame){if(getCurrentComponentInfo===void 0)return null;var current=getCurrentComponentInfo();if(current===null)return null;if(supportsConsoleTasks(current))return null;var enableOwnerStacks=current.debugStack!=null,componentStack="";if(enableOwnerStacks){var topStackFrames=formatOwnerStack(topFrame);if(topStackFrames)componentStack+=`
151
+ `+topStackFrames;componentStack+=getOwnerStackByComponentInfoInDev(current)}return{enableOwnerStacks,componentStack}}function onErrorOrWarning(type,args){if(getCurrentComponentInfo===void 0)return;var componentInfo=getCurrentComponentInfo();if(componentInfo===null)return;if(args.length>3&&typeof args[0]==="string"&&args[0].startsWith("%c%s%c ")&&typeof args[1]==="string"&&typeof args[2]==="string"&&typeof args[3]==="string"){var format=args[0].slice(7),env=args[2].trim();if(args=args.slice(4),env!==componentInfo.env)args.unshift("["+env+"] "+format);else args.unshift(format)}var message=formatConsoleArgumentsToSingleString.apply(void 0,renderer_toConsumableArray(args)),componentLogsEntry=componentInfoToComponentLogsMap.get(componentInfo);if(componentLogsEntry===void 0)componentLogsEntry={errors:new Map,errorsCount:0,warnings:new Map,warningsCount:0},componentInfoToComponentLogsMap.set(componentInfo,componentLogsEntry);var messageMap=type==="error"?componentLogsEntry.errors:componentLogsEntry.warnings,count=messageMap.get(message)||0;if(messageMap.set(message,count+1),type==="error")componentLogsEntry.errorsCount++;else componentLogsEntry.warningsCount++}var supportsTogglingSuspense=!1;return{cleanup:function(){},clearErrorsAndWarnings:function(){},clearErrorsForElementID:function(){},clearWarningsForElementID:function(){},getSerializedElementValueByPath:function(){},deletePath:function(){},findHostInstancesForElementID:function(){return null},findLastKnownRectsForID:function(){return null},flushInitialOperations:function(){},getBestMatchForTrackedPath:function(){return null},getComponentStack,getDisplayNameForElementID:function(){return null},getNearestMountedDOMNode:function(){return null},getElementIDForHostInstance:function(){return null},getSuspenseNodeIDForHostInstance:function(){return null},getInstanceAndStyle:function(){return{instance:null,style:null}},getOwnersList:function(){return null},getPathForElement:function(){return null},getProfilingData:function(){throw Error("getProfilingData not supported by this renderer")},handleCommitFiberRoot:function(){},handleCommitFiberUnmount:function(){},handlePostCommitFiberRoot:function(){},hasElementWithId:function(){return!1},inspectElement:function(requestID,id,path){return{id,responseID:requestID,type:"not-found"}},logElementToConsole:function(){},getElementAttributeByPath:function(){},getElementSourceFunctionById:function(){},onErrorOrWarning,overrideError:function(){},overrideSuspense:function(){},overrideSuspenseMilestone:function(){},overrideValueAtPath:function(){},renamePath:function(){},renderer,setTraceUpdatesEnabled:function(){},setTrackedPath:function(){},startProfiling:function(){},stopProfiling:function(){},storeAsGlobal:function(){},supportsTogglingSuspense,updateComponentFilters:function(){},getEnvironmentNames:function(){return[]}}}function parseStackTrace_slicedToArray(arr,i){return parseStackTrace_arrayWithHoles(arr)||parseStackTrace_iterableToArrayLimit(arr,i)||parseStackTrace_unsupportedIterableToArray(arr,i)||parseStackTrace_nonIterableRest()}function parseStackTrace_nonIterableRest(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
152
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function parseStackTrace_unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return parseStackTrace_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return parseStackTrace_arrayLikeToArray(o,minLen)}function parseStackTrace_arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function parseStackTrace_iterableToArrayLimit(r,l){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,l===0){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r2){o=!0,n=r2}finally{try{if(!f&&t.return!=null&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}function parseStackTrace_arrayWithHoles(arr){if(Array.isArray(arr))return arr}function parseStackTraceFromChromeStack(stack,skipFrames){if(stack.startsWith(`Error: react-stack-top-frame
153
+ `))stack=stack.slice(29);var idx=stack.indexOf("react_stack_bottom_frame");if(idx===-1)idx=stack.indexOf("react-stack-bottom-frame");if(idx!==-1)idx=stack.lastIndexOf(`
154
+ `,idx);if(idx!==-1)stack=stack.slice(0,idx);var frames=stack.split(`
155
+ `),parsedFrames=[];for(var i=skipFrames;i<frames.length;i++){var parsed=chromeFrameRegExp.exec(frames[i]);if(!parsed)continue;var name=parsed[1]||"",isAsync=parsed[8]==="async ";if(name==="<anonymous>")name="";else if(name.startsWith("async "))name=name.slice(5),isAsync=!0;var filename=parsed[2]||parsed[5]||"";if(filename==="<anonymous>")filename="";var line=+(parsed[3]||parsed[6]||0),col=+(parsed[4]||parsed[7]||0);parsedFrames.push([name,filename,line,col,0,0,isAsync])}return parsedFrames}var firefoxFrameRegExp=/^((?:.*".+")?[^@]*)@(.+):(\d+):(\d+)$/;function parseStackTraceFromFirefoxStack(stack,skipFrames){var idx=stack.indexOf("react_stack_bottom_frame");if(idx===-1)idx=stack.indexOf("react-stack-bottom-frame");if(idx!==-1)idx=stack.lastIndexOf(`
156
+ `,idx);if(idx!==-1)stack=stack.slice(0,idx);var frames=stack.split(`
157
+ `),parsedFrames=[];for(var i=skipFrames;i<frames.length;i++){var parsed=firefoxFrameRegExp.exec(frames[i]);if(!parsed)continue;var name=parsed[1]||"",filename=parsed[2]||"",line=+parsed[3],col=+parsed[4];parsedFrames.push([name,filename,line,col,0,0,!1])}return parsedFrames}var CHROME_STACK_REGEXP=/^\s*at .*(\S+:\d+|\(native\))/m;function parseStackTraceFromString(stack,skipFrames){if(stack.match(CHROME_STACK_REGEXP))return parseStackTraceFromChromeStack(stack,skipFrames);return parseStackTraceFromFirefoxStack(stack,skipFrames)}var framesToSkip=0,collectedStackTrace=null,identifierRegExp=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/;function getMethodCallName(callSite){var typeName=callSite.getTypeName(),methodName=callSite.getMethodName(),functionName=callSite.getFunctionName(),result="";if(functionName){if(typeName&&identifierRegExp.test(functionName)&&functionName!==typeName)result+=typeName+".";if(result+=functionName,methodName&&functionName!==methodName&&!functionName.endsWith("."+methodName)&&!functionName.endsWith(" "+methodName))result+=" [as "+methodName+"]"}else{if(typeName)result+=typeName+".";if(methodName)result+=methodName;else result+="<anonymous>"}return result}function collectStackTrace(error,structuredStackTrace){var result=[];for(var i=framesToSkip;i<structuredStackTrace.length;i++){var callSite=structuredStackTrace[i],_name=callSite.getFunctionName()||"<anonymous>";if(_name.includes("react_stack_bottom_frame")||_name.includes("react-stack-bottom-frame"))break;else if(callSite.isNative()){var isAsync=callSite.isAsync();result.push([_name,"",0,0,0,0,isAsync])}else{if(callSite.isConstructor())_name="new "+_name;else if(!callSite.isToplevel())_name=getMethodCallName(callSite);if(_name==="<anonymous>")_name="";var filename=callSite.getScriptNameOrSourceURL()||"<anonymous>";if(filename==="<anonymous>"){if(filename="",callSite.isEval()){var origin=callSite.getEvalOrigin();if(origin)filename=origin.toString()+", <anonymous>"}}var line=callSite.getLineNumber()||0,col=callSite.getColumnNumber()||0,enclosingLine=typeof callSite.getEnclosingLineNumber==="function"?callSite.getEnclosingLineNumber()||0:0,enclosingCol=typeof callSite.getEnclosingColumnNumber==="function"?callSite.getEnclosingColumnNumber()||0:0,_isAsync=callSite.isAsync();result.push([_name,filename,line,col,enclosingLine,enclosingCol,_isAsync])}}collectedStackTrace=result;var name=error.name||"Error",message=error.message||"",stack=name+": "+message;for(var _i=0;_i<structuredStackTrace.length;_i++)stack+=`
158
+ at `+structuredStackTrace[_i].toString();return stack}var chromeFrameRegExp=/^ *at (?:(.+) \((?:(.+):(\d+):(\d+)|\<anonymous\>)\)|(?:async )?(.+):(\d+):(\d+)|\<anonymous\>)$/,stackTraceCache=new WeakMap;function parseStackTrace(error,skipFrames){var existing=stackTraceCache.get(error);if(existing!==void 0)return existing;collectedStackTrace=null,framesToSkip=skipFrames;var previousPrepare=Error.prepareStackTrace;Error.prepareStackTrace=collectStackTrace;var stack;try{stack=String(error.stack)}finally{Error.prepareStackTrace=previousPrepare}if(collectedStackTrace!==null){var result=collectedStackTrace;return collectedStackTrace=null,stackTraceCache.set(error,result),result}var parsedFrames=parseStackTraceFromString(stack,skipFrames);return stackTraceCache.set(error,parsedFrames),parsedFrames}function extractLocationFromOwnerStack(error){var stackTrace=parseStackTrace(error,1),stack=error.stack;if(!stack.includes("react_stack_bottom_frame")&&!stack.includes("react-stack-bottom-frame"))return null;for(var i=stackTrace.length-1;i>=0;i--){var _stackTrace$i=parseStackTrace_slicedToArray(stackTrace[i],6),functionName=_stackTrace$i[0],fileName=_stackTrace$i[1],line=_stackTrace$i[2],col=_stackTrace$i[3],encLine=_stackTrace$i[4],encCol=_stackTrace$i[5];if(fileName.indexOf(":")!==-1)return[functionName,fileName,encLine||line,encCol||col]}return null}function extractLocationFromComponentStack(stack){var stackTrace=parseStackTraceFromString(stack,0);for(var i=0;i<stackTrace.length;i++){var _stackTrace$i2=parseStackTrace_slicedToArray(stackTrace[i],6),functionName=_stackTrace$i2[0],fileName=_stackTrace$i2[1],line=_stackTrace$i2[2],col=_stackTrace$i2[3],encLine=_stackTrace$i2[4],encCol=_stackTrace$i2[5];if(fileName.indexOf(":")!==-1)return[functionName,fileName,encLine||line,encCol||col]}return null}var react_debug_tools=__webpack_require__(987),CONCURRENT_MODE_NUMBER=60111,CONCURRENT_MODE_SYMBOL_STRING="Symbol(react.concurrent_mode)",CONTEXT_NUMBER=60110,CONTEXT_SYMBOL_STRING="Symbol(react.context)",SERVER_CONTEXT_SYMBOL_STRING="Symbol(react.server_context)",DEPRECATED_ASYNC_MODE_SYMBOL_STRING="Symbol(react.async_mode)",ELEMENT_SYMBOL_STRING="Symbol(react.transitional.element)",LEGACY_ELEMENT_NUMBER=60103,LEGACY_ELEMENT_SYMBOL_STRING="Symbol(react.element)",DEBUG_TRACING_MODE_NUMBER=60129,DEBUG_TRACING_MODE_SYMBOL_STRING="Symbol(react.debug_trace_mode)",FORWARD_REF_NUMBER=60112,FORWARD_REF_SYMBOL_STRING="Symbol(react.forward_ref)",FRAGMENT_NUMBER=60107,FRAGMENT_SYMBOL_STRING="Symbol(react.fragment)",LAZY_NUMBER=60116,LAZY_SYMBOL_STRING="Symbol(react.lazy)",MEMO_NUMBER=60115,MEMO_SYMBOL_STRING="Symbol(react.memo)",PORTAL_NUMBER=60106,PORTAL_SYMBOL_STRING="Symbol(react.portal)",PROFILER_NUMBER=60114,PROFILER_SYMBOL_STRING="Symbol(react.profiler)",PROVIDER_NUMBER=60109,PROVIDER_SYMBOL_STRING="Symbol(react.provider)",CONSUMER_SYMBOL_STRING="Symbol(react.consumer)",SCOPE_NUMBER=60119,SCOPE_SYMBOL_STRING="Symbol(react.scope)",STRICT_MODE_NUMBER=60108,STRICT_MODE_SYMBOL_STRING="Symbol(react.strict_mode)",SUSPENSE_NUMBER=60113,SUSPENSE_SYMBOL_STRING="Symbol(react.suspense)",SUSPENSE_LIST_NUMBER=60120,SUSPENSE_LIST_SYMBOL_STRING="Symbol(react.suspense_list)",SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED_SYMBOL_STRING="Symbol(react.server_context.defaultValue)",ReactSymbols_REACT_MEMO_CACHE_SENTINEL=Symbol.for("react.memo_cache_sentinel"),enableLogger=!1,enableStyleXFeatures=!1,isInternalFacebookBuild=!1;function is(x,y){return x===y&&(x!==0||1/x===1/y)||x!==x&&y!==y}var objectIs=typeof Object.is==="function"?Object.is:is;let shared_objectIs=objectIs;var hasOwnProperty_hasOwnProperty=Object.prototype.hasOwnProperty;let shared_hasOwnProperty=hasOwnProperty_hasOwnProperty;function ReactIODescription_typeof(o){return ReactIODescription_typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},ReactIODescription_typeof(o)}function getIODescription(value){return"";try{switch(ReactIODescription_typeof(value)){case"function":return value.name||"";case"object":if(value===null)return"";else if(value instanceof Error)return String(value.message);else if(typeof value.url==="string")return value.url;else if(typeof value.href==="string")return value.href;else if(typeof value.src==="string")return value.src;else if(typeof value.currentSrc==="string")return value.currentSrc;else if(typeof value.command==="string")return value.command;else if(ReactIODescription_typeof(value.request)==="object"&&value.request!==null&&typeof value.request.url==="string")return value.request.url;else if(ReactIODescription_typeof(value.response)==="object"&&value.response!==null&&typeof value.response.url==="string")return value.response.url;else if(typeof value.id==="string"||typeof value.id==="number"||typeof value.id==="bigint")return String(value.id);else if(typeof value.name==="string")return value.name;else{var str=value.toString();if(str.startsWith("[object ")||str.length<5||str.length>500)return"";return str}case"string":if(value.length<5||value.length>500)return"";return value;case"number":case"bigint":return String(value);default:return""}}catch(x){return""}}function describeFiber(workTagMap,workInProgress,currentDispatcherRef){var{HostHoistable,HostSingleton,HostComponent,LazyComponent,SuspenseComponent,SuspenseListComponent,FunctionComponent,IndeterminateComponent,SimpleMemoComponent,ForwardRef,ClassComponent,ViewTransitionComponent,ActivityComponent}=workTagMap;switch(workInProgress.tag){case HostHoistable:case HostSingleton:case HostComponent:return describeBuiltInComponentFrame(workInProgress.type);case LazyComponent:return describeBuiltInComponentFrame("Lazy");case SuspenseComponent:return describeBuiltInComponentFrame("Suspense");case SuspenseListComponent:return describeBuiltInComponentFrame("SuspenseList");case ViewTransitionComponent:return describeBuiltInComponentFrame("ViewTransition");case ActivityComponent:return describeBuiltInComponentFrame("Activity");case FunctionComponent:case IndeterminateComponent:case SimpleMemoComponent:return describeFunctionComponentFrame(workInProgress.type,currentDispatcherRef);case ForwardRef:return describeFunctionComponentFrame(workInProgress.type.render,currentDispatcherRef);case ClassComponent:return describeClassComponentFrame(workInProgress.type,currentDispatcherRef);default:return""}}function getStackByFiberInDevAndProd(workTagMap,workInProgress,currentDispatcherRef){try{var info="",node=workInProgress;do{info+=describeFiber(workTagMap,node,currentDispatcherRef);var debugInfo=node._debugInfo;if(debugInfo)for(var i=debugInfo.length-1;i>=0;i--){var entry=debugInfo[i];if(typeof entry.name==="string")info+=describeDebugInfoFrame(entry.name,entry.env)}node=node.return}while(node);return info}catch(x){return`
159
+ Error generating stack: `+x.message+`
160
+ `+x.stack}}function getSourceLocationByFiber(workTagMap,fiber,currentDispatcherRef){try{var info=describeFiber(workTagMap,fiber,currentDispatcherRef);if(info!=="")return info.slice(1)}catch(x){console.error(x)}return null}function DevToolsFiberComponentStack_supportsConsoleTasks(fiber){return!!fiber._debugTask}function supportsOwnerStacks(fiber){return fiber._debugStack!==void 0}function getOwnerStackByFiberInDev(workTagMap,workInProgress,currentDispatcherRef){var{HostHoistable,HostSingleton,HostText,HostComponent,SuspenseComponent,SuspenseListComponent,ViewTransitionComponent,ActivityComponent}=workTagMap;try{var info="";if(workInProgress.tag===HostText)workInProgress=workInProgress.return;switch(workInProgress.tag){case HostHoistable:case HostSingleton:case HostComponent:info+=describeBuiltInComponentFrame(workInProgress.type);break;case SuspenseComponent:info+=describeBuiltInComponentFrame("Suspense");break;case SuspenseListComponent:info+=describeBuiltInComponentFrame("SuspenseList");break;case ViewTransitionComponent:info+=describeBuiltInComponentFrame("ViewTransition");break;case ActivityComponent:info+=describeBuiltInComponentFrame("Activity");break}var owner=workInProgress;while(owner)if(typeof owner.tag==="number"){var fiber=owner;owner=fiber._debugOwner;var debugStack=fiber._debugStack;if(owner&&debugStack){if(typeof debugStack!=="string")debugStack=formatOwnerStack(debugStack);if(debugStack!=="")info+=`
161
+ `+debugStack}}else if(owner.debugStack!=null){var ownerStack=owner.debugStack;if(owner=owner.owner,owner&&ownerStack)info+=`
162
+ `+formatOwnerStack(ownerStack)}else break;return info}catch(x){return`
163
+ Error generating stack: `+x.message+`
164
+ `+x.stack}}var cachedStyleNameToValueMap=new Map;function getStyleXData(data){var sources=new Set,resolvedStyles={};return crawlData(data,sources,resolvedStyles),{sources:Array.from(sources).sort(),resolvedStyles}}function crawlData(data,sources,resolvedStyles){if(data==null)return;if(src_isArray(data))data.forEach(function(entry){if(entry==null)return;if(src_isArray(entry))crawlData(entry,sources,resolvedStyles);else crawlObjectProperties(entry,sources,resolvedStyles)});else crawlObjectProperties(data,sources,resolvedStyles);resolvedStyles=Object.fromEntries(Object.entries(resolvedStyles).sort())}function crawlObjectProperties(entry,sources,resolvedStyles){var keys=Object.keys(entry);keys.forEach(function(key){var value=entry[key];if(typeof value==="string")if(key===value)sources.add(key);else{var propertyValue=getPropertyValueForStyleName(value);if(propertyValue!=null)resolvedStyles[key]=propertyValue}else{var nestedStyle={};resolvedStyles[key]=nestedStyle,crawlData([value],sources,nestedStyle)}})}function getPropertyValueForStyleName(styleName){if(cachedStyleNameToValueMap.has(styleName))return cachedStyleNameToValueMap.get(styleName);for(var styleSheetIndex=0;styleSheetIndex<document.styleSheets.length;styleSheetIndex++){var styleSheet=document.styleSheets[styleSheetIndex],rules=null;try{rules=styleSheet.cssRules}catch(_e){continue}for(var ruleIndex=0;ruleIndex<rules.length;ruleIndex++){if(!(rules[ruleIndex]instanceof CSSStyleRule))continue;var rule=rules[ruleIndex],cssText=rule.cssText,selectorText=rule.selectorText,style=rule.style;if(selectorText!=null){if(selectorText.startsWith(".".concat(styleName))){var match=cssText.match(/{ *([a-z\-]+):/);if(match!==null){var property=match[1],value=style.getPropertyValue(property);return cachedStyleNameToValueMap.set(styleName,value),value}else return null}}}}return null}var CHANGE_LOG_URL="https://github.com/facebook/react/blob/main/packages/react-devtools/CHANGELOG.md",UNSUPPORTED_VERSION_URL="https://reactjs.org/blog/2019/08/15/new-react-devtools.html#how-do-i-get-the-old-version-back",REACT_DEVTOOLS_WORKPLACE_URL="https://fburl.com/react-devtools-workplace-group",THEME_STYLES={light:{"--color-attribute-name":"#ef6632","--color-attribute-name-not-editable":"#23272f","--color-attribute-name-inverted":"rgba(255, 255, 255, 0.7)","--color-attribute-value":"#1a1aa6","--color-attribute-value-inverted":"#ffffff","--color-attribute-editable-value":"#1a1aa6","--color-background":"#ffffff","--color-background-hover":"rgba(0, 136, 250, 0.1)","--color-background-inactive":"#e5e5e5","--color-background-invalid":"#fff0f0","--color-background-selected":"#0088fa","--color-button-background":"#ffffff","--color-button-background-focus":"#ededed","--color-button-background-hover":"rgba(0, 0, 0, 0.2)","--color-button":"#5f6673","--color-button-disabled":"#cfd1d5","--color-button-active":"#0088fa","--color-button-focus":"#23272f","--color-button-hover":"#23272f","--color-border":"#eeeeee","--color-commit-did-not-render-fill":"#cfd1d5","--color-commit-did-not-render-fill-text":"#000000","--color-commit-did-not-render-pattern":"#cfd1d5","--color-commit-did-not-render-pattern-text":"#333333","--color-commit-gradient-0":"#37afa9","--color-commit-gradient-1":"#63b19e","--color-commit-gradient-2":"#80b393","--color-commit-gradient-3":"#97b488","--color-commit-gradient-4":"#abb67d","--color-commit-gradient-5":"#beb771","--color-commit-gradient-6":"#cfb965","--color-commit-gradient-7":"#dfba57","--color-commit-gradient-8":"#efbb49","--color-commit-gradient-9":"#febc38","--color-commit-gradient-text":"#000000","--color-component-name":"#6a51b2","--color-component-name-inverted":"#ffffff","--color-component-badge-background":"#e6e6e6","--color-component-badge-background-inverted":"rgba(255, 255, 255, 0.25)","--color-component-badge-count":"#777d88","--color-component-badge-count-inverted":"rgba(255, 255, 255, 0.7)","--color-console-error-badge-text":"#ffffff","--color-console-error-background":"#fff0f0","--color-console-error-border":"#ffd6d6","--color-console-error-icon":"#eb3941","--color-console-error-text":"#fe2e31","--color-console-warning-badge-text":"#000000","--color-console-warning-background":"#fffbe5","--color-console-warning-border":"#fff5c1","--color-console-warning-icon":"#f4bd00","--color-console-warning-text":"#64460c","--color-context-background":"rgba(0,0,0,.9)","--color-context-background-hover":"rgba(255, 255, 255, 0.1)","--color-context-background-selected":"#178fb9","--color-context-border":"#3d424a","--color-context-text":"#ffffff","--color-context-text-selected":"#ffffff","--color-dim":"#777d88","--color-dimmer":"#cfd1d5","--color-dimmest":"#eff0f1","--color-error-background":"hsl(0, 100%, 97%)","--color-error-border":"hsl(0, 100%, 92%)","--color-error-text":"#ff0000","--color-expand-collapse-toggle":"#777d88","--color-forget-badge-background":"#2683e2","--color-forget-badge-background-inverted":"#1a6bbc","--color-forget-text":"#fff","--color-link":"#0000ff","--color-modal-background":"rgba(255, 255, 255, 0.75)","--color-bridge-version-npm-background":"#eff0f1","--color-bridge-version-npm-text":"#000000","--color-bridge-version-number":"#0088fa","--color-primitive-hook-badge-background":"#e5e5e5","--color-primitive-hook-badge-text":"#5f6673","--color-record-active":"#fc3a4b","--color-record-hover":"#3578e5","--color-record-inactive":"#0088fa","--color-resize-bar":"#eeeeee","--color-resize-bar-active":"#dcdcdc","--color-resize-bar-border":"#d1d1d1","--color-resize-bar-dot":"#333333","--color-timeline-internal-module":"#d1d1d1","--color-timeline-internal-module-hover":"#c9c9c9","--color-timeline-internal-module-text":"#444","--color-timeline-native-event":"#ccc","--color-timeline-native-event-hover":"#aaa","--color-timeline-network-primary":"#fcf3dc","--color-timeline-network-primary-hover":"#f0e7d1","--color-timeline-network-secondary":"#efc457","--color-timeline-network-secondary-hover":"#e3ba52","--color-timeline-priority-background":"#f6f6f6","--color-timeline-priority-border":"#eeeeee","--color-timeline-user-timing":"#c9cacd","--color-timeline-user-timing-hover":"#93959a","--color-timeline-react-idle":"#d3e5f6","--color-timeline-react-idle-hover":"#c3d9ef","--color-timeline-react-render":"#9fc3f3","--color-timeline-react-render-hover":"#83afe9","--color-timeline-react-render-text":"#11365e","--color-timeline-react-commit":"#c88ff0","--color-timeline-react-commit-hover":"#b281d6","--color-timeline-react-commit-text":"#3e2c4a","--color-timeline-react-layout-effects":"#b281d6","--color-timeline-react-layout-effects-hover":"#9d71bd","--color-timeline-react-layout-effects-text":"#3e2c4a","--color-timeline-react-passive-effects":"#b281d6","--color-timeline-react-passive-effects-hover":"#9d71bd","--color-timeline-react-passive-effects-text":"#3e2c4a","--color-timeline-react-schedule":"#9fc3f3","--color-timeline-react-schedule-hover":"#2683E2","--color-timeline-react-suspense-rejected":"#f1cc14","--color-timeline-react-suspense-rejected-hover":"#ffdf37","--color-timeline-react-suspense-resolved":"#a6e59f","--color-timeline-react-suspense-resolved-hover":"#89d281","--color-timeline-react-suspense-unresolved":"#c9cacd","--color-timeline-react-suspense-unresolved-hover":"#93959a","--color-timeline-thrown-error":"#ee1638","--color-timeline-thrown-error-hover":"#da1030","--color-timeline-text-color":"#000000","--color-timeline-text-dim-color":"#ccc","--color-timeline-react-work-border":"#eeeeee","--color-timebar-background":"#f6f6f6","--color-search-match":"yellow","--color-search-match-current":"#f7923b","--color-selected-tree-highlight-active":"rgba(0, 136, 250, 0.1)","--color-selected-tree-highlight-inactive":"rgba(0, 0, 0, 0.05)","--color-scroll-caret":"rgba(150, 150, 150, 0.5)","--color-tab-selected-border":"#0088fa","--color-text":"#000000","--color-text-invalid":"#ff0000","--color-text-selected":"#ffffff","--color-toggle-background-invalid":"#fc3a4b","--color-toggle-background-on":"#0088fa","--color-toggle-background-off":"#cfd1d5","--color-toggle-text":"#ffffff","--color-warning-background":"#fb3655","--color-warning-background-hover":"#f82042","--color-warning-text-color":"#ffffff","--color-warning-text-color-inverted":"#fd4d69","--color-suspense-default":"#0088fa","--color-transition-default":"#6a51b2","--color-suspense-server":"#62bc6a","--color-transition-server":"#3f7844","--color-suspense-other":"#f3ce49","--color-transition-other":"#917b2c","--color-suspense-errored":"#d57066","--color-scroll-thumb":"#c2c2c2","--color-scroll-track":"#fafafa","--color-tooltip-background":"rgba(0, 0, 0, 0.9)","--color-tooltip-text":"#ffffff","--elevation-4":"0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12)"},dark:{"--color-attribute-name":"#9d87d2","--color-attribute-name-not-editable":"#ededed","--color-attribute-name-inverted":"#282828","--color-attribute-value":"#cedae0","--color-attribute-value-inverted":"#ffffff","--color-attribute-editable-value":"yellow","--color-background":"#282c34","--color-background-hover":"rgba(255, 255, 255, 0.1)","--color-background-inactive":"#3d424a","--color-background-invalid":"#5c0000","--color-background-selected":"#178fb9","--color-button-background":"#282c34","--color-button-background-focus":"#3d424a","--color-button-background-hover":"rgba(255, 255, 255, 0.2)","--color-button":"#afb3b9","--color-button-active":"#61dafb","--color-button-disabled":"#4f5766","--color-button-focus":"#a2e9fc","--color-button-hover":"#ededed","--color-border":"#3d424a","--color-commit-did-not-render-fill":"#777d88","--color-commit-did-not-render-fill-text":"#000000","--color-commit-did-not-render-pattern":"#666c77","--color-commit-did-not-render-pattern-text":"#ffffff","--color-commit-gradient-0":"#37afa9","--color-commit-gradient-1":"#63b19e","--color-commit-gradient-2":"#80b393","--color-commit-gradient-3":"#97b488","--color-commit-gradient-4":"#abb67d","--color-commit-gradient-5":"#beb771","--color-commit-gradient-6":"#cfb965","--color-commit-gradient-7":"#dfba57","--color-commit-gradient-8":"#efbb49","--color-commit-gradient-9":"#febc38","--color-commit-gradient-text":"#000000","--color-component-name":"#61dafb","--color-component-name-inverted":"#282828","--color-component-badge-background":"#5e6167","--color-component-badge-background-inverted":"#46494e","--color-component-badge-count":"#8f949d","--color-component-badge-count-inverted":"rgba(255, 255, 255, 0.85)","--color-console-error-badge-text":"#000000","--color-console-error-background":"#290000","--color-console-error-border":"#5c0000","--color-console-error-icon":"#eb3941","--color-console-error-text":"#fc7f7f","--color-console-warning-badge-text":"#000000","--color-console-warning-background":"#332b00","--color-console-warning-border":"#665500","--color-console-warning-icon":"#f4bd00","--color-console-warning-text":"#f5f2ed","--color-context-background":"rgba(255,255,255,.95)","--color-context-background-hover":"rgba(0, 136, 250, 0.1)","--color-context-background-selected":"#0088fa","--color-context-border":"#eeeeee","--color-context-text":"#000000","--color-context-text-selected":"#ffffff","--color-dim":"#8f949d","--color-dimmer":"#777d88","--color-dimmest":"#4f5766","--color-error-background":"#200","--color-error-border":"#900","--color-error-text":"#f55","--color-expand-collapse-toggle":"#8f949d","--color-forget-badge-background":"#2683e2","--color-forget-badge-background-inverted":"#1a6bbc","--color-forget-text":"#fff","--color-link":"#61dafb","--color-modal-background":"rgba(0, 0, 0, 0.75)","--color-bridge-version-npm-background":"rgba(0, 0, 0, 0.25)","--color-bridge-version-npm-text":"#ffffff","--color-bridge-version-number":"yellow","--color-primitive-hook-badge-background":"rgba(0, 0, 0, 0.25)","--color-primitive-hook-badge-text":"rgba(255, 255, 255, 0.7)","--color-record-active":"#fc3a4b","--color-record-hover":"#a2e9fc","--color-record-inactive":"#61dafb","--color-resize-bar":"#282c34","--color-resize-bar-active":"#31363f","--color-resize-bar-border":"#3d424a","--color-resize-bar-dot":"#cfd1d5","--color-timeline-internal-module":"#303542","--color-timeline-internal-module-hover":"#363b4a","--color-timeline-internal-module-text":"#7f8899","--color-timeline-native-event":"#b2b2b2","--color-timeline-native-event-hover":"#949494","--color-timeline-network-primary":"#fcf3dc","--color-timeline-network-primary-hover":"#e3dbc5","--color-timeline-network-secondary":"#efc457","--color-timeline-network-secondary-hover":"#d6af4d","--color-timeline-priority-background":"#1d2129","--color-timeline-priority-border":"#282c34","--color-timeline-user-timing":"#c9cacd","--color-timeline-user-timing-hover":"#93959a","--color-timeline-react-idle":"#3d485b","--color-timeline-react-idle-hover":"#465269","--color-timeline-react-render":"#2683E2","--color-timeline-react-render-hover":"#1a76d4","--color-timeline-react-render-text":"#11365e","--color-timeline-react-commit":"#731fad","--color-timeline-react-commit-hover":"#611b94","--color-timeline-react-commit-text":"#e5c1ff","--color-timeline-react-layout-effects":"#611b94","--color-timeline-react-layout-effects-hover":"#51167a","--color-timeline-react-layout-effects-text":"#e5c1ff","--color-timeline-react-passive-effects":"#611b94","--color-timeline-react-passive-effects-hover":"#51167a","--color-timeline-react-passive-effects-text":"#e5c1ff","--color-timeline-react-schedule":"#2683E2","--color-timeline-react-schedule-hover":"#1a76d4","--color-timeline-react-suspense-rejected":"#f1cc14","--color-timeline-react-suspense-rejected-hover":"#e4c00f","--color-timeline-react-suspense-resolved":"#a6e59f","--color-timeline-react-suspense-resolved-hover":"#89d281","--color-timeline-react-suspense-unresolved":"#c9cacd","--color-timeline-react-suspense-unresolved-hover":"#93959a","--color-timeline-thrown-error":"#fb3655","--color-timeline-thrown-error-hover":"#f82042","--color-timeline-text-color":"#282c34","--color-timeline-text-dim-color":"#555b66","--color-timeline-react-work-border":"#3d424a","--color-timebar-background":"#1d2129","--color-search-match":"yellow","--color-search-match-current":"#f7923b","--color-selected-tree-highlight-active":"rgba(23, 143, 185, 0.15)","--color-selected-tree-highlight-inactive":"rgba(255, 255, 255, 0.05)","--color-scroll-caret":"#4f5766","--color-shadow":"rgba(0, 0, 0, 0.5)","--color-tab-selected-border":"#178fb9","--color-text":"#ffffff","--color-text-invalid":"#ff8080","--color-text-selected":"#ffffff","--color-toggle-background-invalid":"#fc3a4b","--color-toggle-background-on":"#178fb9","--color-toggle-background-off":"#777d88","--color-toggle-text":"#ffffff","--color-warning-background":"#ee1638","--color-warning-background-hover":"#da1030","--color-warning-text-color":"#ffffff","--color-warning-text-color-inverted":"#ee1638","--color-suspense-default":"#61dafb","--color-transition-default":"#6a51b2","--color-suspense-server":"#62bc6a","--color-transition-server":"#3f7844","--color-suspense-other":"#f3ce49","--color-transition-other":"#917b2c","--color-suspense-errored":"#d57066","--color-scroll-thumb":"#afb3b9","--color-scroll-track":"#313640","--color-tooltip-background":"rgba(255, 255, 255, 0.95)","--color-tooltip-text":"#000000","--elevation-4":"0 2px 8px 0 rgba(0,0,0,0.32),0 4px 12px 0 rgba(0,0,0,0.24),0 1px 10px 0 rgba(0,0,0,0.18)"},compact:{"--font-size-monospace-small":"9px","--font-size-monospace-normal":"11px","--font-size-monospace-large":"15px","--font-size-sans-small":"10px","--font-size-sans-normal":"12px","--font-size-sans-large":"14px","--line-height-data":"18px"},comfortable:{"--font-size-monospace-small":"10px","--font-size-monospace-normal":"13px","--font-size-monospace-large":"17px","--font-size-sans-small":"12px","--font-size-sans-normal":"14px","--font-size-sans-large":"16px","--line-height-data":"22px"}},COMFORTABLE_LINE_HEIGHT=parseInt(THEME_STYLES.comfortable["--line-height-data"],10),COMPACT_LINE_HEIGHT=parseInt(THEME_STYLES.compact["--line-height-data"],10),REACT_TOTAL_NUM_LANES=31,SCHEDULING_PROFILER_VERSION=1,SNAPSHOT_MAX_HEIGHT=60;function profilingHooks_slicedToArray(arr,i){return profilingHooks_arrayWithHoles(arr)||profilingHooks_iterableToArrayLimit(arr,i)||profilingHooks_unsupportedIterableToArray(arr,i)||profilingHooks_nonIterableRest()}function profilingHooks_nonIterableRest(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
165
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function profilingHooks_unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return profilingHooks_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return profilingHooks_arrayLikeToArray(o,minLen)}function profilingHooks_arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function profilingHooks_iterableToArrayLimit(r,l){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,l===0){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r2){o=!0,n=r2}finally{try{if(!f&&t.return!=null&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}function profilingHooks_arrayWithHoles(arr){if(Array.isArray(arr))return arr}function profilingHooks_typeof(o){return profilingHooks_typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},profilingHooks_typeof(o)}var TIME_OFFSET=10,performanceTarget=null,supportsUserTiming=typeof performance<"u"&&typeof performance.mark==="function"&&typeof performance.clearMarks==="function",supportsUserTimingV3=!1;if(supportsUserTiming){var CHECK_V3_MARK="__v3",markOptions={};Object.defineProperty(markOptions,"startTime",{get:function(){return supportsUserTimingV3=!0,0},set:function(){}});try{performance.mark(CHECK_V3_MARK,markOptions)}catch(error){}finally{performance.clearMarks(CHECK_V3_MARK)}}if(supportsUserTimingV3)performanceTarget=performance;var profilingHooks_getCurrentTime=(typeof performance>"u"?"undefined":profilingHooks_typeof(performance))==="object"&&typeof performance.now==="function"?function(){return performance.now()}:function(){return Date.now()};function setPerformanceMock_ONLY_FOR_TESTING(performanceMock){performanceTarget=performanceMock,supportsUserTiming=performanceMock!==null,supportsUserTimingV3=performanceMock!==null}function createProfilingHooks(_ref){var{getDisplayNameForFiber,getIsProfiling,getLaneLabelMap,workTagMap,currentDispatcherRef,reactVersion}=_ref,currentBatchUID=0,currentReactComponentMeasure=null,currentReactMeasuresStack=[],currentTimelineData=null,currentFiberStacks=new Map,isProfiling=!1,nextRenderShouldStartNewBatch=!1;function getRelativeTime(){var currentTime=profilingHooks_getCurrentTime();if(currentTimelineData){if(currentTimelineData.startTime===0)currentTimelineData.startTime=currentTime-TIME_OFFSET;return currentTime-currentTimelineData.startTime}return 0}function getInternalModuleRanges(){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.getInternalModuleRanges==="function"){var ranges=__REACT_DEVTOOLS_GLOBAL_HOOK__.getInternalModuleRanges();if(shared_isArray(ranges))return ranges}return null}function getTimelineData(){return currentTimelineData}function laneToLanesArray(lanes){var lanesArray=[],lane=1;for(var index=0;index<REACT_TOTAL_NUM_LANES;index++){if(lane&lanes)lanesArray.push(lane);lane*=2}return lanesArray}var laneToLabelMap=typeof getLaneLabelMap==="function"?getLaneLabelMap():null;function markMetadata(){markAndClear("--react-version-".concat(reactVersion)),markAndClear("--profiler-version-".concat(SCHEDULING_PROFILER_VERSION));var ranges=getInternalModuleRanges();if(ranges)for(var i=0;i<ranges.length;i++){var range=ranges[i];if(shared_isArray(range)&&range.length===2){var _ranges$i=profilingHooks_slicedToArray(ranges[i],2),startStackFrame=_ranges$i[0],stopStackFrame=_ranges$i[1];markAndClear("--react-internal-module-start-".concat(startStackFrame)),markAndClear("--react-internal-module-stop-".concat(stopStackFrame))}}if(laneToLabelMap!=null){var labels=Array.from(laneToLabelMap.values()).join(",");markAndClear("--react-lane-labels-".concat(labels))}}function markAndClear(markName){performanceTarget.mark(markName),performanceTarget.clearMarks(markName)}function recordReactMeasureStarted(type,lanes){var depth=0;if(currentReactMeasuresStack.length>0){var top=currentReactMeasuresStack[currentReactMeasuresStack.length-1];depth=top.type==="render-idle"?top.depth:top.depth+1}var lanesArray=laneToLanesArray(lanes),reactMeasure={type,batchUID:currentBatchUID,depth,lanes:lanesArray,timestamp:getRelativeTime(),duration:0};if(currentReactMeasuresStack.push(reactMeasure),currentTimelineData){var _currentTimelineData=currentTimelineData,batchUIDToMeasuresMap=_currentTimelineData.batchUIDToMeasuresMap,laneToReactMeasureMap=_currentTimelineData.laneToReactMeasureMap,reactMeasures=batchUIDToMeasuresMap.get(currentBatchUID);if(reactMeasures!=null)reactMeasures.push(reactMeasure);else batchUIDToMeasuresMap.set(currentBatchUID,[reactMeasure]);lanesArray.forEach(function(lane){if(reactMeasures=laneToReactMeasureMap.get(lane),reactMeasures)reactMeasures.push(reactMeasure)})}}function recordReactMeasureCompleted(type){var currentTime=getRelativeTime();if(currentReactMeasuresStack.length===0){console.error('Unexpected type "%s" completed at %sms while currentReactMeasuresStack is empty.',type,currentTime);return}var top=currentReactMeasuresStack.pop();if(top.type!==type)console.error('Unexpected type "%s" completed at %sms before "%s" completed.',type,currentTime,top.type);if(top.duration=currentTime-top.timestamp,currentTimelineData)currentTimelineData.duration=getRelativeTime()+TIME_OFFSET}function markCommitStarted(lanes){if(!isProfiling)return;if(recordReactMeasureStarted("commit",lanes),nextRenderShouldStartNewBatch=!0,supportsUserTimingV3)markAndClear("--commit-start-".concat(lanes)),markMetadata()}function markCommitStopped(){if(!isProfiling)return;if(recordReactMeasureCompleted("commit"),recordReactMeasureCompleted("render-idle"),supportsUserTimingV3)markAndClear("--commit-stop")}function markComponentRenderStarted(fiber){if(!isProfiling)return;var componentName=getDisplayNameForFiber(fiber)||"Unknown";if(currentReactComponentMeasure={componentName,duration:0,timestamp:getRelativeTime(),type:"render",warning:null},supportsUserTimingV3)markAndClear("--component-render-start-".concat(componentName))}function markComponentRenderStopped(){if(!isProfiling)return;if(currentReactComponentMeasure){if(currentTimelineData)currentTimelineData.componentMeasures.push(currentReactComponentMeasure);currentReactComponentMeasure.duration=getRelativeTime()-currentReactComponentMeasure.timestamp,currentReactComponentMeasure=null}if(supportsUserTimingV3)markAndClear("--component-render-stop")}function markComponentLayoutEffectMountStarted(fiber){if(!isProfiling)return;var componentName=getDisplayNameForFiber(fiber)||"Unknown";if(currentReactComponentMeasure={componentName,duration:0,timestamp:getRelativeTime(),type:"layout-effect-mount",warning:null},supportsUserTimingV3)markAndClear("--component-layout-effect-mount-start-".concat(componentName))}function markComponentLayoutEffectMountStopped(){if(!isProfiling)return;if(currentReactComponentMeasure){if(currentTimelineData)currentTimelineData.componentMeasures.push(currentReactComponentMeasure);currentReactComponentMeasure.duration=getRelativeTime()-currentReactComponentMeasure.timestamp,currentReactComponentMeasure=null}if(supportsUserTimingV3)markAndClear("--component-layout-effect-mount-stop")}function markComponentLayoutEffectUnmountStarted(fiber){if(!isProfiling)return;var componentName=getDisplayNameForFiber(fiber)||"Unknown";if(currentReactComponentMeasure={componentName,duration:0,timestamp:getRelativeTime(),type:"layout-effect-unmount",warning:null},supportsUserTimingV3)markAndClear("--component-layout-effect-unmount-start-".concat(componentName))}function markComponentLayoutEffectUnmountStopped(){if(!isProfiling)return;if(currentReactComponentMeasure){if(currentTimelineData)currentTimelineData.componentMeasures.push(currentReactComponentMeasure);currentReactComponentMeasure.duration=getRelativeTime()-currentReactComponentMeasure.timestamp,currentReactComponentMeasure=null}if(supportsUserTimingV3)markAndClear("--component-layout-effect-unmount-stop")}function markComponentPassiveEffectMountStarted(fiber){if(!isProfiling)return;var componentName=getDisplayNameForFiber(fiber)||"Unknown";if(currentReactComponentMeasure={componentName,duration:0,timestamp:getRelativeTime(),type:"passive-effect-mount",warning:null},supportsUserTimingV3)markAndClear("--component-passive-effect-mount-start-".concat(componentName))}function markComponentPassiveEffectMountStopped(){if(!isProfiling)return;if(currentReactComponentMeasure){if(currentTimelineData)currentTimelineData.componentMeasures.push(currentReactComponentMeasure);currentReactComponentMeasure.duration=getRelativeTime()-currentReactComponentMeasure.timestamp,currentReactComponentMeasure=null}if(supportsUserTimingV3)markAndClear("--component-passive-effect-mount-stop")}function markComponentPassiveEffectUnmountStarted(fiber){if(!isProfiling)return;var componentName=getDisplayNameForFiber(fiber)||"Unknown";if(currentReactComponentMeasure={componentName,duration:0,timestamp:getRelativeTime(),type:"passive-effect-unmount",warning:null},supportsUserTimingV3)markAndClear("--component-passive-effect-unmount-start-".concat(componentName))}function markComponentPassiveEffectUnmountStopped(){if(!isProfiling)return;if(currentReactComponentMeasure){if(currentTimelineData)currentTimelineData.componentMeasures.push(currentReactComponentMeasure);currentReactComponentMeasure.duration=getRelativeTime()-currentReactComponentMeasure.timestamp,currentReactComponentMeasure=null}if(supportsUserTimingV3)markAndClear("--component-passive-effect-unmount-stop")}function markComponentErrored(fiber,thrownValue,lanes){if(!isProfiling)return;var componentName=getDisplayNameForFiber(fiber)||"Unknown",phase=fiber.alternate===null?"mount":"update",message="";if(thrownValue!==null&&profilingHooks_typeof(thrownValue)==="object"&&typeof thrownValue.message==="string")message=thrownValue.message;else if(typeof thrownValue==="string")message=thrownValue;if(currentTimelineData)currentTimelineData.thrownErrors.push({componentName,message,phase,timestamp:getRelativeTime(),type:"thrown-error"});if(supportsUserTimingV3)markAndClear("--error-".concat(componentName,"-").concat(phase,"-").concat(message))}var PossiblyWeakMap2=typeof WeakMap==="function"?WeakMap:Map,wakeableIDs=new PossiblyWeakMap2,wakeableID=0;function getWakeableID(wakeable){if(!wakeableIDs.has(wakeable))wakeableIDs.set(wakeable,wakeableID++);return wakeableIDs.get(wakeable)}function markComponentSuspended(fiber,wakeable,lanes){if(!isProfiling)return;var eventType=wakeableIDs.has(wakeable)?"resuspend":"suspend",id=getWakeableID(wakeable),componentName=getDisplayNameForFiber(fiber)||"Unknown",phase=fiber.alternate===null?"mount":"update",displayName=wakeable.displayName||"",suspenseEvent=null;if(suspenseEvent={componentName,depth:0,duration:0,id:"".concat(id),phase,promiseName:displayName,resolution:"unresolved",timestamp:getRelativeTime(),type:"suspense",warning:null},currentTimelineData)currentTimelineData.suspenseEvents.push(suspenseEvent);if(supportsUserTimingV3)markAndClear("--suspense-".concat(eventType,"-").concat(id,"-").concat(componentName,"-").concat(phase,"-").concat(lanes,"-").concat(displayName)),wakeable.then(function(){if(suspenseEvent)suspenseEvent.duration=getRelativeTime()-suspenseEvent.timestamp,suspenseEvent.resolution="resolved";if(supportsUserTimingV3)markAndClear("--suspense-resolved-".concat(id,"-").concat(componentName))},function(){if(suspenseEvent)suspenseEvent.duration=getRelativeTime()-suspenseEvent.timestamp,suspenseEvent.resolution="rejected";if(supportsUserTimingV3)markAndClear("--suspense-rejected-".concat(id,"-").concat(componentName))})}function markLayoutEffectsStarted(lanes){if(!isProfiling)return;if(recordReactMeasureStarted("layout-effects",lanes),supportsUserTimingV3)markAndClear("--layout-effects-start-".concat(lanes))}function markLayoutEffectsStopped(){if(!isProfiling)return;if(recordReactMeasureCompleted("layout-effects"),supportsUserTimingV3)markAndClear("--layout-effects-stop")}function markPassiveEffectsStarted(lanes){if(!isProfiling)return;if(recordReactMeasureStarted("passive-effects",lanes),supportsUserTimingV3)markAndClear("--passive-effects-start-".concat(lanes))}function markPassiveEffectsStopped(){if(!isProfiling)return;if(recordReactMeasureCompleted("passive-effects"),supportsUserTimingV3)markAndClear("--passive-effects-stop")}function markRenderStarted(lanes){if(!isProfiling)return;if(nextRenderShouldStartNewBatch)nextRenderShouldStartNewBatch=!1,currentBatchUID++;if(currentReactMeasuresStack.length===0||currentReactMeasuresStack[currentReactMeasuresStack.length-1].type!=="render-idle")recordReactMeasureStarted("render-idle",lanes);if(recordReactMeasureStarted("render",lanes),supportsUserTimingV3)markAndClear("--render-start-".concat(lanes))}function markRenderYielded(){if(!isProfiling)return;if(recordReactMeasureCompleted("render"),supportsUserTimingV3)markAndClear("--render-yield")}function markRenderStopped(){if(!isProfiling)return;if(recordReactMeasureCompleted("render"),supportsUserTimingV3)markAndClear("--render-stop")}function markRenderScheduled(lane){if(!isProfiling)return;if(currentTimelineData)currentTimelineData.schedulingEvents.push({lanes:laneToLanesArray(lane),timestamp:getRelativeTime(),type:"schedule-render",warning:null});if(supportsUserTimingV3)markAndClear("--schedule-render-".concat(lane))}function markForceUpdateScheduled(fiber,lane){if(!isProfiling)return;var componentName=getDisplayNameForFiber(fiber)||"Unknown";if(currentTimelineData)currentTimelineData.schedulingEvents.push({componentName,lanes:laneToLanesArray(lane),timestamp:getRelativeTime(),type:"schedule-force-update",warning:null});if(supportsUserTimingV3)markAndClear("--schedule-forced-update-".concat(lane,"-").concat(componentName))}function getParentFibers(fiber){var parents=[],parent=fiber;while(parent!==null)parents.push(parent),parent=parent.return;return parents}function markStateUpdateScheduled(fiber,lane){if(!isProfiling)return;var componentName=getDisplayNameForFiber(fiber)||"Unknown";if(currentTimelineData){var event={componentName,lanes:laneToLanesArray(lane),timestamp:getRelativeTime(),type:"schedule-state-update",warning:null};currentFiberStacks.set(event,getParentFibers(fiber)),currentTimelineData.schedulingEvents.push(event)}if(supportsUserTimingV3)markAndClear("--schedule-state-update-".concat(lane,"-").concat(componentName))}function toggleProfilingStatus(value){var recordTimeline=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(isProfiling!==value)if(isProfiling=value,isProfiling){var internalModuleSourceToRanges=new Map;if(supportsUserTimingV3){var ranges=getInternalModuleRanges();if(ranges)for(var i=0;i<ranges.length;i++){var range=ranges[i];if(shared_isArray(range)&&range.length===2){var _ranges$i2=profilingHooks_slicedToArray(ranges[i],2),startStackFrame=_ranges$i2[0],stopStackFrame=_ranges$i2[1];markAndClear("--react-internal-module-start-".concat(startStackFrame)),markAndClear("--react-internal-module-stop-".concat(stopStackFrame))}}}var laneToReactMeasureMap=new Map,lane=1;for(var index=0;index<REACT_TOTAL_NUM_LANES;index++)laneToReactMeasureMap.set(lane,[]),lane*=2;if(currentBatchUID=0,currentReactComponentMeasure=null,currentReactMeasuresStack=[],currentFiberStacks=new Map,recordTimeline)currentTimelineData={internalModuleSourceToRanges,laneToLabelMap:laneToLabelMap||new Map,reactVersion,componentMeasures:[],schedulingEvents:[],suspenseEvents:[],thrownErrors:[],batchUIDToMeasuresMap:new Map,duration:0,laneToReactMeasureMap,startTime:0,flamechart:[],nativeEvents:[],networkMeasures:[],otherUserTimingMarks:[],snapshots:[],snapshotHeight:0};nextRenderShouldStartNewBatch=!0}else{if(currentTimelineData!==null)currentTimelineData.schedulingEvents.forEach(function(event){if(event.type==="schedule-state-update"){var fiberStack=currentFiberStacks.get(event);if(fiberStack&&currentDispatcherRef!=null)event.componentStack=fiberStack.reduce(function(trace,fiber){return trace+describeFiber(workTagMap,fiber,currentDispatcherRef)},"")}});currentFiberStacks.clear()}}return{getTimelineData,profilingHooks:{markCommitStarted,markCommitStopped,markComponentRenderStarted,markComponentRenderStopped,markComponentPassiveEffectMountStarted,markComponentPassiveEffectMountStopped,markComponentPassiveEffectUnmountStarted,markComponentPassiveEffectUnmountStopped,markComponentLayoutEffectMountStarted,markComponentLayoutEffectMountStopped,markComponentLayoutEffectUnmountStarted,markComponentLayoutEffectUnmountStopped,markComponentErrored,markComponentSuspended,markLayoutEffectsStarted,markLayoutEffectsStopped,markPassiveEffectsStarted,markPassiveEffectsStopped,markRenderStarted,markRenderYielded,markRenderStopped,markRenderScheduled,markForceUpdateScheduled,markStateUpdateScheduled},toggleProfilingStatus}}var _excluded=["batchUIDToMeasuresMap","internalModuleSourceToRanges","laneToLabelMap","laneToReactMeasureMap"];function _objectWithoutProperties(source,excluded){if(source==null)return{};var target=_objectWithoutPropertiesLoose(source,excluded),key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++){if(key=sourceSymbolKeys[i],excluded.indexOf(key)>=0)continue;if(!Object.prototype.propertyIsEnumerable.call(source,key))continue;target[key]=source[key]}}return target}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return{};var target={};for(var key in source)if(Object.prototype.hasOwnProperty.call(source,key)){if(excluded.indexOf(key)>=0)continue;target[key]=source[key]}return target}function renderer_ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r2){return Object.getOwnPropertyDescriptor(e,r2).enumerable})),t.push.apply(t,o)}return t}function renderer_objectSpread(e){for(var r=1;r<arguments.length;r++){var t=arguments[r]!=null?arguments[r]:{};r%2?renderer_ownKeys(Object(t),!0).forEach(function(r2){renderer_defineProperty(e,r2,t[r2])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):renderer_ownKeys(Object(t)).forEach(function(r2){Object.defineProperty(e,r2,Object.getOwnPropertyDescriptor(t,r2))})}return e}function renderer_defineProperty(obj,key,value){if(key=renderer_toPropertyKey(key),key in obj)Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0});else obj[key]=value;return obj}function renderer_toPropertyKey(t){var i=renderer_toPrimitive(t,"string");return renderer_typeof(i)=="symbol"?i:i+""}function renderer_toPrimitive(t,r){if(renderer_typeof(t)!="object"||!t)return t;var e=t[Symbol.toPrimitive];if(e!==void 0){var i=e.call(t,r||"default");if(renderer_typeof(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(t)}function fiber_renderer_toConsumableArray(arr){return fiber_renderer_arrayWithoutHoles(arr)||fiber_renderer_iterableToArray(arr)||fiber_renderer_unsupportedIterableToArray(arr)||fiber_renderer_nonIterableSpread()}function fiber_renderer_nonIterableSpread(){throw TypeError(`Invalid attempt to spread non-iterable instance.
166
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function fiber_renderer_iterableToArray(iter){if(typeof Symbol<"u"&&iter[Symbol.iterator]!=null||iter["@@iterator"]!=null)return Array.from(iter)}function fiber_renderer_arrayWithoutHoles(arr){if(Array.isArray(arr))return fiber_renderer_arrayLikeToArray(arr)}function _createForOfIteratorHelper(o,allowArrayLike){var it=typeof Symbol<"u"&&o[Symbol.iterator]||o["@@iterator"];if(!it){if(Array.isArray(o)||(it=fiber_renderer_unsupportedIterableToArray(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it)o=it;var i=0,F=function(){};return{s:F,n:function(){if(i>=o.length)return{done:!0};return{done:!1,value:o[i++]}},e:function(_e){throw _e},f:F}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
167
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var normalCompletion=!0,didErr=!1,err;return{s:function(){it=it.call(o)},n:function(){var step=it.next();return normalCompletion=step.done,step},e:function(_e2){didErr=!0,err=_e2},f:function(){try{if(!normalCompletion&&it.return!=null)it.return()}finally{if(didErr)throw err}}}}function fiber_renderer_unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return fiber_renderer_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return fiber_renderer_arrayLikeToArray(o,minLen)}function fiber_renderer_arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function renderer_typeof(o){return renderer_typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},renderer_typeof(o)}var renderer_toString=Object.prototype.toString;function renderer_isError(object){return renderer_toString.call(object)==="[object Error]"}var FIBER_INSTANCE=0,VIRTUAL_INSTANCE=1,FILTERED_FIBER_INSTANCE=2;function createFiberInstance(fiber){return{kind:FIBER_INSTANCE,id:getUID(),parent:null,firstChild:null,nextSibling:null,source:null,logCount:0,treeBaseDuration:0,suspendedBy:null,suspenseNode:null,data:fiber}}function createFilteredFiberInstance(fiber){return{kind:FILTERED_FIBER_INSTANCE,id:0,parent:null,firstChild:null,nextSibling:null,source:null,logCount:0,treeBaseDuration:0,suspendedBy:null,suspenseNode:null,data:fiber}}function createVirtualInstance(debugEntry){return{kind:VIRTUAL_INSTANCE,id:getUID(),parent:null,firstChild:null,nextSibling:null,source:null,logCount:0,treeBaseDuration:0,suspendedBy:null,suspenseNode:null,data:debugEntry}}var NoUpdate=0,ShouldResetChildren=1,ShouldResetSuspenseChildren=2,ShouldResetParentSuspenseChildren=4;function createSuspenseNode(instance){return instance.suspenseNode={instance,parent:null,firstChild:null,nextSibling:null,rects:null,suspendedBy:new Map,environments:new Map,hasUniqueSuspenders:!1,hasUnknownSuspenders:!1}}function getDispatcherRef(renderer){if(renderer.currentDispatcherRef===void 0)return;var injectedRef=renderer.currentDispatcherRef;if(typeof injectedRef.H>"u"&&typeof injectedRef.current<"u")return{get H(){return injectedRef.current},set H(value){injectedRef.current=value}};return injectedRef}function getFiberFlags(fiber){return fiber.flags!==void 0?fiber.flags:fiber.effectTag}var renderer_getCurrentTime=(typeof performance>"u"?"undefined":renderer_typeof(performance))==="object"&&typeof performance.now==="function"?function(){return performance.now()}:function(){return Date.now()};function getInternalReactConstants(version){var ReactPriorityLevels={ImmediatePriority:99,UserBlockingPriority:98,NormalPriority:97,LowPriority:96,IdlePriority:95,NoPriority:90};if(gt(version,"17.0.2"))ReactPriorityLevels={ImmediatePriority:1,UserBlockingPriority:2,NormalPriority:3,LowPriority:4,IdlePriority:5,NoPriority:0};var StrictModeBits=0;if(gte(version,"18.0.0-alpha"))StrictModeBits=24;else if(gte(version,"16.9.0"))StrictModeBits=1;else if(gte(version,"16.3.0"))StrictModeBits=2;var SuspenseyImagesMode=32,ReactTypeOfWork=null;if(gt(version,"17.0.1"))ReactTypeOfWork={CacheComponent:24,ClassComponent:1,ContextConsumer:9,ContextProvider:10,CoroutineComponent:-1,CoroutineHandlerPhase:-1,DehydratedSuspenseComponent:18,ForwardRef:11,Fragment:7,FunctionComponent:0,HostComponent:5,HostPortal:4,HostRoot:3,HostHoistable:26,HostSingleton:27,HostText:6,IncompleteClassComponent:17,IncompleteFunctionComponent:28,IndeterminateComponent:2,LazyComponent:16,LegacyHiddenComponent:23,MemoComponent:14,Mode:8,OffscreenComponent:22,Profiler:12,ScopeComponent:21,SimpleMemoComponent:15,SuspenseComponent:13,SuspenseListComponent:19,TracingMarkerComponent:25,YieldComponent:-1,Throw:29,ViewTransitionComponent:30,ActivityComponent:31};else if(gte(version,"17.0.0-alpha"))ReactTypeOfWork={CacheComponent:-1,ClassComponent:1,ContextConsumer:9,ContextProvider:10,CoroutineComponent:-1,CoroutineHandlerPhase:-1,DehydratedSuspenseComponent:18,ForwardRef:11,Fragment:7,FunctionComponent:0,HostComponent:5,HostPortal:4,HostRoot:3,HostHoistable:-1,HostSingleton:-1,HostText:6,IncompleteClassComponent:17,IncompleteFunctionComponent:-1,IndeterminateComponent:2,LazyComponent:16,LegacyHiddenComponent:24,MemoComponent:14,Mode:8,OffscreenComponent:23,Profiler:12,ScopeComponent:21,SimpleMemoComponent:15,SuspenseComponent:13,SuspenseListComponent:19,TracingMarkerComponent:-1,YieldComponent:-1,Throw:-1,ViewTransitionComponent:-1,ActivityComponent:-1};else if(gte(version,"16.6.0-beta.0"))ReactTypeOfWork={CacheComponent:-1,ClassComponent:1,ContextConsumer:9,ContextProvider:10,CoroutineComponent:-1,CoroutineHandlerPhase:-1,DehydratedSuspenseComponent:18,ForwardRef:11,Fragment:7,FunctionComponent:0,HostComponent:5,HostPortal:4,HostRoot:3,HostHoistable:-1,HostSingleton:-1,HostText:6,IncompleteClassComponent:17,IncompleteFunctionComponent:-1,IndeterminateComponent:2,LazyComponent:16,LegacyHiddenComponent:-1,MemoComponent:14,Mode:8,OffscreenComponent:-1,Profiler:12,ScopeComponent:-1,SimpleMemoComponent:15,SuspenseComponent:13,SuspenseListComponent:19,TracingMarkerComponent:-1,YieldComponent:-1,Throw:-1,ViewTransitionComponent:-1,ActivityComponent:-1};else if(gte(version,"16.4.3-alpha"))ReactTypeOfWork={CacheComponent:-1,ClassComponent:2,ContextConsumer:11,ContextProvider:12,CoroutineComponent:-1,CoroutineHandlerPhase:-1,DehydratedSuspenseComponent:-1,ForwardRef:13,Fragment:9,FunctionComponent:0,HostComponent:7,HostPortal:6,HostRoot:5,HostHoistable:-1,HostSingleton:-1,HostText:8,IncompleteClassComponent:-1,IncompleteFunctionComponent:-1,IndeterminateComponent:4,LazyComponent:-1,LegacyHiddenComponent:-1,MemoComponent:-1,Mode:10,OffscreenComponent:-1,Profiler:15,ScopeComponent:-1,SimpleMemoComponent:-1,SuspenseComponent:16,SuspenseListComponent:-1,TracingMarkerComponent:-1,YieldComponent:-1,Throw:-1,ViewTransitionComponent:-1,ActivityComponent:-1};else ReactTypeOfWork={CacheComponent:-1,ClassComponent:2,ContextConsumer:12,ContextProvider:13,CoroutineComponent:7,CoroutineHandlerPhase:8,DehydratedSuspenseComponent:-1,ForwardRef:14,Fragment:10,FunctionComponent:1,HostComponent:5,HostPortal:4,HostRoot:3,HostHoistable:-1,HostSingleton:-1,HostText:6,IncompleteClassComponent:-1,IncompleteFunctionComponent:-1,IndeterminateComponent:0,LazyComponent:-1,LegacyHiddenComponent:-1,MemoComponent:-1,Mode:11,OffscreenComponent:-1,Profiler:15,ScopeComponent:-1,SimpleMemoComponent:-1,SuspenseComponent:16,SuspenseListComponent:-1,TracingMarkerComponent:-1,YieldComponent:9,Throw:-1,ViewTransitionComponent:-1,ActivityComponent:-1};function getTypeSymbol(type){var symbolOrNumber=renderer_typeof(type)==="object"&&type!==null?type.$$typeof:type;return renderer_typeof(symbolOrNumber)==="symbol"?symbolOrNumber.toString():symbolOrNumber}var _ReactTypeOfWork=ReactTypeOfWork,CacheComponent=_ReactTypeOfWork.CacheComponent,ClassComponent=_ReactTypeOfWork.ClassComponent,IncompleteClassComponent=_ReactTypeOfWork.IncompleteClassComponent,IncompleteFunctionComponent=_ReactTypeOfWork.IncompleteFunctionComponent,FunctionComponent=_ReactTypeOfWork.FunctionComponent,IndeterminateComponent=_ReactTypeOfWork.IndeterminateComponent,ForwardRef=_ReactTypeOfWork.ForwardRef,HostRoot=_ReactTypeOfWork.HostRoot,HostHoistable=_ReactTypeOfWork.HostHoistable,HostSingleton=_ReactTypeOfWork.HostSingleton,HostComponent=_ReactTypeOfWork.HostComponent,HostPortal=_ReactTypeOfWork.HostPortal,HostText=_ReactTypeOfWork.HostText,Fragment5=_ReactTypeOfWork.Fragment,LazyComponent=_ReactTypeOfWork.LazyComponent,LegacyHiddenComponent=_ReactTypeOfWork.LegacyHiddenComponent,MemoComponent=_ReactTypeOfWork.MemoComponent,OffscreenComponent=_ReactTypeOfWork.OffscreenComponent,Profiler=_ReactTypeOfWork.Profiler,ScopeComponent=_ReactTypeOfWork.ScopeComponent,SimpleMemoComponent=_ReactTypeOfWork.SimpleMemoComponent,SuspenseComponent=_ReactTypeOfWork.SuspenseComponent,SuspenseListComponent=_ReactTypeOfWork.SuspenseListComponent,TracingMarkerComponent=_ReactTypeOfWork.TracingMarkerComponent,Throw=_ReactTypeOfWork.Throw,ViewTransitionComponent=_ReactTypeOfWork.ViewTransitionComponent,ActivityComponent=_ReactTypeOfWork.ActivityComponent;function resolveFiberType(type){var typeSymbol=getTypeSymbol(type);switch(typeSymbol){case MEMO_NUMBER:case MEMO_SYMBOL_STRING:return resolveFiberType(type.type);case FORWARD_REF_NUMBER:case FORWARD_REF_SYMBOL_STRING:return type.render;default:return type}}function getDisplayNameForFiber(fiber){var _fiber$updateQueue,_fiber$memoizedState,_fiber$memoizedState$,_fiber$memoizedState2,shouldSkipForgetCheck=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,elementType=fiber.elementType,type=fiber.type,tag=fiber.tag,resolvedType=type;if(renderer_typeof(type)==="object"&&type!==null)resolvedType=resolveFiberType(type);var resolvedContext=null;if(!shouldSkipForgetCheck&&(((_fiber$updateQueue=fiber.updateQueue)===null||_fiber$updateQueue===void 0?void 0:_fiber$updateQueue.memoCache)!=null||Array.isArray((_fiber$memoizedState=fiber.memoizedState)===null||_fiber$memoizedState===void 0?void 0:_fiber$memoizedState.memoizedState)&&(_fiber$memoizedState$=fiber.memoizedState.memoizedState[0])!==null&&_fiber$memoizedState$!==void 0&&_fiber$memoizedState$[ReactSymbols_REACT_MEMO_CACHE_SENTINEL]||(_fiber$memoizedState2=fiber.memoizedState)!==null&&_fiber$memoizedState2!==void 0&&(_fiber$memoizedState2=_fiber$memoizedState2.memoizedState)!==null&&_fiber$memoizedState2!==void 0&&_fiber$memoizedState2[ReactSymbols_REACT_MEMO_CACHE_SENTINEL])){var displayNameWithoutForgetWrapper=getDisplayNameForFiber(fiber,!0);if(displayNameWithoutForgetWrapper==null)return null;return"Forget(".concat(displayNameWithoutForgetWrapper,")")}switch(tag){case ActivityComponent:return"Activity";case CacheComponent:return"Cache";case ClassComponent:case IncompleteClassComponent:case IncompleteFunctionComponent:case FunctionComponent:case IndeterminateComponent:return getDisplayName(resolvedType);case ForwardRef:return getWrappedDisplayName(elementType,resolvedType,"ForwardRef","Anonymous");case HostRoot:var fiberRoot=fiber.stateNode;if(fiberRoot!=null&&fiberRoot._debugRootType!==null)return fiberRoot._debugRootType;return null;case HostComponent:case HostSingleton:case HostHoistable:return type;case HostPortal:case HostText:return null;case Fragment5:return"Fragment";case LazyComponent:return"Lazy";case MemoComponent:case SimpleMemoComponent:return getWrappedDisplayName(elementType,resolvedType,"Memo","Anonymous");case SuspenseComponent:return"Suspense";case LegacyHiddenComponent:return"LegacyHidden";case OffscreenComponent:return"Offscreen";case ScopeComponent:return"Scope";case SuspenseListComponent:return"SuspenseList";case Profiler:return"Profiler";case TracingMarkerComponent:return"TracingMarker";case ViewTransitionComponent:return"ViewTransition";case Throw:return"Error";default:var typeSymbol=getTypeSymbol(type);switch(typeSymbol){case CONCURRENT_MODE_NUMBER:case CONCURRENT_MODE_SYMBOL_STRING:case DEPRECATED_ASYNC_MODE_SYMBOL_STRING:return null;case PROVIDER_NUMBER:case PROVIDER_SYMBOL_STRING:return resolvedContext=fiber.type._context||fiber.type.context,"".concat(resolvedContext.displayName||"Context",".Provider");case CONTEXT_NUMBER:case CONTEXT_SYMBOL_STRING:case SERVER_CONTEXT_SYMBOL_STRING:if(fiber.type._context===void 0&&fiber.type.Provider===fiber.type)return resolvedContext=fiber.type,"".concat(resolvedContext.displayName||"Context",".Provider");return resolvedContext=fiber.type._context||fiber.type,"".concat(resolvedContext.displayName||"Context",".Consumer");case CONSUMER_SYMBOL_STRING:return resolvedContext=fiber.type._context,"".concat(resolvedContext.displayName||"Context",".Consumer");case STRICT_MODE_NUMBER:case STRICT_MODE_SYMBOL_STRING:return null;case PROFILER_NUMBER:case PROFILER_SYMBOL_STRING:return"Profiler(".concat(fiber.memoizedProps.id,")");case SCOPE_NUMBER:case SCOPE_SYMBOL_STRING:return"Scope";default:return null}}}return{getDisplayNameForFiber,getTypeSymbol,ReactPriorityLevels,ReactTypeOfWork,StrictModeBits,SuspenseyImagesMode}}var knownEnvironmentNames=new Set,rootToFiberInstanceMap=new Map,idToDevToolsInstanceMap=new Map,idToSuspenseNodeMap=new Map,publicInstanceToDevToolsInstanceMap=new Map,hostResourceToDevToolsInstanceMap=new Map;function getPublicInstance(instance){if(renderer_typeof(instance)==="object"&&instance!==null){if(renderer_typeof(instance.canonical)==="object"&&instance.canonical!==null){if(renderer_typeof(instance.canonical.publicInstance)==="object"&&instance.canonical.publicInstance!==null)return instance.canonical.publicInstance}if(typeof instance._nativeTag==="number")return instance._nativeTag}return instance}function getNativeTag(instance){if(renderer_typeof(instance)!=="object"||instance===null)return null;if(instance.canonical!=null&&typeof instance.canonical.nativeTag==="number")return instance.canonical.nativeTag;if(typeof instance._nativeTag==="number")return instance._nativeTag;return null}function aquireHostInstance(nearestInstance,hostInstance){var publicInstance=getPublicInstance(hostInstance);publicInstanceToDevToolsInstanceMap.set(publicInstance,nearestInstance)}function releaseHostInstance(nearestInstance,hostInstance){var publicInstance=getPublicInstance(hostInstance);if(publicInstanceToDevToolsInstanceMap.get(publicInstance)===nearestInstance)publicInstanceToDevToolsInstanceMap.delete(publicInstance)}function aquireHostResource(nearestInstance,resource){var hostInstance=resource&&resource.instance;if(hostInstance){var publicInstance=getPublicInstance(hostInstance),resourceInstances=hostResourceToDevToolsInstanceMap.get(publicInstance);if(resourceInstances===void 0)resourceInstances=new Set,hostResourceToDevToolsInstanceMap.set(publicInstance,resourceInstances),publicInstanceToDevToolsInstanceMap.set(publicInstance,nearestInstance);resourceInstances.add(nearestInstance)}}function releaseHostResource(nearestInstance,resource){var hostInstance=resource&&resource.instance;if(hostInstance){var publicInstance=getPublicInstance(hostInstance),resourceInstances=hostResourceToDevToolsInstanceMap.get(publicInstance);if(resourceInstances!==void 0){if(resourceInstances.delete(nearestInstance),resourceInstances.size===0)hostResourceToDevToolsInstanceMap.delete(publicInstance),publicInstanceToDevToolsInstanceMap.delete(publicInstance);else if(publicInstanceToDevToolsInstanceMap.get(publicInstance)===nearestInstance){var _iterator=_createForOfIteratorHelper(resourceInstances),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var firstInstance=_step.value;publicInstanceToDevToolsInstanceMap.set(firstInstance,nearestInstance);break}}catch(err){_iterator.e(err)}finally{_iterator.f()}}}}}function renderer_attach(hook,rendererID,renderer,global,shouldStartProfilingNow,profilingSettings){var version=renderer.reconcilerVersion||renderer.version,_getInternalReactCons=getInternalReactConstants(version),getDisplayNameForFiber=_getInternalReactCons.getDisplayNameForFiber,getTypeSymbol=_getInternalReactCons.getTypeSymbol,ReactPriorityLevels=_getInternalReactCons.ReactPriorityLevels,ReactTypeOfWork=_getInternalReactCons.ReactTypeOfWork,StrictModeBits=_getInternalReactCons.StrictModeBits,SuspenseyImagesMode=_getInternalReactCons.SuspenseyImagesMode,ActivityComponent=ReactTypeOfWork.ActivityComponent,ClassComponent=ReactTypeOfWork.ClassComponent,ContextConsumer=ReactTypeOfWork.ContextConsumer,DehydratedSuspenseComponent=ReactTypeOfWork.DehydratedSuspenseComponent,ForwardRef=ReactTypeOfWork.ForwardRef,Fragment5=ReactTypeOfWork.Fragment,FunctionComponent=ReactTypeOfWork.FunctionComponent,HostRoot=ReactTypeOfWork.HostRoot,HostHoistable=ReactTypeOfWork.HostHoistable,HostSingleton=ReactTypeOfWork.HostSingleton,HostPortal=ReactTypeOfWork.HostPortal,HostComponent=ReactTypeOfWork.HostComponent,HostText=ReactTypeOfWork.HostText,IncompleteClassComponent=ReactTypeOfWork.IncompleteClassComponent,IncompleteFunctionComponent=ReactTypeOfWork.IncompleteFunctionComponent,IndeterminateComponent=ReactTypeOfWork.IndeterminateComponent,LegacyHiddenComponent=ReactTypeOfWork.LegacyHiddenComponent,MemoComponent=ReactTypeOfWork.MemoComponent,OffscreenComponent=ReactTypeOfWork.OffscreenComponent,SimpleMemoComponent=ReactTypeOfWork.SimpleMemoComponent,SuspenseComponent=ReactTypeOfWork.SuspenseComponent,SuspenseListComponent=ReactTypeOfWork.SuspenseListComponent,TracingMarkerComponent=ReactTypeOfWork.TracingMarkerComponent,Throw=ReactTypeOfWork.Throw,ViewTransitionComponent=ReactTypeOfWork.ViewTransitionComponent,ImmediatePriority=ReactPriorityLevels.ImmediatePriority,UserBlockingPriority=ReactPriorityLevels.UserBlockingPriority,NormalPriority=ReactPriorityLevels.NormalPriority,LowPriority=ReactPriorityLevels.LowPriority,IdlePriority=ReactPriorityLevels.IdlePriority,NoPriority=ReactPriorityLevels.NoPriority,getLaneLabelMap=renderer.getLaneLabelMap,injectProfilingHooks=renderer.injectProfilingHooks,overrideHookState=renderer.overrideHookState,overrideHookStateDeletePath=renderer.overrideHookStateDeletePath,overrideHookStateRenamePath=renderer.overrideHookStateRenamePath,overrideProps=renderer.overrideProps,overridePropsDeletePath=renderer.overridePropsDeletePath,overridePropsRenamePath=renderer.overridePropsRenamePath,scheduleRefresh=renderer.scheduleRefresh,setErrorHandler=renderer.setErrorHandler,setSuspenseHandler=renderer.setSuspenseHandler,scheduleUpdate=renderer.scheduleUpdate,scheduleRetry=renderer.scheduleRetry,getCurrentFiber=renderer.getCurrentFiber,supportsTogglingError=typeof setErrorHandler==="function"&&typeof scheduleUpdate==="function",supportsTogglingSuspense=typeof setSuspenseHandler==="function"&&typeof scheduleUpdate==="function",supportsPerformanceTracks=gte(version,"19.2.0");if(typeof scheduleRefresh==="function")renderer.scheduleRefresh=function(){try{hook.emit("fastRefreshScheduled")}finally{return scheduleRefresh.apply(void 0,arguments)}};var getTimelineData=null,toggleProfilingStatus=null;if(typeof injectProfilingHooks==="function"){var response=createProfilingHooks({getDisplayNameForFiber,getIsProfiling:function(){return isProfiling},getLaneLabelMap,currentDispatcherRef:getDispatcherRef(renderer),workTagMap:ReactTypeOfWork,reactVersion:version});injectProfilingHooks(response.profilingHooks),getTimelineData=response.getTimelineData,toggleProfilingStatus=response.toggleProfilingStatus}var fiberToComponentLogsMap=new WeakMap,needsToFlushComponentLogs=!1;function bruteForceFlushErrorsAndWarnings(){var hasChanges=!1,_iterator2=_createForOfIteratorHelper(idToDevToolsInstanceMap.values()),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var devtoolsInstance=_step2.value;if(devtoolsInstance.kind===FIBER_INSTANCE){var _fiber=devtoolsInstance.data,componentLogsEntry=fiberToComponentLogsMap.get(_fiber),changed=recordConsoleLogs(devtoolsInstance,componentLogsEntry);if(changed)hasChanges=!0,updateMostRecentlyInspectedElementIfNecessary(devtoolsInstance.id)}}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}if(hasChanges)flushPendingEvents()}function clearErrorsAndWarnings(){var _iterator3=_createForOfIteratorHelper(idToDevToolsInstanceMap.values()),_step3;try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){var devtoolsInstance=_step3.value;if(devtoolsInstance.kind===FIBER_INSTANCE){var _fiber2=devtoolsInstance.data;if(fiberToComponentLogsMap.delete(_fiber2),_fiber2.alternate)fiberToComponentLogsMap.delete(_fiber2.alternate)}else componentInfoToComponentLogsMap.delete(devtoolsInstance.data);var changed=recordConsoleLogs(devtoolsInstance,void 0);if(changed)updateMostRecentlyInspectedElementIfNecessary(devtoolsInstance.id)}}catch(err){_iterator3.e(err)}finally{_iterator3.f()}flushPendingEvents()}function clearConsoleLogsHelper(instanceID,type){var devtoolsInstance=idToDevToolsInstanceMap.get(instanceID);if(devtoolsInstance!==void 0){var componentLogsEntry;if(devtoolsInstance.kind===FIBER_INSTANCE){var _fiber3=devtoolsInstance.data;if(componentLogsEntry=fiberToComponentLogsMap.get(_fiber3),componentLogsEntry===void 0&&_fiber3.alternate!==null)componentLogsEntry=fiberToComponentLogsMap.get(_fiber3.alternate)}else{var componentInfo=devtoolsInstance.data;componentLogsEntry=componentInfoToComponentLogsMap.get(componentInfo)}if(componentLogsEntry!==void 0){if(type==="error")componentLogsEntry.errors.clear(),componentLogsEntry.errorsCount=0;else componentLogsEntry.warnings.clear(),componentLogsEntry.warningsCount=0;var changed=recordConsoleLogs(devtoolsInstance,componentLogsEntry);if(changed)flushPendingEvents(),updateMostRecentlyInspectedElementIfNecessary(devtoolsInstance.id)}}}function clearErrorsForElementID(instanceID){clearConsoleLogsHelper(instanceID,"error")}function clearWarningsForElementID(instanceID){clearConsoleLogsHelper(instanceID,"warn")}function updateMostRecentlyInspectedElementIfNecessary(fiberID){if(mostRecentlyInspectedElement!==null&&mostRecentlyInspectedElement.id===fiberID)hasElementUpdatedSinceLastInspected=!0}function getComponentStack(topFrame){if(getCurrentFiber==null)return null;var current=getCurrentFiber();if(current===null)return null;if(DevToolsFiberComponentStack_supportsConsoleTasks(current))return null;var dispatcherRef=getDispatcherRef(renderer);if(dispatcherRef===void 0)return null;var enableOwnerStacks=supportsOwnerStacks(current),componentStack="";if(enableOwnerStacks){var topStackFrames=formatOwnerStack(topFrame);if(topStackFrames)componentStack+=`
168
+ `+topStackFrames;componentStack+=getOwnerStackByFiberInDev(ReactTypeOfWork,current,dispatcherRef)}else componentStack=getStackByFiberInDevAndProd(ReactTypeOfWork,current,dispatcherRef);return{enableOwnerStacks,componentStack}}function onErrorOrWarning(type,args){if(getCurrentFiber==null)return;var fiber=getCurrentFiber();if(fiber===null)return;if(type==="error"){if(forceErrorForFibers.get(fiber)===!0||fiber.alternate!==null&&forceErrorForFibers.get(fiber.alternate)===!0)return}var message=formatConsoleArgumentsToSingleString.apply(void 0,fiber_renderer_toConsumableArray(args)),componentLogsEntry=fiberToComponentLogsMap.get(fiber);if(componentLogsEntry===void 0&&fiber.alternate!==null){if(componentLogsEntry=fiberToComponentLogsMap.get(fiber.alternate),componentLogsEntry!==void 0)fiberToComponentLogsMap.set(fiber,componentLogsEntry)}if(componentLogsEntry===void 0)componentLogsEntry={errors:new Map,errorsCount:0,warnings:new Map,warningsCount:0},fiberToComponentLogsMap.set(fiber,componentLogsEntry);var messageMap=type==="error"?componentLogsEntry.errors:componentLogsEntry.warnings,count=messageMap.get(message)||0;if(messageMap.set(message,count+1),type==="error")componentLogsEntry.errorsCount++;else componentLogsEntry.warningsCount++;needsToFlushComponentLogs=!0}function debug2(name,instance,parentInstance){var extraString=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"";if(__DEBUG__){var displayName=instance.kind===VIRTUAL_INSTANCE?instance.data.name||"null":instance.data.tag+":"+(getDisplayNameForFiber(instance.data)||"null"),maybeID=instance.kind===FILTERED_FIBER_INSTANCE?"<no id>":instance.id,parentDisplayName=parentInstance===null?"":parentInstance.kind===VIRTUAL_INSTANCE?parentInstance.data.name||"null":parentInstance.data.tag+":"+(getDisplayNameForFiber(parentInstance.data)||"null"),maybeParentID=parentInstance===null||parentInstance.kind===FILTERED_FIBER_INSTANCE?"<no id>":parentInstance.id;console.groupCollapsed("[renderer] %c".concat(name," %c").concat(displayName," (").concat(maybeID,") %c").concat(parentInstance?"".concat(parentDisplayName," (").concat(maybeParentID,")"):""," %c").concat(extraString),"color: red; font-weight: bold;","color: blue;","color: purple;","color: black;"),console.log(Error().stack.split(`
169
+ `).slice(1).join(`
170
+ `)),console.groupEnd()}}function debugTree(instance){var indent=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;if(__DEBUG__){var name=(instance.kind!==VIRTUAL_INSTANCE?getDisplayNameForFiber(instance.data):instance.data.name)||"";console.log(" ".repeat(indent)+"- "+(instance.kind===FILTERED_FIBER_INSTANCE?0:instance.id)+" ("+name+")","parent",instance.parent===null?" ":instance.parent.kind===FILTERED_FIBER_INSTANCE?0:instance.parent.id,"next",instance.nextSibling===null?" ":instance.nextSibling.id);var child=instance.firstChild;while(child!==null)debugTree(child,indent+1),child=child.nextSibling}}var hideElementsWithDisplayNames=new Set,hideElementsWithPaths=new Set,hideElementsWithTypes=new Set,hideElementsWithEnvs=new Set,traceUpdatesEnabled=!1,traceUpdatesForNodes=new Set;function applyComponentFilters(componentFilters){hideElementsWithTypes.clear(),hideElementsWithDisplayNames.clear(),hideElementsWithPaths.clear(),hideElementsWithEnvs.clear(),componentFilters.forEach(function(componentFilter){if(!componentFilter.isEnabled)return;switch(componentFilter.type){case ComponentFilterDisplayName:if(componentFilter.isValid&&componentFilter.value!=="")hideElementsWithDisplayNames.add(new RegExp(componentFilter.value,"i"));break;case ComponentFilterElementType:hideElementsWithTypes.add(componentFilter.value);break;case ComponentFilterLocation:if(componentFilter.isValid&&componentFilter.value!=="")hideElementsWithPaths.add(new RegExp(componentFilter.value,"i"));break;case ComponentFilterHOC:hideElementsWithDisplayNames.add(new RegExp("\\("));break;case ComponentFilterEnvironmentName:hideElementsWithEnvs.add(componentFilter.value);break;default:console.warn('Invalid component filter type "'.concat(componentFilter.type,'"'));break}})}if(window.__REACT_DEVTOOLS_COMPONENT_FILTERS__!=null){var componentFiltersWithoutLocationBasedOnes=filterOutLocationComponentFilters(window.__REACT_DEVTOOLS_COMPONENT_FILTERS__);applyComponentFilters(componentFiltersWithoutLocationBasedOnes)}else applyComponentFilters(getDefaultComponentFilters());function updateComponentFilters(componentFilters){if(isProfiling)throw Error("Cannot modify filter preferences while profiling");hook.getFiberRoots(rendererID).forEach(function(root){var rootInstance=rootToFiberInstanceMap.get(root);if(rootInstance===void 0)throw Error("Expected the root instance to already exist when applying filters");currentRoot=rootInstance,unmountInstanceRecursively(rootInstance),rootToFiberInstanceMap.delete(root),flushPendingEvents(),currentRoot=null}),applyComponentFilters(componentFilters),rootDisplayNameCounter.clear(),hook.getFiberRoots(rendererID).forEach(function(root){var current=root.current,newRoot=createFiberInstance(current);if(rootToFiberInstanceMap.set(root,newRoot),idToDevToolsInstanceMap.set(newRoot.id,newRoot),trackedPath!==null)mightBeOnTrackedPath=!0;currentRoot=newRoot,setRootPseudoKey(currentRoot.id,root.current),mountFiberRecursively(root.current,!1),flushPendingEvents(),currentRoot=null}),flushPendingEvents(),needsToFlushComponentLogs=!1}function getEnvironmentNames(){return Array.from(knownEnvironmentNames)}function isFiberHydrated(fiber){if(OffscreenComponent===-1)throw Error("not implemented for legacy suspense");switch(fiber.tag){case HostRoot:var rootState=fiber.memoizedState;return!rootState.isDehydrated;case SuspenseComponent:var suspenseState=fiber.memoizedState;return suspenseState===null||suspenseState.dehydrated===null;default:throw Error("not implemented for work tag "+fiber.tag)}}function shouldFilterVirtual(data,secondaryEnv){if(hideElementsWithTypes.has(types_ElementTypeFunction))return!0;if(hideElementsWithDisplayNames.size>0){var displayName=data.name;if(displayName!=null){var _iterator4=_createForOfIteratorHelper(hideElementsWithDisplayNames),_step4;try{for(_iterator4.s();!(_step4=_iterator4.n()).done;){var displayNameRegExp=_step4.value;if(displayNameRegExp.test(displayName))return!0}}catch(err){_iterator4.e(err)}finally{_iterator4.f()}}}if((data.env==null||hideElementsWithEnvs.has(data.env))&&(secondaryEnv===null||hideElementsWithEnvs.has(secondaryEnv)))return!0;return!1}function shouldFilterFiber(fiber){var{tag,type,key}=fiber;switch(tag){case DehydratedSuspenseComponent:return!0;case HostPortal:case HostText:case LegacyHiddenComponent:case OffscreenComponent:case Throw:return!0;case HostRoot:return!1;case Fragment5:return key===null;default:var typeSymbol=getTypeSymbol(type);switch(typeSymbol){case CONCURRENT_MODE_NUMBER:case CONCURRENT_MODE_SYMBOL_STRING:case DEPRECATED_ASYNC_MODE_SYMBOL_STRING:case STRICT_MODE_NUMBER:case STRICT_MODE_SYMBOL_STRING:return!0;default:break}}var elementType=getElementTypeForFiber(fiber);if(hideElementsWithTypes.has(elementType))return!0;if(hideElementsWithDisplayNames.size>0){var displayName=getDisplayNameForFiber(fiber);if(displayName!=null){var _iterator5=_createForOfIteratorHelper(hideElementsWithDisplayNames),_step5;try{for(_iterator5.s();!(_step5=_iterator5.n()).done;){var displayNameRegExp=_step5.value;if(displayNameRegExp.test(displayName))return!0}}catch(err){_iterator5.e(err)}finally{_iterator5.f()}}}if(hideElementsWithEnvs.has("Client"))switch(tag){case ClassComponent:case IncompleteClassComponent:case IncompleteFunctionComponent:case FunctionComponent:case IndeterminateComponent:case ForwardRef:case MemoComponent:case SimpleMemoComponent:return!0}return!1}function getElementTypeForFiber(fiber){var{type,tag}=fiber;switch(tag){case ActivityComponent:return ElementTypeActivity;case ClassComponent:case IncompleteClassComponent:return types_ElementTypeClass;case IncompleteFunctionComponent:case FunctionComponent:case IndeterminateComponent:return types_ElementTypeFunction;case ForwardRef:return types_ElementTypeForwardRef;case HostRoot:return ElementTypeRoot;case HostComponent:case HostHoistable:case HostSingleton:return ElementTypeHostComponent;case HostPortal:case HostText:case Fragment5:return ElementTypeOtherOrUnknown;case MemoComponent:case SimpleMemoComponent:return types_ElementTypeMemo;case SuspenseComponent:return ElementTypeSuspense;case SuspenseListComponent:return ElementTypeSuspenseList;case TracingMarkerComponent:return ElementTypeTracingMarker;case ViewTransitionComponent:return ElementTypeViewTransition;default:var typeSymbol=getTypeSymbol(type);switch(typeSymbol){case CONCURRENT_MODE_NUMBER:case CONCURRENT_MODE_SYMBOL_STRING:case DEPRECATED_ASYNC_MODE_SYMBOL_STRING:return ElementTypeOtherOrUnknown;case PROVIDER_NUMBER:case PROVIDER_SYMBOL_STRING:return ElementTypeContext;case CONTEXT_NUMBER:case CONTEXT_SYMBOL_STRING:return ElementTypeContext;case STRICT_MODE_NUMBER:case STRICT_MODE_SYMBOL_STRING:return ElementTypeOtherOrUnknown;case PROFILER_NUMBER:case PROFILER_SYMBOL_STRING:return ElementTypeProfiler;default:return ElementTypeOtherOrUnknown}}}var currentRoot=null;function untrackFiber(nearestInstance,fiber){if(forceErrorForFibers.size>0){if(forceErrorForFibers.delete(fiber),fiber.alternate)forceErrorForFibers.delete(fiber.alternate);if(forceErrorForFibers.size===0&&setErrorHandler!=null)setErrorHandler(shouldErrorFiberAlwaysNull)}if(forceFallbackForFibers.size>0){if(forceFallbackForFibers.delete(fiber),fiber.alternate)forceFallbackForFibers.delete(fiber.alternate);if(forceFallbackForFibers.size===0&&setSuspenseHandler!=null)setSuspenseHandler(shouldSuspendFiberAlwaysFalse)}if(fiber.tag===HostHoistable)releaseHostResource(nearestInstance,fiber.memoizedState);else if(fiber.tag===HostComponent||fiber.tag===HostText||fiber.tag===HostSingleton)releaseHostInstance(nearestInstance,fiber.stateNode);for(var child=fiber.child;child!==null;child=child.sibling)if(shouldFilterFiber(child))untrackFiber(nearestInstance,child)}function getChangeDescription(prevFiber,nextFiber){switch(nextFiber.tag){case ClassComponent:if(prevFiber===null)return{context:null,didHooksChange:!1,isFirstMount:!0,props:null,state:null};else{var data={context:getContextChanged(prevFiber,nextFiber),didHooksChange:!1,isFirstMount:!1,props:getChangedKeys(prevFiber.memoizedProps,nextFiber.memoizedProps),state:getChangedKeys(prevFiber.memoizedState,nextFiber.memoizedState)};return data}case IncompleteFunctionComponent:case FunctionComponent:case IndeterminateComponent:case ForwardRef:case MemoComponent:case SimpleMemoComponent:if(prevFiber===null)return{context:null,didHooksChange:!1,isFirstMount:!0,props:null,state:null};else{var indices=getChangedHooksIndices(prevFiber.memoizedState,nextFiber.memoizedState),_data={context:getContextChanged(prevFiber,nextFiber),didHooksChange:indices!==null&&indices.length>0,isFirstMount:!1,props:getChangedKeys(prevFiber.memoizedProps,nextFiber.memoizedProps),state:null,hooks:indices};return _data}default:return null}}function getContextChanged(prevFiber,nextFiber){var prevContext=prevFiber.dependencies&&prevFiber.dependencies.firstContext,nextContext=nextFiber.dependencies&&nextFiber.dependencies.firstContext;while(prevContext&&nextContext){if(prevContext.context!==nextContext.context)return!1;if(!shared_objectIs(prevContext.memoizedValue,nextContext.memoizedValue))return!0;prevContext=prevContext.next,nextContext=nextContext.next}return!1}function isHookThatCanScheduleUpdate(hookObject){var queue=hookObject.queue;if(!queue)return!1;var boundHasOwnProperty=shared_hasOwnProperty.bind(queue);if(boundHasOwnProperty("pending"))return!0;return boundHasOwnProperty("value")&&boundHasOwnProperty("getSnapshot")&&typeof queue.getSnapshot==="function"}function didStatefulHookChange(prev,next){var prevMemoizedState=prev.memoizedState,nextMemoizedState=next.memoizedState;if(isHookThatCanScheduleUpdate(prev))return prevMemoizedState!==nextMemoizedState;return!1}function getChangedHooksIndices(prev,next){if(prev==null||next==null)return null;var indices=[],index=0;while(next!==null){if(didStatefulHookChange(prev,next))indices.push(index);next=next.next,prev=prev.next,index++}return indices}function getChangedKeys(prev,next){if(prev==null||next==null)return null;var keys=new Set([].concat(fiber_renderer_toConsumableArray(Object.keys(prev)),fiber_renderer_toConsumableArray(Object.keys(next)))),changedKeys=[],_iterator6=_createForOfIteratorHelper(keys),_step6;try{for(_iterator6.s();!(_step6=_iterator6.n()).done;){var key=_step6.value;if(prev[key]!==next[key])changedKeys.push(key)}}catch(err){_iterator6.e(err)}finally{_iterator6.f()}return changedKeys}function didFiberRender(prevFiber,nextFiber){switch(nextFiber.tag){case ClassComponent:case FunctionComponent:case ContextConsumer:case MemoComponent:case SimpleMemoComponent:case ForwardRef:var PerformedWork=1;return(getFiberFlags(nextFiber)&PerformedWork)===PerformedWork;default:return prevFiber.memoizedProps!==nextFiber.memoizedProps||prevFiber.memoizedState!==nextFiber.memoizedState||prevFiber.ref!==nextFiber.ref}}var pendingOperations=[],pendingRealUnmountedIDs=[],pendingRealUnmountedSuspenseIDs=[],pendingSuspenderChanges=new Set,pendingOperationsQueue=[],pendingStringTable=new Map,pendingStringTableLength=0,pendingUnmountedRootID=null;function pushOperation(op){pendingOperations.push(op)}function shouldBailoutWithPendingOperations(){if(isProfiling){if(currentCommitProfilingMetadata!=null&&currentCommitProfilingMetadata.durations.length>0)return!1}return pendingOperations.length===0&&pendingRealUnmountedIDs.length===0&&pendingRealUnmountedSuspenseIDs.length===0&&pendingSuspenderChanges.size===0&&pendingUnmountedRootID===null}function flushOrQueueOperations(operations){if(shouldBailoutWithPendingOperations())return;if(pendingOperationsQueue!==null)pendingOperationsQueue.push(operations);else hook.emit("operations",operations)}function recordConsoleLogs(instance,componentLogsEntry){if(componentLogsEntry===void 0){if(instance.logCount===0)return!1;return instance.logCount=0,pushOperation(TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS),pushOperation(instance.id),pushOperation(0),pushOperation(0),!0}else{var totalCount=componentLogsEntry.errorsCount+componentLogsEntry.warningsCount;if(instance.logCount===totalCount)return!1;return instance.logCount=totalCount,pushOperation(TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS),pushOperation(instance.id),pushOperation(componentLogsEntry.errorsCount),pushOperation(componentLogsEntry.warningsCount),!0}}function flushPendingEvents(){if(shouldBailoutWithPendingOperations())return;var numUnmountIDs=pendingRealUnmountedIDs.length+(pendingUnmountedRootID===null?0:1),numUnmountSuspenseIDs=pendingRealUnmountedSuspenseIDs.length,numSuspenderChanges=pendingSuspenderChanges.size,operations=Array(3+pendingStringTableLength+(numUnmountSuspenseIDs>0?2+numUnmountSuspenseIDs:0)+(numUnmountIDs>0?2+numUnmountIDs:0)+pendingOperations.length+(numSuspenderChanges>0?2+numSuspenderChanges*3:0)),i=0;if(operations[i++]=rendererID,currentRoot===null)operations[i++]=-1;else operations[i++]=currentRoot.id;if(operations[i++]=pendingStringTableLength,pendingStringTable.forEach(function(entry,stringKey){var encodedString=entry.encodedString,length=encodedString.length;operations[i++]=length;for(var j2=0;j2<length;j2++)operations[i+j2]=encodedString[j2];i+=length}),numUnmountSuspenseIDs>0){operations[i++]=SUSPENSE_TREE_OPERATION_REMOVE,operations[i++]=numUnmountSuspenseIDs;for(var j=0;j<pendingRealUnmountedSuspenseIDs.length;j++)operations[i++]=pendingRealUnmountedSuspenseIDs[j]}if(numUnmountIDs>0){operations[i++]=TREE_OPERATION_REMOVE,operations[i++]=numUnmountIDs;for(var _j=0;_j<pendingRealUnmountedIDs.length;_j++)operations[i++]=pendingRealUnmountedIDs[_j];if(pendingUnmountedRootID!==null)operations[i]=pendingUnmountedRootID,i++}for(var _j2=0;_j2<pendingOperations.length;_j2++)operations[i+_j2]=pendingOperations[_j2];if(i+=pendingOperations.length,numSuspenderChanges>0)operations[i++]=SUSPENSE_TREE_OPERATION_SUSPENDERS,operations[i++]=numSuspenderChanges,pendingSuspenderChanges.forEach(function(fiberIdWithChanges){var suspense=idToSuspenseNodeMap.get(fiberIdWithChanges);if(suspense===void 0)throw Error('Could not send suspender changes for "'.concat(fiberIdWithChanges,'" since the Fiber no longer exists.'));operations[i++]=fiberIdWithChanges,operations[i++]=suspense.hasUniqueSuspenders?1:0;var instance=suspense.instance,isSuspended=(instance.kind===FIBER_INSTANCE||instance.kind===FILTERED_FIBER_INSTANCE)&&instance.data.tag===SuspenseComponent&&instance.data.memoizedState!==null;operations[i++]=isSuspended?1:0,operations[i++]=suspense.environments.size,suspense.environments.forEach(function(count,env){operations[i++]=getStringID(env)})});flushOrQueueOperations(operations),pendingOperations.length=0,pendingRealUnmountedIDs.length=0,pendingRealUnmountedSuspenseIDs.length=0,pendingSuspenderChanges.clear(),pendingUnmountedRootID=null,pendingStringTable.clear(),pendingStringTableLength=0}function measureHostInstance(instance){if(renderer_typeof(instance)!=="object"||instance===null)return null;if(typeof instance.getClientRects==="function"||instance.nodeType===3){var doc=instance.ownerDocument;if(instance===doc.documentElement)return[{x:0,y:0,width:instance.scrollWidth,height:instance.scrollHeight}];var result=[],win=doc&&doc.defaultView,scrollX=win?win.scrollX:0,scrollY=win?win.scrollY:0,rects;if(instance.nodeType===3){if(typeof doc.createRange!=="function")return null;var range=doc.createRange();if(typeof range.getClientRects!=="function")return null;range.selectNodeContents(instance),rects=range.getClientRects()}else rects=instance.getClientRects();for(var i=0;i<rects.length;i++){var rect=rects[i];result.push({x:rect.x+scrollX,y:rect.y+scrollY,width:rect.width,height:rect.height})}return result}if(instance.canonical){var publicInstance=instance.canonical.publicInstance;if(!publicInstance)return null;if(typeof publicInstance.getBoundingClientRect==="function")return[publicInstance.getBoundingClientRect()];if(typeof publicInstance.unstable_getBoundingClientRect==="function")return[publicInstance.unstable_getBoundingClientRect()]}return null}function measureInstance(instance){var hostInstances=findAllCurrentHostInstances(instance),result=null;for(var i=0;i<hostInstances.length;i++){var childResult=measureHostInstance(hostInstances[i]);if(childResult!==null)if(result===null)result=childResult;else result=result.concat(childResult)}return result}function getStringID(string){if(string===null)return 0;var existingEntry=pendingStringTable.get(string);if(existingEntry!==void 0)return existingEntry.id;var id=pendingStringTable.size+1,encodedString=utfEncodeString(string);return pendingStringTable.set(string,{encodedString,id}),pendingStringTableLength+=encodedString.length+1,id}var isInDisconnectedSubtree=!1;function recordMount(fiber,parentInstance){var isRoot=fiber.tag===HostRoot,fiberInstance;if(isRoot){var entry=rootToFiberInstanceMap.get(fiber.stateNode);if(entry===void 0)throw Error("The root should have been registered at this point");fiberInstance=entry}else fiberInstance=createFiberInstance(fiber);if(idToDevToolsInstanceMap.set(fiberInstance.id,fiberInstance),__DEBUG__)debug2("recordMount()",fiberInstance,parentInstance);return recordReconnect(fiberInstance,parentInstance),fiberInstance}function recordReconnect(fiberInstance,parentInstance){if(isInDisconnectedSubtree)return;var{id,data:fiber}=fiberInstance,isProfilingSupported=fiber.hasOwnProperty("treeBaseDuration"),isRoot=fiber.tag===HostRoot;if(isRoot){var hasOwnerMetadata=fiber.hasOwnProperty("_debugOwner"),profilingFlags=0;if(isProfilingSupported){if(profilingFlags=PROFILING_FLAG_BASIC_SUPPORT,typeof injectProfilingHooks==="function")profilingFlags|=PROFILING_FLAG_TIMELINE_SUPPORT;if(supportsPerformanceTracks)profilingFlags|=PROFILING_FLAG_PERFORMANCE_TRACKS_SUPPORT}var isProductionBuildOfRenderer=renderer.bundleType===0;if(pushOperation(TREE_OPERATION_ADD),pushOperation(id),pushOperation(ElementTypeRoot),pushOperation((fiber.mode&StrictModeBits)!==0?1:0),pushOperation(profilingFlags),pushOperation(!isProductionBuildOfRenderer&&StrictModeBits!==0?1:0),pushOperation(hasOwnerMetadata?1:0),isProfiling){if(displayNamesByRootID!==null)displayNamesByRootID.set(id,getDisplayNameForRoot(fiber))}}else{var key=fiber.key,displayName=getDisplayNameForFiber(fiber),elementType=getElementTypeForFiber(fiber),debugOwner=getUnfilteredOwner(fiber),ownerInstance=findNearestOwnerInstance(parentInstance,debugOwner);if(ownerInstance!==null&&debugOwner===fiber._debugOwner&&fiber._debugStack!=null&&ownerInstance.source===null)ownerInstance.source=fiber._debugStack;var unfilteredParent=parentInstance;while(unfilteredParent!==null&&unfilteredParent.kind===FILTERED_FIBER_INSTANCE)unfilteredParent=unfilteredParent.parent;var ownerID=ownerInstance===null?0:ownerInstance.id,parentID=unfilteredParent===null?0:unfilteredParent.id,displayNameStringID=getStringID(displayName),keyString=key===null?null:String(key),keyStringID=getStringID(keyString),nameProp=fiber.tag===SuspenseComponent?fiber.memoizedProps.name:fiber.tag===ActivityComponent?fiber.memoizedProps.name:null,namePropString=nameProp==null?null:String(nameProp),namePropStringID=getStringID(namePropString);if(pushOperation(TREE_OPERATION_ADD),pushOperation(id),pushOperation(elementType),pushOperation(parentID),pushOperation(ownerID),pushOperation(displayNameStringID),pushOperation(keyStringID),pushOperation(namePropStringID),(fiber.mode&StrictModeBits)!==0){var parentFiber=null,parentFiberInstance=parentInstance;while(parentFiberInstance!==null){if(parentFiberInstance.kind===FIBER_INSTANCE){parentFiber=parentFiberInstance.data;break}parentFiberInstance=parentFiberInstance.parent}if(parentFiber===null||(parentFiber.mode&StrictModeBits)===0)pushOperation(TREE_OPERATION_SET_SUBTREE_MODE),pushOperation(id),pushOperation(StrictMode)}}var componentLogsEntry=fiberToComponentLogsMap.get(fiber);if(componentLogsEntry===void 0&&fiber.alternate!==null)componentLogsEntry=fiberToComponentLogsMap.get(fiber.alternate);if(recordConsoleLogs(fiberInstance,componentLogsEntry),isProfilingSupported)recordProfilingDurations(fiberInstance,null)}function recordVirtualMount(instance,parentInstance,secondaryEnv){var id=instance.id;idToDevToolsInstanceMap.set(id,instance),recordVirtualReconnect(instance,parentInstance,secondaryEnv)}function recordVirtualReconnect(instance,parentInstance,secondaryEnv){if(isInDisconnectedSubtree)return;var componentInfo=instance.data,key=typeof componentInfo.key==="string"?componentInfo.key:null,env=componentInfo.env,displayName=componentInfo.name||"";if(typeof env==="string"){if(secondaryEnv!==null)displayName=secondaryEnv+"("+displayName+")";displayName=env+"("+displayName+")"}var elementType=types_ElementTypeVirtual,debugOwner=getUnfilteredOwner(componentInfo),ownerInstance=findNearestOwnerInstance(parentInstance,debugOwner);if(ownerInstance!==null&&debugOwner===componentInfo.owner&&componentInfo.debugStack!=null&&ownerInstance.source===null)ownerInstance.source=componentInfo.debugStack;var unfilteredParent=parentInstance;while(unfilteredParent!==null&&unfilteredParent.kind===FILTERED_FIBER_INSTANCE)unfilteredParent=unfilteredParent.parent;var ownerID=ownerInstance===null?0:ownerInstance.id,parentID=unfilteredParent===null?0:unfilteredParent.id,displayNameStringID=getStringID(displayName),keyString=key===null?null:String(key),keyStringID=getStringID(keyString),namePropStringID=getStringID(null),id=instance.id;pushOperation(TREE_OPERATION_ADD),pushOperation(id),pushOperation(elementType),pushOperation(parentID),pushOperation(ownerID),pushOperation(displayNameStringID),pushOperation(keyStringID),pushOperation(namePropStringID);var componentLogsEntry=componentInfoToComponentLogsMap.get(componentInfo);recordConsoleLogs(instance,componentLogsEntry)}function recordSuspenseMount(suspenseInstance,parentSuspenseInstance){var fiberInstance=suspenseInstance.instance;if(fiberInstance.kind===FILTERED_FIBER_INSTANCE)throw Error("Cannot record a mount for a filtered Fiber instance.");var fiberID=fiberInstance.id,unfilteredParent=parentSuspenseInstance;while(unfilteredParent!==null&&unfilteredParent.instance.kind===FILTERED_FIBER_INSTANCE)unfilteredParent=unfilteredParent.parent;var unfilteredParentInstance=unfilteredParent!==null?unfilteredParent.instance:null;if(unfilteredParentInstance!==null&&unfilteredParentInstance.kind===FILTERED_FIBER_INSTANCE)throw Error("Should not have a filtered instance at this point. This is a bug.");var parentID=unfilteredParentInstance===null?0:unfilteredParentInstance.id,fiber=fiberInstance.data,props=fiber.memoizedProps,name=fiber.tag!==SuspenseComponent||props===null?null:props.name||null,nameStringID=getStringID(name),isSuspended=fiber.tag===SuspenseComponent&&fiber.memoizedState!==null;if(__DEBUG__)console.log("recordSuspenseMount()",suspenseInstance);idToSuspenseNodeMap.set(fiberID,suspenseInstance),pushOperation(SUSPENSE_TREE_OPERATION_ADD),pushOperation(fiberID),pushOperation(parentID),pushOperation(nameStringID),pushOperation(isSuspended?1:0);var rects=suspenseInstance.rects;if(rects===null)pushOperation(-1);else{pushOperation(rects.length);for(var i=0;i<rects.length;++i){var rect=rects[i];pushOperation(Math.round(rect.x*1000)),pushOperation(Math.round(rect.y*1000)),pushOperation(Math.round(rect.width*1000)),pushOperation(Math.round(rect.height*1000))}}}function recordUnmount(fiberInstance){if(__DEBUG__)debug2("recordUnmount()",fiberInstance,reconcilingParent);recordDisconnect(fiberInstance);var suspenseNode=fiberInstance.suspenseNode;if(suspenseNode!==null)recordSuspenseUnmount(suspenseNode);idToDevToolsInstanceMap.delete(fiberInstance.id),untrackFiber(fiberInstance,fiberInstance.data)}function recordDisconnect(fiberInstance){if(isInDisconnectedSubtree)return;var fiber=fiberInstance.data;if(trackedPathMatchInstance===fiberInstance)setTrackedPath(null);var id=fiberInstance.id,isRoot=fiber.tag===HostRoot;if(isRoot)pendingUnmountedRootID=id;else pendingRealUnmountedIDs.push(id)}function recordSuspenseResize(suspenseNode){if(__DEBUG__)console.log("recordSuspenseResize()",suspenseNode);var fiberInstance=suspenseNode.instance;if(fiberInstance.kind!==FIBER_INSTANCE)return;pushOperation(SUSPENSE_TREE_OPERATION_RESIZE),pushOperation(fiberInstance.id);var rects=suspenseNode.rects;if(rects===null)pushOperation(-1);else{pushOperation(rects.length);for(var i=0;i<rects.length;++i){var rect=rects[i];pushOperation(Math.round(rect.x*1000)),pushOperation(Math.round(rect.y*1000)),pushOperation(Math.round(rect.width*1000)),pushOperation(Math.round(rect.height*1000))}}}function recordSuspenseSuspenders(suspenseNode){if(__DEBUG__)console.log("recordSuspenseSuspenders()",suspenseNode);var fiberInstance=suspenseNode.instance;if(fiberInstance.kind!==FIBER_INSTANCE)return;suspenseNode.environments.forEach(function(count,env){getStringID(env)}),pendingSuspenderChanges.add(fiberInstance.id)}function recordSuspenseUnmount(suspenseInstance){if(__DEBUG__)console.log("recordSuspenseUnmount()",suspenseInstance,reconcilingParentSuspenseNode);var devtoolsInstance=suspenseInstance.instance;if(devtoolsInstance.kind!==FIBER_INSTANCE)throw Error("Can't unmount a filtered SuspenseNode. This is a bug.");var fiberInstance=devtoolsInstance,id=fiberInstance.id;pendingRealUnmountedSuspenseIDs.push(id),pendingSuspenderChanges.delete(id),idToSuspenseNodeMap.delete(id)}var remainingReconcilingChildren=null,previouslyReconciledSibling=null,reconcilingParent=null,remainingReconcilingChildrenSuspenseNodes=null,previouslyReconciledSiblingSuspenseNode=null,reconcilingParentSuspenseNode=null;function ioExistsInSuspenseAncestor(suspenseNode,ioInfo){var ancestor=suspenseNode.parent;while(ancestor!==null){if(ancestor.suspendedBy.has(ioInfo))return!0;ancestor=ancestor.parent}return!1}function insertSuspendedBy(asyncInfo){if(reconcilingParent===null||reconcilingParentSuspenseNode===null)throw Error("It should not be possible to have suspended data outside the root. Even suspending at the first position is still a child of the root.");var parentSuspenseNode=reconcilingParentSuspenseNode,parentInstance=reconcilingParent;while(parentInstance.kind===FILTERED_FIBER_INSTANCE&&parentInstance.parent!==null&&parentInstance!==parentSuspenseNode.instance)parentInstance=parentInstance.parent;var suspenseNodeSuspendedBy=parentSuspenseNode.suspendedBy,ioInfo=asyncInfo.awaited,suspendedBySet=suspenseNodeSuspendedBy.get(ioInfo);if(suspendedBySet===void 0){suspendedBySet=new Set,suspenseNodeSuspendedBy.set(ioInfo,suspendedBySet);var env=ioInfo.env;if(env!=null){var environmentCounts=parentSuspenseNode.environments,count=environmentCounts.get(env);if(count===void 0||count===0)environmentCounts.set(env,1),recordSuspenseSuspenders(parentSuspenseNode);else environmentCounts.set(env,count+1)}}if(!suspendedBySet.has(parentInstance)){if(suspendedBySet.add(parentInstance),!parentSuspenseNode.hasUniqueSuspenders&&!ioExistsInSuspenseAncestor(parentSuspenseNode,ioInfo))parentSuspenseNode.hasUniqueSuspenders=!0,recordSuspenseSuspenders(parentSuspenseNode)}parentSuspenseNode.hasUnknownSuspenders=!1;var suspendedBy=parentInstance.suspendedBy;if(suspendedBy===null)parentInstance.suspendedBy=[asyncInfo];else if(suspendedBy.indexOf(asyncInfo)===-1)suspendedBy.push(asyncInfo)}function getAwaitInSuspendedByFromIO(suspensedBy,ioInfo){for(var i=0;i<suspensedBy.length;i++){var asyncInfo=suspensedBy[i];if(asyncInfo.awaited===ioInfo)return asyncInfo}return null}function unblockSuspendedBy(parentSuspenseNode,ioInfo){var firstChild=parentSuspenseNode.firstChild;if(firstChild===null)return;var node=firstChild;while(node!==null){if(node.suspendedBy.has(ioInfo)){if(!node.hasUniqueSuspenders)recordSuspenseSuspenders(node);node.hasUniqueSuspenders=!0,node.hasUnknownSuspenders=!1}else if(node.firstChild!==null){node=node.firstChild;continue}while(node.nextSibling===null){if(node.parent===null||node.parent===parentSuspenseNode)return;node=node.parent}node=node.nextSibling}}function removePreviousSuspendedBy(instance,previousSuspendedBy,parentSuspenseNode){var suspenseNode=instance.suspenseNode===null?parentSuspenseNode:instance.suspenseNode;if(previousSuspendedBy!==null&&suspenseNode!==null){var nextSuspendedBy=instance.suspendedBy,changedEnvironment=!1;for(var i=0;i<previousSuspendedBy.length;i++){var asyncInfo=previousSuspendedBy[i];if(nextSuspendedBy===null||nextSuspendedBy.indexOf(asyncInfo)===-1&&getAwaitInSuspendedByFromIO(nextSuspendedBy,asyncInfo.awaited)===null){var ioInfo=asyncInfo.awaited,suspendedBySet=suspenseNode.suspendedBy.get(ioInfo);if(suspendedBySet===void 0||!suspendedBySet.delete(instance)){var alreadyRemovedIO=!1;for(var j=0;j<i;j++){var removedIOInfo=previousSuspendedBy[j].awaited;if(removedIOInfo===ioInfo){alreadyRemovedIO=!0;break}}if(!alreadyRemovedIO)throw Error("We are cleaning up async info that was not on the parent Suspense boundary. This is a bug in React.")}if(suspendedBySet!==void 0&&suspendedBySet.size===0){suspenseNode.suspendedBy.delete(ioInfo);var env=ioInfo.env;if(env!=null){var environmentCounts=suspenseNode.environments,count=environmentCounts.get(env);if(count===void 0||count===0)throw Error("We are removing an environment but it was not in the set. This is a bug in React.");if(count===1)environmentCounts.delete(env),changedEnvironment=!0;else environmentCounts.set(env,count-1)}}if(suspenseNode.hasUniqueSuspenders&&!ioExistsInSuspenseAncestor(suspenseNode,ioInfo))unblockSuspendedBy(suspenseNode,ioInfo)}}if(changedEnvironment)recordSuspenseSuspenders(suspenseNode)}}function insertChild(instance){var parentInstance=reconcilingParent;if(parentInstance===null)return;if(instance.parent=parentInstance,previouslyReconciledSibling===null)previouslyReconciledSibling=instance,parentInstance.firstChild=instance;else previouslyReconciledSibling.nextSibling=instance,previouslyReconciledSibling=instance;instance.nextSibling=null;var suspenseNode=instance.suspenseNode;if(suspenseNode!==null){var parentNode=reconcilingParentSuspenseNode;if(parentNode!==null){if(suspenseNode.parent=parentNode,previouslyReconciledSiblingSuspenseNode===null)previouslyReconciledSiblingSuspenseNode=suspenseNode,parentNode.firstChild=suspenseNode;else previouslyReconciledSiblingSuspenseNode.nextSibling=suspenseNode,previouslyReconciledSiblingSuspenseNode=suspenseNode;suspenseNode.nextSibling=null}}}function moveChild(instance,previousSibling){removeChild(instance,previousSibling),insertChild(instance)}function removeChild(instance,previousSibling){if(instance.parent===null){if(remainingReconcilingChildren===instance)throw Error("Remaining children should not have items with no parent");else if(instance.nextSibling!==null)throw Error("A deleted instance should not have next siblings");return}var parentInstance=reconcilingParent;if(parentInstance===null)throw Error("Should not have a parent if we are at the root");if(instance.parent!==parentInstance)throw Error("Cannot remove a node from a different parent than is being reconciled.");if(previousSibling===null){if(remainingReconcilingChildren!==instance)throw Error("Expected a placed child to be moved from the remaining set.");remainingReconcilingChildren=instance.nextSibling}else previousSibling.nextSibling=instance.nextSibling;instance.nextSibling=null,instance.parent=null;var suspenseNode=instance.suspenseNode;if(suspenseNode!==null&&suspenseNode.parent!==null){var parentNode=reconcilingParentSuspenseNode;if(parentNode===null)throw Error("Should not have a parent if we are at the root");if(suspenseNode.parent!==parentNode)throw Error("Cannot remove a Suspense node from a different parent than is being reconciled.");var previousSuspenseSibling=remainingReconcilingChildrenSuspenseNodes;if(previousSuspenseSibling===suspenseNode)remainingReconcilingChildrenSuspenseNodes=suspenseNode.nextSibling;else while(previousSuspenseSibling!==null){if(previousSuspenseSibling.nextSibling===suspenseNode){previousSuspenseSibling.nextSibling=suspenseNode.nextSibling;break}previousSuspenseSibling=previousSuspenseSibling.nextSibling}suspenseNode.nextSibling=null,suspenseNode.parent=null}}function isHiddenOffscreen(fiber){switch(fiber.tag){case LegacyHiddenComponent:case OffscreenComponent:return fiber.memoizedState!==null;default:return!1}}function isSuspendedOffscreen(fiber){switch(fiber.tag){case LegacyHiddenComponent:case OffscreenComponent:return fiber.memoizedState!==null&&fiber.return!==null&&fiber.return.tag===SuspenseComponent;default:return!1}}function unmountRemainingChildren(){if(reconcilingParent!==null&&(reconcilingParent.kind===FIBER_INSTANCE||reconcilingParent.kind===FILTERED_FIBER_INSTANCE)&&isSuspendedOffscreen(reconcilingParent.data)&&!isInDisconnectedSubtree){isInDisconnectedSubtree=!0;try{var child=remainingReconcilingChildren;while(child!==null)unmountInstanceRecursively(child),child=remainingReconcilingChildren}finally{isInDisconnectedSubtree=!1}}else{var _child=remainingReconcilingChildren;while(_child!==null)unmountInstanceRecursively(_child),_child=remainingReconcilingChildren}}function unmountSuspenseChildrenRecursively(contentInstance,stashedSuspenseParent,stashedSuspensePrevious,stashedSuspenseRemaining){unmountInstanceRecursively(contentInstance),reconcilingParentSuspenseNode=stashedSuspenseParent,previouslyReconciledSiblingSuspenseNode=stashedSuspensePrevious,remainingReconcilingChildrenSuspenseNodes=stashedSuspenseRemaining,unmountRemainingChildren()}function isChildOf(parentInstance,childInstance,grandParent){var instance=childInstance.parent;while(instance!==null){if(parentInstance===instance)return!0;if(instance===parentInstance.parent||instance===grandParent)break;instance=instance.parent}return!1}function areEqualRects(a,b){if(a===null)return b===null;if(b===null)return!1;if(a.length!==b.length)return!1;for(var i=0;i<a.length;i++){var aRect=a[i],bRect=b[i];if(aRect.x!==bRect.x||aRect.y!==bRect.y||aRect.width!==bRect.width||aRect.height!==bRect.height)return!1}return!0}function measureUnchangedSuspenseNodesRecursively(suspenseNode){if(isInDisconnectedSubtree)return;var instance=suspenseNode.instance,isSuspendedSuspenseComponent=(instance.kind===FIBER_INSTANCE||instance.kind===FILTERED_FIBER_INSTANCE)&&instance.data.tag===SuspenseComponent&&instance.data.memoizedState!==null;if(isSuspendedSuspenseComponent)return;var parent=instance.parent;while(parent!==null){if((parent.kind===FIBER_INSTANCE||parent.kind===FILTERED_FIBER_INSTANCE)&&isHiddenOffscreen(parent.data))return;if(parent.suspenseNode!==null)break;parent=parent.parent}var nextRects=measureInstance(suspenseNode.instance),prevRects=suspenseNode.rects;if(areEqualRects(prevRects,nextRects))return;for(var child=suspenseNode.firstChild;child!==null;child=child.nextSibling)measureUnchangedSuspenseNodesRecursively(child);suspenseNode.rects=nextRects,recordSuspenseResize(suspenseNode)}function consumeSuspenseNodesOfExistingInstance(instance){var suspenseNode=remainingReconcilingChildrenSuspenseNodes;if(suspenseNode===null)return;var parentSuspenseNode=reconcilingParentSuspenseNode;if(parentSuspenseNode===null)throw Error("The should not be any remaining suspense node children if there is no parent.");var foundOne=!1,previousSkippedSibling=null;while(suspenseNode!==null)if(isChildOf(instance,suspenseNode.instance,parentSuspenseNode.instance)){foundOne=!0;var nextRemainingSibling=suspenseNode.nextSibling;if(previousSkippedSibling===null)remainingReconcilingChildrenSuspenseNodes=nextRemainingSibling;else previousSkippedSibling.nextSibling=nextRemainingSibling;if(suspenseNode.nextSibling=null,previouslyReconciledSiblingSuspenseNode===null)parentSuspenseNode.firstChild=suspenseNode;else previouslyReconciledSiblingSuspenseNode.nextSibling=suspenseNode;previouslyReconciledSiblingSuspenseNode=suspenseNode,measureUnchangedSuspenseNodesRecursively(suspenseNode),suspenseNode=nextRemainingSibling}else if(foundOne)break;else previousSkippedSibling=suspenseNode,suspenseNode=suspenseNode.nextSibling}function mountVirtualInstanceRecursively(virtualInstance,firstChild,lastChild,traceNearestHostComponentUpdate,virtualLevel){var mightSiblingsBeOnTrackedPath=updateVirtualTrackedPathStateBeforeMount(virtualInstance,reconcilingParent),stashedParent=reconcilingParent,stashedPrevious=previouslyReconciledSibling,stashedRemaining=remainingReconcilingChildren;reconcilingParent=virtualInstance,previouslyReconciledSibling=null,remainingReconcilingChildren=null;try{mountVirtualChildrenRecursively(firstChild,lastChild,traceNearestHostComponentUpdate,virtualLevel+1),recordVirtualProfilingDurations(virtualInstance)}finally{reconcilingParent=stashedParent,previouslyReconciledSibling=stashedPrevious,remainingReconcilingChildren=stashedRemaining,updateTrackedPathStateAfterMount(mightSiblingsBeOnTrackedPath)}}function recordVirtualUnmount(instance){recordVirtualDisconnect(instance),idToDevToolsInstanceMap.delete(instance.id)}function recordVirtualDisconnect(instance){if(isInDisconnectedSubtree)return;if(trackedPathMatchInstance===instance)setTrackedPath(null);var id=instance.id;pendingRealUnmountedIDs.push(id)}function getSecondaryEnvironmentName(debugInfo,index){if(debugInfo!=null){var componentInfo=debugInfo[index];for(var i=index+1;i<debugInfo.length;i++){var debugEntry=debugInfo[i];if(typeof debugEntry.env==="string")return componentInfo.env!==debugEntry.env?debugEntry.env:null}}return null}function trackDebugInfoFromLazyType(fiber){var type=fiber.elementType,typeSymbol=getTypeSymbol(type);if(typeSymbol===LAZY_SYMBOL_STRING){var debugInfo=type._debugInfo;if(debugInfo)for(var i=0;i<debugInfo.length;i++){var debugEntry=debugInfo[i];if(debugEntry.awaited){var asyncInfo=debugEntry;insertSuspendedBy(asyncInfo)}}}}function trackDebugInfoFromUsedThenables(fiber){var dependencies=fiber.dependencies;if(dependencies==null)return;var thenableState=dependencies._debugThenableState;if(thenableState==null)return;var usedThenables=thenableState.thenables||thenableState;if(!Array.isArray(usedThenables))return;for(var i=0;i<usedThenables.length;i++){var thenable=usedThenables[i],debugInfo=thenable._debugInfo;if(debugInfo)for(var j=0;j<debugInfo.length;j++){var debugEntry=debugInfo[j];if(debugEntry.awaited){var asyncInfo=debugEntry;insertSuspendedBy(asyncInfo)}}}}var hostAsyncInfoCache=new WeakMap;function trackDebugInfoFromHostResource(devtoolsInstance,fiber){var resource=fiber.memoizedState;if(resource==null)return;var existingEntry=hostAsyncInfoCache.get(resource);if(existingEntry!==void 0){insertSuspendedBy(existingEntry);return}var props=fiber.memoizedProps,mayResourceSuspendCommit=resource.type==="stylesheet"&&(typeof props.media!=="string"||typeof matchMedia!=="function"||matchMedia(props.media));if(!mayResourceSuspendCommit)return;var instance=resource.instance;if(instance==null)return;var href=instance.href;if(typeof href!=="string")return;var start=-1,end=-1,byteSize=0;if(typeof performance.getEntriesByType==="function"){var resourceEntries=performance.getEntriesByType("resource");for(var i=0;i<resourceEntries.length;i++){var resourceEntry=resourceEntries[i];if(resourceEntry.name===href)start=resourceEntry.startTime,end=start+resourceEntry.duration,byteSize=resourceEntry.transferSize||0}}var value=instance.sheet,promise=Promise.resolve(value);promise.status="fulfilled",promise.value=value;var ioInfo={name:"stylesheet",start,end,value:promise,owner:fiber};if(byteSize>0)ioInfo.byteSize=byteSize;var asyncInfo={awaited:ioInfo,owner:fiber._debugOwner==null?null:fiber._debugOwner,debugStack:fiber._debugStack==null?null:fiber._debugStack,debugTask:fiber._debugTask==null?null:fiber._debugTask};hostAsyncInfoCache.set(resource,asyncInfo),insertSuspendedBy(asyncInfo)}function trackDebugInfoFromHostComponent(devtoolsInstance,fiber){if(fiber.tag!==HostComponent)return;if((fiber.mode&SuspenseyImagesMode)===0)return;var{type,memoizedProps:props}=fiber,maySuspendCommit=type==="img"&&props.src!=null&&props.src!==""&&props.onLoad==null&&props.loading!=="lazy";if(!maySuspendCommit)return;var instance=fiber.stateNode;if(instance==null)return;var src=instance.currentSrc;if(typeof src!=="string"||src==="")return;var start=-1,end=-1,byteSize=0,fileSize=0;if(typeof performance.getEntriesByType==="function"){var resourceEntries=performance.getEntriesByType("resource");for(var i=0;i<resourceEntries.length;i++){var resourceEntry=resourceEntries[i];if(resourceEntry.name===src)start=resourceEntry.startTime,end=start+resourceEntry.duration,fileSize=resourceEntry.decodedBodySize||0,byteSize=resourceEntry.transferSize||0}}var value={currentSrc:src};if(instance.naturalWidth>0&&instance.naturalHeight>0)value.naturalWidth=instance.naturalWidth,value.naturalHeight=instance.naturalHeight;if(fileSize>0)value.fileSize=fileSize;var promise=Promise.resolve(value);promise.status="fulfilled",promise.value=value;var ioInfo={name:"img",start,end,value:promise,owner:fiber};if(byteSize>0)ioInfo.byteSize=byteSize;var asyncInfo={awaited:ioInfo,owner:fiber._debugOwner==null?null:fiber._debugOwner,debugStack:fiber._debugStack==null?null:fiber._debugStack,debugTask:fiber._debugTask==null?null:fiber._debugTask};insertSuspendedBy(asyncInfo)}function trackThrownPromisesFromRetryCache(suspenseNode,retryCache){if(retryCache!=null){if(!suspenseNode.hasUniqueSuspenders)recordSuspenseSuspenders(suspenseNode);suspenseNode.hasUniqueSuspenders=!0,suspenseNode.hasUnknownSuspenders=!0}}function mountVirtualChildrenRecursively(firstChild,lastChild,traceNearestHostComponentUpdate,virtualLevel){var fiber=firstChild,previousVirtualInstance=null,previousVirtualInstanceFirstFiber=firstChild;while(fiber!==null&&fiber!==lastChild){var level=0;if(fiber._debugInfo)for(var i=0;i<fiber._debugInfo.length;i++){var debugEntry=fiber._debugInfo[i];if(debugEntry.awaited){var asyncInfo=debugEntry;if(level===virtualLevel)insertSuspendedBy(asyncInfo);continue}if(typeof debugEntry.name!=="string")continue;var componentInfo=debugEntry,secondaryEnv=getSecondaryEnvironmentName(fiber._debugInfo,i);if(componentInfo.env!=null)knownEnvironmentNames.add(componentInfo.env);if(secondaryEnv!==null)knownEnvironmentNames.add(secondaryEnv);if(shouldFilterVirtual(componentInfo,secondaryEnv))continue;if(level===virtualLevel){if(previousVirtualInstance===null||previousVirtualInstance.data!==debugEntry){if(previousVirtualInstance!==null)mountVirtualInstanceRecursively(previousVirtualInstance,previousVirtualInstanceFirstFiber,fiber,traceNearestHostComponentUpdate,virtualLevel);previousVirtualInstance=createVirtualInstance(componentInfo),recordVirtualMount(previousVirtualInstance,reconcilingParent,secondaryEnv),insertChild(previousVirtualInstance),previousVirtualInstanceFirstFiber=fiber}level++;break}else level++}if(level===virtualLevel){if(previousVirtualInstance!==null)mountVirtualInstanceRecursively(previousVirtualInstance,previousVirtualInstanceFirstFiber,fiber,traceNearestHostComponentUpdate,virtualLevel),previousVirtualInstance=null;mountFiberRecursively(fiber,traceNearestHostComponentUpdate)}fiber=fiber.sibling}if(previousVirtualInstance!==null)mountVirtualInstanceRecursively(previousVirtualInstance,previousVirtualInstanceFirstFiber,null,traceNearestHostComponentUpdate,virtualLevel)}function mountChildrenRecursively(firstChild,traceNearestHostComponentUpdate){mountVirtualChildrenRecursively(firstChild,null,traceNearestHostComponentUpdate,0)}function mountSuspenseChildrenRecursively(contentFiber,traceNearestHostComponentUpdate,stashedSuspenseParent,stashedSuspensePrevious,stashedSuspenseRemaining){var fallbackFiber=contentFiber.sibling;if(mountVirtualChildrenRecursively(contentFiber,fallbackFiber,traceNearestHostComponentUpdate,0),reconcilingParentSuspenseNode=stashedSuspenseParent,previouslyReconciledSiblingSuspenseNode=stashedSuspensePrevious,remainingReconcilingChildrenSuspenseNodes=stashedSuspenseRemaining,fallbackFiber!==null)mountVirtualChildrenRecursively(fallbackFiber,null,traceNearestHostComponentUpdate,0)}function mountFiberRecursively(fiber,traceNearestHostComponentUpdate){var shouldIncludeInTree=!shouldFilterFiber(fiber),newInstance=null,newSuspenseNode=null;if(shouldIncludeInTree){if(newInstance=recordMount(fiber,reconcilingParent),fiber.tag===SuspenseComponent||fiber.tag===HostRoot){if(newSuspenseNode=createSuspenseNode(newInstance),fiber.tag===SuspenseComponent)if(OffscreenComponent===-1){var isTimedOut=fiber.memoizedState!==null;if(!isTimedOut)newSuspenseNode.rects=measureInstance(newInstance)}else{var hydrated=isFiberHydrated(fiber);if(hydrated){var contentFiber=fiber.child;if(contentFiber===null)throw Error("There should always be an Offscreen Fiber child in a hydrated Suspense boundary.")}var _isTimedOut=fiber.memoizedState!==null;if(!_isTimedOut)newSuspenseNode.rects=measureInstance(newInstance)}else newSuspenseNode.rects=measureInstance(newInstance);recordSuspenseMount(newSuspenseNode,reconcilingParentSuspenseNode)}if(insertChild(newInstance),__DEBUG__)debug2("mountFiberRecursively()",newInstance,reconcilingParent)}else if(reconcilingParent!==null&&reconcilingParent.kind===VIRTUAL_INSTANCE||fiber.tag===SuspenseComponent||fiber.tag===OffscreenComponent||fiber.tag===LegacyHiddenComponent){if(reconcilingParent!==null&&reconcilingParent.kind===VIRTUAL_INSTANCE&&reconcilingParent.data===fiber._debugOwner&&fiber._debugStack!=null&&reconcilingParent.source===null)reconcilingParent.source=fiber._debugStack;if(newInstance=createFilteredFiberInstance(fiber),fiber.tag===SuspenseComponent)if(newSuspenseNode=createSuspenseNode(newInstance),OffscreenComponent===-1){var _isTimedOut2=fiber.memoizedState!==null;if(!_isTimedOut2)newSuspenseNode.rects=measureInstance(newInstance)}else{var _hydrated=isFiberHydrated(fiber);if(_hydrated){var _contentFiber=fiber.child;if(_contentFiber===null)throw Error("There should always be an Offscreen Fiber child in a hydrated Suspense boundary.")}var suspenseState=fiber.memoizedState,_isTimedOut3=suspenseState!==null;if(!_isTimedOut3)newSuspenseNode.rects=measureInstance(newInstance)}if(insertChild(newInstance),__DEBUG__)debug2("mountFiberRecursively()",newInstance,reconcilingParent)}var mightSiblingsBeOnTrackedPath=updateTrackedPathStateBeforeMount(fiber,newInstance),stashedParent=reconcilingParent,stashedPrevious=previouslyReconciledSibling,stashedRemaining=remainingReconcilingChildren,stashedSuspenseParent=reconcilingParentSuspenseNode,stashedSuspensePrevious=previouslyReconciledSiblingSuspenseNode,stashedSuspenseRemaining=remainingReconcilingChildrenSuspenseNodes;if(newInstance!==null)reconcilingParent=newInstance,previouslyReconciledSibling=null,remainingReconcilingChildren=null;var shouldPopSuspenseNode=!1;if(newSuspenseNode!==null)reconcilingParentSuspenseNode=newSuspenseNode,previouslyReconciledSiblingSuspenseNode=null,remainingReconcilingChildrenSuspenseNodes=null,shouldPopSuspenseNode=!0;try{if(traceUpdatesEnabled){if(traceNearestHostComponentUpdate){var elementType=getElementTypeForFiber(fiber);if(elementType===ElementTypeHostComponent)traceUpdatesForNodes.add(fiber.stateNode),traceNearestHostComponentUpdate=!1}}if(trackDebugInfoFromLazyType(fiber),trackDebugInfoFromUsedThenables(fiber),fiber.tag===HostHoistable){var nearestInstance=reconcilingParent;if(nearestInstance===null)throw Error("Did not expect a host hoistable to be the root");aquireHostResource(nearestInstance,fiber.memoizedState),trackDebugInfoFromHostResource(nearestInstance,fiber)}else if(fiber.tag===HostComponent||fiber.tag===HostText||fiber.tag===HostSingleton){var _nearestInstance=reconcilingParent;if(_nearestInstance===null)throw Error("Did not expect a host hoistable to be the root");aquireHostInstance(_nearestInstance,fiber.stateNode),trackDebugInfoFromHostComponent(_nearestInstance,fiber)}if(isSuspendedOffscreen(fiber)){var stashedDisconnected=isInDisconnectedSubtree;isInDisconnectedSubtree=!0;try{if(fiber.child!==null)mountChildrenRecursively(fiber.child,!1)}finally{isInDisconnectedSubtree=stashedDisconnected}}else if(isHiddenOffscreen(fiber));else if(fiber.tag===SuspenseComponent&&OffscreenComponent===-1){if(newSuspenseNode!==null)trackThrownPromisesFromRetryCache(newSuspenseNode,fiber.stateNode);var _isTimedOut4=fiber.memoizedState!==null;if(_isTimedOut4){var primaryChildFragment=fiber.child,fallbackChildFragment=primaryChildFragment?primaryChildFragment.sibling:null;if(fallbackChildFragment){var fallbackChild=fallbackChildFragment.child;if(fallbackChild!==null)updateTrackedPathStateBeforeMount(fallbackChildFragment,null),mountChildrenRecursively(fallbackChild,traceNearestHostComponentUpdate)}}else{var primaryChild=fiber.child;if(primaryChild!==null)mountChildrenRecursively(primaryChild,traceNearestHostComponentUpdate)}}else if(fiber.tag===SuspenseComponent&&OffscreenComponent!==-1&&newInstance!==null&&newSuspenseNode!==null){var _contentFiber2=fiber.child,_hydrated2=isFiberHydrated(fiber);if(_hydrated2){if(_contentFiber2===null)throw Error("There should always be an Offscreen Fiber child in a hydrated Suspense boundary.");trackThrownPromisesFromRetryCache(newSuspenseNode,fiber.stateNode),mountSuspenseChildrenRecursively(_contentFiber2,traceNearestHostComponentUpdate,stashedSuspenseParent,stashedSuspensePrevious,stashedSuspenseRemaining),shouldPopSuspenseNode=!1}}else if(fiber.child!==null)mountChildrenRecursively(fiber.child,traceNearestHostComponentUpdate)}finally{if(newInstance!==null)reconcilingParent=stashedParent,previouslyReconciledSibling=stashedPrevious,remainingReconcilingChildren=stashedRemaining;if(shouldPopSuspenseNode)reconcilingParentSuspenseNode=stashedSuspenseParent,previouslyReconciledSiblingSuspenseNode=stashedSuspensePrevious,remainingReconcilingChildrenSuspenseNodes=stashedSuspenseRemaining}updateTrackedPathStateAfterMount(mightSiblingsBeOnTrackedPath)}function unmountInstanceRecursively(instance){if(__DEBUG__)debug2("unmountInstanceRecursively()",instance,reconcilingParent);var shouldPopSuspenseNode=!1,stashedParent=reconcilingParent,stashedPrevious=previouslyReconciledSibling,stashedRemaining=remainingReconcilingChildren,stashedSuspenseParent=reconcilingParentSuspenseNode,stashedSuspensePrevious=previouslyReconciledSiblingSuspenseNode,stashedSuspenseRemaining=remainingReconcilingChildrenSuspenseNodes,previousSuspendedBy=instance.suspendedBy;if(reconcilingParent=instance,previouslyReconciledSibling=null,remainingReconcilingChildren=instance.firstChild,instance.firstChild=null,instance.suspendedBy=null,instance.suspenseNode!==null)reconcilingParentSuspenseNode=instance.suspenseNode,previouslyReconciledSiblingSuspenseNode=null,remainingReconcilingChildrenSuspenseNodes=instance.suspenseNode.firstChild,shouldPopSuspenseNode=!0;try{if((instance.kind===FIBER_INSTANCE||instance.kind===FILTERED_FIBER_INSTANCE)&&instance.data.tag===SuspenseComponent&&OffscreenComponent!==-1){var _fiber4=instance.data,contentFiberInstance=remainingReconcilingChildren,hydrated=isFiberHydrated(_fiber4);if(hydrated){if(contentFiberInstance===null)throw Error("There should always be an Offscreen Fiber child in a hydrated Suspense boundary.");unmountSuspenseChildrenRecursively(contentFiberInstance,stashedSuspenseParent,stashedSuspensePrevious,stashedSuspenseRemaining),shouldPopSuspenseNode=!1}else if(contentFiberInstance!==null)throw Error("A dehydrated Suspense node should not have a content Fiber.")}else unmountRemainingChildren();removePreviousSuspendedBy(instance,previousSuspendedBy,reconcilingParentSuspenseNode)}finally{if(reconcilingParent=stashedParent,previouslyReconciledSibling=stashedPrevious,remainingReconcilingChildren=stashedRemaining,shouldPopSuspenseNode)reconcilingParentSuspenseNode=stashedSuspenseParent,previouslyReconciledSiblingSuspenseNode=stashedSuspensePrevious,remainingReconcilingChildrenSuspenseNodes=stashedSuspenseRemaining}if(instance.kind===FIBER_INSTANCE)recordUnmount(instance);else if(instance.kind===VIRTUAL_INSTANCE)recordVirtualUnmount(instance);else untrackFiber(instance,instance.data);removeChild(instance,null)}function recordProfilingDurations(fiberInstance,prevFiber){var{id,data:fiber}=fiberInstance,actualDuration=fiber.actualDuration,treeBaseDuration=fiber.treeBaseDuration;if(fiberInstance.treeBaseDuration=treeBaseDuration||0,isProfiling){if(prevFiber==null||treeBaseDuration!==prevFiber.treeBaseDuration){var convertedTreeBaseDuration=Math.floor((treeBaseDuration||0)*1000);pushOperation(TREE_OPERATION_UPDATE_TREE_BASE_DURATION),pushOperation(id),pushOperation(convertedTreeBaseDuration)}if(prevFiber==null||didFiberRender(prevFiber,fiber)){if(actualDuration!=null){var selfDuration=actualDuration,child=fiber.child;while(child!==null)selfDuration-=child.actualDuration||0,child=child.sibling;var metadata=currentCommitProfilingMetadata;if(metadata.durations.push(id,actualDuration,selfDuration),metadata.maxActualDuration=Math.max(metadata.maxActualDuration,actualDuration),recordChangeDescriptions){var changeDescription=getChangeDescription(prevFiber,fiber);if(changeDescription!==null){if(metadata.changeDescriptions!==null)metadata.changeDescriptions.set(id,changeDescription)}}}}var fiberRoot=currentRoot.data.stateNode,updaters=fiberRoot.memoizedUpdaters;if(updaters!=null&&(updaters.has(fiber)||fiber.alternate!==null&&updaters.has(fiber.alternate))){var _metadata=currentCommitProfilingMetadata;if(_metadata.updaters===null)_metadata.updaters=[];_metadata.updaters.push(instanceToSerializedElement(fiberInstance))}}}function recordVirtualProfilingDurations(virtualInstance){var id=virtualInstance.id,treeBaseDuration=0;for(var child=virtualInstance.firstChild;child!==null;child=child.nextSibling)treeBaseDuration+=child.treeBaseDuration;if(isProfiling){var previousTreeBaseDuration=virtualInstance.treeBaseDuration;if(treeBaseDuration!==previousTreeBaseDuration){var convertedTreeBaseDuration=Math.floor((treeBaseDuration||0)*1000);pushOperation(TREE_OPERATION_UPDATE_TREE_BASE_DURATION),pushOperation(id),pushOperation(convertedTreeBaseDuration)}}virtualInstance.treeBaseDuration=treeBaseDuration}function addUnfilteredChildrenIDs(parentInstance,nextChildren){var child=parentInstance.firstChild;while(child!==null){if(child.kind===FILTERED_FIBER_INSTANCE){var _fiber5=child.data;if(isHiddenOffscreen(_fiber5));else addUnfilteredChildrenIDs(child,nextChildren)}else nextChildren.push(child.id);child=child.nextSibling}}function recordResetChildren(parentInstance){if(__DEBUG__){if(parentInstance.firstChild!==null)debug2("recordResetChildren()",parentInstance.firstChild,parentInstance)}var nextChildren=[];addUnfilteredChildrenIDs(parentInstance,nextChildren);var numChildren=nextChildren.length;if(numChildren<2)return;pushOperation(TREE_OPERATION_REORDER_CHILDREN),pushOperation(parentInstance.id),pushOperation(numChildren);for(var i=0;i<nextChildren.length;i++)pushOperation(nextChildren[i])}function addUnfilteredSuspenseChildrenIDs(parentInstance,nextChildren){var child=parentInstance.firstChild;while(child!==null){if(child.instance.kind===FILTERED_FIBER_INSTANCE)addUnfilteredSuspenseChildrenIDs(child,nextChildren);else nextChildren.push(child.instance.id);child=child.nextSibling}}function recordResetSuspenseChildren(parentInstance){if(__DEBUG__){if(parentInstance.firstChild!==null)console.log("recordResetSuspenseChildren()",parentInstance.firstChild,parentInstance)}var nextChildren=[];addUnfilteredSuspenseChildrenIDs(parentInstance,nextChildren);var numChildren=nextChildren.length;if(numChildren<2)return;pushOperation(SUSPENSE_TREE_OPERATION_REORDER_CHILDREN),pushOperation(parentInstance.instance.id),pushOperation(numChildren);for(var i=0;i<nextChildren.length;i++)pushOperation(nextChildren[i])}function updateVirtualInstanceRecursively(virtualInstance,nextFirstChild,nextLastChild,prevFirstChild,traceNearestHostComponentUpdate,virtualLevel){var stashedParent=reconcilingParent,stashedPrevious=previouslyReconciledSibling,stashedRemaining=remainingReconcilingChildren,previousSuspendedBy=virtualInstance.suspendedBy;reconcilingParent=virtualInstance,previouslyReconciledSibling=null,remainingReconcilingChildren=virtualInstance.firstChild,virtualInstance.firstChild=null,virtualInstance.suspendedBy=null;try{var updateFlags=updateVirtualChildrenRecursively(nextFirstChild,nextLastChild,prevFirstChild,traceNearestHostComponentUpdate,virtualLevel+1);if((updateFlags&ShouldResetChildren)!==NoUpdate){if(!isInDisconnectedSubtree)recordResetChildren(virtualInstance);updateFlags&=~ShouldResetChildren}removePreviousSuspendedBy(virtualInstance,previousSuspendedBy,reconcilingParentSuspenseNode);var componentLogsEntry=componentInfoToComponentLogsMap.get(virtualInstance.data);return recordConsoleLogs(virtualInstance,componentLogsEntry),recordVirtualProfilingDurations(virtualInstance),updateFlags}finally{unmountRemainingChildren(),reconcilingParent=stashedParent,previouslyReconciledSibling=stashedPrevious,remainingReconcilingChildren=stashedRemaining}}function updateVirtualChildrenRecursively(nextFirstChild,nextLastChild,prevFirstChild,traceNearestHostComponentUpdate,virtualLevel){var updateFlags=NoUpdate,nextChild=nextFirstChild,prevChildAtSameIndex=prevFirstChild,previousVirtualInstance=null,previousVirtualInstanceWasMount=!1,previousVirtualInstanceNextFirstFiber=nextFirstChild,previousVirtualInstancePrevFirstFiber=prevFirstChild;while(nextChild!==null&&nextChild!==nextLastChild){var level=0;if(nextChild._debugInfo)for(var i=0;i<nextChild._debugInfo.length;i++){var debugEntry=nextChild._debugInfo[i];if(debugEntry.awaited){var asyncInfo=debugEntry;if(level===virtualLevel)insertSuspendedBy(asyncInfo);continue}if(typeof debugEntry.name!=="string")continue;var componentInfo=debugEntry,secondaryEnv=getSecondaryEnvironmentName(nextChild._debugInfo,i);if(componentInfo.env!=null)knownEnvironmentNames.add(componentInfo.env);if(secondaryEnv!==null)knownEnvironmentNames.add(secondaryEnv);if(shouldFilterVirtual(componentInfo,secondaryEnv))continue;if(level===virtualLevel){if(previousVirtualInstance===null||previousVirtualInstance.data!==componentInfo){if(previousVirtualInstance!==null)if(previousVirtualInstanceWasMount)mountVirtualInstanceRecursively(previousVirtualInstance,previousVirtualInstanceNextFirstFiber,nextChild,traceNearestHostComponentUpdate,virtualLevel),updateFlags|=ShouldResetChildren|ShouldResetSuspenseChildren;else updateFlags|=updateVirtualInstanceRecursively(previousVirtualInstance,previousVirtualInstanceNextFirstFiber,nextChild,previousVirtualInstancePrevFirstFiber,traceNearestHostComponentUpdate,virtualLevel);var previousSiblingOfBestMatch=null,bestMatch=remainingReconcilingChildren;if(componentInfo.key!=null){bestMatch=remainingReconcilingChildren;while(bestMatch!==null){if(bestMatch.kind===VIRTUAL_INSTANCE&&bestMatch.data.key===componentInfo.key)break;previousSiblingOfBestMatch=bestMatch,bestMatch=bestMatch.nextSibling}}if(bestMatch!==null&&bestMatch.kind===VIRTUAL_INSTANCE&&bestMatch.data.name===componentInfo.name&&bestMatch.data.env===componentInfo.env&&bestMatch.data.key===componentInfo.key)bestMatch.data=componentInfo,moveChild(bestMatch,previousSiblingOfBestMatch),previousVirtualInstance=bestMatch,previousVirtualInstanceWasMount=!1;else{var newVirtualInstance=createVirtualInstance(componentInfo);recordVirtualMount(newVirtualInstance,reconcilingParent,secondaryEnv),insertChild(newVirtualInstance),previousVirtualInstance=newVirtualInstance,previousVirtualInstanceWasMount=!0,updateFlags|=ShouldResetChildren}previousVirtualInstanceNextFirstFiber=nextChild,previousVirtualInstancePrevFirstFiber=prevChildAtSameIndex}level++;break}else level++}if(level===virtualLevel){if(previousVirtualInstance!==null){if(previousVirtualInstanceWasMount)mountVirtualInstanceRecursively(previousVirtualInstance,previousVirtualInstanceNextFirstFiber,nextChild,traceNearestHostComponentUpdate,virtualLevel),updateFlags|=ShouldResetChildren|ShouldResetSuspenseChildren;else updateFlags|=updateVirtualInstanceRecursively(previousVirtualInstance,previousVirtualInstanceNextFirstFiber,nextChild,previousVirtualInstancePrevFirstFiber,traceNearestHostComponentUpdate,virtualLevel);previousVirtualInstance=null}var prevChild=void 0;if(prevChildAtSameIndex===nextChild)prevChild=nextChild;else prevChild=nextChild.alternate;var previousSiblingOfExistingInstance=null,existingInstance=null;if(prevChild!==null){existingInstance=remainingReconcilingChildren;while(existingInstance!==null){if(existingInstance.data===prevChild)break;previousSiblingOfExistingInstance=existingInstance,existingInstance=existingInstance.nextSibling}}if(existingInstance!==null){var fiberInstance=existingInstance;if(prevChild!==prevChildAtSameIndex)updateFlags|=ShouldResetChildren|ShouldResetSuspenseChildren;moveChild(fiberInstance,previousSiblingOfExistingInstance),updateFlags|=updateFiberRecursively(fiberInstance,nextChild,prevChild,traceNearestHostComponentUpdate)}else if(prevChild!==null&&shouldFilterFiber(nextChild)){if(prevChild!==prevChildAtSameIndex)updateFlags|=ShouldResetChildren|ShouldResetSuspenseChildren;updateFlags|=updateFiberRecursively(null,nextChild,prevChild,traceNearestHostComponentUpdate)}else mountFiberRecursively(nextChild,traceNearestHostComponentUpdate),updateFlags|=ShouldResetChildren|ShouldResetSuspenseChildren}if(nextChild=nextChild.sibling,(updateFlags&ShouldResetChildren)===NoUpdate&&prevChildAtSameIndex!==null)prevChildAtSameIndex=prevChildAtSameIndex.sibling}if(previousVirtualInstance!==null)if(previousVirtualInstanceWasMount)mountVirtualInstanceRecursively(previousVirtualInstance,previousVirtualInstanceNextFirstFiber,null,traceNearestHostComponentUpdate,virtualLevel),updateFlags|=ShouldResetChildren|ShouldResetSuspenseChildren;else updateFlags|=updateVirtualInstanceRecursively(previousVirtualInstance,previousVirtualInstanceNextFirstFiber,null,previousVirtualInstancePrevFirstFiber,traceNearestHostComponentUpdate,virtualLevel);if(prevChildAtSameIndex!==null)updateFlags|=ShouldResetChildren|ShouldResetSuspenseChildren;return updateFlags}function updateChildrenRecursively(nextFirstChild,prevFirstChild,traceNearestHostComponentUpdate){if(nextFirstChild===null)return prevFirstChild!==null?ShouldResetChildren:NoUpdate;return updateVirtualChildrenRecursively(nextFirstChild,null,prevFirstChild,traceNearestHostComponentUpdate,0)}function updateSuspenseChildrenRecursively(nextContentFiber,prevContentFiber,traceNearestHostComponentUpdate,stashedSuspenseParent,stashedSuspensePrevious,stashedSuspenseRemaining){var updateFlags=NoUpdate,prevFallbackFiber=prevContentFiber.sibling,nextFallbackFiber=nextContentFiber.sibling;if(updateFlags|=updateVirtualChildrenRecursively(nextContentFiber,nextFallbackFiber,prevContentFiber,traceNearestHostComponentUpdate,0),reconcilingParentSuspenseNode=stashedSuspenseParent,previouslyReconciledSiblingSuspenseNode=stashedSuspensePrevious,remainingReconcilingChildrenSuspenseNodes=stashedSuspenseRemaining,prevFallbackFiber!==null||nextFallbackFiber!==null){if(nextFallbackFiber===null)unmountRemainingChildren();else if(updateFlags|=updateVirtualChildrenRecursively(nextFallbackFiber,null,prevFallbackFiber,traceNearestHostComponentUpdate,0),(updateFlags&ShouldResetSuspenseChildren)!==NoUpdate)updateFlags|=ShouldResetParentSuspenseChildren,updateFlags&=~ShouldResetSuspenseChildren}return updateFlags}function updateFiberRecursively(fiberInstance,nextFiber,prevFiber,traceNearestHostComponentUpdate){if(__DEBUG__){if(fiberInstance!==null)debug2("updateFiberRecursively()",fiberInstance,reconcilingParent)}if(traceUpdatesEnabled){var elementType=getElementTypeForFiber(nextFiber);if(traceNearestHostComponentUpdate){if(elementType===ElementTypeHostComponent)traceUpdatesForNodes.add(nextFiber.stateNode),traceNearestHostComponentUpdate=!1}else if(elementType===types_ElementTypeFunction||elementType===types_ElementTypeClass||elementType===ElementTypeContext||elementType===types_ElementTypeMemo||elementType===types_ElementTypeForwardRef)traceNearestHostComponentUpdate=didFiberRender(prevFiber,nextFiber)}var stashedParent=reconcilingParent,stashedPrevious=previouslyReconciledSibling,stashedRemaining=remainingReconcilingChildren,stashedSuspenseParent=reconcilingParentSuspenseNode,stashedSuspensePrevious=previouslyReconciledSiblingSuspenseNode,stashedSuspenseRemaining=remainingReconcilingChildrenSuspenseNodes,updateFlags=NoUpdate,shouldMeasureSuspenseNode=!1,shouldPopSuspenseNode=!1,previousSuspendedBy=null;if(fiberInstance!==null){if(previousSuspendedBy=fiberInstance.suspendedBy,fiberInstance.data=nextFiber,mostRecentlyInspectedElement!==null&&(mostRecentlyInspectedElement.id===fiberInstance.id||mostRecentlyInspectedElement.type===ElementTypeRoot&&nextFiber.tag===HostRoot)&&didFiberRender(prevFiber,nextFiber))hasElementUpdatedSinceLastInspected=!0;reconcilingParent=fiberInstance,previouslyReconciledSibling=null,remainingReconcilingChildren=fiberInstance.firstChild,fiberInstance.firstChild=null,fiberInstance.suspendedBy=null;var suspenseNode=fiberInstance.suspenseNode;if(suspenseNode!==null)reconcilingParentSuspenseNode=suspenseNode,previouslyReconciledSiblingSuspenseNode=null,remainingReconcilingChildrenSuspenseNodes=suspenseNode.firstChild,suspenseNode.firstChild=null,shouldMeasureSuspenseNode=!0,shouldPopSuspenseNode=!0}try{if(trackDebugInfoFromLazyType(nextFiber),trackDebugInfoFromUsedThenables(nextFiber),nextFiber.tag===HostHoistable){var nearestInstance=reconcilingParent;if(nearestInstance===null)throw Error("Did not expect a host hoistable to be the root");if(prevFiber.memoizedState!==nextFiber.memoizedState)releaseHostResource(nearestInstance,prevFiber.memoizedState),aquireHostResource(nearestInstance,nextFiber.memoizedState);trackDebugInfoFromHostResource(nearestInstance,nextFiber)}else if(nextFiber.tag===HostComponent||nextFiber.tag===HostText||nextFiber.tag===HostSingleton){var _nearestInstance2=reconcilingParent;if(_nearestInstance2===null)throw Error("Did not expect a host hoistable to be the root");if(prevFiber.stateNode!==nextFiber.stateNode)releaseHostInstance(_nearestInstance2,prevFiber.stateNode),aquireHostInstance(_nearestInstance2,nextFiber.stateNode);trackDebugInfoFromHostComponent(_nearestInstance2,nextFiber)}var isLegacySuspense=nextFiber.tag===SuspenseComponent&&OffscreenComponent===-1,prevDidTimeout=isLegacySuspense&&prevFiber.memoizedState!==null,nextDidTimeOut=isLegacySuspense&&nextFiber.memoizedState!==null,prevWasHidden=isHiddenOffscreen(prevFiber),nextIsHidden=isHiddenOffscreen(nextFiber),prevWasSuspended=isSuspendedOffscreen(prevFiber),nextIsSuspended=isSuspendedOffscreen(nextFiber);if(isLegacySuspense){if(fiberInstance!==null&&fiberInstance.suspenseNode!==null){var _suspenseNode=fiberInstance.suspenseNode;if(prevFiber.stateNode===null!==(nextFiber.stateNode===null))trackThrownPromisesFromRetryCache(_suspenseNode,nextFiber.stateNode);if(prevFiber.memoizedState===null!==(nextFiber.memoizedState===null))recordSuspenseSuspenders(_suspenseNode)}}if(prevDidTimeout&&nextDidTimeOut){var nextFiberChild=nextFiber.child,nextFallbackChildSet=nextFiberChild?nextFiberChild.sibling:null,prevFiberChild=prevFiber.child,prevFallbackChildSet=prevFiberChild?prevFiberChild.sibling:null;if(prevFallbackChildSet==null&&nextFallbackChildSet!=null)mountChildrenRecursively(nextFallbackChildSet,traceNearestHostComponentUpdate),updateFlags|=ShouldResetChildren|ShouldResetSuspenseChildren;var childrenUpdateFlags=nextFallbackChildSet!=null&&prevFallbackChildSet!=null?updateChildrenRecursively(nextFallbackChildSet,prevFallbackChildSet,traceNearestHostComponentUpdate):NoUpdate;updateFlags|=childrenUpdateFlags}else if(prevDidTimeout&&!nextDidTimeOut){var nextPrimaryChildSet=nextFiber.child;if(nextPrimaryChildSet!==null)mountChildrenRecursively(nextPrimaryChildSet,traceNearestHostComponentUpdate),updateFlags|=ShouldResetChildren|ShouldResetSuspenseChildren}else if(!prevDidTimeout&&nextDidTimeOut){var _nextFiberChild=nextFiber.child,_nextFallbackChildSet=_nextFiberChild?_nextFiberChild.sibling:null;if(_nextFallbackChildSet!=null)mountChildrenRecursively(_nextFallbackChildSet,traceNearestHostComponentUpdate),updateFlags|=ShouldResetChildren|ShouldResetSuspenseChildren}else if(nextIsSuspended){if(!prevWasSuspended){if(fiberInstance!==null&&!isInDisconnectedSubtree)disconnectChildrenRecursively(remainingReconcilingChildren)}var stashedDisconnected=isInDisconnectedSubtree;isInDisconnectedSubtree=!0;try{updateFlags|=updateChildrenRecursively(nextFiber.child,prevFiber.child,!1)}finally{isInDisconnectedSubtree=stashedDisconnected}}else if(prevWasSuspended&&!nextIsSuspended){var _stashedDisconnected=isInDisconnectedSubtree;isInDisconnectedSubtree=!0;try{if(nextFiber.child!==null)updateFlags|=updateChildrenRecursively(nextFiber.child,prevFiber.child,!1);unmountRemainingChildren(),remainingReconcilingChildren=null}finally{isInDisconnectedSubtree=_stashedDisconnected}if(fiberInstance!==null&&!isInDisconnectedSubtree)reconnectChildrenRecursively(fiberInstance),updateFlags|=ShouldResetChildren|ShouldResetSuspenseChildren}else if(nextIsHidden)if(prevWasHidden);else unmountRemainingChildren();else if(nextFiber.tag===SuspenseComponent&&OffscreenComponent!==-1&&fiberInstance!==null&&fiberInstance.suspenseNode!==null){var _suspenseNode2=fiberInstance.suspenseNode,prevContentFiber=prevFiber.child,nextContentFiber=nextFiber.child,previousHydrated=isFiberHydrated(prevFiber),nextHydrated=isFiberHydrated(nextFiber);if(previousHydrated&&nextHydrated){if(nextContentFiber===null||prevContentFiber===null)throw Error("There should always be an Offscreen Fiber child in a hydrated Suspense boundary.");if(prevFiber.stateNode===null!==(nextFiber.stateNode===null))trackThrownPromisesFromRetryCache(_suspenseNode2,nextFiber.stateNode);if(prevFiber.memoizedState===null!==(nextFiber.memoizedState===null))recordSuspenseSuspenders(_suspenseNode2);if(shouldMeasureSuspenseNode=!1,updateFlags|=updateSuspenseChildrenRecursively(nextContentFiber,prevContentFiber,traceNearestHostComponentUpdate,stashedSuspenseParent,stashedSuspensePrevious,stashedSuspenseRemaining),shouldPopSuspenseNode=!1,nextFiber.memoizedState===null)shouldMeasureSuspenseNode=!isInDisconnectedSubtree}else if(!previousHydrated&&nextHydrated){if(nextContentFiber===null)throw Error("There should always be an Offscreen Fiber child in a hydrated Suspense boundary.");trackThrownPromisesFromRetryCache(_suspenseNode2,nextFiber.stateNode),recordSuspenseSuspenders(_suspenseNode2),mountSuspenseChildrenRecursively(nextContentFiber,traceNearestHostComponentUpdate,stashedSuspenseParent,stashedSuspensePrevious,stashedSuspenseRemaining),shouldPopSuspenseNode=!1}else if(previousHydrated&&!nextHydrated)throw Error("Encountered a dehydrated Suspense boundary that was previously hydrated.")}else if(nextFiber.child!==prevFiber.child)updateFlags|=updateChildrenRecursively(nextFiber.child,prevFiber.child,traceNearestHostComponentUpdate);else if(fiberInstance!==null){if(fiberInstance.firstChild=remainingReconcilingChildren,remainingReconcilingChildren=null,consumeSuspenseNodesOfExistingInstance(fiberInstance),traceUpdatesEnabled){if(traceNearestHostComponentUpdate){var hostInstances=findAllCurrentHostInstances(fiberInstance);hostInstances.forEach(function(hostInstance){traceUpdatesForNodes.add(hostInstance)})}}}else{var _childrenUpdateFlags=updateChildrenRecursively(nextFiber.child,prevFiber.child,!1);if((_childrenUpdateFlags&ShouldResetChildren)!==NoUpdate)throw Error("The children should not have changed if we pass in the same set.");updateFlags|=_childrenUpdateFlags}if(fiberInstance!==null){if(removePreviousSuspendedBy(fiberInstance,previousSuspendedBy,shouldPopSuspenseNode?reconcilingParentSuspenseNode:stashedSuspenseParent),fiberInstance.kind===FIBER_INSTANCE){var componentLogsEntry=fiberToComponentLogsMap.get(fiberInstance.data);if(componentLogsEntry===void 0&&fiberInstance.data.alternate)componentLogsEntry=fiberToComponentLogsMap.get(fiberInstance.data.alternate);recordConsoleLogs(fiberInstance,componentLogsEntry);var isProfilingSupported=nextFiber.hasOwnProperty("treeBaseDuration");if(isProfilingSupported)recordProfilingDurations(fiberInstance,prevFiber)}}if((updateFlags&ShouldResetChildren)!==NoUpdate){if(fiberInstance!==null&&fiberInstance.kind===FIBER_INSTANCE){if(!nextIsSuspended&&!isInDisconnectedSubtree)recordResetChildren(fiberInstance);updateFlags&=~ShouldResetChildren}}if((updateFlags&ShouldResetSuspenseChildren)!==NoUpdate){if(fiberInstance!==null&&fiberInstance.kind===FIBER_INSTANCE){var _suspenseNode3=fiberInstance.suspenseNode;if(_suspenseNode3!==null)recordResetSuspenseChildren(_suspenseNode3),updateFlags&=~ShouldResetSuspenseChildren}}if((updateFlags&ShouldResetParentSuspenseChildren)!==NoUpdate){if(fiberInstance!==null&&fiberInstance.kind===FIBER_INSTANCE){var _suspenseNode4=fiberInstance.suspenseNode;if(_suspenseNode4!==null)updateFlags&=~ShouldResetParentSuspenseChildren,updateFlags|=ShouldResetSuspenseChildren}}return updateFlags}finally{if(fiberInstance!==null){if(unmountRemainingChildren(),reconcilingParent=stashedParent,previouslyReconciledSibling=stashedPrevious,remainingReconcilingChildren=stashedRemaining,shouldMeasureSuspenseNode){if(!isInDisconnectedSubtree){var _suspenseNode5=fiberInstance.suspenseNode;if(_suspenseNode5===null)throw Error("Attempted to measure a Suspense node that does not exist.");var prevRects=_suspenseNode5.rects,nextRects=measureInstance(fiberInstance);if(!areEqualRects(prevRects,nextRects))_suspenseNode5.rects=nextRects,recordSuspenseResize(_suspenseNode5)}}if(shouldPopSuspenseNode)reconcilingParentSuspenseNode=stashedSuspenseParent,previouslyReconciledSiblingSuspenseNode=stashedSuspensePrevious,remainingReconcilingChildrenSuspenseNodes=stashedSuspenseRemaining}}}function disconnectChildrenRecursively(firstChild){for(var child=firstChild;child!==null;child=child.nextSibling){if((child.kind===FIBER_INSTANCE||child.kind===FILTERED_FIBER_INSTANCE)&&isSuspendedOffscreen(child.data));else disconnectChildrenRecursively(child.firstChild);if(child.kind===FIBER_INSTANCE)recordDisconnect(child);else if(child.kind===VIRTUAL_INSTANCE)recordVirtualDisconnect(child)}}function reconnectChildrenRecursively(parentInstance){for(var child=parentInstance.firstChild;child!==null;child=child.nextSibling){if(child.kind===FIBER_INSTANCE)recordReconnect(child,parentInstance);else if(child.kind===VIRTUAL_INSTANCE){var secondaryEnv=null;recordVirtualReconnect(child,parentInstance,secondaryEnv)}if((child.kind===FIBER_INSTANCE||child.kind===FILTERED_FIBER_INSTANCE)&&isHiddenOffscreen(child.data));else reconnectChildrenRecursively(child)}}function cleanup(){isProfiling=!1}function rootSupportsProfiling(root){if(root.memoizedInteractions!=null)return!0;else if(root.current!=null&&root.current.hasOwnProperty("treeBaseDuration"))return!0;else return!1}function flushInitialOperations(){var localPendingOperationsQueue=pendingOperationsQueue;if(pendingOperationsQueue=null,localPendingOperationsQueue!==null&&localPendingOperationsQueue.length>0)localPendingOperationsQueue.forEach(function(operations){hook.emit("operations",operations)});else{if(trackedPath!==null)mightBeOnTrackedPath=!0;hook.getFiberRoots(rendererID).forEach(function(root){var current=root.current,newRoot=createFiberInstance(current);if(rootToFiberInstanceMap.set(root,newRoot),idToDevToolsInstanceMap.set(newRoot.id,newRoot),currentRoot=newRoot,setRootPseudoKey(currentRoot.id,root.current),isProfiling&&rootSupportsProfiling(root))currentCommitProfilingMetadata={changeDescriptions:recordChangeDescriptions?new Map:null,durations:[],commitTime:renderer_getCurrentTime()-profilingStartTime,maxActualDuration:0,priorityLevel:null,updaters:null,effectDuration:null,passiveEffectDuration:null};mountFiberRecursively(root.current,!1),flushPendingEvents(),needsToFlushComponentLogs=!1,currentRoot=null})}}function handleCommitFiberUnmount(fiber){}function handlePostCommitFiberRoot(root){if(isProfiling&&rootSupportsProfiling(root)){if(currentCommitProfilingMetadata!==null){var _getEffectDurations=getEffectDurations(root),effectDuration=_getEffectDurations.effectDuration,passiveEffectDuration=_getEffectDurations.passiveEffectDuration;currentCommitProfilingMetadata.effectDuration=effectDuration,currentCommitProfilingMetadata.passiveEffectDuration=passiveEffectDuration}}if(needsToFlushComponentLogs)bruteForceFlushErrorsAndWarnings()}function handleCommitFiberRoot(root,priorityLevel){var nextFiber=root.current,prevFiber=null,rootInstance=rootToFiberInstanceMap.get(root);if(!rootInstance)rootInstance=createFiberInstance(nextFiber),rootToFiberInstanceMap.set(root,rootInstance),idToDevToolsInstanceMap.set(rootInstance.id,rootInstance);else prevFiber=rootInstance.data;if(currentRoot=rootInstance,trackedPath!==null)mightBeOnTrackedPath=!0;if(traceUpdatesEnabled)traceUpdatesForNodes.clear();var isProfilingSupported=rootSupportsProfiling(root);if(isProfiling&&isProfilingSupported)currentCommitProfilingMetadata={changeDescriptions:recordChangeDescriptions?new Map:null,durations:[],commitTime:renderer_getCurrentTime()-profilingStartTime,maxActualDuration:0,priorityLevel:priorityLevel==null?null:formatPriorityLevel(priorityLevel),updaters:null,effectDuration:null,passiveEffectDuration:null};var nextIsMounted=nextFiber.child!==null,prevWasMounted=prevFiber!==null&&prevFiber.child!==null;if(!prevWasMounted&&nextIsMounted)setRootPseudoKey(currentRoot.id,nextFiber),mountFiberRecursively(nextFiber,!1);else if(prevWasMounted&&nextIsMounted){if(prevFiber===null)throw Error("Expected a previous Fiber when updating an existing root.");updateFiberRecursively(rootInstance,nextFiber,prevFiber,!1)}else if(prevWasMounted&&!nextIsMounted)unmountInstanceRecursively(rootInstance),removeRootPseudoKey(currentRoot.id),rootToFiberInstanceMap.delete(root);else if(!prevWasMounted&&!nextIsMounted)rootToFiberInstanceMap.delete(root);if(isProfiling&&isProfilingSupported){if(!shouldBailoutWithPendingOperations()){var commitProfilingMetadata=rootToCommitProfilingMetadataMap.get(currentRoot.id);if(commitProfilingMetadata!=null)commitProfilingMetadata.push(currentCommitProfilingMetadata);else rootToCommitProfilingMetadataMap.set(currentRoot.id,[currentCommitProfilingMetadata])}}if(flushPendingEvents(),needsToFlushComponentLogs=!1,traceUpdatesEnabled)hook.emit("traceUpdates",traceUpdatesForNodes);currentRoot=null}function getResourceInstance(fiber){if(fiber.tag===HostHoistable){var resource=fiber.memoizedState;if(renderer_typeof(resource)==="object"&&resource!==null&&resource.instance!=null)return resource.instance}return null}function appendHostInstancesByDevToolsInstance(devtoolsInstance,hostInstances){if(devtoolsInstance.kind!==VIRTUAL_INSTANCE){var _fiber6=devtoolsInstance.data;appendHostInstancesByFiber(_fiber6,hostInstances);return}for(var child=devtoolsInstance.firstChild;child!==null;child=child.nextSibling)appendHostInstancesByDevToolsInstance(child,hostInstances)}function appendHostInstancesByFiber(fiber,hostInstances){var node=fiber;while(!0){if(node.tag===HostComponent||node.tag===HostText||node.tag===HostSingleton||node.tag===HostHoistable){var hostInstance=node.stateNode||getResourceInstance(node);if(hostInstance)hostInstances.push(hostInstance)}else if(node.child){node.child.return=node,node=node.child;continue}if(node===fiber)return;while(!node.sibling){if(!node.return||node.return===fiber)return;node=node.return}node.sibling.return=node.return,node=node.sibling}}function findAllCurrentHostInstances(devtoolsInstance){var hostInstances=[];return appendHostInstancesByDevToolsInstance(devtoolsInstance,hostInstances),hostInstances}function findHostInstancesForElementID(id){try{var devtoolsInstance=idToDevToolsInstanceMap.get(id);if(devtoolsInstance===void 0)return console.warn('Could not find DevToolsInstance with id "'.concat(id,'"')),null;return findAllCurrentHostInstances(devtoolsInstance)}catch(err){return null}}function findLastKnownRectsForID(id){try{var devtoolsInstance=idToDevToolsInstanceMap.get(id);if(devtoolsInstance===void 0)return console.warn('Could not find DevToolsInstance with id "'.concat(id,'"')),null;if(devtoolsInstance.suspenseNode===null)return null;return devtoolsInstance.suspenseNode.rects}catch(err){return null}}function getDisplayNameForElementID(id){var devtoolsInstance=idToDevToolsInstanceMap.get(id);if(devtoolsInstance===void 0)return null;if(devtoolsInstance.kind===FIBER_INSTANCE){var _fiber7=devtoolsInstance.data;if(_fiber7.tag===HostRoot)return"Initial Paint";if(_fiber7.tag===SuspenseComponent||_fiber7.tag===ActivityComponent){var props=_fiber7.memoizedProps;if(props.name!=null)return props.name;var owner=getUnfilteredOwner(_fiber7);if(owner!=null)if(typeof owner.tag==="number")return getDisplayNameForFiber(owner);else return owner.name||""}return getDisplayNameForFiber(_fiber7)}else return devtoolsInstance.data.name||""}function getNearestSuspenseNode(instance){while(instance.suspenseNode===null){if(instance.parent===null)throw Error("There should always be a SuspenseNode parent on a mounted instance.");instance=instance.parent}return instance.suspenseNode}function getNearestMountedDOMNode(publicInstance){var domNode=publicInstance;while(domNode&&!publicInstanceToDevToolsInstanceMap.has(domNode))domNode=domNode.parentNode;return domNode}function getElementIDForHostInstance(publicInstance){var instance=publicInstanceToDevToolsInstanceMap.get(publicInstance);if(instance!==void 0){if(instance.kind===FILTERED_FIBER_INSTANCE)return instance.parent.id;return instance.id}return null}function getSuspenseNodeIDForHostInstance(publicInstance){var instance=publicInstanceToDevToolsInstanceMap.get(publicInstance);if(instance!==void 0){var suspenseInstance=instance;while(suspenseInstance.suspenseNode===null||suspenseInstance.kind===FILTERED_FIBER_INSTANCE){if(suspenseInstance.parent===null)return null;suspenseInstance=suspenseInstance.parent}return suspenseInstance.id}return null}function getElementAttributeByPath(id,path){if(isMostRecentlyInspectedElement(id))return utils_getInObject(mostRecentlyInspectedElement,path);return}function getElementSourceFunctionById(id){var devtoolsInstance=idToDevToolsInstanceMap.get(id);if(devtoolsInstance===void 0)return console.warn('Could not find DevToolsInstance with id "'.concat(id,'"')),null;if(devtoolsInstance.kind!==FIBER_INSTANCE)return null;var fiber=devtoolsInstance.data,elementType=fiber.elementType,tag=fiber.tag,type=fiber.type;switch(tag){case ClassComponent:case IncompleteClassComponent:case IncompleteFunctionComponent:case IndeterminateComponent:case FunctionComponent:return type;case ForwardRef:return type.render;case MemoComponent:case SimpleMemoComponent:return elementType!=null&&elementType.type!=null?elementType.type:type;default:return null}}function instanceToSerializedElement(instance){if(instance.kind===FIBER_INSTANCE){var _fiber8=instance.data;return{displayName:getDisplayNameForFiber(_fiber8)||"Anonymous",id:instance.id,key:_fiber8.key,env:null,stack:_fiber8._debugOwner==null||_fiber8._debugStack==null?null:parseStackTrace(_fiber8._debugStack,1),type:getElementTypeForFiber(_fiber8)}}else{var componentInfo=instance.data;return{displayName:componentInfo.name||"Anonymous",id:instance.id,key:componentInfo.key==null?null:componentInfo.key,env:componentInfo.env==null?null:componentInfo.env,stack:componentInfo.owner==null||componentInfo.debugStack==null?null:parseStackTrace(componentInfo.debugStack,1),type:types_ElementTypeVirtual}}}function getOwnersList(id){var devtoolsInstance=idToDevToolsInstanceMap.get(id);if(devtoolsInstance===void 0)return console.warn('Could not find DevToolsInstance with id "'.concat(id,'"')),null;var self2=instanceToSerializedElement(devtoolsInstance),owners=getOwnersListFromInstance(devtoolsInstance);if(owners===null)return[self2];return owners.unshift(self2),owners.reverse(),owners}function getOwnersListFromInstance(instance){var owner=getUnfilteredOwner(instance.data);if(owner===null)return null;var owners=[],parentInstance=instance.parent;while(parentInstance!==null&&owner!==null){var ownerInstance=findNearestOwnerInstance(parentInstance,owner);if(ownerInstance!==null)owners.push(instanceToSerializedElement(ownerInstance)),owner=getUnfilteredOwner(owner),parentInstance=ownerInstance.parent;else break}return owners}function getUnfilteredOwner(owner){if(owner==null)return null;if(typeof owner.tag==="number"){var ownerFiber=owner;owner=ownerFiber._debugOwner}else{var ownerInfo=owner;owner=ownerInfo.owner}while(owner)if(typeof owner.tag==="number"){var _ownerFiber=owner;if(!shouldFilterFiber(_ownerFiber))return _ownerFiber;owner=_ownerFiber._debugOwner}else{var _ownerInfo=owner;if(!shouldFilterVirtual(_ownerInfo,null))return _ownerInfo;owner=_ownerInfo.owner}return null}function findNearestOwnerInstance(parentInstance,owner){if(owner==null)return null;while(parentInstance!==null){if(parentInstance.data===owner||parentInstance.data===owner.alternate){if(parentInstance.kind===FILTERED_FIBER_INSTANCE)return null;return parentInstance}parentInstance=parentInstance.parent}return null}function inspectHooks(fiber){var originalConsoleMethods={};for(var method in console)try{originalConsoleMethods[method]=console[method],console[method]=function(){}}catch(error){}try{return(0,react_debug_tools.inspectHooksOfFiber)(fiber,getDispatcherRef(renderer))}finally{for(var _method in originalConsoleMethods)try{console[_method]=originalConsoleMethods[_method]}catch(error){}}}function getSuspendedByOfSuspenseNode(suspenseNode,filterByChildInstance){var result=[];if(!suspenseNode.hasUniqueSuspenders)return result;var hooksCacheKey=null,hooksCache=null,streamEntries=new Map;return suspenseNode.suspendedBy.forEach(function(set,ioInfo){var parentNode=suspenseNode.parent;while(parentNode!==null){if(parentNode.suspendedBy.has(ioInfo))return;parentNode=parentNode.parent}if(set.size===0)return;var firstInstance=null;if(filterByChildInstance===null)firstInstance=set.values().next().value;else{var _iterator7=_createForOfIteratorHelper(set.values()),_step7;try{for(_iterator7.s();!(_step7=_iterator7.n()).done;){var childInstance=_step7.value;if(firstInstance===null)firstInstance=childInstance;if(childInstance!==filterByChildInstance&&!isChildOf(filterByChildInstance,childInstance,suspenseNode.instance))return}}catch(err){_iterator7.e(err)}finally{_iterator7.f()}}if(firstInstance!==null&&firstInstance.suspendedBy!==null){var asyncInfo=getAwaitInSuspendedByFromIO(firstInstance.suspendedBy,ioInfo);if(asyncInfo!==null){var hooks=null;if(asyncInfo.stack==null&&asyncInfo.owner==null){if(hooksCacheKey===firstInstance)hooks=hooksCache;else if(firstInstance.kind!==VIRTUAL_INSTANCE){var _fiber9=firstInstance.data;if(_fiber9.dependencies&&_fiber9.dependencies._debugThenableState)hooksCacheKey=firstInstance,hooksCache=hooks=inspectHooks(_fiber9)}}var newIO=asyncInfo.awaited;if((newIO.name==="RSC stream"||newIO.name==="rsc stream")&&newIO.value!=null){var streamPromise=newIO.value,existingEntry=streamEntries.get(streamPromise);if(existingEntry===void 0)streamEntries.set(streamPromise,{asyncInfo,instance:firstInstance,hooks});else{var existingIO=existingEntry.asyncInfo.awaited;if(newIO!==existingIO&&(newIO.byteSize!==void 0&&existingIO.byteSize!==void 0&&newIO.byteSize>existingIO.byteSize||newIO.end>existingIO.end))existingEntry.asyncInfo=asyncInfo,existingEntry.instance=firstInstance,existingEntry.hooks=hooks}}else result.push(serializeAsyncInfo(asyncInfo,firstInstance,hooks))}}}),streamEntries.forEach(function(_ref){var{asyncInfo,instance,hooks}=_ref;result.push(serializeAsyncInfo(asyncInfo,instance,hooks))}),result}function getSuspendedByOfInstance(devtoolsInstance,hooks){var suspendedBy=devtoolsInstance.suspendedBy;if(suspendedBy===null)return[];var foundIOEntries=new Set,streamEntries=new Map,result=[];for(var i=0;i<suspendedBy.length;i++){var asyncInfo=suspendedBy[i],ioInfo=asyncInfo.awaited;if(foundIOEntries.has(ioInfo))continue;if(foundIOEntries.add(ioInfo),(ioInfo.name==="RSC stream"||ioInfo.name==="rsc stream")&&ioInfo.value!=null){var streamPromise=ioInfo.value,existingEntry=streamEntries.get(streamPromise);if(existingEntry===void 0)streamEntries.set(streamPromise,asyncInfo);else{var existingIO=existingEntry.awaited;if(ioInfo!==existingIO&&(ioInfo.byteSize!==void 0&&existingIO.byteSize!==void 0&&ioInfo.byteSize>existingIO.byteSize||ioInfo.end>existingIO.end))streamEntries.set(streamPromise,asyncInfo)}}else result.push(serializeAsyncInfo(asyncInfo,devtoolsInstance,hooks))}return streamEntries.forEach(function(asyncInfo2){result.push(serializeAsyncInfo(asyncInfo2,devtoolsInstance,hooks))}),result}function getSuspendedByOfInstanceSubtree(devtoolsInstance){var suspenseParentInstance=devtoolsInstance;while(suspenseParentInstance.suspenseNode===null){if(suspenseParentInstance.parent===null)return[];suspenseParentInstance=suspenseParentInstance.parent}var suspenseNode=suspenseParentInstance.suspenseNode;return getSuspendedByOfSuspenseNode(suspenseNode,devtoolsInstance)}var FALLBACK_THROTTLE_MS=300;function getSuspendedByRange(suspenseNode){var min=1/0,max=-1/0;suspenseNode.suspendedBy.forEach(function(_2,ioInfo){if(ioInfo.end>max)max=ioInfo.end;if(ioInfo.start<min)min=ioInfo.start});var parentSuspenseNode=suspenseNode.parent;if(parentSuspenseNode!==null){var parentMax=-1/0;parentSuspenseNode.suspendedBy.forEach(function(_2,ioInfo){if(ioInfo.end>parentMax)parentMax=ioInfo.end});var throttleTime=parentMax+FALLBACK_THROTTLE_MS;if(throttleTime>max)max=throttleTime;var startTime=max-FALLBACK_THROTTLE_MS;if(parentMax>startTime)startTime=parentMax;if(startTime<min)min=startTime}if(min<1/0&&max>-1/0)return[min,max];return null}function getAwaitStackFromHooks(hooks,asyncInfo){for(var i=0;i<hooks.length;i++){var node=hooks[i],debugInfo=node.debugInfo;if(debugInfo!=null&&debugInfo.indexOf(asyncInfo)!==-1){var source=node.hookSource;if(source!=null&&source.functionName!==null&&source.fileName!==null&&source.lineNumber!==null&&source.columnNumber!==null){var callSite=[source.functionName,source.fileName,source.lineNumber,source.columnNumber,0,0,!1];return[callSite]}else return[]}var matchedStack=getAwaitStackFromHooks(node.subHooks,asyncInfo);if(matchedStack!==null){var _source=node.hookSource;if(_source!=null&&_source.functionName!==null&&_source.fileName!==null&&_source.lineNumber!==null&&_source.columnNumber!==null){var _callSite=[_source.functionName,_source.fileName,_source.lineNumber,_source.columnNumber,0,0,!1];matchedStack.push(_callSite)}return matchedStack}}return null}function serializeAsyncInfo(asyncInfo,parentInstance,hooks){var ioInfo=asyncInfo.awaited,ioOwnerInstance=findNearestOwnerInstance(parentInstance,ioInfo.owner),awaitStack=asyncInfo.debugStack==null?null:parseStackTrace(asyncInfo.debugStack,1),awaitOwnerInstance;if(asyncInfo.owner==null&&(awaitStack===null||awaitStack.length===0)){if(awaitStack=null,awaitOwnerInstance=parentInstance.kind===FILTERED_FIBER_INSTANCE?null:parentInstance,parentInstance.kind===FIBER_INSTANCE||parentInstance.kind===FILTERED_FIBER_INSTANCE){var _fiber10=parentInstance.data;switch(_fiber10.tag){case ClassComponent:case FunctionComponent:case IncompleteClassComponent:case IncompleteFunctionComponent:case IndeterminateComponent:case MemoComponent:case SimpleMemoComponent:if(hooks!==null)awaitStack=getAwaitStackFromHooks(hooks,asyncInfo);break;default:if(_fiber10._debugOwner!=null&&_fiber10._debugStack!=null&&typeof _fiber10._debugStack!=="string")awaitStack=parseStackTrace(_fiber10._debugStack,1),awaitOwnerInstance=findNearestOwnerInstance(parentInstance,_fiber10._debugOwner)}}}else awaitOwnerInstance=findNearestOwnerInstance(parentInstance,asyncInfo.owner);var value=ioInfo.value,resolvedValue=void 0;if(renderer_typeof(value)==="object"&&value!==null&&typeof value.then==="function")switch(value.status){case"fulfilled":resolvedValue=value.value;break;case"rejected":resolvedValue=value.reason;break}return{awaited:{name:ioInfo.name,description:getIODescription(resolvedValue),start:ioInfo.start,end:ioInfo.end,byteSize:ioInfo.byteSize==null?null:ioInfo.byteSize,value:ioInfo.value==null?null:ioInfo.value,env:ioInfo.env==null?null:ioInfo.env,owner:ioOwnerInstance===null?null:instanceToSerializedElement(ioOwnerInstance),stack:ioInfo.debugStack==null?null:parseStackTrace(ioInfo.debugStack,1)},env:asyncInfo.env==null?null:asyncInfo.env,owner:awaitOwnerInstance===null?null:instanceToSerializedElement(awaitOwnerInstance),stack:awaitStack}}function getInstanceAndStyle(id){var instance=null,style=null,devtoolsInstance=idToDevToolsInstanceMap.get(id);if(devtoolsInstance===void 0)return console.warn('Could not find DevToolsInstance with id "'.concat(id,'"')),{instance,style};if(devtoolsInstance.kind!==FIBER_INSTANCE)return{instance,style};var fiber=devtoolsInstance.data;if(fiber!==null){if(instance=fiber.stateNode,fiber.memoizedProps!==null)style=fiber.memoizedProps.style}return{instance,style}}function isErrorBoundary(fiber){var{tag,type}=fiber;switch(tag){case ClassComponent:case IncompleteClassComponent:var instance=fiber.stateNode;return typeof type.getDerivedStateFromError==="function"||instance!==null&&typeof instance.componentDidCatch==="function";default:return!1}}function inspectElementRaw(id){var devtoolsInstance=idToDevToolsInstanceMap.get(id);if(devtoolsInstance===void 0)return console.warn('Could not find DevToolsInstance with id "'.concat(id,'"')),null;if(devtoolsInstance.kind===VIRTUAL_INSTANCE)return inspectVirtualInstanceRaw(devtoolsInstance);if(devtoolsInstance.kind===FIBER_INSTANCE){var isRoot=devtoolsInstance.parent===null;return isRoot?inspectRootsRaw(devtoolsInstance.id):inspectFiberInstanceRaw(devtoolsInstance)}throw Error("Unsupported instance kind")}function inspectFiberInstanceRaw(fiberInstance){var fiber=fiberInstance.data;if(fiber==null)return null;var{stateNode,key,memoizedProps,memoizedState,dependencies,tag,type}=fiber,elementType=getElementTypeForFiber(fiber),usesHooks=(tag===FunctionComponent||tag===SimpleMemoComponent||tag===ForwardRef)&&(!!memoizedState||!!dependencies),showState=tag===ClassComponent||tag===IncompleteClassComponent,typeSymbol=getTypeSymbol(type),canViewSource=!1,context=null;if(tag===ClassComponent||tag===FunctionComponent||tag===IncompleteClassComponent||tag===IncompleteFunctionComponent||tag===IndeterminateComponent||tag===MemoComponent||tag===ForwardRef||tag===SimpleMemoComponent){if(canViewSource=!0,stateNode&&stateNode.context!=null){var shouldHideContext=elementType===types_ElementTypeClass&&!(type.contextTypes||type.contextType);if(!shouldHideContext)context=stateNode.context}}else if((typeSymbol===CONTEXT_NUMBER||typeSymbol===CONTEXT_SYMBOL_STRING)&&!(type._context===void 0&&type.Provider===type)){var consumerResolvedContext=type._context||type;context=consumerResolvedContext._currentValue||null;var _current=fiber.return;while(_current!==null){var currentType=_current.type,currentTypeSymbol=getTypeSymbol(currentType);if(currentTypeSymbol===PROVIDER_NUMBER||currentTypeSymbol===PROVIDER_SYMBOL_STRING){var providerResolvedContext=currentType._context||currentType.context;if(providerResolvedContext===consumerResolvedContext){context=_current.memoizedProps.value;break}}_current=_current.return}}else if(typeSymbol===CONSUMER_SYMBOL_STRING){var _consumerResolvedContext=type._context;context=_consumerResolvedContext._currentValue||null;var _current2=fiber.return;while(_current2!==null){var _currentType=_current2.type,_currentTypeSymbol=getTypeSymbol(_currentType);if(_currentTypeSymbol===CONTEXT_SYMBOL_STRING){var _providerResolvedContext=_currentType;if(_providerResolvedContext===_consumerResolvedContext){context=_current2.memoizedProps.value;break}}_current2=_current2.return}}var hasLegacyContext=!1;if(context!==null)hasLegacyContext=!!type.contextTypes,context={value:context};var owners=getOwnersListFromInstance(fiberInstance),hooks=null;if(usesHooks)hooks=inspectHooks(fiber);var rootType=null,current=fiber,hasErrorBoundary=!1,hasSuspenseBoundary=!1;while(current.return!==null){var temp=current;if(current=current.return,temp.tag===SuspenseComponent)hasSuspenseBoundary=!0;else if(isErrorBoundary(temp))hasErrorBoundary=!0}var fiberRoot=current.stateNode;if(fiberRoot!=null&&fiberRoot._debugRootType!==null)rootType=fiberRoot._debugRootType;var isErrored=!1;if(isErrorBoundary(fiber)){var DidCapture=128;isErrored=(fiber.flags&DidCapture)!==0||forceErrorForFibers.get(fiber)===!0||fiber.alternate!==null&&forceErrorForFibers.get(fiber.alternate)===!0}var plugins={stylex:null};if(enableStyleXFeatures){if(memoizedProps!=null&&memoizedProps.hasOwnProperty("xstyle"))plugins.stylex=getStyleXData(memoizedProps.xstyle)}var source=null;if(canViewSource)source=getSourceForFiberInstance(fiberInstance);var componentLogsEntry=fiberToComponentLogsMap.get(fiber);if(componentLogsEntry===void 0&&fiber.alternate!==null)componentLogsEntry=fiberToComponentLogsMap.get(fiber.alternate);var nativeTag=null;if(elementType===ElementTypeHostComponent)nativeTag=getNativeTag(fiber.stateNode);var isSuspended=null;if(tag===SuspenseComponent)isSuspended=memoizedState!==null;var suspendedBy=fiberInstance.suspenseNode!==null?getSuspendedByOfSuspenseNode(fiberInstance.suspenseNode,null):tag===ActivityComponent?getSuspendedByOfInstanceSubtree(fiberInstance):getSuspendedByOfInstance(fiberInstance,hooks),suspendedByRange=getSuspendedByRange(getNearestSuspenseNode(fiberInstance)),unknownSuspenders=UNKNOWN_SUSPENDERS_NONE;if(fiberInstance.suspenseNode!==null&&fiberInstance.suspenseNode.hasUnknownSuspenders&&!isSuspended)if(renderer.bundleType===0)unknownSuspenders=UNKNOWN_SUSPENDERS_REASON_PRODUCTION;else if(!("_debugInfo"in fiber))unknownSuspenders=UNKNOWN_SUSPENDERS_REASON_OLD_VERSION;else unknownSuspenders=UNKNOWN_SUSPENDERS_REASON_THROWN_PROMISE;return{id:fiberInstance.id,canEditHooks:typeof overrideHookState==="function",canEditFunctionProps:typeof overrideProps==="function",canEditHooksAndDeletePaths:typeof overrideHookStateDeletePath==="function",canEditHooksAndRenamePaths:typeof overrideHookStateRenamePath==="function",canEditFunctionPropsDeletePaths:typeof overridePropsDeletePath==="function",canEditFunctionPropsRenamePaths:typeof overridePropsRenamePath==="function",canToggleError:supportsTogglingError&&hasErrorBoundary,isErrored,canToggleSuspense:supportsTogglingSuspense&&hasSuspenseBoundary&&(!isSuspended||forceFallbackForFibers.has(fiber)||fiber.alternate!==null&&forceFallbackForFibers.has(fiber.alternate)),isSuspended,source,stack:fiber._debugOwner==null||fiber._debugStack==null?null:parseStackTrace(fiber._debugStack,1),hasLegacyContext,key:key!=null?key:null,type:elementType,context,hooks,props:memoizedProps,state:showState?memoizedState:null,errors:componentLogsEntry===void 0?[]:Array.from(componentLogsEntry.errors.entries()),warnings:componentLogsEntry===void 0?[]:Array.from(componentLogsEntry.warnings.entries()),suspendedBy,suspendedByRange,unknownSuspenders,owners,env:null,rootType,rendererPackageName:renderer.rendererPackageName,rendererVersion:renderer.version,plugins,nativeTag}}function inspectVirtualInstanceRaw(virtualInstance){var source=getSourceForInstance(virtualInstance),componentInfo=virtualInstance.data,key=typeof componentInfo.key==="string"?componentInfo.key:null,props=componentInfo.props==null?null:componentInfo.props,owners=getOwnersListFromInstance(virtualInstance),rootType=null,hasErrorBoundary=!1,hasSuspenseBoundary=!1,nearestFiber=getNearestFiber(virtualInstance);if(nearestFiber!==null){var current=nearestFiber;while(current.return!==null){var temp=current;if(current=current.return,temp.tag===SuspenseComponent)hasSuspenseBoundary=!0;else if(isErrorBoundary(temp))hasErrorBoundary=!0}var fiberRoot=current.stateNode;if(fiberRoot!=null&&fiberRoot._debugRootType!==null)rootType=fiberRoot._debugRootType}var plugins={stylex:null},componentLogsEntry=componentInfoToComponentLogsMap.get(componentInfo),isSuspended=null,suspendedBy=getSuspendedByOfInstance(virtualInstance,null),suspendedByRange=getSuspendedByRange(getNearestSuspenseNode(virtualInstance));return{id:virtualInstance.id,canEditHooks:!1,canEditFunctionProps:!1,canEditHooksAndDeletePaths:!1,canEditHooksAndRenamePaths:!1,canEditFunctionPropsDeletePaths:!1,canEditFunctionPropsRenamePaths:!1,canToggleError:supportsTogglingError&&hasErrorBoundary,isErrored:!1,canToggleSuspense:supportsTogglingSuspense&&hasSuspenseBoundary,isSuspended,source,stack:componentInfo.owner==null||componentInfo.debugStack==null?null:parseStackTrace(componentInfo.debugStack,1),hasLegacyContext:!1,key,type:types_ElementTypeVirtual,context:null,hooks:null,props,state:null,errors:componentLogsEntry===void 0?[]:Array.from(componentLogsEntry.errors.entries()),warnings:componentLogsEntry===void 0?[]:Array.from(componentLogsEntry.warnings.entries()),suspendedBy,suspendedByRange,unknownSuspenders:UNKNOWN_SUSPENDERS_NONE,owners,env:componentInfo.env==null?null:componentInfo.env,rootType,rendererPackageName:renderer.rendererPackageName,rendererVersion:renderer.version,plugins,nativeTag:null}}var mostRecentlyInspectedElement=null,hasElementUpdatedSinceLastInspected=!1,currentlyInspectedPaths={};function isMostRecentlyInspectedElement(id){if(mostRecentlyInspectedElement===null)return!1;if(mostRecentlyInspectedElement.id===id)return!0;if(mostRecentlyInspectedElement.type===ElementTypeRoot){var instance=idToDevToolsInstanceMap.get(id);return instance!==void 0&&instance.kind===FIBER_INSTANCE&&instance.parent===null}return!1}function isMostRecentlyInspectedElementCurrent(id){return isMostRecentlyInspectedElement(id)&&!hasElementUpdatedSinceLastInspected}function mergeInspectedPaths(path){var current=currentlyInspectedPaths;path.forEach(function(key){if(!current[key])current[key]={};current=current[key]})}function createIsPathAllowed(key,secondaryCategory){return function(path){switch(secondaryCategory){case"hooks":if(path.length===1)return!0;if(path[path.length-2]==="hookSource"&&path[path.length-1]==="fileName")return!0;if(path[path.length-1]==="subHooks"||path[path.length-2]==="subHooks")return!0;break;case"suspendedBy":if(path.length<5)return!0;break;default:break}var current=key===null?currentlyInspectedPaths:currentlyInspectedPaths[key];if(!current)return!1;for(var i=0;i<path.length;i++)if(current=current[path[i]],!current)return!1;return!0}}function updateSelectedElement(inspectedElement){var{hooks,id,props}=inspectedElement,devtoolsInstance=idToDevToolsInstanceMap.get(id);if(devtoolsInstance===void 0){console.warn('Could not find DevToolsInstance with id "'.concat(id,'"'));return}if(devtoolsInstance.kind!==FIBER_INSTANCE)return;var fiber=devtoolsInstance.data,elementType=fiber.elementType,stateNode=fiber.stateNode,tag=fiber.tag,type=fiber.type;switch(tag){case ClassComponent:case IncompleteClassComponent:case IndeterminateComponent:global.$r=stateNode;break;case IncompleteFunctionComponent:case FunctionComponent:global.$r={hooks,props,type};break;case ForwardRef:global.$r={hooks,props,type:type.render};break;case MemoComponent:case SimpleMemoComponent:global.$r={hooks,props,type:elementType!=null&&elementType.type!=null?elementType.type:type};break;default:global.$r=null;break}}function storeAsGlobal(id,path,count){if(isMostRecentlyInspectedElement(id)){var value=utils_getInObject(mostRecentlyInspectedElement,path),key="$reactTemp".concat(count);window[key]=value,console.log(key),console.log(value)}}function getSerializedElementValueByPath(id,path){if(isMostRecentlyInspectedElement(id)){var valueToCopy=utils_getInObject(mostRecentlyInspectedElement,path);return serializeToString(valueToCopy)}}function inspectElement(requestID,id,path,forceFullData){if(path!==null)mergeInspectedPaths(path);if(isMostRecentlyInspectedElement(id)&&!forceFullData){if(!hasElementUpdatedSinceLastInspected)if(path!==null){var secondaryCategory=null;if(path[0]==="hooks"||path[0]==="suspendedBy")secondaryCategory=path[0];return{id,responseID:requestID,type:"hydrated-path",path,value:cleanForBridge(utils_getInObject(mostRecentlyInspectedElement,path),createIsPathAllowed(null,secondaryCategory),path)}}else return{id,responseID:requestID,type:"no-change"}}else currentlyInspectedPaths={};hasElementUpdatedSinceLastInspected=!1;try{mostRecentlyInspectedElement=inspectElementRaw(id)}catch(error){if(error.name==="ReactDebugToolsRenderError"){var message="Error rendering inspected element.",stack;if(console.error(message+`
171
+
172
+ `,error),error.cause!=null){var componentName=getDisplayNameForElementID(id);if(console.error("React DevTools encountered an error while trying to inspect hooks. This is most likely caused by an error in current inspected component"+(componentName!=null?': "'.concat(componentName,'".'):".")+`
173
+ The error thrown in the component is:
174
+
175
+ `,error.cause),error.cause instanceof Error)message=error.cause.message||message,stack=error.cause.stack}return{type:"error",errorType:"user",id,responseID:requestID,message,stack}}if(error.name==="ReactDebugToolsUnsupportedHookError")return{type:"error",errorType:"unknown-hook",id,responseID:requestID,message:"Unsupported hook in the react-debug-tools package: "+error.message};return console.error(`Error inspecting element.
176
+
177
+ `,error),{type:"error",errorType:"uncaught",id,responseID:requestID,message:error.message,stack:error.stack}}if(mostRecentlyInspectedElement===null)return{id,responseID:requestID,type:"not-found"};var inspectedElement=mostRecentlyInspectedElement;updateSelectedElement(inspectedElement);var cleanedInspectedElement=renderer_objectSpread({},inspectedElement);return cleanedInspectedElement.context=cleanForBridge(inspectedElement.context,createIsPathAllowed("context",null)),cleanedInspectedElement.hooks=cleanForBridge(inspectedElement.hooks,createIsPathAllowed("hooks","hooks")),cleanedInspectedElement.props=cleanForBridge(inspectedElement.props,createIsPathAllowed("props",null)),cleanedInspectedElement.state=cleanForBridge(inspectedElement.state,createIsPathAllowed("state",null)),cleanedInspectedElement.suspendedBy=cleanForBridge(inspectedElement.suspendedBy,createIsPathAllowed("suspendedBy","suspendedBy")),{id,responseID:requestID,type:"full-data",value:cleanedInspectedElement}}function inspectRootsRaw(arbitraryRootID){var roots=hook.getFiberRoots(rendererID);if(roots.size===0)return null;var inspectedRoots={id:arbitraryRootID,type:ElementTypeRoot,isErrored:!1,errors:[],warnings:[],suspendedBy:[],suspendedByRange:null,unknownSuspenders:UNKNOWN_SUSPENDERS_NONE,rootType:null,plugins:{stylex:null},nativeTag:null,env:null,source:null,stack:null,rendererPackageName:null,rendererVersion:null,key:null,canEditFunctionProps:!1,canEditHooks:!1,canEditFunctionPropsDeletePaths:!1,canEditFunctionPropsRenamePaths:!1,canEditHooksAndDeletePaths:!1,canEditHooksAndRenamePaths:!1,canToggleError:!1,canToggleSuspense:!1,isSuspended:!1,hasLegacyContext:!1,context:null,hooks:null,props:null,state:null,owners:null},minSuspendedByRange=1/0,maxSuspendedByRange=-1/0;if(roots.forEach(function(root){var rootInstance=rootToFiberInstanceMap.get(root);if(rootInstance===void 0)throw Error("Expected a root instance to exist for this Fiber root");var inspectedRoot=inspectFiberInstanceRaw(rootInstance);if(inspectedRoot===null)return;if(inspectedRoot.isErrored)inspectedRoots.isErrored=!0;for(var i=0;i<inspectedRoot.errors.length;i++)inspectedRoots.errors.push(inspectedRoot.errors[i]);for(var _i=0;_i<inspectedRoot.warnings.length;_i++)inspectedRoots.warnings.push(inspectedRoot.warnings[_i]);for(var _i2=0;_i2<inspectedRoot.suspendedBy.length;_i2++)inspectedRoots.suspendedBy.push(inspectedRoot.suspendedBy[_i2]);var suspendedByRange=inspectedRoot.suspendedByRange;if(suspendedByRange!==null){if(suspendedByRange[0]<minSuspendedByRange)minSuspendedByRange=suspendedByRange[0];if(suspendedByRange[1]>maxSuspendedByRange)maxSuspendedByRange=suspendedByRange[1]}}),minSuspendedByRange!==1/0||maxSuspendedByRange!==-1/0)inspectedRoots.suspendedByRange=[minSuspendedByRange,maxSuspendedByRange];return inspectedRoots}function logElementToConsole(id){var result=isMostRecentlyInspectedElementCurrent(id)?mostRecentlyInspectedElement:inspectElementRaw(id);if(result===null){console.warn('Could not find DevToolsInstance with id "'.concat(id,'"'));return}var displayName=getDisplayNameForElementID(id),supportsGroup=typeof console.groupCollapsed==="function";if(supportsGroup)console.groupCollapsed("[Click to expand] %c<".concat(displayName||"Component"," />"),"color: var(--dom-tag-name-color); font-weight: normal;");if(result.props!==null)console.log("Props:",result.props);if(result.state!==null)console.log("State:",result.state);if(result.hooks!==null)console.log("Hooks:",result.hooks);var hostInstances=findHostInstancesForElementID(id);if(hostInstances!==null)console.log("Nodes:",hostInstances);if(window.chrome||/firefox/i.test(navigator.userAgent))console.log("Right-click any value to save it as a global variable for further inspection.");if(supportsGroup)console.groupEnd()}function deletePath(type,id,hookID,path){var devtoolsInstance=idToDevToolsInstanceMap.get(id);if(devtoolsInstance===void 0){console.warn('Could not find DevToolsInstance with id "'.concat(id,'"'));return}if(devtoolsInstance.kind!==FIBER_INSTANCE)return;var fiber=devtoolsInstance.data;if(fiber!==null){var instance=fiber.stateNode;switch(type){case"context":switch(path=path.slice(1),fiber.tag){case ClassComponent:if(path.length===0);else deletePathInObject(instance.context,path);instance.forceUpdate();break;case FunctionComponent:break}break;case"hooks":if(typeof overrideHookStateDeletePath==="function")overrideHookStateDeletePath(fiber,hookID,path);break;case"props":if(instance===null){if(typeof overridePropsDeletePath==="function")overridePropsDeletePath(fiber,path)}else fiber.pendingProps=copyWithDelete(instance.props,path),instance.forceUpdate();break;case"state":deletePathInObject(instance.state,path),instance.forceUpdate();break}}}function renamePath(type,id,hookID,oldPath,newPath){var devtoolsInstance=idToDevToolsInstanceMap.get(id);if(devtoolsInstance===void 0){console.warn('Could not find DevToolsInstance with id "'.concat(id,'"'));return}if(devtoolsInstance.kind!==FIBER_INSTANCE)return;var fiber=devtoolsInstance.data;if(fiber!==null){var instance=fiber.stateNode;switch(type){case"context":switch(oldPath=oldPath.slice(1),newPath=newPath.slice(1),fiber.tag){case ClassComponent:if(oldPath.length===0);else renamePathInObject(instance.context,oldPath,newPath);instance.forceUpdate();break;case FunctionComponent:break}break;case"hooks":if(typeof overrideHookStateRenamePath==="function")overrideHookStateRenamePath(fiber,hookID,oldPath,newPath);break;case"props":if(instance===null){if(typeof overridePropsRenamePath==="function")overridePropsRenamePath(fiber,oldPath,newPath)}else fiber.pendingProps=copyWithRename(instance.props,oldPath,newPath),instance.forceUpdate();break;case"state":renamePathInObject(instance.state,oldPath,newPath),instance.forceUpdate();break}}}function overrideValueAtPath(type,id,hookID,path,value){var devtoolsInstance=idToDevToolsInstanceMap.get(id);if(devtoolsInstance===void 0){console.warn('Could not find DevToolsInstance with id "'.concat(id,'"'));return}if(devtoolsInstance.kind!==FIBER_INSTANCE)return;var fiber=devtoolsInstance.data;if(fiber!==null){var instance=fiber.stateNode;switch(type){case"context":switch(path=path.slice(1),fiber.tag){case ClassComponent:if(path.length===0)instance.context=value;else utils_setInObject(instance.context,path,value);instance.forceUpdate();break;case FunctionComponent:break}break;case"hooks":if(typeof overrideHookState==="function")overrideHookState(fiber,hookID,path,value);break;case"props":switch(fiber.tag){case ClassComponent:fiber.pendingProps=copyWithSet(instance.props,path,value),instance.forceUpdate();break;default:if(typeof overrideProps==="function")overrideProps(fiber,path,value);break}break;case"state":switch(fiber.tag){case ClassComponent:utils_setInObject(instance.state,path,value),instance.forceUpdate();break}break}}}var currentCommitProfilingMetadata=null,displayNamesByRootID=null,initialTreeBaseDurationsMap=null,isProfiling=!1,profilingStartTime=0,recordChangeDescriptions=!1,recordTimeline=!1,rootToCommitProfilingMetadataMap=null;function getProfilingData(){var dataForRoots=[];if(rootToCommitProfilingMetadataMap===null)throw Error("getProfilingData() called before any profiling data was recorded");rootToCommitProfilingMetadataMap.forEach(function(commitProfilingMetadata,rootID){var commitData=[],displayName=displayNamesByRootID!==null&&displayNamesByRootID.get(rootID)||"Unknown",initialTreeBaseDurations=initialTreeBaseDurationsMap!==null&&initialTreeBaseDurationsMap.get(rootID)||[];commitProfilingMetadata.forEach(function(commitProfilingData,commitIndex){var{changeDescriptions,durations,effectDuration,maxActualDuration,passiveEffectDuration,priorityLevel,commitTime,updaters}=commitProfilingData,fiberActualDurations=[],fiberSelfDurations=[];for(var i=0;i<durations.length;i+=3){var fiberID=durations[i];fiberActualDurations.push([fiberID,formatDurationToMicrosecondsGranularity(durations[i+1])]),fiberSelfDurations.push([fiberID,formatDurationToMicrosecondsGranularity(durations[i+2])])}commitData.push({changeDescriptions:changeDescriptions!==null?Array.from(changeDescriptions.entries()):null,duration:formatDurationToMicrosecondsGranularity(maxActualDuration),effectDuration:effectDuration!==null?formatDurationToMicrosecondsGranularity(effectDuration):null,fiberActualDurations,fiberSelfDurations,passiveEffectDuration:passiveEffectDuration!==null?formatDurationToMicrosecondsGranularity(passiveEffectDuration):null,priorityLevel,timestamp:commitTime,updaters})}),dataForRoots.push({commitData,displayName,initialTreeBaseDurations,rootID})});var timelineData=null;if(typeof getTimelineData==="function"){var currentTimelineData=getTimelineData();if(currentTimelineData){var{batchUIDToMeasuresMap,internalModuleSourceToRanges,laneToLabelMap,laneToReactMeasureMap}=currentTimelineData,rest=_objectWithoutProperties(currentTimelineData,_excluded);timelineData=renderer_objectSpread(renderer_objectSpread({},rest),{},{batchUIDToMeasuresKeyValueArray:Array.from(batchUIDToMeasuresMap.entries()),internalModuleSourceToRanges:Array.from(internalModuleSourceToRanges.entries()),laneToLabelKeyValueArray:Array.from(laneToLabelMap.entries()),laneToReactMeasureKeyValueArray:Array.from(laneToReactMeasureMap.entries())})}}return{dataForRoots,rendererID,timelineData}}function snapshotTreeBaseDurations(instance,target){if(instance.kind!==FILTERED_FIBER_INSTANCE)target.push([instance.id,instance.treeBaseDuration]);for(var child=instance.firstChild;child!==null;child=child.nextSibling)snapshotTreeBaseDurations(child,target)}function startProfiling(shouldRecordChangeDescriptions,shouldRecordTimeline){if(isProfiling)return;if(recordChangeDescriptions=shouldRecordChangeDescriptions,recordTimeline=shouldRecordTimeline,displayNamesByRootID=new Map,initialTreeBaseDurationsMap=new Map,hook.getFiberRoots(rendererID).forEach(function(root){var rootInstance=rootToFiberInstanceMap.get(root);if(rootInstance===void 0)throw Error("Expected the root instance to already exist when starting profiling");var rootID=rootInstance.id;displayNamesByRootID.set(rootID,getDisplayNameForRoot(root.current));var initialTreeBaseDurations=[];snapshotTreeBaseDurations(rootInstance,initialTreeBaseDurations),initialTreeBaseDurationsMap.set(rootID,initialTreeBaseDurations)}),isProfiling=!0,profilingStartTime=renderer_getCurrentTime(),rootToCommitProfilingMetadataMap=new Map,toggleProfilingStatus!==null)toggleProfilingStatus(!0,recordTimeline)}function stopProfiling(){if(isProfiling=!1,recordChangeDescriptions=!1,toggleProfilingStatus!==null)toggleProfilingStatus(!1,recordTimeline);recordTimeline=!1}if(shouldStartProfilingNow)startProfiling(profilingSettings.recordChangeDescriptions,profilingSettings.recordTimeline);function getNearestFiber(devtoolsInstance){if(devtoolsInstance.kind===VIRTUAL_INSTANCE){var inst=devtoolsInstance;while(inst.kind===VIRTUAL_INSTANCE){if(inst.firstChild===null)return null;inst=inst.firstChild}return inst.data.return}else return devtoolsInstance.data}function shouldErrorFiberAlwaysNull(){return null}var forceErrorForFibers=new Map;function shouldErrorFiberAccordingToMap(fiber){if(typeof setErrorHandler!=="function")throw Error("Expected overrideError() to not get called for earlier React versions.");var status=forceErrorForFibers.get(fiber);if(status===!1){if(forceErrorForFibers.delete(fiber),forceErrorForFibers.size===0)setErrorHandler(shouldErrorFiberAlwaysNull);return!1}if(status===void 0&&fiber.alternate!==null){if(status=forceErrorForFibers.get(fiber.alternate),status===!1){if(forceErrorForFibers.delete(fiber.alternate),forceErrorForFibers.size===0)setErrorHandler(shouldErrorFiberAlwaysNull)}}if(status===void 0)return!1;return status}function overrideError(id,forceError){if(typeof setErrorHandler!=="function"||typeof scheduleUpdate!=="function")throw Error("Expected overrideError() to not get called for earlier React versions.");var devtoolsInstance=idToDevToolsInstanceMap.get(id);if(devtoolsInstance===void 0)return;var nearestFiber=getNearestFiber(devtoolsInstance);if(nearestFiber===null)return;var fiber=nearestFiber;while(!isErrorBoundary(fiber)){if(fiber.return===null)return;fiber=fiber.return}if(forceErrorForFibers.set(fiber,forceError),fiber.alternate!==null)forceErrorForFibers.delete(fiber.alternate);if(forceErrorForFibers.size===1)setErrorHandler(shouldErrorFiberAccordingToMap);if(!forceError&&typeof scheduleRetry==="function")scheduleRetry(fiber);else scheduleUpdate(fiber)}function shouldSuspendFiberAlwaysFalse(){return!1}var forceFallbackForFibers=new Set;function shouldSuspendFiberAccordingToSet(fiber){return forceFallbackForFibers.has(fiber)||fiber.alternate!==null&&forceFallbackForFibers.has(fiber.alternate)}function overrideSuspense(id,forceFallback){if(typeof setSuspenseHandler!=="function"||typeof scheduleUpdate!=="function")throw Error("Expected overrideSuspense() to not get called for earlier React versions.");var devtoolsInstance=idToDevToolsInstanceMap.get(id);if(devtoolsInstance===void 0)return;var nearestFiber=getNearestFiber(devtoolsInstance);if(nearestFiber===null)return;var fiber=nearestFiber;while(fiber.tag!==SuspenseComponent){if(fiber.return===null)return;fiber=fiber.return}if(fiber.alternate!==null)forceFallbackForFibers.delete(fiber.alternate);if(forceFallback){if(forceFallbackForFibers.add(fiber),forceFallbackForFibers.size===1)setSuspenseHandler(shouldSuspendFiberAccordingToSet)}else if(forceFallbackForFibers.delete(fiber),forceFallbackForFibers.size===0)setSuspenseHandler(shouldSuspendFiberAlwaysFalse);if(!forceFallback&&typeof scheduleRetry==="function")scheduleRetry(fiber);else scheduleUpdate(fiber)}function overrideSuspenseMilestone(suspendedSet){if(typeof setSuspenseHandler!=="function"||typeof scheduleUpdate!=="function")throw Error("Expected overrideSuspenseMilestone() to not get called for earlier React versions.");var unsuspendedSet=new Set(forceFallbackForFibers),resuspended=!1;for(var i=0;i<suspendedSet.length;++i){var instance=idToDevToolsInstanceMap.get(suspendedSet[i]);if(instance===void 0){console.warn("Could not suspend ID '".concat(suspendedSet[i],"' since the instance can't be found."));continue}if(instance.kind===FIBER_INSTANCE){var _fiber11=instance.data;if(forceFallbackForFibers.has(_fiber11)||_fiber11.alternate!==null&&forceFallbackForFibers.has(_fiber11.alternate)){if(unsuspendedSet.delete(_fiber11),_fiber11.alternate!==null)unsuspendedSet.delete(_fiber11.alternate)}else forceFallbackForFibers.add(_fiber11),scheduleUpdate(_fiber11),resuspended=!0}else console.warn("Cannot not suspend ID '".concat(suspendedSet[i],"'."))}if(unsuspendedSet.forEach(function(fiber){if(forceFallbackForFibers.delete(fiber),!resuspended&&typeof scheduleRetry==="function")scheduleRetry(fiber);else scheduleUpdate(fiber)}),forceFallbackForFibers.size>0)setSuspenseHandler(shouldSuspendFiberAccordingToSet);else setSuspenseHandler(shouldSuspendFiberAlwaysFalse)}var trackedPath=null,trackedPathMatchFiber=null,trackedPathMatchInstance=null,trackedPathMatchDepth=-1,mightBeOnTrackedPath=!1;function setTrackedPath(path){if(path===null)trackedPathMatchFiber=null,trackedPathMatchInstance=null,trackedPathMatchDepth=-1,mightBeOnTrackedPath=!1;trackedPath=path}function updateTrackedPathStateBeforeMount(fiber,fiberInstance){if(trackedPath===null||!mightBeOnTrackedPath)return!1;var returnFiber=fiber.return,returnAlternate=returnFiber!==null?returnFiber.alternate:null;if(trackedPathMatchFiber===returnFiber||trackedPathMatchFiber===returnAlternate&&returnAlternate!==null){var actualFrame=getPathFrame(fiber),expectedFrame=trackedPath[trackedPathMatchDepth+1];if(expectedFrame===void 0)throw Error("Expected to see a frame at the next depth.");if(actualFrame.index===expectedFrame.index&&actualFrame.key===expectedFrame.key&&actualFrame.displayName===expectedFrame.displayName){if(trackedPathMatchFiber=fiber,fiberInstance!==null&&fiberInstance.kind===FIBER_INSTANCE)trackedPathMatchInstance=fiberInstance;if(trackedPathMatchDepth++,trackedPathMatchDepth===trackedPath.length-1)mightBeOnTrackedPath=!1;else mightBeOnTrackedPath=!0;return!1}}if(trackedPathMatchFiber===null&&fiberInstance===null)return!0;return mightBeOnTrackedPath=!1,!0}function updateVirtualTrackedPathStateBeforeMount(virtualInstance,parentInstance){if(trackedPath===null||!mightBeOnTrackedPath)return!1;if(trackedPathMatchInstance===parentInstance){var actualFrame=getVirtualPathFrame(virtualInstance),expectedFrame=trackedPath[trackedPathMatchDepth+1];if(expectedFrame===void 0)throw Error("Expected to see a frame at the next depth.");if(actualFrame.index===expectedFrame.index&&actualFrame.key===expectedFrame.key&&actualFrame.displayName===expectedFrame.displayName){if(trackedPathMatchFiber=null,trackedPathMatchInstance=virtualInstance,trackedPathMatchDepth++,trackedPathMatchDepth===trackedPath.length-1)mightBeOnTrackedPath=!1;else mightBeOnTrackedPath=!0;return!1}}if(trackedPathMatchFiber!==null)return!0;return mightBeOnTrackedPath=!1,!0}function updateTrackedPathStateAfterMount(mightSiblingsBeOnTrackedPath){mightBeOnTrackedPath=mightSiblingsBeOnTrackedPath}var rootPseudoKeys=new Map,rootDisplayNameCounter=new Map;function setRootPseudoKey(id,fiber){var name=getDisplayNameForRoot(fiber),counter=rootDisplayNameCounter.get(name)||0;rootDisplayNameCounter.set(name,counter+1);var pseudoKey="".concat(name,":").concat(counter);rootPseudoKeys.set(id,pseudoKey)}function removeRootPseudoKey(id){var pseudoKey=rootPseudoKeys.get(id);if(pseudoKey===void 0)throw Error("Expected root pseudo key to be known.");var name=pseudoKey.slice(0,pseudoKey.lastIndexOf(":")),counter=rootDisplayNameCounter.get(name);if(counter===void 0)throw Error("Expected counter to be known.");if(counter>1)rootDisplayNameCounter.set(name,counter-1);else rootDisplayNameCounter.delete(name);rootPseudoKeys.delete(id)}function getDisplayNameForRoot(fiber){var preferredDisplayName=null,fallbackDisplayName=null,child=fiber.child;for(var i=0;i<3;i++){if(child===null)break;var displayName=getDisplayNameForFiber(child);if(displayName!==null){if(typeof child.type==="function")preferredDisplayName=displayName;else if(fallbackDisplayName===null)fallbackDisplayName=displayName}if(preferredDisplayName!==null)break;child=child.child}return preferredDisplayName||fallbackDisplayName||"Anonymous"}function getPathFrame(fiber){var key=fiber.key,displayName=getDisplayNameForFiber(fiber),index=fiber.index;switch(fiber.tag){case HostRoot:var rootInstance=rootToFiberInstanceMap.get(fiber.stateNode);if(rootInstance===void 0)throw Error("Expected the root instance to exist when computing a path");var pseudoKey=rootPseudoKeys.get(rootInstance.id);if(pseudoKey===void 0)throw Error("Expected mounted root to have known pseudo key.");displayName=pseudoKey;break;case HostComponent:displayName=fiber.type;break;default:break}return{displayName,key,index}}function getVirtualPathFrame(virtualInstance){return{displayName:virtualInstance.data.name||"",key:virtualInstance.data.key==null?null:virtualInstance.data.key,index:-1}}function getPathForElement(id){var devtoolsInstance=idToDevToolsInstanceMap.get(id);if(devtoolsInstance===void 0)return null;var keyPath=[],inst=devtoolsInstance;while(inst.kind===VIRTUAL_INSTANCE){if(keyPath.push(getVirtualPathFrame(inst)),inst.parent===null)return null;inst=inst.parent}var fiber=inst.data;while(fiber!==null)keyPath.push(getPathFrame(fiber)),fiber=fiber.return;return keyPath.reverse(),keyPath}function getBestMatchForTrackedPath(){if(trackedPath===null)return null;if(trackedPathMatchInstance===null)return null;return{id:trackedPathMatchInstance.id,isFullMatch:trackedPathMatchDepth===trackedPath.length-1}}var formatPriorityLevel=function(priorityLevel){if(priorityLevel==null)return"Unknown";switch(priorityLevel){case ImmediatePriority:return"Immediate";case UserBlockingPriority:return"User-Blocking";case NormalPriority:return"Normal";case LowPriority:return"Low";case IdlePriority:return"Idle";case NoPriority:default:return"Unknown"}};function setTraceUpdatesEnabled(isEnabled2){traceUpdatesEnabled=isEnabled2}function hasElementWithId(id){return idToDevToolsInstanceMap.has(id)}function getSourceForFiberInstance(fiberInstance){var ownerSource=getSourceForInstance(fiberInstance);if(ownerSource!==null)return ownerSource;var dispatcherRef=getDispatcherRef(renderer),stackFrame=dispatcherRef==null?null:getSourceLocationByFiber(ReactTypeOfWork,fiberInstance.data,dispatcherRef);if(stackFrame===null)return null;var source=extractLocationFromComponentStack(stackFrame);return fiberInstance.source=source,source}function getSourceForInstance(instance){var unresolvedSource=instance.source;if(unresolvedSource===null)return null;if(instance.kind===VIRTUAL_INSTANCE){var debugLocation=instance.data.debugLocation;if(debugLocation!=null)unresolvedSource=debugLocation}if(renderer_isError(unresolvedSource))return instance.source=extractLocationFromOwnerStack(unresolvedSource);if(typeof unresolvedSource==="string"){var idx=unresolvedSource.lastIndexOf(`
178
+ `),lastLine=idx===-1?unresolvedSource:unresolvedSource.slice(idx+1);return instance.source=extractLocationFromComponentStack(lastLine)}return unresolvedSource}var internalMcpFunctions={};return renderer_objectSpread({cleanup,clearErrorsAndWarnings,clearErrorsForElementID,clearWarningsForElementID,getSerializedElementValueByPath,deletePath,findHostInstancesForElementID,findLastKnownRectsForID,flushInitialOperations,getBestMatchForTrackedPath,getDisplayNameForElementID,getNearestMountedDOMNode,getElementIDForHostInstance,getSuspenseNodeIDForHostInstance,getInstanceAndStyle,getOwnersList,getPathForElement,getProfilingData,handleCommitFiberRoot,handleCommitFiberUnmount,handlePostCommitFiberRoot,hasElementWithId,inspectElement,logElementToConsole,getComponentStack,getElementAttributeByPath,getElementSourceFunctionById,onErrorOrWarning,overrideError,overrideSuspense,overrideSuspenseMilestone,overrideValueAtPath,renamePath,renderer,setTraceUpdatesEnabled,setTrackedPath,startProfiling,stopProfiling,storeAsGlobal,supportsTogglingSuspense,updateComponentFilters,getEnvironmentNames},internalMcpFunctions)}function decorate(object,attr,fn){var old=object[attr];return object[attr]=function(instance){return fn.call(this,old,arguments)},old}function decorateMany(source,fns){var olds={};for(var name in fns)olds[name]=decorate(source,name,fns[name]);return olds}function restoreMany(source,olds){for(var name in olds)source[name]=olds[name]}function forceUpdate(instance){if(typeof instance.forceUpdate==="function")instance.forceUpdate();else if(instance.updater!=null&&typeof instance.updater.enqueueForceUpdate==="function")instance.updater.enqueueForceUpdate(this,function(){},"forceUpdate")}function legacy_renderer_ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r2){return Object.getOwnPropertyDescriptor(e,r2).enumerable})),t.push.apply(t,o)}return t}function legacy_renderer_objectSpread(e){for(var r=1;r<arguments.length;r++){var t=arguments[r]!=null?arguments[r]:{};r%2?legacy_renderer_ownKeys(Object(t),!0).forEach(function(r2){legacy_renderer_defineProperty(e,r2,t[r2])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):legacy_renderer_ownKeys(Object(t)).forEach(function(r2){Object.defineProperty(e,r2,Object.getOwnPropertyDescriptor(t,r2))})}return e}function legacy_renderer_defineProperty(obj,key,value){if(key=legacy_renderer_toPropertyKey(key),key in obj)Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0});else obj[key]=value;return obj}function legacy_renderer_toPropertyKey(t){var i=legacy_renderer_toPrimitive(t,"string");return legacy_renderer_typeof(i)=="symbol"?i:i+""}function legacy_renderer_toPrimitive(t,r){if(legacy_renderer_typeof(t)!="object"||!t)return t;var e=t[Symbol.toPrimitive];if(e!==void 0){var i=e.call(t,r||"default");if(legacy_renderer_typeof(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(t)}function legacy_renderer_typeof(o){return legacy_renderer_typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},legacy_renderer_typeof(o)}function getData(internalInstance){var displayName=null,key=null;if(internalInstance._currentElement!=null){if(internalInstance._currentElement.key)key=String(internalInstance._currentElement.key);var elementType=internalInstance._currentElement.type;if(typeof elementType==="string")displayName=elementType;else if(typeof elementType==="function")displayName=getDisplayName(elementType)}return{displayName,key}}function getElementType(internalInstance){if(internalInstance._currentElement!=null){var elementType=internalInstance._currentElement.type;if(typeof elementType==="function"){var publicInstance=internalInstance.getPublicInstance();if(publicInstance!==null)return types_ElementTypeClass;else return types_ElementTypeFunction}else if(typeof elementType==="string")return ElementTypeHostComponent}return ElementTypeOtherOrUnknown}function getChildren(internalInstance){var children=[];if(legacy_renderer_typeof(internalInstance)!=="object");else if(internalInstance._currentElement===null||internalInstance._currentElement===!1);else if(internalInstance._renderedComponent){var child=internalInstance._renderedComponent;if(getElementType(child)!==ElementTypeOtherOrUnknown)children.push(child)}else if(internalInstance._renderedChildren){var renderedChildren=internalInstance._renderedChildren;for(var name in renderedChildren){var _child=renderedChildren[name];if(getElementType(_child)!==ElementTypeOtherOrUnknown)children.push(_child)}}return children}function legacy_renderer_attach(hook,rendererID,renderer,global){var idToInternalInstanceMap=new Map,internalInstanceToIDMap=new WeakMap,internalInstanceToRootIDMap=new WeakMap,getElementIDForHostInstance=null,findHostInstanceForInternalID,getNearestMountedDOMNode=function(node){return null};if(renderer.ComponentTree)getElementIDForHostInstance=function(node){var internalInstance=renderer.ComponentTree.getClosestInstanceFromNode(node);return internalInstanceToIDMap.get(internalInstance)||null},findHostInstanceForInternalID=function(id){var internalInstance=idToInternalInstanceMap.get(id);return renderer.ComponentTree.getNodeFromInstance(internalInstance)},getNearestMountedDOMNode=function(node){var internalInstance=renderer.ComponentTree.getClosestInstanceFromNode(node);if(internalInstance!=null)return renderer.ComponentTree.getNodeFromInstance(internalInstance);return null};else if(renderer.Mount.getID&&renderer.Mount.getNode)getElementIDForHostInstance=function(node){return null},findHostInstanceForInternalID=function(id){return null};var supportsTogglingSuspense=!1;function getDisplayNameForElementID(id){var internalInstance=idToInternalInstanceMap.get(id);return internalInstance?getData(internalInstance).displayName:null}function getID(internalInstance){if(legacy_renderer_typeof(internalInstance)!=="object"||internalInstance===null)throw Error("Invalid internal instance: "+internalInstance);if(!internalInstanceToIDMap.has(internalInstance)){var _id=getUID();internalInstanceToIDMap.set(internalInstance,_id),idToInternalInstanceMap.set(_id,internalInstance)}return internalInstanceToIDMap.get(internalInstance)}function areEqualArrays(a,b){if(a.length!==b.length)return!1;for(var i=0;i<a.length;i++)if(a[i]!==b[i])return!1;return!0}var parentIDStack=[],oldReconcilerMethods=null;if(renderer.Reconciler)oldReconcilerMethods=decorateMany(renderer.Reconciler,{mountComponent:function(fn,args){var internalInstance=args[0],hostContainerInfo=args[3];if(getElementType(internalInstance)===ElementTypeOtherOrUnknown)return fn.apply(this,args);if(hostContainerInfo._topLevelWrapper===void 0)return fn.apply(this,args);var id=getID(internalInstance),parentID=parentIDStack.length>0?parentIDStack[parentIDStack.length-1]:0;recordMount(internalInstance,id,parentID),parentIDStack.push(id),internalInstanceToRootIDMap.set(internalInstance,getID(hostContainerInfo._topLevelWrapper));try{var result=fn.apply(this,args);return parentIDStack.pop(),result}catch(err){throw parentIDStack=[],err}finally{if(parentIDStack.length===0){var rootID=internalInstanceToRootIDMap.get(internalInstance);if(rootID===void 0)throw Error("Expected to find root ID.");flushPendingEvents(rootID)}}},performUpdateIfNecessary:function(fn,args){var internalInstance=args[0];if(getElementType(internalInstance)===ElementTypeOtherOrUnknown)return fn.apply(this,args);var id=getID(internalInstance);parentIDStack.push(id);var prevChildren=getChildren(internalInstance);try{var result=fn.apply(this,args),nextChildren=getChildren(internalInstance);if(!areEqualArrays(prevChildren,nextChildren))recordReorder(internalInstance,id,nextChildren);return parentIDStack.pop(),result}catch(err){throw parentIDStack=[],err}finally{if(parentIDStack.length===0){var rootID=internalInstanceToRootIDMap.get(internalInstance);if(rootID===void 0)throw Error("Expected to find root ID.");flushPendingEvents(rootID)}}},receiveComponent:function(fn,args){var internalInstance=args[0];if(getElementType(internalInstance)===ElementTypeOtherOrUnknown)return fn.apply(this,args);var id=getID(internalInstance);parentIDStack.push(id);var prevChildren=getChildren(internalInstance);try{var result=fn.apply(this,args),nextChildren=getChildren(internalInstance);if(!areEqualArrays(prevChildren,nextChildren))recordReorder(internalInstance,id,nextChildren);return parentIDStack.pop(),result}catch(err){throw parentIDStack=[],err}finally{if(parentIDStack.length===0){var rootID=internalInstanceToRootIDMap.get(internalInstance);if(rootID===void 0)throw Error("Expected to find root ID.");flushPendingEvents(rootID)}}},unmountComponent:function(fn,args){var internalInstance=args[0];if(getElementType(internalInstance)===ElementTypeOtherOrUnknown)return fn.apply(this,args);var id=getID(internalInstance);parentIDStack.push(id);try{var result=fn.apply(this,args);return parentIDStack.pop(),recordUnmount(internalInstance,id),result}catch(err){throw parentIDStack=[],err}finally{if(parentIDStack.length===0){var rootID=internalInstanceToRootIDMap.get(internalInstance);if(rootID===void 0)throw Error("Expected to find root ID.");flushPendingEvents(rootID)}}}});function cleanup(){if(oldReconcilerMethods!==null)if(renderer.Component)restoreMany(renderer.Component.Mixin,oldReconcilerMethods);else restoreMany(renderer.Reconciler,oldReconcilerMethods);oldReconcilerMethods=null}function recordMount(internalInstance,id,parentID){var isRoot=parentID===0;if(__DEBUG__)console.log("%crecordMount()","color: green; font-weight: bold;",id,getData(internalInstance).displayName);if(isRoot){var hasOwnerMetadata=internalInstance._currentElement!=null&&internalInstance._currentElement._owner!=null;pushOperation(TREE_OPERATION_ADD),pushOperation(id),pushOperation(ElementTypeRoot),pushOperation(0),pushOperation(0),pushOperation(0),pushOperation(hasOwnerMetadata?1:0),pushOperation(SUSPENSE_TREE_OPERATION_ADD),pushOperation(id),pushOperation(parentID),pushOperation(getStringID(null)),pushOperation(0),pushOperation(-1)}else{var type=getElementType(internalInstance),_getData=getData(internalInstance),displayName=_getData.displayName,key=_getData.key,ownerID=internalInstance._currentElement!=null&&internalInstance._currentElement._owner!=null?getID(internalInstance._currentElement._owner):0,displayNameStringID=getStringID(displayName),keyStringID=getStringID(key);pushOperation(TREE_OPERATION_ADD),pushOperation(id),pushOperation(type),pushOperation(parentID),pushOperation(ownerID),pushOperation(displayNameStringID),pushOperation(keyStringID),pushOperation(getStringID(null))}}function recordReorder(internalInstance,id,nextChildren){pushOperation(TREE_OPERATION_REORDER_CHILDREN),pushOperation(id);var nextChildIDs=nextChildren.map(getID);pushOperation(nextChildIDs.length);for(var i=0;i<nextChildIDs.length;i++)pushOperation(nextChildIDs[i])}function recordUnmount(internalInstance,id){var isRoot=parentIDStack.length===0;if(isRoot)pendingUnmountedRootID=id;else pendingUnmountedIDs.push(id);idToInternalInstanceMap.delete(id)}function crawlAndRecordInitialMounts(id,parentID,rootID){if(__DEBUG__)console.group("crawlAndRecordInitialMounts() id:",id);var internalInstance=idToInternalInstanceMap.get(id);if(internalInstance!=null)internalInstanceToRootIDMap.set(internalInstance,rootID),recordMount(internalInstance,id,parentID),getChildren(internalInstance).forEach(function(child){return crawlAndRecordInitialMounts(getID(child),id,rootID)});if(__DEBUG__)console.groupEnd()}function flushInitialOperations(){var roots=renderer.Mount._instancesByReactRootID||renderer.Mount._instancesByContainerID;for(var key in roots){var internalInstance=roots[key],_id2=getID(internalInstance);crawlAndRecordInitialMounts(_id2,0,_id2),flushPendingEvents(_id2)}}var pendingOperations=[],pendingStringTable=new Map,pendingUnmountedIDs=[],pendingStringTableLength=0,pendingUnmountedRootID=null;function flushPendingEvents(rootID){if(pendingOperations.length===0&&pendingUnmountedIDs.length===0&&pendingUnmountedRootID===null)return;var numUnmountIDs=pendingUnmountedIDs.length+(pendingUnmountedRootID===null?0:1),operations=Array(3+pendingStringTableLength+(numUnmountIDs>0?2+numUnmountIDs:0)+(pendingUnmountedRootID===null?0:3)+pendingOperations.length),i=0;if(operations[i++]=rendererID,operations[i++]=rootID,operations[i++]=pendingStringTableLength,pendingStringTable.forEach(function(value,key){operations[i++]=key.length;var encodedKey=utfEncodeString(key);for(var j2=0;j2<encodedKey.length;j2++)operations[i+j2]=encodedKey[j2];i+=key.length}),numUnmountIDs>0){operations[i++]=TREE_OPERATION_REMOVE,operations[i++]=numUnmountIDs;for(var j=0;j<pendingUnmountedIDs.length;j++)operations[i++]=pendingUnmountedIDs[j];if(pendingUnmountedRootID!==null)operations[i]=pendingUnmountedRootID,i++,operations[i++]=SUSPENSE_TREE_OPERATION_REMOVE,operations[i++]=1,operations[i++]=pendingUnmountedRootID}for(var _j=0;_j<pendingOperations.length;_j++)operations[i+_j]=pendingOperations[_j];if(i+=pendingOperations.length,__DEBUG__)printOperationsArray(operations);hook.emit("operations",operations),pendingOperations.length=0,pendingUnmountedIDs=[],pendingUnmountedRootID=null,pendingStringTable.clear(),pendingStringTableLength=0}function pushOperation(op){pendingOperations.push(op)}function getStringID(str){if(str===null)return 0;var existingID=pendingStringTable.get(str);if(existingID!==void 0)return existingID;var stringID=pendingStringTable.size+1;return pendingStringTable.set(str,stringID),pendingStringTableLength+=str.length+1,stringID}var currentlyInspectedElementID=null,currentlyInspectedPaths={};function mergeInspectedPaths(path){var current=currentlyInspectedPaths;path.forEach(function(key){if(!current[key])current[key]={};current=current[key]})}function createIsPathAllowed(key){return function(path){var current=currentlyInspectedPaths[key];if(!current)return!1;for(var i=0;i<path.length;i++)if(current=current[path[i]],!current)return!1;return!0}}function getInstanceAndStyle(id){var instance=null,style=null,internalInstance=idToInternalInstanceMap.get(id);if(internalInstance!=null){instance=internalInstance._instance||null;var element=internalInstance._currentElement;if(element!=null&&element.props!=null)style=element.props.style||null}return{instance,style}}function updateSelectedElement(id){var internalInstance=idToInternalInstanceMap.get(id);if(internalInstance==null){console.warn('Could not find instance with id "'.concat(id,'"'));return}switch(getElementType(internalInstance)){case types_ElementTypeClass:global.$r=internalInstance._instance;break;case types_ElementTypeFunction:var element=internalInstance._currentElement;if(element==null){console.warn('Could not find element with id "'.concat(id,'"'));return}global.$r={props:element.props,type:element.type};break;default:global.$r=null;break}}function storeAsGlobal(id,path,count){var inspectedElement=inspectElementRaw(id);if(inspectedElement!==null){var value=utils_getInObject(inspectedElement,path),key="$reactTemp".concat(count);window[key]=value,console.log(key),console.log(value)}}function getSerializedElementValueByPath(id,path){var inspectedElement=inspectElementRaw(id);if(inspectedElement!==null){var valueToCopy=utils_getInObject(inspectedElement,path);return serializeToString(valueToCopy)}}function inspectElement(requestID,id,path,forceFullData){if(forceFullData||currentlyInspectedElementID!==id)currentlyInspectedElementID=id,currentlyInspectedPaths={};var inspectedElement=inspectElementRaw(id);if(inspectedElement===null)return{id,responseID:requestID,type:"not-found"};if(path!==null)mergeInspectedPaths(path);return updateSelectedElement(id),inspectedElement.context=cleanForBridge(inspectedElement.context,createIsPathAllowed("context")),inspectedElement.props=cleanForBridge(inspectedElement.props,createIsPathAllowed("props")),inspectedElement.state=cleanForBridge(inspectedElement.state,createIsPathAllowed("state")),inspectedElement.suspendedBy=cleanForBridge(inspectedElement.suspendedBy,createIsPathAllowed("suspendedBy")),{id,responseID:requestID,type:"full-data",value:inspectedElement}}function inspectElementRaw(id){var internalInstance=idToInternalInstanceMap.get(id);if(internalInstance==null)return null;var rootID=internalInstanceToRootIDMap.get(internalInstance);if(rootID===void 0)throw Error("Expected to find root ID.");var isRoot=rootID===id;return isRoot?inspectRootsRaw(rootID):inspectInternalInstanceRaw(id,internalInstance)}function inspectInternalInstanceRaw(id,internalInstance){var _getData2=getData(internalInstance),key=_getData2.key,type=getElementType(internalInstance),context=null,owners=null,props=null,state=null,element=internalInstance._currentElement;if(element!==null){props=element.props;var owner=element._owner;if(owner){owners=[];while(owner!=null)if(owners.push({displayName:getData(owner).displayName||"Unknown",id:getID(owner),key:element.key,env:null,stack:null,type:getElementType(owner)}),owner._currentElement)owner=owner._currentElement._owner}}var publicInstance=internalInstance._instance;if(publicInstance!=null)context=publicInstance.context||null,state=publicInstance.state||null;var errors=[],warnings=[];return{id,canEditHooks:!1,canEditFunctionProps:!1,canEditHooksAndDeletePaths:!1,canEditHooksAndRenamePaths:!1,canEditFunctionPropsDeletePaths:!1,canEditFunctionPropsRenamePaths:!1,canToggleError:!1,isErrored:!1,canToggleSuspense:!1,isSuspended:null,source:null,stack:null,hasLegacyContext:!0,type,key:key!=null?key:null,context,hooks:null,props,state,errors,warnings,suspendedBy:[],suspendedByRange:null,unknownSuspenders:UNKNOWN_SUSPENDERS_NONE,owners,env:null,rootType:null,rendererPackageName:null,rendererVersion:null,plugins:{stylex:null},nativeTag:null}}function inspectRootsRaw(arbitraryRootID){var roots=renderer.Mount._instancesByReactRootID||renderer.Mount._instancesByContainerID,inspectedRoots={id:arbitraryRootID,type:ElementTypeRoot,isErrored:!1,errors:[],warnings:[],suspendedBy:[],suspendedByRange:null,unknownSuspenders:UNKNOWN_SUSPENDERS_NONE,rootType:null,plugins:{stylex:null},nativeTag:null,env:null,source:null,stack:null,rendererPackageName:null,rendererVersion:null,key:null,canEditFunctionProps:!1,canEditHooks:!1,canEditFunctionPropsDeletePaths:!1,canEditFunctionPropsRenamePaths:!1,canEditHooksAndDeletePaths:!1,canEditHooksAndRenamePaths:!1,canToggleError:!1,canToggleSuspense:!1,isSuspended:!1,hasLegacyContext:!1,context:null,hooks:null,props:null,state:null,owners:null},minSuspendedByRange=1/0,maxSuspendedByRange=-1/0;for(var rootKey in roots){var internalInstance=roots[rootKey],_id3=getID(internalInstance),inspectedRoot=inspectInternalInstanceRaw(_id3,internalInstance);if(inspectedRoot===null)return null;if(inspectedRoot.isErrored)inspectedRoots.isErrored=!0;for(var i=0;i<inspectedRoot.errors.length;i++)inspectedRoots.errors.push(inspectedRoot.errors[i]);for(var _i=0;_i<inspectedRoot.warnings.length;_i++)inspectedRoots.warnings.push(inspectedRoot.warnings[_i]);for(var _i2=0;_i2<inspectedRoot.suspendedBy.length;_i2++)inspectedRoots.suspendedBy.push(inspectedRoot.suspendedBy[_i2]);var suspendedByRange=inspectedRoot.suspendedByRange;if(suspendedByRange!==null){if(suspendedByRange[0]<minSuspendedByRange)minSuspendedByRange=suspendedByRange[0];if(suspendedByRange[1]>maxSuspendedByRange)maxSuspendedByRange=suspendedByRange[1]}}if(minSuspendedByRange!==1/0||maxSuspendedByRange!==-1/0)inspectedRoots.suspendedByRange=[minSuspendedByRange,maxSuspendedByRange];return inspectedRoots}function logElementToConsole(id){var result=inspectElementRaw(id);if(result===null){console.warn('Could not find element with id "'.concat(id,'"'));return}var displayName=getDisplayNameForElementID(id),supportsGroup=typeof console.groupCollapsed==="function";if(supportsGroup)console.groupCollapsed("[Click to expand] %c<".concat(displayName||"Component"," />"),"color: var(--dom-tag-name-color); font-weight: normal;");if(result.props!==null)console.log("Props:",result.props);if(result.state!==null)console.log("State:",result.state);if(result.context!==null)console.log("Context:",result.context);var hostInstance=findHostInstanceForInternalID(id);if(hostInstance!==null)console.log("Node:",hostInstance);if(window.chrome||/firefox/i.test(navigator.userAgent))console.log("Right-click any value to save it as a global variable for further inspection.");if(supportsGroup)console.groupEnd()}function getElementAttributeByPath(id,path){var inspectedElement=inspectElementRaw(id);if(inspectedElement!==null)return utils_getInObject(inspectedElement,path);return}function getElementSourceFunctionById(id){var internalInstance=idToInternalInstanceMap.get(id);if(internalInstance==null)return console.warn('Could not find instance with id "'.concat(id,'"')),null;var element=internalInstance._currentElement;if(element==null)return console.warn('Could not find element with id "'.concat(id,'"')),null;return element.type}function deletePath(type,id,hookID,path){var internalInstance=idToInternalInstanceMap.get(id);if(internalInstance!=null){var publicInstance=internalInstance._instance;if(publicInstance!=null)switch(type){case"context":deletePathInObject(publicInstance.context,path),forceUpdate(publicInstance);break;case"hooks":throw Error("Hooks not supported by this renderer");case"props":var element=internalInstance._currentElement;internalInstance._currentElement=legacy_renderer_objectSpread(legacy_renderer_objectSpread({},element),{},{props:copyWithDelete(element.props,path)}),forceUpdate(publicInstance);break;case"state":deletePathInObject(publicInstance.state,path),forceUpdate(publicInstance);break}}}function renamePath(type,id,hookID,oldPath,newPath){var internalInstance=idToInternalInstanceMap.get(id);if(internalInstance!=null){var publicInstance=internalInstance._instance;if(publicInstance!=null)switch(type){case"context":renamePathInObject(publicInstance.context,oldPath,newPath),forceUpdate(publicInstance);break;case"hooks":throw Error("Hooks not supported by this renderer");case"props":var element=internalInstance._currentElement;internalInstance._currentElement=legacy_renderer_objectSpread(legacy_renderer_objectSpread({},element),{},{props:copyWithRename(element.props,oldPath,newPath)}),forceUpdate(publicInstance);break;case"state":renamePathInObject(publicInstance.state,oldPath,newPath),forceUpdate(publicInstance);break}}}function overrideValueAtPath(type,id,hookID,path,value){var internalInstance=idToInternalInstanceMap.get(id);if(internalInstance!=null){var publicInstance=internalInstance._instance;if(publicInstance!=null)switch(type){case"context":utils_setInObject(publicInstance.context,path,value),forceUpdate(publicInstance);break;case"hooks":throw Error("Hooks not supported by this renderer");case"props":var element=internalInstance._currentElement;internalInstance._currentElement=legacy_renderer_objectSpread(legacy_renderer_objectSpread({},element),{},{props:copyWithSet(element.props,path,value)}),forceUpdate(publicInstance);break;case"state":utils_setInObject(publicInstance.state,path,value),forceUpdate(publicInstance);break}}}var getProfilingData=function(){throw Error("getProfilingData not supported by this renderer")},handleCommitFiberRoot=function(){throw Error("handleCommitFiberRoot not supported by this renderer")},handleCommitFiberUnmount=function(){throw Error("handleCommitFiberUnmount not supported by this renderer")},handlePostCommitFiberRoot=function(){throw Error("handlePostCommitFiberRoot not supported by this renderer")},overrideError=function(){throw Error("overrideError not supported by this renderer")},overrideSuspense=function(){throw Error("overrideSuspense not supported by this renderer")},overrideSuspenseMilestone=function(){throw Error("overrideSuspenseMilestone not supported by this renderer")},startProfiling=function(){},stopProfiling=function(){};function getBestMatchForTrackedPath(){return null}function getPathForElement(id){return null}function updateComponentFilters(componentFilters){}function getEnvironmentNames(){return[]}function setTraceUpdatesEnabled(enabled){}function setTrackedPath(path){}function getOwnersList(id){return null}function clearErrorsAndWarnings(){}function clearErrorsForElementID(id){}function clearWarningsForElementID(id){}function hasElementWithId(id){return idToInternalInstanceMap.has(id)}return{clearErrorsAndWarnings,clearErrorsForElementID,clearWarningsForElementID,cleanup,getSerializedElementValueByPath,deletePath,flushInitialOperations,getBestMatchForTrackedPath,getDisplayNameForElementID,getNearestMountedDOMNode,getElementIDForHostInstance,getSuspenseNodeIDForHostInstance:function(id){return null},getInstanceAndStyle,findHostInstancesForElementID:function(id){var hostInstance=findHostInstanceForInternalID(id);return hostInstance==null?null:[hostInstance]},findLastKnownRectsForID:function(){return null},getOwnersList,getPathForElement,getProfilingData,handleCommitFiberRoot,handleCommitFiberUnmount,handlePostCommitFiberRoot,hasElementWithId,inspectElement,logElementToConsole,overrideError,overrideSuspense,overrideSuspenseMilestone,overrideValueAtPath,renamePath,getElementAttributeByPath,getElementSourceFunctionById,renderer,setTraceUpdatesEnabled,setTrackedPath,startProfiling,stopProfiling,storeAsGlobal,supportsTogglingSuspense,updateComponentFilters,getEnvironmentNames}}function isMatchingRender(version){return!hasAssignedBackend(version)}function attachRenderer(hook,id,renderer,global,shouldStartProfilingNow,profilingSettings){if(!isMatchingRender(renderer.reconcilerVersion||renderer.version))return;var rendererInterface=hook.rendererInterfaces.get(id);if(rendererInterface==null){if(typeof renderer.getCurrentComponentInfo==="function")rendererInterface=attach(hook,id,renderer,global);else if(typeof renderer.findFiberByHostInstance==="function"||renderer.currentDispatcherRef!=null)rendererInterface=renderer_attach(hook,id,renderer,global,shouldStartProfilingNow,profilingSettings);else if(renderer.ComponentTree)rendererInterface=legacy_renderer_attach(hook,id,renderer,global)}return rendererInterface}function formatConsoleArguments_toConsumableArray(arr){return formatConsoleArguments_arrayWithoutHoles(arr)||formatConsoleArguments_iterableToArray(arr)||formatConsoleArguments_unsupportedIterableToArray(arr)||formatConsoleArguments_nonIterableSpread()}function formatConsoleArguments_nonIterableSpread(){throw TypeError(`Invalid attempt to spread non-iterable instance.
179
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function formatConsoleArguments_iterableToArray(iter){if(typeof Symbol<"u"&&iter[Symbol.iterator]!=null||iter["@@iterator"]!=null)return Array.from(iter)}function formatConsoleArguments_arrayWithoutHoles(arr){if(Array.isArray(arr))return formatConsoleArguments_arrayLikeToArray(arr)}function formatConsoleArguments_slicedToArray(arr,i){return formatConsoleArguments_arrayWithHoles(arr)||formatConsoleArguments_iterableToArrayLimit(arr,i)||formatConsoleArguments_unsupportedIterableToArray(arr,i)||formatConsoleArguments_nonIterableRest()}function formatConsoleArguments_nonIterableRest(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
180
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function formatConsoleArguments_unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return formatConsoleArguments_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return formatConsoleArguments_arrayLikeToArray(o,minLen)}function formatConsoleArguments_arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function formatConsoleArguments_iterableToArrayLimit(r,l){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,l===0){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r2){o=!0,n=r2}finally{try{if(!f&&t.return!=null&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}function formatConsoleArguments_arrayWithHoles(arr){if(Array.isArray(arr))return arr}function formatConsoleArguments(maybeMessage){for(var _len=arguments.length,inputArgs=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)inputArgs[_key-1]=arguments[_key];if(inputArgs.length===0||typeof maybeMessage!=="string")return[maybeMessage].concat(inputArgs);var args=inputArgs.slice(),template="",argumentsPointer=0;for(var i=0;i<maybeMessage.length;++i){var currentChar=maybeMessage[i];if(currentChar!=="%"){template+=currentChar;continue}var nextChar=maybeMessage[i+1];switch(++i,nextChar){case"c":case"O":case"o":{++argumentsPointer,template+="%".concat(nextChar);break}case"d":case"i":{var _args$splice=args.splice(argumentsPointer,1),_args$splice2=formatConsoleArguments_slicedToArray(_args$splice,1),arg=_args$splice2[0];template+=parseInt(arg,10).toString();break}case"f":{var _args$splice3=args.splice(argumentsPointer,1),_args$splice4=formatConsoleArguments_slicedToArray(_args$splice3,1),_arg=_args$splice4[0];template+=parseFloat(_arg).toString();break}case"s":{var _args$splice5=args.splice(argumentsPointer,1),_args$splice6=formatConsoleArguments_slicedToArray(_args$splice5,1),_arg2=_args$splice6[0];template+=String(_arg2);break}default:template+="%".concat(nextChar)}}return[template].concat(formatConsoleArguments_toConsumableArray(args))}function hook_createForOfIteratorHelper(o,allowArrayLike){var it=typeof Symbol<"u"&&o[Symbol.iterator]||o["@@iterator"];if(!it){if(Array.isArray(o)||(it=hook_unsupportedIterableToArray(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it)o=it;var i=0,F=function(){};return{s:F,n:function(){if(i>=o.length)return{done:!0};return{done:!1,value:o[i++]}},e:function(_e){throw _e},f:F}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
181
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var normalCompletion=!0,didErr=!1,err;return{s:function(){it=it.call(o)},n:function(){var step=it.next();return normalCompletion=step.done,step},e:function(_e2){didErr=!0,err=_e2},f:function(){try{if(!normalCompletion&&it.return!=null)it.return()}finally{if(didErr)throw err}}}}function hook_toConsumableArray(arr){return hook_arrayWithoutHoles(arr)||hook_iterableToArray(arr)||hook_unsupportedIterableToArray(arr)||hook_nonIterableSpread()}function hook_nonIterableSpread(){throw TypeError(`Invalid attempt to spread non-iterable instance.
182
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function hook_unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return hook_arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return hook_arrayLikeToArray(o,minLen)}function hook_iterableToArray(iter){if(typeof Symbol<"u"&&iter[Symbol.iterator]!=null||iter["@@iterator"]!=null)return Array.from(iter)}function hook_arrayWithoutHoles(arr){if(Array.isArray(arr))return hook_arrayLikeToArray(arr)}function hook_arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=Array(len);i<len;i++)arr2[i]=arr[i];return arr2}var PREFIX_REGEX=/\s{4}(in|at)\s{1}/,ROW_COLUMN_NUMBER_REGEX=/:\d+:\d+(\n|$)/;function isStringComponentStack(text){return PREFIX_REGEX.test(text)||ROW_COLUMN_NUMBER_REGEX.test(text)}var frameDiffs=/ \(\<anonymous\>\)$|\@unknown\:0\:0$|\(|\)|\[|\]/gm;function areStackTracesEqual(a,b){return a.replace(frameDiffs,"")===b.replace(frameDiffs,"")}var targetConsole=console,defaultProfilingSettings={recordChangeDescriptions:!1,recordTimeline:!1};function installHook(target,maybeSettingsOrSettingsPromise){var shouldStartProfilingNow=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,profilingSettings=arguments.length>3&&arguments[3]!==void 0?arguments[3]:defaultProfilingSettings;if(target.hasOwnProperty("__REACT_DEVTOOLS_GLOBAL_HOOK__"))return null;function detectReactBuildType(renderer){try{if(typeof renderer.version==="string"){if(renderer.bundleType>0)return"development";return"production"}var _toString=Function.prototype.toString;if(renderer.Mount&&renderer.Mount._renderNewRootComponent){var renderRootCode=_toString.call(renderer.Mount._renderNewRootComponent);if(renderRootCode.indexOf("function")!==0)return"production";if(renderRootCode.indexOf("storedMeasure")!==-1)return"development";if(renderRootCode.indexOf("should be a pure function")!==-1){if(renderRootCode.indexOf("NODE_ENV")!==-1)return"development";if(renderRootCode.indexOf("development")!==-1)return"development";if(renderRootCode.indexOf("true")!==-1)return"development";if(renderRootCode.indexOf("nextElement")!==-1||renderRootCode.indexOf("nextComponent")!==-1)return"unminified";else return"development"}if(renderRootCode.indexOf("nextElement")!==-1||renderRootCode.indexOf("nextComponent")!==-1)return"unminified";return"outdated"}}catch(err){}return"production"}function checkDCE(fn){try{var _toString2=Function.prototype.toString,code=_toString2.call(fn);if(code.indexOf("^_^")>-1)hasDetectedBadDCE=!0,setTimeout(function(){throw Error("React is running in production mode, but dead code elimination has not been applied. Read how to correctly configure React for production: https://react.dev/link/perf-use-production-build")})}catch(err){}}var isProfiling=shouldStartProfilingNow,uidCounter2=0;function inject(renderer){var id=++uidCounter2;renderers.set(id,renderer);var reactBuildType=hasDetectedBadDCE?"deadcode":detectReactBuildType(renderer);hook.emit("renderer",{id,renderer,reactBuildType});var rendererInterface=attachRenderer(hook,id,renderer,target,isProfiling,profilingSettings);if(rendererInterface!=null)hook.rendererInterfaces.set(id,rendererInterface),hook.emit("renderer-attached",{id,rendererInterface});else hook.hasUnsupportedRendererAttached=!0,hook.emit("unsupported-renderer-version");return id}var hasDetectedBadDCE=!1;function sub(event,fn){return hook.on(event,fn),function(){return hook.off(event,fn)}}function on(event,fn){if(!listeners[event])listeners[event]=[];listeners[event].push(fn)}function off(event,fn){if(!listeners[event])return;var index=listeners[event].indexOf(fn);if(index!==-1)listeners[event].splice(index,1);if(!listeners[event].length)delete listeners[event]}function emit(event,data){if(listeners[event])listeners[event].map(function(fn){return fn(data)})}function getFiberRoots(rendererID){var roots=fiberRoots;if(!roots[rendererID])roots[rendererID]=new Set;return roots[rendererID]}function onCommitFiberUnmount(rendererID,fiber){var rendererInterface=rendererInterfaces.get(rendererID);if(rendererInterface!=null)rendererInterface.handleCommitFiberUnmount(fiber)}function onCommitFiberRoot(rendererID,root,priorityLevel){var mountedRoots=hook.getFiberRoots(rendererID),current=root.current,isKnownRoot=mountedRoots.has(root),isUnmounting=current.memoizedState==null||current.memoizedState.element==null;if(!isKnownRoot&&!isUnmounting)mountedRoots.add(root);else if(isKnownRoot&&isUnmounting)mountedRoots.delete(root);var rendererInterface=rendererInterfaces.get(rendererID);if(rendererInterface!=null)rendererInterface.handleCommitFiberRoot(root,priorityLevel)}function onPostCommitFiberRoot(rendererID,root){var rendererInterface=rendererInterfaces.get(rendererID);if(rendererInterface!=null)rendererInterface.handlePostCommitFiberRoot(root)}var isRunningDuringStrictModeInvocation=!1;function setStrictMode(rendererID,isStrictMode){if(isRunningDuringStrictModeInvocation=isStrictMode,isStrictMode)patchConsoleForStrictMode();else unpatchConsoleForStrictMode()}var unpatchConsoleCallbacks=[];function patchConsoleForStrictMode(){if(!hook.settings)return;if(unpatchConsoleCallbacks.length>0)return;var consoleMethodsToOverrideForStrictMode=["group","groupCollapsed","info","log"],_loop=function(){var method=_consoleMethodsToOver[_i],originalMethod=targetConsole[method],overrideMethod=function(){var settings=hook.settings;for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];if(settings==null){originalMethod.apply(void 0,args);return}if(settings.hideConsoleLogsInStrictMode)return;originalMethod.apply(void 0,[ANSI_STYLE_DIMMING_TEMPLATE].concat(hook_toConsumableArray(formatConsoleArguments.apply(void 0,args))))};targetConsole[method]=overrideMethod,unpatchConsoleCallbacks.push(function(){targetConsole[method]=originalMethod})};for(var _i=0,_consoleMethodsToOver=consoleMethodsToOverrideForStrictMode;_i<_consoleMethodsToOver.length;_i++)_loop()}function unpatchConsoleForStrictMode(){unpatchConsoleCallbacks.forEach(function(callback){return callback()}),unpatchConsoleCallbacks.length=0}var openModuleRangesStack=[],moduleRanges=[];function getTopStackFrameString(error){var frames=error.stack.split(`
183
+ `),frame=frames.length>1?frames[1]:null;return frame}function getInternalModuleRanges(){return moduleRanges}function registerInternalModuleStart(error){var startStackFrame=getTopStackFrameString(error);if(startStackFrame!==null)openModuleRangesStack.push(startStackFrame)}function registerInternalModuleStop(error){if(openModuleRangesStack.length>0){var startStackFrame=openModuleRangesStack.pop(),stopStackFrame=getTopStackFrameString(error);if(stopStackFrame!==null)moduleRanges.push([startStackFrame,stopStackFrame])}}function patchConsoleForErrorsAndWarnings(){if(!hook.settings)return;var consoleMethodsToOverrideForErrorsAndWarnings=["error","trace","warn"],_loop2=function(){var method=_consoleMethodsToOver2[_i2],originalMethod=targetConsole[method],overrideMethod=function(){var settings=hook.settings;for(var _len2=arguments.length,args=Array(_len2),_key2=0;_key2<_len2;_key2++)args[_key2]=arguments[_key2];if(settings==null){originalMethod.apply(void 0,args);return}if(isRunningDuringStrictModeInvocation&&settings.hideConsoleLogsInStrictMode)return;var injectedComponentStackAsFakeError=!1,alreadyHasComponentStack=!1;if(settings.appendComponentStack){var lastArg=args.length>0?args[args.length-1]:null;alreadyHasComponentStack=typeof lastArg==="string"&&isStringComponentStack(lastArg)}var shouldShowInlineWarningsAndErrors=settings.showInlineWarningsAndErrors&&(method==="error"||method==="warn"),_iterator=hook_createForOfIteratorHelper(hook.rendererInterfaces.values()),_step;try{var _loop3=function(){var rendererInterface=_step.value,onErrorOrWarning=rendererInterface.onErrorOrWarning,getComponentStack=rendererInterface.getComponentStack;try{if(shouldShowInlineWarningsAndErrors){if(onErrorOrWarning!=null)onErrorOrWarning(method,args.slice())}}catch(error){setTimeout(function(){throw error},0)}try{if(settings.appendComponentStack&&getComponentStack!=null){var topFrame=Error("react-stack-top-frame"),match=getComponentStack(topFrame);if(match!==null){var{enableOwnerStacks,componentStack}=match;if(componentStack!==""){var fakeError=Error("");if(fakeError.name=enableOwnerStacks?"Stack":"Component Stack",fakeError.stack=(enableOwnerStacks?"Error Stack:":"Error Component Stack:")+componentStack,alreadyHasComponentStack){if(areStackTracesEqual(args[args.length-1],componentStack)){var firstArg=args[0];if(args.length>1&&typeof firstArg==="string"&&firstArg.endsWith("%s"))args[0]=firstArg.slice(0,firstArg.length-2);args[args.length-1]=fakeError,injectedComponentStackAsFakeError=!0}}else args.push(fakeError),injectedComponentStackAsFakeError=!0}return 1}}}catch(error){setTimeout(function(){throw error},0)}};for(_iterator.s();!(_step=_iterator.n()).done;)if(_loop3())break}catch(err){_iterator.e(err)}finally{_iterator.f()}if(settings.breakOnConsoleErrors)debugger;if(isRunningDuringStrictModeInvocation)if(!1)var argsWithCSSStyles;else originalMethod.apply(void 0,[injectedComponentStackAsFakeError?ANSI_STYLE_DIMMING_TEMPLATE_WITH_COMPONENT_STACK:ANSI_STYLE_DIMMING_TEMPLATE].concat(hook_toConsumableArray(formatConsoleArguments.apply(void 0,args))));else originalMethod.apply(void 0,args)};targetConsole[method]=overrideMethod};for(var _i2=0,_consoleMethodsToOver2=consoleMethodsToOverrideForErrorsAndWarnings;_i2<_consoleMethodsToOver2.length;_i2++)_loop2()}var fiberRoots={},rendererInterfaces=new Map,listeners={},renderers=new Map,backends=new Map,hook={rendererInterfaces,listeners,backends,renderers,hasUnsupportedRendererAttached:!1,emit,getFiberRoots,inject,on,off,sub,supportsFiber:!0,supportsFlight:!0,checkDCE,onCommitFiberUnmount,onCommitFiberRoot,onPostCommitFiberRoot,setStrictMode,getInternalModuleRanges,registerInternalModuleStart,registerInternalModuleStop};if(maybeSettingsOrSettingsPromise==null)hook.settings={appendComponentStack:!0,breakOnConsoleErrors:!1,showInlineWarningsAndErrors:!0,hideConsoleLogsInStrictMode:!1},patchConsoleForErrorsAndWarnings();else Promise.resolve(maybeSettingsOrSettingsPromise).then(function(settings){hook.settings=settings,hook.emit("settingsInitialized",settings),patchConsoleForErrorsAndWarnings()}).catch(function(){targetConsole.error("React DevTools failed to get Console Patching settings. Console won't be patched and some console features will not work.")});return Object.defineProperty(target,"__REACT_DEVTOOLS_GLOBAL_HOOK__",{configurable:!1,enumerable:!1,get:function(){return hook}}),hook}function initBackend(hook,agent2,global,isReloadAndProfileSupported){if(hook==null)return function(){};function registerRendererInterface(id,rendererInterface){agent2.registerRendererInterface(id,rendererInterface),rendererInterface.flushInitialOperations()}var subs=[hook.sub("renderer-attached",function(_ref){var{id,rendererInterface}=_ref;registerRendererInterface(id,rendererInterface)}),hook.sub("unsupported-renderer-version",function(){agent2.onUnsupportedRenderer()}),hook.sub("fastRefreshScheduled",agent2.onFastRefreshScheduled),hook.sub("operations",agent2.onHookOperations),hook.sub("traceUpdates",agent2.onTraceUpdates),hook.sub("settingsInitialized",agent2.onHookSettings)];agent2.addListener("getIfHasUnsupportedRendererVersion",function(){if(hook.hasUnsupportedRendererAttached)agent2.onUnsupportedRenderer()}),hook.rendererInterfaces.forEach(function(rendererInterface,id){registerRendererInterface(id,rendererInterface)}),hook.emit("react-devtools",agent2),hook.reactDevtoolsAgent=agent2;var onAgentShutdown=function(){subs.forEach(function(fn){return fn()}),hook.rendererInterfaces.forEach(function(rendererInterface){rendererInterface.cleanup()}),hook.reactDevtoolsAgent=null};if(agent2.addListener("shutdown",onAgentShutdown),agent2.addListener("updateHookSettings",function(settings){hook.settings=settings}),agent2.addListener("getHookSettings",function(){if(hook.settings!=null)agent2.onHookSettings(hook.settings)}),isReloadAndProfileSupported)agent2.onReloadAndProfileSupportedByHost();return function(){subs.forEach(function(fn){return fn()})}}function resolveBoxStyle(prefix2,style){var hasParts=!1,result={bottom:0,left:0,right:0,top:0},styleForAll=style[prefix2];if(styleForAll!=null){for(var _i=0,_Object$keys=Object.keys(result);_i<_Object$keys.length;_i++){var key=_Object$keys[_i];result[key]=styleForAll}hasParts=!0}var styleForHorizontal=style[prefix2+"Horizontal"];if(styleForHorizontal!=null)result.left=styleForHorizontal,result.right=styleForHorizontal,hasParts=!0;else{var styleForLeft=style[prefix2+"Left"];if(styleForLeft!=null)result.left=styleForLeft,hasParts=!0;var styleForRight=style[prefix2+"Right"];if(styleForRight!=null)result.right=styleForRight,hasParts=!0;var styleForEnd=style[prefix2+"End"];if(styleForEnd!=null)result.right=styleForEnd,hasParts=!0;var styleForStart=style[prefix2+"Start"];if(styleForStart!=null)result.left=styleForStart,hasParts=!0}var styleForVertical=style[prefix2+"Vertical"];if(styleForVertical!=null)result.bottom=styleForVertical,result.top=styleForVertical,hasParts=!0;else{var styleForBottom=style[prefix2+"Bottom"];if(styleForBottom!=null)result.bottom=styleForBottom,hasParts=!0;var styleForTop=style[prefix2+"Top"];if(styleForTop!=null)result.top=styleForTop,hasParts=!0}return hasParts?result:null}function setupNativeStyleEditor_typeof(o){return setupNativeStyleEditor_typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o2){return typeof o2}:function(o2){return o2&&typeof Symbol=="function"&&o2.constructor===Symbol&&o2!==Symbol.prototype?"symbol":typeof o2},setupNativeStyleEditor_typeof(o)}function setupNativeStyleEditor_defineProperty(obj,key,value){if(key=setupNativeStyleEditor_toPropertyKey(key),key in obj)Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0});else obj[key]=value;return obj}function setupNativeStyleEditor_toPropertyKey(t){var i=setupNativeStyleEditor_toPrimitive(t,"string");return setupNativeStyleEditor_typeof(i)=="symbol"?i:i+""}function setupNativeStyleEditor_toPrimitive(t,r){if(setupNativeStyleEditor_typeof(t)!="object"||!t)return t;var e=t[Symbol.toPrimitive];if(e!==void 0){var i=e.call(t,r||"default");if(setupNativeStyleEditor_typeof(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(t)}function setupNativeStyleEditor(bridge,agent2,resolveNativeStyle,validAttributes){bridge.addListener("NativeStyleEditor_measure",function(_ref){var{id,rendererID}=_ref;measureStyle(agent2,bridge,resolveNativeStyle,id,rendererID)}),bridge.addListener("NativeStyleEditor_renameAttribute",function(_ref2){var{id,rendererID,oldName,newName,value}=_ref2;renameStyle(agent2,id,rendererID,oldName,newName,value),setTimeout(function(){return measureStyle(agent2,bridge,resolveNativeStyle,id,rendererID)})}),bridge.addListener("NativeStyleEditor_setValue",function(_ref3){var{id,rendererID,name,value}=_ref3;setStyle(agent2,id,rendererID,name,value),setTimeout(function(){return measureStyle(agent2,bridge,resolveNativeStyle,id,rendererID)})}),bridge.send("isNativeStyleEditorSupported",{isSupported:!0,validAttributes})}var EMPTY_BOX_STYLE={top:0,left:0,right:0,bottom:0},componentIDToStyleOverrides=new Map;function measureStyle(agent2,bridge,resolveNativeStyle,id,rendererID){var data=agent2.getInstanceAndStyle({id,rendererID});if(!data||!data.style){bridge.send("NativeStyleEditor_styleAndLayout",{id,layout:null,style:null});return}var{instance,style}=data,resolvedStyle=resolveNativeStyle(style),styleOverrides=componentIDToStyleOverrides.get(id);if(styleOverrides!=null)resolvedStyle=Object.assign({},resolvedStyle,styleOverrides);if(!instance||typeof instance.measure!=="function"){bridge.send("NativeStyleEditor_styleAndLayout",{id,layout:null,style:resolvedStyle||null});return}instance.measure(function(x,y,width,height,left,top){if(typeof x!=="number"){bridge.send("NativeStyleEditor_styleAndLayout",{id,layout:null,style:resolvedStyle||null});return}var margin=resolvedStyle!=null&&resolveBoxStyle("margin",resolvedStyle)||EMPTY_BOX_STYLE,padding=resolvedStyle!=null&&resolveBoxStyle("padding",resolvedStyle)||EMPTY_BOX_STYLE;bridge.send("NativeStyleEditor_styleAndLayout",{id,layout:{x,y,width,height,left,top,margin,padding},style:resolvedStyle||null})})}function shallowClone(object){var cloned={};for(var n in object)cloned[n]=object[n];return cloned}function renameStyle(agent2,id,rendererID,oldName,newName,value){var data=agent2.getInstanceAndStyle({id,rendererID});if(!data||!data.style)return;var{instance,style}=data,newStyle=newName?setupNativeStyleEditor_defineProperty(setupNativeStyleEditor_defineProperty({},oldName,void 0),newName,value):setupNativeStyleEditor_defineProperty({},oldName,void 0),customStyle;if(instance!==null&&typeof instance.setNativeProps==="function"){var styleOverrides=componentIDToStyleOverrides.get(id);if(!styleOverrides)componentIDToStyleOverrides.set(id,newStyle);else Object.assign(styleOverrides,newStyle);instance.setNativeProps({style:newStyle})}else if(src_isArray(style)){var lastIndex=style.length-1;if(setupNativeStyleEditor_typeof(style[lastIndex])==="object"&&!src_isArray(style[lastIndex])){if(customStyle=shallowClone(style[lastIndex]),delete customStyle[oldName],newName)customStyle[newName]=value;else customStyle[oldName]=void 0;agent2.overrideValueAtPath({type:"props",id,rendererID,path:["style",lastIndex],value:customStyle})}else agent2.overrideValueAtPath({type:"props",id,rendererID,path:["style"],value:style.concat([newStyle])})}else if(setupNativeStyleEditor_typeof(style)==="object"){if(customStyle=shallowClone(style),delete customStyle[oldName],newName)customStyle[newName]=value;else customStyle[oldName]=void 0;agent2.overrideValueAtPath({type:"props",id,rendererID,path:["style"],value:customStyle})}else agent2.overrideValueAtPath({type:"props",id,rendererID,path:["style"],value:[style,newStyle]});agent2.emit("hideNativeHighlight")}function setStyle(agent2,id,rendererID,name,value){var data=agent2.getInstanceAndStyle({id,rendererID});if(!data||!data.style)return;var{instance,style}=data,newStyle=setupNativeStyleEditor_defineProperty({},name,value);if(instance!==null&&typeof instance.setNativeProps==="function"){var styleOverrides=componentIDToStyleOverrides.get(id);if(!styleOverrides)componentIDToStyleOverrides.set(id,newStyle);else Object.assign(styleOverrides,newStyle);instance.setNativeProps({style:newStyle})}else if(src_isArray(style)){var lastLength=style.length-1;if(setupNativeStyleEditor_typeof(style[lastLength])==="object"&&!src_isArray(style[lastLength]))agent2.overrideValueAtPath({type:"props",id,rendererID,path:["style",lastLength,name],value});else agent2.overrideValueAtPath({type:"props",id,rendererID,path:["style"],value:style.concat([newStyle])})}else agent2.overrideValueAtPath({type:"props",id,rendererID,path:["style"],value:[style,newStyle]});agent2.emit("hideNativeHighlight")}var savedComponentFilters=getDefaultComponentFilters();function backend_debug(methodName){if(__DEBUG__){var _console;for(var _len=arguments.length,args=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)args[_key-1]=arguments[_key];(_console=console).log.apply(_console,["%c[core/backend] %c".concat(methodName),"color: teal; font-weight: bold;","font-weight: bold;"].concat(args))}}function backend_initialize(maybeSettingsOrSettingsPromise){var shouldStartProfilingNow=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,profilingSettings=arguments.length>2?arguments[2]:void 0;installHook(window,maybeSettingsOrSettingsPromise,shouldStartProfilingNow,profilingSettings)}function connectToDevTools(options){var hook=window.__REACT_DEVTOOLS_GLOBAL_HOOK__;if(hook==null)return;var _ref=options||{},_ref$host=_ref.host,host=_ref$host===void 0?"localhost":_ref$host,nativeStyleEditorValidAttributes=_ref.nativeStyleEditorValidAttributes,_ref$useHttps=_ref.useHttps,useHttps=_ref$useHttps===void 0?!1:_ref$useHttps,_ref$port=_ref.port,port=_ref$port===void 0?8097:_ref$port,websocket=_ref.websocket,_ref$resolveRNStyle=_ref.resolveRNStyle,resolveRNStyle=_ref$resolveRNStyle===void 0?null:_ref$resolveRNStyle,_ref$retryConnectionD=_ref.retryConnectionDelay,retryConnectionDelay=_ref$retryConnectionD===void 0?2000:_ref$retryConnectionD,_ref$isAppActive=_ref.isAppActive,isAppActive=_ref$isAppActive===void 0?function(){return!0}:_ref$isAppActive,onSettingsUpdated=_ref.onSettingsUpdated,_ref$isReloadAndProfi=_ref.isReloadAndProfileSupported,isReloadAndProfileSupported=_ref$isReloadAndProfi===void 0?getIsReloadAndProfileSupported():_ref$isReloadAndProfi,isProfiling=_ref.isProfiling,onReloadAndProfile2=_ref.onReloadAndProfile,onReloadAndProfileFlagsReset2=_ref.onReloadAndProfileFlagsReset,protocol=useHttps?"wss":"ws",retryTimeoutID=null;function scheduleRetry(){if(retryTimeoutID===null)retryTimeoutID=setTimeout(function(){return connectToDevTools(options)},retryConnectionDelay)}if(!isAppActive()){scheduleRetry();return}var bridge=null,messageListeners=[],uri=protocol+"://"+host+":"+port,ws=websocket?websocket:new window.WebSocket(uri);ws.onclose=handleClose,ws.onerror=handleFailed,ws.onmessage=handleMessage,ws.onopen=function(){if(bridge=new src_bridge({listen:function(fn){return messageListeners.push(fn),function(){var index=messageListeners.indexOf(fn);if(index>=0)messageListeners.splice(index,1)}},send:function(event,payload,transferable){if(ws.readyState===ws.OPEN){if(__DEBUG__)backend_debug("wall.send()",event,payload);ws.send(JSON.stringify({event,payload}))}else{if(__DEBUG__)backend_debug("wall.send()","Shutting down bridge because of closed WebSocket connection");if(bridge!==null)bridge.shutdown();scheduleRetry()}}}),bridge.addListener("updateComponentFilters",function(componentFilters){savedComponentFilters=componentFilters}),window.__REACT_DEVTOOLS_COMPONENT_FILTERS__==null)bridge.send("overrideComponentFilters",savedComponentFilters);var agent2=new Agent(bridge,isProfiling,onReloadAndProfile2);if(typeof onReloadAndProfileFlagsReset2==="function")onReloadAndProfileFlagsReset2();if(onSettingsUpdated!=null)agent2.addListener("updateHookSettings",onSettingsUpdated);if(agent2.addListener("shutdown",function(){if(onSettingsUpdated!=null)agent2.removeListener("updateHookSettings",onSettingsUpdated);hook.emit("shutdown")}),initBackend(hook,agent2,window,isReloadAndProfileSupported),resolveRNStyle!=null||hook.resolveRNStyle!=null)setupNativeStyleEditor(bridge,agent2,resolveRNStyle||hook.resolveRNStyle,nativeStyleEditorValidAttributes||hook.nativeStyleEditorValidAttributes||null);else{var lazyResolveRNStyle,lazyNativeStyleEditorValidAttributes,initAfterTick=function(){if(bridge!==null)setupNativeStyleEditor(bridge,agent2,lazyResolveRNStyle,lazyNativeStyleEditorValidAttributes)};if(!hook.hasOwnProperty("resolveRNStyle"))Object.defineProperty(hook,"resolveRNStyle",{enumerable:!1,get:function(){return lazyResolveRNStyle},set:function(value){lazyResolveRNStyle=value,initAfterTick()}});if(!hook.hasOwnProperty("nativeStyleEditorValidAttributes"))Object.defineProperty(hook,"nativeStyleEditorValidAttributes",{enumerable:!1,get:function(){return lazyNativeStyleEditorValidAttributes},set:function(value){lazyNativeStyleEditorValidAttributes=value,initAfterTick()}})}};function handleClose(){if(__DEBUG__)backend_debug("WebSocket.onclose");if(bridge!==null)bridge.emit("shutdown");scheduleRetry()}function handleFailed(){if(__DEBUG__)backend_debug("WebSocket.onerror");scheduleRetry()}function handleMessage(event){var data;try{if(typeof event.data==="string"){if(data=JSON.parse(event.data),__DEBUG__)backend_debug("WebSocket.onmessage",data)}else throw Error()}catch(e){console.error("[React DevTools] Failed to parse JSON: "+event.data);return}messageListeners.forEach(function(fn){try{fn(data)}catch(error){throw console.log("[React DevTools] Error calling listener",data),console.log("error:",error),error}})}}function connectWithCustomMessagingProtocol(_ref2){var{onSubscribe,onUnsubscribe,onMessage,nativeStyleEditorValidAttributes,resolveRNStyle,onSettingsUpdated,isReloadAndProfileSupported:_ref2$isReloadAndProf}=_ref2,isReloadAndProfileSupported=_ref2$isReloadAndProf===void 0?getIsReloadAndProfileSupported():_ref2$isReloadAndProf,isProfiling=_ref2.isProfiling,onReloadAndProfile2=_ref2.onReloadAndProfile,onReloadAndProfileFlagsReset2=_ref2.onReloadAndProfileFlagsReset,hook=window.__REACT_DEVTOOLS_GLOBAL_HOOK__;if(hook==null)return;var wall={listen:function(fn){return onSubscribe(fn),function(){onUnsubscribe(fn)}},send:function(event,payload){onMessage(event,payload)}},bridge=new src_bridge(wall);if(bridge.addListener("updateComponentFilters",function(componentFilters){savedComponentFilters=componentFilters}),window.__REACT_DEVTOOLS_COMPONENT_FILTERS__==null)bridge.send("overrideComponentFilters",savedComponentFilters);var agent2=new Agent(bridge,isProfiling,onReloadAndProfile2);if(typeof onReloadAndProfileFlagsReset2==="function")onReloadAndProfileFlagsReset2();if(onSettingsUpdated!=null)agent2.addListener("updateHookSettings",onSettingsUpdated);agent2.addListener("shutdown",function(){if(onSettingsUpdated!=null)agent2.removeListener("updateHookSettings",onSettingsUpdated);hook.emit("shutdown")});var unsubscribeBackend=initBackend(hook,agent2,window,isReloadAndProfileSupported),nativeStyleResolver=resolveRNStyle||hook.resolveRNStyle;if(nativeStyleResolver!=null){var validAttributes=nativeStyleEditorValidAttributes||hook.nativeStyleEditorValidAttributes||null;setupNativeStyleEditor(bridge,agent2,nativeStyleResolver,validAttributes)}return unsubscribeBackend}})(),__webpack_exports__})()})});var exports_devtools={};__export(exports_devtools,{isDevToolsConnected:()=>isDevToolsConnected,connectDevTools:()=>connectDevTools,autoConnectDevTools:()=>autoConnectDevTools});async function connectDevTools(){if(connected)return!0;try{if(typeof globalThis.WebSocket>"u")try{let ws=await Promise.resolve().then(() => (init_wrapper(),exports_wrapper));globalThis.WebSocket=ws.default??ws}catch{return console.warn("silvery devtools: 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 Promise.resolve().then(() => __toESM(require_backend(),1));return devtools.initialize(),devtools.connectToDevTools(),reconciler.injectIntoDevTools(),connected=!0,!0}catch(error){let message=error instanceof Error?error.message:String(error);return console.warn(`silvery devtools: Failed to connect to React DevTools. Install react-devtools-core: bun add -d react-devtools-core
184
+ Error: ${message}`),!1}}function isDevToolsConnected(){return connected}async function autoConnectDevTools(){if(process.env.DEBUG_DEVTOOLS==="1"||process.env.DEBUG_DEVTOOLS==="true")await connectDevTools()}var connected=!1;var init_devtools=__esm(()=>{init_reconciler()});import process2 from"node:process";import{createLogger as createLogger7}from"loggily";import{useCallback as useCallback28,useEffect as useEffect19,useMemo as useMemo18,useRef as useRef24}from"react";import{jsxDEV as jsxDEV49}from"react/jsx-dev-runtime";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()}}async function ensureLayoutEngineInitialized(engineType){if(isLayoutEngineInitialized()){log5.debug?.("Layout engine already initialized");return}log5.debug?.(`Initializing layout engine (${engineType??"default"})...`);let startTime=Date.now(),{ensureDefaultLayoutEngine:ensureDefaultLayoutEngine2}=await Promise.resolve().then(() => exports_layout_engine);await ensureDefaultLayoutEngine2(engineType),log5.debug?.(`Layout engine initialized in ${Date.now()-startTime}ms`)}function createSubscriberList(){return{input:new Set,paste:new Set}}function SilveryApp({children,onInputSubscribe,exitOnCtrlC,stdoutWrite,stdout,onExit,onPause,onResume,onScrollback,getRoot:getRootProp,handleFocusCycling=!0}){let subscribersRef=useRef24(null);if(!subscribersRef.current)subscribersRef.current=createSubscriberList();let subscribers=subscribersRef.current,handleExit=useCallback28((error)=>{onExit(error)},[onExit]),exitOnCtrlCRef=useRef24(exitOnCtrlC);exitOnCtrlCRef.current=exitOnCtrlC;let handleExitRef=useRef24(handleExit);handleExitRef.current=handleExit;let focusManagerRef=useRef24(null),getRootRef=useRef24(getRootProp);getRootRef.current=getRootProp;let handleFocusCyclingRef=useRef24(handleFocusCycling);handleFocusCyclingRef.current=handleFocusCycling;let handleChunkRef=useRef24(null);if(handleChunkRef.current===null){let processSingleKey=function(chunk){if(log5.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)=>{log5.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;useEffect19(()=>{if(!onInputSubscribe)return;return onInputSubscribe(handleChunk)},[onInputSubscribe,handleChunk]);let stdoutContextValue=useMemo18(()=>({stdout,write:stdoutWrite,notifyScrollback:onScrollback}),[stdout,stdoutWrite,onScrollback]),runtimeContextValue=useMemo18(()=>({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=useMemo18(()=>createFocusManager(),[]);return focusManagerRef.current=focusManager,useEffect19(()=>{return setOnNodeRemoved((removedNode)=>focusManager.handleSubtreeRemoved(removedNode)),()=>setOnNodeRemoved(null)},[focusManager]),jsxDEV49(StdoutContext.Provider,{value:stdoutContextValue,children:jsxDEV49(StderrContext.Provider,{value:{stderr:process2.stderr,write:(data)=>{process2.stderr.write(data)}},children:jsxDEV49(FocusManagerContext.Provider,{value:focusManager,children:jsxDEV49(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)}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){log5.debug?.(`render() called, isStatic=${resolved.isStatic}`);let renderStart=Date.now();if(await ensureLayoutEngineInitialized(options.layoutEngine),log5.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)log5.debug?.("render(): creating new SilveryInstance"),instance=new SilveryInstance(resolvedOptions),instances.set(resolvedOptions.stdout,instance),log5.debug?.(`render(): SilveryInstance created in ${Date.now()-renderStart}ms`);let wrappedElement=jsxDEV49(TermContext.Provider,{value:term2,children:element},void 0,!1,void 0,this);return log5.debug?.("render(): calling instance.render()"),instance.render(wrappedElement),log5.debug?.(`render(): instance.render() complete, total: ${Date.now()-renderStart}ms`),{rerender:(newElement)=>instance.rerender(jsxDEV49(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){log5.debug?.(`renderStatic() called, dimensions: ${resolved.width}x${resolved.height}`);let{renderStringSync:renderStringSync2}=await Promise.resolve().then(() => (init_render_string(),exports_render_string)),wrappedElement=jsxDEV49(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(`
185
+ `);let lastFrame=output;return{rerender:(newElement)=>{let newWrapped=jsxDEV49(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(`
186
+ `)},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=jsxDEV49(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(`
187
+ `);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=jsxDEV49(TermContext.Provider,{value:term2,children:element},void 0,!1,void 0,this);return instance.render(wrappedElement),{rerender:(newElement)=>instance.rerender(jsxDEV49(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)}var log5,instances,SilveryInstance;var init_render=__esm(()=>{init_ansi();init_context();init_useCursor();init_focus_manager();init_keys();init_output();init_reconciler();init_render_string();init_scheduler();init_keys();init_flexily_zero_adapter();log5=createLogger7("silvery:render");instances=new Map;SilveryInstance=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;constructor(options){log5.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)enableBracketedPaste(this.stdout);this.cursorStore=createCursorStore(),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}),this.setupResizeListener(),this.setupSignalHandlers(),log5.debug?.(`SilveryInstance constructor complete in ${Date.now()-startTime}ms`)}render(element){log5.debug?.("SilveryInstance.render() start");let startTime=Date.now();if(this.isUnmounted||!this.fiberRoot)return;this.lastElement=element;let tree=jsxDEV49(CursorProvider,{store:this.cursorStore,children:jsxDEV49(SilveryApp,{onInputSubscribe:this.subscribeToInput,exitOnCtrlC:this.exitOnCtrlC,stdoutWrite:(data)=>{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);log5.debug?.("SilveryInstance.render() calling updateContainerSync"),reconciler.updateContainerSync(tree,this.fiberRoot,null,null),log5.debug?.(`SilveryInstance.render() updateContainerSync complete in ${Date.now()-startTime}ms`),log5.debug?.("SilveryInstance.render() calling flushSyncWork");let flushStart=Date.now();reconciler.flushSyncWork(),log5.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.stdout.isTTY)disableBracketedPaste(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}
188
+ `);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(log5.debug?.(`subscribeToInput: stdin=${stdin===process2.stdin?"process.stdin":"other"}, isTTY=${stdin.isTTY}, isRawModeSupported=${isRawModeSupported}`),!isRawModeSupported)return log5.debug?.("subscribeToInput: raw mode not supported, skipping"),()=>{};let handleReadable=()=>{let chunk;while((chunk=stdin.read())!==null)log5.debug?.(`subscribeToInput: stdin.read() returned: ${JSON.stringify(chunk)}`),handler(chunk)};return stdin.setEncoding("utf8"),stdin.ref(),stdin.setRawMode(!0),stdin.on("readable",handleReadable),log5.debug?.(`subscribeToInput: enabled raw mode, stdin.isRaw=${stdin.isRaw}`),()=>{log5.debug?.("subscribeToInput: cleanup — disabling raw mode"),stdin.setRawMode(!1),stdin.off("readable",handleReadable),stdin.unref()}}}});function resolveNode(nodeOrHandle){if(!nodeOrHandle)return null;if(typeof nodeOrHandle.getNode==="function")return nodeOrHandle.getNode();return nodeOrHandle}function measureElement(nodeOrHandle){let node=resolveNode(nodeOrHandle);if(!node)return{width:0,height:0};if(node.contentRect)return{width:node.contentRect.width,height:node.contentRect.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 React27 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"?`
189
+ `:" ";return parts.join(sep)}if(React27.isValidElement(node)){let props=node.props;if(props["aria-hidden"])return"";if(props.display==="none")return"";let direction=props.flexDirection==="column"?"column":"row",content;if(props["aria-label"]!=null)content=String(props["aria-label"]);else{let children=props.children;content=walkChildren(children,direction)}let statePrefix=buildStatePrefix(props["aria-state"]),role=props["aria-role"];if(role&&statePrefix)return`${role}: ${statePrefix}${content}`;if(role)return`${role}: ${content}`;if(statePrefix)return`${statePrefix}${content}`;return content}return""}function walkChildren(children,direction){if(children==null)return"";if(!Array.isArray(children)){let childArray=React27.Children.toArray(children);if(childArray.length<=1)return walkNode(children,direction);let parts2=childArray.map((child)=>walkNode(child,direction)).filter((s)=>s!==""),sep2=direction==="column"?`
190
+ `:" ";return parts2.join(sep2)}let parts=children.map((child)=>walkNode(child,direction)).filter((s)=>s!==""),sep=direction==="column"?`
191
+ `:" ";return parts.join(sep)}function buildStatePrefix(state){if(!state)return"";let activeStates=[],stateNames=["busy","checked","disabled","expanded","multiline","multiselectable","readonly","required","selected"];for(let name of stateNames)if(state[name])activeStates.push(`(${name})`);if(activeStates.length===0)return"";return activeStates.join(" ")+" "}var init_accessibility=()=>{};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;case 3:return hex.slice(0,2);case 4:return hex.slice(0,2);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})$/});async function detectKittySupport(write,read,timeoutMs=200){write(queryKittyKeyboard());let data=await read(timeoutMs);if(data==null)return{supported:!1,flags:0};let match=KITTY_RESPONSE_RE.exec(data);if(!match)return{supported:!1,flags:0,buffered:data};let flags=parseInt(match[1],10),before=data.slice(0,match.index),after=data.slice(match.index+match[0].length),buffered=before+after;return{supported:!0,flags,buffered:buffered||void 0}}async function detectKittyFromStdio(stdout,stdin,timeoutMs=200){let wasRaw=stdin.isRaw;if(!wasRaw)stdin.setRawMode(!0);try{return await detectKittySupport((s)=>{stdout.write(s)},(ms)=>new Promise((resolve)=>{let timer=setTimeout(()=>{stdin.removeListener("data",onData),resolve(null)},ms);function onData(chunk){clearTimeout(timer),stdin.removeListener("data",onData),resolve(chunk.toString())}stdin.on("data",onData)}),timeoutMs)}finally{if(!wasRaw)stdin.setRawMode(!1)}}var KITTY_RESPONSE_RE;var init_kitty_detect=__esm(()=>{init_output();KITTY_RESPONSE_RE=/\x1b\[\?(\d+)u/});var init_terminal_caps=__esm(()=>{init_detection()});function sgr(...codes){return`${CSI2}${codes.join(";")}m`}function sectionHeader(title){return`
192
+ ${sgr(1)}═══ ${title} ═══${RESET2}
193
+ `}function row(label,content){return` ${label.padEnd(24)} ${content}${RESET2}`}function runTermtest(options){let w=options?.output??process.stdout,filter=options?.sections,show=(s)=>!filter||filter.length===0||filter.includes(s),caps=detectTerminalCaps();if(w.write(`
194
+ ${sgr(1)}Terminal Capability Test${RESET2}
195
+ `),w.write(` Program: ${caps.program||"(unknown)"}
196
+ `),w.write(` TERM: ${caps.term||"(unknown)"}
197
+ `),w.write(` COLORTERM: ${process.env.COLORTERM||"(unset)"}
198
+ `),w.write(` Detected: color=${caps.colorLevel} dark=${caps.darkBackground} nerdfont=${caps.nerdfont}
199
+ `),w.write(` Underline: styles=${caps.underlineStyles} color=${caps.underlineColor}
200
+ `),w.write(` Emoji wide: ${caps.textEmojiWide}
201
+ `),show("sgr"))w.write(sectionHeader("SGR Text Attributes")),w.write(row("Bold",`${sgr(1)}The quick brown fox${RESET2}`)+`
202
+ `),w.write(row("Dim",`${sgr(2)}The quick brown fox${RESET2}`)+`
203
+ `),w.write(row("Italic",`${sgr(3)}The quick brown fox${RESET2}`)+`
204
+ `),w.write(row("Underline",`${sgr(4)}The quick brown fox${RESET2}`)+`
205
+ `),w.write(row("Strikethrough",`${sgr(9)}The quick brown fox${RESET2}`)+`
206
+ `),w.write(row("Inverse",`${sgr(7)}The quick brown fox${RESET2}`)+`
207
+ `),w.write(row("Blink",`${sgr(5)}The quick brown fox${RESET2}`)+`
208
+ `),w.write(row("Bold+Italic",`${sgr(1,3)}The quick brown fox${RESET2}`)+`
209
+ `);if(show("underline"))w.write(sectionHeader("SGR 4:x Underline Styles (Terminal.app BREAKS here)")),w.write(row("4:1 Single",`${CSI2}4:1mThe quick brown fox${RESET2}`)+`
210
+ `),w.write(row("4:2 Double",`${CSI2}4:2mThe quick brown fox${RESET2}`)+`
211
+ `),w.write(row("4:3 Curly",`${CSI2}4:3mThe quick brown fox${RESET2}`)+`
212
+ `),w.write(row("4:4 Dotted",`${CSI2}4:4mThe quick brown fox${RESET2}`)+`
213
+ `),w.write(row("4:5 Dashed",`${CSI2}4:5mThe quick brown fox${RESET2}`)+`
214
+ `),w.write(row("After 4:x (clean?)",`${CSI2}4:3m${RESET2}This text should be normal — if garbled, 4:x corrupted SGR state`)+`
215
+ `),w.write(sectionHeader("SGR 58 Underline Color (Terminal.app BREAKS here)")),w.write(row("58;5;1 Red UL",`${sgr(4)}${CSI2}58;5;1mThe quick brown fox${RESET2}`)+`
216
+ `),w.write(row("58;5;2 Green UL",`${sgr(4)}${CSI2}58;5;2mThe quick brown fox${RESET2}`)+`
217
+ `),w.write(row("58;5;4 Blue UL",`${sgr(4)}${CSI2}58;5;4mThe quick brown fox${RESET2}`)+`
218
+ `),w.write(row("58;2;R;G;B TC UL",`${sgr(4)}${CSI2}58;2;255;128;0mThe quick brown fox${RESET2}`)+`
219
+ `),w.write(row("After SGR 58 (clean?)",`${sgr(4)}${CSI2}58;5;1m${RESET2}This text should be normal — if garbled, 58 corrupted SGR state`)+`
220
+ `);if(show("colors")){w.write(sectionHeader("ANSI 16 Colors"));let colorNames=["Black","Red","Green","Yellow","Blue","Magenta","Cyan","White"],fgLine=" FG: ";for(let i=0;i<8;i++)fgLine+=`${sgr(30+i)} ${colorNames[i]}${RESET2}`;w.write(fgLine+`
221
+ `);let fgBrLine=" Br: ";for(let i=0;i<8;i++)fgBrLine+=`${sgr(90+i)} ${colorNames[i]}${RESET2}`;w.write(fgBrLine+`
222
+ `);let bgLine=" BG: ";for(let i=0;i<8;i++)bgLine+=`${sgr(40+i)} ${colorNames[i]} ${RESET2}`;w.write(bgLine+`
223
+ `);let bgBrLine=" BrBG:";for(let i=0;i<8;i++)bgBrLine+=`${sgr(100+i)} ${colorNames[i]} ${RESET2}`;w.write(bgBrLine+`
224
+ `)}if(show("256")){w.write(sectionHeader("256 Colors (indices 0-15, 16-231, 232-255)"));let stdLine=" 0-15: ";for(let i=0;i<16;i++)stdLine+=`${CSI2}48;5;${i}m ${RESET2}`;w.write(stdLine+`
225
+ `);let cubeLine=" Cube: ";for(let i=16;i<52;i++)cubeLine+=`${CSI2}48;5;${i}m ${RESET2}`;w.write(cubeLine+`
226
+ `);let grayLine=" Gray: ";for(let i=232;i<256;i++)grayLine+=`${CSI2}48;5;${i}m ${RESET2}`;w.write(grayLine+`
227
+ `)}if(show("truecolor")){w.write(sectionHeader("Truecolor (38;2;R;G;B / 48;2;R;G;B)"));let tcLine=" Gradient: ";for(let i=0;i<40;i++){let r=Math.round(i/39*255),g=Math.round((39-i)/39*128);tcLine+=`${CSI2}48;2;${r};${g};80m ${RESET2}`}w.write(tcLine+`
228
+ `),w.write(row("If solid blocks →","Truecolor NOT supported (256-color fallback)")+`
229
+ `)}if(show("unicode"))w.write(sectionHeader("Unicode, Emoji, PUA (Nerd Fonts)")),w.write(row("ASCII","Hello World! 0123456789")+`
230
+ `),w.write(row("Latin Extended","àéîõü ñ ß ø å")+`
231
+ `),w.write(row("CJK","你好世界 日本語 한국어")+`
232
+ `),w.write(row("Box Drawing","┌─┬─┐ ╔═╦═╗ ╭─╮")+`
233
+ `),w.write(row("Block Elements","▀▄█▌▐░▒▓")+`
234
+ `),w.write(row("Symbols","● ○ ◉ ▶ ◀ ⚠ ✓ ✗ ⋮ §")+`
235
+ `),w.write(row("Emoji","\uD83C\uDF89 \uD83D\uDE80 \uD83D\uDCC1 \uD83D\uDCC4 ⭐ \uD83D\uDD25 \uD83D\uDC4D")+`
236
+ `),w.write(row("Nerd Font PUA"," folder  file  arrow  gear")+`
237
+ `),w.write(row("If PUA = boxes →","Nerd Fonts not installed")+`
238
+ `);if(show("emoji"))w.write(sectionHeader("Emoji Width Alignment (_'s should align with ruler)")),w.write(` Ruler: |1234567890|
239
+ `),w.write(` ASCII 'A': |A_________| (w=1)
240
+ `),w.write(` CJK '你': |你________| (w=2)
241
+ `),w.write(` Flag \uD83C\uDDE8\uD83C\uDDE6: |\uD83C\uDDE8\uD83C\uDDE6________| (w=2)
242
+ `),w.write(` Flag \uD83C\uDDFA\uD83C\uDDF8: |\uD83C\uDDFA\uD83C\uDDF8________| (w=2)
243
+ `),w.write(` Emoji \uD83D\uDCC1: |\uD83D\uDCC1________| (w=2)
244
+ `),w.write(` Emoji \uD83D\uDCC4: |\uD83D\uDCC4________| (w=2)
245
+ `),w.write(` Emoji \uD83D\uDCCB: |\uD83D\uDCCB________| (w=2)
246
+ `),w.write(` Emoji ⚠️: |⚠️________| (w=2)
247
+ `),w.write(` Text ⚠: |⚠_________| (w=1 text, 2 emoji)
248
+ `),w.write(` Text ⭐: |⭐________| (w=1 text, 2 emoji)
249
+ `),w.write(` Text ☑: |☑_________| (w=1 text, 2 emoji)
250
+ `),w.write(` Emoji \uD83C\uDFE0: |\uD83C\uDFE0________| (w=2)
251
+ `),w.write(` Emoji \uD83D\uDC53: |\uD83D\uDC53________| (w=2)
252
+ `),w.write(` ZWJ \uD83D\uDC68\uD83C\uDFFB‍\uD83D\uDCBB: |\uD83D\uDC68\uD83C\uDFFB‍\uD83D\uDCBB________| (w=2)
253
+ `),w.write(` Arrow →: |→_________| (w=1)
254
+ `),w.write(` Arrow ▸: |▸_________| (w=1)
255
+ `),w.write(` Circle ○: |○_________| (w=1)
256
+ `),w.write(` Square □: |□_________| (w=1)
257
+ `),w.write(` Check ✓: |✓_________| (w=1)
258
+ `);if(show("borders"))w.write(sectionHeader("Box Drawing Borders")),w.write(` ┌──────────┐ ╔══════════╗ ╭──────────╮
259
+ `),w.write(` │ single │ ║ double ║ │ round │
260
+ `),w.write(` └──────────┘ ╚══════════╝ ╰──────────╯
261
+ `);if(show("inverse"))w.write(sectionHeader("Inverse + Background (potential artifact source)")),w.write(row("Red FG + Inverse",`${sgr(31,7)}This should have red background${RESET2}`)+`
262
+ `),w.write(row("Cyan BG + White FG",`${sgr(46,37)}Cyan background, white text${RESET2}`)+`
263
+ `),w.write(row("Black BG + White FG",`${sgr(40,97)}Black bg, bright white text${RESET2}`)+`
264
+ `),w.write(row("White BG + Black FG",`${sgr(107,30)}White bg, black text${RESET2}`)+`
265
+ `),w.write(sectionHeader("Reset Sanity Check")),w.write(` This line should be completely normal with no formatting artifacts.
266
+ `),w.write(` If you see colors, underlines, or other styling above, the terminal
267
+ `),w.write(` failed to process an SGR reset (\\x1b[0m) correctly.
268
+ `);if(show("profile")){w.write(sectionHeader("Detected Terminal Profile"));let entries=Object.entries(caps);for(let[key,value]of entries){let indicator=value===!0?"✓":value===!1?"✗":String(value);w.write(` ${key.padEnd(20)} ${indicator}
269
+ `)}}w.write(`
270
+ `)}var ESC2="\x1B",CSI2,RESET2,TERMTEST_SECTIONS;var init_termtest=__esm(()=>{init_terminal_caps();CSI2=`${ESC2}[`,RESET2=`${CSI2}0m`;TERMTEST_SECTIONS=["sgr","underline","colors","256","truecolor","unicode","emoji","borders","inverse","profile"]});function withMeasurer(term2){let caps=term2.caps,measurer=createWidthMeasurer(caps?{textEmojiWide:caps.textEmojiWide,textSizingEnabled:caps.textSizingSupported}:{});return Object.create(term2,{textEmojiWide:{get:()=>measurer.textEmojiWide,enumerable:!0},textSizingEnabled:{get:()=>measurer.textSizingEnabled,enumerable:!0},displayWidth:{value:measurer.displayWidth.bind(measurer),enumerable:!0},displayWidthAnsi:{value:measurer.displayWidthAnsi.bind(measurer),enumerable:!0},graphemeWidth:{value:measurer.graphemeWidth.bind(measurer),enumerable:!0},wrapText:{value:measurer.wrapText.bind(measurer),enumerable:!0},sliceByWidth:{value:measurer.sliceByWidth.bind(measurer),enumerable:!0},sliceByWidthFromEnd:{value:measurer.sliceByWidthFromEnd.bind(measurer),enumerable:!0}})}function createPipeline(options={}){let{caps,measurer:explicitMeasurer}=options,measurer=explicitMeasurer??createWidthMeasurer(caps?{textEmojiWide:caps.textEmojiWide,textSizingEnabled:caps.textSizingSupported}:{}),outputPhaseFn=createOutputPhase(caps?{underlineStyles:caps.underlineStyles,underlineColor:caps.underlineColor,colorLevel:caps.colorLevel}:{},measurer);return{measurer,outputPhaseFn}}var init_measurer=__esm(()=>{init_unicode();init_output_phase()});function withRender(term2){let pipelineConfig=createPipeline({caps:term2.caps}),{measurer}=pipelineConfig;function renderPipeline(root,width,height,prevBuffer,options){return executeRender(root,width,height,prevBuffer,options,pipelineConfig)}async function renderStaticFn(element,options){let{renderString:renderString2}=await Promise.resolve().then(() => (init_render_string(),exports_render_string));return renderString2(element,{...options,pipelineConfig})}return Object.create(term2,{textEmojiWide:{get:()=>measurer.textEmojiWide,enumerable:!0},textSizingEnabled:{get:()=>measurer.textSizingEnabled,enumerable:!0},displayWidth:{value:measurer.displayWidth.bind(measurer),enumerable:!0},displayWidthAnsi:{value:measurer.displayWidthAnsi.bind(measurer),enumerable:!0},graphemeWidth:{value:measurer.graphemeWidth.bind(measurer),enumerable:!0},wrapText:{value:measurer.wrapText.bind(measurer),enumerable:!0},sliceByWidth:{value:measurer.sliceByWidth.bind(measurer),enumerable:!0},sliceByWidthFromEnd:{value:measurer.sliceByWidthFromEnd.bind(measurer),enumerable:!0},pipelineConfig:{value:pipelineConfig,enumerable:!0},render:{value:renderPipeline,enumerable:!0},renderStatic:{value:renderStaticFn,enumerable:!0}})}var init_with_render=__esm(()=>{init_measurer();init_pipeline2()});async function queryCursorPosition(write,read,timeoutMs=200){write("\x1B[6n");let data=await read(timeoutMs);if(data==null)return null;let match=CPR_RESPONSE_RE.exec(data);if(!match)return null;return{row:parseInt(match[1],10),col:parseInt(match[2],10)}}async function queryCursorFromStdio(stdout,stdin,timeoutMs=200){let wasRaw=stdin.isRaw;if(!wasRaw)stdin.setRawMode(!0);try{return await queryCursorPosition((s)=>{stdout.write(s)},(ms)=>new Promise((resolve)=>{let timer=setTimeout(()=>{stdin.removeListener("data",onData),resolve(null)},ms);function onData(chunk){clearTimeout(timer),stdin.removeListener("data",onData),resolve(chunk.toString())}stdin.on("data",onData)}),timeoutMs)}finally{if(!wasRaw)stdin.setRawMode(!1)}}var CPR_RESPONSE_RE;var init_cursor_query=__esm(()=>{CPR_RESPONSE_RE=/\x1b\[(\d+);(\d+)R/});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;let r=normalizeHexChannel2(match[1]),g=normalizeHexChannel2(match[2]),b=normalizeHexChannel2(match[3]);return`#${r}${g}${b}`}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_terminal_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 queryPrimaryDA(write,read,timeoutMs=200){write("\x1B[c");let data=await read(timeoutMs);if(data==null)return null;let match=DA1_RESPONSE_RE.exec(data);if(!match)return null;return{params:match[1].split(";").map((s)=>parseInt(s,10))}}async function querySecondaryDA(write,read,timeoutMs=200){write("\x1B[>c");let data=await read(timeoutMs);if(data==null)return null;let match=DA2_RESPONSE_RE.exec(data);if(!match)return null;let parts=match[1].split(";");if(parts.length<3)return null;return{type:parseInt(parts[0],10),version:parseInt(parts[1],10),id:parseInt(parts[2],10)}}async function queryTertiaryDA(write,read,timeoutMs=200){write("\x1B[=c");let data=await read(timeoutMs);if(data==null)return null;let match=DA3_RESPONSE_RE.exec(data);if(!match)return null;return match[1]}async function queryTerminalVersion(write,read,timeoutMs=200){write("\x1B[>0q");let data=await read(timeoutMs);if(data==null)return null;let match=XTVERSION_RESPONSE_RE.exec(data);if(!match)return null;return match[1]}async function queryDeviceAttributes(stdout,stdin,timeoutMs=200){let wasRaw=stdin.isRaw;if(!wasRaw)stdin.setRawMode(!0);try{let write=(s)=>{stdout.write(s)},read=(ms)=>new Promise((resolve)=>{let timer=setTimeout(()=>{stdin.removeListener("data",onData),resolve(null)},ms);function onData(chunk){clearTimeout(timer),stdin.removeListener("data",onData),resolve(chunk.toString())}stdin.on("data",onData)}),da1=await queryPrimaryDA(write,read,timeoutMs),da2=await querySecondaryDA(write,read,timeoutMs),version=await queryTerminalVersion(write,read,timeoutMs);return{da1,da2,version}}finally{if(!wasRaw)stdin.setRawMode(!1)}}var DA1_RESPONSE_RE,DA2_RESPONSE_RE,DA3_RESPONSE_RE,XTVERSION_RESPONSE_RE;var init_device_attrs=__esm(()=>{DA1_RESPONSE_RE=/\x1b\[\?([\d;]+)c/,DA2_RESPONSE_RE=/\x1b\[>([\d;]+)c/,DA3_RESPONSE_RE=/\x1bP!\|([0-9a-fA-F]*)\x1b\\/,XTVERSION_RESPONSE_RE=/\x1bP>\|([^\x1b]*)\x1b\\/});async function queryMode(write,read,mode,timeoutMs=200){write(`\x1B[?${mode}$p`);let data=await read(timeoutMs);if(data==null)return"unknown";let match=DECRPM_RESPONSE_RE.exec(data);if(!match)return"unknown";if(parseInt(match[1],10)!==mode)return"unknown";switch(parseInt(match[2],10)){case 1:case 3:return"set";case 2:case 4:return"reset";default:return"unknown"}}async function queryModes(write,read,modes,timeoutMs=200){let results=new Map;for(let mode of modes){let state=await queryMode(write,read,mode,timeoutMs);results.set(mode,state)}return results}var DECRPM_RESPONSE_RE,DecMode;var init_mode_query=__esm(()=>{DECRPM_RESPONSE_RE=/\x1b\[\?(\d+);(\d+)\$y/,DecMode={CURSOR_VISIBLE:25,ALT_SCREEN:1049,MOUSE_TRACKING:1000,BRACKETED_PASTE:2004,SYNC_OUTPUT:2026,FOCUS_REPORTING:1004}});async function queryTextAreaPixels(write,read,timeoutMs=200){write("\x1B[14t");let data=await read(timeoutMs);if(data==null)return null;let match=PIXEL_RESPONSE_RE.exec(data);if(!match)return null;return{height:parseInt(match[1],10),width:parseInt(match[2],10)}}async function queryTextAreaSize(write,read,timeoutMs=200){write("\x1B[18t");let data=await read(timeoutMs);if(data==null)return null;let match=TEXT_AREA_RESPONSE_RE.exec(data);if(!match)return null;return{rows:parseInt(match[1],10),cols:parseInt(match[2],10)}}async function queryCellSize(write,read,timeoutMs=200){let pixels=await queryTextAreaPixels(write,read,timeoutMs);if(pixels==null)return null;let size=await queryTextAreaSize(write,read,timeoutMs);if(size==null)return null;if(size.cols===0||size.rows===0)return null;return{width:pixels.width/size.cols,height:pixels.height/size.rows}}var PIXEL_RESPONSE_RE,TEXT_AREA_RESPONSE_RE;var init_pixel_size=__esm(()=>{PIXEL_RESPONSE_RE=/\x1b\[4;(\d+);(\d+)t/,TEXT_AREA_RESPONSE_RE=/\x1b\[8;(\d+);(\d+)t/});function createCanvasMeasurer(_config){return{measureText(text,_style){return{width:text.length,height:1}},getLineHeight(_style){return 1}}}function resolveColor(color,fallback){if(!color)return fallback;if(color.startsWith("#")||color.startsWith("rgb"))return color;let named=ANSI_COLORS[color.toLowerCase()];if(named)return named;return color}class CanvasRenderBuffer{width;height;canvas;ctx;config;charWidth;cellHeight;constructor(width,height,config){this.width=width,this.height=height,this.config=config,this.charWidth=config.fontSize*0.6,this.cellHeight=config.fontSize*config.lineHeight;let pixelWidth=width*this.charWidth,pixelHeight=height*this.cellHeight;if(typeof OffscreenCanvas<"u")this.canvas=new OffscreenCanvas(pixelWidth,pixelHeight);else if(typeof document<"u")this.canvas=document.createElement("canvas"),this.canvas.width=pixelWidth,this.canvas.height=pixelHeight;else throw Error("Canvas not available");let ctx=this.canvas.getContext("2d");if(!ctx)throw Error("Could not get 2d context");this.ctx=ctx,this.ctx.fillStyle=config.backgroundColor,this.ctx.fillRect(0,0,pixelWidth,pixelHeight)}fillRect(x,y,width,height,style){if(style.bg){let px=x*this.charWidth,py=y*this.cellHeight,pw=width*this.charWidth,ph=height*this.cellHeight;this.ctx.fillStyle=resolveColor(style.bg,this.config.backgroundColor),this.ctx.fillRect(px,py,pw,ph)}}drawText(x,y,text,style){let px=x*this.charWidth,py=y*this.cellHeight,attrs=style.attrs??{},weight=attrs.bold?"bold":"normal",fontStyle=attrs.italic?"italic":"normal";if(this.ctx.font=`${fontStyle} ${weight} ${this.config.fontSize}px ${this.config.fontFamily}`,this.ctx.fillStyle=resolveColor(style.fg,this.config.foregroundColor),this.ctx.textBaseline="top",this.ctx.fillText(text,px,py),attrs.underline)this.drawUnderline(px,py,text,style);if(attrs.strikethrough){let textWidth=this.ctx.measureText(text).width,strikeY=py+this.config.fontSize*0.5;this.ctx.strokeStyle=resolveColor(style.fg,this.config.foregroundColor),this.ctx.lineWidth=1,this.ctx.beginPath(),this.ctx.moveTo(px,strikeY),this.ctx.lineTo(px+textWidth,strikeY),this.ctx.stroke()}}drawUnderline(px,py,text,style){let attrs=style.attrs??{},textWidth=this.ctx.measureText(text).width,underlineY=py+this.config.fontSize*0.9,underlineColor2=resolveColor(attrs.underlineColor??style.fg,this.config.foregroundColor);switch(this.ctx.strokeStyle=underlineColor2,this.ctx.lineWidth=1,attrs.underlineStyle??"single"){case"double":this.ctx.beginPath(),this.ctx.moveTo(px,underlineY-1),this.ctx.lineTo(px+textWidth,underlineY-1),this.ctx.moveTo(px,underlineY+1),this.ctx.lineTo(px+textWidth,underlineY+1),this.ctx.stroke();break;case"curly":this.ctx.beginPath(),this.ctx.moveTo(px,underlineY);let waveLength=4,amplitude=2;for(let wx=0;wx<textWidth;wx+=waveLength*2)this.ctx.quadraticCurveTo(px+wx+waveLength/2,underlineY-amplitude,px+wx+waveLength,underlineY),this.ctx.quadraticCurveTo(px+wx+waveLength*3/2,underlineY+amplitude,px+wx+waveLength*2,underlineY);this.ctx.stroke();break;case"dotted":this.ctx.setLineDash([2,2]),this.ctx.beginPath(),this.ctx.moveTo(px,underlineY),this.ctx.lineTo(px+textWidth,underlineY),this.ctx.stroke(),this.ctx.setLineDash([]);break;case"dashed":this.ctx.setLineDash([4,2]),this.ctx.beginPath(),this.ctx.moveTo(px,underlineY),this.ctx.lineTo(px+textWidth,underlineY),this.ctx.stroke(),this.ctx.setLineDash([]);break;default:this.ctx.beginPath(),this.ctx.moveTo(px,underlineY),this.ctx.lineTo(px+textWidth,underlineY),this.ctx.stroke()}}drawChar(x,y,char,style){this.drawText(x,y,char,style)}inBounds(x,y){return x>=0&&x<this.width&&y>=0&&y<this.height}}function createCanvasAdapter(config={}){let cfg={...DEFAULT_CONFIG,...config};return{name:"canvas",measurer:createCanvasMeasurer(cfg),createBuffer(width,height){return new CanvasRenderBuffer(width,height,cfg)},flush(_buffer,_prevBuffer){},getBorderChars(style){return BORDER_CHARS2[style]??BORDER_CHARS2.single}}}var DEFAULT_CONFIG,BORDER_CHARS2,ANSI_COLORS;var init_canvas_adapter=__esm(()=>{DEFAULT_CONFIG={fontSize:14,fontFamily:"monospace",lineHeight:1.2,backgroundColor:"#1e1e1e",foregroundColor:"#d4d4d4"},BORDER_CHARS2={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:"┃"}};ANSI_COLORS={black:"#000000",red:"#cd0000",green:"#00cd00",yellow:"#cdcd00",blue:"#0000ee",magenta:"#cd00cd",cyan:"#00cdcd",white:"#e5e5e5",gray:"#7f7f7f",grey:"#7f7f7f",brightBlack:"#7f7f7f",brightRed:"#ff0000",brightGreen:"#00ff00",brightYellow:"#ffff00",brightBlue:"#5c5cff",brightMagenta:"#ff00ff",brightCyan:"#00ffff",brightWhite:"#ffffff"}});function resolveColor2(color,fallback){if(!color)return fallback;if(color.startsWith("#")||color.startsWith("rgb"))return color;return ANSI_COLORS2[color.toLowerCase()]??color}function createDOMMeasurer(_config){return{measureText(text,_style){return{width:text.length,height:1}},getLineHeight(_style){return 1}}}class DOMRenderBuffer{width;height;config;lines;backgrounds;charWidth;cellHeight;container=null;constructor(width,height,config){this.width=width,this.height=height,this.config=config,this.lines=new Map,this.backgrounds=new Map,this.charWidth=config.fontSize*0.6,this.cellHeight=config.fontSize*config.lineHeight}setContainer(container){this.container=container}getContainer(){return this.container}fillRect(x,y,width,height,style){if(style.bg){let key=`${x},${y},${width},${height}`;this.backgrounds.set(key,{x,y,w:width,h:height,color:resolveColor2(style.bg,this.config.backgroundColor)})}}drawText(x,y,text,style){if(!this.lines.has(y))this.lines.set(y,[]);this.lines.get(y).push({text,style,x})}drawChar(x,y,char,style){this.drawText(x,y,char,style)}inBounds(x,y){return x>=0&&x<this.width&&y>=0&&y<this.height}render(){if(!this.container)throw Error("DOMRenderBuffer: No container set. Call setContainer() first.");let container=this.container,cw=this.charWidth,ch=this.cellHeight,containerWidthPx=this.width*cw,containerHeightPx=this.height*ch;container.innerHTML="",container.style.cssText=`
271
+ position: relative;
272
+ font-family: ${this.config.fontFamily};
273
+ font-size: ${this.config.fontSize}px;
274
+ line-height: ${this.config.lineHeight};
275
+ background-color: ${this.config.backgroundColor};
276
+ color: ${this.config.foregroundColor};
277
+ white-space: pre;
278
+ overflow: hidden;
279
+ width: ${containerWidthPx}px;
280
+ height: ${containerHeightPx}px;
281
+ `;for(let bg of this.backgrounds.values()){let bgDiv=document.createElement("div");bgDiv.className=`${this.config.classPrefix}-bg`,bgDiv.style.cssText=`
282
+ position: absolute;
283
+ left: ${bg.x*cw}px;
284
+ top: ${bg.y*ch}px;
285
+ width: ${bg.w*cw}px;
286
+ height: ${bg.h*ch}px;
287
+ background-color: ${bg.color};
288
+ `,container.appendChild(bgDiv)}let sortedLines=Array.from(this.lines.entries()).sort((a,b)=>a[0]-b[0]);for(let[y,runs]of sortedLines){let lineDiv=document.createElement("div");lineDiv.className=`${this.config.classPrefix}-line`,lineDiv.style.cssText=`
289
+ position: absolute;
290
+ left: 0;
291
+ top: ${y*ch}px;
292
+ height: ${ch}px;
293
+ white-space: pre;
294
+ `;let sortedRuns=runs.sort((a,b)=>a.x-b.x);for(let run of sortedRuns){let span=document.createElement("span");span.className=`${this.config.classPrefix}-text`,span.textContent=run.text;let styles=["position: absolute",`left: ${run.x*cw}px`];if(run.style.fg)styles.push(`color: ${resolveColor2(run.style.fg,this.config.foregroundColor)}`);if(run.style.bg)styles.push(`background-color: ${resolveColor2(run.style.bg,this.config.backgroundColor)}`);let attrs=run.style.attrs;if(attrs){if(attrs.bold)styles.push("font-weight: bold");if(attrs.dim)styles.push("opacity: 0.5");if(attrs.italic)styles.push("font-style: italic");if(attrs.underline||attrs.underlineStyle){let underlineStyle=attrs.underlineStyle??"single",underlineColor2=attrs.underlineColor?resolveColor2(attrs.underlineColor,this.config.foregroundColor):"currentColor";switch(underlineStyle){case"double":styles.push(`text-decoration: underline double ${underlineColor2}`);break;case"curly":styles.push(`text-decoration: underline wavy ${underlineColor2}`);break;case"dotted":styles.push(`text-decoration: underline dotted ${underlineColor2}`);break;case"dashed":styles.push(`text-decoration: underline dashed ${underlineColor2}`);break;default:styles.push(`text-decoration: underline solid ${underlineColor2}`)}}if(attrs.strikethrough){let existing=styles.find((s)=>s.startsWith("text-decoration:"));if(existing){let idx=styles.indexOf(existing);styles[idx]=existing.replace("underline","underline line-through")}else styles.push("text-decoration: line-through")}if(attrs.inverse){let fg=run.style.fg?resolveColor2(run.style.fg,this.config.foregroundColor):this.config.foregroundColor,bg=run.style.bg?resolveColor2(run.style.bg,this.config.backgroundColor):this.config.backgroundColor;styles.push(`color: ${bg}`,`background-color: ${fg}`)}}span.style.cssText=styles.join("; "),lineDiv.appendChild(span)}container.appendChild(lineDiv)}}clear(){this.lines.clear(),this.backgrounds.clear()}}function createDOMAdapter(config={}){let cfg={...DEFAULT_CONFIG2,...config};return{name:"dom",measurer:createDOMMeasurer(cfg),createBuffer(width,height){return new DOMRenderBuffer(width,height,cfg)},flush(buffer,_prevBuffer){let domBuffer=buffer;if(domBuffer.getContainer())domBuffer.render()},getBorderChars(style){return BORDER_CHARS3[style]??BORDER_CHARS3.single}}}function injectDOMStyles(classPrefix="silvery"){if(stylesInjected||typeof document>"u")return;let style=document.createElement("style");style.textContent=`
295
+ .${classPrefix}-container {
296
+ font-family: monospace;
297
+ white-space: pre;
298
+ overflow: hidden;
299
+ }
300
+ .${classPrefix}-line {
301
+ white-space: pre;
302
+ }
303
+ .${classPrefix}-text {
304
+ white-space: pre;
305
+ }
306
+ /* Selection styling */
307
+ .${classPrefix}-text::selection {
308
+ background-color: rgba(100, 150, 255, 0.3);
309
+ }
310
+ `,document.head.appendChild(style),stylesInjected=!0}var DEFAULT_CONFIG2,BORDER_CHARS3,ANSI_COLORS2,stylesInjected=!1;var init_dom_adapter=__esm(()=>{DEFAULT_CONFIG2={fontSize:14,fontFamily:"monospace",lineHeight:1.2,backgroundColor:"#1e1e1e",foregroundColor:"#d4d4d4",classPrefix:"silvery"},BORDER_CHARS3={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:"┃"}},ANSI_COLORS2={black:"#000000",red:"#cd0000",green:"#00cd00",yellow:"#cdcd00",blue:"#0000ee",magenta:"#cd00cd",cyan:"#00cdcd",white:"#e5e5e5",gray:"#7f7f7f",grey:"#7f7f7f",brightblack:"#7f7f7f",brightred:"#ff0000",brightgreen:"#00ff00",brightyellow:"#ffff00",brightblue:"#5c5cff",brightmagenta:"#ff00ff",brightcyan:"#00ffff",brightwhite:"#ffffff"}});import{createLogger as createLogger8}from"loggily";function createMouseEvent(type,x,y,target,parsed,keyboardMods){let propagationStopped=!1,defaultPrevented=!1,metaKey=keyboardMods?.super??!1;if(type==="click"||type==="mousedown")mouseLog.debug?.(`createMouseEvent(${type}) metaKey=${metaKey} keyboardMods.super=${keyboardMods?.super}`);return{type,clientX:x,clientY:y,button:parsed.button,altKey:parsed.meta,ctrlKey:parsed.ctrl,metaKey,shiftKey:parsed.shift,target,currentTarget:target,nativeEvent:parsed,get propagationStopped(){return propagationStopped},get defaultPrevented(){return defaultPrevented},stopPropagation(){propagationStopped=!0},preventDefault(){defaultPrevented=!0}}}function createWheelEvent(x,y,target,parsed,keyboardMods){let base=createMouseEvent("wheel",x,y,target,parsed,keyboardMods);return base.deltaY=parsed.delta??0,base.deltaX=0,base}function hitTest(node,x,y){let rect=node.screenRect;if(!rect)return null;if(!pointInRect(x,y,rect))return null;let props=node.props;if(props.pointerEvents==="none")return null;let clips=props.overflow==="hidden"||props.overflow==="scroll";for(let i=node.children.length-1;i>=0;i--){let child=node.children[i];if(clips){if(child.screenRect&&!pointInRect(x,y,rect))continue}let hit=hitTest(child,x,y);if(hit)return hit}if(node.type==="silvery-text")for(let i=node.children.length-1;i>=0;i--){let child=node.children[i];if(child.inlineRects){for(let inlineRect of child.inlineRects)if(pointInRect(x,y,inlineRect))return child}}return node}function dispatchMouseEvent(event){let handlerProp=EVENT_HANDLER_MAP[event.type];if(!handlerProp)return;if(event.type==="mouseenter"||event.type==="mouseleave"){let handler=event.target.props[handlerProp];if(handler){let mutableEvent=event;mutableEvent.currentTarget=event.target,handler(event)}return}let path=getAncestorPath(event.target);for(let node of path){if(event.propagationStopped)break;let handler=node.props[handlerProp];if(handler){let mutableEvent=event;mutableEvent.currentTarget=node,handler(event)}}}function createDoubleClickState(){return{lastClickTime:0,lastClickX:-999,lastClickY:-999,lastClickButton:-1}}function checkDoubleClick(state,x,y,button,now=Date.now()){let timeDelta=now-state.lastClickTime,dx=Math.abs(x-state.lastClickX),dy=Math.abs(y-state.lastClickY),isDouble=button===state.lastClickButton&&timeDelta<=DOUBLE_CLICK_TIME_MS&&dx<=DOUBLE_CLICK_DISTANCE&&dy<=DOUBLE_CLICK_DISTANCE;if(state.lastClickTime=now,state.lastClickX=x,state.lastClickY=y,state.lastClickButton=button,isDouble)state.lastClickTime=0;return isDouble}function computeEnterLeave(prevPath,nextPath){let prevSet=new Set(prevPath),nextSet=new Set(nextPath),entered=nextPath.filter((n)=>!prevSet.has(n)),left=prevPath.filter((n)=>!nextSet.has(n));return{entered,left}}function createMouseEventProcessor(options){return{doubleClick:createDoubleClickState(),hoverPath:[],mouseDownTarget:null,focusManager:options?.focusManager,keyboardModifiers:{super:!1,hyper:!1,capsLock:!1,numLock:!1}}}function processMouseEvent(state,parsed,root){let{x,y,action}=parsed,target=hitTest(root,x,y);if(action==="move"){let nodeType=target?.type??"null",nodeId=target?target.props.id??"":"",enterAncestor="";if(target){let n=target;while(n){if("onMouseEnter"in n.props){enterAncestor=`${n.type}#${n.props.id??""}`;break}n=n.parent}}let newPath=target?getAncestorPath(target):[],{entered}=computeEnterLeave(state.hoverPath,newPath);mouseLog.debug?.(`move x=${x} y=${y} target=${nodeType}#${nodeId} enterAncestor=${enterAncestor||"none"} entered=${entered.length} prevPath=${state.hoverPath.length}`)}if(!target)return!1;let defaultPrevented=!1;if(action==="down"){if(state.mouseDownTarget=target,state.focusManager){let focusable=findFocusableAncestor(target);if(focusable)state.focusManager.focus(focusable,"mouse")}let event=createMouseEvent("mousedown",x,y,target,parsed,state.keyboardModifiers);dispatchMouseEvent(event)}else if(action==="up"){let event=createMouseEvent("mouseup",x,y,target,parsed,state.keyboardModifiers);if(dispatchMouseEvent(event),state.mouseDownTarget){let clickEvent=createMouseEvent("click",x,y,target,parsed,state.keyboardModifiers);if(dispatchMouseEvent(clickEvent),clickEvent.defaultPrevented)defaultPrevented=!0;if(checkDoubleClick(state.doubleClick,x,y,parsed.button)){let dblEvent=createMouseEvent("dblclick",x,y,target,parsed,state.keyboardModifiers);if(dispatchMouseEvent(dblEvent),dblEvent.defaultPrevented)defaultPrevented=!0}}state.mouseDownTarget=null}else if(action==="move"){let event=createMouseEvent("mousemove",x,y,target,parsed,state.keyboardModifiers);dispatchMouseEvent(event);let newPath=getAncestorPath(target),{entered,left}=computeEnterLeave(state.hoverPath,newPath);for(let node of left){let leaveEvent=createMouseEvent("mouseleave",x,y,node,parsed,state.keyboardModifiers);dispatchMouseEvent(leaveEvent)}for(let node of entered.reverse()){let enterEvent=createMouseEvent("mouseenter",x,y,node,parsed,state.keyboardModifiers);dispatchMouseEvent(enterEvent)}state.hoverPath=newPath}else if(action==="wheel"){let event=createWheelEvent(x,y,target,parsed,state.keyboardModifiers);if(dispatchMouseEvent(event),event.defaultPrevented)defaultPrevented=!0}return defaultPrevented}var mouseLog,EVENT_HANDLER_MAP,DOUBLE_CLICK_TIME_MS=300,DOUBLE_CLICK_DISTANCE=2;var init_mouse_events=__esm(()=>{mouseLog=createLogger8("silvery:mouse");EVENT_HANDLER_MAP={click:"onClick",dblclick:"onDoubleClick",mousedown:"onMouseDown",mouseup:"onMouseUp",mousemove:"onMouseMove",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",wheel:"onWheel"}});function enableInspector(options){if(inspectorEnabled=!0,options?.logFile)inspectorOutput=__require("node:fs").createWriteStream(options.logFile,{flags:"a"});else if(options?.output)inspectorOutput=options.output;else inspectorOutput=process.stderr}function disableInspector(){inspectorEnabled=!1}function isInspectorEnabled(){return inspectorEnabled}function inspectFrame(stats){if(!inspectorEnabled)return;let line=`[silvery] frame #${stats.renderCount} ${stats.lastRenderTime.toFixed(1)}ms avg=${stats.avgRenderTime.toFixed(1)}ms skipped=${stats.skippedCount}
311
+ `;inspectorOutput.write(line)}function inspectTree(rootNode,options){let maxDepth=options?.depth??10,showLayout=options?.showLayout??!0,lines=[];function walk(node,indent){if(indent>maxDepth)return;let prefix=" ".repeat(indent),type=node.type,testID=node.props?.testID,idStr=testID?` #${testID}`:"",rectStr="";if(showLayout){if(node.contentRect){let r=node.contentRect;rectStr=` [${r.x},${r.y} ${r.width}x${r.height}]`}else if(node.layoutNode){let ln=node.layoutNode;rectStr=` [${ln.getComputedLeft()},${ln.getComputedTop()} ${ln.getComputedWidth()}x${ln.getComputedHeight()}]`}}let dirtyFlags=[];if(node.layoutDirty)dirtyFlags.push("layout");if(node.contentDirty)dirtyFlags.push("content");if(node.stylePropsDirty)dirtyFlags.push("paint");if(node.bgDirty)dirtyFlags.push("bg");if(node.subtreeDirty)dirtyFlags.push("subtree");if(node.childrenDirty)dirtyFlags.push("children");let dirtyStr=dirtyFlags.length>0?` dirty=[${dirtyFlags.join(",")}]`:"",textStr=node.textContent?` "${node.textContent.slice(0,30)}${node.textContent.length>30?"...":""}"`:"";lines.push(`${prefix}${type}${idStr}${rectStr}${dirtyStr}${textStr}`);for(let child of node.children)walk(child,indent+1)}return walk(rootNode,0),lines.join(`
312
+ `)}function autoEnableInspector(){if(process.env.SILVERY_DEV==="1"||process.env.SILVERY_DEV==="true"){let logFile=process.env.SILVERY_DEV_LOG;enableInspector(logFile?{logFile}:void 0)}}var inspectorEnabled=!1,inspectorOutput;var init_inspector=__esm(()=>{inspectorOutput=process.stderr});function createTermEditContext(options){let _text=options?.text??"",_selectionStart=options?.selectionStart??0,_selectionEnd=options?.selectionEnd??_selectionStart,_wrapWidth=options?.wrapWidth??80,_stickyX=null,_textHandlers=[],_selectionHandlers=[];function clampOffset(offset){return Math.max(0,Math.min(offset,_text.length))}function fireTextUpdate(op){for(let handler of _textHandlers)handler(op)}function fireSelectionChange(){for(let handler of _selectionHandlers)handler(_selectionStart,_selectionEnd)}function wordDeleteStart(offset){let pos=offset;while(pos>0&&isWhitespace(_text[pos-1]))pos--;while(pos>0&&!isWhitespace(_text[pos-1]))pos--;return pos}function visualLineStart(offset){let lines=getWrappedLines(_text,_wrapWidth),{row:row2}=cursorToRowCol(_text,offset,_wrapWidth),line=lines[row2];return line?line.startOffset:0}function visualLineEnd(offset){let lines=getWrappedLines(_text,_wrapWidth),{row:row2}=cursorToRowCol(_text,offset,_wrapWidth),line=lines[row2];if(!line)return _text.length;return line.startOffset+line.line.length}function updateText(rangeStart,rangeEnd,newText){let start=clampOffset(rangeStart),end=clampOffset(rangeEnd);if(start>end)throw RangeError(`updateText: rangeStart (${start}) > rangeEnd (${end})`);let deletedText=_text.slice(start,end);_text=_text.slice(0,start)+newText+_text.slice(end);let op;if(deletedText.length>0&&newText.length===0)op={type:"delete",offset:start,text:deletedText};else if(deletedText.length===0&&newText.length>0)op={type:"insert",offset:start,text:newText};else op={type:"replace",offset:start,text:newText,deleted:deletedText};return _selectionStart=start+newText.length,_selectionEnd=_selectionStart,fireTextUpdate(op),fireSelectionChange(),op}function updateSelection(start,end){_selectionStart=clampOffset(start),_selectionEnd=end!==void 0?clampOffset(end):_selectionStart,fireSelectionChange()}function onTextUpdate(handler){return _textHandlers.push(handler),()=>{_textHandlers=_textHandlers.filter((h)=>h!==handler)}}function onSelectionChange(handler){return _selectionHandlers.push(handler),()=>{_selectionHandlers=_selectionHandlers.filter((h)=>h!==handler)}}function moveCursor3(direction){let hasSelection=_selectionStart!==_selectionEnd;switch(direction){case"left":{if(_stickyX=null,hasSelection){let left=Math.min(_selectionStart,_selectionEnd);return _selectionStart=left,_selectionEnd=left,fireSelectionChange(),!0}if(_selectionStart===0)return!1;return _selectionStart=_selectionStart-1,_selectionEnd=_selectionStart,fireSelectionChange(),!0}case"right":{if(_stickyX=null,hasSelection){let right=Math.max(_selectionStart,_selectionEnd);return _selectionStart=right,_selectionEnd=right,fireSelectionChange(),!0}if(_selectionStart>=_text.length)return!1;return _selectionStart=_selectionStart+1,_selectionEnd=_selectionStart,fireSelectionChange(),!0}case"up":{if(hasSelection){let left=Math.min(_selectionStart,_selectionEnd);_selectionStart=left,_selectionEnd=left}if(_stickyX===null){let{col}=cursorToRowCol(_text,_selectionStart,_wrapWidth);_stickyX=col}let next=cursorMoveUp(_text,_selectionStart,_wrapWidth,_stickyX);if(next===null){if(hasSelection)fireSelectionChange();return!1}return _selectionStart=next,_selectionEnd=next,fireSelectionChange(),!0}case"down":{if(hasSelection){let right=Math.max(_selectionStart,_selectionEnd);_selectionStart=right,_selectionEnd=right}if(_stickyX===null){let{col}=cursorToRowCol(_text,_selectionStart,_wrapWidth);_stickyX=col}let next=cursorMoveDown(_text,_selectionStart,_wrapWidth,_stickyX);if(next===null){if(hasSelection)fireSelectionChange();return!1}return _selectionStart=next,_selectionEnd=next,fireSelectionChange(),!0}}}function atBoundary(direction){if(direction==="up"){let{row:row3}=cursorToRowCol(_text,_selectionStart,_wrapWidth);return row3===0}let{row:row2}=cursorToRowCol(_text,_selectionStart,_wrapWidth),totalLines=countVisualLines(_text,_wrapWidth);return row2>=totalLines-1}function insertChar(char){return _stickyX=null,updateText(_selectionStart,_selectionEnd,char)}function deleteBackward(){if(_stickyX=null,_selectionStart!==_selectionEnd){let start=Math.min(_selectionStart,_selectionEnd),end=Math.max(_selectionStart,_selectionEnd);return updateText(start,end,"")}if(_selectionStart===0)return null;return updateText(_selectionStart-1,_selectionStart,"")}function deleteForward(){if(_stickyX=null,_selectionStart!==_selectionEnd){let start=Math.min(_selectionStart,_selectionEnd),end=Math.max(_selectionStart,_selectionEnd);return updateText(start,end,"")}if(_selectionStart>=_text.length)return null;return updateText(_selectionStart,_selectionStart+1,"")}function deleteWord(){if(_stickyX=null,_selectionStart!==_selectionEnd){let start2=Math.min(_selectionStart,_selectionEnd),end=Math.max(_selectionStart,_selectionEnd);return updateText(start2,end,"")}if(_selectionStart===0)return null;let start=wordDeleteStart(_selectionStart);if(start===_selectionStart)return null;return updateText(start,_selectionStart,"")}function deleteToStart(){if(_stickyX=null,_selectionStart!==_selectionEnd){let start=Math.min(_selectionStart,_selectionEnd),end=Math.max(_selectionStart,_selectionEnd);return updateText(start,end,"")}let lineStart=visualLineStart(_selectionStart);if(lineStart===_selectionStart)return null;return updateText(lineStart,_selectionStart,"")}function deleteToEnd(){if(_stickyX=null,_selectionStart!==_selectionEnd){let start=Math.min(_selectionStart,_selectionEnd),end=Math.max(_selectionStart,_selectionEnd);return updateText(start,end,"")}let lineEnd=visualLineEnd(_selectionStart);if(lineEnd===_selectionStart)return null;return updateText(_selectionStart,lineEnd,"")}function getContent(){return _text}function getCursorOffset(){return _selectionStart}function setCursorOffset(offset){_stickyX=null,updateSelection(offset)}function getVisualLineCount(){return countVisualLines(_text,_wrapWidth)}function getCursorRowCol(){return cursorToRowCol(_text,_selectionStart,_wrapWidth)}function setWrapWidth(width){if(width<=0)throw RangeError(`setWrapWidth: width must be positive, got ${width}`);_wrapWidth=width}function dispose(){_textHandlers=[],_selectionHandlers=[]}return{get text(){return _text},get selectionStart(){return _selectionStart},get selectionEnd(){return _selectionEnd},get wrapWidth(){return _wrapWidth},get stickyX(){return _stickyX},updateText,updateSelection,onTextUpdate,onSelectionChange,moveCursor:moveCursor3,atBoundary,insertChar,deleteBackward,deleteForward,deleteWord,deleteToStart,deleteToEnd,getContent,getCursorOffset,setCursorOffset,getVisualLineCount,getCursorRowCol,setWrapWidth,[Symbol.dispose]:dispose}}function isWhitespace(ch){return ch===" "||ch==="\t"||ch===`
313
+ `||ch==="\r"}var init_edit_context=__esm(()=>{init_text_cursor()});function applyTextOp(text,op){if(op.offset<0||op.offset>text.length)throw RangeError(`TextOp offset ${op.offset} out of bounds for text of length ${text.length}`);if(op.type==="insert")return text.slice(0,op.offset)+op.text+text.slice(op.offset);if(op.type==="replace"){let end2=op.offset+op.deleted.length;if(end2>text.length)throw RangeError(`TextOp replace extends past end: offset=${op.offset}, deleteLen=${op.deleted.length}, textLen=${text.length}`);let actual2=text.slice(op.offset,end2);if(actual2!==op.deleted)throw Error(`TextOp replace mismatch at offset ${op.offset}: expected ${JSON.stringify(op.deleted)}, got ${JSON.stringify(actual2)}`);return text.slice(0,op.offset)+op.text+text.slice(end2)}let end=op.offset+op.text.length;if(end>text.length)throw RangeError(`TextOp delete extends past end: offset=${op.offset}, deleteLen=${op.text.length}, textLen=${text.length}`);let actual=text.slice(op.offset,end);if(actual!==op.text)throw Error(`TextOp delete mismatch at offset ${op.offset}: expected ${JSON.stringify(op.text)}, got ${JSON.stringify(actual)}`);return text.slice(0,op.offset)+text.slice(end)}function invertTextOp(op){if(op.type==="insert")return{type:"delete",offset:op.offset,text:op.text};if(op.type==="replace")return{type:"replace",offset:op.offset,text:op.deleted,deleted:op.text};return{type:"insert",offset:op.offset,text:op.text}}function mergeTextOps(a,b){if(a.type==="insert"&&b.type==="insert"){if(b.offset===a.offset+a.text.length)return{type:"insert",offset:a.offset,text:a.text+b.text};return null}if(a.type==="delete"&&b.type==="delete"){if(b.offset+b.text.length===a.offset)return{type:"delete",offset:b.offset,text:b.text+a.text};if(b.offset===a.offset)return{type:"delete",offset:a.offset,text:a.text+b.text};return null}if(a.type==="insert"&&b.type==="delete"){if(b.offset===a.offset&&b.text===a.text)return null}return null}import{useState as useState22,useCallback as useCallback29,useEffect as useEffect20,useLayoutEffect as useLayoutEffect7,useMemo as useMemo19,useRef as useRef25}from"react";function useEditContext({initialValue="",onChange,onConfirm,onCancel,onSave,onSplitAtBoundary,onMergeBackward,wrapWidth,initialCursorPos,stickyX,onTextOp}={}){let onChangeRef=useRef25(onChange);onChangeRef.current=onChange;let onConfirmRef=useRef25(onConfirm);onConfirmRef.current=onConfirm;let onCancelRef=useRef25(onCancel);onCancelRef.current=onCancel;let onSaveRef=useRef25(onSave);onSaveRef.current=onSave;let onSplitRef=useRef25(onSplitAtBoundary);onSplitRef.current=onSplitAtBoundary;let onMergeBackwardRef=useRef25(onMergeBackward);onMergeBackwardRef.current=onMergeBackward;let onTextOpRef=useRef25(onTextOp);onTextOpRef.current=onTextOp;let cancelledRef=useRef25(!1),initialValueRef=useRef25(initialValue),[_version,setVersion]=useState22(0),forceRender=useCallback29(()=>setVersion((v)=>v+1),[]),ctx=useMemo19(()=>{let effectiveWrapWidth=wrapWidth??1/0,cursorPos2;if(stickyX!=null&&initialValue.length>0)if(typeof initialCursorPos==="number")cursorPos2=Math.max(0,Math.min(initialCursorPos,initialValue.length));else{let targetRow=initialCursorPos==="start"?0:Math.max(0,countVisualLines(initialValue,effectiveWrapWidth)-1);cursorPos2=rowColToCursor(initialValue,targetRow,stickyX,effectiveWrapWidth)}else cursorPos2=typeof initialCursorPos==="number"?Math.max(0,Math.min(initialCursorPos,initialValue.length)):initialCursorPos==="start"?0:initialValue.length;return createTermEditContext({text:initialValue,selectionStart:cursorPos2,selectionEnd:cursorPos2,wrapWidth:effectiveWrapWidth})},[]);useLayoutEffect7(()=>{return ctx.onTextUpdate((op)=>{onChangeRef.current?.(ctx.text),onTextOpRef.current?.(op),forceRender()})},[ctx,forceRender]),useEffect20(()=>{if(wrapWidth!==void 0)ctx.setWrapWidth(wrapWidth)},[wrapWidth,ctx]);let target=useMemo19(()=>({insertChar(char){ctx.insertChar(char)},deleteBackward(){ctx.deleteBackward()},deleteForward(){ctx.deleteForward()},cursorLeft(){ctx.moveCursor("left"),forceRender()},cursorRight(){ctx.moveCursor("right"),forceRender()},cursorUp(){let moved=ctx.moveCursor("up");if(moved)forceRender();return moved},cursorDown(){let moved=ctx.moveCursor("down");if(moved)forceRender();return moved},cursorStart(){ctx.setCursorOffset(0),forceRender()},cursorEnd(){ctx.setCursorOffset(ctx.text.length),forceRender()},deleteWord(){ctx.deleteWord()},deleteToStart(){ctx.deleteToStart()},deleteToEnd(){ctx.deleteToEnd()},confirm(){cancelledRef.current=!0,onConfirmRef.current?.(ctx.text)},cancel(){cancelledRef.current=!0,onCancelRef.current?.()},save(){(onSaveRef.current??onConfirmRef.current)?.(ctx.text),initialValueRef.current=ctx.text},getCursorOffset(){return ctx.selectionStart},getContent(){return ctx.text},insertBreak(){return!!onSplitRef.current},replaceContent(content,cursor){ctx.updateText(0,ctx.text.length,content),ctx.setCursorOffset(cursor),initialValueRef.current=content,forceRender()},setCursorOffset(offset){ctx.setCursorOffset(Math.min(Math.max(0,offset),ctx.text.length)),forceRender()}}),[ctx,forceRender]);useLayoutEffect7(()=>{return activeEditContextRef.current=ctx,activeEditTargetRef.current=target,()=>{if(activeEditContextRef.current===ctx)activeEditContextRef.current=null;if(activeEditTargetRef.current===target)activeEditTargetRef.current=null;if(!cancelledRef.current){let currentValue=ctx.text;if(currentValue!==initialValueRef.current)onConfirmRef.current?.(currentValue)}}},[ctx,target]);let{text,selectionStart:cursorPos}=ctx,beforeCursor=text.slice(0,cursorPos),afterCursor=text.slice(cursorPos);return{value:text,cursor:cursorPos,beforeCursor,afterCursor,clear:useCallback29(()=>{ctx.updateText(0,ctx.text.length,""),ctx.setCursorOffset(0),onChangeRef.current?.(""),forceRender()},[ctx,forceRender]),setValue:useCallback29((value)=>{ctx.updateText(0,ctx.text.length,value),ctx.setCursorOffset(value.length),onChangeRef.current?.(value),forceRender()},[ctx,forceRender]),editContext:ctx,target,setCursorOffset:useCallback29((offset)=>{ctx.setCursorOffset(Math.min(Math.max(0,offset),ctx.text.length)),forceRender()},[ctx,forceRender])}}var activeEditContextRef,activeEditTargetRef;var init_use_edit_context=__esm(()=>{init_edit_context();init_text_cursor();activeEditContextRef={current:null},activeEditTargetRef={current:null}});function findCommand(registry,key){let byId=registry.get(key);if(byId)return byId;return registry.getAll().find((c)=>{return c.id.split(/[._]/).pop()===key})}function getKeysForCommand(commandId,keybindings){if(!keybindings)return[];return keybindings.filter((kb)=>kb.commandId===commandId).map((kb)=>{let parts=[];if(kb.cmd)parts.push("Cmd");if(kb.ctrl)parts.push("Ctrl");if(kb.alt||kb.opt)parts.push("Alt");if(kb.shift)parts.push("Shift");return parts.push(kb.key),parts.join("+")})}function formatHelp(registry,keybindings){return registry.getAll().map((cmd)=>{let keys=getKeysForCommand(cmd.id,keybindings),keyStr=keys.length>0?` [${keys.join(", ")}]`:"";return`${cmd.id}${keyStr}: ${cmd.description}`}).join(`
314
+ `)}function withCommands(appOrOptions,maybeOptions){if(maybeOptions===void 0){let options=appOrOptions;return(app)=>applyCommands(app,options)}return applyCommands(appOrOptions,maybeOptions)}function applyCommands(app,options){let{registry,getContext,handleAction,getKeybindings}=options,cmd=new Proxy({},{get(_2,prop){if(typeof prop==="symbol")return;if(prop==="all")return()=>{let commands=registry.getAll(),keybindings2=getKeybindings?.();return commands.map((c)=>({id:c.id,name:c.name,description:c.description,keys:getKeysForCommand(c.id,keybindings2)}))};if(prop==="describe")return()=>formatHelp(registry,getKeybindings?.());let def=findCommand(registry,prop);if(!def)return;let fn=async()=>{let ctx=getContext(),result=def.execute(ctx);if(result){let actions=Array.isArray(result)?result:[result];for(let action of actions)handleAction(action)}await Promise.resolve()},keybindings=getKeybindings?.();return Object.defineProperties(fn,{id:{value:def.id,enumerable:!0},name:{value:def.name,enumerable:!0},help:{value:def.description,enumerable:!0},keys:{value:getKeysForCommand(def.id,keybindings),enumerable:!0}}),fn},has(_2,prop){if(typeof prop==="symbol")return!1;if(prop==="all"||prop==="describe")return!0;return!!findCommand(registry,prop)}});return Object.assign(app,{cmd,getState:()=>{let commands=registry.getAll(),keybindings=getKeybindings?.();return{screen:app.text,commands:commands.map((c)=>({id:c.id,name:c.name,description:c.description,keys:getKeysForCommand(c.id,keybindings)})),focus:void 0}}})}var init_keys3=__esm(()=>{init_keys()});function resolveKeybinding(key,modifiers,bindings,ctx){for(let binding of bindings){if(binding.key!==key)continue;if(!!binding.ctrl!==!!modifiers.ctrl)continue;if(!!binding.opt!==!!modifiers.meta)continue;if(!!binding.cmd!==!!modifiers.super)continue;if(!(key.length===1&&key>="A"&&key<="Z"&&!binding.shift)&&!!binding.shift!==!!modifiers.shift)continue;if(binding.modes&&binding.modes.length>0){if(!binding.modes.includes(ctx.mode))continue}if(binding.when&&!binding.when(ctx))continue;return binding.commandId}return null}function withKeybindings(appOrOptions,maybeOptions){if(maybeOptions===void 0){let options=appOrOptions;return(app)=>applyKeybindings(app,options)}return applyKeybindings(appOrOptions,maybeOptions)}function applyKeybindings(app,options){let{bindings,getKeyContext}=options,originalPress=app.press.bind(app);return new Proxy(app,{get(target,prop,receiver){if(prop==="press")return async function(keyStr){let{key,...modifiers}=parseHotkey(keyStr),ctx=getKeyContext(),commandId=resolveKeybinding(key,modifiers,bindings,ctx);if(commandId){let cmd=target.cmd[commandId];if(cmd)return await cmd(),receiver}return await originalPress(keyStr),receiver};return Reflect.get(target,prop,receiver)}})}var init_with_keybindings=__esm(()=>{init_keys3()});function compareBuffers(a,b){let width=Math.max(a.width,b.width),height=Math.max(a.height,b.height);for(let y=0;y<height;y++)for(let x=0;x<width;x++){let cellA=a.inBounds(x,y)?a.getCell(x,y):{char:" ",fg:null,bg:null,underlineColor:null,attrs:{},wide:!1,continuation:!1},cellB=b.inBounds(x,y)?b.getCell(x,y):{char:" ",fg:null,bg:null,underlineColor:null,attrs:{},wide:!1,continuation:!1};if(!cellEquals(cellA,cellB))return{x,y,cellA,cellB}}return null}function formatMismatch(mismatch,context){let{x,y,cellA,cellB}=mismatch,lines=[`Buffer mismatch at (${x}, ${y})`,` incremental: char=${JSON.stringify(cellA.char)} fg=${JSON.stringify(cellA.fg)} bg=${JSON.stringify(cellA.bg)} attrs=${JSON.stringify(cellA.attrs)}`,` fresh: char=${JSON.stringify(cellB.char)} fg=${JSON.stringify(cellB.fg)} bg=${JSON.stringify(cellB.bg)} attrs=${JSON.stringify(cellB.attrs)}`];if(context?.seed!==void 0)lines.push(` seed: ${context.seed}`);if(context?.iteration!==void 0)lines.push(` iteration: ${context.iteration}`);if(context?.key)lines.push(` key: ${JSON.stringify(context.key)}`);if(context?.incrementalText)lines.push("","--- incremental ---",context.incrementalText);if(context?.freshText)lines.push("","--- fresh ---",context.freshText);return lines.join(`
315
+ `)}var init_compare_buffers=__esm(()=>{init_buffer()});import{mkdir}from"node:fs/promises";import{join}from"node:path";class VirtualTerminal{width;height;grid;wideMarker;styles;sgr;cursorX=0;cursorY=0;constructor(width,height){this.width=width;this.height=height;this.grid=Array.from({length:height},()=>Array(width).fill(" ")),this.wideMarker=Array.from({length:height},()=>Array(width).fill(!1)),this.styles=Array.from({length:height},()=>Array.from({length:width},()=>createDefaultVTermStyle())),this.sgr=createDefaultVTermStyle()}loadFromBuffer(buffer){for(let y=0;y<Math.min(this.height,buffer.height);y++)for(let x=0;x<Math.min(this.width,buffer.width);x++)if(buffer.isCellContinuation(x,y))this.wideMarker[y][x]=!0,this.grid[y][x]="",this.styles[y][x]=createDefaultVTermStyle();else{this.grid[y][x]=buffer.getCellChar(x,y),this.wideMarker[y][x]=!1;let cell=buffer.getCell(x,y);this.styles[y][x]={fg:cell.fg,bg:cell.bg,bold:!!cell.attrs.bold,dim:!!cell.attrs.dim,italic:!!cell.attrs.italic,underline:!!cell.attrs.underline||!!cell.attrs.underlineStyle,blink:!!cell.attrs.blink,inverse:!!cell.attrs.inverse,hidden:!!cell.attrs.hidden,strikethrough:!!cell.attrs.strikethrough}}}applyAnsi(ansi){let i=0;while(i<ansi.length){if(ansi[i]==="\x1B"&&ansi[i+1]==="["){let match=ansi.slice(i).match(/^\x1b\[([0-9;:?]*)([A-Za-z])/);if(match){this.handleCsi(match[1]||"",match[2]),i+=match[0].length;continue}}if(ansi[i]==="\r"){this.cursorX=0,i++;continue}if(ansi[i]===`
316
+ `){this.cursorY=Math.min(this.cursorY+1,this.height-1),i++;continue}let char=this.extractChar(ansi,i);if(this.cursorX<this.width&&this.cursorY<this.height){if(this.grid[this.cursorY][this.cursorX]=char,this.wideMarker[this.cursorY][this.cursorX]=!1,this.styles[this.cursorY][this.cursorX]={...this.sgr},this.cursorX++,this.isWideChar(char)&&this.cursorX<this.width)this.grid[this.cursorY][this.cursorX]="",this.wideMarker[this.cursorY][this.cursorX]=!0,this.styles[this.cursorY][this.cursorX]=createDefaultVTermStyle(),this.cursorX++}i+=char.length}}isWideChar(char){if(char.length===0)return!1;if(char.includes("️"))return!0;let code=char.codePointAt(0)||0;if(code>=127744&&code<=129535)return!0;if(code>=9728&&code<=9983)return!0;if(code>=9984&&code<=10175)return!0;if(code>=19968&&code<=40959)return!0;if(code>=12288&&code<=12351)return!0;if(code>=65280&&code<=65519)return!0;return!1}extractChar(str,start){let code=str.codePointAt(start);if(code===void 0)return str[start]||"";let char;if(code>65535)char=String.fromCodePoint(code);else char=str[start]||"";let nextIdx=start+char.length;if(nextIdx<str.length&&str.codePointAt(nextIdx)===65039)char+="️";return char}handleCsi(params,cmd){switch(cmd){case"H":{let parts=params.split(";");this.cursorY=Math.max(0,(Number.parseInt(parts[0]||"1",10)||1)-1),this.cursorX=Math.max(0,(Number.parseInt(parts[1]||"1",10)||1)-1);break}case"G":{this.cursorX=Math.max(0,(Number.parseInt(params||"1",10)||1)-1);break}case"A":{let n=Number.parseInt(params||"1",10)||1;this.cursorY=Math.max(0,this.cursorY-n);break}case"B":{let n=Number.parseInt(params||"1",10)||1;this.cursorY=Math.min(this.height-1,this.cursorY+n);break}case"C":{let n=Number.parseInt(params||"1",10)||1;this.cursorX=Math.min(this.width-1,this.cursorX+n);break}case"D":{let n=Number.parseInt(params||"1",10)||1;this.cursorX=Math.max(0,this.cursorX-n);break}case"K":{let mode=Number.parseInt(params||"0",10);if(mode===0)for(let x=this.cursorX;x<this.width;x++)this.grid[this.cursorY][x]=" ",this.wideMarker[this.cursorY][x]=!1,this.styles[this.cursorY][x]={...createDefaultVTermStyle(),bg:this.sgr.bg};else if(mode===1)for(let x=0;x<=this.cursorX;x++)this.grid[this.cursorY][x]=" ",this.wideMarker[this.cursorY][x]=!1,this.styles[this.cursorY][x]={...createDefaultVTermStyle(),bg:this.sgr.bg};else if(mode===2)for(let x=0;x<this.width;x++)this.grid[this.cursorY][x]=" ",this.wideMarker[this.cursorY][x]=!1,this.styles[this.cursorY][x]={...createDefaultVTermStyle(),bg:this.sgr.bg};break}case"m":this.applySgr(params);break;case"l":case"h":break}}applySgr(params){if(params===""||params==="0"){Object.assign(this.sgr,createDefaultVTermStyle());return}let parts=params.split(";"),i=0;while(i<parts.length){let code=parts[i],colonIdx=code.indexOf(":");if(colonIdx>=0){if(Number.parseInt(code.substring(0,colonIdx),10)===4){let sub=Number.parseInt(code.substring(colonIdx+1),10);this.sgr.underline=sub>0}i++;continue}let n=Number.parseInt(code,10);if(n===0)Object.assign(this.sgr,createDefaultVTermStyle());else if(n===1)this.sgr.bold=!0;else if(n===2)this.sgr.dim=!0;else if(n===3)this.sgr.italic=!0;else if(n===4)this.sgr.underline=!0;else if(n===5||n===6)this.sgr.blink=!0;else if(n===7)this.sgr.inverse=!0;else if(n===8)this.sgr.hidden=!0;else if(n===9)this.sgr.strikethrough=!0;else if(n===22)this.sgr.bold=!1,this.sgr.dim=!1;else if(n===23)this.sgr.italic=!1;else if(n===24)this.sgr.underline=!1;else if(n===25)this.sgr.blink=!1;else if(n===27)this.sgr.inverse=!1;else if(n===28)this.sgr.hidden=!1;else if(n===29)this.sgr.strikethrough=!1;else if(n>=30&&n<=37)this.sgr.fg=n-30;else if(n===38){if(i+1<parts.length&&parts[i+1]==="5"&&i+2<parts.length)this.sgr.fg=Number.parseInt(parts[i+2],10),i+=2;else if(i+1<parts.length&&parts[i+1]==="2"&&i+4<parts.length)this.sgr.fg={r:Number.parseInt(parts[i+2],10),g:Number.parseInt(parts[i+3],10),b:Number.parseInt(parts[i+4],10)},i+=4}else if(n===39)this.sgr.fg=null;else if(n>=40&&n<=47)this.sgr.bg=n-40;else if(n===48){if(i+1<parts.length&&parts[i+1]==="5"&&i+2<parts.length)this.sgr.bg=Number.parseInt(parts[i+2],10),i+=2;else if(i+1<parts.length&&parts[i+1]==="2"&&i+4<parts.length)this.sgr.bg={r:Number.parseInt(parts[i+2],10),g:Number.parseInt(parts[i+3],10),b:Number.parseInt(parts[i+4],10)},i+=4}else if(n===49)this.sgr.bg=null;else if(n>=90&&n<=97)this.sgr.fg=n-90+8;else if(n>=100&&n<=107)this.sgr.bg=n-100+8;i++}}getChar(x,y){if(this.wideMarker[y]?.[x])return"";return this.grid[y]?.[x]??" "}getStyle(x,y){return this.styles[y]?.[x]??createDefaultVTermStyle()}compareToBuffer(buffer){let mismatches=[];for(let y=0;y<Math.min(this.height,buffer.height);y++)for(let x=0;x<Math.min(this.width,buffer.width);x++){if(buffer.isCellContinuation(x,y))continue;let expected=buffer.getCellChar(x,y),actual=this.getChar(x,y);if(expected!==actual)mismatches.push({x,y,expected,actual})}return mismatches}compareStylesToBuffer(buffer){let mismatches=[];for(let y=0;y<Math.min(this.height,buffer.height);y++)for(let x=0;x<Math.min(this.width,buffer.width);x++){if(buffer.isCellContinuation(x,y))continue;let cell=buffer.getCell(x,y),actual=this.getStyle(x,y),diffs=[];if(!colorEquals(actual.fg,cell.fg))diffs.push(`fg: ${formatVTermColor(actual.fg)} vs ${formatVTermColor(cell.fg)}`);if(!colorEquals(actual.bg,cell.bg))diffs.push(`bg: ${formatVTermColor(actual.bg)} vs ${formatVTermColor(cell.bg)}`);if(actual.bold!==!!cell.attrs.bold)diffs.push(`bold: ${actual.bold} vs ${!!cell.attrs.bold}`);if(actual.dim!==!!cell.attrs.dim)diffs.push(`dim: ${actual.dim} vs ${!!cell.attrs.dim}`);if(actual.italic!==!!cell.attrs.italic)diffs.push(`italic: ${actual.italic} vs ${!!cell.attrs.italic}`);let expectedUnderline=!!cell.attrs.underline||!!cell.attrs.underlineStyle;if(actual.underline!==expectedUnderline)diffs.push(`underline: ${actual.underline} vs ${expectedUnderline}`);if(actual.blink!==!!cell.attrs.blink)diffs.push(`blink: ${actual.blink} vs ${!!cell.attrs.blink}`);if(actual.inverse!==!!cell.attrs.inverse)diffs.push(`inverse: ${actual.inverse} vs ${!!cell.attrs.inverse}`);if(actual.hidden!==!!cell.attrs.hidden)diffs.push(`hidden: ${actual.hidden} vs ${!!cell.attrs.hidden}`);if(actual.strikethrough!==!!cell.attrs.strikethrough)diffs.push(`strikethrough: ${actual.strikethrough} vs ${!!cell.attrs.strikethrough}`);if(diffs.length>0)mismatches.push({x,y,char:cell.char,diffs})}return mismatches}}function createDefaultVTermStyle(){return{fg:null,bg:null,bold:!1,dim:!1,italic:!1,underline:!1,blink:!1,inverse:!1,hidden:!1,strikethrough:!1}}function formatVTermColor(c){if(c===null)return"default";if(typeof c==="number")return`${c}`;return`rgb(${c.r},${c.g},${c.b})`}function parseSkipLines(env){if(!env)return[];return env.split(",").map((s)=>Number.parseInt(s.trim(),10)).filter((n)=>!isNaN(n))}function compareText(before,after,skipLines){let beforeLines=before.split(`
317
+ `),afterLines=after.split(`
318
+ `),maxLines=Math.max(beforeLines.length,afterLines.length),skipSet=new Set;for(let line of skipLines)if(line>=0)skipSet.add(line);else skipSet.add(maxLines+line);for(let i=0;i<maxLines;i++){if(skipSet.has(i))continue;let b=beforeLines[i]??"",a=afterLines[i]??"";if(b!==a)return{line:i,before:b,after:a}}return null}function checkLayoutInvariants(node){let violations=[];return walkLayout(node,null,violations),violations}function walkLayout(node,parentRect,violations){let rect=node.contentRect;if(!rect)return;let id=node.props.id??node.type;if(!Number.isFinite(rect.width)||rect.width<0)violations.push(`${id}: invalid width ${rect.width}`);if(!Number.isFinite(rect.height)||rect.height<0)violations.push(`${id}: invalid height ${rect.height}`);if(!Number.isFinite(rect.x))violations.push(`${id}: invalid x ${rect.x}`);if(!Number.isFinite(rect.y))violations.push(`${id}: invalid y ${rect.y}`);if(parentRect&&!parentRect.clipped){if(rect.x+rect.width>parentRect.x+parentRect.width+1)violations.push(`${id}: overflows parent right (${rect.x+rect.width} > ${parentRect.x+parentRect.width})`);if(rect.y+rect.height>parentRect.y+parentRect.height+1)violations.push(`${id}: overflows parent bottom (${rect.y+rect.height} > ${parentRect.y+parentRect.height})`);if(rect.x<parentRect.x-1)violations.push(`${id}: overflows parent left (${rect.x} < ${parentRect.x})`);if(rect.y<parentRect.y-1)violations.push(`${id}: overflows parent top (${rect.y} < ${parentRect.y})`)}let overflow=node.props.overflow,clipped=overflow==="hidden"||overflow==="scroll",childParentRect={x:rect.x,y:rect.y,width:rect.width,height:rect.height,clipped};for(let child of node.children)walkLayout(child,childParentRect,violations)}function withDiagnostics(app,options={}){let{checkIncremental=!0,checkStability=!0,checkReplay=!0,checkLayout=!0,skipLines=parseSkipLines(process.env.SILVERY_STABILITY_SKIP_LINES),captureOnFailure=!1,screenshotDir="/tmp/silvery-diagnostics"}=options;if(!checkIncremental&&!checkStability&&!checkReplay&&!checkLayout)return app;async function captureFailureScreenshot(commandId,checkType){if(!captureOnFailure)return null;try{await mkdir(screenshotDir,{recursive:!0});let filename=`fail-${commandId}-${checkType}.png`,filepath=join(screenshotDir,filename);return await app.screenshot(filepath),filepath}catch{return null}}let wrappedCmd=new Proxy(app.cmd,{get(target,prop){if(typeof prop==="symbol")return Reflect.get(target,prop);let original=Reflect.get(target,prop);if(typeof original!=="function")return original;if(prop==="all"||prop==="describe")return original;let command=original,wrapped=async()=>{let beforeText=app.text,beforeBuffer=checkReplay?app.lastBuffer():null;if(await command(),checkIncremental){let incremental=app.lastBuffer();try{let fresh=app.freshRender();if(incremental&&fresh){let mismatch=compareBuffers(incremental,fresh);if(mismatch){let incrementalText=app.text,freshText=fresh?Array.from({length:fresh.height},(_2,y)=>Array.from({length:fresh.width},(_3,x)=>fresh.getCellChar(x,y)).join("")).join(`
319
+ `):"(no fresh buffer)",screenshotPath=await captureFailureScreenshot(command.id,"incremental");throw Error(`SILVERY_DIAGNOSTIC: Incremental/fresh mismatch after ${command.id}
320
+ `+formatMismatch(mismatch,{key:command.id,incrementalText,freshText})+(screenshotPath?`
321
+ Screenshot saved: ${screenshotPath}`:""))}}}catch(e){if(!(e instanceof Error)||!e.message.includes("only available in test renderer"))throw e}}if(checkStability&&CURSOR_COMMANDS.has(command.id)){let afterText=app.text,mismatch=compareText(beforeText,afterText,skipLines);if(mismatch){let screenshotPath=await captureFailureScreenshot(command.id,"stability");throw Error(`SILVERY_DIAGNOSTIC: Content changed after cursor move ${command.id}
322
+ Line ${mismatch.line}: "${mismatch.before}" → "${mismatch.after}"`+(screenshotPath?`
323
+ Screenshot saved: ${screenshotPath}`:""))}}if(checkReplay&&beforeBuffer){let afterBuffer=app.lastBuffer();if(afterBuffer){let ansiDiff=outputPhase(beforeBuffer,afterBuffer),vterm=new VirtualTerminal(afterBuffer.width,afterBuffer.height);vterm.loadFromBuffer(beforeBuffer),vterm.applyAnsi(ansiDiff);let mismatches=vterm.compareToBuffer(afterBuffer);if(mismatches.length>0){let details=mismatches.slice(0,5).map((m)=>` (${m.x},${m.y}): expected="${m.expected}" actual="${m.actual}"`).join(`
324
+ `),screenshotPath=await captureFailureScreenshot(command.id,"replay");throw Error(`SILVERY_DIAGNOSTIC: ANSI replay mismatch after ${command.id}
325
+ ${mismatches.length} cells differ:
326
+ ${details}`+(mismatches.length>5?`
327
+ ... and ${mismatches.length-5} more`:"")+(screenshotPath?`
328
+ Screenshot saved: ${screenshotPath}`:""))}let styleMismatches=vterm.compareStylesToBuffer(afterBuffer);if(styleMismatches.length>0){let details=styleMismatches.slice(0,5).map((m)=>` (${m.x},${m.y}) char="${m.char}": ${m.diffs.join(", ")}`).join(`
329
+ `),screenshotPath=await captureFailureScreenshot(command.id,"replay-style");throw Error(`SILVERY_DIAGNOSTIC: ANSI replay style mismatch after ${command.id}
330
+ ${styleMismatches.length} cells have style differences:
331
+ ${details}`+(styleMismatches.length>5?`
332
+ ... and ${styleMismatches.length-5} more`:"")+(screenshotPath?`
333
+ Screenshot saved: ${screenshotPath}`:""))}}}if(checkLayout){let root=app.getContainer(),violations=checkLayoutInvariants(root);if(violations.length>0){let details=violations.slice(0,10).map((v)=>` ${v}`).join(`
334
+ `),screenshotPath=await captureFailureScreenshot(command.id,"layout");throw Error(`SILVERY_DIAGNOSTIC: Layout invariant violation after ${command.id}
335
+ ${violations.length} violation(s):
336
+ ${details}`+(violations.length>10?`
337
+ ... and ${violations.length-10} more`:"")+(screenshotPath?`
338
+ 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{...app,cmd:wrappedCmd}}var CURSOR_COMMANDS;var init_with_diagnostics=__esm(()=>{init_buffer();init_pipeline2();init_compare_buffers();CURSOR_COMMANDS=new Set(["cursor_up","cursor_down","cursor_left","cursor_right","up","down","left","right"])});import{useCallback as useCallback30,useId,useLayoutEffect as useLayoutEffect8,useMemo as useMemo20,useRef as useRef26}from"react";import{jsxDEV as jsxDEV50}from"react/jsx-dev-runtime";function createSubscriberList2(){return{input:new Set,paste:new Set}}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=useRef26(null);if(!subscribersRef.current)subscribersRef.current=createSubscriberList2();let subscribers=subscribersRef.current,activeRef=useRef26(active);activeRef.current=active;let onEscapeRef=useRef26(onEscape);onEscapeRef.current=onEscape;let exitKeyRef=useRef26(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=useMemo20(()=>({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 useLayoutEffect8(()=>{return()=>{subscribers.input.clear(),subscribers.paste.clear()}},[subscribers]),jsxDEV50(RuntimeContext.Provider,{value:runtimeContextValue,children:jsxDEV50(InputLayerProvider,{children},void 0,!1,void 0,this)},void 0,!1,void 0,this)}var init_InputBoundary=__esm(()=>{init_context();init_keys();init_InputLayerContext()});function resolveEasing(easing){return typeof easing==="function"?easing:easings[easing]}var easings;var init_easing=__esm(()=>{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}});import{useState as useState23,useEffect as useEffect21,useRef as useRef27,useCallback as useCallback31}from"react";function useAnimation(options){let{duration,easing="linear",delay=0,onComplete,enabled=!0}=options,[value,setValue]=useState23(0),[isAnimating,setIsAnimating]=useState23(!1),startTimeRef=useRef27(0),intervalRef=useRef27(null),onCompleteRef=useRef27(onComplete);onCompleteRef.current=onComplete;let epochRef=useRef27(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]);useEffect21(()=>{if(!enabled){stopInterval(),setValue(0),setIsAnimating(!1);return}return startAnimation(),()=>{stopInterval()}},[enabled,startAnimation,stopInterval]);let reset=useCallback31(()=>{startAnimation()},[startAnimation]);return{value,isAnimating,reset}}var TICK_MS=33;var init_useAnimation=__esm(()=>{init_easing()});import{useState as useState24,useEffect as useEffect22,useRef as useRef28}from"react";function useTransition(targetValue,options){let{duration=300,easing="easeOut"}=options??{},[currentValue,setCurrentValue]=useState24(targetValue),fromRef=useRef28(targetValue),toRef=useRef28(targetValue),startTimeRef=useRef28(0),intervalRef=useRef28(null),isFirstRef=useRef28(!0),easingFn=resolveEasing(easing);return useEffect22(()=>{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}var TICK_MS2=33;var init_useTransition=__esm(()=>{init_easing()});import{useEffect as useEffect23,useRef as useRef29}from"react";function useInterval(callback,ms,enabled=!0){let callbackRef=useRef29(callback);callbackRef.current=callback,useEffect23(()=>{if(!enabled)return;let id=setInterval(()=>{callbackRef.current()},ms);return()=>{clearInterval(id)}},[ms,enabled])}var init_useInterval=()=>{};import{useCallback as useCallback32,useEffect as useEffect24,useRef as useRef30}from"react";function useTimeout(callback,ms,enabled=!0){let callbackRef=useRef30(callback);callbackRef.current=callback;let timerRef=useRef30(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 useEffect24(()=>{if(!enabled){clear();return}return timerRef.current=setTimeout(()=>{timerRef.current=null,callbackRef.current()},ms),clear},[ms,enabled,clear]),{reset,clear}}var init_useTimeout=()=>{};import{useRef as useRef31}from"react";function useLatest(value){let ref=useRef31(value);return ref.current=value,ref}var init_useLatest=()=>{};var init_animation=__esm(()=>{init_easing();init_useAnimation();init_useTransition();init_useInterval();init_useTimeout();init_useLatest()});var init_animation2=__esm(()=>{init_animation();init_animation()});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}}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(effect,dispatch){let id=effect.id??`__anon_${nextAnon++}`;clearTimer(id);let timer=setTimeout(()=>{timers.delete(id),dispatch(effect.msg)},effect.ms);timers.set(id,timer)},interval(effect,dispatch){clearTimer(effect.id);let timer=setInterval(()=>{dispatch(effect.msg)},effect.ms);timers.set(effect.id,timer)},cancel(effect){clearTimer(effect.id)}};function cleanup(){for(let[id]of timers)clearTimer(id)}return{runners,cleanup}}var fx;var init_effects=__esm(()=>{fx={delay,interval,cancel}});import{useCallback as useCallback33,useEffect as useEffect25,useRef as useRef32,useReducer as useReducer2}from"react";function useTea(initialState,update,customRunners){let timerRef=useRef32(null);if(timerRef.current===null)timerRef.current=createTimerRunners();let{runners:timerRunners,cleanup}=timerRef.current,customRunnersRef=useRef32(customRunners);customRunnersRef.current=customRunners;let pendingEffectsRef=useRef32([]),[state,reactDispatch]=useReducer2((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=useRef32(()=>{}),executeEffects=useCallback33(()=>{if(pendingEffectsRef.current.length===0)return;let effects=pendingEffectsRef.current.splice(0);for(let effect of effects){let timerRunner=timerRunners[effect.type];if(timerRunner){timerRunner(effect,sendRef.current);continue}let customRunner=customRunnersRef.current?.[effect.type];if(customRunner)customRunner(effect,sendRef.current)}},[timerRunners]),send=useCallback33((msg)=>{reactDispatch(msg),queueMicrotask(executeEffects)},[reactDispatch,executeEffects]);return sendRef.current=send,useEffect25(()=>{executeEffects()},[executeEffects]),useEffect25(()=>cleanup,[cleanup]),[state,send]}var init_useTea=__esm(()=>{init_effects()});var init_focus_manager2=__esm(()=>{init_focus_manager()});var init_focus_events2=__esm(()=>{init_focus_events()});var init_core=__esm(()=>{init_focus_manager2();init_focus_events2()});var init_store=__esm(()=>{init_core()});var init_types3=()=>{};var init_tree_utils=()=>{};var init_with_focus=__esm(()=>{init_focus_manager2();init_focus_events2();init_keys3()});var init_with_dom_events=__esm(()=>{init_mouse_events()});import React28,{createContext as createContext14,Fragment as Fragment5}from"react";var InkCursorStoreCtx;var init_with_ink_cursor=__esm(()=>{init_useCursor();InkCursorStoreCtx=createContext14(null)});import React29,{createContext as createContext15,Fragment as Fragment6,useCallback as useCallback34,useEffect as useEffect26,useMemo as useMemo21,useState as useState25}from"react";var InkFocusContext;var init_with_ink_focus=__esm(()=>{InkFocusContext=createContext15({activeId:void 0,isFocusEnabled:!0,add(){},remove(){},activate(){},deactivate(){},enableFocus(){},disableFocus(){},focusNext(){},focusPrevious(){},focus(){},blur(){}})});var init_with_ink=__esm(()=>{init_with_ink_cursor();init_with_ink_focus()});var init_plugins=__esm(()=>{init_with_focus();init_with_dom_events();init_with_keybindings();init_with_diagnostics();init_with_ink();init_with_ink_cursor();init_with_ink_focus();init_scheduler()});var init_create_buffer=__esm(()=>{init_buffer()});var init_diff=__esm(()=>{init_pipeline2()});var init_create_runtime=__esm(()=>{init_output_phase();init_diff()});var init_event_handlers=__esm(()=>{init_focus_events();init_mouse_events();init_reconciler()});import React30 from"react";var init_layout=__esm(()=>{init_ansi();init_buffer();init_context();init_pipeline2();init_reconciler()});var init_terminal_lifecycle=__esm(()=>{init_output()});var init_selection_renderer=()=>{};var init_virtual_scrollback=__esm(()=>{init_unicode()});import React31,{createContext as createContext16,useContext as useContext28,useEffect as useEffect27,useRef as useRef33}from"react";import{createStore}from"zustand";import{jsxDEV as jsxDEV51}from"react/jsx-dev-runtime";var StoreContext;var init_create_app=__esm(()=>{init_ansi();init_context();init_error_boundary();init_focus_manager();init_useCursor();init_focus_events();init_pipeline2();init_measurer();init_text_sizing();init_scheduler();init_reconciler();init_create_buffer();init_create_runtime();init_event_handlers();init_keys();init_keys2();init_layout();init_mouse_events();init_output();init_kitty_detect();init_terminal_lifecycle();init_term_provider();init_selection_renderer();init_virtual_scrollback();StoreContext=createContext16(null)});var init_src2=__esm(()=>{init_core();init_focus_events2();init_store();init_effects();init_keys3();init_text_cursor();init_types3();init_tree_utils();init_with_focus();init_with_dom_events();init_with_keybindings();init_with_diagnostics();init_with_render();init_plugins();init_create_app()});import{useTransition as useTransition2,useDeferredValue,useId as useId2}from"react";var init_exports=__esm(()=>{init_Box();init_components();init_components();init_components();init_components();init_components();init_Text();init_Link();init_Transform();init_Fill();init_Newline();init_Spacer();init_Static();init_components();init_components();init_components();init_components();init_components();init_error_boundary();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_components();init_image();init_image();init_image();init_useLayout();init_useInput();init_useApp();init_useStdout();init_useStderr();init_useFocusManager();init_focus_manager();init_focus_events();init_useFocusable();init_useFocusWithin();init_useTerminalFocused();init_useModifierKeys();init_useMouseCursor();init_useTerm();init_useWindowSize();init_useConsole();init_useCursor();init_useSelection();init_useScrollback();init_useVirtualizer();init_useScrollbackItem();init_useListItem();init_SurfaceRegistry();init_SearchProvider();init_components();init_useRuntime();init_context();init_ThemeProvider();init_ThemeContext();init_src();init_ansi();init_hit_registry();init_render();init_render_string();init_accessibility();init_output();init_osc_palette();init_osc_markers();init_kitty_detect();init_terminal_caps();init_termtest();init_output_phase();init_with_render();init_text_sizing();init_cursor_query();init_terminal_colors();init_device_attrs();init_mode_query();init_pixel_size();init_canvas_adapter();init_dom_adapter();init_keys();init_mouse();init_mouse_events();init_non_tty();init_devtools();init_inspector();init_unicode();init_unicode();init_measurer();init_text_cursor();init_edit_context();init_use_edit_context();init_with_keybindings();init_with_diagnostics();init_scheduler();init_InputLayerContext();init_InputBoundary();init_usePositionRegistry();init_useGridPosition();init_components();init_animation2();init_animation2();init_useTea();init_src2()});var exports_src={};__export(exports_src,{writeTextTruncated:()=>writeTextTruncated,writeTextToBuffer:()=>writeTextToBuffer,writeLinesToBuffer:()=>writeLinesToBuffer,wrapText:()=>wrapText,withRender:()=>withRender,withMeasurer:()=>withMeasurer,withKeybindings:()=>withKeybindings,withDiagnostics:()=>withDiagnostics,withCommands:()=>withCommands,useWindowSize:()=>useWindowSize,useVirtualizer:()=>useVirtualizer,useTransition:()=>useTransition2,useToast:()=>useToast,useTimeout:()=>useTimeout,useTheme:()=>useTheme,useTextArea:()=>useTextArea,useTerminalFocused:()=>useTerminalFocused,useTerm:()=>useTerm,useTea:()=>useTea,useSurfaceRegistryOptional:()=>useSurfaceRegistryOptional,useSurfaceRegistry:()=>useSurfaceRegistry,useStdout:()=>useStdout,useStderr:()=>useStderr,useSelectionContext:()=>useSelectionContext,useSelection:()=>useSelection,useSearch:()=>useSearch,useScrollbackItem:()=>useScrollbackItem,useScrollback:()=>useScrollback,useScreenRectCallback:()=>useScreenRectCallback,useScreenRect:()=>useScreenRect,useRuntime:()=>useRuntime,useRenderRectCallback:()=>useRenderRectCallback,useRenderRect:()=>useRenderRect,useReadline:()=>useReadline,usePositionRegistry:()=>usePositionRegistry,useMouseCursor:()=>useMouseCursor,useModifierKeys:()=>useModifierKeys,useListItem:()=>useListItem,useLatest:()=>useLatest,useInterval:()=>useInterval,useInputLayerContext:()=>useInputLayerContext,useInputLayer:()=>useInputLayer,useInput:()=>useInput,useId:()=>useId2,useHitRegistry:()=>useHitRegistry,useHitRegionCallback:()=>useHitRegionCallback,useHitRegion:()=>useHitRegion,useGridPosition:()=>useGridPosition,useFocusable:()=>useFocusable,useFocusWithin:()=>useFocusWithin,useFocusManager:()=>useFocusManager,useEditContext:()=>useEditContext,useDeferredValue:()=>useDeferredValue,useCursor:()=>useCursor,useContentRectCallback:()=>useContentRectCallback,useContentRect:()=>useContentRect,useConsole:()=>useConsole,useApp:()=>useApp,useAnimation:()=>useAnimation,useAnimatedTransition:()=>useTransition,truncateText:()=>truncateText,truncateAnsi:()=>truncateAnsi,textSized:()=>textSized,term:()=>term,swapPanes:()=>swapPanes,supportsScrollRegions:()=>supportsScrollRegions,subscribeCursor:()=>subscribeCursor,stripAnsiUnicode:()=>stripAnsi3,stripAnsi:()=>stripAnsi3,splitPane:()=>splitPane,splitGraphemes:()=>splitGraphemes,sliceByWidthRange:()=>sliceByWidthRange,sliceByWidthFromEnd:()=>sliceByWidthFromEnd,sliceByWidth:()=>sliceByWidth,shallow:()=>shallow,setWindowTitle:()=>setWindowTitle,setWindowAndIconTitle:()=>setWindowAndIconTitle,setTextSizingEnabled:()=>setTextSizingEnabled,setTextEmojiWide:()=>setTextEmojiWide,setScrollRegion:()=>setScrollRegion2,setRenderAdapter:()=>setRenderAdapter,setPaletteColor:()=>setPaletteColor,setOutputCaps:()=>setOutputCaps,setMouseCursorShape:()=>setMouseCursorShape,setLayoutEngine:()=>setLayoutEngine,setForegroundColor:()=>setForegroundColor,setCursorStyle:()=>setCursorStyle,setCursorColor:()=>setCursorColor,setBackgroundColor:()=>setBackgroundColor,scrollUp:()=>scrollUp2,scrollDown:()=>scrollDown2,runWithMeasurer:()=>runWithMeasurer,runTermtest:()=>runTermtest,rowColToCursor:()=>rowColToCursor,resolveThemeColor:()=>resolveThemeColor,resolveTermDef:()=>resolveTermDef,resolveNonTTYMode:()=>resolveNonTTYMode,resolveFromTerm:()=>resolveFromTerm,resolveEasing:()=>resolveEasing,resizeSplit:()=>resizeSplit,resetWindowTitle:()=>resetWindowTitle,resetScrollRegion:()=>resetScrollRegion2,resetMouseCursorShape:()=>resetMouseCursorShape,resetHitRegionIdCounter:()=>resetHitRegionIdCounter,resetForegroundColor:()=>resetForegroundColor,resetCursorStyle:()=>resetCursorStyle,resetCursorState:()=>resetCursorState,resetCursorColor:()=>resetCursorColor,resetBackgroundColor:()=>resetBackgroundColor,requestClipboard:()=>requestClipboard,reportDirectory:()=>reportDirectory,renderSync:()=>renderSync,renderStringSync:()=>renderStringSync,renderString:()=>renderString,renderStatic:()=>renderStatic,renderScreenReaderOutput:()=>renderScreenReaderOutput,render:()=>render,removePane:()=>removePane,queryTextAreaSize:()=>queryTextAreaSize,queryTextAreaPixels:()=>queryTextAreaPixels,queryTertiaryDA:()=>queryTertiaryDA,queryTerminalVersion:()=>queryTerminalVersion,querySecondaryDA:()=>querySecondaryDA,queryPrimaryDA:()=>queryPrimaryDA,queryPaletteColor:()=>queryPaletteColor,queryMultiplePaletteColors:()=>queryMultiplePaletteColors,queryModes:()=>queryModes,queryMode:()=>queryMode,queryKittyKeyboard:()=>queryKittyKeyboard,queryForegroundColor:()=>queryForegroundColor,queryDeviceAttributes:()=>queryDeviceAttributes,queryCursorPosition:()=>queryCursorPosition,queryCursorFromStdio:()=>queryCursorFromStdio,queryCursorColor:()=>queryCursorColor,queryCellSize:()=>queryCellSize,queryBackgroundColor:()=>queryBackgroundColor,processMouseEvent:()=>processMouseEvent,patchConsole:()=>patchConsole,parsePaletteResponse:()=>parsePaletteResponse,parseMouseSequence:()=>parseMouseSequence,parseKeypress:()=>parseKeypress,parseKey:()=>parseKey,parseHotkey:()=>parseHotkey,parseFocusEvent:()=>parseFocusEvent,parseClipboardResponse:()=>parseClipboardResponse,parseBracketedPaste:()=>parseBracketedPaste,parseAnsiText:()=>parseAnsiText,padText:()=>padText,notifyKitty:()=>notifyKitty,notifyITerm2:()=>notifyITerm2,notify:()=>notify,normalizeText:()=>normalizeText,moveCursor:()=>moveCursor2,mergeTextOps:()=>mergeTextOps,measureText:()=>measureText,measureElement:()=>measureElement,matchHotkey:()=>matchHotkey,lastModifierState:()=>lastModifierState,keyToName:()=>keyToName,keyToModifiers:()=>keyToModifiers,isZeroWidthGrapheme:()=>isZeroWidthGrapheme,isWideGrapheme:()=>isWideGrapheme,isTextSizingLikelySupported:()=>isTextSizingLikelySupported,isTextSizingEnabled:()=>isTextSizingEnabled,isTermDef:()=>isTermDef,isTerm:()=>isTerm,isTTY:()=>isTTY,isSixelSupported:()=>isSixelSupported,isPrivateUseArea:()=>isPrivateUseArea,isMouseSequence:()=>isMouseSequence,isLikelyEmoji:()=>isLikelyEmoji,isLayoutEngineInitialized:()=>isLayoutEngineInitialized,isKittyGraphicsSupported:()=>isKittyGraphicsSupported,isInspectorEnabled:()=>isInspectorEnabled,isDevToolsConnected:()=>isDevToolsConnected,isCJK:()=>isCJK,invertTextOp:()=>invertTextOp,inspectTree:()=>inspectTree,inspectFrame:()=>inspectFrame,injectDOMStyles:()=>injectDOMStyles,initYogaEngine:()=>initYogaEngine,hitTest:()=>hitTest,hasZeroWidthCharacters:()=>hasZeroWidthCharacters,hasWideCharacters:()=>hasWideCharacters,hasRenderAdapter:()=>hasRenderAdapter,hasAnsi:()=>hasAnsi,graphemeWidth:()=>graphemeWidth,graphemeCount:()=>graphemeCount,getWrappedLines:()=>getWrappedLines,getThemeByName:()=>getThemeByName,getTextMeasurer:()=>getTextMeasurer,getTabOrder:()=>getTabOrder2,getSplitTabOrder:()=>getTabOrder,getRenderAdapter:()=>getRenderAdapter,getPaneIds:()=>getPaneIds,getModifierState:()=>getModifierState,getFirstCodePoint:()=>getFirstCodePoint,getExplicitFocusLink:()=>getExplicitFocusLink,getCursorState:()=>getCursorState,generateTheme:()=>generateTheme,fx:()=>fx,formatTitleWithHotkey:()=>formatTitleWithHotkey,findSpatialTarget:()=>findSpatialTarget,findFocusableAncestor:()=>findFocusableAncestor,findEnclosingScope:()=>findEnclosingScope,findByTestID:()=>findByTestID,findAdjacentPane:()=>findAdjacentPane,ensureRenderAdapterInitialized:()=>ensureRenderAdapterInitialized,ensureEmojiPresentation:()=>ensureEmojiPresentation,encodeSixel:()=>encodeSixel,encodeKittyImage:()=>encodeKittyImage,enableMouse:()=>enableMouse2,enableKittyKeyboard:()=>enableKittyKeyboard2,enableInspector:()=>enableInspector,enableFocusReporting:()=>enableFocusReporting,enableBracketedPaste:()=>enableBracketedPaste,emptyKey:()=>emptyKey,easings:()=>easings,displayWidthAnsi:()=>displayWidthAnsi,displayWidth:()=>displayWidth,dispatchMouseEvent:()=>dispatchMouseEvent,dispatchKeyEvent:()=>dispatchKeyEvent,dispatchFocusEvent:()=>dispatchFocusEvent,disableMouse:()=>disableMouse2,disableKittyKeyboard:()=>disableKittyKeyboard2,disableInspector:()=>disableInspector,disableFocusReporting:()=>disableFocusReporting,disableBracketedPaste:()=>disableBracketedPaste,detectTheme:()=>detectTheme,detectTextSizingSupport:()=>detectTextSizingSupport,detectTerminalCaps:()=>detectTerminalCaps,detectKittySupport:()=>detectKittySupport,detectKittyFromStdio:()=>detectKittyFromStdio,detectColorScheme:()=>detectColorScheme,deriveTheme:()=>deriveTheme,deleteKittyImage:()=>deleteKittyImage,defaultLightTheme:()=>defaultLightTheme,defaultDarkTheme:()=>defaultDarkTheme,defaultCaps:()=>defaultCaps,cursorToRowCol:()=>cursorToRowCol,cursorMoveUp:()=>cursorMoveUp,cursorMoveDown:()=>cursorMoveDown,createYogaEngine:()=>createYogaEngine,createWidthMeasurer:()=>createWidthMeasurer,createWheelEvent:()=>createWheelEvent,createTermEditContext:()=>createTermEditContext,createTerm:()=>createTerm,createPositionRegistry:()=>createPositionRegistry,createPipeline:()=>createPipeline,createOutputPhase:()=>createOutputPhase,createMouseEventProcessor:()=>createMouseEventProcessor,createMouseEvent:()=>createMouseEvent,createMeasurer:()=>createMeasurer,createLeaf:()=>createLeaf,createKeyEvent:()=>createKeyEvent,createInputEvents:()=>createInputEvents,createFocusManager:()=>createFocusManager,createFocusEvent:()=>createFocusEvent,createFlexilyEngine:()=>createFlexilyZeroEngine,createDoubleClickState:()=>createDoubleClickState,createDOMAdapter:()=>createDOMAdapter,createCursorStore:()=>createCursorStore,createCanvasAdapter:()=>createCanvasAdapter,countVisualLines:()=>countVisualLines,copyToClipboard:()=>copyToClipboard,constrainText:()=>constrainText,connectDevTools:()=>connectDevTools,computeEnterLeave:()=>computeEnterLeave,collect:()=>collect,clampScroll:()=>clampScroll,checkDoubleClick:()=>checkDoubleClick,calcEdgeBasedScrollOffset:()=>calcEdgeBasedScrollOffset,builtinThemes:()=>builtinThemes,autoEnableInspector:()=>autoEnableInspector,applyTextOp:()=>applyTextOp,ansi16LightTheme:()=>ansi16LightTheme,ansi16DarkTheme:()=>ansi16DarkTheme,activeEditTargetRef:()=>activeEditTargetRef,activeEditContextRef:()=>activeEditContextRef,Z_INDEX:()=>Z_INDEX,YogaLayoutEngine:()=>YogaLayoutEngine,VirtualView:()=>VirtualView,VirtualTerminal:()=>VirtualTerminal,VirtualList:()=>VirtualList,UL:()=>UL,TreeView:()=>TreeView,Transform:()=>Transform,Tooltip:()=>Tooltip,Toggle:()=>Toggle,ToastItem:()=>ToastItem,ToastContainer:()=>ToastContainer,ThemeProvider:()=>ThemeProvider,TextInput:()=>TextInput,TextArea:()=>TextArea,Text:()=>Text,TermContext:()=>TermContext,Tabs:()=>Tabs,Table:()=>Table,TabPanel:()=>TabPanel,TabList:()=>TabList,Tab:()=>Tab,TERMTEST_SECTIONS:()=>TERMTEST_SECTIONS,SurfaceRegistryProvider:()=>SurfaceRegistryProvider,Strong:()=>Strong,StderrContext:()=>StderrContext,Static:()=>Static,SplitView:()=>SplitView,Spinner:()=>Spinner,Spacer:()=>Spacer,Small:()=>Small,Skeleton:()=>Skeleton,SilveryErrorBoundary:()=>SilveryErrorBoundary,SelectionProvider:()=>SelectionProvider,SelectList:()=>SelectList,SearchProvider:()=>SearchProvider,SearchBar:()=>SearchBar,ScrollbackView:()=>ScrollbackView,ScrollbackList:()=>ScrollbackList,Screen:()=>Screen,RuntimeContext:()=>RuntimeContext,ProgressBar:()=>ProgressBar,PositionRegistryProvider:()=>PositionRegistryProvider,PickerList:()=>PickerList,PickerDialog:()=>PickerDialog,PASTE_START:()=>PASTE_START,PASTE_END:()=>PASTE_END,P:()=>P,OSC133:()=>OSC133,OL:()=>OL,Newline:()=>Newline,Muted:()=>Muted,ModalDialog:()=>ModalDialog,ListView:()=>ListView,Link:()=>Link,Lead:()=>Lead,LI:()=>LI,KittyFlags:()=>KittyFlags,Kbd:()=>Kbd,InputLayerProvider:()=>InputLayerProvider,InputLayerContext:()=>InputLayerContext,InputBoundary:()=>InputBoundary,IncrementalRenderMismatchError:()=>IncrementalRenderMismatchError,Image:()=>Image,HorizontalVirtualList:()=>HorizontalVirtualList,HitRegistryContext:()=>HitRegistryContext,HitRegistry:()=>HitRegistry,HR:()=>HR,H3:()=>H3,H2:()=>H2,H1:()=>H1,GridCell:()=>GridCell,FormField:()=>FormField,Form:()=>Form,FocusManagerContext:()=>FocusManagerContext,FlexilyLayoutEngine:()=>FlexilyZeroLayoutEngine,Fill:()=>Fill,ErrorBoundary:()=>ErrorBoundary,Em:()=>Em,EditContextDisplay:()=>EditContextDisplay,Divider:()=>Divider,DecMode:()=>DecMode,DOMRenderBuffer:()=>DOMRenderBuffer,CursorProvider:()=>CursorProvider,CursorLine:()=>CursorLine,Console:()=>Console,CommandPalette:()=>CommandPalette,CodeBlock:()=>CodeBlock,Code:()=>Code,CanvasRenderBuffer:()=>CanvasRenderBuffer,Button:()=>Button,Breadcrumb:()=>Breadcrumb,Box:()=>Box,Blockquote:()=>Blockquote,Badge:()=>Badge,BEL:()=>BEL,ANSI:()=>ANSI});var init_src3=__esm(()=>{init_exports()});init_src3();init_src3();var VERSION="0.0.1";function render2(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,useSurfaceRegistryOptional,useSurfaceRegistry,useStdout,useStderr,useSelectionContext,useSelection,useSearch,useScrollbackItem,useScrollback,useScreenRectCallback,useScreenRect,useRuntime,useRenderRectCallback,useRenderRect,useReadline,usePositionRegistry,useMouseCursor,useModifierKeys,useListItem,useLatest,useInterval,useInputLayerContext,useInputLayer,useInput,useId2 as useId,useHitRegistry,useHitRegionCallback,useHitRegion,useGridPosition,useFocusable,useFocusWithin,useFocusManager,useEditContext,useDeferredValue,useCursor,useContentRectCallback,useContentRect,useConsole,useApp,useAnimation,useTransition as useAnimatedTransition,truncateText,truncateAnsi,textSized,term,swapPanes,supportsScrollRegions,subscribeCursor,stripAnsi3 as stripAnsiUnicode,stripAnsi3 as stripAnsi,splitPane,splitGraphemes,sliceByWidthRange,sliceByWidthFromEnd,sliceByWidth,shallow,setWindowTitle,setWindowAndIconTitle,setTextSizingEnabled,setTextEmojiWide,setScrollRegion2 as setScrollRegion,setRenderAdapter,setPaletteColor,setOutputCaps,setMouseCursorShape,setLayoutEngine,setForegroundColor,setCursorStyle,setCursorColor,setBackgroundColor,scrollUp2 as scrollUp,scrollDown2 as scrollDown,runWithMeasurer,runTermtest,rowColToCursor,resolveThemeColor,resolveTermDef,resolveNonTTYMode,resolveFromTerm,resolveEasing,resizeSplit,resetWindowTitle,resetScrollRegion2 as resetScrollRegion,resetMouseCursorShape,resetHitRegionIdCounter,resetForegroundColor,resetCursorStyle,resetCursorState,resetCursorColor,resetBackgroundColor,requestClipboard,reportDirectory,renderSync,renderStringSync,renderString,renderStatic,renderScreenReaderOutput,render2 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,isTermDef,isTerm,isTTY,isSixelSupported,isPrivateUseArea,isMouseSequence,isLikelyEmoji,isLayoutEngineInitialized,isKittyGraphicsSupported,isInspectorEnabled,isDevToolsConnected,isCJK,invertTextOp,inspectTree,inspectFrame,injectDOMStyles,initYogaEngine,hitTest,hasZeroWidthCharacters,hasWideCharacters,hasRenderAdapter,hasAnsi,graphemeWidth,graphemeCount,getWrappedLines,getThemeByName,getTextMeasurer,getTabOrder2 as getTabOrder,getTabOrder as getSplitTabOrder,getRenderAdapter,getPaneIds,getModifierState,getFirstCodePoint,getExplicitFocusLink,getCursorState,generateTheme,fx,formatTitleWithHotkey,findSpatialTarget,findFocusableAncestor,findEnclosingScope,findByTestID,findAdjacentPane,ensureRenderAdapterInitialized,ensureEmojiPresentation,encodeSixel,encodeKittyImage,enableMouse2 as enableMouse,enableKittyKeyboard2 as enableKittyKeyboard,enableInspector,enableFocusReporting,enableBracketedPaste,emptyKey,easings,displayWidthAnsi,displayWidth,dispatchMouseEvent,dispatchKeyEvent,dispatchFocusEvent,disableMouse2 as disableMouse,disableKittyKeyboard2 as disableKittyKeyboard,disableInspector,disableFocusReporting,disableBracketedPaste,detectTheme,detectTextSizingSupport,detectTerminalCaps,detectKittySupport,detectKittyFromStdio,detectColorScheme,deriveTheme,deleteKittyImage,defaultLightTheme,defaultDarkTheme,defaultCaps,cursorToRowCol,cursorMoveUp,cursorMoveDown,createYogaEngine,createWidthMeasurer,createWheelEvent,createTermEditContext,createTerm,createPositionRegistry,createPipeline,createOutputPhase,createMouseEventProcessor,createMouseEvent,createMeasurer,createLeaf,createKeyEvent,createInputEvents,createFocusManager,createFocusEvent,createFlexilyZeroEngine as createFlexilyEngine,createDoubleClickState,createDOMAdapter,createCursorStore,createCanvasAdapter,countVisualLines,copyToClipboard,constrainText,connectDevTools,computeEnterLeave,collect,clampScroll,checkDoubleClick,calcEdgeBasedScrollOffset,builtinThemes,autoEnableInspector,applyTextOp,ansi16LightTheme,ansi16DarkTheme,activeEditTargetRef,activeEditContextRef,Z_INDEX,YogaLayoutEngine,VirtualView,VirtualTerminal,VirtualList,VERSION,UL,TreeView,Transform,Tooltip,Toggle,ToastItem,ToastContainer,ThemeProvider,TextInput,TextArea,Text,TermContext,Tabs,Table,TabPanel,TabList,Tab,TERMTEST_SECTIONS,SurfaceRegistryProvider,Strong,StderrContext,Static,SplitView,Spinner,Spacer,Small,Skeleton,SilveryErrorBoundary,SelectionProvider,SelectList,SearchProvider,SearchBar,ScrollbackView,ScrollbackList,Screen,RuntimeContext,ProgressBar,PositionRegistryProvider,PickerList,PickerDialog,PASTE_START,PASTE_END,P,OSC133,OL,Newline,Muted,ModalDialog,ListView,Link,Lead,LI,KittyFlags,Kbd,InputLayerProvider,InputLayerContext,InputBoundary,IncrementalRenderMismatchError,Image,HorizontalVirtualList,HitRegistryContext,HitRegistry,HR,H3,H2,H1,GridCell,FormField,Form,FocusManagerContext,FlexilyZeroLayoutEngine as FlexilyLayoutEngine,Fill,ErrorBoundary,Em,EditContextDisplay,Divider,DecMode,DOMRenderBuffer,CursorProvider,CursorLine,Console,CommandPalette,CodeBlock,Code,CanvasRenderBuffer,Button,Breadcrumb,Box,Blockquote,Badge,BEL,ANSI};
339
+
340
+ //# debugId=689E352E929137B764756E2164756E21