var Ua=Object.defineProperty;var ja=(e,t,s)=>t in e?Ua(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var D=(e,t,s)=>ja(e,typeof t!="symbol"?t+"":t,s);import{e as li,Z as is,V as ve,ed as Ka,ee as rt,ef as ei,eg as qa,eh as xo,dG as ko,dH as Va,a1 as Eo,ei as Ga,ej as Ya,ek as Xa,bG as Ja,el as Za,cx as Qa,w as Ro,dF as el,bP as tl,em as sl,c9 as Bo,en as ce,bH as il,P as rl,c7 as nl,cy as xt,eo as ol,ep as al,eq as ll,dy as hl,e4 as Ur,er as vs,es as Lo,et as Mo,eu as Do,j as m,ay as To,aH as $o,aA as jr,az as Ao,B as cl,r as U,d as fi,m as $s,ev as Kr,ew as qr,d0 as dl,ex as ul,c as ti,ey as _l,ez as fl,aa as pl,eA as ml,eB as gl,eC as vl}from"./index-C4inJ1rU.js";import{g as Sl}from"./transport-CW_z2teL.js";import{r as yl}from"./system-Yjyk7rn7.js";import{P as wl,B as bl,C as Cl}from"./PageLayout-CdGXajgM.js";import{K as Po,S as xl}from"./KeycapButton-DSV3CIRm.js";import{S as Vr}from"./search-qUivGgU1.js";import{C as kl}from"./chevron-right-CU8UihKL.js";import"./keycap-sfx-ByZp-njj.js";/**
 * @license lucide-react v0.559.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const El=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M16 12h2",key:"7q9ll5"}],["path",{d:"M16 8h2",key:"msurwy"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}],["path",{d:"M6 12h2",key:"32wvfc"}],["path",{d:"M6 8h2",key:"30oboj"}]],No=li("book-open-text",El);/**
 * @license lucide-react v0.559.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Rl=[["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}],["path",{d:"m9 10-5 5 5 5",key:"1kshq7"}]],Bl=li("corner-down-left",Rl);/**
 * @license lucide-react v0.559.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ll=[["path",{d:"M20 5a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h2.5a1.5 1.5 0 0 1 1.2.6l.6.8a1.5 1.5 0 0 0 1.2.6z",key:"a4852j"}],["path",{d:"M3 8.268a2 2 0 0 0-1 1.738V19a2 2 0 0 0 2 2h11a2 2 0 0 0 1.732-1",key:"yxbcw3"}]],Ml=li("folders",Ll);/**
 * @license lucide-react v0.559.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Dl=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],Tl=li("package",Dl);/**
 * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
 * @license MIT
 *
 * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
 * @license MIT
 *
 * Originally forked from (with the author's permission):
 *   Fabrice Bellard's javascript vt100 for jslinux:
 *   http://bellard.org/jslinux/
 *   Copyright (c) 2011 Fabrice Bellard
 */var Io=Object.defineProperty,$l=Object.getOwnPropertyDescriptor,Al=(e,t)=>{for(var s in t)Io(e,s,{get:t[s],enumerable:!0})},pe=(e,t,s,i)=>{for(var r=i>1?void 0:i?$l(t,s):t,n=e.length-1,o;n>=0;n--)(o=e[n])&&(r=(i?o(t,s,r):o(r))||r);return i&&r&&Io(t,s,r),r},$=(e,t)=>(s,i)=>t(s,i,e),Gr="Terminal input",Oi={get:()=>Gr,set:e=>Gr=e},Yr="Too much output to announce, navigate to rows manually to read",Hi={get:()=>Yr,set:e=>Yr=e};function Pl(e){return e.replace(/\r?\n/g,"\r")}function Nl(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function Il(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function Ol(e,t,s,i){if(e.stopPropagation(),e.clipboardData){let r=e.clipboardData.getData("text/plain");Oo(r,t,s,i)}}function Oo(e,t,s,i){e=Pl(e),e=Nl(e,s.decPrivateModes.bracketedPasteMode&&i.rawOptions.ignoreBracketedPasteMode!==!0),s.triggerDataEvent(e,!0),t.value=""}function Ho(e,t,s){let i=s.getBoundingClientRect(),r=e.clientX-i.left-10,n=e.clientY-i.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${r}px`,t.style.top=`${n}px`,t.style.zIndex="1000",t.focus()}function Xr(e,t,s,i,r){Ho(e,t,s),r&&i.rightClickSelect(e),t.value=i.selectionText,t.select()}function Ct(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function hi(e,t=0,s=e.length){let i="";for(let r=t;r<s;++r){let n=e[r];n>65535?(n-=65536,i+=String.fromCharCode((n>>10)+55296)+String.fromCharCode(n%1024+56320)):i+=String.fromCharCode(n)}return i}var Hl=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let s=e.length;if(!s)return 0;let i=0,r=0;if(this._interim){let n=e.charCodeAt(r++);56320<=n&&n<=57343?t[i++]=(this._interim-55296)*1024+n-56320+65536:(t[i++]=this._interim,t[i++]=n),this._interim=0}for(let n=r;n<s;++n){let o=e.charCodeAt(n);if(55296<=o&&o<=56319){if(++n>=s)return this._interim=o,i;let a=e.charCodeAt(n);56320<=a&&a<=57343?t[i++]=(o-55296)*1024+a-56320+65536:(t[i++]=o,t[i++]=a);continue}o!==65279&&(t[i++]=o)}return i}},Fl=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let s=e.length;if(!s)return 0;let i=0,r,n,o,a,h=0,l=0;if(this.interim[0]){let u=!1,f=this.interim[0];f&=(f&224)===192?31:(f&240)===224?15:7;let _=0,p;for(;(p=this.interim[++_]&63)&&_<4;)f<<=6,f|=p;let g=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,k=g-_;for(;l<k;){if(l>=s)return 0;if(p=e[l++],(p&192)!==128){l--,u=!0;break}else this.interim[_++]=p,f<<=6,f|=p&63}u||(g===2?f<128?l--:t[i++]=f:g===3?f<2048||f>=55296&&f<=57343||f===65279||(t[i++]=f):f<65536||f>1114111||(t[i++]=f)),this.interim.fill(0)}let c=s-4,d=l;for(;d<s;){for(;d<c&&!((r=e[d])&128)&&!((n=e[d+1])&128)&&!((o=e[d+2])&128)&&!((a=e[d+3])&128);)t[i++]=r,t[i++]=n,t[i++]=o,t[i++]=a,d+=4;if(r=e[d++],r<128)t[i++]=r;else if((r&224)===192){if(d>=s)return this.interim[0]=r,i;if(n=e[d++],(n&192)!==128){d--;continue}if(h=(r&31)<<6|n&63,h<128){d--;continue}t[i++]=h}else if((r&240)===224){if(d>=s)return this.interim[0]=r,i;if(n=e[d++],(n&192)!==128){d--;continue}if(d>=s)return this.interim[0]=r,this.interim[1]=n,i;if(o=e[d++],(o&192)!==128){d--;continue}if(h=(r&15)<<12|(n&63)<<6|o&63,h<2048||h>=55296&&h<=57343||h===65279)continue;t[i++]=h}else if((r&248)===240){if(d>=s)return this.interim[0]=r,i;if(n=e[d++],(n&192)!==128){d--;continue}if(d>=s)return this.interim[0]=r,this.interim[1]=n,i;if(o=e[d++],(o&192)!==128){d--;continue}if(d>=s)return this.interim[0]=r,this.interim[1]=n,this.interim[2]=o,i;if(a=e[d++],(a&192)!==128){d--;continue}if(h=(r&7)<<18|(n&63)<<12|(o&63)<<6|a&63,h<65536||h>1114111)continue;t[i++]=h}}return i}},Fo="",kt=" ",xs=class Wo{constructor(){this.fg=0,this.bg=0,this.extended=new si}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new Wo;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},si=class zo{constructor(t=0,s=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=s}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new zo(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Ze=class Uo extends xs{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new si,this.combinedData=""}static fromCharData(t){let s=new Uo;return s.setFromCharData(t),s}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Ct(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let s=!1;if(t[1].length>2)s=!0;else if(t[1].length===2){let i=t[1].charCodeAt(0);if(55296<=i&&i<=56319){let r=t[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(i-55296)*1024+r-56320+65536|t[2]<<22:s=!0}else s=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;s&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Jr="di$target",Fi="di$dependencies",pi=new Map;function Wl(e){return e[Fi]||[]}function Me(e){if(pi.has(e))return pi.get(e);let t=function(s,i,r){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");zl(t,s,r)};return t._id=e,pi.set(e,t),t}function zl(e,t,s){t[Jr]===t?t[Fi].push({id:e,index:s}):(t[Fi]=[{id:e,index:s}],t[Jr]=t)}var He=Me("BufferService"),jo=Me("CoreMouseService"),Ht=Me("CoreService"),Ul=Me("CharsetService"),Rr=Me("InstantiationService"),Ko=Me("LogService"),Fe=Me("OptionsService"),qo=Me("OscLinkService"),jl=Me("UnicodeService"),ks=Me("DecorationService"),Wi=class{constructor(e,t,s){this._bufferService=e,this._optionsService=t,this._oscLinkService=s}provideLinks(e,t){var c;let s=this._bufferService.buffer.lines.get(e-1);if(!s){t(void 0);return}let i=[],r=this._optionsService.rawOptions.linkHandler,n=new Ze,o=s.getTrimmedLength(),a=-1,h=-1,l=!1;for(let d=0;d<o;d++)if(!(h===-1&&!s.hasContent(d))){if(s.loadCell(d,n),n.hasExtendedAttrs()&&n.extended.urlId)if(h===-1){h=d,a=n.extended.urlId;continue}else l=n.extended.urlId!==a;else h!==-1&&(l=!0);if(l||h!==-1&&d===o-1){let u=(c=this._oscLinkService.getLinkData(a))==null?void 0:c.uri;if(u){let f={start:{x:h+1,y:e},end:{x:d+(!l&&d===o-1?1:0),y:e}},_=!1;if(!(r!=null&&r.allowNonHttpProtocols))try{let p=new URL(u);["http:","https:"].includes(p.protocol)||(_=!0)}catch{_=!0}_||i.push({text:u,range:f,activate:(p,g)=>r?r.activate(p,g,f):Kl(p,g),hover:(p,g)=>{var k;return(k=r==null?void 0:r.hover)==null?void 0:k.call(r,p,g,f)},leave:(p,g)=>{var k;return(k=r==null?void 0:r.leave)==null?void 0:k.call(r,p,g,f)}})}l=!1,n.hasExtendedAttrs()&&n.extended.urlId?(h=d,a=n.extended.urlId):(h=-1,a=-1)}}t(i)}};Wi=pe([$(0,He),$(1,Fe),$(2,qo)],Wi);function Kl(e,t){if(confirm(`Do you want to navigate to ${t}?

WARNING: This link could potentially be dangerous`)){let s=window.open();if(s){try{s.opener=null}catch{}s.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var ci=Me("CharSizeService"),pt=Me("CoreBrowserService"),Br=Me("MouseService"),mt=Me("RenderService"),ql=Me("SelectionService"),Vo=Me("CharacterJoinerService"),es=Me("ThemeService"),Go=Me("LinkProviderService"),Vl=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?Zr.isErrorNoTelemetry(e)?new Zr(e.message+`

`+e.stack):new Error(e.message+`

`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},Gl=new Vl;function zs(e){Yl(e)||Gl.onUnexpectedError(e)}var zi="Canceled";function Yl(e){return e instanceof Xl?!0:e instanceof Error&&e.name===zi&&e.message===zi}var Xl=class extends Error{constructor(){super(zi),this.name=this.message}};function Jl(e){return new Error(`Illegal argument: ${e}`)}var Zr=class Ui extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Ui)return t;let s=new Ui;return s.message=t.message,s.stack=t.stack,s}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},ji=class Yo extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,Yo.prototype)}};function Ke(e,t=0){return e[e.length-(1+t)]}var Zl;(e=>{function t(n){return n<0}e.isLessThan=t;function s(n){return n<=0}e.isLessThanOrEqual=s;function i(n){return n>0}e.isGreaterThan=i;function r(n){return n===0}e.isNeitherLessOrGreaterThan=r,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(Zl||(Zl={}));function Ql(e,t){let s=this,i=!1,r;return function(){return i||(i=!0,t||(r=e.apply(s,arguments))),r}}var Xo;(e=>{function t(T){return T&&typeof T=="object"&&typeof T[Symbol.iterator]=="function"}e.is=t;let s=Object.freeze([]);function i(){return s}e.empty=i;function*r(T){yield T}e.single=r;function n(T){return t(T)?T:r(T)}e.wrap=n;function o(T){return T||s}e.from=o;function*a(T){for(let N=T.length-1;N>=0;N--)yield T[N]}e.reverse=a;function h(T){return!T||T[Symbol.iterator]().next().done===!0}e.isEmpty=h;function l(T){return T[Symbol.iterator]().next().value}e.first=l;function c(T,N){let F=0;for(let Z of T)if(N(Z,F++))return!0;return!1}e.some=c;function d(T,N){for(let F of T)if(N(F))return F}e.find=d;function*u(T,N){for(let F of T)N(F)&&(yield F)}e.filter=u;function*f(T,N){let F=0;for(let Z of T)yield N(Z,F++)}e.map=f;function*_(T,N){let F=0;for(let Z of T)yield*N(Z,F++)}e.flatMap=_;function*p(...T){for(let N of T)yield*N}e.concat=p;function g(T,N,F){let Z=F;for(let me of T)Z=N(Z,me);return Z}e.reduce=g;function*k(T,N,F=T.length){for(N<0&&(N+=T.length),F<0?F+=T.length:F>T.length&&(F=T.length);N<F;N++)yield T[N]}e.slice=k;function q(T,N=Number.POSITIVE_INFINITY){let F=[];if(N===0)return[F,T];let Z=T[Symbol.iterator]();for(let me=0;me<N;me++){let X=Z.next();if(X.done)return[F,e.empty()];F.push(X.value)}return[F,{[Symbol.iterator](){return Z}}]}e.consume=q;async function H(T){let N=[];for await(let F of T)N.push(F);return Promise.resolve(N)}e.asyncToArray=H})(Xo||(Xo={}));function It(e){if(Xo.is(e)){let t=[];for(let s of e)if(s)try{s.dispose()}catch(i){t.push(i)}if(t.length===1)throw t[0];if(t.length>1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function eh(...e){return ae(()=>It(e))}function ae(e){return{dispose:Ql(()=>{e()})}}var Jo=class Zo{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{It(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?Zo.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),void 0)}};Jo.DISABLE_DISPOSED_WARNING=!1;var Et=Jo,Y=class{constructor(){this._store=new Et,this._store}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};Y.None=Object.freeze({dispose(){}});var Zt=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,(e=this._value)==null||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},ft=typeof window=="object"?window:globalThis,Ki=class qi{constructor(t){this.element=t,this.next=qi.Undefined,this.prev=qi.Undefined}};Ki.Undefined=new Ki(void 0);var le=Ki,Qr=class{constructor(){this._first=le.Undefined,this._last=le.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===le.Undefined}clear(){let e=this._first;for(;e!==le.Undefined;){let t=e.next;e.prev=le.Undefined,e.next=le.Undefined,e=t}this._first=le.Undefined,this._last=le.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let s=new le(e);if(this._first===le.Undefined)this._first=s,this._last=s;else if(t){let r=this._last;this._last=s,s.prev=r,r.next=s}else{let r=this._first;this._first=s,s.next=r,r.prev=s}this._size+=1;let i=!1;return()=>{i||(i=!0,this._remove(s))}}shift(){if(this._first!==le.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==le.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==le.Undefined&&e.next!==le.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===le.Undefined&&e.next===le.Undefined?(this._first=le.Undefined,this._last=le.Undefined):e.next===le.Undefined?(this._last=this._last.prev,this._last.next=le.Undefined):e.prev===le.Undefined&&(this._first=this._first.next,this._first.prev=le.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==le.Undefined;)yield e.element,e=e.next}},th=globalThis.performance&&typeof globalThis.performance.now=="function",sh=class Qo{static create(t){return new Qo(t)}constructor(t){this._now=th&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},Te;(e=>{e.None=()=>Y.None;function t(P,S){return d(P,()=>{},0,void 0,!0,void 0,S)}e.defer=t;function s(P){return(S,L=null,C)=>{let M=!1,I;return I=P(R=>{if(!M)return I?I.dispose():M=!0,S.call(L,R)},null,C),M&&I.dispose(),I}}e.once=s;function i(P,S,L){return l((C,M=null,I)=>P(R=>C.call(M,S(R)),null,I),L)}e.map=i;function r(P,S,L){return l((C,M=null,I)=>P(R=>{S(R),C.call(M,R)},null,I),L)}e.forEach=r;function n(P,S,L){return l((C,M=null,I)=>P(R=>S(R)&&C.call(M,R),null,I),L)}e.filter=n;function o(P){return P}e.signal=o;function a(...P){return(S,L=null,C)=>{let M=eh(...P.map(I=>I(R=>S.call(L,R))));return c(M,C)}}e.any=a;function h(P,S,L,C){let M=L;return i(P,I=>(M=S(M,I),M),C)}e.reduce=h;function l(P,S){let L,C={onWillAddFirstListener(){L=P(M.fire,M)},onDidRemoveLastListener(){L==null||L.dispose()}},M=new x(C);return S==null||S.add(M),M.event}function c(P,S){return S instanceof Array?S.push(P):S&&S.add(P),P}function d(P,S,L=100,C=!1,M=!1,I,R){let V,ee,Se,$e=0,Ne,re={leakWarningThreshold:I,onWillAddFirstListener(){V=P(We=>{$e++,ee=S(ee,We),C&&!Se&&(Ge.fire(ee),ee=void 0),Ne=()=>{let ut=ee;ee=void 0,Se=void 0,(!C||$e>1)&&Ge.fire(ut),$e=0},typeof L=="number"?(clearTimeout(Se),Se=setTimeout(Ne,L)):Se===void 0&&(Se=0,queueMicrotask(Ne))})},onWillRemoveListener(){M&&$e>0&&(Ne==null||Ne())},onDidRemoveLastListener(){Ne=void 0,V.dispose()}},Ge=new x(re);return R==null||R.add(Ge),Ge.event}e.debounce=d;function u(P,S=0,L){return e.debounce(P,(C,M)=>C?(C.push(M),C):[M],S,void 0,!0,void 0,L)}e.accumulate=u;function f(P,S=(C,M)=>C===M,L){let C=!0,M;return n(P,I=>{let R=C||!S(I,M);return C=!1,M=I,R},L)}e.latch=f;function _(P,S,L){return[e.filter(P,S,L),e.filter(P,C=>!S(C),L)]}e.split=_;function p(P,S=!1,L=[],C){let M=L.slice(),I=P(ee=>{M?M.push(ee):V.fire(ee)});C&&C.add(I);let R=()=>{M==null||M.forEach(ee=>V.fire(ee)),M=null},V=new x({onWillAddFirstListener(){I||(I=P(ee=>V.fire(ee)),C&&C.add(I))},onDidAddFirstListener(){M&&(S?setTimeout(R):R())},onDidRemoveLastListener(){I&&I.dispose(),I=null}});return C&&C.add(V),V.event}e.buffer=p;function g(P,S){return(L,C,M)=>{let I=S(new q);return P(function(R){let V=I.evaluate(R);V!==k&&L.call(C,V)},void 0,M)}}e.chain=g;let k=Symbol("HaltChainable");class q{constructor(){this.steps=[]}map(S){return this.steps.push(S),this}forEach(S){return this.steps.push(L=>(S(L),L)),this}filter(S){return this.steps.push(L=>S(L)?L:k),this}reduce(S,L){let C=L;return this.steps.push(M=>(C=S(C,M),C)),this}latch(S=(L,C)=>L===C){let L=!0,C;return this.steps.push(M=>{let I=L||!S(M,C);return L=!1,C=M,I?M:k}),this}evaluate(S){for(let L of this.steps)if(S=L(S),S===k)break;return S}}function H(P,S,L=C=>C){let C=(...V)=>R.fire(L(...V)),M=()=>P.on(S,C),I=()=>P.removeListener(S,C),R=new x({onWillAddFirstListener:M,onDidRemoveLastListener:I});return R.event}e.fromNodeEventEmitter=H;function T(P,S,L=C=>C){let C=(...V)=>R.fire(L(...V)),M=()=>P.addEventListener(S,C),I=()=>P.removeEventListener(S,C),R=new x({onWillAddFirstListener:M,onDidRemoveLastListener:I});return R.event}e.fromDOMEventEmitter=T;function N(P){return new Promise(S=>s(P)(S))}e.toPromise=N;function F(P){let S=new x;return P.then(L=>{S.fire(L)},()=>{S.fire(void 0)}).finally(()=>{S.dispose()}),S.event}e.fromPromise=F;function Z(P,S){return P(L=>S.fire(L))}e.forward=Z;function me(P,S,L){return S(L),P(C=>S(C))}e.runAndSubscribe=me;class X{constructor(S,L){this._observable=S,this._counter=0,this._hasChanged=!1;let C={onWillAddFirstListener:()=>{S.addObserver(this)},onDidRemoveLastListener:()=>{S.removeObserver(this)}};this.emitter=new x(C),L&&L.add(this.emitter)}beginUpdate(S){this._counter++}handlePossibleChange(S){}handleChange(S,L){this._hasChanged=!0}endUpdate(S){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function oe(P,S){return new X(P,S).emitter.event}e.fromObservable=oe;function J(P){return(S,L,C)=>{let M=0,I=!1,R={beginUpdate(){M++},endUpdate(){M--,M===0&&(P.reportChanges(),I&&(I=!1,S.call(L)))},handlePossibleChange(){},handleChange(){I=!0}};P.addObserver(R),P.reportChanges();let V={dispose(){P.removeObserver(R)}};return C instanceof Et?C.add(V):Array.isArray(C)&&C.push(V),V}}e.fromObservableLight=J})(Te||(Te={}));var Vi=class Gi{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Gi._idPool++}`,Gi.all.add(this)}start(t){this._stopWatch=new sh,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Vi.all=new Set,Vi._idPool=0;var ih=Vi,rh=-1,ea=class ta{constructor(t,s,i=(ta._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=s,this.name=i,this._warnCountdown=0}dispose(){var t;(t=this._stacks)==null||t.clear()}check(t,s){let i=this.threshold;if(i<=0||s<i)return;this._stacks||(this._stacks=new Map);let r=this._stacks.get(t.value)||0;if(this._stacks.set(t.value,r+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=i*.5;let[n,o]=this.getMostFrequentStack(),a=`[${this.name}] potential listener LEAK detected, having ${s} listeners already. MOST frequent listener (${o}):`;console.warn(a),console.warn(n);let h=new ah(a,n);this._errorHandler(h)}return()=>{let n=this._stacks.get(t.value)||0;this._stacks.set(t.value,n-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,s=0;for(let[i,r]of this._stacks)(!t||s<r)&&(t=[i,r],s=r);return t}};ea._idPool=1;var nh=ea,oh=class sa{constructor(t){this.value=t}static create(){let t=new Error;return new sa(t.stack??"")}print(){console.warn(this.value.split(`
`).slice(2).join(`
`))}},ah=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},lh=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},hh=0,mi=class{constructor(e){this.value=e,this.id=hh++}},ch=2,dh,x=class{constructor(t){var s,i,r,n;this._size=0,this._options=t,this._leakageMon=(s=this._options)!=null&&s.leakWarningThreshold?new nh((t==null?void 0:t.onListenerError)??zs,((i=this._options)==null?void 0:i.leakWarningThreshold)??rh):void 0,this._perfMon=(r=this._options)!=null&&r._profName?new ih(this._options._profName):void 0,this._deliveryQueue=(n=this._options)==null?void 0:n.deliveryQueue}dispose(){var t,s,i,r;this._disposed||(this._disposed=!0,((t=this._deliveryQueue)==null?void 0:t.current)===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),(i=(s=this._options)==null?void 0:s.onDidRemoveLastListener)==null||i.call(s),(r=this._leakageMon)==null||r.dispose())}get event(){return this._event??(this._event=(t,s,i)=>{var a,h,l,c,d;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let u=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(u);let f=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],_=new lh(`${u}. HINT: Stack shows most frequent listener (${f[1]}-times)`,f[0]);return(((a=this._options)==null?void 0:a.onListenerError)||zs)(_),Y.None}if(this._disposed)return Y.None;s&&(t=t.bind(s));let r=new mi(t),n;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=oh.create(),n=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof mi?(this._deliveryQueue??(this._deliveryQueue=new uh),this._listeners=[this._listeners,r]):this._listeners.push(r):((l=(h=this._options)==null?void 0:h.onWillAddFirstListener)==null||l.call(h,this),this._listeners=r,(d=(c=this._options)==null?void 0:c.onDidAddFirstListener)==null||d.call(c,this)),this._size++;let o=ae(()=>{n==null||n(),this._removeListener(r)});return i instanceof Et?i.add(o):Array.isArray(i)&&i.push(o),o}),this._event}_removeListener(t){var n,o,a,h;if((o=(n=this._options)==null?void 0:n.onWillRemoveListener)==null||o.call(n,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(h=(a=this._options)==null?void 0:a.onDidRemoveLastListener)==null||h.call(a,this),this._size=0;return}let s=this._listeners,i=s.indexOf(t);if(i===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,s[i]=void 0;let r=this._deliveryQueue.current===this;if(this._size*ch<=s.length){let l=0;for(let c=0;c<s.length;c++)s[c]?s[l++]=s[c]:r&&(this._deliveryQueue.end--,l<this._deliveryQueue.i&&this._deliveryQueue.i--);s.length=l}}_deliver(t,s){var r;if(!t)return;let i=((r=this._options)==null?void 0:r.onListenerError)||zs;if(!i){t.value(s);return}try{t.value(s)}catch(n){i(n)}}_deliverQueue(t){let s=t.current._listeners;for(;t.i<t.end;)this._deliver(s[t.i++],t.value);t.reset()}fire(t){var s,i,r,n;if((s=this._deliveryQueue)!=null&&s.current&&(this._deliverQueue(this._deliveryQueue),(i=this._perfMon)==null||i.stop()),(r=this._perfMon)==null||r.start(this._size),this._listeners)if(this._listeners instanceof mi)this._deliver(this._listeners,t);else{let o=this._deliveryQueue;o.enqueue(this,t,this._listeners.length),this._deliverQueue(o)}(n=this._perfMon)==null||n.stop()}hasListeners(){return this._size>0}},uh=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,s){this.i=0,this.end=s,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Yi=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new x,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new x,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,s){if(this.getZoomLevel(s)===t)return;let i=this.getWindowId(s);this.mapWindowIdToZoomLevel.set(i,t),this._onDidChangeZoomLevel.fire(i)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,s){this.mapWindowIdToZoomFactor.set(this.getWindowId(s),t)}setFullscreen(t,s){if(this.isFullscreen(s)===t)return;let i=this.getWindowId(s);this.mapWindowIdToFullScreen.set(i,t),this._onDidChangeFullscreen.fire(i)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};Yi.INSTANCE=new Yi;var Lr=Yi;function _h(e,t,s){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",s)}Lr.INSTANCE.onDidChangeZoomLevel;function fh(e){return Lr.INSTANCE.getZoomFactor(e)}Lr.INSTANCE.onDidChangeFullscreen;var ts=typeof navigator=="object"?navigator.userAgent:"",Xi=ts.indexOf("Firefox")>=0,ph=ts.indexOf("AppleWebKit")>=0,Mr=ts.indexOf("Chrome")>=0,mh=!Mr&&ts.indexOf("Safari")>=0;ts.indexOf("Electron/")>=0;ts.indexOf("Android")>=0;var gi=!1;if(typeof ft.matchMedia=="function"){let e=ft.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=ft.matchMedia("(display-mode: fullscreen)");gi=e.matches,_h(ft,e,({matches:s})=>{gi&&t.matches||(gi=s)})}var Gt="en",Ji=!1,Zi=!1,Us=!1,ia=!1,As,js=Gt,en=Gt,gh,tt,Nt=globalThis,De,wo;typeof Nt.vscode<"u"&&typeof Nt.vscode.process<"u"?De=Nt.vscode.process:typeof process<"u"&&typeof((wo=process==null?void 0:process.versions)==null?void 0:wo.node)=="string"&&(De=process);var bo,vh=typeof((bo=De==null?void 0:De.versions)==null?void 0:bo.electron)=="string",Sh=vh&&(De==null?void 0:De.type)==="renderer",Co;if(typeof De=="object"){Ji=De.platform==="win32",Zi=De.platform==="darwin",Us=De.platform==="linux",Us&&De.env.SNAP&&De.env.SNAP_REVISION,De.env.CI||De.env.BUILD_ARTIFACTSTAGINGDIRECTORY,As=Gt,js=Gt;let e=De.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);As=t.userLocale,en=t.osLocale,js=t.resolvedLanguage||Gt,gh=(Co=t.languagePack)==null?void 0:Co.translationsConfigFile}catch{}ia=!0}else typeof navigator=="object"&&!Sh?(tt=navigator.userAgent,Ji=tt.indexOf("Windows")>=0,Zi=tt.indexOf("Macintosh")>=0,(tt.indexOf("Macintosh")>=0||tt.indexOf("iPad")>=0||tt.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,Us=tt.indexOf("Linux")>=0,(tt==null?void 0:tt.indexOf("Mobi"))>=0,js=globalThis._VSCODE_NLS_LANGUAGE||Gt,As=navigator.language.toLowerCase(),en=As):console.error("Unable to resolve platform.");var ra=Ji,ct=Zi,yh=Us,tn=ia,dt=tt,vt=js,wh;(e=>{function t(){return vt}e.value=t;function s(){return vt.length===2?vt==="en":vt.length>=3?vt[0]==="e"&&vt[1]==="n"&&vt[2]==="-":!1}e.isDefaultVariant=s;function i(){return vt==="en"}e.isDefault=i})(wh||(wh={}));var bh=typeof Nt.postMessage=="function"&&!Nt.importScripts;(()=>{if(bh){let e=[];Nt.addEventListener("message",s=>{if(s.data&&s.data.vscodeScheduleAsyncWork)for(let i=0,r=e.length;i<r;i++){let n=e[i];if(n.id===s.data.vscodeScheduleAsyncWork){e.splice(i,1),n.callback();return}}});let t=0;return s=>{let i=++t;e.push({id:i,callback:s}),Nt.postMessage({vscodeScheduleAsyncWork:i},"*")}}return e=>setTimeout(e)})();var Ch=!!(dt&&dt.indexOf("Chrome")>=0);dt&&dt.indexOf("Firefox")>=0;!Ch&&dt&&dt.indexOf("Safari")>=0;dt&&dt.indexOf("Edg/")>=0;dt&&dt.indexOf("Android")>=0;var Ut=typeof navigator=="object"?navigator:{};tn||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ut&&Ut.clipboard&&Ut.clipboard.writeText,tn||Ut&&Ut.clipboard&&Ut.clipboard.readText;var Dr=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},vi=new Dr,sn=new Dr,rn=new Dr,xh=new Array(230),na;(e=>{function t(a){return vi.keyCodeToStr(a)}e.toString=t;function s(a){return vi.strToKeyCode(a)}e.fromString=s;function i(a){return sn.keyCodeToStr(a)}e.toUserSettingsUS=i;function r(a){return rn.keyCodeToStr(a)}e.toUserSettingsGeneral=r;function n(a){return sn.strToKeyCode(a)||rn.strToKeyCode(a)}e.fromUserSettings=n;function o(a){if(a>=98&&a<=113)return null;switch(a){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return vi.keyCodeToStr(a)}e.toElectronAccelerator=o})(na||(na={}));var kh=class oa{constructor(t,s,i,r,n){this.ctrlKey=t,this.shiftKey=s,this.altKey=i,this.metaKey=r,this.keyCode=n}equals(t){return t instanceof oa&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",s=this.shiftKey?"1":"0",i=this.altKey?"1":"0",r=this.metaKey?"1":"0";return`K${t}${s}${i}${r}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new Eh([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Eh=class{constructor(e){if(e.length===0)throw Jl("chords");this.chords=e}getHashCode(){let e="";for(let t=0,s=this.chords.length;t<s;t++)t!==0&&(e+=";"),e+=this.chords[t].getHashCode();return e}equals(e){if(e===null||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};function Rh(e){if(e.charCode){let s=String.fromCharCode(e.charCode).toUpperCase();return na.fromString(s)}let t=e.keyCode;if(t===3)return 7;if(Xi)switch(t){case 59:return 85;case 60:if(yh)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(ct)return 57;break}else if(ph&&(ct&&t===93||!ct&&t===92))return 57;return xh[t]||0}var Bh=ct?256:2048,Lh=512,Mh=1024,Dh=ct?2048:256,nn=class{constructor(e){var s;this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=(s=t.getModifierState)==null?void 0:s.call(t,"AltGraph"),this.keyCode=Rh(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===5,this.altKey=this.altKey||this.keyCode===6,this.shiftKey=this.shiftKey||this.keyCode===4,this.metaKey=this.metaKey||this.keyCode===57,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=Bh),this.altKey&&(t|=Lh),this.shiftKey&&(t|=Mh),this.metaKey&&(t|=Dh),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new kh(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},on=new WeakMap;function Th(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,s=e.parent.location;if(t.origin!=="null"&&s.origin!=="null"&&t.origin!==s.origin)return null}catch{return null}return e.parent}var $h=class{static getSameOriginWindowChain(e){let t=on.get(e);if(!t){t=[],on.set(e,t);let s=e,i;do i=Th(s),i?t.push({window:new WeakRef(s),iframeElement:s.frameElement||null}):t.push({window:new WeakRef(s),iframeElement:null}),s=i;while(s)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let s=0,i=0,r=this.getSameOriginWindowChain(e);for(let n of r){let o=n.window.deref();if(s+=(o==null?void 0:o.scrollY)??0,i+=(o==null?void 0:o.scrollX)??0,o===t||!n.iframeElement)break;let a=n.iframeElement.getBoundingClientRect();s+=a.top,i+=a.left}return{top:s,left:i}}},Ps=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type==="dblclick"&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX=="number"?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let s=$h.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=s.left,this.posy-=s.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},an=class{constructor(e,t=0,s=0){var r;this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=s,this.deltaX=t;let i=!1;if(Mr){let n=navigator.userAgent.match(/Chrome\/(\d+)/);i=(n?parseInt(n[1]):123)<=122}if(e){let n=e,o=e,a=((r=e.view)==null?void 0:r.devicePixelRatio)||1;if(typeof n.wheelDeltaY<"u")i?this.deltaY=n.wheelDeltaY/(120*a):this.deltaY=n.wheelDeltaY/120;else if(typeof o.VERTICAL_AXIS<"u"&&o.axis===o.VERTICAL_AXIS)this.deltaY=-o.detail/3;else if(e.type==="wheel"){let h=e;h.deltaMode===h.DOM_DELTA_LINE?Xi&&!ct?this.deltaY=-e.deltaY/3:this.deltaY=-e.deltaY:this.deltaY=-e.deltaY/40}if(typeof n.wheelDeltaX<"u")mh&&ra?this.deltaX=-(n.wheelDeltaX/120):i?this.deltaX=n.wheelDeltaX/(120*a):this.deltaX=n.wheelDeltaX/120;else if(typeof o.HORIZONTAL_AXIS<"u"&&o.axis===o.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type==="wheel"){let h=e;h.deltaMode===h.DOM_DELTA_LINE?Xi&&!ct?this.deltaX=-e.deltaX/3:this.deltaX=-e.deltaX:this.deltaX=-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(i?this.deltaY=e.wheelDelta/(120*a):this.deltaY=e.wheelDelta/120)}}preventDefault(){var e;(e=this.browserEvent)==null||e.preventDefault()}stopPropagation(){var e;(e=this.browserEvent)==null||e.stopPropagation()}},aa=Object.freeze(function(e,t){let s=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(s)}}}),Ah;(e=>{function t(s){return s===e.None||s===e.Cancelled||s instanceof Ph?!0:!s||typeof s!="object"?!1:typeof s.isCancellationRequested=="boolean"&&typeof s.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Te.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:aa})})(Ah||(Ah={}));var Ph=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?aa:(this._emitter||(this._emitter=new x),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Tr=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new ji("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new ji("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},Nh=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){var e;(e=this.disposable)==null||e.dispose(),this.disposable=void 0}cancelAndSet(e,t,s=globalThis){if(this.isDisposed)throw new ji("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let i=s.setInterval(()=>{e()},t);this.disposable=ae(()=>{s.clearInterval(i),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Ih;(e=>{async function t(i){let r,n=await Promise.all(i.map(o=>o.then(a=>a,a=>{r||(r=a)})));if(typeof r<"u")throw r;return n}e.settled=t;function s(i){return new Promise(async(r,n)=>{try{await i(r,n)}catch(o){n(o)}})}e.withAsyncBody=s})(Ih||(Ih={}));var ln=class Xe{static fromArray(t){return new Xe(s=>{s.emitMany(t)})}static fromPromise(t){return new Xe(async s=>{s.emitMany(await t)})}static fromPromises(t){return new Xe(async s=>{await Promise.all(t.map(async i=>s.emitOne(await i)))})}static merge(t){return new Xe(async s=>{await Promise.all(t.map(async i=>{for await(let r of i)s.emitOne(r)}))})}constructor(t,s){this._state=0,this._results=[],this._error=null,this._onReturn=s,this._onStateChanged=new x,queueMicrotask(async()=>{let i={emitOne:r=>this.emitOne(r),emitMany:r=>this.emitMany(r),reject:r=>this.reject(r)};try{await Promise.resolve(t(i)),this.resolve()}catch(r){this.reject(r)}finally{i.emitOne=void 0,i.emitMany=void 0,i.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t<this._results.length)return{done:!1,value:this._results[t++]};if(this._state===1)return{done:!0,value:void 0};await Te.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>{var s;return(s=this._onReturn)==null||s.call(this),{done:!0,value:void 0}}}}static map(t,s){return new Xe(async i=>{for await(let r of t)i.emitOne(s(r))})}map(t){return Xe.map(this,t)}static filter(t,s){return new Xe(async i=>{for await(let r of t)s(r)&&i.emitOne(r)})}filter(t){return Xe.filter(this,t)}static coalesce(t){return Xe.filter(t,s=>!!s)}coalesce(){return Xe.coalesce(this)}static async toPromise(t){let s=[];for await(let i of t)s.push(i);return s}toPromise(){return Xe.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};ln.EMPTY=ln.fromArray([]);var{getWindow:ht,getWindowId:Oh,onDidRegisterWindow:Hh}=(function(){let e=new Map,t={window:ft,disposables:new Et};e.set(ft.vscodeWindowId,t);let s=new x,i=new x,r=new x;function n(o,a){return(typeof o=="number"?e.get(o):void 0)??(a?t:void 0)}return{onDidRegisterWindow:s.event,onWillUnregisterWindow:r.event,onDidUnregisterWindow:i.event,registerWindow(o){if(e.has(o.vscodeWindowId))return Y.None;let a=new Et,h={window:o,disposables:a.add(new Et)};return e.set(o.vscodeWindowId,h),a.add(ae(()=>{e.delete(o.vscodeWindowId),i.fire(o)})),a.add(j(o,Ee.BEFORE_UNLOAD,()=>{r.fire(o)})),s.fire(h),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(o){return o.vscodeWindowId},hasWindow(o){return e.has(o)},getWindowById:n,getWindow(o){var l;let a=o;if((l=a==null?void 0:a.ownerDocument)!=null&&l.defaultView)return a.ownerDocument.defaultView.window;let h=o;return h!=null&&h.view?h.view.window:ft},getDocument(o){return ht(o).document}}})(),Fh=class{constructor(e,t,s,i){this._node=e,this._type=t,this._handler=s,this._options=i||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function j(e,t,s,i){return new Fh(e,t,s,i)}var hn=function(e,t,s,i){return j(e,t,s,i)},$r,Wh=class extends Nh{constructor(e){super(),this.defaultTarget=e&&ht(e)}cancelAndSet(e,t,s){return super.cancelAndSet(e,t,s??this.defaultTarget)}},cn=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){zs(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,s=new Map,i=new Map,r=n=>{s.set(n,!1);let o=e.get(n)??[];for(t.set(n,o),e.set(n,[]),i.set(n,!0);o.length>0;)o.sort(cn.sort),o.shift().execute();i.set(n,!1)};$r=(n,o,a=0)=>{let h=Oh(n),l=new cn(o,a),c=e.get(h);return c||(c=[],e.set(h,c)),c.push(l),s.get(h)||(s.set(h,!0),n.requestAnimationFrame(()=>r(h))),l}})();function zh(e){let t=e.getBoundingClientRect(),s=ht(e);return{left:t.left+s.scrollX,top:t.top+s.scrollY,width:t.width,height:t.height}}var Ee={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},Uh=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=ze(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=ze(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=ze(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=ze(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=ze(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=ze(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=ze(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=ze(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=ze(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=ze(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=ze(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=ze(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=ze(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=ze(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function ze(e){return typeof e=="number"?`${e}px`:e}function Ss(e){return new Uh(e)}var la=class{constructor(){this._hooks=new Et,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let s=this._onStopCallback;this._onStopCallback=null,e&&s&&s(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,s,i,r){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=i,this._onStopCallback=r;let n=e;try{e.setPointerCapture(t),this._hooks.add(ae(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{n=ht(e)}this._hooks.add(j(n,Ee.POINTER_MOVE,o=>{if(o.buttons!==s){this.stopMonitoring(!0);return}o.preventDefault(),this._pointerMoveCallback(o)})),this._hooks.add(j(n,Ee.POINTER_UP,o=>this.stopMonitoring(!0)))}};function jh(e,t,s){let i=null,r=null;if(typeof s.value=="function"?(i="value",r=s.value,r.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof s.get=="function"&&(i="get",r=s.get),!r)throw new Error("not supported");let n=`$memoize$${t}`;s[i]=function(...o){return this.hasOwnProperty(n)||Object.defineProperty(this,n,{configurable:!1,enumerable:!1,writable:!1,value:r.apply(this,o)}),this[n]}}var lt;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(lt||(lt={}));var us=class Ae extends Y{constructor(){super(),this.dispatched=!1,this.targets=new Qr,this.ignoreTargets=new Qr,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Te.runAndSubscribe(Hh,({window:t,disposables:s})=>{s.add(j(t.document,"touchstart",i=>this.onTouchStart(i),{passive:!1})),s.add(j(t.document,"touchend",i=>this.onTouchEnd(t,i))),s.add(j(t.document,"touchmove",i=>this.onTouchMove(i),{passive:!1}))},{window:ft,disposables:this._store}))}static addTarget(t){if(!Ae.isTouchDevice())return Y.None;Ae.INSTANCE||(Ae.INSTANCE=new Ae);let s=Ae.INSTANCE.targets.push(t);return ae(s)}static ignoreTarget(t){if(!Ae.isTouchDevice())return Y.None;Ae.INSTANCE||(Ae.INSTANCE=new Ae);let s=Ae.INSTANCE.ignoreTargets.push(t);return ae(s)}static isTouchDevice(){return"ontouchstart"in ft||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let s=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let i=0,r=t.targetTouches.length;i<r;i++){let n=t.targetTouches.item(i);this.activeTouches[n.identifier]={id:n.identifier,initialTarget:n.target,initialTimeStamp:s,initialPageX:n.pageX,initialPageY:n.pageY,rollingTimestamps:[s],rollingPageX:[n.pageX],rollingPageY:[n.pageY]};let o=this.newGestureEvent(lt.Start,n.target);o.pageX=n.pageX,o.pageY=n.pageY,this.dispatchEvent(o)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}onTouchEnd(t,s){let i=Date.now(),r=Object.keys(this.activeTouches).length;for(let n=0,o=s.changedTouches.length;n<o;n++){let a=s.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(a.identifier))){console.warn("move of an UNKNOWN touch",a);continue}let h=this.activeTouches[a.identifier],l=Date.now()-h.initialTimeStamp;if(l<Ae.HOLD_DELAY&&Math.abs(h.initialPageX-Ke(h.rollingPageX))<30&&Math.abs(h.initialPageY-Ke(h.rollingPageY))<30){let c=this.newGestureEvent(lt.Tap,h.initialTarget);c.pageX=Ke(h.rollingPageX),c.pageY=Ke(h.rollingPageY),this.dispatchEvent(c)}else if(l>=Ae.HOLD_DELAY&&Math.abs(h.initialPageX-Ke(h.rollingPageX))<30&&Math.abs(h.initialPageY-Ke(h.rollingPageY))<30){let c=this.newGestureEvent(lt.Contextmenu,h.initialTarget);c.pageX=Ke(h.rollingPageX),c.pageY=Ke(h.rollingPageY),this.dispatchEvent(c)}else if(r===1){let c=Ke(h.rollingPageX),d=Ke(h.rollingPageY),u=Ke(h.rollingTimestamps)-h.rollingTimestamps[0],f=c-h.rollingPageX[0],_=d-h.rollingPageY[0],p=[...this.targets].filter(g=>h.initialTarget instanceof Node&&g.contains(h.initialTarget));this.inertia(t,p,i,Math.abs(f)/u,f>0?1:-1,c,Math.abs(_)/u,_>0?1:-1,d)}this.dispatchEvent(this.newGestureEvent(lt.End,h.initialTarget)),delete this.activeTouches[a.identifier]}this.dispatched&&(s.preventDefault(),s.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,s){let i=document.createEvent("CustomEvent");return i.initEvent(t,!1,!0),i.initialTarget=s,i.tapCount=0,i}dispatchEvent(t){if(t.type===lt.Tap){let s=new Date().getTime(),i=0;s-this._lastSetTapCountTime>Ae.CLEAR_TAP_COUNT_TIME?i=1:i=2,this._lastSetTapCountTime=s,t.tapCount=i}else(t.type===lt.Change||t.type===lt.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let i of this.ignoreTargets)if(i.contains(t.initialTarget))return;let s=[];for(let i of this.targets)if(i.contains(t.initialTarget)){let r=0,n=t.initialTarget;for(;n&&n!==i;)r++,n=n.parentElement;s.push([r,i])}s.sort((i,r)=>i[0]-r[0]);for(let[i,r]of s)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,s,i,r,n,o,a,h,l){this.handle=$r(t,()=>{let c=Date.now(),d=c-i,u=0,f=0,_=!0;r+=Ae.SCROLL_FRICTION*d,a+=Ae.SCROLL_FRICTION*d,r>0&&(_=!1,u=n*r*d),a>0&&(_=!1,f=h*a*d);let p=this.newGestureEvent(lt.Change);p.translationX=u,p.translationY=f,s.forEach(g=>g.dispatchEvent(p)),_||this.inertia(t,s,c,r,n,o+u,a,h,l+f)})}onTouchMove(t){let s=Date.now();for(let i=0,r=t.changedTouches.length;i<r;i++){let n=t.changedTouches.item(i);if(!this.activeTouches.hasOwnProperty(String(n.identifier))){console.warn("end of an UNKNOWN touch",n);continue}let o=this.activeTouches[n.identifier],a=this.newGestureEvent(lt.Change,o.initialTarget);a.translationX=n.pageX-Ke(o.rollingPageX),a.translationY=n.pageY-Ke(o.rollingPageY),a.pageX=n.pageX,a.pageY=n.pageY,this.dispatchEvent(a),o.rollingPageX.length>3&&(o.rollingPageX.shift(),o.rollingPageY.shift(),o.rollingTimestamps.shift()),o.rollingPageX.push(n.pageX),o.rollingPageY.push(n.pageY),o.rollingTimestamps.push(s)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};us.SCROLL_FRICTION=-.005,us.HOLD_DELAY=700,us.CLEAR_TAP_COUNT_TIME=400,pe([jh],us,"isTouchDevice",1);var Kh=us,Ar=class extends Y{onclick(e,t){this._register(j(e,Ee.CLICK,s=>t(new Ps(ht(e),s))))}onmousedown(e,t){this._register(j(e,Ee.MOUSE_DOWN,s=>t(new Ps(ht(e),s))))}onmouseover(e,t){this._register(j(e,Ee.MOUSE_OVER,s=>t(new Ps(ht(e),s))))}onmouseleave(e,t){this._register(j(e,Ee.MOUSE_LEAVE,s=>t(new Ps(ht(e),s))))}onkeydown(e,t){this._register(j(e,Ee.KEY_DOWN,s=>t(new nn(s))))}onkeyup(e,t){this._register(j(e,Ee.KEY_UP,s=>t(new nn(s))))}oninput(e,t){this._register(j(e,Ee.INPUT,t))}onblur(e,t){this._register(j(e,Ee.BLUR,t))}onfocus(e,t){this._register(j(e,Ee.FOCUS,t))}onchange(e,t){this._register(j(e,Ee.CHANGE,t))}ignoreGesture(e){return Kh.ignoreTarget(e)}},dn=11,qh=class extends Ar{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=dn+"px",this.domNode.style.height=dn+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new la),this._register(hn(this.bgDomNode,Ee.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(hn(this.domNode,Ee.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new Wh),this._pointerdownScheduleRepeatTimer=this._register(new Tr)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,ht(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,s=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},Vh=class Qi{constructor(t,s,i,r,n,o,a){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(s=s|0,i=i|0,r=r|0,n=n|0,o=o|0,a=a|0),this.rawScrollLeft=r,this.rawScrollTop=a,s<0&&(s=0),r+s>i&&(r=i-s),r<0&&(r=0),n<0&&(n=0),a+n>o&&(a=o-n),a<0&&(a=0),this.width=s,this.scrollWidth=i,this.scrollLeft=r,this.height=n,this.scrollHeight=o,this.scrollTop=a}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,s){return new Qi(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,s?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,s?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new Qi(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,s){let i=this.width!==t.width,r=this.scrollWidth!==t.scrollWidth,n=this.scrollLeft!==t.scrollLeft,o=this.height!==t.height,a=this.scrollHeight!==t.scrollHeight,h=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:s,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:i,scrollWidthChanged:r,scrollLeftChanged:n,heightChanged:o,scrollHeightChanged:a,scrollTopChanged:h}}},Gh=class extends Y{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new x),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Vh(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){var i;let s=this._state.withScrollDimensions(e,t);this._setState(s,!!this._smoothScrolling),(i=this._smoothScrolling)==null||i.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let s=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===s.scrollLeft&&this._smoothScrolling.to.scrollTop===s.scrollTop)return;let i;t?i=new _n(this._smoothScrolling.from,s,this._smoothScrolling.startTime,this._smoothScrolling.duration):i=this._smoothScrolling.combine(this._state,s,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=i}else{let s=this._state.withScrollPosition(e);this._smoothScrolling=_n.start(this._state,s,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let s=this._state;s.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(s,t)))}},un=class{constructor(e,t,s){this.scrollLeft=e,this.scrollTop=t,this.isDone=s}};function Si(e,t){let s=t-e;return function(i){return e+s*Jh(i)}}function Yh(e,t,s){return function(i){return i<s?e(i/s):t((i-s)/(1-s))}}var _n=class er{constructor(t,s,i,r){this.from=t,this.to=s,this.duration=r,this.startTime=i,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(t,s,i){if(Math.abs(t-s)>2.5*i){let r,n;return t<s?(r=t+.75*i,n=s-.75*i):(r=t-.75*i,n=s+.75*i),Yh(Si(t,r),Si(n,s),.33)}return Si(t,s)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(t){this.to=t.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(t){let s=(t-this.startTime)/this.duration;if(s<1){let i=this.scrollLeft(s),r=this.scrollTop(s);return new un(i,r,!1)}return new un(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,s,i){return er.start(t,s,i)}static start(t,s,i){i=i+10;let r=Date.now()-10;return new er(t,s,r,i)}};function Xh(e){return Math.pow(e,3)}function Jh(e){return 1-Xh(1-e)}var Zh=class extends Y{constructor(e,t,s){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=s,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new Tr)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3?!0:this._rawShouldBeVisible}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){if(!this._isNeeded){this._hide(!1);return}this._shouldBeVisible?this._reveal():this._hide(!0)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{var e;(e=this._domNode)==null||e.setClassName(this._visibleClassName)},0))}_hide(e){var t;this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,(t=this._domNode)==null||t.setClassName(this._invisibleClassName+(e?" fade":"")))}},Qh=140,ha=class extends Ar{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new Zh(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new la),this._shouldRender=!0,this.domNode=Ss(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(j(this.domNode.domNode,Ee.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new qh(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,s,i){this.slider=Ss(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof s=="number"&&this.slider.setWidth(s),typeof i=="number"&&this.slider.setHeight(i),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(j(this.slider.domNode,Ee.POINTER_DOWN,r=>{r.button===0&&(r.preventDefault(),this._sliderPointerDown(r))})),this.onclick(this.slider.domNode,r=>{r.leftButton&&r.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,s=t+this._scrollbarState.getSliderPosition(),i=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),r=this._sliderPointerPosition(e);s<=r&&r<=i?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,s;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,s=e.offsetY;else{let r=zh(this.domNode.domNode);t=e.pageX-r.left,s=e.pageY-r.top}let i=this._pointerDownRelativePosition(t,s);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(i):this._scrollbarState.getDesiredScrollPositionFromOffset(i)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),s=this._sliderOrthogonalPointerPosition(e),i=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,r=>{let n=this._sliderOrthogonalPointerPosition(r),o=Math.abs(n-s);if(ra&&o>Qh){this._setDesiredScrollPositionNow(i.getScrollPosition());return}let a=this._sliderPointerPosition(r)-t;this._setDesiredScrollPositionNow(i.getDesiredScrollPositionFromDelta(a))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},ca=class tr{constructor(t,s,i,r,n,o){this._scrollbarSize=Math.round(s),this._oppositeScrollbarSize=Math.round(i),this._arrowSize=Math.round(t),this._visibleSize=r,this._scrollSize=n,this._scrollPosition=o,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new tr(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let s=Math.round(t);return this._visibleSize!==s?(this._visibleSize=s,this._refreshComputedValues(),!0):!1}setScrollSize(t){let s=Math.round(t);return this._scrollSize!==s?(this._scrollSize=s,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let s=Math.round(t);return this._scrollPosition!==s?(this._scrollPosition=s,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,s,i,r,n){let o=Math.max(0,i-t),a=Math.max(0,o-2*s),h=r>0&&r>i;if(!h)return{computedAvailableSize:Math.round(o),computedIsNeeded:h,computedSliderSize:Math.round(a),computedSliderRatio:0,computedSliderPosition:0};let l=Math.round(Math.max(20,Math.floor(i*a/r))),c=(a-l)/(r-i),d=n*c;return{computedAvailableSize:Math.round(o),computedIsNeeded:h,computedSliderSize:Math.round(l),computedSliderRatio:c,computedSliderPosition:Math.round(d)}}_refreshComputedValues(){let t=tr._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let s=t-this._arrowSize-this._computedSliderSize/2;return Math.round(s/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let s=t-this._arrowSize,i=this._scrollPosition;return s<this._computedSliderPosition?i-=this._visibleSize:i+=this._visibleSize,i}getDesiredScrollPositionFromDelta(t){if(!this._computedIsNeeded)return 0;let s=this._computedSliderPosition+t;return Math.round(s/this._computedSliderRatio)}},ec=class extends ha{constructor(e,t,s){let i=e.getScrollDimensions(),r=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:s,scrollbarState:new ca(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,i.width,i.scrollWidth,r.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:"horizontal",scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===2?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},tc=class extends ha{constructor(e,t,s){let i=e.getScrollDimensions(),r=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:s,scrollbarState:new ca(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,i.height,i.scrollHeight,r.scrollTop),visibility:t.vertical,extraScrollbarClassName:"vertical",scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},sc=500,fn=50,ic=class{constructor(e,t,s){this.timestamp=e,this.deltaX=t,this.deltaY=s,this.score=0}},sr=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let t=1,s=0,i=1,r=this._rear;do{let n=r===this._front?t:Math.pow(2,-i);if(t-=n,s+=this._memory[r].score*n,r===this._front)break;r=(this._capacity+r-1)%this._capacity,i++}while(!0);return s<=.5}acceptStandardWheelEvent(t){if(Mr){let s=ht(t.browserEvent),i=fh(s);this.accept(Date.now(),t.deltaX*i,t.deltaY*i)}else this.accept(Date.now(),t.deltaX,t.deltaY)}accept(t,s,i){let r=null,n=new ic(t,s,i);this._front===-1&&this._rear===-1?(this._memory[0]=n,this._front=0,this._rear=0):(r=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=n),n.score=this._computeScore(n,r)}_computeScore(t,s){if(Math.abs(t.deltaX)>0&&Math.abs(t.deltaY)>0)return 1;let i=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(i+=.25),s){let r=Math.abs(t.deltaX),n=Math.abs(t.deltaY),o=Math.abs(s.deltaX),a=Math.abs(s.deltaY),h=Math.max(Math.min(r,o),1),l=Math.max(Math.min(n,a),1),c=Math.max(r,o),d=Math.max(n,a);c%h===0&&d%l===0&&(i-=.5)}return Math.min(Math.max(i,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};sr.INSTANCE=new sr;var rc=sr,nc=class extends Ar{constructor(e,t,s){super(),this._onScroll=this._register(new x),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new x),this.onWillScroll=this._onWillScroll.event,this._options=ac(t),this._scrollable=s,this._register(this._scrollable.onScroll(r=>{this._onWillScroll.fire(r),this._onDidScroll(r),this._onScroll.fire(r)}));let i={onMouseWheel:r=>this._onMouseWheel(r),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new tc(this._scrollable,this._options,i)),this._horizontalScrollbar=this._register(new ec(this._scrollable,this._options,i)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=Ss(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Ss(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Ss(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,r=>this._onMouseOver(r)),this.onmouseleave(this._listenOnDomNode,r=>this._onMouseLeave(r)),this._hideTimeout=this._register(new Tr),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=It(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,ct&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new an(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=It(this._mouseWheelToDispose),e)){let t=s=>{this._onMouseWheel(new an(s))};this._mouseWheelToDispose.push(j(this._listenOnDomNode,Ee.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var r;if((r=e.browserEvent)!=null&&r.defaultPrevented)return;let t=rc.INSTANCE;t.acceptStandardWheelEvent(e);let s=!1;if(e.deltaY||e.deltaX){let n=e.deltaY*this._options.mouseWheelScrollSensitivity,o=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&o+n===0?o=n=0:Math.abs(n)>=Math.abs(o)?o=0:n=0),this._options.flipAxes&&([n,o]=[o,n]);let a=!ct&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!o&&(o=n,n=0),e.browserEvent&&e.browserEvent.altKey&&(o=o*this._options.fastScrollSensitivity,n=n*this._options.fastScrollSensitivity);let h=this._scrollable.getFutureScrollPosition(),l={};if(n){let c=fn*n,d=h.scrollTop-(c<0?Math.floor(c):Math.ceil(c));this._verticalScrollbar.writeScrollPosition(l,d)}if(o){let c=fn*o,d=h.scrollLeft-(c<0?Math.floor(c):Math.ceil(c));this._horizontalScrollbar.writeScrollPosition(l,d)}l=this._scrollable.validateScrollPosition(l),(h.scrollLeft!==l.scrollLeft||h.scrollTop!==l.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(l):this._scrollable.setScrollPositionNow(l),s=!0)}let i=s;!i&&this._options.alwaysConsumeMouseWheel&&(i=!0),!i&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(i=!0),i&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,s=e.scrollLeft>0,i=s?" left":"",r=t?" top":"",n=s||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${i}`),this._topShadowDomNode.setClassName(`shadow${r}`),this._topLeftShadowDomNode.setClassName(`shadow${n}${r}${i}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),sc)}},oc=class extends nc{constructor(e,t,s){super(e,t,s)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function ac(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,ct&&(t.className+=" mac"),t}var ir=class extends Y{constructor(e,t,s,i,r,n,o,a){super(),this._bufferService=s,this._optionsService=o,this._renderService=a,this._onRequestScrollLines=this._register(new x),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let h=this._register(new Gh({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:l=>$r(i.window,l)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{h.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new oc(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},h)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(r.onProtocolChange(l=>{this._scrollableElement.updateOptions({handleMouseWheel:!(l&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Te.runAndSubscribe(n.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=n.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(ae(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=i.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(ae(()=>this._styleElement.remove())),this._register(Te.runAndSubscribe(n.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",`  background: ${n.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",`  background: ${n.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",`  background: ${n.colors.scrollbarSliderActiveBackground.css};`,"}"].join(`
`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(l=>this._handleScroll(l)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){var e;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:((e=this._optionsService.rawOptions.overviewRuler)==null?void 0:e.width)||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),s=t-this._bufferService.buffer.ydisp;s!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(s)),this._isHandlingScroll=!1}};ir=pe([$(2,He),$(3,pt),$(4,jo),$(5,es),$(6,Fe),$(7,mt)],ir);var rr=class extends Y{constructor(e,t,s,i,r){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=s,this._decorationService=i,this._renderService=r,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(n=>this._removeDecoration(n))),this._register(ae(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){var i;let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",((i=e==null?void 0:e.options)==null?void 0:i.layer)==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let s=e.options.x??0;return s&&s>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let s=this._decorationElements.get(e);s||(s=this._createElement(e),e.element=s,this._decorationElements.set(e,s),this._container.appendChild(s),e.onDispose(()=>{this._decorationElements.delete(e),s.remove()})),s.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(s.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,s.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,s.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,s.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(s)}}_refreshXPosition(e,t=e.element){if(!t)return;let s=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=s?`${s*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=s?`${s*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){var t;(t=this._decorationElements.get(e))==null||t.remove(),this._decorationElements.delete(e),e.dispose()}};rr=pe([$(1,He),$(2,pt),$(3,ks),$(4,mt)],rr);var lc=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,s){return t>=e.startBufferLine-this._linePadding[s||"full"]&&t<=e.endBufferLine+this._linePadding[s||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},ot={full:0,left:0,center:0,right:0},St={full:0,left:0,center:0,right:0},rs={full:0,left:0,center:0,right:0},ii=class extends Y{constructor(e,t,s,i,r,n,o,a){var l;super(),this._viewportElement=e,this._screenElement=t,this._bufferService=s,this._decorationService=i,this._renderService=r,this._optionsService=n,this._themeService=o,this._coreBrowserService=a,this._colorZoneStore=new lc,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),(l=this._viewportElement.parentElement)==null||l.insertBefore(this._canvas,this._viewportElement),this._register(ae(()=>{var c;return(c=this._canvas)==null?void 0:c.remove()}));let h=this._canvas.getContext("2d");if(h)this._ctx=h;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){var e;return((e=this._optionsService.options.overviewRuler)==null?void 0:e.width)||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);St.full=this._canvas.width,St.left=e,St.center=t,St.right=e,this._refreshDrawHeightConstants(),rs.full=1,rs.left=1,rs.center=1+St.left,rs.right=1+St.left+St.center}_refreshDrawHeightConstants(){ot.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);ot.left=t,ot.center=t,ot.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*ot.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*ot.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*ot.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*ot.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(rs[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-ot[e.position||"full"]/2),St[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+ot[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};ii=pe([$(2,He),$(3,ks),$(4,mt),$(5,Fe),$(6,es),$(7,pt)],ii);var v;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT="	",e.LF=`
`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(v||(v={}));var Ks;(e=>(e.PAD="",e.HOP="",e.BPH="",e.NBH="",e.IND="",e.NEL="",e.SSA="",e.ESA="",e.HTS="",e.HTJ="",e.VTS="",e.PLD="",e.PLU="",e.RI="",e.SS2="",e.SS3="",e.DCS="",e.PU1="",e.PU2="",e.STS="",e.CCH="",e.MW="",e.SPA="",e.EPA="",e.SOS="",e.SGCI="",e.SCI="",e.CSI="",e.ST="",e.OSC="",e.PM="",e.APC=""))(Ks||(Ks={}));var da;(e=>e.ST=`${v.ESC}\\`)(da||(da={}));var nr=class{constructor(e,t,s,i,r,n){this._textarea=e,this._compositionView=t,this._bufferService=s,this._optionsService=i,this._coreService=r,this._renderService=n,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let s;t.start+=this._dataAlreadySent.length,this._isComposing?s=this._textarea.value.substring(t.start,this._compositionPosition.start):s=this._textarea.value.substring(t.start),s.length>0&&this._coreService.triggerDataEvent(s,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,s=t.replace(e,"");this._dataAlreadySent=s,t.length>e.length?this._coreService.triggerDataEvent(s,!0):t.length<e.length?this._coreService.triggerDataEvent(`${v.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let t=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),s=this._renderService.dimensions.css.cell.height,i=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=t*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+"px",this._compositionView.style.top=i+"px",this._compositionView.style.height=s+"px",this._compositionView.style.lineHeight=s+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";let n=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+"px",this._textarea.style.top=i+"px",this._textarea.style.width=Math.max(n.width,1)+"px",this._textarea.style.height=Math.max(n.height,1)+"px",this._textarea.style.lineHeight=n.height+"px"}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};nr=pe([$(2,He),$(3,Fe),$(4,Ht),$(5,mt)],nr);var Re=0,Be=0,Le=0,fe=0,pn={css:"#00000000",rgba:0},we;(e=>{function t(r,n,o,a){return a!==void 0?`#${Tt(r)}${Tt(n)}${Tt(o)}${Tt(a)}`:`#${Tt(r)}${Tt(n)}${Tt(o)}`}e.toCss=t;function s(r,n,o,a=255){return(r<<24|n<<16|o<<8|a)>>>0}e.toRgba=s;function i(r,n,o,a){return{css:e.toCss(r,n,o,a),rgba:e.toRgba(r,n,o,a)}}e.toColor=i})(we||(we={}));var ne;(e=>{function t(h,l){if(fe=(l.rgba&255)/255,fe===1)return{css:l.css,rgba:l.rgba};let c=l.rgba>>24&255,d=l.rgba>>16&255,u=l.rgba>>8&255,f=h.rgba>>24&255,_=h.rgba>>16&255,p=h.rgba>>8&255;Re=f+Math.round((c-f)*fe),Be=_+Math.round((d-_)*fe),Le=p+Math.round((u-p)*fe);let g=we.toCss(Re,Be,Le),k=we.toRgba(Re,Be,Le);return{css:g,rgba:k}}e.blend=t;function s(h){return(h.rgba&255)===255}e.isOpaque=s;function i(h,l,c){let d=qs.ensureContrastRatio(h.rgba,l.rgba,c);if(d)return we.toColor(d>>24&255,d>>16&255,d>>8&255)}e.ensureContrastRatio=i;function r(h){let l=(h.rgba|255)>>>0;return[Re,Be,Le]=qs.toChannels(l),{css:we.toCss(Re,Be,Le),rgba:l}}e.opaque=r;function n(h,l){return fe=Math.round(l*255),[Re,Be,Le]=qs.toChannels(h.rgba),{css:we.toCss(Re,Be,Le,fe),rgba:we.toRgba(Re,Be,Le,fe)}}e.opacity=n;function o(h,l){return fe=h.rgba&255,n(h,fe*l/255)}e.multiplyOpacity=o;function a(h){return[h.rgba>>24&255,h.rgba>>16&255,h.rgba>>8&255]}e.toColorRGB=a})(ne||(ne={}));var he;(e=>{let t,s;try{let r=document.createElement("canvas");r.width=1,r.height=1;let n=r.getContext("2d",{willReadFrequently:!0});n&&(t=n,t.globalCompositeOperation="copy",s=t.createLinearGradient(0,0,1,1))}catch{}function i(r){if(r.match(/#[\da-f]{3,8}/i))switch(r.length){case 4:return Re=parseInt(r.slice(1,2).repeat(2),16),Be=parseInt(r.slice(2,3).repeat(2),16),Le=parseInt(r.slice(3,4).repeat(2),16),we.toColor(Re,Be,Le);case 5:return Re=parseInt(r.slice(1,2).repeat(2),16),Be=parseInt(r.slice(2,3).repeat(2),16),Le=parseInt(r.slice(3,4).repeat(2),16),fe=parseInt(r.slice(4,5).repeat(2),16),we.toColor(Re,Be,Le,fe);case 7:return{css:r,rgba:(parseInt(r.slice(1),16)<<8|255)>>>0};case 9:return{css:r,rgba:parseInt(r.slice(1),16)>>>0}}let n=r.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(n)return Re=parseInt(n[1]),Be=parseInt(n[2]),Le=parseInt(n[3]),fe=Math.round((n[5]===void 0?1:parseFloat(n[5]))*255),we.toColor(Re,Be,Le,fe);if(!t||!s)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=s,t.fillStyle=r,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Re,Be,Le,fe]=t.getImageData(0,0,1,1).data,fe!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:we.toRgba(Re,Be,Le,fe),css:r}}e.toColor=i})(he||(he={}));var Ie;(e=>{function t(i){return s(i>>16&255,i>>8&255,i&255)}e.relativeLuminance=t;function s(i,r,n){let o=i/255,a=r/255,h=n/255,l=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4),c=a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4),d=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4);return l*.2126+c*.7152+d*.0722}e.relativeLuminance2=s})(Ie||(Ie={}));var qs;(e=>{function t(o,a){if(fe=(a&255)/255,fe===1)return a;let h=a>>24&255,l=a>>16&255,c=a>>8&255,d=o>>24&255,u=o>>16&255,f=o>>8&255;return Re=d+Math.round((h-d)*fe),Be=u+Math.round((l-u)*fe),Le=f+Math.round((c-f)*fe),we.toRgba(Re,Be,Le)}e.blend=t;function s(o,a,h){let l=Ie.relativeLuminance(o>>8),c=Ie.relativeLuminance(a>>8);if(_t(l,c)<h){if(c<l){let f=i(o,a,h),_=_t(l,Ie.relativeLuminance(f>>8));if(_<h){let p=r(o,a,h),g=_t(l,Ie.relativeLuminance(p>>8));return _>g?f:p}return f}let d=r(o,a,h),u=_t(l,Ie.relativeLuminance(d>>8));if(u<h){let f=i(o,a,h),_=_t(l,Ie.relativeLuminance(f>>8));return u>_?d:f}return d}}e.ensureContrastRatio=s;function i(o,a,h){let l=o>>24&255,c=o>>16&255,d=o>>8&255,u=a>>24&255,f=a>>16&255,_=a>>8&255,p=_t(Ie.relativeLuminance2(u,f,_),Ie.relativeLuminance2(l,c,d));for(;p<h&&(u>0||f>0||_>0);)u-=Math.max(0,Math.ceil(u*.1)),f-=Math.max(0,Math.ceil(f*.1)),_-=Math.max(0,Math.ceil(_*.1)),p=_t(Ie.relativeLuminance2(u,f,_),Ie.relativeLuminance2(l,c,d));return(u<<24|f<<16|_<<8|255)>>>0}e.reduceLuminance=i;function r(o,a,h){let l=o>>24&255,c=o>>16&255,d=o>>8&255,u=a>>24&255,f=a>>16&255,_=a>>8&255,p=_t(Ie.relativeLuminance2(u,f,_),Ie.relativeLuminance2(l,c,d));for(;p<h&&(u<255||f<255||_<255);)u=Math.min(255,u+Math.ceil((255-u)*.1)),f=Math.min(255,f+Math.ceil((255-f)*.1)),_=Math.min(255,_+Math.ceil((255-_)*.1)),p=_t(Ie.relativeLuminance2(u,f,_),Ie.relativeLuminance2(l,c,d));return(u<<24|f<<16|_<<8|255)>>>0}e.increaseLuminance=r;function n(o){return[o>>24&255,o>>16&255,o>>8&255,o&255]}e.toChannels=n})(qs||(qs={}));function Tt(e){let t=e.toString(16);return t.length<2?"0"+t:t}function _t(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var hc=class extends xs{constructor(e,t,s){super(),this.content=0,this.combinedData="",this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=s}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},ri=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new Ze}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let s=[],i=t.translateToString(!0),r=0,n=0,o=0,a=t.getFg(0),h=t.getBg(0);for(let l=0;l<t.getTrimmedLength();l++)if(t.loadCell(l,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==a||this._workCell.bg!==h){if(l-r>1){let c=this._getJoinedRanges(i,o,n,t,r);for(let d=0;d<c.length;d++)s.push(c[d])}r=l,o=n,a=this._workCell.fg,h=this._workCell.bg}n+=this._workCell.getChars().length||kt.length}if(this._bufferService.cols-r>1){let l=this._getJoinedRanges(i,o,n,t,r);for(let c=0;c<l.length;c++)s.push(l[c])}return s}_getJoinedRanges(e,t,s,i,r){let n=e.substring(t,s),o=[];try{o=this._characterJoiners[0].handler(n)}catch(a){console.error(a)}for(let a=1;a<this._characterJoiners.length;a++)try{let h=this._characterJoiners[a].handler(n);for(let l=0;l<h.length;l++)ri._mergeRanges(o,h[l])}catch(h){console.error(h)}return this._stringRangesToCellRanges(o,i,r),o}_stringRangesToCellRanges(e,t,s){let i=0,r=!1,n=0,o=e[i];if(o){for(let a=s;a<this._bufferService.cols;a++){let h=t.getWidth(a),l=t.getString(a).length||kt.length;if(h!==0){if(!r&&o[0]<=n&&(o[0]=a,r=!0),o[1]<=n){if(o[1]=a,o=e[++i],!o)break;o[0]<=n?(o[0]=a,r=!0):r=!1}n+=l}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let s=!1;for(let i=0;i<e.length;i++){let r=e[i];if(s){if(t[1]<=r[0])return e[i-1][1]=t[1],e;if(t[1]<=r[1])return e[i-1][1]=Math.max(t[1],r[1]),e.splice(i,1),e;e.splice(i,1),i--}else{if(t[1]<=r[0])return e.splice(i,0,t),e;if(t[1]<=r[1])return r[0]=Math.min(t[0],r[0]),e;t[0]<r[1]&&(r[0]=Math.min(t[0],r[0]),s=!0);continue}}return s?e[e.length-1][1]=t[1]:e.push(t),e}};ri=pe([$(0,He)],ri);function cc(e){return 57508<=e&&e<=57558}function dc(e){return 9472<=e&&e<=9631}function uc(e){return cc(e)||dc(e)}function _c(){return{css:{canvas:Ns(),cell:Ns()},device:{canvas:Ns(),cell:Ns(),char:{width:0,height:0,left:0,top:0}}}}function Ns(){return{width:0,height:0}}var or=class{constructor(e,t,s,i,r,n,o){this._document=e,this._characterJoinerService=t,this._optionsService=s,this._coreBrowserService=i,this._coreService=r,this._decorationService=n,this._themeService=o,this._workCell=new Ze,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,s){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=s}createRow(e,t,s,i,r,n,o,a,h,l,c){let d=[],u=this._characterJoinerService.getJoinedCharacters(t),f=this._themeService.colors,_=e.getNoBgTrimmedLength();s&&_<n+1&&(_=n+1);let p,g=0,k="",q=0,H=0,T=0,N=0,F=!1,Z=0,me=!1,X=0,oe=0,J=[],P=l!==-1&&c!==-1;for(let S=0;S<_;S++){e.loadCell(S,this._workCell);let L=this._workCell.getWidth();if(L===0)continue;let C=!1,M=S>=oe,I=S,R=this._workCell;if(u.length>0&&S===u[0][0]&&M){let O=u.shift(),K=this._isCellInSelection(O[0],t);for(q=O[0]+1;q<O[1];q++)M&&(M=K===this._isCellInSelection(q,t));M&&(M=!s||n<O[0]||n>=O[1]),M?(C=!0,R=new hc(this._workCell,e.translateToString(!0,O[0],O[1]),O[1]-O[0]),I=O[1]-1,L=R.getWidth()):oe=O[1]}let V=this._isCellInSelection(S,t),ee=s&&S===n,Se=P&&S>=l&&S<=c,$e=!1;this._decorationService.forEachDecorationAtCell(S,t,void 0,O=>{$e=!0});let Ne=R.getChars()||kt;if(Ne===" "&&(R.isUnderline()||R.isOverline())&&(Ne=" "),X=L*a-h.get(Ne,R.isBold(),R.isItalic()),!p)p=this._document.createElement("span");else if(g&&(V&&me||!V&&!me&&R.bg===H)&&(V&&me&&f.selectionForeground||R.fg===T)&&R.extended.ext===N&&Se===F&&X===Z&&!ee&&!C&&!$e&&M){R.isInvisible()?k+=kt:k+=Ne,g++;continue}else g&&(p.textContent=k),p=this._document.createElement("span"),g=0,k="";if(H=R.bg,T=R.fg,N=R.extended.ext,F=Se,Z=X,me=V,C&&n>=S&&n<=I&&(n=S),!this._coreService.isCursorHidden&&ee&&this._coreService.isCursorInitialized){if(J.push("xterm-cursor"),this._coreBrowserService.isFocused)o&&J.push("xterm-cursor-blink"),J.push(i==="bar"?"xterm-cursor-bar":i==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(r)switch(r){case"outline":J.push("xterm-cursor-outline");break;case"block":J.push("xterm-cursor-block");break;case"bar":J.push("xterm-cursor-bar");break;case"underline":J.push("xterm-cursor-underline");break}}if(R.isBold()&&J.push("xterm-bold"),R.isItalic()&&J.push("xterm-italic"),R.isDim()&&J.push("xterm-dim"),R.isInvisible()?k=kt:k=R.getChars()||kt,R.isUnderline()&&(J.push(`xterm-underline-${R.extended.underlineStyle}`),k===" "&&(k=" "),!R.isUnderlineColorDefault()))if(R.isUnderlineColorRGB())p.style.textDecorationColor=`rgb(${xs.toColorRGB(R.getUnderlineColor()).join(",")})`;else{let O=R.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&R.isBold()&&O<8&&(O+=8),p.style.textDecorationColor=f.ansi[O].css}R.isOverline()&&(J.push("xterm-overline"),k===" "&&(k=" ")),R.isStrikethrough()&&J.push("xterm-strikethrough"),Se&&(p.style.textDecoration="underline");let re=R.getFgColor(),Ge=R.getFgColorMode(),We=R.getBgColor(),ut=R.getBgColorMode(),ss=!!R.isInverse();if(ss){let O=re;re=We,We=O;let K=Ge;Ge=ut,ut=K}let nt,E,A=!1;this._decorationService.forEachDecorationAtCell(S,t,void 0,O=>{O.options.layer!=="top"&&A||(O.backgroundColorRGB&&(ut=50331648,We=O.backgroundColorRGB.rgba>>8&16777215,nt=O.backgroundColorRGB),O.foregroundColorRGB&&(Ge=50331648,re=O.foregroundColorRGB.rgba>>8&16777215,E=O.foregroundColorRGB),A=O.options.layer==="top")}),!A&&V&&(nt=this._coreBrowserService.isFocused?f.selectionBackgroundOpaque:f.selectionInactiveBackgroundOpaque,We=nt.rgba>>8&16777215,ut=50331648,A=!0,f.selectionForeground&&(Ge=50331648,re=f.selectionForeground.rgba>>8&16777215,E=f.selectionForeground)),A&&J.push("xterm-decoration-top");let W;switch(ut){case 16777216:case 33554432:W=f.ansi[We],J.push(`xterm-bg-${We}`);break;case 50331648:W=we.toColor(We>>16,We>>8&255,We&255),this._addStyle(p,`background-color:#${mn((We>>>0).toString(16),"0",6)}`);break;case 0:default:ss?(W=f.foreground,J.push("xterm-bg-257")):W=f.background}switch(nt||R.isDim()&&(nt=ne.multiplyOpacity(W,.5)),Ge){case 16777216:case 33554432:R.isBold()&&re<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(re+=8),this._applyMinimumContrast(p,W,f.ansi[re],R,nt,void 0)||J.push(`xterm-fg-${re}`);break;case 50331648:let O=we.toColor(re>>16&255,re>>8&255,re&255);this._applyMinimumContrast(p,W,O,R,nt,E)||this._addStyle(p,`color:#${mn(re.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(p,W,f.foreground,R,nt,E)||ss&&J.push("xterm-fg-257")}J.length&&(p.className=J.join(" "),J.length=0),!ee&&!C&&!$e&&M?g++:p.textContent=k,X!==this.defaultSpacing&&(p.style.letterSpacing=`${X}px`),d.push(p),S=I}return p&&g&&(p.textContent=k),d}_applyMinimumContrast(e,t,s,i,r,n){if(this._optionsService.rawOptions.minimumContrastRatio===1||uc(i.getCode()))return!1;let o=this._getContrastCache(i),a;if(!r&&!n&&(a=o.getColor(t.rgba,s.rgba)),a===void 0){let h=this._optionsService.rawOptions.minimumContrastRatio/(i.isDim()?2:1);a=ne.ensureContrastRatio(r||t,n||s,h),o.setColor((r||t).rgba,(n||s).rgba,a??null)}return a?(this._addStyle(e,`color:${a.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let s=this._selectionStart,i=this._selectionEnd;return!s||!i?!1:this._columnSelectMode?s[0]<=i[0]?e>=s[0]&&t>=s[1]&&e<i[0]&&t<=i[1]:e<s[0]&&t>=s[1]&&e>=i[0]&&t<=i[1]:t>s[1]&&t<i[1]||s[1]===i[1]&&t===s[1]&&e>=s[0]&&e<i[0]||s[1]<i[1]&&t===i[1]&&e<i[0]||s[1]<i[1]&&t===s[1]&&e>=s[0]}};or=pe([$(1,Vo),$(2,Fe),$(3,pt),$(4,Ht),$(5,ks),$(6,es)],or);function mn(e,t,s){for(;e.length<s;)e=t+e;return e}var fc=class{constructor(e,t){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=e.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";let s=e.createElement("span");s.classList.add("xterm-char-measure-element");let i=e.createElement("span");i.classList.add("xterm-char-measure-element"),i.style.fontWeight="bold";let r=e.createElement("span");r.classList.add("xterm-char-measure-element"),r.style.fontStyle="italic";let n=e.createElement("span");n.classList.add("xterm-char-measure-element"),n.style.fontWeight="bold",n.style.fontStyle="italic",this._measureElements=[s,i,r,n],this._container.appendChild(s),this._container.appendChild(i),this._container.appendChild(r),this._container.appendChild(n),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,s,i){e===this._font&&t===this._fontSize&&s===this._weight&&i===this._weightBold||(this._font=e,this._fontSize=t,this._weight=s,this._weightBold=i,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${s}`,this._measureElements[1].style.fontWeight=`${i}`,this._measureElements[2].style.fontWeight=`${s}`,this._measureElements[3].style.fontWeight=`${i}`,this.clear())}get(e,t,s){let i=0;if(!t&&!s&&e.length===1&&(i=e.charCodeAt(0))<256){if(this._flat[i]!==-9999)return this._flat[i];let o=this._measure(e,0);return o>0&&(this._flat[i]=o),o}let r=e;t&&(r+="B"),s&&(r+="I");let n=this._holey.get(r);if(n===void 0){let o=0;t&&(o|=1),s&&(o|=2),n=this._measure(e,o),n>0&&this._holey.set(r,n)}return n}_measure(e,t){let s=this._measureElements[t];return s.textContent=e.repeat(32),s.offsetWidth/32}},pc=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,s,i=!1){if(this.selectionStart=t,this.selectionEnd=s,!t||!s||t[0]===s[0]&&t[1]===s[1]){this.clear();return}let r=e.buffers.active.ydisp,n=t[1]-r,o=s[1]-r,a=Math.max(n,0),h=Math.min(o,e.rows-1);if(a>=e.rows||h<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=i,this.viewportStartRow=n,this.viewportEndRow=o,this.viewportCappedStartRow=a,this.viewportCappedEndRow=h,this.startCol=t[0],this.endCol=s[0]}isCellSelected(e,t,s){return this.hasSelection?(s-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&s>=this.viewportCappedStartRow&&t<this.endCol&&s<=this.viewportCappedEndRow:t<this.startCol&&s>=this.viewportCappedStartRow&&t>=this.endCol&&s<=this.viewportCappedEndRow:s>this.viewportStartRow&&s<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&s===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&s===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&s===this.viewportStartRow&&t>=this.startCol):!1}};function mc(){return new pc}var yi="xterm-dom-renderer-owner-",Ye="xterm-rows",Is="xterm-fg-",gn="xterm-bg-",ns="xterm-focus",Os="xterm-selection",gc=1,ar=class extends Y{constructor(e,t,s,i,r,n,o,a,h,l,c,d,u,f){super(),this._terminal=e,this._document=t,this._element=s,this._screenElement=i,this._viewportElement=r,this._helperContainer=n,this._linkifier2=o,this._charSizeService=h,this._optionsService=l,this._bufferService=c,this._coreService=d,this._coreBrowserService=u,this._themeService=f,this._terminalClass=gc++,this._rowElements=[],this._selectionRenderModel=mc(),this.onRequestRedraw=this._register(new x).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(Ye),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(Os),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=_c(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(_=>this._injectCss(_))),this._injectCss(this._themeService.colors),this._rowFactory=a.createInstance(or,document),this._element.classList.add(yi+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(_=>this._handleLinkHover(_))),this._register(this._linkifier2.onHideLinkUnderline(_=>this._handleLinkLeave(_))),this._register(ae(()=>{this._element.classList.remove(yi+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new fc(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let s of this._rowElements)s.style.width=`${this.dimensions.css.canvas.width}px`,s.style.height=`${this.dimensions.css.cell.height}px`,s.style.lineHeight=`${this.dimensions.css.cell.height}px`,s.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${Ye} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${Ye} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${Ye} .xterm-dim { color: ${ne.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let s=`blink_underline_${this._terminalClass}`,i=`blink_bar_${this._terminalClass}`,r=`blink_block_${this._terminalClass}`;t+=`@keyframes ${s} { 50% {  border-bottom-style: hidden; }}`,t+=`@keyframes ${i} { 50% {  box-shadow: none; }}`,t+=`@keyframes ${r} { 0% {  background-color: ${e.cursor.css};  color: ${e.cursorAccent.css}; } 50% {  background-color: inherit;  color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${Ye}.${ns} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${Ye}.${ns} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${Ye}.${ns} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${Ye} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${Ye} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${Ye} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${Ye} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${Ye} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Os} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Os} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Os} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,o]of e.ansi.entries())t+=`${this._terminalSelector} .${Is}${n} { color: ${o.css}; }${this._terminalSelector} .${Is}${n}.xterm-dim { color: ${ne.multiplyOpacity(o,.5).css}; }${this._terminalSelector} .${gn}${n} { background-color: ${o.css}; }`;t+=`${this._terminalSelector} .${Is}257 { color: ${ne.opaque(e.background).css}; }${this._terminalSelector} .${Is}257.xterm-dim { color: ${ne.multiplyOpacity(ne.opaque(e.background),.5).css}; }${this._terminalSelector} .${gn}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let s=this._rowElements.length;s<=t;s++){let i=this._document.createElement("div");this._rowContainer.appendChild(i),this._rowElements.push(i)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(ns),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ns),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,s){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,s),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,s),!this._selectionRenderModel.hasSelection))return;let i=this._selectionRenderModel.viewportStartRow,r=this._selectionRenderModel.viewportEndRow,n=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,a=this._document.createDocumentFragment();if(s){let h=e[0]>t[0];a.appendChild(this._createSelectionElement(n,h?t[0]:e[0],h?e[0]:t[0],o-n+1))}else{let h=i===n?e[0]:0,l=n===r?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(n,h,l));let c=o-n-1;if(a.appendChild(this._createSelectionElement(n+1,0,this._bufferService.cols,c)),n!==o){let d=r===o?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(o,0,d))}}this._selectionContainer.appendChild(a)}_createSelectionElement(e,t,s,i=1){let r=this._document.createElement("div"),n=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(s-t);return n+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-n),r.style.height=`${i*this.dimensions.css.cell.height}px`,r.style.top=`${e*this.dimensions.css.cell.height}px`,r.style.left=`${n}px`,r.style.width=`${o}px`,r}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let s=this._bufferService.buffer,i=s.ybase+s.y,r=Math.min(s.x,this._bufferService.cols-1),n=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,a=this._optionsService.rawOptions.cursorInactiveStyle;for(let h=e;h<=t;h++){let l=h+s.ydisp,c=this._rowElements[h],d=s.lines.get(l);if(!c||!d)break;c.replaceChildren(...this._rowFactory.createRow(d,l,l===i,o,a,r,n,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${yi}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,s,i,r,n){s<0&&(e=0),i<0&&(t=0);let o=this._bufferService.rows-1;s=Math.max(Math.min(s,o),0),i=Math.max(Math.min(i,o),0),r=Math.min(r,this._bufferService.cols);let a=this._bufferService.buffer,h=a.ybase+a.y,l=Math.min(a.x,r-1),c=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,u=this._optionsService.rawOptions.cursorInactiveStyle;for(let f=s;f<=i;++f){let _=f+a.ydisp,p=this._rowElements[f],g=a.lines.get(_);if(!p||!g)break;p.replaceChildren(...this._rowFactory.createRow(g,_,_===h,d,u,l,c,this.dimensions.css.cell.width,this._widthCache,n?f===s?e:0:-1,n?(f===i?t:r)-1:-1))}}};ar=pe([$(7,Rr),$(8,ci),$(9,Fe),$(10,He),$(11,Ht),$(12,pt),$(13,es)],ar);var lr=class extends Y{constructor(e,t,s){super(),this._optionsService=s,this.width=0,this.height=0,this._onCharSizeChange=this._register(new x),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new Sc(this._optionsService))}catch{this._measureStrategy=this._register(new vc(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};lr=pe([$(2,Fe)],lr);var ua=class extends Y{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},vc=class extends ua{constructor(e,t,s){super(),this._document=e,this._parentElement=t,this._optionsService=s,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},Sc=class extends ua{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},yc=class extends Y{constructor(e,t,s){super(),this._textarea=e,this._window=t,this.mainDocument=s,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new wc(this._window)),this._onDprChange=this._register(new x),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new x),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(i=>this._screenDprMonitor.setWindow(i))),this._register(Te.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(j(this._textarea,"focus",()=>this._isFocused=!0)),this._register(j(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},wc=class extends Y{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new Zt),this._onDprChange=this._register(new x),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(ae(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=j(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){var e;this._outerListener&&((e=this._resolutionMediaMatchList)==null||e.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},bc=class extends Y{constructor(){super(),this.linkProviders=[],this._register(ae(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function Pr(e,t,s){let i=s.getBoundingClientRect(),r=e.getComputedStyle(s),n=parseInt(r.getPropertyValue("padding-left")),o=parseInt(r.getPropertyValue("padding-top"));return[t.clientX-i.left-n,t.clientY-i.top-o]}function Cc(e,t,s,i,r,n,o,a,h){if(!n)return;let l=Pr(e,t,s);if(l)return l[0]=Math.ceil((l[0]+(h?o/2:0))/o),l[1]=Math.ceil(l[1]/a),l[0]=Math.min(Math.max(l[0],1),i+(h?1:0)),l[1]=Math.min(Math.max(l[1],1),r),l}var hr=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,s,i,r){return Cc(window,e,t,s,i,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,r)}getMouseReportCoords(e,t){let s=Pr(window,e,t);if(this._charSizeService.hasValidSize)return s[0]=Math.min(Math.max(s[0],0),this._renderService.dimensions.css.canvas.width-1),s[1]=Math.min(Math.max(s[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(s[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(s[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(s[0]),y:Math.floor(s[1])}}};hr=pe([$(0,mt),$(1,ci)],hr);var xc=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,s){this._rowCount=s,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},_a={};Al(_a,{getSafariVersion:()=>Ec,isChromeOS:()=>ga,isFirefox:()=>fa,isIpad:()=>Rc,isIphone:()=>Bc,isLegacyEdge:()=>kc,isLinux:()=>Nr,isMac:()=>ni,isNode:()=>di,isSafari:()=>pa,isWindows:()=>ma});var di=typeof process<"u"&&"title"in process,Es=di?"node":navigator.userAgent,Rs=di?"node":navigator.platform,fa=Es.includes("Firefox"),kc=Es.includes("Edge"),pa=/^((?!chrome|android).)*safari/i.test(Es);function Ec(){if(!pa)return 0;let e=Es.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var ni=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Rs),Rc=Rs==="iPad",Bc=Rs==="iPhone",ma=["Windows","Win16","Win32","WinCE"].includes(Rs),Nr=Rs.indexOf("Linux")>=0,ga=/\bCrOS\b/.test(Es),va=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(e){this._idleCallback=void 0;let t=0,s=0,i=e.timeRemaining(),r=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),s=Math.max(t,s),r=e.timeRemaining(),s*1.5>r){i-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(i-t))}ms`),this._start();return}i=r}this.clear()}},Lc=class extends va{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},Mc=class extends va{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},oi=!di&&"requestIdleCallback"in window?Mc:Lc,Dc=class{constructor(){this._queue=new oi}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},cr=class extends Y{constructor(e,t,s,i,r,n,o,a,h){super(),this._rowCount=e,this._optionsService=s,this._charSizeService=i,this._coreService=r,this._coreBrowserService=a,this._renderer=this._register(new Zt),this._pausedResizeTask=new Dc,this._observerDisposable=this._register(new Zt),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new x),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new x),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new x),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new x),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new xc((l,c)=>this._renderRows(l,c),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new Tc(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(ae(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>{var l;return(l=this._renderer.value)==null?void 0:l.clear()})),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(n.onDecorationRegistered(()=>this._fullRefresh())),this._register(n.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(h.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(l=>this._registerIntersectionObserver(l,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let s=new e.IntersectionObserver(i=>this._handleIntersectionChange(i[i.length-1]),{threshold:0});s.observe(t),this._observerDisposable.value=ae(()=>s.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,s=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let i=this._syncOutputHandler.flush();i&&(e=Math.min(e,i.start),t=Math.max(t,i.end)),s||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var e,t;this._renderer.value&&((t=(e=this._renderer.value).clearTextureAtlas)==null||t.call(e),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>{var s;return(s=this._renderer.value)==null?void 0:s.handleResize(e,t)}):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){var e;(e=this._renderer.value)==null||e.handleCharSizeChanged()}handleBlur(){var e;(e=this._renderer.value)==null||e.handleBlur()}handleFocus(){var e;(e=this._renderer.value)==null||e.handleFocus()}handleSelectionChanged(e,t,s){var i;this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=s,(i=this._renderer.value)==null||i.handleSelectionChanged(e,t,s)}handleCursorMove(){var e;(e=this._renderer.value)==null||e.handleCursorMove()}clear(){var e;(e=this._renderer.value)==null||e.clear()}};cr=pe([$(2,Fe),$(3,ci),$(4,Ht),$(5,ks),$(6,He),$(7,pt),$(8,es)],cr);var Tc=class{constructor(e,t,s){this._coreBrowserService=e,this._coreService=t,this._onTimeout=s,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function $c(e,t,s,i){let r=s.buffer.x,n=s.buffer.y;if(!s.buffer.hasScrollback)return Nc(r,n,e,t,s,i)+ui(n,t,s,i)+Ic(r,n,e,t,s,i);let o;if(n===t)return o=r>e?"D":"C",ws(Math.abs(r-e),ys(o,i));o=n>t?"D":"C";let a=Math.abs(n-t),h=Pc(n>t?e:r,s)+(a-1)*s.cols+1+Ac(n>t?r:e);return ws(h,ys(o,i))}function Ac(e,t){return e-1}function Pc(e,t){return t.cols-e}function Nc(e,t,s,i,r,n){return ui(t,i,r,n).length===0?"":ws(ya(e,t,e,t-Ot(t,r),!1,r).length,ys("D",n))}function ui(e,t,s,i){let r=e-Ot(e,s),n=t-Ot(t,s),o=Math.abs(r-n)-Oc(e,t,s);return ws(o,ys(Sa(e,t),i))}function Ic(e,t,s,i,r,n){let o;ui(t,i,r,n).length>0?o=i-Ot(i,r):o=t;let a=i,h=Hc(e,t,s,i,r,n);return ws(ya(e,o,s,a,h==="C",r).length,ys(h,n))}function Oc(e,t,s){var o;let i=0,r=e-Ot(e,s),n=t-Ot(t,s);for(let a=0;a<Math.abs(r-n);a++){let h=Sa(e,t)==="A"?-1:1;(o=s.buffer.lines.get(r+h*a))!=null&&o.isWrapped&&i++}return i}function Ot(e,t){let s=0,i=t.buffer.lines.get(e),r=i==null?void 0:i.isWrapped;for(;r&&e>=0&&e<t.rows;)s++,i=t.buffer.lines.get(--e),r=i==null?void 0:i.isWrapped;return s}function Hc(e,t,s,i,r,n){let o;return ui(s,i,r,n).length>0?o=i-Ot(i,r):o=t,e<s&&o<=i||e>=s&&o<i?"C":"D"}function Sa(e,t){return e>t?"A":"B"}function ya(e,t,s,i,r,n){let o=e,a=t,h="";for(;(o!==s||a!==i)&&a>=0&&a<n.buffer.lines.length;)o+=r?1:-1,r&&o>n.cols-1?(h+=n.buffer.translateBufferLineToString(a,!1,e,o),o=0,e=0,a++):!r&&o<0&&(h+=n.buffer.translateBufferLineToString(a,!1,0,e+1),o=n.cols-1,e=o,a--);return h+n.buffer.translateBufferLineToString(a,!1,e,o)}function ys(e,t){let s=t?"O":"[";return v.ESC+s+e}function ws(e,t){e=Math.floor(e);let s="";for(let i=0;i<e;i++)s+=t;return s}var Fc=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function vn(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var wi=50,Wc=15,zc=50,Uc=500,jc=" ",Kc=new RegExp(jc,"g"),dr=class extends Y{constructor(e,t,s,i,r,n,o,a,h){super(),this._element=e,this._screenElement=t,this._linkifier=s,this._bufferService=i,this._coreService=r,this._mouseService=n,this._optionsService=o,this._renderService=a,this._coreBrowserService=h,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new Ze,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new x),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new x),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new x),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new x),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=l=>this._handleMouseMove(l),this._mouseUpListener=l=>this._handleMouseUp(l),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(l=>this._handleTrim(l)),this._register(this._bufferService.buffers.onBufferActivate(l=>this._handleBufferActivate(l))),this.enable(),this._model=new Fc(this._bufferService),this._activeSelectionMode=0,this._register(ae(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(l=>{l.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let s=this._bufferService.buffer,i=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let r=e[0]<t[0]?e[0]:t[0],n=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let a=s.translateBufferLineToString(o,!0,r,n);i.push(a)}}else{let r=e[1]===t[1]?t[0]:void 0;i.push(s.translateBufferLineToString(e[1],!0,e[0],r));for(let n=e[1]+1;n<=t[1]-1;n++){let o=s.lines.get(n),a=s.translateBufferLineToString(n,!0);o!=null&&o.isWrapped?i[i.length-1]+=a:i.push(a)}if(e[1]!==t[1]){let n=s.lines.get(t[1]),o=s.translateBufferLineToString(t[1],!0,0,t[0]);n&&n.isWrapped?i[i.length-1]+=o:i.push(o)}}return i.map(r=>r.replace(Kc," ")).join(ma?`\r
`:`
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Nr&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),s=this._model.finalSelectionStart,i=this._model.finalSelectionEnd;return!s||!i||!t?!1:this._areCoordsInSelection(t,s,i)}isCellInSelection(e,t){let s=this._model.finalSelectionStart,i=this._model.finalSelectionEnd;return!s||!i?!1:this._areCoordsInSelection([e,t],s,i)}_areCoordsInSelection(e,t,s){return e[1]>t[1]&&e[1]<s[1]||t[1]===s[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<s[0]||t[1]<s[1]&&e[1]===s[1]&&e[0]<s[0]||t[1]<s[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){var r,n;let s=(n=(r=this._linkifier.currentLink)==null?void 0:r.link)==null?void 0:n.range;if(s)return this._model.selectionStart=[s.start.x-1,s.start.y-1],this._model.selectionStartLength=vn(s,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let i=this._getMouseBufferCoords(e);return i?(this._selectWordAt(i,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Pr(this._coreBrowserService.window,e,this._screenElement)[1],s=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=s?0:(t>s&&(t-=s),t=Math.min(Math.max(t,-wi),wi),t/=wi,t/Math.abs(t)+Math.round(t*(Wc-1)))}shouldForceSelection(e){return ni?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),zc)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(ni&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let s=this._bufferService.buffer;if(this._model.selectionEnd[1]<s.lines.length){let i=s.lines.get(this._model.selectionEnd[1]);i&&i.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(!(!this._model.selectionEnd||!this._model.selectionStart)&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<Uc&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let s=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(s&&s[0]!==void 0&&s[1]!==void 0){let i=$c(s[0]-1,s[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(i,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,s=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);if(!s){this._oldHasSelection&&this._fireOnSelectionChange(e,t,s);return}!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,s)}_fireOnSelectionChange(e,t,s){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=s,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(t=>this._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let s=t;for(let i=0;t>=i;i++){let r=e.loadCell(i,this._workCell).getChars().length;this._workCell.getWidth()===0?s--:r>1&&t!==i&&(s+=r-1)}return s}setSelection(e,t,s){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=s,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,s=!0,i=!0){if(e[0]>=this._bufferService.cols)return;let r=this._bufferService.buffer,n=r.lines.get(e[1]);if(!n)return;let o=r.translateBufferLineToString(e[1],!1),a=this._convertViewportColToCharacterIndex(n,e[0]),h=a,l=e[0]-a,c=0,d=0,u=0,f=0;if(o.charAt(a)===" "){for(;a>0&&o.charAt(a-1)===" ";)a--;for(;h<o.length&&o.charAt(h+1)===" ";)h++}else{let g=e[0],k=e[0];n.getWidth(g)===0&&(c++,g--),n.getWidth(k)===2&&(d++,k++);let q=n.getString(k).length;for(q>1&&(f+=q-1,h+=q-1);g>0&&a>0&&!this._isCharWordSeparator(n.loadCell(g-1,this._workCell));){n.loadCell(g-1,this._workCell);let H=this._workCell.getChars().length;this._workCell.getWidth()===0?(c++,g--):H>1&&(u+=H-1,a-=H-1),a--,g--}for(;k<n.length&&h+1<o.length&&!this._isCharWordSeparator(n.loadCell(k+1,this._workCell));){n.loadCell(k+1,this._workCell);let H=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,k++):H>1&&(f+=H-1,h+=H-1),h++,k++}}h++;let _=a+l-c+u,p=Math.min(this._bufferService.cols,h-a+c+d-u-f);if(!(!t&&o.slice(a,h).trim()==="")){if(s&&_===0&&n.getCodePoint(0)!==32){let g=r.lines.get(e[1]-1);if(g&&n.isWrapped&&g.getCodePoint(this._bufferService.cols-1)!==32){let k=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(k){let q=this._bufferService.cols-k.start;_-=q,p+=q}}}if(i&&_+p===this._bufferService.cols&&n.getCodePoint(this._bufferService.cols-1)!==32){let g=r.lines.get(e[1]+1);if(g!=null&&g.isWrapped&&g.getCodePoint(0)!==32){let k=this._getWordAt([0,e[1]+1],!1,!1,!0);k&&(p+=k.length)}}return{start:_,length:p}}}_selectWordAt(e,t){let s=this._getWordAt(e,t);if(s){for(;s.start<0;)s.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[s.start,e[1]],this._model.selectionStartLength=s.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let s=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,s--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,s++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,s]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),s={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=vn(s,this._bufferService.cols)}};dr=pe([$(3,He),$(4,Ht),$(5,Br),$(6,Fe),$(7,mt),$(8,pt)],dr);var Sn=class{constructor(){this._data={}}set(e,t,s){this._data[e]||(this._data[e]={}),this._data[e][t]=s}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},yn=class{constructor(){this._color=new Sn,this._css=new Sn}setCss(e,t,s){this._css.set(e,t,s)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,s){this._color.set(e,t,s)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Ce=Object.freeze((()=>{let e=[he.toColor("#2e3436"),he.toColor("#cc0000"),he.toColor("#4e9a06"),he.toColor("#c4a000"),he.toColor("#3465a4"),he.toColor("#75507b"),he.toColor("#06989a"),he.toColor("#d3d7cf"),he.toColor("#555753"),he.toColor("#ef2929"),he.toColor("#8ae234"),he.toColor("#fce94f"),he.toColor("#729fcf"),he.toColor("#ad7fa8"),he.toColor("#34e2e2"),he.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let s=0;s<216;s++){let i=t[s/36%6|0],r=t[s/6%6|0],n=t[s%6];e.push({css:we.toCss(i,r,n),rgba:we.toRgba(i,r,n)})}for(let s=0;s<24;s++){let i=8+s*10;e.push({css:we.toCss(i,i,i),rgba:we.toRgba(i,i,i)})}return e})()),$t=he.toColor("#ffffff"),_s=he.toColor("#000000"),wn=he.toColor("#ffffff"),bn=_s,os={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},qc=$t,ur=class extends Y{constructor(e){super(),this._optionsService=e,this._contrastCache=new yn,this._halfContrastCache=new yn,this._onChangeColors=this._register(new x),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:$t,background:_s,cursor:wn,cursorAccent:bn,selectionForeground:void 0,selectionBackgroundTransparent:os,selectionBackgroundOpaque:ne.blend(_s,os),selectionInactiveBackgroundTransparent:os,selectionInactiveBackgroundOpaque:ne.blend(_s,os),scrollbarSliderBackground:ne.opacity($t,.2),scrollbarSliderHoverBackground:ne.opacity($t,.4),scrollbarSliderActiveBackground:ne.opacity($t,.5),overviewRulerBorder:$t,ansi:Ce.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=Q(e.foreground,$t),t.background=Q(e.background,_s),t.cursor=ne.blend(t.background,Q(e.cursor,wn)),t.cursorAccent=ne.blend(t.background,Q(e.cursorAccent,bn)),t.selectionBackgroundTransparent=Q(e.selectionBackground,os),t.selectionBackgroundOpaque=ne.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=Q(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=ne.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?Q(e.selectionForeground,pn):void 0,t.selectionForeground===pn&&(t.selectionForeground=void 0),ne.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=ne.opacity(t.selectionBackgroundTransparent,.3)),ne.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=ne.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=Q(e.scrollbarSliderBackground,ne.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=Q(e.scrollbarSliderHoverBackground,ne.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=Q(e.scrollbarSliderActiveBackground,ne.opacity(t.foreground,.5)),t.overviewRulerBorder=Q(e.overviewRulerBorder,qc),t.ansi=Ce.slice(),t.ansi[0]=Q(e.black,Ce[0]),t.ansi[1]=Q(e.red,Ce[1]),t.ansi[2]=Q(e.green,Ce[2]),t.ansi[3]=Q(e.yellow,Ce[3]),t.ansi[4]=Q(e.blue,Ce[4]),t.ansi[5]=Q(e.magenta,Ce[5]),t.ansi[6]=Q(e.cyan,Ce[6]),t.ansi[7]=Q(e.white,Ce[7]),t.ansi[8]=Q(e.brightBlack,Ce[8]),t.ansi[9]=Q(e.brightRed,Ce[9]),t.ansi[10]=Q(e.brightGreen,Ce[10]),t.ansi[11]=Q(e.brightYellow,Ce[11]),t.ansi[12]=Q(e.brightBlue,Ce[12]),t.ansi[13]=Q(e.brightMagenta,Ce[13]),t.ansi[14]=Q(e.brightCyan,Ce[14]),t.ansi[15]=Q(e.brightWhite,Ce[15]),e.extendedAnsi){let s=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let i=0;i<s;i++)t.ansi[i+16]=Q(e.extendedAnsi[i],Ce[i+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0){for(let t=0;t<this._restoreColors.ansi.length;++t)this._colors.ansi[t]=this._restoreColors.ansi[t];return}switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};ur=pe([$(0,Fe)],ur);function Q(e,t){if(e!==void 0)try{return he.toColor(e)}catch{}return t}var Vc=class{constructor(...e){this._entries=new Map;for(let[t,s]of e)this.set(t,s)}set(e,t){let s=this._entries.get(e);return this._entries.set(e,t),s}forEach(e){for(let[t,s]of this._entries.entries())e(t,s)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},Gc=class{constructor(){this._services=new Vc,this._services.set(Rr,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let s=Wl(e).sort((n,o)=>n.index-o.index),i=[];for(let n of s){let o=this._services.get(n.id);if(!o)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${n.id._id}.`);i.push(o)}let r=s.length>0?s[0].index:t.length;if(t.length!==r)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${r+1} conflicts with ${t.length} static arguments`);return new e(...t,...i)}},Yc={trace:0,debug:1,info:2,warn:3,error:4,off:5},Xc="xterm.js: ",_r=class extends Y{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=Yc[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]=="function"&&(e[t]=e[t]())}_log(e,t,s){this._evalLazyOptionalParams(s),e.call(console,(this._optionsService.options.logger?"":Xc)+t,...s)}trace(e,...t){var s;this._logLevel<=0&&this._log(((s=this._optionsService.options.logger)==null?void 0:s.trace.bind(this._optionsService.options.logger))??console.log,e,t)}debug(e,...t){var s;this._logLevel<=1&&this._log(((s=this._optionsService.options.logger)==null?void 0:s.debug.bind(this._optionsService.options.logger))??console.log,e,t)}info(e,...t){var s;this._logLevel<=2&&this._log(((s=this._optionsService.options.logger)==null?void 0:s.info.bind(this._optionsService.options.logger))??console.info,e,t)}warn(e,...t){var s;this._logLevel<=3&&this._log(((s=this._optionsService.options.logger)==null?void 0:s.warn.bind(this._optionsService.options.logger))??console.warn,e,t)}error(e,...t){var s;this._logLevel<=4&&this._log(((s=this._optionsService.options.logger)==null?void 0:s.error.bind(this._optionsService.options.logger))??console.error,e,t)}};_r=pe([$(0,Fe)],_r);var Cn=class extends Y{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new x),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new x),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new x),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=new Array(e);for(let s=0;s<Math.min(e,this.length);s++)t[s]=this._array[this._getCyclicIndex(s)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...s){if(t){for(let i=e;i<this._length-t;i++)this._array[this._getCyclicIndex(i)]=this._array[this._getCyclicIndex(i+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let i=this._length-1;i>=e;i--)this._array[this._getCyclicIndex(i+s.length)]=this._array[this._getCyclicIndex(i)];for(let i=0;i<s.length;i++)this._array[this._getCyclicIndex(e+i)]=s[i];if(s.length&&this.onInsertEmitter.fire({index:e,amount:s.length}),this._length+s.length>this._maxLength){let i=this._length+s.length-this._maxLength;this._startIndex+=i,this._length=this._maxLength,this.onTrimEmitter.fire(i)}else this._length+=s.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,s){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+s<0)throw new Error("Cannot shift elements in list beyond index 0");if(s>0){for(let r=t-1;r>=0;r--)this.set(e+r+s,this.get(e+r));let i=e+t+s-this._length;if(i>0)for(this._length+=i;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let i=0;i<t;i++)this.set(e+i+s,this.get(e+i))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},G=3,ye=Object.freeze(new xs),Hs=0,bi=2,fs=class wa{constructor(t,s,i=!1){this.isWrapped=i,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(t*G);let r=s||Ze.fromCharData([0,Fo,1,0]);for(let n=0;n<t;++n)this.setCell(n,r);this.length=t}get(t){let s=this._data[t*G+0],i=s&2097151;return[this._data[t*G+1],s&2097152?this._combined[t]:i?Ct(i):"",s>>22,s&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i]}set(t,s){this._data[t*G+1]=s[0],s[1].length>1?(this._combined[t]=s[1],this._data[t*G+0]=t|2097152|s[2]<<22):this._data[t*G+0]=s[1].charCodeAt(0)|s[2]<<22}getWidth(t){return this._data[t*G+0]>>22}hasWidth(t){return this._data[t*G+0]&12582912}getFg(t){return this._data[t*G+1]}getBg(t){return this._data[t*G+2]}hasContent(t){return this._data[t*G+0]&4194303}getCodePoint(t){let s=this._data[t*G+0];return s&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):s&2097151}isCombined(t){return this._data[t*G+0]&2097152}getString(t){let s=this._data[t*G+0];return s&2097152?this._combined[t]:s&2097151?Ct(s&2097151):""}isProtected(t){return this._data[t*G+2]&536870912}loadCell(t,s){return Hs=t*G,s.content=this._data[Hs+0],s.fg=this._data[Hs+1],s.bg=this._data[Hs+2],s.content&2097152&&(s.combinedData=this._combined[t]),s.bg&268435456&&(s.extended=this._extendedAttrs[t]),s}setCell(t,s){s.content&2097152&&(this._combined[t]=s.combinedData),s.bg&268435456&&(this._extendedAttrs[t]=s.extended),this._data[t*G+0]=s.content,this._data[t*G+1]=s.fg,this._data[t*G+2]=s.bg}setCellFromCodepoint(t,s,i,r){r.bg&268435456&&(this._extendedAttrs[t]=r.extended),this._data[t*G+0]=s|i<<22,this._data[t*G+1]=r.fg,this._data[t*G+2]=r.bg}addCodepointToCell(t,s,i){let r=this._data[t*G+0];r&2097152?this._combined[t]+=Ct(s):r&2097151?(this._combined[t]=Ct(r&2097151)+Ct(s),r&=-2097152,r|=2097152):r=s|1<<22,i&&(r&=-12582913,r|=i<<22),this._data[t*G+0]=r}insertCells(t,s,i){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,i),s<this.length-t){let r=new Ze;for(let n=this.length-t-s-1;n>=0;--n)this.setCell(t+s+n,this.loadCell(t+n,r));for(let n=0;n<s;++n)this.setCell(t+n,i)}else for(let r=t;r<this.length;++r)this.setCell(r,i);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,i)}deleteCells(t,s,i){if(t%=this.length,s<this.length-t){let r=new Ze;for(let n=0;n<this.length-t-s;++n)this.setCell(t+n,this.loadCell(t+s+n,r));for(let n=this.length-s;n<this.length;++n)this.setCell(n,i)}else for(let r=t;r<this.length;++r)this.setCell(r,i);t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,i),this.getWidth(t)===0&&!this.hasContent(t)&&this.setCellFromCodepoint(t,0,1,i)}replaceCells(t,s,i,r=!1){if(r){for(t&&this.getWidth(t-1)===2&&!this.isProtected(t-1)&&this.setCellFromCodepoint(t-1,0,1,i),s<this.length&&this.getWidth(s-1)===2&&!this.isProtected(s)&&this.setCellFromCodepoint(s,0,1,i);t<s&&t<this.length;)this.isProtected(t)||this.setCell(t,i),t++;return}for(t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,i),s<this.length&&this.getWidth(s-1)===2&&this.setCellFromCodepoint(s,0,1,i);t<s&&t<this.length;)this.setCell(t++,i)}resize(t,s){if(t===this.length)return this._data.length*4*bi<this._data.buffer.byteLength;let i=t*G;if(t>this.length){if(this._data.buffer.byteLength>=i*4)this._data=new Uint32Array(this._data.buffer,0,i);else{let r=new Uint32Array(i);r.set(this._data),this._data=r}for(let r=this.length;r<t;++r)this.setCell(r,s)}else{this._data=this._data.subarray(0,i);let r=Object.keys(this._combined);for(let o=0;o<r.length;o++){let a=parseInt(r[o],10);a>=t&&delete this._combined[a]}let n=Object.keys(this._extendedAttrs);for(let o=0;o<n.length;o++){let a=parseInt(n[o],10);a>=t&&delete this._extendedAttrs[a]}}return this.length=t,i*4*bi<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*bi<this._data.buffer.byteLength){let t=new Uint32Array(this._data.length);return t.set(this._data),this._data=t,1}return 0}fill(t,s=!1){if(s){for(let i=0;i<this.length;++i)this.isProtected(i)||this.setCell(i,t);return}this._combined={},this._extendedAttrs={};for(let i=0;i<this.length;++i)this.setCell(i,t)}copyFrom(t){this.length!==t.length?this._data=new Uint32Array(t._data):this._data.set(t._data),this.length=t.length,this._combined={};for(let s in t._combined)this._combined[s]=t._combined[s];this._extendedAttrs={};for(let s in t._extendedAttrs)this._extendedAttrs[s]=t._extendedAttrs[s];this.isWrapped=t.isWrapped}clone(){let t=new wa(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let s in this._combined)t._combined[s]=this._combined[s];for(let s in this._extendedAttrs)t._extendedAttrs[s]=this._extendedAttrs[s];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*G+0]&4194303)return t+(this._data[t*G+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*G+0]&4194303||this._data[t*G+2]&50331648)return t+(this._data[t*G+0]>>22);return 0}copyCellsFrom(t,s,i,r,n){let o=t._data;if(n)for(let h=r-1;h>=0;h--){for(let l=0;l<G;l++)this._data[(i+h)*G+l]=o[(s+h)*G+l];o[(s+h)*G+2]&268435456&&(this._extendedAttrs[i+h]=t._extendedAttrs[s+h])}else for(let h=0;h<r;h++){for(let l=0;l<G;l++)this._data[(i+h)*G+l]=o[(s+h)*G+l];o[(s+h)*G+2]&268435456&&(this._extendedAttrs[i+h]=t._extendedAttrs[s+h])}let a=Object.keys(t._combined);for(let h=0;h<a.length;h++){let l=parseInt(a[h],10);l>=s&&(this._combined[l-s+i]=t._combined[l])}}translateToString(t,s,i,r){s=s??0,i=i??this.length,t&&(i=Math.min(i,this.getTrimmedLength())),r&&(r.length=0);let n="";for(;s<i;){let o=this._data[s*G+0],a=o&2097151,h=o&2097152?this._combined[s]:a?Ct(a):kt;if(n+=h,r)for(let l=0;l<h.length;++l)r.push(s);s+=o>>22||1}return r&&r.push(s),n}};function Jc(e,t,s,i,r,n){let o=[];for(let a=0;a<e.length-1;a++){let h=a,l=e.get(++h);if(!l.isWrapped)continue;let c=[e.get(a)];for(;h<e.length&&l.isWrapped;)c.push(l),l=e.get(++h);if(!n&&i>=a&&i<h){a+=c.length-1;continue}let d=0,u=bs(c,d,t),f=1,_=0;for(;f<c.length;){let g=bs(c,f,t),k=g-_,q=s-u,H=Math.min(k,q);c[d].copyCellsFrom(c[f],_,u,H,!1),u+=H,u===s&&(d++,u=0),_+=H,_===g&&(f++,_=0),u===0&&d!==0&&c[d-1].getWidth(s-1)===2&&(c[d].copyCellsFrom(c[d-1],s-1,u++,1,!1),c[d-1].setCell(s-1,r))}c[d].replaceCells(u,s,r);let p=0;for(let g=c.length-1;g>0&&(g>d||c[g].getTrimmedLength()===0);g--)p++;p>0&&(o.push(a+c.length-p),o.push(p)),a+=c.length-1}return o}function Zc(e,t){let s=[],i=0,r=t[i],n=0;for(let o=0;o<e.length;o++)if(r===o){let a=t[++i];e.onDeleteEmitter.fire({index:o-n,amount:a}),o+=a-1,n+=a,r=t[++i]}else s.push(o);return{layout:s,countRemoved:n}}function Qc(e,t){let s=[];for(let i=0;i<t.length;i++)s.push(e.get(t[i]));for(let i=0;i<s.length;i++)e.set(i,s[i]);e.length=t.length}function ed(e,t,s){let i=[],r=e.map((h,l)=>bs(e,l,t)).reduce((h,l)=>h+l),n=0,o=0,a=0;for(;a<r;){if(r-a<s){i.push(r-a);break}n+=s;let h=bs(e,o,t);n>h&&(n-=h,o++);let l=e[o].getWidth(n-1)===2;l&&n--;let c=l?s-1:s;i.push(c),a+=c}return i}function bs(e,t,s){if(t===e.length-1)return e[t].getTrimmedLength();let i=!e[t].hasContent(s-1)&&e[t].getWidth(s-1)===1,r=e[t+1].getWidth(0)===2;return i&&r?s-1:s}var ba=class Ca{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=Ca._nextId++,this._onDispose=this.register(new x),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),It(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};ba._nextId=1;var td=ba,ke={},At=ke.B;ke[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};ke.A={"#":"£"};ke.B=void 0;ke[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};ke.C=ke[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};ke.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};ke.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};ke.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};ke.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};ke.E=ke[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};ke.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};ke.H=ke[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};ke["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var xn=4294967295,kn=class{constructor(e,t,s){this._hasScrollback=e,this._optionsService=t,this._bufferService=s,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=ye.clone(),this.savedCharset=At,this.markers=[],this._nullCell=Ze.fromCharData([0,Fo,1,0]),this._whitespaceCell=Ze.fromCharData([0,kt,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new oi,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Cn(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new si),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new si),this._whitespaceCell}getBlankLine(e,t){return new fs(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>xn?xn:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=ye);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Cn(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let s=this.getNullCell(ye),i=0,r=this._getCorrectBufferLength(t);if(r>this.lines.maxLength&&(this.lines.maxLength=r),this.lines.length>0){if(this._cols<e)for(let o=0;o<this.lines.length;o++)i+=+this.lines.get(o).resize(e,s);let n=0;if(this._rows<t)for(let o=this._rows;o<t;o++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new fs(e,s)):this.ybase>0&&this.lines.length<=this.ybase+this.y+n+1?(this.ybase--,n++,this.ydisp>0&&this.ydisp--):this.lines.push(new fs(e,s)));else for(let o=this._rows;o>t;o--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(r<this.lines.maxLength){let o=this.lines.length-r;o>0&&(this.lines.trimStart(o),this.ybase=Math.max(this.ybase-o,0),this.ydisp=Math.max(this.ydisp-o,0),this.savedY=Math.max(this.savedY-o,0)),this.lines.maxLength=r}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),n&&(this.y+=n),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let n=0;n<this.lines.length;n++)i+=+this.lines.get(n).resize(e,s);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),i>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let s=this._optionsService.rawOptions.reflowCursorLine,i=Jc(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(ye),s);if(i.length>0){let r=Zc(this.lines,i);Qc(this.lines,r.layout),this._reflowLargerAdjustViewport(e,t,r.countRemoved)}}_reflowLargerAdjustViewport(e,t,s){let i=this.getNullCell(ye),r=s;for(;r-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new fs(e,i))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-s,0)}_reflowSmaller(e,t){let s=this._optionsService.rawOptions.reflowCursorLine,i=this.getNullCell(ye),r=[],n=0;for(let o=this.lines.length-1;o>=0;o--){let a=this.lines.get(o);if(!a||!a.isWrapped&&a.getTrimmedLength()<=e)continue;let h=[a];for(;a.isWrapped&&o>0;)a=this.lines.get(--o),h.unshift(a);if(!s){let H=this.ybase+this.y;if(H>=o&&H<o+h.length)continue}let l=h[h.length-1].getTrimmedLength(),c=ed(h,this._cols,e),d=c.length-h.length,u;this.ybase===0&&this.y!==this.lines.length-1?u=Math.max(0,this.y-this.lines.maxLength+d):u=Math.max(0,this.lines.length-this.lines.maxLength+d);let f=[];for(let H=0;H<d;H++){let T=this.getBlankLine(ye,!0);f.push(T)}f.length>0&&(r.push({start:o+h.length+n,newLines:f}),n+=f.length),h.push(...f);let _=c.length-1,p=c[_];p===0&&(_--,p=c[_]);let g=h.length-d-1,k=l;for(;g>=0;){let H=Math.min(k,p);if(h[_]===void 0)break;if(h[_].copyCellsFrom(h[g],k-H,p-H,H,!0),p-=H,p===0&&(_--,p=c[_]),k-=H,k===0){g--;let T=Math.max(g,0);k=bs(h,T,this._cols)}}for(let H=0;H<h.length;H++)c[H]<e&&h[H].setCell(c[H],i);let q=d-u;for(;q-- >0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+n)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(r.length>0){let o=[],a=[];for(let p=0;p<this.lines.length;p++)a.push(this.lines.get(p));let h=this.lines.length,l=h-1,c=0,d=r[c];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+n);let u=0;for(let p=Math.min(this.lines.maxLength-1,h+n-1);p>=0;p--)if(d&&d.start>l+u){for(let g=d.newLines.length-1;g>=0;g--)this.lines.set(p--,d.newLines[g]);p++,o.push({index:l+1,amount:d.newLines.length}),u+=d.newLines.length,d=r[++c]}else this.lines.set(p,a[l--]);let f=0;for(let p=o.length-1;p>=0;p--)o[p].index+=f,this.lines.onInsertEmitter.fire(o[p]),f+=o[p].amount;let _=Math.max(0,h+n-this.lines.maxLength);_>0&&this.lines.onTrimEmitter.fire(_)}}translateBufferLineToString(e,t,s=0,i){let r=this.lines.get(e);return r?r.translateToString(t,s,i):""}getWrappedRangeForLine(e){let t=e,s=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;s+1<this.lines.length&&this.lines.get(s+1).isWrapped;)s++;return{first:t,last:s}}setupTabStops(e){for(e!=null?this.tabs[e]||(e=this.prevStop(e)):(this.tabs={},e=0);e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e==null&&(e=this.x);!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new td(e);return this.markers.push(t),t.register(this.lines.onTrim(s=>{t.line-=s,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(s=>{t.line>=s.index&&(t.line+=s.amount)})),t.register(this.lines.onDelete(s=>{t.line>=s.index&&t.line<s.index+s.amount&&t.dispose(),t.line>s.index&&(t.line-=s.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},sd=class extends Y{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new x),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new kn(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new kn(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},xa=2,ka=1,fr=class extends Y{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new x),this.onResize=this._onResize.event,this._onScroll=this._register(new x),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,xa),this.rows=Math.max(e.rawOptions.rows||0,ka),this.buffers=this._register(new sd(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let s=this.cols!==e,i=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:s,rowsChanged:i})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let s=this.buffer,i;i=this._cachedBlankLine,(!i||i.length!==this.cols||i.getFg(0)!==e.fg||i.getBg(0)!==e.bg)&&(i=s.getBlankLine(e,t),this._cachedBlankLine=i),i.isWrapped=t;let r=s.ybase+s.scrollTop,n=s.ybase+s.scrollBottom;if(s.scrollTop===0){let o=s.lines.isFull;n===s.lines.length-1?o?s.lines.recycle().copyFrom(i):s.lines.push(i.clone()):s.lines.splice(n+1,0,i.clone()),o?this.isUserScrolling&&(s.ydisp=Math.max(s.ydisp-1,0)):(s.ybase++,this.isUserScrolling||s.ydisp++)}else{let o=n-r+1;s.lines.shiftElements(r+1,o-1,-1),s.lines.set(n,i.clone())}this.isUserScrolling||(s.ydisp=s.ybase),this._onScroll.fire(s.ydisp)}scrollLines(e,t){let s=this.buffer;if(e<0){if(s.ydisp===0)return;this.isUserScrolling=!0}else e+s.ydisp>=s.ybase&&(this.isUserScrolling=!1);let i=s.ydisp;s.ydisp=Math.max(Math.min(s.ydisp+e,s.ybase),0),i!==s.ydisp&&(t||this._onScroll.fire(s.ydisp))}};fr=pe([$(0,Fe)],fr);var jt={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:ni,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},id=["normal","bold","100","200","300","400","500","600","700","800","900"],rd=class extends Y{constructor(e){super(),this._onOptionChange=this._register(new x),this.onOptionChange=this._onOptionChange.event;let t={...jt};for(let s in e)if(s in t)try{let i=e[s];t[s]=this._sanitizeAndValidateOption(s,i)}catch(i){console.error(i)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(ae(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(s=>{s===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(s=>{e.indexOf(s)!==-1&&t()})}_setupOptions(){let e=s=>{if(!(s in jt))throw new Error(`No option with key "${s}"`);return this.rawOptions[s]},t=(s,i)=>{if(!(s in jt))throw new Error(`No option with key "${s}"`);i=this._sanitizeAndValidateOption(s,i),this.rawOptions[s]!==i&&(this.rawOptions[s]=i,this._onOptionChange.fire(s))};for(let s in this.rawOptions){let i={get:e.bind(this,s),set:t.bind(this,s)};Object.defineProperty(this.options,s,i)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=jt[e]),!nd(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=jt[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=id.includes(t)?t:jt[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function nd(e){return e==="block"||e==="underline"||e==="bar"}function ps(e,t=5){if(typeof e!="object")return e;let s=Array.isArray(e)?[]:{};for(let i in e)s[i]=t<=1?e[i]:e[i]&&ps(e[i],t-1);return s}var En=Object.freeze({insertMode:!1}),Rn=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),pr=class extends Y{constructor(e,t,s){super(),this._bufferService=e,this._logService=t,this._optionsService=s,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new x),this.onData=this._onData.event,this._onUserInput=this._register(new x),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new x),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new x),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=ps(En),this.decPrivateModes=ps(Rn)}reset(){this.modes=ps(En),this.decPrivateModes=ps(Rn)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let s=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&s.ybase!==s.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(i=>i.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};pr=pe([$(0,He),$(1,Ko),$(2,Fe)],pr);var Bn={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function Ci(e,t){let s=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(s|=64,s|=e.action):(s|=e.button&3,e.button&4&&(s|=64),e.button&8&&(s|=128),e.action===32?s|=32:e.action===0&&!t&&(s|=3)),s}var xi=String.fromCharCode,Ln={DEFAULT:e=>{let t=[Ci(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${xi(t[0])}${xi(t[1])}${xi(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${Ci(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${Ci(e,!0)};${e.x};${e.y}${t}`}},mr=class extends Y{constructor(e,t,s){super(),this._bufferService=e,this._coreService=t,this._optionsService=s,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new x),this.onProtocolChange=this._onProtocolChange.event;for(let i of Object.keys(Bn))this.addProtocol(i,Bn[i]);for(let i of Object.keys(Ln))this.addEncoding(i,Ln[i]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,s){if(e.deltaY===0||e.shiftKey||t===void 0||s===void 0)return 0;let i=t/s,r=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(r/=i+0,Math.abs(e.deltaY)<50&&(r*=.3),this._wheelPartialScroll+=r,r=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(r*=this._bufferService.rows),r}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,s){if(s){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};mr=pe([$(0,He),$(1,Ht),$(2,Fe)],mr);var ki=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],od=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],xe;function ad(e,t){let s=0,i=t.length-1,r;if(e<t[0][0]||e>t[i][1])return!1;for(;i>=s;)if(r=s+i>>1,e>t[r][1])s=r+1;else if(e<t[r][0])i=r-1;else return!0;return!1}var ld=class{constructor(){if(this.version="6",!xe){xe=new Uint8Array(65536),xe.fill(1),xe[0]=0,xe.fill(0,1,32),xe.fill(0,127,160),xe.fill(2,4352,4448),xe[9001]=2,xe[9002]=2,xe.fill(2,11904,42192),xe[12351]=1,xe.fill(2,44032,55204),xe.fill(2,63744,64256),xe.fill(2,65040,65050),xe.fill(2,65072,65136),xe.fill(2,65280,65377),xe.fill(2,65504,65511);for(let e=0;e<ki.length;++e)xe.fill(0,ki[e][0],ki[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?xe[e]:ad(e,od)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let s=this.wcwidth(e),i=s===0&&t!==0;if(i){let r=Pt.extractWidth(t);r===0?i=!1:r>s&&(s=r)}return Pt.createPropertyValue(0,s,i)}},Pt=class Vs{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new x,this.onChange=this._onChange.event;let t=new ld;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,s,i=!1){return(t&16777215)<<3|(s&3)<<1|(i?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let s=0,i=0,r=t.length;for(let n=0;n<r;++n){let o=t.charCodeAt(n);if(55296<=o&&o<=56319){if(++n>=r)return s+this.wcwidth(o);let l=t.charCodeAt(n);56320<=l&&l<=57343?o=(o-55296)*1024+l-56320+65536:s+=this.wcwidth(l)}let a=this.charProperties(o,i),h=Vs.extractWidth(a);Vs.extractShouldJoin(a)&&(h-=Vs.extractWidth(i)),s+=h,i=a}return s}charProperties(t,s){return this._activeProvider.charProperties(t,s)}},hd=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Mn(e){var i;let t=(i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1))==null?void 0:i.get(e.cols-1),s=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);s&&t&&(s.isWrapped=t[3]!==0&&t[3]!==32)}var as=2147483647,cd=256,Ea=class gr{constructor(t=32,s=32){if(this.maxLength=t,this.maxSubParamsLength=s,s>cd)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(s),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let s=new gr;if(!t.length)return s;for(let i=Array.isArray(t[0])?1:0;i<t.length;++i){let r=t[i];if(Array.isArray(r))for(let n=0;n<r.length;++n)s.addSubParam(r[n]);else s.addParam(r)}return s}clone(){let t=new gr(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let t=[];for(let s=0;s<this.length;++s){t.push(this.params[s]);let i=this._subParamsIdx[s]>>8,r=this._subParamsIdx[s]&255;r-i>0&&t.push(Array.prototype.slice.call(this._subParams,i,r))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>as?as:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>as?as:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let s=this._subParamsIdx[t]>>8,i=this._subParamsIdx[t]&255;return i-s>0?this._subParams.subarray(s,i):null}getSubParamsAll(){let t={};for(let s=0;s<this.length;++s){let i=this._subParamsIdx[s]>>8,r=this._subParamsIdx[s]&255;r-i>0&&(t[s]=this._subParams.slice(i,r))}return t}addDigit(t){let s;if(this._rejectDigits||!(s=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let i=this._digitIsSub?this._subParams:this.params,r=i[s-1];i[s-1]=~r?Math.min(r*10+t,as):t}},ls=[],dd=class{constructor(){this._state=0,this._active=ls,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let s=this._handlers[e];return s.push(t),{dispose:()=>{let i=s.indexOf(t);i!==-1&&s.splice(i,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=ls}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=ls,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||ls,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,s){if(!this._active.length)this._handlerFb(this._id,"PUT",hi(e,t,s));else for(let i=this._active.length-1;i>=0;i--)this._active[i].put(e,t,s)}start(){this.reset(),this._state=1}put(e,t,s){if(this._state!==3){if(this._state===1)for(;t<s;){let i=e[t++];if(i===59){this._state=2,this._start();break}if(i<48||57<i){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+i-48}this._state===2&&s-t>0&&this._put(e,t,s)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let s=!1,i=this._active.length-1,r=!1;if(this._stack.paused&&(i=this._stack.loopPosition-1,s=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&s===!1){for(;i>=0&&(s=this._active[i].end(e),s!==!0);i--)if(s instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=i,this._stack.fallThrough=!1,s;i--}for(;i>=0;i--)if(s=this._active[i].end(!1),s instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=i,this._stack.fallThrough=!0,s}this._active=ls,this._id=-1,this._state=0}}},qe=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,s){this._hitLimit||(this._data+=hi(e,t,s),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(s=>(this._data="",this._hitLimit=!1,s));return this._data="",this._hitLimit=!1,t}},hs=[],ud=class{constructor(){this._handlers=Object.create(null),this._active=hs,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=hs}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let s=this._handlers[e];return s.push(t),{dispose:()=>{let i=s.indexOf(t);i!==-1&&s.splice(i,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=hs,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||hs,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let s=this._active.length-1;s>=0;s--)this._active[s].hook(t)}put(e,t,s){if(!this._active.length)this._handlerFb(this._ident,"PUT",hi(e,t,s));else for(let i=this._active.length-1;i>=0;i--)this._active[i].put(e,t,s)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let s=!1,i=this._active.length-1,r=!1;if(this._stack.paused&&(i=this._stack.loopPosition-1,s=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&s===!1){for(;i>=0&&(s=this._active[i].unhook(e),s!==!0);i--)if(s instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=i,this._stack.fallThrough=!1,s;i--}for(;i>=0;i--)if(s=this._active[i].unhook(!1),s instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=i,this._stack.fallThrough=!0,s}this._active=hs,this._ident=0}},ms=new Ea;ms.addParam(0);var Dn=class{constructor(e){this._handler=e,this._data="",this._params=ms,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():ms,this._data="",this._hitLimit=!1}put(e,t,s){this._hitLimit||(this._data+=hi(e,t,s),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(s=>(this._params=ms,this._data="",this._hitLimit=!1,s));return this._params=ms,this._data="",this._hitLimit=!1,t}},_d=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,s,i){this.table[t<<8|e]=s<<4|i}addMany(e,t,s,i){for(let r=0;r<e.length;r++)this.table[t<<8|e[r]]=s<<4|i}},Je=160,fd=(function(){let e=new _d(4095),t=Array.apply(null,Array(256)).map((a,h)=>h),s=(a,h)=>t.slice(a,h),i=s(32,127),r=s(0,24);r.push(25),r.push.apply(r,s(28,32));let n=s(0,14),o;e.setDefault(1,0),e.addMany(i,0,2,0);for(o in n)e.addMany([24,26,153,154],o,3,0),e.addMany(s(128,144),o,3,0),e.addMany(s(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(r,0,3,0),e.addMany(r,1,3,1),e.add(127,1,0,1),e.addMany(r,8,0,8),e.addMany(r,3,3,3),e.add(127,3,0,3),e.addMany(r,4,3,4),e.add(127,4,0,4),e.addMany(r,6,3,6),e.addMany(r,5,3,5),e.add(127,5,0,5),e.addMany(r,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(i,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(s(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(i,7,0,7),e.addMany(r,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(s(64,127),3,7,0),e.addMany(s(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(s(48,60),4,8,4),e.addMany(s(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(s(32,64),6,0,6),e.add(127,6,0,6),e.addMany(s(64,127),6,0,0),e.addMany(s(32,48),3,9,5),e.addMany(s(32,48),5,9,5),e.addMany(s(48,64),5,0,6),e.addMany(s(64,127),5,7,0),e.addMany(s(32,48),4,9,5),e.addMany(s(32,48),1,9,2),e.addMany(s(32,48),2,9,2),e.addMany(s(48,127),2,10,0),e.addMany(s(48,80),1,10,0),e.addMany(s(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(s(96,127),1,10,0),e.add(80,1,11,9),e.addMany(r,9,0,9),e.add(127,9,0,9),e.addMany(s(28,32),9,0,9),e.addMany(s(32,48),9,9,12),e.addMany(s(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(r,11,0,11),e.addMany(s(32,128),11,0,11),e.addMany(s(28,32),11,0,11),e.addMany(r,10,0,10),e.add(127,10,0,10),e.addMany(s(28,32),10,0,10),e.addMany(s(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(s(32,48),10,9,12),e.addMany(r,12,0,12),e.add(127,12,0,12),e.addMany(s(28,32),12,0,12),e.addMany(s(32,48),12,9,12),e.addMany(s(48,64),12,0,11),e.addMany(s(64,127),12,12,13),e.addMany(s(64,127),10,12,13),e.addMany(s(64,127),9,12,13),e.addMany(r,13,13,13),e.addMany(i,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(Je,0,2,0),e.add(Je,8,5,8),e.add(Je,6,0,6),e.add(Je,11,0,11),e.add(Je,13,13,13),e})(),pd=class extends Y{constructor(e=fd){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new Ea,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,s,i)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,s)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(ae(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new dd),this._dcsParser=this._register(new ud),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let s=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(s=e.prefix.charCodeAt(0),s&&60>s||s>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let r=0;r<e.intermediates.length;++r){let n=e.intermediates.charCodeAt(r);if(32>n||n>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");s<<=8,s|=n}}if(e.final.length!==1)throw new Error("final must be a single byte");let i=e.final.charCodeAt(0);if(t[0]>i||i>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return s<<=8,s|=i,s}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let s=this._identifier(e,[48,126]);this._escHandlers[s]===void 0&&(this._escHandlers[s]=[]);let i=this._escHandlers[s];return i.push(t),{dispose:()=>{let r=i.indexOf(t);r!==-1&&i.splice(r,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let s=this._identifier(e);this._csiHandlers[s]===void 0&&(this._csiHandlers[s]=[]);let i=this._csiHandlers[s];return i.push(t),{dispose:()=>{let r=i.indexOf(t);r!==-1&&i.splice(r,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,s,i,r){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=s,this._parseStack.transition=i,this._parseStack.chunkPos=r}parse(e,t,s){let i=0,r=0,n=0,o;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,n=this._parseStack.chunkPos+1;else{if(s===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let a=this._parseStack.handlers,h=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(s===!1&&h>-1){for(;h>=0&&(o=a[h](this._params),o!==!0);h--)if(o instanceof Promise)return this._parseStack.handlerPos=h,o}this._parseStack.handlers=[];break;case 4:if(s===!1&&h>-1){for(;h>=0&&(o=a[h](),o!==!0);h--)if(o instanceof Promise)return this._parseStack.handlerPos=h,o}this._parseStack.handlers=[];break;case 6:if(i=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(i!==24&&i!==26,s),o)return o;i===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(i=e[this._parseStack.chunkPos],o=this._oscParser.end(i!==24&&i!==26,s),o)return o;i===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,n=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let a=n;a<t;++a){switch(i=e[a],r=this._transitions.table[this.currentState<<8|(i<160?i:Je)],r>>4){case 2:for(let u=a+1;;++u){if(u>=t||(i=e[u])<32||i>126&&i<Je){this._printHandler(e,a,u),a=u-1;break}if(++u>=t||(i=e[u])<32||i>126&&i<Je){this._printHandler(e,a,u),a=u-1;break}if(++u>=t||(i=e[u])<32||i>126&&i<Je){this._printHandler(e,a,u),a=u-1;break}if(++u>=t||(i=e[u])<32||i>126&&i<Je){this._printHandler(e,a,u),a=u-1;break}}break;case 3:this._executeHandlers[i]?this._executeHandlers[i]():this._executeHandlerFb(i),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:a,code:i,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let h=this._csiHandlers[this._collect<<8|i],l=h?h.length-1:-1;for(;l>=0&&(o=h[l](this._params),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(3,h,l,r,a),o;l<0&&this._csiHandlerFb(this._collect<<8|i,this._params),this.precedingJoinState=0;break;case 8:do switch(i){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(i-48)}while(++a<t&&(i=e[a])>47&&i<60);a--;break;case 9:this._collect<<=8,this._collect|=i;break;case 10:let c=this._escHandlers[this._collect<<8|i],d=c?c.length-1:-1;for(;d>=0&&(o=c[d](),o!==!0);d--)if(o instanceof Promise)return this._preserveStack(4,c,d,r,a),o;d<0&&this._escHandlerFb(this._collect<<8|i),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|i,this._params);break;case 13:for(let u=a+1;;++u)if(u>=t||(i=e[u])===24||i===26||i===27||i>127&&i<Je){this._dcsParser.put(e,a,u),a=u-1;break}break;case 14:if(o=this._dcsParser.unhook(i!==24&&i!==26),o)return this._preserveStack(6,[],0,r,a),o;i===27&&(r|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let u=a+1;;u++)if(u>=t||(i=e[u])<32||i>127&&i<Je){this._oscParser.put(e,a,u),a=u-1;break}break;case 6:if(o=this._oscParser.end(i!==24&&i!==26),o)return this._preserveStack(5,[],0,r,a),o;i===27&&(r|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break}this.currentState=r&15}}},md=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,gd=/^[\da-f]+$/;function Tn(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf("rgb:")===0){t=t.slice(4);let s=md.exec(t);if(s){let i=s[1]?15:s[4]?255:s[7]?4095:65535;return[Math.round(parseInt(s[1]||s[4]||s[7]||s[10],16)/i*255),Math.round(parseInt(s[2]||s[5]||s[8]||s[11],16)/i*255),Math.round(parseInt(s[3]||s[6]||s[9]||s[12],16)/i*255)]}}else if(t.indexOf("#")===0&&(t=t.slice(1),gd.exec(t)&&[3,6,9,12].includes(t.length))){let s=t.length/3,i=[0,0,0];for(let r=0;r<3;++r){let n=parseInt(t.slice(s*r,s*r+s),16);i[r]=s===1?n<<4:s===2?n:s===3?n>>4:n>>8}return i}}function Ei(e,t){let s=e.toString(16),i=s.length<2?"0"+s:s;switch(t){case 4:return s[0];case 8:return i;case 12:return(i+i).slice(0,3);default:return i+i}}function vd(e,t=16){let[s,i,r]=e;return`rgb:${Ei(s,t)}/${Ei(i,t)}/${Ei(r,t)}`}var Sd={"(":0,")":1,"*":2,"+":3,"-":1,".":2},yt=131072,$n=10;function An(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Pn=5e3,Nn=0,yd=class extends Y{constructor(e,t,s,i,r,n,o,a,h=new pd){super(),this._bufferService=e,this._charsetService=t,this._coreService=s,this._logService=i,this._optionsService=r,this._oscLinkService=n,this._coreMouseService=o,this._unicodeService=a,this._parser=h,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new Hl,this._utf8Decoder=new Fl,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=ye.clone(),this._eraseAttrDataInternal=ye.clone(),this._onRequestBell=this._register(new x),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new x),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new x),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new x),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new x),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new x),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new x),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new x),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new x),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new x),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new x),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new x),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new x),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new vr(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(l=>this._activeBuffer=l.activeBuffer)),this._parser.setCsiHandlerFallback((l,c)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(l),params:c.toArray()})}),this._parser.setEscHandlerFallback(l=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(l)})}),this._parser.setExecuteHandlerFallback(l=>{this._logService.debug("Unknown EXECUTE code: ",{code:l})}),this._parser.setOscHandlerFallback((l,c,d)=>{this._logService.debug("Unknown OSC code: ",{identifier:l,action:c,data:d})}),this._parser.setDcsHandlerFallback((l,c,d)=>{c==="HOOK"&&(d=d.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(l),action:c,payload:d})}),this._parser.setPrintHandler((l,c,d)=>this.print(l,c,d)),this._parser.registerCsiHandler({final:"@"},l=>this.insertChars(l)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},l=>this.scrollLeft(l)),this._parser.registerCsiHandler({final:"A"},l=>this.cursorUp(l)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},l=>this.scrollRight(l)),this._parser.registerCsiHandler({final:"B"},l=>this.cursorDown(l)),this._parser.registerCsiHandler({final:"C"},l=>this.cursorForward(l)),this._parser.registerCsiHandler({final:"D"},l=>this.cursorBackward(l)),this._parser.registerCsiHandler({final:"E"},l=>this.cursorNextLine(l)),this._parser.registerCsiHandler({final:"F"},l=>this.cursorPrecedingLine(l)),this._parser.registerCsiHandler({final:"G"},l=>this.cursorCharAbsolute(l)),this._parser.registerCsiHandler({final:"H"},l=>this.cursorPosition(l)),this._parser.registerCsiHandler({final:"I"},l=>this.cursorForwardTab(l)),this._parser.registerCsiHandler({final:"J"},l=>this.eraseInDisplay(l,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},l=>this.eraseInDisplay(l,!0)),this._parser.registerCsiHandler({final:"K"},l=>this.eraseInLine(l,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},l=>this.eraseInLine(l,!0)),this._parser.registerCsiHandler({final:"L"},l=>this.insertLines(l)),this._parser.registerCsiHandler({final:"M"},l=>this.deleteLines(l)),this._parser.registerCsiHandler({final:"P"},l=>this.deleteChars(l)),this._parser.registerCsiHandler({final:"S"},l=>this.scrollUp(l)),this._parser.registerCsiHandler({final:"T"},l=>this.scrollDown(l)),this._parser.registerCsiHandler({final:"X"},l=>this.eraseChars(l)),this._parser.registerCsiHandler({final:"Z"},l=>this.cursorBackwardTab(l)),this._parser.registerCsiHandler({final:"`"},l=>this.charPosAbsolute(l)),this._parser.registerCsiHandler({final:"a"},l=>this.hPositionRelative(l)),this._parser.registerCsiHandler({final:"b"},l=>this.repeatPrecedingCharacter(l)),this._parser.registerCsiHandler({final:"c"},l=>this.sendDeviceAttributesPrimary(l)),this._parser.registerCsiHandler({prefix:">",final:"c"},l=>this.sendDeviceAttributesSecondary(l)),this._parser.registerCsiHandler({final:"d"},l=>this.linePosAbsolute(l)),this._parser.registerCsiHandler({final:"e"},l=>this.vPositionRelative(l)),this._parser.registerCsiHandler({final:"f"},l=>this.hVPosition(l)),this._parser.registerCsiHandler({final:"g"},l=>this.tabClear(l)),this._parser.registerCsiHandler({final:"h"},l=>this.setMode(l)),this._parser.registerCsiHandler({prefix:"?",final:"h"},l=>this.setModePrivate(l)),this._parser.registerCsiHandler({final:"l"},l=>this.resetMode(l)),this._parser.registerCsiHandler({prefix:"?",final:"l"},l=>this.resetModePrivate(l)),this._parser.registerCsiHandler({final:"m"},l=>this.charAttributes(l)),this._parser.registerCsiHandler({final:"n"},l=>this.deviceStatus(l)),this._parser.registerCsiHandler({prefix:"?",final:"n"},l=>this.deviceStatusPrivate(l)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},l=>this.softReset(l)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},l=>this.setCursorStyle(l)),this._parser.registerCsiHandler({final:"r"},l=>this.setScrollRegion(l)),this._parser.registerCsiHandler({final:"s"},l=>this.saveCursor(l)),this._parser.registerCsiHandler({final:"t"},l=>this.windowOptions(l)),this._parser.registerCsiHandler({final:"u"},l=>this.restoreCursor(l)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},l=>this.insertColumns(l)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},l=>this.deleteColumns(l)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},l=>this.selectProtected(l)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},l=>this.requestMode(l,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},l=>this.requestMode(l,!1)),this._parser.setExecuteHandler(v.BEL,()=>this.bell()),this._parser.setExecuteHandler(v.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(v.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(v.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(v.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(v.BS,()=>this.backspace()),this._parser.setExecuteHandler(v.HT,()=>this.tab()),this._parser.setExecuteHandler(v.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(v.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Ks.IND,()=>this.index()),this._parser.setExecuteHandler(Ks.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Ks.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new qe(l=>(this.setTitle(l),this.setIconName(l),!0))),this._parser.registerOscHandler(1,new qe(l=>this.setIconName(l))),this._parser.registerOscHandler(2,new qe(l=>this.setTitle(l))),this._parser.registerOscHandler(4,new qe(l=>this.setOrReportIndexedColor(l))),this._parser.registerOscHandler(8,new qe(l=>this.setHyperlink(l))),this._parser.registerOscHandler(10,new qe(l=>this.setOrReportFgColor(l))),this._parser.registerOscHandler(11,new qe(l=>this.setOrReportBgColor(l))),this._parser.registerOscHandler(12,new qe(l=>this.setOrReportCursorColor(l))),this._parser.registerOscHandler(104,new qe(l=>this.restoreIndexedColor(l))),this._parser.registerOscHandler(110,new qe(l=>this.restoreFgColor(l))),this._parser.registerOscHandler(111,new qe(l=>this.restoreBgColor(l))),this._parser.registerOscHandler(112,new qe(l=>this.restoreCursorColor(l))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let l in ke)this._parser.registerEscHandler({intermediates:"(",final:l},()=>this.selectCharset("("+l)),this._parser.registerEscHandler({intermediates:")",final:l},()=>this.selectCharset(")"+l)),this._parser.registerEscHandler({intermediates:"*",final:l},()=>this.selectCharset("*"+l)),this._parser.registerEscHandler({intermediates:"+",final:l},()=>this.selectCharset("+"+l)),this._parser.registerEscHandler({intermediates:"-",final:l},()=>this.selectCharset("-"+l)),this._parser.registerEscHandler({intermediates:".",final:l},()=>this.selectCharset("."+l)),this._parser.registerEscHandler({intermediates:"/",final:l},()=>this.selectCharset("/"+l));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(l=>(this._logService.error("Parsing error: ",l),l)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Dn((l,c)=>this.requestStatusString(l,c)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,s,i){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=s,this._parseStack.position=i}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,s)=>setTimeout(()=>s("#SLOW_TIMEOUT"),Pn))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Pn} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let s,i=this._activeBuffer.x,r=this._activeBuffer.y,n=0,o=this._parseStack.paused;if(o){if(s=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(s),s;i=this._parseStack.cursorStartX,r=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>yt&&(n=this._parseStack.position+yt)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,l=>String.fromCharCode(l)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(l=>l.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<yt&&(this._parseBuffer=new Uint32Array(Math.min(e.length,yt))),o||this._dirtyRowTracker.clearRange(),e.length>yt)for(let l=n;l<e.length;l+=yt){let c=l+yt<e.length?l+yt:e.length,d=typeof e=="string"?this._stringDecoder.decode(e.substring(l,c),this._parseBuffer):this._utf8Decoder.decode(e.subarray(l,c),this._parseBuffer);if(s=this._parser.parse(this._parseBuffer,d))return this._preserveStack(i,r,d,l),this._logSlowResolvingAsync(s),s}else if(!o){let l=typeof e=="string"?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(s=this._parser.parse(this._parseBuffer,l))return this._preserveStack(i,r,l,0),this._logSlowResolvingAsync(s),s}(this._activeBuffer.x!==i||this._activeBuffer.y!==r)&&this._onCursorMove.fire();let a=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),h=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);h<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(h,this._bufferService.rows-1),end:Math.min(a,this._bufferService.rows-1)})}print(e,t,s){let i,r,n=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,a=this._bufferService.cols,h=this._coreService.decPrivateModes.wraparound,l=this._coreService.modes.insertMode,c=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&s-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,c);let u=this._parser.precedingJoinState;for(let f=t;f<s;++f){if(i=e[f],i<127&&n){let k=n[String.fromCharCode(i)];k&&(i=k.charCodeAt(0))}let _=this._unicodeService.charProperties(i,u);r=Pt.extractWidth(_);let p=Pt.extractShouldJoin(_),g=p?Pt.extractWidth(u):0;if(u=_,o&&this._onA11yChar.fire(Ct(i)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+r-g>a){if(h){let k=d,q=this._activeBuffer.x-g;for(this._activeBuffer.x=g,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),g>0&&d instanceof fs&&d.copyCellsFrom(k,q,0,g,!1);q<a;)k.setCellFromCodepoint(q++,0,1,c)}else if(this._activeBuffer.x=a-1,r===2)continue}if(p&&this._activeBuffer.x){let k=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-k,i,r);for(let q=r-g;--q>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,c);continue}if(l&&(d.insertCells(this._activeBuffer.x,r-g,this._activeBuffer.getNullCell(c)),d.getWidth(a-1)===2&&d.setCellFromCodepoint(a-1,0,1,c)),d.setCellFromCodepoint(this._activeBuffer.x++,i,r,c),r>0)for(;--r;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,c)}this._parser.precedingJoinState=u,this._activeBuffer.x<a&&s-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,c),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,s=>An(s.params[0],this._optionsService.rawOptions.windowOptions)?t(s):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Dn(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new qe(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var e;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&((e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&e.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);t.hasWidth(this._activeBuffer.x)&&!t.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,s,i=!1,r=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.replaceCells(t,s,this._activeBuffer.getNullCell(this._eraseAttrData()),r),i&&(n.isWrapped=!1)}_resetBufferLine(e,t=!1){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);s&&(s.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),s.isWrapped=!1)}eraseInDisplay(e,t=!1){var i;this._restrictCursor(this._bufferService.cols);let s;switch(e.params[0]){case 0:for(s=this._activeBuffer.y,this._dirtyRowTracker.markDirty(s),this._eraseInBufferLine(s++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);s<this._bufferService.rows;s++)this._resetBufferLine(s,t);this._dirtyRowTracker.markDirty(s);break;case 1:for(s=this._activeBuffer.y,this._dirtyRowTracker.markDirty(s),this._eraseInBufferLine(s,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(s+1).isWrapped=!1);s--;)this._resetBufferLine(s,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(s=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,s-1);s--&&!((i=this._activeBuffer.lines.get(this._activeBuffer.ybase+s))!=null&&i.getTrimmedLength()););for(;s>=0;s--)this._bufferService.scroll(this._eraseAttrData())}else{for(s=this._bufferService.rows,this._dirtyRowTracker.markDirty(s-1);s--;)this._resetBufferLine(s,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let r=this._activeBuffer.lines.length-this._bufferService.rows;r>0&&(this._activeBuffer.lines.trimStart(r),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-r,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-r,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let s=this._activeBuffer.ybase+this._activeBuffer.y,i=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-i+1;for(;t--;)this._activeBuffer.lines.splice(r-1,1),this._activeBuffer.lines.splice(s,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let s=this._activeBuffer.ybase+this._activeBuffer.y,i;for(i=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-i;t--;)this._activeBuffer.lines.splice(s,1),this._activeBuffer.lines.splice(i,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(ye));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let s=this._activeBuffer.scrollTop;s<=this._activeBuffer.scrollBottom;++s){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+s);i.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),i.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let s=this._activeBuffer.scrollTop;s<=this._activeBuffer.scrollBottom;++s){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+s);i.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),i.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let s=this._activeBuffer.scrollTop;s<=this._activeBuffer.scrollBottom;++s){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+s);i.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),i.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let s=this._activeBuffer.scrollTop;s<=this._activeBuffer.scrollBottom;++s){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+s);i.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),i.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let s=e.params[0]||1,i=Pt.extractWidth(t),r=this._activeBuffer.x-i,n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(r),o=new Uint32Array(n.length*s),a=0;for(let l=0;l<n.length;){let c=n.codePointAt(l)||0;o[a++]=c,l+=c>65535?2:1}let h=a;for(let l=1;l<s;++l)o.copyWithin(h,0,a),h+=a;return this.print(o,0,h),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(v.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(v.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(v.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(v.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(v.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0;break}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,At),this._charsetService.setgCharset(1,At),this._charsetService.setgCharset(2,At),this._charsetService.setgCharset(3,At);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0;break}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1;break}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0);break}return!0}requestMode(e,t){(p=>(p[p.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",p[p.SET=1]="SET",p[p.RESET=2]="RESET",p[p.PERMANENTLY_SET=3]="PERMANENTLY_SET",p[p.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(void 0||(s={}));let i=this._coreService.decPrivateModes,{activeProtocol:r,activeEncoding:n}=this._coreMouseService,o=this._coreService,{buffers:a,cols:h}=this._bufferService,{active:l,alt:c}=a,d=this._optionsService.rawOptions,u=(p,g)=>(o.triggerDataEvent(`${v.ESC}[${t?"":"?"}${p};${g}$y`),!0),f=p=>p?1:2,_=e.params[0];return t?_===2?u(_,4):_===4?u(_,f(o.modes.insertMode)):_===12?u(_,3):_===20?u(_,f(d.convertEol)):u(_,0):_===1?u(_,f(i.applicationCursorKeys)):_===3?u(_,d.windowOptions.setWinLines?h===80?2:h===132?1:0:0):_===6?u(_,f(i.origin)):_===7?u(_,f(i.wraparound)):_===8?u(_,3):_===9?u(_,f(r==="X10")):_===12?u(_,f(d.cursorBlink)):_===25?u(_,f(!o.isCursorHidden)):_===45?u(_,f(i.reverseWraparound)):_===66?u(_,f(i.applicationKeypad)):_===67?u(_,4):_===1e3?u(_,f(r==="VT200")):_===1002?u(_,f(r==="DRAG")):_===1003?u(_,f(r==="ANY")):_===1004?u(_,f(i.sendFocus)):_===1005?u(_,4):_===1006?u(_,f(n==="SGR")):_===1015?u(_,4):_===1016?u(_,f(n==="SGR_PIXELS")):_===1048?u(_,1):_===47||_===1047||_===1049?u(_,f(l===c)):_===2004?u(_,f(i.bracketedPasteMode)):_===2026?u(_,f(i.synchronizedOutput)):u(_,0)}_updateAttrColor(e,t,s,i,r){return t===2?(e|=50331648,e&=-16777216,e|=xs.fromColorRGB([s,i,r])):t===5&&(e&=-50331904,e|=33554432|s&255),e}_extractColor(e,t,s){let i=[0,0,-1,0,0,0],r=0,n=0;do{if(i[n+r]=e.params[t+n],e.hasSubParams(t+n)){let o=e.getSubParams(t+n),a=0;do i[1]===5&&(r=1),i[n+a+1+r]=o[a];while(++a<o.length&&a+n+1+r<i.length);break}if(i[1]===5&&n+r>=2||i[1]===2&&n+r>=5)break;i[1]&&(r=1)}while(++n+t<e.length&&n+r<i.length);for(let o=2;o<i.length;++o)i[o]===-1&&(i[o]=0);switch(i[0]){case 38:s.fg=this._updateAttrColor(s.fg,i[1],i[3],i[4],i[5]);break;case 48:s.bg=this._updateAttrColor(s.bg,i[1],i[3],i[4],i[5]);break;case 58:s.extended=s.extended.clone(),s.extended.underlineColor=this._updateAttrColor(s.extended.underlineColor,i[1],i[3],i[4],i[5])}return n}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=ye.fg,e.bg=ye.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,s,i=this._curAttrData;for(let r=0;r<t;r++)s=e.params[r],s>=30&&s<=37?(i.fg&=-50331904,i.fg|=16777216|s-30):s>=40&&s<=47?(i.bg&=-50331904,i.bg|=16777216|s-40):s>=90&&s<=97?(i.fg&=-50331904,i.fg|=16777216|s-90|8):s>=100&&s<=107?(i.bg&=-50331904,i.bg|=16777216|s-100|8):s===0?this._processSGR0(i):s===1?i.fg|=134217728:s===3?i.bg|=67108864:s===4?(i.fg|=268435456,this._processUnderline(e.hasSubParams(r)?e.getSubParams(r)[0]:1,i)):s===5?i.fg|=536870912:s===7?i.fg|=67108864:s===8?i.fg|=1073741824:s===9?i.fg|=2147483648:s===2?i.bg|=134217728:s===21?this._processUnderline(2,i):s===22?(i.fg&=-134217729,i.bg&=-134217729):s===23?i.bg&=-67108865:s===24?(i.fg&=-268435457,this._processUnderline(0,i)):s===25?i.fg&=-536870913:s===27?i.fg&=-67108865:s===28?i.fg&=-1073741825:s===29?i.fg&=2147483647:s===39?(i.fg&=-67108864,i.fg|=ye.fg&16777215):s===49?(i.bg&=-67108864,i.bg|=ye.bg&16777215):s===38||s===48||s===58?r+=this._extractColor(e,r,i):s===53?i.bg|=1073741824:s===55?i.bg&=-1073741825:s===59?(i.extended=i.extended.clone(),i.extended.underlineColor=-1,i.updateExtended()):s===100?(i.fg&=-67108864,i.fg|=ye.fg&16777215,i.bg&=-67108864,i.bg|=ye.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",s);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${v.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,s=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${v.ESC}[${t};${s}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,s=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${v.ESC}[?${t};${s}R`);break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=ye.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let s=t%2===1;this._coreService.decPrivateModes.cursorBlink=s}return!0}setScrollRegion(e){let t=e.params[0]||1,s;return(e.length<2||(s=e.params[1])>this._bufferService.rows||s===0)&&(s=this._bufferService.rows),s>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=s-1,this._setCursor(0,0)),!0}windowOptions(e){if(!An(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${v.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>$n&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>$n&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],s=e.split(";");for(;s.length>1;){let i=s.shift(),r=s.shift();if(/^\d+$/.exec(i)){let n=parseInt(i);if(In(n))if(r==="?")t.push({type:0,index:n});else{let o=Tn(r);o&&t.push({type:1,index:n,color:o})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let s=e.slice(0,t).trim(),i=e.slice(t+1);return i?this._createHyperlink(s,i):s.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let s=e.split(":"),i,r=s.findIndex(n=>n.startsWith("id="));return r!==-1&&(i=s[r].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:i,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let s=e.split(";");for(let i=0;i<s.length&&!(t>=this._specialColors.length);++i,++t)if(s[i]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=Tn(s[i]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],s=e.split(";");for(let i=0;i<s.length;++i)if(/^\d+$/.exec(s[i])){let r=parseInt(s[i]);In(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,At),!0}selectCharset(e){return e.length!==2?(this.selectDefaultCharset(),!0):(e[0]==="/"||this._charsetService.setgCharset(Sd[e[0]],ke[e[1]]||At),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=ye.clone(),this._eraseAttrDataInternal=ye.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new Ze;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let s=this._activeBuffer.ybase+this._activeBuffer.y+t,i=this._activeBuffer.lines.get(s);i&&(i.fill(e),i.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let s=o=>(this._coreService.triggerDataEvent(`${v.ESC}${o}${v.ESC}\\`),!0),i=this._bufferService.buffer,r=this._optionsService.rawOptions;return s(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${i.scrollTop+1};${i.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[r.cursorStyle]-(r.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},vr=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Nn=e,e=t,t=Nn),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};vr=pe([$(0,He)],vr);function In(e){return 0<=e&&e<256}var wd=5e7,On=12,bd=50,Cd=class extends Y{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new x),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let s;for(;s=this._writeBuffer.shift();){this._action(s);let i=this._callbacks.shift();i&&i()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>wd)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let s=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let i=this._writeBuffer[this._bufferOffset],r=this._action(i,t);if(r){let o=a=>performance.now()-s>=On?setTimeout(()=>this._innerWrite(0,a)):this._innerWrite(s,a);r.catch(a=>(queueMicrotask(()=>{throw a}),Promise.resolve(!1))).then(o);return}let n=this._callbacks[this._bufferOffset];if(n&&n(),this._bufferOffset++,this._pendingData-=i.length,performance.now()-s>=On)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>bd&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},Sr=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let a=t.addMarker(t.ybase+t.y),h={data:e,id:this._nextId++,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(h,a)),this._dataByLinkId.set(h.id,h),h.id}let s=e,i=this._getEntryIdKey(s),r=this._entriesWithId.get(i);if(r)return this.addLineToLink(r.id,t.ybase+t.y),r.id;let n=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(s),data:s,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(o,n)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let s=this._dataByLinkId.get(e);if(s&&s.lines.every(i=>i.line!==t)){let i=this._bufferService.buffer.addMarker(t);s.lines.push(i),i.onDispose(()=>this._removeMarkerFromLink(s,i))}}getLinkData(e){var t;return(t=this._dataByLinkId.get(e))==null?void 0:t.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let s=e.lines.indexOf(t);s!==-1&&(e.lines.splice(s,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};Sr=pe([$(0,He)],Sr);var Hn=!1,xd=class extends Y{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new Zt),this._onBinary=this._register(new x),this.onBinary=this._onBinary.event,this._onData=this._register(new x),this.onData=this._onData.event,this._onLineFeed=this._register(new x),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new x),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new x),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new x),this._instantiationService=new Gc,this.optionsService=this._register(new rd(e)),this._instantiationService.setService(Fe,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(fr)),this._instantiationService.setService(He,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(_r)),this._instantiationService.setService(Ko,this._logService),this.coreService=this._register(this._instantiationService.createInstance(pr)),this._instantiationService.setService(Ht,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(mr)),this._instantiationService.setService(jo,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Pt)),this._instantiationService.setService(jl,this.unicodeService),this._charsetService=this._instantiationService.createInstance(hd),this._instantiationService.setService(Ul,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Sr),this._instantiationService.setService(qo,this._oscLinkService),this._inputHandler=this._register(new yd(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Te.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Te.forward(this._bufferService.onResize,this._onResize)),this._register(Te.forward(this.coreService.onData,this._onData)),this._register(Te.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new Cd((t,s)=>this._inputHandler.parse(t,s))),this._register(Te.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new x),this._onScroll.event(e=>{var t;(t=this._onScrollApi)==null||t.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!Hn&&(this._logService.warn("writeSync is unreliable and will be removed soon."),Hn=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,xa),t=Math.max(t,ka),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Mn.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Mn(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ae(()=>{for(let t of e)t.dispose()})}}},kd={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function Ed(e,t,s,i){var o;let r={type:0,cancel:!1,key:void 0},n=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?r.key=v.ESC+"OA":r.key=v.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?r.key=v.ESC+"OD":r.key=v.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?r.key=v.ESC+"OC":r.key=v.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?r.key=v.ESC+"OB":r.key=v.ESC+"[B");break;case 8:r.key=e.ctrlKey?"\b":v.DEL,e.altKey&&(r.key=v.ESC+r.key);break;case 9:if(e.shiftKey){r.key=v.ESC+"[Z";break}r.key=v.HT,r.cancel=!0;break;case 13:r.key=e.altKey?v.ESC+v.CR:v.CR,r.cancel=!0;break;case 27:r.key=v.ESC,e.altKey&&(r.key=v.ESC+v.ESC),r.cancel=!0;break;case 37:if(e.metaKey)break;n?r.key=v.ESC+"[1;"+(n+1)+"D":t?r.key=v.ESC+"OD":r.key=v.ESC+"[D";break;case 39:if(e.metaKey)break;n?r.key=v.ESC+"[1;"+(n+1)+"C":t?r.key=v.ESC+"OC":r.key=v.ESC+"[C";break;case 38:if(e.metaKey)break;n?r.key=v.ESC+"[1;"+(n+1)+"A":t?r.key=v.ESC+"OA":r.key=v.ESC+"[A";break;case 40:if(e.metaKey)break;n?r.key=v.ESC+"[1;"+(n+1)+"B":t?r.key=v.ESC+"OB":r.key=v.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(r.key=v.ESC+"[2~");break;case 46:n?r.key=v.ESC+"[3;"+(n+1)+"~":r.key=v.ESC+"[3~";break;case 36:n?r.key=v.ESC+"[1;"+(n+1)+"H":t?r.key=v.ESC+"OH":r.key=v.ESC+"[H";break;case 35:n?r.key=v.ESC+"[1;"+(n+1)+"F":t?r.key=v.ESC+"OF":r.key=v.ESC+"[F";break;case 33:e.shiftKey?r.type=2:e.ctrlKey?r.key=v.ESC+"[5;"+(n+1)+"~":r.key=v.ESC+"[5~";break;case 34:e.shiftKey?r.type=3:e.ctrlKey?r.key=v.ESC+"[6;"+(n+1)+"~":r.key=v.ESC+"[6~";break;case 112:n?r.key=v.ESC+"[1;"+(n+1)+"P":r.key=v.ESC+"OP";break;case 113:n?r.key=v.ESC+"[1;"+(n+1)+"Q":r.key=v.ESC+"OQ";break;case 114:n?r.key=v.ESC+"[1;"+(n+1)+"R":r.key=v.ESC+"OR";break;case 115:n?r.key=v.ESC+"[1;"+(n+1)+"S":r.key=v.ESC+"OS";break;case 116:n?r.key=v.ESC+"[15;"+(n+1)+"~":r.key=v.ESC+"[15~";break;case 117:n?r.key=v.ESC+"[17;"+(n+1)+"~":r.key=v.ESC+"[17~";break;case 118:n?r.key=v.ESC+"[18;"+(n+1)+"~":r.key=v.ESC+"[18~";break;case 119:n?r.key=v.ESC+"[19;"+(n+1)+"~":r.key=v.ESC+"[19~";break;case 120:n?r.key=v.ESC+"[20;"+(n+1)+"~":r.key=v.ESC+"[20~";break;case 121:n?r.key=v.ESC+"[21;"+(n+1)+"~":r.key=v.ESC+"[21~";break;case 122:n?r.key=v.ESC+"[23;"+(n+1)+"~":r.key=v.ESC+"[23~";break;case 123:n?r.key=v.ESC+"[24;"+(n+1)+"~":r.key=v.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?r.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?r.key=v.NUL:e.keyCode>=51&&e.keyCode<=55?r.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?r.key=v.DEL:e.keyCode===219?r.key=v.ESC:e.keyCode===220?r.key=v.FS:e.keyCode===221&&(r.key=v.GS);else if((!s||i)&&e.altKey&&!e.metaKey){let a=(o=kd[e.keyCode])==null?void 0:o[e.shiftKey?1:0];if(a)r.key=v.ESC+a;else if(e.keyCode>=65&&e.keyCode<=90){let h=e.ctrlKey?e.keyCode-64:e.keyCode+32,l=String.fromCharCode(h);e.shiftKey&&(l=l.toUpperCase()),r.key=v.ESC+l}else if(e.keyCode===32)r.key=v.ESC+(e.ctrlKey?v.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let h=e.code.slice(3,4);e.shiftKey||(h=h.toLowerCase()),r.key=v.ESC+h,r.cancel=!0}}else s&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(r.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?r.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(r.key=v.US),e.key==="@"&&(r.key=v.NUL));break}return r}var ge=0,Rd=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new oi,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new oi,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((r,n)=>this._getKey(r)-this._getKey(n)),t=0,s=0,i=new Array(this._array.length+this._insertedValues.length);for(let r=0;r<i.length;r++)s>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[s])?(i[r]=e[t],t++):i[r]=this._array[s++];this._array=i,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(ge=this._search(t),ge===-1)||this._getKey(this._array[ge])!==t)return!1;do if(this._array[ge]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(ge),!0;while(++ge<this._array.length&&this._getKey(this._array[ge])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((r,n)=>r-n),t=0,s=new Array(this._array.length-e.length),i=0;for(let r=0;r<this._array.length;r++)e[t]===r?t++:s[i++]=this._array[r];this._array=s,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(ge=this._search(e),!(ge<0||ge>=this._array.length)&&this._getKey(this._array[ge])===e))do yield this._array[ge];while(++ge<this._array.length&&this._getKey(this._array[ge])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(ge=this._search(e),!(ge<0||ge>=this._array.length)&&this._getKey(this._array[ge])===e))do t(this._array[ge]);while(++ge<this._array.length&&this._getKey(this._array[ge])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,s=this._array.length-1;for(;s>=t;){let i=t+s>>1,r=this._getKey(this._array[i]);if(r>e)s=i-1;else if(r<e)t=i+1;else{for(;i>0&&this._getKey(this._array[i-1])===e;)i--;return i}}return t}},Ri=0,Fn=0,Bd=class extends Y{constructor(){super(),this._decorations=new Rd(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new x),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new x),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(ae(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new Ld(e);if(t){let s=t.marker.onDispose(()=>t.dispose()),i=t.onDispose(()=>{i.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),s.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,s){let i=0,r=0;for(let n of this._decorations.getKeyIterator(t))i=n.options.x??0,r=i+(n.options.width??1),e>=i&&e<r&&(!s||(n.options.layer??"bottom")===s)&&(yield n)}forEachDecorationAtCell(e,t,s,i){this._decorations.forEachByKey(t,r=>{Ri=r.options.x??0,Fn=Ri+(r.options.width??1),e>=Ri&&e<Fn&&(!s||(r.options.layer??"bottom")===s)&&i(r)})}},Ld=class extends Et{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new x),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new x),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=he.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=he.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},Md=1e3,Dd=class{constructor(e,t=Md){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,s){this._rowCount=s,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t;let i=performance.now();if(i-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=i,this._innerRefresh();else if(!this._additionalRefreshRequested){let r=i-this._lastRefreshMs,n=this._debounceThresholdMS-r;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},n)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Wn=20,ai=class extends Y{constructor(e,t,s,i){super(),this._terminal=e,this._coreBrowserService=s,this._renderService=i,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let r=this._coreBrowserService.mainDocument;this._accessibilityContainer=r.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=r.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let n=0;n<this._terminal.rows;n++)this._rowElements[n]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[n]);if(this._topBoundaryFocusListener=n=>this._handleBoundaryFocus(n,0),this._bottomBoundaryFocusListener=n=>this._handleBoundaryFocus(n,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=r.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new Dd(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(n=>this._handleResize(n.rows))),this._register(this._terminal.onRender(n=>this._refreshRows(n.start,n.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(n=>this._handleChar(n))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
`))),this._register(this._terminal.onA11yTab(n=>this._handleTab(n))),this._register(this._terminal.onKey(n=>this._handleKey(n.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(j(r,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(ae(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<Wn+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Wn+1&&(this._liveRegion.textContent+=Hi.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let s=this._terminal.buffer,i=s.lines.length.toString();for(let r=e;r<=t;r++){let n=s.lines.get(s.ydisp+r),o=[],a=(n==null?void 0:n.translateToString(!0,void 0,void 0,o))||"",h=(s.ydisp+r+1).toString(),l=this._rowElements[r];l&&(a.length===0?(l.textContent=" ",this._rowColumns.set(l,[0,1])):(l.textContent=a,this._rowColumns.set(l,o)),l.setAttribute("aria-posinset",h),l.setAttribute("aria-setsize",i),this._alignRowWidth(l))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let s=e.target,i=this._rowElements[t===0?1:this._rowElements.length-2],r=s.getAttribute("aria-posinset"),n=t===0?"1":`${this._terminal.buffer.lines.length}`;if(r===n||e.relatedTarget!==i)return;let o,a;if(t===0?(o=s,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(o=this._rowElements.shift(),a=s,this._rowContainer.removeChild(o)),o.removeEventListener("focus",this._topBoundaryFocusListener),a.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let h=this._createAccessibilityTreeNode();this._rowElements.unshift(h),this._rowContainer.insertAdjacentElement("afterbegin",h)}else{let h=this._createAccessibilityTreeNode();this._rowElements.push(h),this._rowContainer.appendChild(h)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){var a;if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},s={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(s.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===s.node&&t.offset>s.offset)&&([t,s]=[s,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let i=this._rowElements.slice(-1)[0];if(s.node.compareDocumentPosition(i)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(s={node:i,offset:((a=i.textContent)==null?void 0:a.length)??0}),!this._rowContainer.contains(s.node))return;let r=({node:h,offset:l})=>{let c=h instanceof Text?h.parentNode:h,d=parseInt(c==null?void 0:c.getAttribute("aria-posinset"),10)-1;if(isNaN(d))return console.warn("row is invalid. Race condition?"),null;let u=this._rowColumns.get(c);if(!u)return console.warn("columns is null. Race condition?"),null;let f=l<u.length?u[l]:u.slice(-1)[0]+1;return f>=this._terminal.cols&&(++d,f=0),{row:d,column:f}},n=r(t),o=r(s);if(!(!n||!o)){if(n.row>o.row||n.row===o.row&&n.column>=o.column)throw new Error("invalid range");this._terminal.select(n.column,n.row,(o.row-n.row)*this._terminal.cols-n.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;t<this._terminal.rows;t++)this._rowElements[t]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[t]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){var r,n;e.style.transform="";let t=e.getBoundingClientRect().width,s=(n=(r=this._rowColumns.get(e))==null?void 0:r.slice(-1))==null?void 0:n[0];if(!s)return;let i=s*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${i/t})`}};ai=pe([$(1,Rr),$(2,pt),$(3,mt)],ai);var yr=class extends Y{constructor(e,t,s,i,r){super(),this._element=e,this._mouseService=t,this._renderService=s,this._bufferService=i,this._linkProviderService=r,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new x),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new x),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(ae(()=>{var n;It(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(n=this._activeProviderReplies)==null||n.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(j(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(j(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(j(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(j(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let s=e.composedPath();for(let i=0;i<s.length;i++){let r=s[i];if(r.classList.contains("xterm"))break;if(r.classList.contains("xterm-hover"))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){if(this._activeLine!==e.y||this._wasResized){this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1;return}this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){var i,r;(!this._activeProviderReplies||!t)&&((i=this._activeProviderReplies)==null||i.forEach(n=>{n==null||n.forEach(o=>{o.link.dispose&&o.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let s=!1;for(let[n,o]of this._linkProviderService.linkProviders.entries())t?(r=this._activeProviderReplies)!=null&&r.get(n)&&(s=this._checkLinkProviderResult(n,e,s)):o.provideLinks(e.y,a=>{var l,c;if(this._isMouseOut)return;let h=a==null?void 0:a.map(d=>({link:d}));(l=this._activeProviderReplies)==null||l.set(n,h),s=this._checkLinkProviderResult(n,e,s),((c=this._activeProviderReplies)==null?void 0:c.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let s=new Set;for(let i=0;i<t.size;i++){let r=t.get(i);if(r)for(let n=0;n<r.length;n++){let o=r[n],a=o.link.range.start.y<e?0:o.link.range.start.x,h=o.link.range.end.y>e?this._bufferService.cols:o.link.range.end.x;for(let l=a;l<=h;l++){if(s.has(l)){r.splice(n--,1);break}s.add(l)}}}}_checkLinkProviderResult(e,t,s){var n;if(!this._activeProviderReplies)return s;let i=this._activeProviderReplies.get(e),r=!1;for(let o=0;o<e;o++)(!this._activeProviderReplies.has(o)||this._activeProviderReplies.get(o))&&(r=!0);if(!r&&i){let o=i.find(a=>this._linkAtPosition(a.link,t));o&&(s=!0,this._handleNewLink(o))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!s)for(let o=0;o<this._activeProviderReplies.size;o++){let a=(n=this._activeProviderReplies.get(o))==null?void 0:n.find(h=>this._linkAtPosition(h.link,t));if(a){s=!0,this._handleNewLink(a);break}}return s}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&Td(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,It(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>{var s,i;return(i=(s=this._currentLink)==null?void 0:s.state)==null?void 0:i.decorations.pointerCursor},set:s=>{var i;(i=this._currentLink)!=null&&i.state&&this._currentLink.state.decorations.pointerCursor!==s&&(this._currentLink.state.decorations.pointerCursor=s,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",s))}},underline:{get:()=>{var s,i;return(i=(s=this._currentLink)==null?void 0:s.state)==null?void 0:i.decorations.underline},set:s=>{var i,r,n;(i=this._currentLink)!=null&&i.state&&((n=(r=this._currentLink)==null?void 0:r.state)==null?void 0:n.decorations.underline)!==s&&(this._currentLink.state.decorations.underline=s,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,s))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(s=>{if(!this._currentLink)return;let i=s.start===0?0:s.start+1+this._bufferService.buffer.ydisp,r=this._bufferService.buffer.ydisp+1+s.end;if(this._currentLink.link.range.start.y>=i&&this._currentLink.link.range.end.y<=r&&(this._clearCurrentLink(i,r),this._lastMouseEvent)){let n=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);n&&this._askForLink(n,!1)}})))}_linkHover(e,t,s){var i;(i=this._currentLink)!=null&&i.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(s,t.text)}_fireUnderlineEvent(e,t){let s=e.range,i=this._bufferService.buffer.ydisp,r=this._createLinkUnderlineEvent(s.start.x-1,s.start.y-i-1,s.end.x,s.end.y-i-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(r)}_linkLeave(e,t,s){var i;(i=this._currentLink)!=null&&i.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(s,t.text)}_linkAtPosition(e,t){let s=e.range.start.y*this._bufferService.cols+e.range.start.x,i=e.range.end.y*this._bufferService.cols+e.range.end.x,r=t.y*this._bufferService.cols+t.x;return s<=r&&r<=i}_positionFromMouseEvent(e,t,s){let i=s.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(i)return{x:i[0],y:i[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,s,i,r){return{x1:e,y1:t,x2:s,y2:i,cols:this._bufferService.cols,fg:r}}};yr=pe([$(1,Br),$(2,mt),$(3,He),$(4,Go)],yr);function Td(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var $d=class extends xd{constructor(e={}){super(e),this._linkifier=this._register(new Zt),this.browser=_a,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Zt),this._onCursorMove=this._register(new x),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new x),this.onKey=this._onKey.event,this._onRender=this._register(new x),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new x),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new x),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new x),this.onBell=this._onBell.event,this._onFocus=this._register(new x),this._onBlur=this._register(new x),this._onA11yCharEmitter=this._register(new x),this._onA11yTabEmitter=this._register(new x),this._onWillOpen=this._register(new x),this._setup(),this._decorationService=this._instantiationService.createInstance(Bd),this._instantiationService.setService(ks,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(bc),this._instantiationService.setService(Go,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Wi)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh((t==null?void 0:t.start)??0,(t==null?void 0:t.end)??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(Te.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Te.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Te.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Te.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(ae(()=>{var t,s;this._customKeyEventHandler=void 0,(s=(t=this.element)==null?void 0:t.parentNode)==null||s.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let s,i="";switch(t.index){case 256:s="foreground",i="10";break;case 257:s="background",i="11";break;case 258:s="cursor",i="12";break;default:s="ansi",i="4;"+t.index}switch(t.type){case 0:let r=ne.toColorRGB(s==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[s]);this.coreService.triggerDataEvent(`${v.ESC}]${i};${vd(r)}${da.ST}`);break;case 1:if(s==="ansi")this._themeService.modifyColors(n=>n.ansi[t.index]=we.toColor(...t.color));else{let n=s;this._themeService.modifyColors(o=>o[n]=we.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(ai,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(v.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var e;return(e=this.textarea)==null?void 0:e.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(v.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let s=Math.min(this.buffer.x,this.cols-1),i=this._renderService.dimensions.css.cell.height,r=t.getWidth(s),n=this._renderService.dimensions.css.cell.width*r,o=this.buffer.y*this._renderService.dimensions.css.cell.height,a=s*this._renderService.dimensions.css.cell.width;this.textarea.style.left=a+"px",this.textarea.style.top=o+"px",this.textarea.style.width=n+"px",this.textarea.style.height=i+"px",this.textarea.style.lineHeight=i+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(j(this.element,"copy",t=>{this.hasSelection()&&Il(t,this._selectionService)}));let e=t=>Ol(t,this.textarea,this.coreService,this.optionsService);this._register(j(this.textarea,"paste",e)),this._register(j(this.element,"paste",e)),fa?this._register(j(this.element,"mousedown",t=>{t.button===2&&Xr(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(j(this.element,"contextmenu",t=>{Xr(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Nr&&this._register(j(this.element,"auxclick",t=>{t.button===1&&Ho(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(j(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(j(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(j(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(j(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(j(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(j(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(j(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){var r;if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),((r=this.element)==null?void 0:r.ownerDocument.defaultView)&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(j(this.screenElement,"mousemove",n=>this.updateCursorStyle(n))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let s=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Oi.get()),ga||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>s.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(yc,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(pt,this._coreBrowserService),this._register(j(this.textarea,"focus",n=>this._handleTextAreaFocus(n))),this._register(j(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(lr,this._document,this._helperContainer),this._instantiationService.setService(ci,this._charSizeService),this._themeService=this._instantiationService.createInstance(ur),this._instantiationService.setService(es,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(ri),this._instantiationService.setService(Vo,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(cr,this.rows,this.screenElement)),this._instantiationService.setService(mt,this._renderService),this._register(this._renderService.onRenderedViewportChange(n=>this._onRender.fire(n))),this.onResize(n=>this._renderService.resize(n.cols,n.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(nr,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(hr),this._instantiationService.setService(Br,this._mouseService);let i=this._linkifier.value=this._register(this._instantiationService.createInstance(yr,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(ir,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(n=>{super.scrollLines(n,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(dr,this.element,this.screenElement,i)),this._instantiationService.setService(ql,this._selectionService),this._register(this._selectionService.onRequestScrollLines(n=>this.scrollLines(n.amount,n.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(n=>this._renderService.handleSelectionChanged(n.start,n.end,n.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(n=>{this.textarea.value=n,this.textarea.focus(),this.textarea.select()})),this._register(Te.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var n;this._selectionService.refresh(),(n=this._viewport)==null||n.queueSync()})),this._register(this._instantiationService.createInstance(rr,this.screenElement)),this._register(j(this.element,"mousedown",n=>this._selectionService.handleMouseDown(n))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(ai,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",n=>this._handleScreenReaderModeOptionChange(n))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ii,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",n=>{!this._overviewRulerRenderer&&n&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ii,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(ar,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function s(n){var l,c,d,u,f;let o=e._mouseService.getMouseReportCoords(n,e.screenElement);if(!o)return!1;let a,h;switch(n.overrideType||n.type){case"mousemove":h=32,n.buttons===void 0?(a=3,n.button!==void 0&&(a=n.button<3?n.button:3)):a=n.buttons&1?0:n.buttons&4?1:n.buttons&2?2:3;break;case"mouseup":h=0,a=n.button<3?n.button:3;break;case"mousedown":h=1,a=n.button<3?n.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(n)===!1)return!1;let _=n.deltaY;if(_===0||e.coreMouseService.consumeWheelEvent(n,(u=(d=(c=(l=e._renderService)==null?void 0:l.dimensions)==null?void 0:c.device)==null?void 0:d.cell)==null?void 0:u.height,(f=e._coreBrowserService)==null?void 0:f.dpr)===0)return!1;h=_<0?0:1,a=4;break;default:return!1}return h===void 0||a===void 0||a>4?!1:e.coreMouseService.triggerMouseEvent({col:o.col,row:o.row,x:o.x,y:o.y,button:a,action:h,ctrl:n.ctrlKey,alt:n.altKey,shift:n.shiftKey})}let i={mouseup:null,wheel:null,mousedrag:null,mousemove:null},r={mouseup:n=>(s(n),n.buttons||(this._document.removeEventListener("mouseup",i.mouseup),i.mousedrag&&this._document.removeEventListener("mousemove",i.mousedrag)),this.cancel(n)),wheel:n=>(s(n),this.cancel(n,!0)),mousedrag:n=>{n.buttons&&s(n)},mousemove:n=>{n.buttons||s(n)}};this._register(this.coreMouseService.onProtocolChange(n=>{n?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(n)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),n&8?i.mousemove||(t.addEventListener("mousemove",r.mousemove),i.mousemove=r.mousemove):(t.removeEventListener("mousemove",i.mousemove),i.mousemove=null),n&16?i.wheel||(t.addEventListener("wheel",r.wheel,{passive:!1}),i.wheel=r.wheel):(t.removeEventListener("wheel",i.wheel),i.wheel=null),n&2?i.mouseup||(i.mouseup=r.mouseup):(this._document.removeEventListener("mouseup",i.mouseup),i.mouseup=null),n&4?i.mousedrag||(i.mousedrag=r.mousedrag):(this._document.removeEventListener("mousemove",i.mousedrag),i.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(j(t,"mousedown",n=>{if(n.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(n)))return s(n),i.mouseup&&this._document.addEventListener("mouseup",i.mouseup),i.mousedrag&&this._document.addEventListener("mousemove",i.mousedrag),this.cancel(n)})),this._register(j(t,"wheel",n=>{var o,a,h,l,c;if(!i.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(n)===!1)return!1;if(!this.buffer.hasScrollback){if(n.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(n,(l=(h=(a=(o=e._renderService)==null?void 0:o.dimensions)==null?void 0:a.device)==null?void 0:h.cell)==null?void 0:l.height,(c=e._coreBrowserService)==null?void 0:c.dpr)===0)return this.cancel(n,!0);let d=v.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(n.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(d,!0),this.cancel(n,!0)}}},{passive:!1}))}refresh(e,t){var s;(s=this._renderService)==null||s.refreshRows(e,t)}updateCursorStyle(e){var t;(t=this._selectionService)!=null&&t.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){Oo(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,s){this._selectionService.setSelection(e,t,s)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var e;(e=this._selectionService)==null||e.clearSelection()}selectAll(){var e;(e=this._selectionService)==null||e.selectAll()}selectLines(e,t){var s;(s=this._selectionService)==null||s.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let s=Ed(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),s.type===3||s.type===2){let i=this.rows-1;return this.scrollLines(s.type===2?-i:i),this.cancel(e,!0)}if(s.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(s.cancel&&this.cancel(e,!0),!s.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((s.key===v.ETX||s.key===v.CR)&&(this.textarea.value=""),this._onKey.fire({key:s.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(s.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let s=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?s:s&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(Ad(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){var s;(s=this._charSizeService)==null||s.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(ye));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){var t;this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),(t=this._selectionService)==null||t.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){var e;(e=this._renderService)==null||e.clearTextureAtlas()}_reportFocus(){var e;(e=this.element)!=null&&e.classList.contains("focus")?this.coreService.triggerDataEvent(v.ESC+"[I"):this.coreService.triggerDataEvent(v.ESC+"[O")}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let t=this._renderService.dimensions.css.canvas.width.toFixed(0),s=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${v.ESC}[4;${s};${t}t`);break;case 1:let i=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${v.ESC}[6;${r};${i}t`);break}}cancel(e,t){if(!(!this.options.cancelEvents&&!t))return e.preventDefault(),e.stopPropagation(),!1}};function Ad(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var Pd=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let s={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(s),t.dispose=()=>this._wrappedAddonDispose(s),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let s=0;s<this._addons.length;s++)if(this._addons[s]===e){t=s;break}if(t===-1)throw new Error("Could not dispose an addon that has not been loaded");e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},Nd=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new Ze)}translateToString(e,t,s){return this._line.translateToString(e,t,s)}},zn=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new Nd(t)}getNullCell(){return new Ze}},Id=class extends Y{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new x),this.onBufferChange=this._onBufferChange.event,this._normal=new zn(this._core.buffers.normal,"normal"),this._alternate=new zn(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},Od=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,s=>t(s.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(s,i)=>t(s,i.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},Hd=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},Fd=["cols","rows"],at=0,Wd=class extends Y{constructor(e){super(),this._core=this._register(new $d(e)),this._addonManager=this._register(new Pd),this._publicOptions={...this._core.options};let t=i=>this._core.options[i],s=(i,r)=>{this._checkReadonlyOptions(i),this._core.options[i]=r};for(let i in this._core.options){let r={get:t.bind(this,i),set:s.bind(this,i)};Object.defineProperty(this._publicOptions,i,r)}}_checkReadonlyOptions(e){if(Fd.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new Od(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new Hd(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new Id(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,s){this._verifyIntegers(e,t,s),this._core.select(e,t,s)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Oi.get()},set promptLabel(e){Oi.set(e)},get tooMuchOutput(){return Hi.get()},set tooMuchOutput(e){Hi.set(e)}}}_verifyIntegers(...e){for(at of e)if(at===1/0||isNaN(at)||at%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(at of e)if(at&&(at===1/0||isNaN(at)||at%1!==0||at<0))throw new Error("This API only accepts positive integers")}};/**
 * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
 * @license MIT
 *
 * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
 * @license MIT
 *
 * Originally forked from (with the author's permission):
 *   Fabrice Bellard's javascript vt100 for jslinux:
 *   http://bellard.org/jslinux/
 *   Copyright (c) 2011 Fabrice Bellard
 */var zd=2,Ud=1,jd=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){var d;if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:((d=this._terminal.options.overviewRuler)==null?void 0:d.width)||14,s=window.getComputedStyle(this._terminal.element.parentElement),i=parseInt(s.getPropertyValue("height")),r=Math.max(0,parseInt(s.getPropertyValue("width"))),n=window.getComputedStyle(this._terminal.element),o={top:parseInt(n.getPropertyValue("padding-top")),bottom:parseInt(n.getPropertyValue("padding-bottom")),right:parseInt(n.getPropertyValue("padding-right")),left:parseInt(n.getPropertyValue("padding-left"))},a=o.top+o.bottom,h=o.right+o.left,l=i-a,c=r-h-t;return{cols:Math.max(zd,Math.floor(c/e.css.cell.width)),rows:Math.max(Ud,Math.floor(l/e.css.cell.height))}}};/**
 * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
 * @license MIT
 *
 * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
 * @license MIT
 *
 * Originally forked from (with the author's permission):
 *   Fabrice Bellard's javascript vt100 for jslinux:
 *   http://bellard.org/jslinux/
 *   Copyright (c) 2011 Fabrice Bellard
 */var Kd=class{constructor(e,t,s,i={}){this._terminal=e,this._regex=t,this._handler=s,this._options=i}provideLinks(e,t){let s=Vd.computeLink(e,this._regex,this._terminal,this._handler);t(this._addCallbacks(s))}_addCallbacks(e){return e.map(t=>(t.leave=this._options.leave,t.hover=(s,i)=>{if(this._options.hover){let{range:r}=t;this._options.hover(s,i,r)}},t))}};function qd(e){try{let t=new URL(e),s=t.password&&t.username?`${t.protocol}//${t.username}:${t.password}@${t.host}`:t.username?`${t.protocol}//${t.username}@${t.host}`:`${t.protocol}//${t.host}`;return e.toLocaleLowerCase().startsWith(s.toLocaleLowerCase())}catch{return!1}}var Vd=class Gs{static computeLink(t,s,i,r){let n=new RegExp(s.source,(s.flags||"")+"g"),[o,a]=Gs._getWindowedLineStrings(t-1,i),h=o.join(""),l,c=[];for(;l=n.exec(h);){let d=l[0];if(!qd(d))continue;let[u,f]=Gs._mapStrIdx(i,a,0,l.index),[_,p]=Gs._mapStrIdx(i,u,f,d.length);if(u===-1||f===-1||_===-1||p===-1)continue;let g={start:{x:f+1,y:u+1},end:{x:p,y:_+1}};c.push({range:g,text:d,activate:r})}return c}static _getWindowedLineStrings(t,s){let i,r=t,n=t,o=0,a="",h=[];if(i=s.buffer.active.getLine(t)){let l=i.translateToString(!0);if(i.isWrapped&&l[0]!==" "){for(o=0;(i=s.buffer.active.getLine(--r))&&o<2048&&(a=i.translateToString(!0),o+=a.length,h.push(a),!(!i.isWrapped||a.indexOf(" ")!==-1)););h.reverse()}for(h.push(l),o=0;(i=s.buffer.active.getLine(++n))&&i.isWrapped&&o<2048&&(a=i.translateToString(!0),o+=a.length,h.push(a),a.indexOf(" ")===-1););}return[h,r]}static _mapStrIdx(t,s,i,r){let n=t.buffer.active,o=n.getNullCell(),a=i;for(;r;){let h=n.getLine(s);if(!h)return[-1,-1];for(let l=a;l<h.length;++l){h.getCell(l,o);let c=o.getChars();if(o.getWidth()&&(r-=c.length||1,l===h.length-1&&c==="")){let d=n.getLine(s+1);d&&d.isWrapped&&(d.getCell(0,o),o.getWidth()===2&&(r+=1))}if(r<0)return[s,l]}s++,a=0}return[s,a]}},Gd=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function Yd(e,t){let s=window.open();if(s){try{s.opener=null}catch{}s.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}var Xd=class{constructor(t=Yd,s={}){this._handler=t,this._options=s}activate(t){this._terminal=t;let s=this._options,i=s.urlRegex||Gd;this._linkProvider=this._terminal.registerLinkProvider(new Kd(this._terminal,i,this._handler,s))}dispose(){var t;(t=this._linkProvider)==null||t.dispose()}};class Jd{constructor(){D(this,"commands",[])}register(...t){this.commands.push(...t)}find(t){let s;for(const i of this.commands)i.matches(t)&&(!s||i.name.length>s.name.length)&&(s=i);return s}all(){return this.commands}}class ie{constructor(){D(this,"aliases",[]);D(this,"params")}matches(t){const s=t.toLowerCase().trim(),i=r=>s===r||s.startsWith(r+" ");return i(this.name)||this.aliases.some(i)}argsAfterName(t){const s=t.toLowerCase().trim(),i=[this.name,...this.aliases].sort((r,n)=>n.length-r.length);for(const r of i)if(s.startsWith(r))return t.trim().slice(r.length).trim();return t.trim()}}const Qe="\x1B[",se=`${Qe}0m`,Rt=`${Qe}1m`,Zd=`${Qe}2m`,Qd=`${Qe}3m`,_i=`${Qe}32m`,Qt=`${Qe}31m`,Bs=`${Qe}33m`,Ra=`${Qe}36m`,Ls=`${Qe}34m`,Ft=`${Qe}90m`,eu=`${Qe}92m`,tu=`${Qe}96m`;function Un(e,t){switch(t){case"success":return`${_i}${e}${se}`;case"error":return`${Qt}${e}${se}`;case"warning":return`${Bs}${e}${se}`;case"info":return`${Ra}${e}${se}`;case"value":return`${Ls}${e}${se}`;case"system":return`${Ft}${e}${se}`;default:return e}}function st(e){return`${Rt}${e}${se}`}function Pe(e){return`${Zd}${e}${se}`}function su(e){return`${Bs}${e}${se}`}function y(e){return`${Ls}${e}${se}`}function w(e){return`${Ft}${e}${se}`}function b(e,t){return`${Ft}${e}: ${se}${Ls}${Rt}${t}${se}`}function B(e,t,s=22){const i=e.split(" "),r=i[0];let n=Ra;r==="get"?n=_i:r==="set"&&(n=Bs);const o=i.length>1?`${n}${Rt}${r}${se} ${Ls}${i.slice(1).join(" ")}${se}`:`${n}${Rt}${e}${se}`,a=" ".repeat(Math.max(1,s-e.length));return`  ${o}${a}${Ft}${t}${se}`}function z(e){return`${Rt}${Ls}${e}${se}`}function it(e){return`${Ft}${Qd}${e}${se}`}function iu(e){return`\x1B[1;92m${e||"user"}@openhop${se}: \x1B[38;2;91;91;214m$${se} `}function Bi(e){return`${Qt}${Rt}●${se} ${Ft}${e}${se}`}function ru(e){return e<1500?eu:e<4e3?_i:e<8e3?Bs:e<15e3?Qt:`${Qt}${Rt}`}function nu(e){const t=e<1e3?`${e.toFixed(0)}ms`:`${(e/1e3).toFixed(1)}s`;return`${ru(e)}${t}${se}`}function Ir(e){switch(e){case"excellent":return tu;case"good":return _i;case"fair":return Bs;case"poor":return Qt;case"critical":return`${Qt}${Rt}`;default:return Ft}}function ou(e,t){return`${Ir(t)}${e}${se}`}function jn(e){return e.replace(/[\p{Emoji_Presentation}\p{Extended_Pictographic}\uFE0F\u200D]/gu,"").trim()}const Fs="\x1B[2K\r";function au(e=1){return`\x1B[${e}A`}const lu="\x1B[K",hu="\x1B[H",cu="\x1B[J",du="\x1B[?1049h",Kn="\x1B[?1049l",uu="\x1B[?25l",qn="\x1B[?25h";function Ba(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function _u(e){return Ba(e).length}function wr(e,t){let s=0;for(const i of e){const r=Ba(i).length;s+=r===0?1:Math.ceil(r/t)}return s}function fu(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function et(e,t){return fu(e)||t}function pu(){return document.documentElement.dataset.mode==="light"}function La(){const e=pu(),t=et("--terminal-bg","#0d0d0d"),s=et("--sys-blue",ve.blue);if(e){const f="#EFF0F1";return{background:f,foreground:"#111314",cursor:ve.blue,cursorAccent:f,selectionBackground:`${ve.blue}30`,selectionForeground:"#111314",black:"#111314",red:ve.red,green:ve.green,yellow:ve.amber,blue:ve.blue,magenta:ve.purple,cyan:ve.cyan,white:f,brightBlack:is[500],brightRed:ve.red,brightGreen:ve.green,brightYellow:ve.orange,brightBlue:ve.indigo,brightMagenta:ve.pink,brightCyan:ve.teal,brightWhite:is[600]}}const i=et("--text-primary","#e0e0e0"),r=s+"40",n=et("--sys-red",ve.red),o=et("--sys-green",ve.green),a=et("--sys-purple",ve.purple),h=et("--sys-blue",ve.blue),l=et("--sys-cyan",ve.cyan),c=et("--text-muted",is[500]),d=et("--text-secondary",is[400]),u=et("--bg-surface",is[900]);return{background:t,foreground:i,cursor:s,cursorAccent:t,selectionBackground:r,selectionForeground:i,black:u,red:n,green:o,yellow:a,blue:h,magenta:a,cyan:l,white:i,brightBlack:c,brightRed:n,brightGreen:"#4ADE80",brightYellow:a,brightBlue:h,brightMagenta:a,brightCyan:l,brightWhite:d}}function mu(e){return Ka.subscribe(()=>{e.options.theme=La()})}const Ms="\x1B[",Bt=`${Ms}0m`,gu=`${Ms}1m`,vu=`${Ms}2m`,Ma=`${Ms}34m`,Ds=`${Ms}90m`,Li=24,Mi=13,Vn="  ",Gn="        ",Su=[{label:"INFORMATION",entries:[{cmd:"status",desc:"Repeater status summary",alias:"st"},{cmd:"top",desc:"Live system overview (Ctrl+C to exit)",alias:"htop"},{cmd:"ver",desc:"Version info",alias:"version"},{cmd:"clock",desc:"System UTC time"},{cmd:"uptime",desc:"System uptime"},{cmd:"board",desc:"Board / platform info"},{cmd:"packets",desc:"Packet statistics"},{cmd:"stats-packets",desc:"Packet counters (firmware compat)"},{cmd:"stats-radio",desc:"Radio health stats (firmware compat)"},{cmd:"stats-core",desc:"Engine vitals (firmware compat)"}]},{label:"NETWORK",entries:[{cmd:"neighbors [sort]",desc:"Direct RF neighbors",alias:"nb",sub:"sig · name · rssi · snr · dist · heard"},{cmd:"ping {name}",desc:"Ping neighbor (name or 0xXX)"},{cmd:"identities",desc:"List configured identities",alias:"id ids"},{cmd:"keys",desc:"Transport keys"},{cmd:"acl",desc:"ACL statistics"},{cmd:"rooms",desc:"Room statistics"}]},{label:"RADIO",entries:[{cmd:"get {param}",desc:"Read parameter"},{cmd:"set {param} {value}",desc:"Write parameter"},{cmd:"advert",desc:"Send advertisement"}]},{label:"SYSTEM",entries:[{cmd:"restart",desc:"Restart service",alias:"reboot"},{cmd:"start cap [seconds]",desc:"Start packet capture"},{cmd:"end cap",desc:"Stop capture"},{cmd:"list cap",desc:"List captures"},{cmd:"export cap [id]",desc:"Download capture"}]},{label:"TOOLS",entries:[{cmd:"convert hex {value}",desc:"Hex → base64"},{cmd:"convert base64 {value}",desc:"Base64 → hex"},{cmd:"clear",desc:"Clear terminal",alias:"cls"},{cmd:"help [command]",desc:"Show this help",alias:"? h"}]}],yu=[{cat:"Identity",params:["name","role","lat","lon","public.key"]},{cat:"Radio",params:["radio","freq","tx","bw","sf","cr"]},{cat:"Timing",params:["txdelay","direct.txdelay","rxdelay"]},{cat:"Repeater",params:["mode","duty","repeat","flood.max","advert.interval"]},{cat:"Advanced",params:["multi.acks","int.thresh","agc.reset.interval"]},{cat:"set only",params:["log","prv.key"]}];function Da(e){return`${Ds}${"─".repeat(e)}${Bt}`}function wu(e){const t="openhop console",s="terminal",i=Math.max(3,e-t.length-s.length-6);return`  ${Ma}${gu}${t}${Bt} ${Da(i)} ${Ds}${s}${Bt}`}function Ta(e){return`  ${Ds}${e}${Bt}`}function bu(e,t){const s=[],i=e.alias?`  ${vu}${e.alias}${Bt}`:"";return 4+Math.max(e.cmd.length,Li)+e.desc.length+(e.alias?2+e.alias.length:0)<=t?s.push(Vn+B(e.cmd,e.desc,Li)+i):(s.push(Vn+B(e.cmd,"",Li)),s.push(Gn+w(e.desc)+i)),e.sub&&s.push(`${Gn}${Pe("└ "+e.sub)}`),s}function Yn(e){return e.split(" · ").map(t=>`${Ma}${t}${Bt}`).join(`${Ds} · ${Bt}`)}function Cu(e,t){const i=[];let r=[],n=0;for(const o of e){const a=r.length>0?3+o.length:o.length;n+a>t&&r.length>0?(i.push(r),r=[o],n=o.length):(r.push(o),n+=a)}return r.length>0&&i.push(r),i}function xu(e){const t=["",Ta("GET/SET QUALIFIERS")],s=Math.max(20,e-4-Mi);for(const i of yu){const r=`${Ds}${i.cat.padEnd(Mi)}${Bt}`,n=Cu(i.params,s),o=" ".repeat(4+Mi);t.push(`    ${r}${Yn(n[0].join(" · "))}`);for(let a=1;a<n.length;a++)t.push(`${o}${Yn(n[a].join(" · "))}`)}return t}function ku(e){const t=Math.min(e-4,56);return[`  ${Da(t)}`,`  ${it("<command> help for detailed usage")}`]}class Eu extends ie{constructor(s){super();D(this,"name","help");D(this,"description","Show available commands");D(this,"aliases",["?","h"]);this.registry=s}execute({output:s,rawInput:i,cols:r}){const n=this.argsAfterName(i).toLowerCase().trim();if(n&&n!=="help"){const a=this.registry.find(n+" help")||this.registry.find(n);if(a){a.execute({output:s,rawInput:a.name+" help",args:[a.name,"help"],cols:r,signal:new AbortController().signal});return}s.write(`Unknown command: ${y(n)}`,"warning");return}const o=[wu(r),""];for(const a of Su){o.push(Ta(a.label));for(const h of a.entries)o.push(...bu(h,r));a.label==="RADIO"&&o.push(...xu(r)),o.push("")}o.push(...ku(r)),s.write(o.join(`
`))}}class Ru extends ie{constructor(){super(...arguments);D(this,"name","clear");D(this,"description","Clear terminal screen");D(this,"aliases",["cls"])}execute({output:s,rawInput:i}){if(this.argsAfterName(i).toLowerCase().trim()==="help"){s.write([z("clear"),`  ${w("Clear all terminal output.")}`,"",B("clear","clear the screen"),"",z("Aliases"),`  ${w("cls")}`].join(`
`));return}s.clear()}}function Or(e){const t=Math.floor(e/86400),s=Math.floor(e%86400/3600),i=Math.floor(e%3600/60);return t>0?`${t}d ${s}h ${i}m`:s>0?`${s}h ${i}m`:`${i}m`}class Bu extends ie{constructor(){super(...arguments);D(this,"name","status");D(this,"description","Get repeater status summary");D(this,"aliases",["st"])}async execute({output:s,rawInput:i}){var n,o,a;if(this.argsAfterName(i).toLowerCase().trim()==="help"){s.write([z("status"),`  ${w("Show a quick summary of mode, neighbor count, and uptime.")}`,"",B("status","show summary"),"",z("Aliases"),`  ${w("st")}`].join(`
`));return}const r=s.write("processing...","system");try{const h=await rt(),l=((o=(n=h.config)==null?void 0:n.repeater)==null?void 0:o.mode)||"unknown",c=Object.keys(h.neighbors||{}).length,d=Object.values(h.neighbors||{}).filter(_=>_.zero_hop).length,u=((a=h.config)==null?void 0:a.node_name)||h.node_name||"unknown",f=Or(h.uptime_seconds||0);s.update(r,[`${st(u)}  ${w("repeater")}`,"",`  ${b("Mode",y(l))}`,`  ${b("Neighbors",`${y(String(d))} direct  ${w(`${c} total`)}`)}`,`  ${b("RX / TX",`${y(String(h.rx_count??0))} / ${y(String(h.tx_count??0))}`)}`,`  ${b("Uptime",y(f))}`].join(`
`))}catch(h){s.update(r,`Error: ${h instanceof Error?h.message:"Command failed"}`,"error")}}}class Lu extends ie{constructor(){super(...arguments);D(this,"name","uptime");D(this,"description","Show system uptime")}async execute({output:s,rawInput:i}){if(this.argsAfterName(i).toLowerCase().trim()==="help"){s.write([z("uptime"),`  ${w("Display how long the repeater service has been running.")}`,"",B("uptime","show uptime")].join(`
`));return}const r=s.write("processing...","system");try{const n=await rt();s.update(r,b("Uptime",y(Or(n.uptime_seconds||0))))}catch(n){s.update(r,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}class Mu extends ie{constructor(){super(...arguments);D(this,"name","packets");D(this,"description","Show packet statistics")}async execute({output:s,rawInput:i}){if(this.argsAfterName(i).toLowerCase().trim()==="help"){s.write([z("packets"),`  ${w("Display packet counters (received, transmitted, forwarded, dropped).")}`,"",B("packets","show packet stats")].join(`
`));return}const r=s.write("processing...","system");try{const n=await rt(),o=(n.rx_count??0)+(n.tx_count??0);s.update(r,[z("Packet Stats")+`  ${w(`${o} total`)}`,"",`  ${b("Received",y(String(n.rx_count??0)))}`,`  ${b("Transmitted",y(String(n.tx_count??0)))}`,`  ${b("Forwarded",y(String(n.forwarded_count??0)))}`,`  ${b("Dropped",y(String(n.dropped_count??0)))}`].join(`
`))}catch(n){s.update(r,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}function Kt(e){return e>=1073741824?`${(e/1073741824).toFixed(1)} GB`:e>=1048576?`${(e/1048576).toFixed(0)} MB`:`${(e/1024).toFixed(0)} KB`}function Di(e){const t=Math.floor(e/86400),s=Math.floor(e%86400/3600),i=Math.floor(e%3600/60);return t>0?`${t}d ${s}h ${i}m`:s>0?`${s}h ${i}m`:`${i}m`}class Du extends ie{constructor(){super(...arguments);D(this,"name","board");D(this,"description","Show board/platform info")}async execute({output:s,rawInput:i}){var n;if(this.argsAfterName(i).toLowerCase().trim()==="help"){s.write([z("board"),`  ${w("Display platform and hardware information.")}`,"",B("board","show board info")].join(`
`));return}const r=s.write("loading...","system");try{const[o,a]=await Promise.all([ei(),rt()]),h=[];if(h.push(`  ${b("Node",y(a.node_name||"Unknown"))}`),h.push(`  ${b("Runtime",y(`pyMC_Repeater v${a.version||"?"}`))}`),a.core_version&&h.push(`  ${b("Core",y(a.core_version))}`),h.push(""),o.success&&o.data){const l=o.data;h.push(`  ${b("CPU",y(`${l.cpu.usage_percent.toFixed(1)}%`))}  ${w(`${l.cpu.count} core${l.cpu.count>1?"s":""}`)}`),l.cpu.load_avg&&h.push(`  ${b("Load",y(`${l.cpu.load_avg["1min"].toFixed(2)} / ${l.cpu.load_avg["5min"].toFixed(2)} / ${l.cpu.load_avg["15min"].toFixed(2)}`))}`);const c=Object.entries(l.temperatures||{});if(c.length>0){const d=c[0];h.push(`  ${b("Temp",y(`${d[1].toFixed(1)}°C`))}${c.length>1?`  ${w(c.slice(1).map(([u,f])=>`${u}: ${f.toFixed(1)}°C`).join(", "))}`:""}`)}h.push(""),h.push(`  ${b("Memory",y(`${Kt(l.memory.used)} / ${Kt(l.memory.total)}`))}  ${w(`${l.memory.usage_percent.toFixed(0)}%`)}`),h.push(`  ${b("Disk",y(`${Kt(l.disk.used)} / ${Kt(l.disk.total)}`))}  ${w(`${l.disk.usage_percent.toFixed(0)}%`)}`),h.push(""),(n=l.system)!=null&&n.uptime&&h.push(`  ${b("System uptime",y(Di(l.system.uptime)))}`),h.push(`  ${b("Service uptime",y(Di(a.uptime_seconds)))}`),l.network&&h.push(`  ${b("Net TX/RX",y(`${Kt(l.network.bytes_sent)} / ${Kt(l.network.bytes_recv)}`))}`)}else h.push(`  ${b("Platform",y("Linux"))}`),h.push(`  ${b("Service uptime",y(Di(a.uptime_seconds)))}`),h.push(`  ${w("Hardware stats unavailable")}`);s.update(r,h.join(`
`),"value")}catch(o){s.update(r,`Error: ${o instanceof Error?o.message:"Failed to load hardware stats"}`,"error")}}}const Ys="\x1B[0m",Xs="\x1B[1m",br="\x1B[2m",Xn="\x1B[36m",Jn="\x1B[96m",Tu="\x1B[97m",$u="\x1B[93m",Ve=48,Au=14,wt=22,gs=5,Js=22,Pu=5,Nu=wt+gs+Js+Pu,Iu=50;function $a(e,t,s,i){return r=>{if(r<=0)return 0;if(r>=1)return 1;let n=r;for(let o=0;o<8;o++){const a=3*(1-n)*(1-n)*n*e+3*(1-n)*n*n*s+n*n*n-r,h=3*(1-n)*(1-n)*e+6*(1-n)*n*(s-e)+3*n*n*(1-s);if(Math.abs(h)<1e-7)break;n=Math.max(0,Math.min(1,n-a/h))}return 3*(1-n)*(1-n)*n*t+3*(1-n)*n*n*i+n*n*n}}const Ou=$a(.25,1,.5,1),Hu=$a(.4,0,1,1);function Fu(e,t){const s=e%Au;return Math.sin(.45*s+.04*s*s+t*.25)}const Wu=[1,2,4,64],zu=[8,16,32,128],Zn=Wu.map((e,t)=>e|zu[t]);function Yt(e,t,s,i){i<4?e[s]|=Zn[i]:t[s]|=Zn[i-4]}function Uu(e){return e>.8?Tu+Xs:e>.6?$u+Xs:e>.4?Jn+Xs:e>.2?Jn:e>.08?Xn:Xn+br}function Qn(e,t,s){const i=new Uint8Array(Ve),r=new Uint8Array(Ve),n=new Float32Array(Ve),o=e*.35;for(let a=0;a<Ve;a++){const h=s?Ve-1-a:a;if(h>=t)continue;const l=t-h,c=Math.min(1,l/3),d=Math.min(1,h/2),u=l<5?1+.3*(1-l/5):1,f=Math.min(1,c*d*u);if(f<.04)continue;const _=1+.06*Math.sin(e*.7+h*.3),g=Fu(h,o)*f*_*3.5+3.5,k=Math.abs(g-3.5)/3.5,q=l<6?1-l/6:0;n[a]=Math.min(1,k*.65+q*.35)*f;const H=Math.max(0,Math.min(7,Math.round(g)));if(g>=3.5){for(let N=3;N<=H;N++)Yt(i,r,a,N);const T=Math.round((g-3.5)*.4);for(let N=Math.max(0,3-T);N<3;N++)Yt(i,r,a,N)}else{for(let N=H;N<=4;N++)Yt(i,r,a,N);const T=Math.round((3.5-g)*.4);for(let N=5;N<=Math.min(7,4+T);N++)Yt(i,r,a,N)}}return{top:i,bot:r,heat:n}}function eo(e,t,s){const i=new Uint8Array(Ve),r=new Uint8Array(Ve),n=new Float32Array(Ve),o=Math.exp(-t*.5),a=Math.max(0,10-t*2.5),h=.7+t*.2;for(let l=0;l<Math.ceil(a);l++){const c=e?Ve-1-l:l;if(c<0||c>=Ve)continue;const d=o*(1-l/a);if(d<.04)continue;n[c]=d;const f=Math.sin(l*h+s*.6)*d*3.5+3.5,_=Math.max(0,Math.min(7,Math.round(f)));if(f>=3.5)for(let p=3;p<=_;p++)Yt(i,r,c,p);else for(let p=_;p<=4;p++)Yt(i,r,c,p)}return{top:i,bot:r,heat:n}}function to(e,t){let s="",i="";for(let r=0;r<Ve;r++){const n=String.fromCodePoint(10240+e[r]),o=e[r]?Uu(t[r]):"";o!==i&&(s+=o,i=o),s+=n}return s+Ys}function so(e,t,s){const i=e%Nu;let r,n,o;if(i<wt){const l=i/(wt-1);({top:r,bot:n,heat:o}=Qn(e,Math.round(Ou(l)*Ve),!1))}else if(i<wt+gs)({top:r,bot:n,heat:o}=eo(!0,i-wt,e));else if(i<wt+gs+Js){const l=(i-wt-gs)/(Js-1);({top:r,bot:n,heat:o}=Qn(e,Math.round(Hu(l)*Ve),!0))}else({top:r,bot:n,heat:o}=eo(!1,i-wt-gs-Js,e));const a=(s/1e3).toFixed(1),h=`${br} ── chirp → ${Ys}${Xs}${t}${Ys}${br} ── ${a}s${Ys}`;return[to(r,o),to(n,o),h]}function Aa(e,t){const s=Date.now();let i=0;const r=e.write(so(0,t,0).join(`
`)),n=setInterval(()=>{i++,e.update(r,so(i,t,Date.now()-s).join(`
`))},Iu);return{id:r,stop:()=>clearInterval(n)}}class ju extends ie{constructor(){super(...arguments);D(this,"name","advert");D(this,"description","Send repeater advertisement")}async execute({output:s,rawInput:i}){if(this.argsAfterName(i).toLowerCase().trim()==="help"){s.write([z("advert"),`  ${w("Broadcast a repeater advertisement to the mesh network.")}`,"",B("advert","send advert now"),"",it("Adverts announce this repeater's presence to neighbors.")].join(`
`));return}const r=Aa(s,"broadcast");try{const n=await qa();r.stop(),n.success?s.update(r.id,`✓ ${y("Advert sent")}`,"success"):s.update(r.id,`Error: ${n.error||"Failed"}`,"error")}catch(n){r.stop(),s.update(r.id,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}const Ku=["sig","name","rssi","snr","dist","heard"],io={excellent:5,good:4,fair:3,poor:2,critical:1};function ro(e){const t=Math.floor(Date.now()/1e3-e);return t<60?`${t}s ago`:t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:`${Math.floor(t/86400)}d ago`}function qu(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}function no(e){return e<1e3?`${Math.round(e)}m`:`${(e/1e3).toFixed(1)}km`}const Vu={excellent:5,good:4,fair:3,poor:2,critical:1};function oo(e){const t=Vu[e]??0,s=Ir(e),i=t>0?`${s}${"█".repeat(t)}${se}`:"",r=w("⣿".repeat(5-t));return i+r}const ao=3.5;function Gu(e){var s;const t=(s=e.config)==null?void 0:s.radio;return!(t!=null&&t.spreading_factor)||!(t!=null&&t.bandwidth)?null:{sf:t.spreading_factor,bwHz:t.bandwidth}}function Yu(e){var s;const t=(s=e.config)==null?void 0:s.repeater;return!t||!ko(t.latitude,t.longitude)?null:{lat:t.latitude,lon:t.longitude}}function qt(e,t=s=>s){return{text:e,color:t}}function Xu(e,t){return{text:e,color:s=>s,rendered:t}}function Ti(e){return w("+"+e.map(t=>"-".repeat(t+2)).join("+")+"+")}function lo(e,t){const s=e.map((i,r)=>{if(i.rendered!=null){const n=Math.max(0,t[r]-i.text.length);return" "+i.rendered+" ".repeat(n)+" "}return" "+i.color(qu(i.text,t[r]))+" "});return w("|")+s.join(w("|"))+w("|")}const Ju=70,Zu=55;class Qu extends ie{constructor(){super(...arguments);D(this,"name","neighbors");D(this,"description","Show direct RF neighbors with signal stats");D(this,"aliases",["nb","get neighbors","get neighbor"]);D(this,"params","[sig|name|rssi|snr|dist|heard]")}async execute(s){const{output:i,cols:r}=s,n=this.argsAfterName(s.rawInput).toLowerCase().trim();if(n==="help"){this.printUsage(i);return}const o=Ku.includes(n)?n:null,a=i.write("processing...","system");try{const h=await rt(),l=h.neighbors||{},c=Object.entries(l).filter(([,g])=>g.zero_hop);if(c.length===0){const g=Object.keys(l).length;i.update(a,g>0?`No direct neighbors. ${g} relayed neighbor${g!==1?"s":""} known.`:"No neighbors discovered yet.","warning");return}const d=Gu(h),u=Yu(h),f=h.noise_floor_dbm;this.sortNeighbors(c,o,d,u,f);const _=o?`  ${Pe(`sorted by ${o}`)}`:"",p=[z(`Direct Neighbors (${c.length})`)+_,""];if(r<Zu)for(const[g,k]of c)p.push(...this.cardLayout(g,k,d,u,f));else{const g=r>=Ju&&u!=null,k=c.map(([X,oe])=>this.buildRow(X,oe,d,u,f,g)),q=g?["SIG","NAME","RSSI","SNR","DIST","HEARD"]:["SIG","NAME","RSSI","SNR","HEARD"],H=q.slice(1).map((X,oe)=>Math.max(X.length,...k.map(J=>J[oe+1].text.length))),T=5,N=H.reduce((X,oe)=>X+oe+3,0),F=Math.max(4,r-N-T-7),Z=Math.min(F,Math.max(4,...k.map(X=>X[1].text.length))),me=[T,Z,...H.slice(1)];p.push(Ti(me),...k.map(X=>lo(X,me)),Ti(me),lo(q.map(X=>qt(X,st)),me),Ti(me)),p.push(this.footer(d,f))}i.update(a,p.join(`
`))}catch(h){i.update(a,`Error: ${h instanceof Error?h.message:"Command failed"}`,"error")}}sortNeighbors(s,i,r,n,o){switch(i){case"sig":s.sort(([,a],[,h])=>{const l=io[this.gradeNeighbor(a,r,o)]??0,c=io[this.gradeNeighbor(h,r,o)]??0;return l-c});break;case"name":s.sort(([a,h],[l,c])=>{const d=(h.name||h.node_name||a.slice(0,8)).toLowerCase(),u=(c.name||c.node_name||l.slice(0,8)).toLowerCase();return d.localeCompare(u)});break;case"rssi":s.sort(([,a],[,h])=>(a.rssi??-999)-(h.rssi??-999));break;case"snr":s.sort(([,a],[,h])=>(a.snr??-999)-(h.snr??-999));break;case"dist":s.sort(([,a],[,h])=>{const l=this.distTo(a,n)??1/0,c=this.distTo(h,n)??1/0;return l-c});break;case"heard":s.sort(([,a],[,h])=>(a.last_seen||0)-(h.last_seen||0));break;default:s.sort(([,a],[,h])=>(h.last_seen||0)-(a.last_seen||0))}}gradeNeighbor(s,i,r){const n=s.rssi!=null?s.rssi-ao:null,o=r!=null&&r>-100?1:0,a=xo(s.snr??null,n,i,o);return(a==null?void 0:a.finalGrade)??"critical"}distTo(s,i){return!i||!ko(s.latitude,s.longitude)?null:Va(i.lat,i.lon,s.latitude,s.longitude)}buildRow(s,i,r,n,o,a){const h=this.gradeNeighbor(i,r,o),l=jn(i.name||i.node_name||s.slice(0,8))||s.slice(0,8),c=i.rssi!=null?`${i.rssi} dBm`:"-",d=i.snr!=null?`${i.snr} dB`:"-",u=i.last_seen?ro(i.last_seen):"-",f=oo(h),_=[Xu("|||||",f),qt(l,st),qt(c,y),qt(d,y)];if(a){const p=this.distTo(i,n);_.push(qt(p!=null?no(p):"-",Pe))}return _.push(qt(u,Pe)),_}cardLayout(s,i,r,n,o){const a=this.gradeNeighbor(i,r,o),h=jn(i.name||i.node_name||s.slice(0,8))||s.slice(0,8),l=i.rssi!=null?`${i.rssi}`:"-",c=i.snr!=null?`${i.snr}`:"-",d=i.last_seen?ro(i.last_seen):"-",u=this.distTo(i,n),f=u!=null?`  ${w("dist")} ${y(no(u))}`:"";return[`${oo(a)} ${st(h)}`,`  ${w("rssi")} ${y(l)}  ${w("snr")} ${y(c)}${f}  ${Pe(d)}`,""]}footer(s,i){const r=[];return s&&r.push(`SF${s.sf}/${s.bwHz>=1e3?s.bwHz/1e3+"kHz":s.bwHz+"Hz"}`),r.push(`ant ${ao}dBi`),i!=null&&r.push(`nf ${i}dBm`),w(r.join("  "))}printUsage(s){const i=[z("neighbors"),`  ${w("Show direct RF neighbors with signal quality, RSSI, SNR, and distance.")}`,"",z("Usage"),B("neighbors","default sort (most recent)"),B("neighbors sig","sort by signal grade (weakest first)"),B("neighbors name","sort alphabetically"),B("neighbors rssi","sort by RSSI (weakest first)"),B("neighbors snr","sort by SNR (lowest first)"),B("neighbors dist","sort by distance (closest first)"),B("neighbors heard","sort by last seen (oldest first)"),B("neighbors help","show this help"),"",z("Aliases"),`  ${w("nb, get neighbors, get neighbor")}`,"",it("Signal bars factor radio config, noise floor, and 3.5 dBi antenna gain."),it("Only zero-hop (direct RF) neighbors are shown.")];s.write(i.join(`
`))}}class e_ extends ie{constructor(){super(...arguments);D(this,"name","get");D(this,"description","Get repeater parameter");D(this,"params","{parameter}")}async execute({output:s,rawInput:i}){const r=this.argsAfterName(i).toLowerCase().trim();if(r==="help"||!r){s.write([z("get"),`  ${w("Read a repeater configuration parameter.")}`,"",z("Identity"),B("get name","node name"),B("get role","node role"),B("get public.key","public key"),"",z("Location"),B("get lat","latitude"),B("get lon","longitude"),"",z("Radio"),B("get radio","full radio summary"),B("get freq","frequency (MHz)"),B("get tx","TX power (dBm)"),B("get bw","bandwidth (kHz)"),B("get sf","spreading factor"),B("get cr","coding rate"),"",z("Timing"),B("get af","airtime factor (pending backend)"),B("get txdelay","TX delay factor"),B("get direct.txdelay","direct TX delay"),B("get rxdelay","RX delay base"),"",z("Repeater"),B("get mode","forward or monitor"),B("get flood.max","max flood hops"),B("get advert.interval","advert interval"),B("get duty","duty cycle state"),"",z("Advanced"),B("get multi.acks","multi-ack count"),B("get int.thresh","interference threshold (dBm)"),B("get agc.reset.interval","AGC reset interval")].join(`
`));return}const n=s.write("processing...","system");try{const o=await rt(),{result:a,type:h}=t_(r,o);s.update(n,a,h)}catch(o){s.update(n,`Error: ${o instanceof Error?o.message:"Command failed"}`,"error")}}}function t_(e,t){const s=t.config||{},i=s.radio||{},r=s.repeater||{},n=s.delays||{},o=s.duty_cycle||{},a=(h,l)=>({result:b(h,y(l)),type:"value"});switch(e){case"name":return a("name",s.node_name||"Unknown");case"role":return a("role","repeater");case"lat":return a("lat",r.latitude!=null?String(r.latitude):"not set");case"lon":return a("lon",r.longitude!=null?String(r.longitude):"not set");case"freq":return a("freq",i.frequency?`${(i.frequency/1e6).toFixed(3)} MHz`:"?");case"tx":return a("tx",i.tx_power!=null?`${i.tx_power} dBm`:"?");case"bw":return a("bw",i.bandwidth?`${i.bandwidth/1e3} kHz`:"?");case"sf":return a("sf",String(i.spreading_factor??"?"));case"cr":return a("cr",i.coding_rate?`4/${i.coding_rate}`:"?");case"radio":return i.frequency?{result:[`  ${b("freq",y(`${(i.frequency/1e6).toFixed(3)} MHz`))}`,`  ${b("bw",y(`${i.bandwidth/1e3} kHz`))}`,`  ${b("sf",y(String(i.spreading_factor)))}`,`  ${b("cr",y(`4/${i.coding_rate}`))}`,`  ${b("tx",y(`${i.tx_power} dBm`))}`].join(`
`),type:"value"}:a("radio","?");case"af":case"airtime.factor":return{result:`${w("airtime_factor is not yet exposed by the pyMC_Repeater API.")}
${w("Firmware range: 0-9. Controls airtime budget fraction.")}
${w("Tracked in CLI-Alignment.md — needs backend support.")}`,type:"warning"};case"txdelay":return a("txdelay",String(n.tx_delay_factor??"1.0"));case"direct.txdelay":return a("direct.txdelay",String(n.direct_tx_delay_factor??"0.5"));case"rxdelay":return a("rxdelay",String(n.rx_delay_base??"0.0"));case"mode":return a("mode",r.mode||"forward");case"repeat":return a("repeat",r.mode==="forward"?"on":"off");case"flood.max":return a("flood.max",String(r.max_flood_hops??"3"));case"flood.advert.interval":return a("flood.advert.interval",r.send_advert_interval_hours!=null?`${r.send_advert_interval_hours}h`:"?");case"advert.interval":return a("advert.interval",r.advert_interval_minutes!=null?`${r.advert_interval_minutes}m`:"120m");case"duty":case"duty.enabled":return a("duty",o.enforcement_enabled?"on":"off");case"duty.max":return a("duty.max",o.max_airtime_percent!=null?`${o.max_airtime_percent}%`:"?");case"multi.acks":return a("multi.acks",String(r.multi_acks??"0"));case"int.thresh":return a("int.thresh",`${r.interference_threshold??-120} dBm`);case"agc.reset.interval":return a("agc.reset.interval",String(r.agc_reset_interval??"0"));case"public.key":return a("public.key",t.public_key||"not available");case"prv.key":return{result:`${w("Private key stored in /etc/openhop_repeater/config.yaml")}

  ${b("view",y("sudo grep identity_key /etc/openhop_repeater/config.yaml"))}
  ${b("set",y("sudo ./convert_firmware_key.sh <64-byte-hex>"))}`,type:"info"};case"guest.password":case"allow.read.only":return{result:`${w("Security settings not exposed via stats API.")}
${w("Check /etc/openhop_repeater/config.yaml")}`,type:"warning"};default:return{result:`Unknown parameter: ${y(e)}
${w('Run "get help" to see available parameters.')}`,type:"error"}}}class s_ extends ie{constructor(){super(...arguments);D(this,"name","set");D(this,"description","Set repeater parameter");D(this,"params","{parameter} {value}")}async execute({output:s,rawInput:i}){var l;const n=this.argsAfterName(i).split(/\s+/),o=(l=n[0])==null?void 0:l.toLowerCase(),a=n.slice(1).join(" ");if(o==="help"||!o){s.write([z("set"),`  ${w("Write a repeater configuration parameter.")}`,"",z("Identity"),B("set name <name>","node name"),B("set lat <deg>","latitude (-90 to 90)"),B("set lon <deg>","longitude (-180 to 180)"),"",z("Radio"),B("set freq <MHz>","frequency"),B("set tx <dBm>","TX power (2-22)"),B("set bw <kHz>","bandwidth"),B("set sf <5-12>","spreading factor"),B("set cr <5-8>","coding rate"),"",z("Timing"),B("set af <0-9>","airtime factor (pending backend)"),B("set txdelay <0-5>","TX delay factor"),B("set direct.txdelay <0-5>","direct TX delay"),B("set rxdelay <n>","RX delay base"),"",z("Repeater"),B("set mode <fwd|mon|no_tx>","forward, monitor, or no transmit"),B("set flood.max <0-64>","max flood hops"),B("set advert.interval <m>","advert interval (min)"),B("set duty <on|off>","duty cycle enforcement"),B("set log <level>","log level"),"",z("Advanced"),B("set multi.acks <n>","multi-ack count"),B("set int.thresh <dBm>","interference threshold"),B("set agc.reset.interval <n>","AGC reset interval (x4)"),"",it("Some changes require a service restart.")].join(`
`));return}const h=s.write("processing...","system");try{const{result:c,type:d}=await i_(o,a,i);s.update(h,c,d)}catch(c){s.update(h,`Error: ${c instanceof Error?c.message:"Command failed"}`,"error")}}}async function i_(e,t,s){switch(e){case"mode":return r_(t);case"duty":return n_(t);case"tx":return Ue("tx_power",Vt(t,2,22,"TX power must be 2-22 dBm"));case"sf":return Ue("spreading_factor",Vt(t,5,12,"SF must be 5-12"));case"af":case"airtime.factor":return{result:`Error: airtime_factor is not yet exposed by the pyMC_Repeater API.
Firmware range: 0-9. Tracked in CLI-Alignment.md — needs backend support.`,type:"info"};case"txdelay":return Ue("tx_delay_factor",cs(t,0,5,"TX delay must be 0.0-5.0"));case"direct.txdelay":return Ue("direct_tx_delay_factor",cs(t,0,5,"Direct TX delay must be 0.0-5.0"));case"rxdelay":return Ue("rx_delay_base",a_(t,0,"RX delay must be >= 0"));case"flood.max":return Ue("max_flood_hops",Vt(t,0,64,"Max flood hops must be 0-64"));case"log":return o_(t);case"multi.acks":return Ue("multi_acks",Vt(t,0,255,"Multi-acks must be 0-255"));case"int.thresh":return Ue("interference_threshold",Vt(t,-200,0,"Interference threshold must be -200 to 0 dBm"));case"agc.reset.interval":{const i=Ai(t);if(!i.ok)return _e(i.error);if(i.value<0)return _e("AGC reset interval must be >= 0");const r=Math.floor(i.value/4)*4;return $i("agc_reset_interval",r,`OK - AGC reset interval set to ${r}${r!==i.value?` (rounded from ${i.value})`:""}`)}case"name":{const i=s.trim().substring(s.toLowerCase().indexOf("name")+5).trim();return i?/[\[\]\\/\\:,?*]/.test(i)?_e("Name contains invalid characters: [ ] \\ / : , ? * are not allowed"):Ue("node_name",{ok:!0,value:i}):_e("Node name cannot be empty")}case"lat":return Ue("latitude",cs(t,-90,90,"Latitude must be -90 to 90"));case"lon":return Ue("longitude",cs(t,-180,180,"Longitude must be -180 to 180"));case"freq":{const i=cs(t,100,1e3,"Frequency must be 100-1000 MHz");return i.ok?Ue("frequency",{ok:!0,value:i.value*1e6}):_e(i.error)}case"bw":{const i=[7.8,10.4,15.6,20.8,31.25,41.7,62.5,125,250,500],r=parseFloat(t);return isNaN(r)||!i.includes(r)?_e(`BW must be one of: ${i.join(", ")} kHz`):Ue("bandwidth",{ok:!0,value:r*1e3})}case"cr":return Ue("coding_rate",Vt(t,5,8,"Coding rate must be 5-8"));case"advert.interval":{const i=Ai(t);return i.ok?i.value!==0&&(i.value<1||i.value>10080)?_e("Advert interval must be 0 (off) or 1-10080 minutes"):$i("advert_interval_minutes",i.value,i.value===0?"OK - Local adverts disabled":`OK - Local advert interval set to ${i.value}m`):_e(i.error)}case"flood.advert.interval":{const i=Ai(t);return i.ok?i.value!==0&&(i.value<3||i.value>168)?_e("Flood advert interval must be 0 (off) or 3-168 hours"):$i("flood_advert_interval_hours",i.value,i.value===0?"OK - Flood adverts disabled":`OK - Flood advert interval set to ${i.value}h`):_e(i.error)}case"prv.key":{const i=t.trim();return i?/^[0-9a-fA-F]+$/.test(i)?i.length!==128?_e(`Key must be 64 bytes (128 hex chars), got ${i.length} chars`):{result:`To set this key, run on the Pi:

  sudo ./convert_firmware_key.sh ${i}

Then restart: sudo systemctl restart pymc-repeater`,type:"info"}:_e("Private key must be a hex string"):_e("Private key cannot be empty")}default:return _e(`Unknown parameter: ${e}`)}}async function r_(e){const t=e.toLowerCase(),s=t==="fwd"?"forward":t==="mon"?"monitor":t;return s!=="forward"&&s!=="monitor"&&s!=="no_tx"?_e('Mode must be "forward", "monitor", or "no_tx"'):(await Xa(s)).success?Ts(`OK - Mode set to ${s}`):_e("Failed")}async function n_(e){const t=e.toLowerCase()==="on"||e==="1";return(await Ya(t)).success?Ts(`OK - Duty cycle ${t?"enabled":"disabled"}`):_e("Failed")}async function o_(e){const t=e.toUpperCase();if(!["DEBUG","INFO","WARNING","ERROR"].includes(t))return _e("Level must be debug, info, warning, or error");const s=await Ga(t);return s.success?Ts(`OK - Log level set to ${t}`):_e(s.error||"Failed")}async function Ue(e,t){if(!t.ok)return _e(t.error);const s=await Eo({[e]:t.value});if(!s.success)return _e(s.error||"Failed");let i=`OK - ${e} set to ${t.value}`;return s.restart_required&&(i+=`
⚠ Service restart required for changes to take effect
Run: sudo systemctl restart pymc_repeater`),Ts(i)}async function $i(e,t,s){const i=await Eo({[e]:t});if(!i.success)return _e(i.error||"Failed");let r=s;return i.restart_required&&(r+=`
⚠ Service restart required for changes to take effect
Run: sudo systemctl restart pymc_repeater`),Ts(r)}function Vt(e,t,s,i){const r=parseInt(e);return isNaN(r)||r<t||r>s?{ok:!1,error:`Error: ${i}`}:{ok:!0,value:r}}function cs(e,t,s,i){const r=parseFloat(e);return isNaN(r)||r<t||r>s?{ok:!1,error:`Error: ${i}`}:{ok:!0,value:r}}function a_(e,t,s){const i=parseFloat(e);return isNaN(i)||i<t?{ok:!1,error:`Error: ${s}`}:{ok:!0,value:i}}function Ai(e){const t=parseInt(e);return isNaN(t)?{ok:!1,error:"Error: Expected a number"}:{ok:!0,value:t}}function Ts(e){return{result:e,type:"success"}}function _e(e){return{result:`Error: ${e}`,type:"error"}}const l_={excellent:5,good:4,fair:3,poor:2,critical:1};function h_(e){const t=l_[e]??0,s=Ir(e);return(t>0?`${s}${"█".repeat(t)}${se}`:"")+w("·".repeat(5-t))}const ho=3.5;class c_ extends ie{constructor(){super(...arguments);D(this,"name","ping");D(this,"description","Ping neighbor (name or 0xXX)");D(this,"params","{target} [timeout]")}async execute({output:s,rawInput:i}){var u,f,_,p,g,k,q;const r=this.argsAfterName(i).trim(),n=r.split(/\s+/);if(((u=n[0])==null?void 0:u.toLowerCase())==="help"){s.write([z("ping"),`  ${w("Send a ping to a neighbor and measure round-trip time, signal quality, and path.")}`,"",B("ping <name>","ping by node name"),B("ping 0xAB","ping by hex prefix"),B("ping <name> 60","ping with custom timeout (seconds)"),"",it("Default timeout: 30s. Signal bars factor radio config and noise floor.")].join(`
`));return}const o=n[n.length-1],a=parseInt(o),h=n.length>1&&!isNaN(a)&&a>0,l=h?n.slice(0,-1).join(" "):r,c=h?a:30;if(!l){s.write([z("ping"),`  ${w("Send a ping to a neighbor and measure round-trip time.")}`,"",B("ping <name>","ping by node name"),B("ping <name> 60","with custom timeout"),"",it('Run "ping help" for full usage.')].join(`
`));return}const d=Aa(s,l);try{const H=await rt(),T=Ja((_=(f=H==null?void 0:H.config)==null?void 0:f.mesh)==null?void 0:_.path_hash_mode),N=await Za(l,c,T);if(d.stop(),N.success&&N.data){const F=N.data,Z=(p=F.path)!=null&&p.length?F.path.length:0,me=(g=F.path)!=null&&g.length?F.path.join(" > "):"direct",X=Qa(F);let oe;if(X){const I=(k=H.config)==null?void 0:k.radio,R=I!=null&&I.spreading_factor&&(I!=null&&I.bandwidth)?{sf:I.spreading_factor,bwHz:I.bandwidth}:null,V=H.noise_floor_dbm,ee=V!=null&&V>-100?1:0,Se=F.rssi-ho,$e=xo(F.snr_db,Se,R,ee);oe=($e==null?void 0:$e.finalGrade)??"critical"}else oe=null;const J=oe?h_(oe):w("·····"),P=oe?oe.charAt(0).toUpperCase()+oe.slice(1):w("N/A"),S=[`${J} ${st("Reply from")} ${y(F.target_id)}`,"",`  ${b("RTT",nu(F.rtt_ms))}`,`  ${b("RSSI",X?`${F.rssi} dBm`:w("N/A"))}`,`  ${b("SNR",X?`${F.snr_db} dB`:w("N/A"))}`,`  ${b("Path",me)}${Z>0?w(` (${Z} hop${Z!==1?"s":""})`):""}`,`  ${b("Quality",oe?ou(P,oe):P)}`],L=[],C=(q=H.config)==null?void 0:q.radio;if(C!=null&&C.spreading_factor&&(C!=null&&C.bandwidth)){const I=C.bandwidth>=1e3?C.bandwidth/1e3+"kHz":C.bandwidth+"Hz";L.push(`SF${C.spreading_factor}/${I}`)}L.push(`ant ${ho}dBi`);const M=H.noise_floor_dbm;M!=null&&L.push(`nf ${M}dBm`),T>1&&L.push(`${T}-byte hash`),S.push("",w(L.join("  "))),s.update(d.id,S.join(`
`))}else s.update(d.id,N.error||"Ping failed","error")}catch(H){d.stop(),s.update(d.id,`Error: ${H instanceof Error?H.message:"Ping failed"}`,"error")}}}class d_ extends ie{constructor(){super(...arguments);D(this,"name","convert");D(this,"description","Convert between hex and base64");D(this,"params","hex|base64 {value}")}execute({output:s,args:i}){var o;const r=(o=i[1])==null?void 0:o.toLowerCase(),n=i.slice(2).join(" ").trim();if(r==="help"||!r&&!n){s.write([z("convert"),`  ${w("Convert between hex and base64 encodings.")}`,"",B("convert hex <hex>","hex → base64"),B("convert base64 <b64>","base64 → hex"),"",it("Example: convert hex 48656C6C6F")].join(`
`));return}r==="hex"?this.hexToBase64(s,n):r==="base64"?this.base64ToHex(s,n):s.write([z("convert"),`  ${w("Convert between hex and base64 encodings.")}`,"",B("convert hex <hex>","hex → base64"),B("convert base64 <b64>","base64 → hex")].join(`
`))}hexToBase64(s,i){if(!i){s.write("Usage: convert hex <hex-string>","error");return}if(!/^[0-9a-fA-F]+$/.test(i)){s.write("Error: Input must be a hex string","error");return}if(i.length%2!==0){s.write("Error: Hex string must have even length","error");return}try{const r=new Uint8Array(i.length/2);for(let h=0;h<i.length;h+=2)r[h/2]=parseInt(i.substring(h,h+2),16);let n="";const o=8192;for(let h=0;h<r.length;h+=o)n+=String.fromCharCode.apply(null,Array.from(r.subarray(h,Math.min(h+o,r.length))));const a=typeof globalThis.btoa=="function"?globalThis.btoa(n):Buffer.from(n,"binary").toString("base64");s.write(`  ${b("hex",y(i))}
  ${b("base64",y(a))}`)}catch(r){s.write(`Error: Failed to convert - ${r instanceof Error?r.message:"unknown error"}`,"error")}}base64ToHex(s,i){if(!i){s.write("Usage: convert base64 <base64-string>","error");return}try{const r=typeof globalThis.atob=="function"?globalThis.atob(i):Buffer.from(i,"base64").toString("binary");let n="";for(let o=0;o<r.length;o++)n+=r.charCodeAt(o).toString(16).padStart(2,"0");s.write(`  ${b("base64",y(i))}
  ${b("hex",y(n.toUpperCase()))}`)}catch(r){s.write(`Error: Invalid base64 string - ${r instanceof Error?r.message:"unknown error"}`,"error")}}}const u_=10,__=500;function f_(){const e=new Date;return`${e.toISOString().slice(0,10)}_${e.toTimeString().slice(0,8).replace(/:/g,"-")}`}function p_(e,t){const s=e.toISOString().slice(0,10),i=e.toTimeString().slice(0,5).replace(":","");return`pymc-${s}-${i}-${t}s.json`}const bt=Ro((e,t)=>({isCapturing:!1,captureStartTime:null,captureStartPacketHashes:new Set,captureTimer:null,reports:[],startCapture:s=>{const{captureTimer:i}=t();i&&clearTimeout(i),e({isCapturing:!0,captureStartTime:new Date,captureStartPacketHashes:new Set(s.map(r=>r.packet_hash))})},stopCapture:s=>{const{isCapturing:i,captureStartTime:r,captureStartPacketHashes:n,captureTimer:o}=t();if(!i||!r)return null;o&&clearTimeout(o);const a=new Date,h=Math.round((a.getTime()-r.getTime())/1e3),l=r.getTime()/1e3,c=s.filter(u=>!n.has(u.packet_hash)&&u.timestamp>=l).sort((u,f)=>u.timestamp-f.timestamp),d={id:f_(),filename:p_(r,h),startTime:r,endTime:a,durationSec:h,packetCount:c.length,packets:c,sizeBytes:c.length*__};return e(u=>({isCapturing:!1,captureStartTime:null,captureStartPacketHashes:new Set,captureTimer:null,reports:[d,...u.reports].slice(0,u_)})),d},getReport:s=>t().reports.find(i=>i.id===s),_setTimer:s=>e({captureTimer:s})})),Pa=()=>bt(e=>e.reports);function de(e){var t;return((t=e.match(/.{1,2}/g))==null?void 0:t.join(" ").toUpperCase())||""}function Hr(e){return e===void 0?"UNKNOWN":rl[e]??`TYPE_${e}`}function Na(e){return e===void 0?"UNKNOWN":il[e]??`ROUTE_${e}`}function m_(e){const t=[];let s=0;if(e.length>=32&&(t.push({name:"public_key",offset:s,length:32,bytes:de(ce(e.slice(s,s+32))),decoded:{value:ce(e.slice(s,s+32))}}),s+=32),e.length>=s+4){const i=e.slice(s,s+4),r=i[0]|i[1]<<8|i[2]<<16|i[3]<<24;t.push({name:"timestamp",offset:s,length:4,bytes:de(ce(i)),decoded:{value:r>>>0,iso:new Date(r*1e3).toISOString()}}),s+=4}if(e.length>=s+64&&(t.push({name:"signature",offset:s,length:64,bytes:de(ce(e.slice(s,s+64))),decoded:{value:ce(e.slice(s,s+64))}}),s+=64),e.length>s){const i=e[s],r=[];if(i&1&&r.push("CHAT_NODE"),i&2&&r.push("REPEATER"),i&3&&r.push("ROOM_SERVER"),i&16&&r.push("HAS_LOCATION"),i&128&&r.push("HAS_NAME"),t.push({name:"flags",offset:s,length:1,bytes:de(ce(e.slice(s,s+1))),decoded:{value:i,binary:i.toString(2).padStart(8,"0"),flags:r}}),s+=1,i&16&&e.length>=s+8){const n=e.slice(s,s+8),o=new ArrayBuffer(8);new Uint8Array(o).set(n);const a=new DataView(o),h=a.getInt32(0,!0),l=a.getInt32(4,!0);t.push({name:"location",offset:s,length:8,bytes:de(ce(n)),decoded:{lat_raw:h,lon_raw:l,latitude:h/1e6,longitude:l/1e6}}),s+=8}if(i&128&&e.length>s){const n=e.slice(s);let o=n.indexOf(0);o===-1&&(o=n.length);const a=new TextDecoder().decode(n.slice(0,o));t.push({name:"name",offset:s,length:o+(n[o]===0?1:0),bytes:de(ce(n.slice(0,o+1))),decoded:{value:a,encoding:"utf-8",null_terminated:n[o]===0}})}}return t}function g_(e){if(e.length<4)return[];const t=e.slice(0,4),s=t[0]|t[1]<<8|t[2]<<16|t[3]<<24;return[{name:"crc",offset:0,length:4,bytes:de(ce(t)),decoded:{value:s>>>0,hex:(s>>>0).toString(16).toUpperCase().padStart(8,"0"),note:"CRC of the acknowledged packet (little-endian)"}}]}function v_(e){const t=[];if(e.length<9)return t;const s=e.slice(0,4),i=s[0]|s[1]<<8|s[2]<<16|s[3]<<24;t.push({name:"trace_tag",offset:0,length:4,bytes:de(ce(s)),decoded:{value:i>>>0,hex:(i>>>0).toString(16).toUpperCase().padStart(8,"0")}});const r=e.slice(4,8),n=r[0]|r[1]<<8|r[2]<<16|r[3]<<24;t.push({name:"auth_code",offset:4,length:4,bytes:de(ce(r)),decoded:{value:n>>>0}});const o=e[8],a=1<<(o&3);if(t.push({name:"flags",offset:8,length:1,bytes:de(ce(e.slice(8,9))),decoded:{value:o,binary:o.toString(2).padStart(8,"0"),...a>1?{hash_size:a}:{}}}),e.length>9){const h=e.slice(9),l=[];for(let c=0;c+a<=h.length;c+=a){let d="";for(let u=0;u<a;u++)d+=h[c+u].toString(16).toUpperCase().padStart(2,"0");l.push(d)}t.push({name:"target_path",offset:9,length:h.length,bytes:de(ce(h)),decoded:{hops:l,path_string:l.join("->"),...a>1?{hash_size:`${a}B per hop`}:{}}})}return t}function S_(e){if(e.length===0)return[];const{hashSize:t,hopCount:s}=nl(e[0]),i=s*t,r=[];if(r.push({name:"path_length",offset:0,length:1,bytes:de(ce(e.slice(0,1))),decoded:{raw:e[0],hop_count:s,...t>1?{hash_size:t}:{}}}),s>0&&e.length>1){const o=e.slice(1,1+Math.min(i,e.length-1)),a=[];for(let h=0;h+t<=o.length;h+=t){let l="";for(let c=0;c<t;c++)l+=o[h+c].toString(16).toUpperCase().padStart(2,"0");a.push(l)}r.push({name:"path_hops",offset:1,length:o.length,bytes:de(ce(o)),decoded:{hops:a,path_string:a.join("->"),...t>1?{hash_size:`${t}B per hop`}:{}}})}const n=1+i;if(e.length>n){const o=e[n]&15;if(r.push({name:"extra_type",offset:n,length:1,bytes:de(ce(e.slice(n,n+1))),decoded:{value:o,name:Hr(o)}}),e.length>n+1){const a=e.slice(n+1);r.push({name:"extra_data",offset:n+1,length:a.length,bytes:de(ce(a)),decoded:{length:a.length}})}}return r}function y_(e){const t=[];if(e.length<1)return t;if(t.push({name:"channel_hash",offset:0,length:1,bytes:de(ce(e.slice(0,1))),decoded:{value:e[0].toString(16).toUpperCase().padStart(2,"0")}}),e.length>13){const i=e.length-1-12;t.push({name:"ciphertext",offset:1,length:i,bytes:de(ce(e.slice(1,1+i))),decoded:{length:i,note:"Encrypted message content"}}),t.push({name:"mac",offset:1+i,length:12,bytes:de(ce(e.slice(-12))),decoded:{note:"Message authentication code"}})}return t}function w_(e){return e.length===0?[]:[{name:"raw_data",offset:0,length:e.length,bytes:de(ce(e)),decoded:{length:e.length}}]}function Ia(e,t){switch(e){case 4:return m_(t);case 3:return g_(t);case 9:return v_(t);case 8:return S_(t);case 5:return y_(t);default:return w_(t)}}function b_(e){const t=e.type??e.payload_type??0,s=e.route??e.route_type??0,i=e.raw_packet||"";let r,n=null;if(i){const o=tl.fromHex(i);if(o.success&&o.packet){const a=o.packet;try{n=sl(a)}catch{n=null}const h=Bo(i);let l=0;const c={offset:0,length:1,bytes:de(i.slice(0,2)),decoded:{route_type:a.routeType,route_name:a.routeTypeName,payload_type:a.payloadType,payload_name:a.payloadTypeName,version:a.payloadVersion}};l+=1,a.hasTransportCodes()&&(l+=4);const u={offset:l,length:1,bytes:de(ce(h.slice(l,l+1))),decoded:{value:a.pathLen}};l+=1;const f=l,_=h.slice(l,l+a.pathLen),p=a.pathHexArray,g=a.payloadType===9,k={offset:f,length:a.pathLen,bytes:de(ce(_)),decoded:{hops:p,hop_count:a.hopCount,...a.pathHashSize>1?{hash_size:`${a.pathHashSize}B per hop`}:{},path_string:p.length>0?p.join("->"):"(direct)",...g&&{note:"For TRACE packets, path bytes are SNR×4 values, not node hashes",snr_values:Array.from(a.path).map(T=>{let N=T;return N>127&&(N-=256),N/4})}}};l+=a.pathLen;const H={offset:l,length:a.payload.length,bytes:de(a.payloadHex),sections:Ia(a.payloadType,a.payload)};r={header:c,path_length:u,path:k,payload:H}}else r=co(e)}else r=co(e);return{timestamp:e.timestamp,packet_hash:e.packet_hash,type:t,type_name:Hr(t),route:s,route_name:Na(s),rssi:e.rssi,snr:e.snr,length:e.length??0,src_hash:e.src_hash,dst_hash:e.dst_hash,transmitted:e.transmitted,drop_reason:e.drop_reason,is_duplicate:e.is_duplicate,lbt_attempts:e.lbt_attempts,lbt_backoff_delays_ms:e.lbt_backoff_delays_ms,lbt_channel_busy:e.lbt_channel_busy,raw_packet:i,structure:r,decoded:n}}function co(e){var r;const t=e.type??e.payload_type??0,s=e.route??e.route_type??0,i=e.original_path??e.forwarded_path??[];return{header:{offset:0,length:1,bytes:"??",decoded:{route_type:s,route_name:Na(s),payload_type:t,payload_name:Hr(t),version:0}},path_length:{offset:1,length:1,bytes:i.length.toString(16).toUpperCase().padStart(2,"0"),decoded:{value:i.length}},path:{offset:2,length:i.length,bytes:i.join(" "),decoded:{hops:i,path_string:i.length>0?i.join("->"):"(direct)"}},payload:{offset:2+i.length,length:((r=e.payload)==null?void 0:r.length)??0,bytes:e.payload??"",sections:e.payload?Ia(t,Bo(e.payload)):[]}}}function C_(e,t){var s;return{capture:{start:e.startTime.toISOString(),end:e.endTime.toISOString(),duration_sec:e.durationSec,packet_count:e.packetCount,node_name:(t==null?void 0:t.node_name)??"unknown",local_hash:(t==null?void 0:t.local_hash)??"unknown",pymc_console_version:el,pymc_repeater_version:(t==null?void 0:t.version)??"unknown",radio_config:(s=t==null?void 0:t.config)!=null&&s.radio?{frequency:t.config.radio.frequency,tx_power:t.config.radio.tx_power,bandwidth:t.config.radio.bandwidth,spreading_factor:t.config.radio.spreading_factor}:null},packets:e.packets.map(b_)}}function Oa(e,t){const s=C_(e,t),i=JSON.stringify(s,null,2),r=new Blob([i],{type:"application/json"}),n=URL.createObjectURL(r),o=document.createElement("a");o.href=n,o.download=e.filename,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(n)}function Zs(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}class x_ extends ie{constructor(){super(...arguments);D(this,"name","cap");D(this,"description","Packet capture (start/end/list/export)")}matches(s){const i=s.toLowerCase().trim();return i==="cap"||i==="cap help"||i.startsWith("start cap")||i.startsWith("end cap")||i.startsWith("list cap")||i.startsWith("export cap")}async execute({output:s,rawInput:i}){const r=i.toLowerCase().trim();if(r==="cap"||r==="cap help")return this.showHelp(s);if(r.startsWith("start cap"))return this.startCapture(s,r);if(r==="end cap")return this.endCapture(s);if(r==="list cap")return this.listCaptures(s);if(r.startsWith("export cap"))return this.exportCapture(s,r);this.showHelp(s)}showHelp(s){const i=bt.getState(),r=i.isCapturing?`
${Bi('Recording in progress... use "end cap" to stop')}`:"",n=i.reports.length,o=n>0?` (${n} saved)`:"",a=[z("Packet Capture"),"",B("start cap","Start capture (default: 120s)"),B("end cap","Stop capture early"),B("list cap",`List saved captures${o}`),B("export cap","Download capture by ID"),"",it("Captures stored in session memory. JSON includes decoded payloads."),r].filter(Boolean);s.write(a.join(`
`))}startCapture(s,i){const r=i.slice(9).trim(),n=r?parseInt(r):120;if(isNaN(n)||n<1||n>3600){s.write("Error: Duration must be 1-3600 seconds","error");return}const o=bt.getState();if(o.isCapturing){s.write('Error: Capture already in progress. Use "end cap" first.',"error");return}const a=xt.getState().packets;o.startCapture(a);let h=n;const l=s.write(Bi(`Capturing... ${h}s remaining`),"system"),c=setInterval(()=>{h--;const u=bt.getState();if(h>=0&&u.isCapturing){const _=xt.getState().packets.filter(g=>{if(!u.captureStartTime)return!1;const k=u.captureStartTime.getTime()/1e3;return g.timestamp>=k&&!u.captureStartPacketHashes.has(g.packet_hash)}).length,p=h>0?`${h}s remaining`:"finishing...";s.update(l,Bi(`Capturing... ${p} (${_} captured)`),"system")}},1e3),d=setTimeout(()=>{clearInterval(c);const u=bt.getState();if(u.isCapturing){const f=xt.getState().packets,_=u.stopCapture(f);_?s.write(`✓ Capture complete!
  Captured: ${_.packetCount} packets
  Duration: ${_.durationSec}s
  Size: ~${Zs(_.sizeBytes)}

Run \`export cap ${_.id}\` to download.`,"value"):s.write("Capture completed with no packets.","warning")}},n*1e3);o._setTimer(d)}endCapture(s){const i=bt.getState();if(!i.isCapturing){s.write("No capture in progress.","warning");return}const r=xt.getState().packets,n=i.stopCapture(r);n?s.write(`✓ Capture stopped!
  Captured: ${n.packetCount} packets
  Duration: ${n.durationSec}s
  Size: ~${Zs(n.sizeBytes)}

Run \`export cap ${n.id}\` to download.`,"value"):s.write("Capture stopped with no packets.","warning")}listCaptures(s){const{reports:i}=bt.getState();if(i.length===0){s.write(`No capture reports available.
Start a capture with: start cap [seconds]`,"info");return}const r=i.map((n,o)=>`  ${o+1}. ${n.packetCount} pkts • ${n.durationSec}s • ~${Zs(n.sizeBytes)} (id: ${n.id})`);s.write(`Capture Reports (${i.length}):
${r.join(`
`)}`,"info")}exportCapture(s,i){const r=i.slice(10).trim(),n=bt.getState(),o=xt.getState().stats;if(!r){if(n.reports.length===0)s.write(`No capture reports available.
Start a capture with: start cap [seconds]`,"info");else{const h=n.reports.map((l,c)=>`  ${c+1}. ${l.id}`);s.write(`Usage: export cap <id>

Available reports:
${h.join(`
`)}`,"info")}return}let a=n.getReport(r);if(!a){const h=parseInt(r)-1;a=n.reports[h]}if(!a){s.write(`Error: Report "${r}" not found.
Use "list cap" to see available reports.`,"error");return}Oa(a,o),s.write(`✓ Downloading ${a.filename}...`,"value")}}class k_ extends ie{constructor(){super(...arguments);D(this,"name","identities");D(this,"description","List configured identities");D(this,"aliases",["id","ids"])}async execute({output:s,rawInput:i}){var n;if(this.argsAfterName(i).toLowerCase().trim()==="help"){s.write([z("identities"),`  ${w("List all configured repeater and room server identities.")}`,"",B("identities","list identities"),"",z("Aliases"),`  ${w("id, ids")}`].join(`
`));return}const r=s.write("processing...","system");try{const o=await ol();if(!o.success||!o.data){s.update(r,o.error||"Failed to fetch identities","error");return}const a=o.data,h=(n=a.configured)!=null&&n.length?a.configured:a.registered||[];if(h.length===0){s.update(r,"No identities configured.","warning");return}const l=[z(`Identities (${h.length})`),"",...h.map((c,d)=>{var p;const u=c.name||"Unnamed",f=c.type||"unknown",_=((p=c.hash)==null?void 0:p.slice(0,8))||"—";return`  ${w(`${d+1}.`)} ${st(u)}  ${Pe(f)}  ${y(_)}`})];s.update(r,l.join(`
`))}catch(o){s.update(r,`Error: ${o instanceof Error?o.message:"Command failed"}`,"error")}}}class E_ extends ie{constructor(){super(...arguments);D(this,"name","keys");D(this,"description","List transport keys")}async execute({output:s,rawInput:i}){if(this.argsAfterName(i).toLowerCase().trim()==="help"){s.write([z("keys"),`  ${w("List configured transport encryption keys.")}`,"",B("keys","list transport keys")].join(`
`));return}const r=s.write("processing...","system");try{const n=await Sl();if(!n.success||!n.data){s.update(r,n.error||"Failed to fetch transport keys","error");return}const o=n.data;if(o.length===0){s.update(r,"No transport keys configured.","warning");return}const a=[z(`Transport Keys (${o.length})`),"",...o.map(h=>{const l=h.parent_id?`  ${Pe(`parent: ${h.parent_id}`)}`:"";return`  ${st(h.name)}  ${b("flood",y(h.flood_policy))}${l}`})];s.update(r,a.join(`
`))}catch(n){s.update(r,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}class R_ extends ie{constructor(){super(...arguments);D(this,"name","acl");D(this,"description","Show ACL statistics")}async execute({output:s,rawInput:i}){if(this.argsAfterName(i).toLowerCase().trim()==="help"){s.write([z("acl"),`  ${w("Display access control list statistics.")}`,"",B("acl","show ACL stats")].join(`
`));return}const r=s.write("processing...","system");try{const n=await al();if(!n.success||!n.data){s.update(r,n.error||"Failed to fetch ACL stats","error");return}const o=n.data,a=[z("ACL Stats"),"",`  ${b("Identities",y(String(o.total_identities)))}`,`  ${b("Total clients",y(String(o.total_clients)))}`,`  ${b("Admin",y(String(o.admin_clients)))}`,`  ${b("Guest",y(String(o.guest_clients)))}`];if(o.by_identity_type){const h=o.by_identity_type.repeater,l=o.by_identity_type.room_server;h&&a.push(`  ${b("Repeater",`${y(String(h.count))} ids  ${w(`${h.clients} clients`)}`)}`),l&&a.push(`  ${b("Room Server",`${y(String(l.count))} ids  ${w(`${l.clients} clients`)}`)}`)}s.update(r,a.join(`
`))}catch(n){s.update(r,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}class B_ extends ie{constructor(){super(...arguments);D(this,"name","rooms");D(this,"description","Show room server statistics")}async execute({output:s,rawInput:i}){if(this.argsAfterName(i).toLowerCase().trim()==="help"){s.write([z("rooms"),`  ${w("Display room server statistics and sync status.")}`,"",B("rooms","list rooms")].join(`
`));return}const r=s.write("processing...","system");try{const n=await ll();if(!n.success||!n.data){s.update(r,n.error||"Failed to fetch room stats","error");return}const o=n.data.rooms||[];if(o.length===0){s.update(r,"No room servers configured.","warning");return}const a=[z(`Rooms (${o.length})`),"",...o.map(h=>[`  ${st(h.room_name)}`,`    ${b("msgs",y(String(h.total_messages)))}  ${b("clients",`${y(String(h.active_clients))}${Pe(`/${h.total_clients}`)}`)}  ${b("sync",h.sync_running?y("running"):Pe("idle"))}`]).flat()];s.update(r,a.join(`
`))}catch(n){s.update(r,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}class L_ extends ie{constructor(){super(...arguments);D(this,"name","restart");D(this,"description","Restart openhop-repeater service");D(this,"aliases",["reboot"])}async execute({output:s,rawInput:i}){if(this.argsAfterName(i).toLowerCase().trim()==="help"){s.write([z("restart"),`  ${w("Restart the openhop-repeater systemd service.")}`,"",B("restart","restart the service"),"",z("Aliases"),`  ${w("reboot")}`,"",it("Requires polkit permissions for the web user."),it("The page will need a manual refresh after restart.")].join(`
`));return}const r=s.write("Restarting service...","system");try{const n=new AbortController,o=setTimeout(()=>n.abort(),8e3),a=await yl(n.signal);if(clearTimeout(o),a.success){s.update(r,"Service restart initiated.","success"),await this.waitForService(s);return}const h=a.status;if(h===403||h===401){s.update(r,`Error: Permission denied.

The web user needs polkit permissions to restart the service.
See: /etc/polkit-1/localauthority/50-local.d/openhop-repeater.pkla`,"error");return}s.update(r,a.error||"Restart failed","error")}catch(n){const o=n instanceof Error?n.message:"";o.includes("ERR_NETWORK")||o.includes("ECONNRESET")||o.includes("Failed to fetch")||o.includes("Load failed")||o.includes("network connection was lost")||o.includes("abort")||o.includes("timeout")||n instanceof DOMException&&n.name==="TimeoutError"||n instanceof DOMException&&n.name==="AbortError"?(s.update(r,"Service is restarting (connection dropped).","success"),await this.waitForService(s)):s.update(r,`Error: ${o||"Restart failed"}`,"error")}}waitForService(s){return new Promise(i=>{const r=s.write("Waiting for service...","system");let n=0;const o=30;setTimeout(()=>{const a=setInterval(async()=>{n++,s.update(r,`Waiting for service... ${n}s`,"system");try{const h=new AbortController,l=setTimeout(()=>h.abort(),3e3);await fetch(`${hl}/api/stats`,{signal:h.signal}),clearTimeout(l),clearInterval(a),s.update(r,`Service connected. (${n+4}s)`,"success"),i();return}catch{}n>=o&&(clearInterval(a),s.update(r,`Service did not respond within ${o+4}s. Check manually.`,"warning"),i())},1e3)},4e3)})}}const Wt="\x1B[",Oe=`${Wt}0m`,Ha=`${Wt}32m`,Fr=`${Wt}33m`,Wr=`${Wt}31m`,M_=`${Wt}36m`,Lt=`${Wt}90m`,Fa=`${Wt}1m`;function Xt(e){return e>=1073741824?`${(e/1073741824).toFixed(1)}G`:e>=1048576?`${(e/1048576).toFixed(0)}M`:e>=1024?`${(e/1024).toFixed(0)}K`:`${e}B`}function uo(e){const t=Math.floor(e/86400),s=Math.floor(e%86400/3600),i=Math.floor(e%3600/60);return t>0?`${t}d ${s}h ${i}m`:s>0?`${s}h ${i}m`:`${i}m`}function D_(e,t){const s=Math.max(0,Math.min(100,e)),i=Math.round(s/100*t),r=t-i,n=s>=90?Wr:s>=70?Fr:Ha,o=`${n}${"█".repeat(i)}${Oe}${Lt}${"░".repeat(r)}${Oe}`,a=`${s.toFixed(1)}%`.padStart(6);return`[${o}] ${n}${a}${Oe}`}function T_(e){return e>=80?`${Wr}${Fa}${e.toFixed(1)}°C${Oe}`:e>=60?`${Fr}${e.toFixed(1)}°C${Oe}`:`${Ha}${e.toFixed(1)}°C${Oe}`}const Cs=2,_o="  ";function Jt(e,t){const s=" ".repeat(Cs),i=t-Cs,r=_o.length,n=[];let o="",a=0;for(const h of e){const l=_u(h);a===0?(o=h,a=l):a+r+l<=i?(o+=_o+h,a+=r+l):(n.push(s+o),o=h,a=l)}return a>0&&n.push(s+o),n}function $_(e,t,s){var d,u;const i=e.node_name||"unknown",r=e.version?`v${e.version}`:"",n=(d=t.system)!=null&&d.uptime?uo(t.system.uptime):"?",o=uo(e.uptime_seconds||0),a=Math.max(3,s-Cs*2),h=((u=t.cpu.load_avg)==null?void 0:u["1min"].toFixed(2))??"?",l=t.cpu.load_avg?`${h} ${t.cpu.load_avg["5min"].toFixed(2)} ${t.cpu.load_avg["15min"].toFixed(2)}`:"?",c=s>=60?l:h;return[`  ${M_}${Fa}${i}${Oe}  ${Lt}${r}${Oe}`,`  ${Lt}${"─".repeat(a)}${Oe}`,...Jt([b("Sys",y(n)),b("Svc",y(o)),b("Load",y(c))],s)]}function A_(e,t){const i=Cs+4+1+2+6,r=Math.max(6,Math.min(30,t-i)),n=i+r,o=t-n-2,a=[""],h=`${e.cpu.count} core${e.cpu.count>1?"s":""}`,l=`${Xt(e.memory.used)}/${Xt(e.memory.total)}`,c=`${Xt(e.disk.used)}/${Xt(e.disk.total)}`,d=(f,_,p)=>{const g=D_(_,r),k=o>=p.length?`  ${Pe(p)}`:"";return`  ${w(f.padEnd(4))}${g}${k}`};a.push(d("CPU",e.cpu.usage_percent,h)),a.push(d("Mem",e.memory.usage_percent,l)),a.push(d("Dsk",e.disk.usage_percent,c));const u=Object.entries(e.temperatures||{});if(u.length>0){const f=u.map(([_,p])=>`${Pe(_+":")} ${T_(p)}`);a.push(...Jt(f,t))}return a}function P_(e,t){var l,c;const s=e.neighbors||{},i=Object.keys(s).length,r=Object.values(s).filter(d=>d.zero_hop).length,n=((c=(l=e.config)==null?void 0:l.repeater)==null?void 0:c.mode)||"?",o=e.noise_floor_dbm!=null?`${e.noise_floor_dbm}dBm`:"?",a=e.duty_cycle_percent??0,h=["",`  ${Lt}MESH${Oe}`];return h.push(...Jt([b("Mode",y(n)),b("Nbrs",`${y(String(r))}${Pe(`/${i}`)}`),b("Noise",y(o)),b("Air",y(`${a.toFixed(1)}%`))],t)),h.push(...Jt([b("RX",y(String(e.rx_count??0))),b("TX",y(String(e.tx_count??0))),b("FWD",y(String(e.forwarded_count??0))),b("Drop",y(String(e.dropped_count??0)))],t)),h.push(...Jt([b("RX/h",y(String(Math.round(e.rx_per_hour??0)))),b("FWD/h",y(String(Math.round(e.forwarded_per_hour??0))))],t)),h}function N_(e,t){if(!e.network)return[];const s=["",`  ${Lt}NET${Oe}`];return s.push(...Jt([b("TX",y(Xt(e.network.bytes_sent))),b("RX",y(Xt(e.network.bytes_recv))),b("Pkt",`${y(String(e.network.packets_sent))}${Pe("/")}${y(String(e.network.packets_recv))}`)],t)),s}function I_(e,t,s){if(e.length===0)return[];const i=t>=50,r=t>=50?6:5,n=t>=50?6:5,o=i?7:0,a=Cs+0,h=Math.max(4,t-a-o-r-n-4),l=3,c=t>=50?8:5,d=s!=null?Math.max(0,Math.min(c,s-l)):c;if(d<=0)return[];const u=["",`  ${Lt}PROCS${Oe}`],f=(i?"PID".padEnd(o):"")+"CPU".padStart(r)+"MEM".padStart(n)+"  NAME";u.push(`  ${Pe(f)}`);for(const _ of e.slice(0,d)){const p=i?Pe(String(_.pid).padEnd(o)):"",g=(t>=50?_.cpu_percent.toFixed(1):_.cpu_percent.toFixed(0)).padStart(r),k=(t>=50?_.memory_percent.toFixed(1):_.memory_percent.toFixed(0)).padStart(n),q=_.name.length>h?_.name.slice(0,h-1)+"…":_.name,H=_.cpu_percent>=50?Wr:_.cpu_percent>=20?Fr:"",T=H?`${H}${g}${Oe}`:g;u.push(`  ${p}${T}${Pe(k)}  ${q}`)}return u}function O_(){return new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}function fo(e,t,s,i,r){if(!e||!t)return`  ${Lt}Waiting for data…${Oe}`;const n=$_(e,t,i),o=A_(t,i),a=P_(e,i),h=N_(t,i),l=["",`  ${Lt}${O_()}  ·  Ctrl+C to exit${Oe}`],c=[...n,...o,...a,...h,...l],d=r?wr(c,i):0,u=r?Math.max(0,r-d):void 0,f=I_(s,i,u),_=[...c.slice(0,-l.length),...f,...l];return r&&_.length>r&&(_.length=r),_.join(`
`)}const H_=3e3;class F_ extends ie{constructor(){super(...arguments);D(this,"name","top");D(this,"description","Live system overview (Ctrl+C to exit)");D(this,"aliases",["htop"])}async execute({output:s,rawInput:i,cols:r,signal:n}){var l,c;if(this.argsAfterName(i).toLowerCase().trim()==="help"){s.write([z("top"),`  ${w("Live-updating system overview combining hardware")}`,`  ${w("stats, mesh metrics, and running processes.")}`,`  ${w("Refreshes every 3s. Press Ctrl+C to exit.")}`,"",B("top","start live display"),"",z("Sections"),`  ${w("Header     Node name, version, uptime, load average")}`,`  ${w("Gauges     CPU, memory, disk usage with bar charts")}`,`  ${w("Mesh       Mode, neighbors, packet counts, airtime")}`,`  ${w("Network    TCP/IP bytes and packet counters")}`,`  ${w("Processes  Top 8 processes by CPU usage")}`,"",z("Aliases"),`  ${w("htop")}`].join(`
`));return}let o=null,a=[],h=xt.getState().stats;try{const[d,u]=await Promise.all([ei(),Ur()]);d.success&&d.data&&(o=d.data),u.success&&u.data&&(a=u.data.processes.sort((f,_)=>_.cpu_percent-f.cpu_percent))}catch{}if(!n.aborted){(l=s.enterFullscreen)==null||l.call(s);try{const d=s.write(fo(h,o,a,s.cols??r,s.rows));await new Promise(u=>{if(n.aborted){u();return}const f=async()=>{h=xt.getState().stats;try{const[p,g]=await Promise.all([ei(),Ur()]);p.success&&p.data&&(o=p.data),g.success&&g.data&&(a=g.data.processes.sort((k,q)=>q.cpu_percent-k.cpu_percent))}catch{}n.aborted||s.update(d,fo(h,o,a,s.cols??r,s.rows))},_=setInterval(()=>{if(n.aborted){clearInterval(_),u();return}f()},H_);n.addEventListener("abort",()=>{clearInterval(_),u()},{once:!0})})}finally{(c=s.exitFullscreen)==null||c.call(s)}}}}const po=["DONT PANIC","C0FFEE","FEED C0DE","LOL","I CANNOT DO THAT"];function zr(){return po[Math.floor(Math.random()*po.length)]}const Cr=new EventTarget,xr="shell-phrase";function Wa(e){Cr.dispatchEvent(new CustomEvent(xr,{detail:e??zr()}))}function W_(e){const t=s=>e(s.detail);return Cr.addEventListener(xr,t),()=>Cr.removeEventListener(xr,t)}class z_ extends ie{constructor(){super(...arguments);D(this,"name","fortune");D(this,"description","Display a fortune on the header");D(this,"aliases",["lol"])}execute({output:s}){const i=zr();Wa(i),s.write(w(`  ${i}`))}}const kr=new EventTarget,Er="party-time";function U_(){kr.dispatchEvent(new Event(Er))}function j_(e){return kr.addEventListener(Er,e),()=>kr.removeEventListener(Er,e)}class K_ extends ie{constructor(){super(...arguments);D(this,"name","partytime");D(this,"description","Party on, Garth!");D(this,"aliases",["party","excellent","waynesworld"])}execute({output:s}){U_(),Wa("PARTY 0N GARTH"),s.write(w("  SCHWING!"))}}class q_ extends ie{constructor(){super(...arguments);D(this,"name","ver");D(this,"description","Show version info");D(this,"aliases",["version"])}async execute({output:s,rawInput:i}){if(this.argsAfterName(i).toLowerCase().trim()==="help"){s.write([z("ver"),`  ${w("Display pyMC_Repeater, core, and console version.")}`,`  ${w('Equivalent to firmware serial CLI "ver" command.')}`,"",B("ver","show version"),"",z("Aliases"),`  ${w("version")}`].join(`
`));return}const r=s.write("processing...","system");try{const n=await rt();s.update(r,[`  ${b("pyMC_Repeater",y(`v${n.version||"?"}`))}`,`  ${b("pyMC_Core",y(n.core_version||"?"))}`,`  ${b("pyMC_Console",y("v0.9.330"))}`].join(`
`),"value")}catch(n){s.update(r,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}class V_ extends ie{constructor(){super(...arguments);D(this,"name","clock");D(this,"description","Show system UTC time")}execute({output:s,rawInput:i}){if(this.argsAfterName(i).toLowerCase().trim()==="help"){s.write([z("clock"),`  ${w("Display the current system UTC time.")}`,`  ${w('Equivalent to firmware serial CLI "clock" command.')}`,`  ${w("Use to verify NTP sync and correlate packet timestamps.")}`,"",B("clock","show UTC time")].join(`
`));return}const r=new Date;s.write([`  ${b("UTC",y(r.toUTCString()))}`,`  ${b("ISO",y(r.toISOString()))}`,`  ${b("Unix",y(String(Math.floor(r.getTime()/1e3))))}`].join(`
`),"value")}}class G_ extends ie{constructor(){super(...arguments);D(this,"name","stats-packets");D(this,"description","Packet counters")}async execute({output:s,rawInput:i}){if(this.argsAfterName(i).toLowerCase().trim()==="help"){s.write([z("stats-packets"),`  ${w("Display packet counters: sent, received, forwarded, dropped.")}`,`  ${w('Equivalent to firmware serial CLI "stats-packets" command.')}`,"",B("stats-packets","show packet counters")].join(`
`));return}const r=s.write("processing...","system");try{const n=await rt(),o=n.rx_count??0,a=n.tx_count??0,h=n.forwarded_count??0,l=n.dropped_count??0,c=n.rx_per_hour??0,d=n.forwarded_per_hour??0,u=n.duplicate_cache_size??0;s.update(r,[`  ${st("Packet Counters")}`,"",`  ${b("RX",y(String(o)))}        ${w(`${c.toFixed(1)}/hr`)}`,`  ${b("TX",y(String(a)))}`,`  ${b("Forwarded",y(String(h)))}  ${w(`${d.toFixed(1)}/hr`)}`,`  ${b("Dropped",y(String(l)))}`,"",`  ${b("Dup cache",y(String(u)))}`].join(`
`),"value")}catch(n){s.update(r,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}function Pi(e){return e>=6e4?`${(e/6e4).toFixed(1)}m`:e>=1e3?`${(e/1e3).toFixed(1)}s`:`${e.toFixed(0)}ms`}class Y_ extends ie{constructor(){super(...arguments);D(this,"name","stats-radio");D(this,"description","Radio health stats")}async execute({output:s,rawInput:i}){var n;if(this.argsAfterName(i).toLowerCase().trim()==="help"){s.write([z("stats-radio"),`  ${w("Display radio health: airtime, noise floor, duty cycle.")}`,`  ${w('Equivalent to firmware serial CLI "stats-radio" command.')}`,"",B("stats-radio","show radio stats")].join(`
`));return}const r=s.write("processing...","system");try{const o=await rt(),a=(n=o.config)==null?void 0:n.radio,h=o.noise_floor_dbm,l=o.airtime_used_ms??0,c=o.airtime_remaining_ms??0,d=o.duty_cycle_percent??0,u=o.utilization_percent??0,f=o.total_airtime_ms??0,_=[`  ${st("Radio Stats")}`,""];if(a){const p=a.frequency?`${(a.frequency/1e6).toFixed(3)} MHz`:"?",g=a.bandwidth?`${a.bandwidth/1e3} kHz`:"?";_.push(`  ${b("Radio",y(`${p}  SF${a.spreading_factor??"?"}  BW ${g}  CR 4/${a.coding_rate??"?"}  ${a.tx_power??"?"} dBm`))}`),_.push("")}_.push(`  ${b("Noise floor",h!=null?y(`${h} dBm`):w("N/A"))}`),_.push(`  ${b("Airtime used",y(Pi(l)))}  ${w(`remaining: ${Pi(c)}`)}`),_.push(`  ${b("Total airtime",y(Pi(f)))}`),_.push(`  ${b("Duty cycle",y(`${d.toFixed(1)}%`))}`),_.push(`  ${b("Utilization",y(`${u.toFixed(1)}%`))}`),s.update(r,_.join(`
`),"value")}catch(o){s.update(r,`Error: ${o instanceof Error?o.message:"Command failed"}`,"error")}}}function mo(e){return e>=1073741824?`${(e/1073741824).toFixed(1)} GB`:e>=1048576?`${(e/1048576).toFixed(0)} MB`:`${(e/1024).toFixed(0)} KB`}class X_ extends ie{constructor(){super(...arguments);D(this,"name","stats-core");D(this,"description","Engine vitals")}async execute({output:s,rawInput:i}){if(this.argsAfterName(i).toLowerCase().trim()==="help"){s.write([z("stats-core"),`  ${w("Display engine vitals: uptime, memory, CPU, queue depth.")}`,`  ${w('Equivalent to firmware serial CLI "stats-core" command.')}`,`  ${w("On firmware this shows free heap — here we show Linux process health.")}`,"",B("stats-core","show core stats")].join(`
`));return}const r=s.write("processing...","system");try{const[n,o]=await Promise.all([rt(),ei()]),a=[`  ${st("Core Stats")}`,"",`  ${b("Uptime",y(Or(n.uptime_seconds??0)))}`,`  ${b("Dup cache",y(`${n.duplicate_cache_size??0} entries`))}  ${w(`TTL ${n.cache_ttl??"?"}s`)}`];if(o.success&&o.data){const h=o.data;a.push(""),a.push(`  ${b("CPU",y(`${h.cpu.usage_percent.toFixed(1)}%`))}  ${w(`${h.cpu.count} core${h.cpu.count>1?"s":""}`)}`),h.cpu.load_avg&&a.push(`  ${b("Load",y(`${h.cpu.load_avg["1min"].toFixed(2)} / ${h.cpu.load_avg["5min"].toFixed(2)} / ${h.cpu.load_avg["15min"].toFixed(2)}`))}`),a.push(`  ${b("Memory",y(`${mo(h.memory.used)} / ${mo(h.memory.total)}`))}  ${w(`${h.memory.usage_percent.toFixed(0)}%`)}`);const l=Object.entries(h.temperatures||{});l.length>0&&a.push(`  ${b("Temp",y(`${l[0][1].toFixed(1)}°C`))}`)}s.update(r,a.join(`
`),"value")}catch(n){s.update(r,`Error: ${n instanceof Error?n.message:"Command failed"}`,"error")}}}const Ni=["  @@@@@@   @@@@@@@   @@@@@@@@  @@@  @@@  @@@  @@@   @@@@@@   @@@@@@@   "," @@@@@@@@  @@@@@@@@  @@@@@@@@  @@@@ @@@  @@@  @@@  @@@@@@@@  @@@@@@@@  ","@@!  @@@  @@!  @@@  @@!       @@!@!@@@  @@!  @@@  @@!  @@@  @@!  @@@  ","!@!  @!@  !@!  @!@  !@!       !@!!@!@!  !@!  @!@  !@!  @!@  !@!  @!@  ","@!@  !@!  @!@@!@!   @!!!:!    @!@ !!@!  @!@!@!@!  @!@  !@!  @!@@!@!   ","!@!  !!!  !!@!!!    !!!!!:    !@!  !!!  !!!@!!!!  !@!  !!!  !!@!!!    ","!!:  !!!  !!:       !!:       !!:  !!!  !!:  !!!  !!:  !!!  !!:       ",":!:  !:!  :!:       :!:       :!:  !:!  :!:  !:!  :!:  !:!  :!:       ","::::: ::   ::        :: ::::   ::   ::  ::   :::  ::::: ::   ::       "," : :  :    :        : :: ::   ::    :    :   : :   : :  :    :        "],go=Do-1;class J_ extends ie{constructor(){super(...arguments);D(this,"name","hello");D(this,"description","Play the openHop burst intro");D(this,"aliases",["hi","intro"])}async execute({output:s,signal:i}){if(i.aborted)return;let r=0;const n=s.write(vs(Ni,0).join(`
`));try{await new Promise(o=>{const a=setInterval(()=>{if(i.aborted||r>=go){clearInterval(a),i.aborted||s.update(n,vs(Ni,go).join(`
`)),o();return}r++,s.update(n,vs(Ni,r).join(`
`))},Lo);i.addEventListener("abort",()=>{clearInterval(a),o()},{once:!0})})}finally{Mo()}}}function Z_(){const e=new Jd,t=new Eu(e);return e.register(t,new Ru,new Bu,new q_,new V_,new Lu,new Mu,new Du,new G_,new Y_,new X_,new ju,new Qu,new c_,new e_,new s_,new d_,new x_,new k_,new E_,new R_,new B_,new L_,new F_,new z_,new K_,new J_),e}const Q_=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)}),vo=Ro(e=>({entries:[],commandHistory:[],isInitialized:!1,addEntry:t=>{const s=Q_(),i={...t,id:s,timestamp:Date.now()};return e(r=>({entries:[...r.entries,i]})),s},updateEntry:(t,s)=>{e(i=>({entries:i.entries.map(r=>r.id===t?{...r,...s}:r)}))},addCommand:t=>{e(s=>({commandHistory:[...s.commandHistory,t]}))},clearEntries:()=>{e({entries:[],commandHistory:[]})},setInitialized:t=>{e({isInitialized:t})}}));function ef({isOpen:e,onClose:t}){const s=Pa(),i=xt(n=>n.stats),r=n=>{const o=s.find(a=>a.id===n);o&&Oa(o,i)};return m.jsxs(To,{open:e,onClose:t,size:"sm",children:[m.jsx($o,{icon:m.jsx(jr,{size:20}),title:"Download Captures",onClose:t}),m.jsx(Ao,{className:"flex flex-col gap-2",children:s.length===0?m.jsxs("div",{className:"flex flex-col items-center gap-2 py-6 text-fg-muted",children:[m.jsx(Tl,{className:"w-8 h-8 opacity-40"}),m.jsx("p",{className:"text-sm",children:"No captures available."})]}):s.map(n=>m.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 radius-inset bg-elevated/50 border border-edge-subtle",children:[m.jsxs("div",{className:"flex-1 min-w-0",children:[m.jsx("p",{className:"type-label text-fg-primary truncate",children:n.filename}),m.jsxs("p",{className:"text-xs text-fg-muted mt-0.5",children:[n.packetCount," packets · ",n.durationSec,"s · ~",Zs(n.sizeBytes)]})]}),m.jsx(cl,{plain:!0,color:"primary",onClick:()=>r(n.id),title:"Download",className:"flex-shrink-0",children:m.jsx(jr,{"data-slot":"icon"})})]},n.id))})]})}function tf(){const e=Pa(),[t,s]=U.useState(!1);return m.jsxs(m.Fragment,{children:[m.jsx(Po,{icon:m.jsx(Ml,{size:20}),onClick:()=>s(!0),title:e.length>0?`Download captures (${e.length})`:"Captures",variant:"red",iconActiveColor:ve.red}),m.jsx(ef,{isOpen:t,onClose:()=>s(!1)})]})}const So=[{name:"acl",description:"Access control list statistics — identity and client counts.",body:["```","> acl","ACL Stats","","  Identities     2","  Total clients  5","  Admin          2","  Guest          3","  Repeater       1 ids  3 clients","  Room Server    1 ids  2 clients","```"],searchText:"acl access control list statistics identity client"},{name:"advert",description:"Broadcast a repeater advertisement to the mesh.",body:["```","> advert","✓ Advert sent","```"],searchText:"advert advertisement broadcast mesh"},{name:"board",description:"Hardware and platform info — CPU, memory, disk, temperatures, network I/O.",body:["```","> board","  Node     Local-Node","  Runtime  pyMC_Repeater v1.0.0","  Core     v1.12.0","","  CPU      12.3%  4 cores","  Load     0.42 / 0.38 / 0.35","  Temp     48.2°C","","  Memory   412 MB / 664 MB  62%","  Disk     5.2 GB / 28.7 GB  18%","","  System uptime   14d 3h 22m","  Service uptime  2d 14h 32m","  Net TX/RX       128 MB / 342 MB","```"],searchText:"board hardware platform cpu memory disk temperature network"},{name:"cap",description:"Packet capture — start, stop, list, and export captures.",body:["**Sub-commands:** `start cap [sec]` · `end cap` · `list cap` · `export cap [id]`","","**`start cap [seconds]`** — Begin capture (default 120s, max 3600):","```","> start cap","Capturing... 118s remaining (4 captured)","","✓ Capture complete!","  Captured: 23 packets","  Duration: 120s","  Size: ~14.2 KB","```","","**`end cap`** — Stop capture early:","```","> end cap","✓ Capture stopped!","  Captured: 12 packets","```","","**`list cap`** — List saved captures:","```","> list cap","Capture Reports (2):","  1. 23 pkts • 120s • ~14.2 KB (id: abc123)","  2. 12 pkts • 34s • ~7.1 KB (id: def456)","```","","**`export cap [id]`** — Download by ID or index:","```","> export cap 1","✓ Downloading capture-abc123.json...","```"],searchText:"cap capture packet start end list export download diagnostic"},{name:"clear",description:"Clear the terminal screen.",body:["**Alias:** `cls`","```","> clear","```"],searchText:"clear cls screen"},{name:"clock",description:"Current system UTC time. Useful for NTP sync and packet timestamp correlation.",body:["```","> clock","  UTC   Wed, 12 Feb 2026 00:01:34 GMT","  ISO   2026-02-12T00:01:34.000Z","  Unix  1770768094","```"],searchText:"clock time utc ntp unix iso timestamp"},{name:"convert",description:"Convert between hex and base64 encodings.",body:["**Usage:** `convert hex <value>` · `convert base64 <value>`","```","> convert hex 48656C6C6F","  hex     48656C6C6F","  base64  SGVsbG8=","","> convert base64 SGVsbG8=","  base64  SGVsbG8=","  hex     48656C6C6F","```"],searchText:"convert hex base64 encoding decode"},{name:"get",description:"Read a configuration parameter.",body:[],interactive:"get",searchText:"get read config parameter name role lat lon radio freq tx bw sf cr txdelay mode duty flood advert"},{name:"help",description:"Show all commands, or detailed help for a specific command.",body:["**Alias:** `?` · `h`","```","> help           Full command listing","> help ping      Detailed help for ping","> ping help      Same thing","```"],searchText:"help commands reference guide"},{name:"identities",description:"List all configured repeater and room server identities.",body:["**Alias:** `id` · `ids`","```","> identities","Identities (2)","","  1. Local-Node   repeater     0A1B2C3D","  2. local-room   room_server  0E5F6A7B","```"],searchText:"identities id ids repeater room server identity"},{name:"keys",description:"List configured transport encryption keys.",body:["```","> keys","Transport Keys (1)","","  main-transport  flood: allow","```"],searchText:"keys transport encryption"},{name:"neighbors",description:"Direct RF neighbors with signal quality, RSSI, SNR, distance, and last-heard.",body:["**Alias:** `nb`","","**Sort qualifiers:** `sig` · `name` · `rssi` · `snr` · `dist` · `heard`","```","> neighbors","Direct Neighbors (4)","","+-------+-----------+-----------+--------+-------+--------+","| ▁▃▅▇█ | Node-1 | -87 dBm  | 8.5 dB | 2.1km | 3m ago |","| ▁▃▅▇. | Relay-2   | -94 dBm  | 5.2 dB | 4.8km | 1m ago |","| ▁▃▅.. | Node-3   | -108 dBm | 1.0 dB | 8.3km | 5m ago |","| ▁▃... | Node-4  | -118 dBm | -3 dB  | 14km  | 12m ago|","+-------+-----------+-----------+--------+-------+--------+","| SIG   | NAME      | RSSI      | SNR    | DIST  | HEARD  |","+-------+-----------+-----------+--------+-------+--------+","SF11/250kHz  ant 3.5dBi  nf -112dBm","```","","- **sig** — signal grade (weakest first)","- **name** — alphabetical","- **rssi** — RSSI (weakest first)","- **snr** — SNR (lowest first)","- **dist** — distance (closest first)","- **heard** — last seen (oldest first)"],searchText:"neighbors nb signal rssi snr distance sort direct rf"},{name:"packets",description:"Packet counters — received, transmitted, forwarded, dropped.",body:["```","> packets","Packet Stats  1321 total","","  Received     1284","  Transmitted  37","  Forwarded    891","  Dropped      14","```"],searchText:"packets received transmitted forwarded dropped counter"},{name:"ping",description:"Ping a neighbor by name or hex prefix. Shows RTT, signal quality, and path.",body:["**Usage:** `ping <target> [timeout]`","```","> ping Node-1","▁▃▅▇█ Reply from Node-1","","  RTT      342ms","  RSSI     -87 dBm","  SNR      8.5 dB","  Path     direct","  Quality  Excellent","```","","Custom timeout (default 30s):","```","> ping Node-4 60","```"],searchText:"ping rtt round trip time signal quality path neighbor"},{name:"restart",description:"Restart the pymc-repeater systemd service.",body:["**Alias:** `reboot`","```","> restart","Service is restarting (connection dropped).","Waiting for service... 8s","Service connected. (12s)","```","","The terminal polls automatically until the service comes back up."],searchText:"restart reboot service systemd"},{name:"rooms",description:"Room server statistics — message counts, active clients, sync status.",body:["```","> rooms","Rooms (1)","","  Local Room","    msgs 142  clients 3/5  sync running","```"],searchText:"rooms room server messages clients sync"},{name:"set",description:"Write a configuration parameter.",body:[],interactive:"set",searchText:"set write config parameter name lat lon freq tx bw sf cr txdelay mode duty log flood advert"},{name:"stats-core",description:"Engine vitals — uptime, duplicate cache, CPU, memory, temperature.",body:["```","> stats-core","  Core Stats","","  Uptime     2d 14h 32m","  Dup cache  128 entries  TTL 900s","","  CPU        12.3%  4 cores","  Load       0.42 / 0.38 / 0.35","  Memory     412 MB / 664 MB  62%","  Temp       48.2°C","```"],searchText:"stats core engine vitals uptime cache cpu memory temperature"},{name:"stats-packets",description:"Firmware-compatible packet counters with rates and duplicate cache depth.",body:["```","> stats-packets","  Packet Counters","","  RX         1284        22.4/hr","  TX         37","  Forwarded  891   15.2/hr","  Dropped    14","","  Dup cache  128","```"],searchText:"stats packets firmware counter rate duplicate cache"},{name:"stats-radio",description:"Radio health — noise floor, airtime, duty cycle, and radio configuration.",body:["```","> stats-radio","  Radio Stats","","  Radio        906.875 MHz  SF11  BW 250 kHz  CR 4/5  22 dBm","","  Noise floor  -112 dBm","  Airtime used 4.2s  remaining: 55.8m","  Total airtime 1.2m","  Duty cycle   1.2%","  Utilization  0.8%","```"],searchText:"stats radio noise floor airtime duty cycle utilization"},{name:"status",description:"Quick summary of mode, neighbors, and uptime.",body:["**Alias:** `st`","```","> status","Local-Node  repeater","","  Mode       forward","  Neighbors  4 direct  12 total","  RX / TX    1284 / 37","  Uptime     2d 14h 32m","```"],searchText:"status st summary mode neighbors uptime"},{name:"top",description:"Live-updating system overview — CPU/memory gauges, mesh counters, processes.",body:["**Alias:** `htop`","","Refreshes every 3s. Press **Ctrl+C** to exit.","```","> top","Local-Node  v1.0.0","──────────────────────────────────","  Sys 14d 3h 22m  Svc 2d 14h 32m  Load 0.42 0.38 0.35","","  CPU [████░░░░░░░░░░░░]  12.3%  4 cores","  Mem [██████████░░░░░░]  62.1%  412M/664M","  Dsk [███░░░░░░░░░░░░░]  18.4%  5.2G/28.7G","  cpu_thermal: 48.2°C","","  MESH","  Mode forward  Nbrs 4/12  Noise -112dBm  Air 1.2%","  RX 1284  TX 37  FWD 891  Drop 14","  RX/h 22  FWD/h 15","","  PROCS","    CPU   MEM  NAME","    8.2   3.1  python3","    2.1   1.4  cherrypy","","  14:32:08  ·  Ctrl+C to exit","```","","Uses alternate screen buffer — scrollback is preserved."],searchText:"top htop live system overview cpu memory gauges mesh processes"},{name:"uptime",description:"How long the repeater service has been running.",body:["```","> uptime","Uptime  2d 14h 32m","```"],searchText:"uptime service running duration"},{name:"ver",description:"Version info for all three components.",body:["**Alias:** `version`","```","> ver","  pyMC_Repeater  v1.0.0","  pyMC_Core      v1.12.0","  pyMC_Console   v1.0.0","```"],searchText:"ver version pymc repeater core console"}],sf=[{param:"name",category:"Identity",example:["> get name","name  Local-Node"]},{param:"role",category:"Identity",example:["> get role","role  repeater"]},{param:"lat",category:"Identity",example:["> get lat","lat  34.0522"],range:"-90 to 90"},{param:"lon",category:"Identity",example:["> get lon","lon  -118.2437"],range:"-180 to 180"},{param:"public.key",category:"Identity",example:["> get public.key","public.key  0A1B2C3D4E5F..."]},{param:"radio",category:"Radio",example:["> get radio","  freq  906.875 MHz","  bw    250 kHz","  sf    11","  cr    4/5","  tx    22 dBm"]},{param:"freq",category:"Radio",example:["> get freq","freq  906.875 MHz"],range:"100–1000 MHz"},{param:"tx",category:"Radio",example:["> get tx","tx  22 dBm"],range:"2–22 dBm"},{param:"bw",category:"Radio",example:["> get bw","bw  250 kHz"],range:"7.8–500 kHz"},{param:"sf",category:"Radio",example:["> get sf","sf  11"],range:"5–12"},{param:"cr",category:"Radio",example:["> get cr","cr  4/5"],range:"5–8"},{param:"af",category:"Timing",example:["> get af","⚠ airtime_factor not yet exposed by pyMC_Repeater API.","  Firmware range: 0-9. Tracked in CLI-Alignment.md."],range:"0–9 (pending)"},{param:"txdelay",category:"Timing",example:["> get txdelay","txdelay  1.0"],range:"0.0–5.0"},{param:"direct.txdelay",category:"Timing",example:["> get direct.txdelay","direct.txdelay  0.5"],range:"0.0–5.0"},{param:"rxdelay",category:"Timing",example:["> get rxdelay","rxdelay  0.0"],range:"≥ 0"},{param:"mode",category:"Repeater",example:["> get mode","mode  forward"],range:"forward / monitor"},{param:"duty",category:"Repeater",example:["> get duty","duty  on"],range:"on / off"},{param:"flood.max",category:"Repeater",example:["> get flood.max","flood.max  3"],range:"0–64"},{param:"advert.interval",category:"Repeater",example:["> get advert.interval","advert.interval  120m"],range:"0 (off) or 1–10080 min"},{param:"multi.acks",category:"Advanced",example:["> get multi.acks","multi.acks  0"],range:"0–255"},{param:"int.thresh",category:"Advanced",example:["> get int.thresh","int.thresh  -120 dBm"],range:"-200 to 0 dBm"},{param:"agc.reset.interval",category:"Advanced",example:["> get agc.reset.interval","agc.reset.interval  0"],range:"≥ 0 (×4)"}],rf=[{param:"name",category:"Identity",example:["> set name Local-Node","OK - node_name set to Local-Node"],range:"text (no [ ] \\ / : , ? *)"},{param:"lat",category:"Identity",example:["> set lat 34.0522","OK - latitude set to 34.0522"],range:"-90 to 90"},{param:"lon",category:"Identity",example:["> set lon -118.2437","OK - longitude set to -118.2437"],range:"-180 to 180"},{param:"freq",category:"Radio",example:["> set freq 906.875","OK - frequency set to 906875000"],range:"100–1000 MHz"},{param:"tx",category:"Radio",example:["> set tx 22","OK - tx_power set to 22"],range:"2–22 dBm"},{param:"bw",category:"Radio",example:["> set bw 250","OK - bandwidth set to 250000"],range:"7.8, 10.4, 15.6, 20.8, 31.25, 41.7, 62.5, 125, 250, 500 kHz"},{param:"sf",category:"Radio",example:["> set sf 11","OK - spreading_factor set to 11"],range:"5–12"},{param:"cr",category:"Radio",example:["> set cr 5","OK - coding_rate set to 5"],range:"5–8"},{param:"af",category:"Timing",example:["> set af 2","⚠ airtime_factor not yet exposed by pyMC_Repeater API.","  Firmware range: 0-9. Needs backend support."],range:"0–9 (pending)"},{param:"txdelay",category:"Timing",example:["> set txdelay 1.0","OK - tx_delay_factor set to 1"],range:"0.0–5.0"},{param:"direct.txdelay",category:"Timing",example:["> set direct.txdelay 0.5","OK - direct_tx_delay_factor set to 0.5"],range:"0.0–5.0"},{param:"rxdelay",category:"Timing",example:["> set rxdelay 0","OK - rx_delay_base set to 0"],range:"≥ 0"},{param:"mode",category:"Repeater",example:["> set mode forward","OK - Mode set to forward"],range:"forward / monitor"},{param:"flood.max",category:"Repeater",example:["> set flood.max 3","OK - max_flood_hops set to 3"],range:"0–64"},{param:"advert.interval",category:"Repeater",example:["> set advert.interval 120","OK - Local advert interval set to 120m"],range:"0 (off) or 1–10080 min"},{param:"duty",category:"Repeater",example:["> set duty on","OK - Duty cycle enabled"],range:"on / off"},{param:"log",category:"Repeater",example:["> set log info","OK - Log level set to INFO"],range:"debug, info, warning, error"},{param:"multi.acks",category:"Advanced",example:["> set multi.acks 0","OK - multi_acks set to 0"],range:"0–255"},{param:"int.thresh",category:"Advanced",example:["> set int.thresh -120","OK - interference_threshold set to -120"],range:"-200 to 0 dBm"},{param:"agc.reset.interval",category:"Advanced",example:["> set agc.reset.interval 8","OK - AGC reset interval set to 8"],range:"≥ 0 (rounded to ×4)"},{param:"prv.key",category:"Advanced",example:["> set prv.key <128-hex>","To set this key, run on the Pi:","","  sudo ./convert_firmware_key.sh <key>","","Then restart: sudo systemctl restart pymc-repeater"],range:"128-char hex (SSH only)"}];function nf({mode:e}){const t=e==="get"?sf:rf,[s,i]=U.useState(0),r=t[s],n=U.useMemo(()=>{const o=new Map;for(const a of t){const h=o.get(a.category)||[];h.push(a),o.set(a.category,h)}return Array.from(o.entries())},[t]);return m.jsxs("div",{className:"flex flex-col gap-2",children:[m.jsx("div",{className:"flex flex-col gap-1.5",children:n.map(([o,a])=>m.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[m.jsx("span",{className:"text-xs text-fg-muted w-16 shrink-0 text-right pr-1",children:o}),a.map(h=>{const l=t.indexOf(h),c=l===s;return m.jsx("button",{onClick:()=>i(l),className:ti("px-1.5 py-0.5 type-data-xs radius-badge transition-colors cursor-pointer",c?"bg-sys-blue text-fg-invert font-semibold":"bg-elevated text-fg-secondary hover:bg-elevated/80 hover:text-sys-blue"),children:h.param},h.param)})]},o))}),m.jsx("pre",{className:"px-3 py-2.5 radius-inner bg-body text-fg-secondary type-code overflow-x-auto border border-edge-subtle",children:r.example.map((o,a)=>m.jsx("div",{children:o||" "},a))}),r.range&&m.jsxs("p",{className:"text-xs text-fg-muted",children:[m.jsx("span",{className:"text-fg-secondary font-medium",children:r.param})," — ",r.range]})]})}function yo(e,t){const s=e.split(/(\*\*[^*]+\*\*)/g);return m.jsx("span",{children:s.map((i,r)=>i.startsWith("**")&&i.endsWith("**")?m.jsx("strong",{className:"text-fg-primary font-semibold",children:i.slice(2,-2)},r):i.split(/(`[^`]+`)/g).map((o,a)=>o.startsWith("`")&&o.endsWith("`")?m.jsx("code",{className:"px-1 py-0.5 radius-badge bg-elevated text-sys-blue type-data-xs",children:o.slice(1,-1)},`${r}-${a}`):m.jsx("span",{children:o},`${r}-${a}`)))},t)}function of({lines:e}){const t=[];let s=0;for(;s<e.length;){const i=e[s];if(i==="```"){const r=[];for(s++;s<e.length&&e[s]!=="```";)r.push(e[s]),s++;s++,t.push(m.jsx("pre",{className:"px-3 py-2.5 my-2 radius-inner bg-body text-fg-secondary type-code overflow-x-auto border border-edge-subtle",children:r.map((n,o)=>m.jsx("div",{children:n||" "},o))},t.length));continue}if(!i.trim()){t.push(m.jsx("div",{className:"h-1.5"},t.length)),s++;continue}if(i.startsWith("- ")){t.push(m.jsxs("div",{className:"flex gap-2 text-sm text-fg-secondary pl-2 py-0.5",children:[m.jsx("span",{className:"text-fg-muted shrink-0",children:"•"}),m.jsx("span",{children:yo(i.slice(2),0)})]},t.length)),s++;continue}t.push(m.jsx("p",{className:"text-sm text-fg-secondary py-0.5",children:yo(i,0)},t.length)),s++}return m.jsx(m.Fragment,{children:t})}function af({isOpen:e,onClose:t,onUseCommand:s}){const[i,r]=U.useState(""),n=U.useMemo(()=>{if(!i.trim())return So;const a=i.toLowerCase();return So.filter(h=>h.name.includes(a)||h.searchText.includes(a)||h.description.toLowerCase().includes(a))},[i]),o=i.trim().length>0;return m.jsxs(To,{open:e,onClose:t,size:"3xl",motionPlus:!0,className:"sm:min-w-[540px] md:min-w-[680px]",children:[m.jsx($o,{icon:m.jsx(No,{size:20}),title:"Terminal Command Guide",onClose:t}),m.jsxs(Ao,{className:"flex flex-col gap-0 !px-0 !py-0",children:[m.jsx("div",{className:"sticky top-0 z-10 px-5 py-3 border-b border-edge-subtle bg-surface/95 backdrop-blur-sm",children:m.jsxs("div",{className:"relative",children:[m.jsx(Vr,{size:14,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-fg-muted"}),m.jsx("input",{type:"text",value:i,onChange:a=>r(a.target.value),placeholder:"Search commands...",className:"w-full pl-8 pr-3 py-1.5 text-sm bg-elevated border border-edge-subtle radius-inner text-fg-primary placeholder:text-fg-muted focus:outline-none focus:ring-1 focus:ring-sys-blue/50",autoFocus:!0})]})}),m.jsxs("div",{className:"overflow-y-auto px-5 py-3 h-[420px] sm:h-[520px] md:h-[600px]",children:[m.jsx(fi,{mode:"popLayout",children:n.length===0?m.jsxs($s.div,{initial:{opacity:0,scale:.96},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.96},transition:{duration:qr.normal,ease:Kr.easeOut},className:"flex flex-col items-center gap-2 py-10 text-fg-muted",children:[m.jsx(Vr,{className:"w-6 h-6 opacity-40"}),m.jsxs("p",{className:"text-sm",children:['No commands match "',i,'"']})]},"empty"):m.jsx($s.div,{initial:!1,className:"flex flex-col gap-1",children:m.jsx(fi,{initial:!1,children:n.map(a=>m.jsx($s.div,{layout:"position",initial:{opacity:0,y:-4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:dl.fade,className:"min-w-0",children:m.jsx(ul,{children:({open:h})=>m.jsxs("div",{className:ti("radius-inner border transition-colors",h?"border-edge-subtle bg-elevated/50":"border-transparent hover:bg-elevated/30"),children:[m.jsxs("div",{className:"flex items-center w-full min-w-0",children:[m.jsxs(_l,{className:"flex items-center gap-3 flex-1 min-w-0 px-3 py-2 text-left cursor-pointer",children:[m.jsx(kl,{size:14,className:ti("shrink-0 text-fg-muted transition-transform duration-150",h&&"rotate-90")}),m.jsx("code",{className:"text-sm font-semibold text-sys-blue font-mono shrink-0",children:a.name}),m.jsx("span",{className:"text-xs text-fg-muted truncate min-w-0",children:a.description})]}),s&&m.jsx("button",{onClick:l=>{l.stopPropagation(),s(a.name)},className:"shrink-0 mr-2 px-2 py-0.5 text-xs font-semibold uppercase tracking-wider radius-badge bg-elevated text-fg-muted hover:text-sys-blue hover:bg-elevated/80 transition-colors cursor-pointer",title:`Use "${a.name}" in terminal`,children:"use"})]}),m.jsx(fl,{className:"px-3 pb-3 pt-0 pl-9",children:a.interactive?m.jsx(nf,{mode:a.interactive}):m.jsx(of,{lines:a.body})})]})})},a.name))})},"list")}),m.jsx(fi,{children:!o&&m.jsxs($s.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},exit:{opacity:0,y:6},transition:{duration:qr.normal,ease:Kr.easeOut},className:"mt-4 px-3 py-3 radius-inner border border-edge-subtle bg-elevated/30",children:[m.jsx("p",{className:"text-xs font-semibold text-fg-muted mb-2",children:"Tips"}),m.jsxs("div",{className:"flex flex-col gap-1 text-xs text-fg-muted",children:[m.jsxs("p",{children:["Type ",m.jsx("code",{className:"px-1 py-0.5 radius-badge bg-elevated text-sys-blue font-mono",children:"<command> help"})," in the terminal for detailed usage."]}),m.jsxs("p",{children:["Most commands have shorter aliases (e.g. ",m.jsx("code",{className:"px-1 py-0.5 radius-badge bg-elevated text-sys-blue font-mono",children:"st"}),", ",m.jsx("code",{className:"px-1 py-0.5 radius-badge bg-elevated text-sys-blue font-mono",children:"nb"}),", ",m.jsx("code",{className:"px-1 py-0.5 radius-badge bg-elevated text-sys-blue font-mono",children:"id"}),")."]}),m.jsxs("p",{children:["Signal bars ",m.jsx("span",{className:"font-mono",children:"▁▃▅▇█"})," are colored by link quality grade based on RSSI, SNR, and radio config."]}),m.jsx("p",{children:"Captures are stored in browser session only — export before closing the tab."})]})]})})]})]})]})}function lf({onUseCommand:e}){const[t,s]=U.useState(!1),i=e?r=>{s(!1),e(r)}:void 0;return m.jsxs(m.Fragment,{children:[m.jsx(Po,{icon:m.jsx(No,{size:17,className:"translate-y-px"}),onClick:()=>s(!0),title:"CLI Command Guide"}),m.jsx(af,{isOpen:t,onClose:()=>s(!1),onUseCommand:i})]})}const za=Z_(),Qs=za.all().flatMap(e=>[{cmd:e.name,desc:e.description,params:e.params,required:!!e.params},...e.aliases.filter(t=>t.includes(" ")).map(t=>({cmd:t,desc:e.description,params:e.params,required:!!e.params}))]);Qs.push({cmd:"start cap",desc:"Start packet capture",params:"[seconds]",required:!0},{cmd:"end cap",desc:"Stop capture"},{cmd:"list cap",desc:"List captures"},{cmd:"export cap",desc:"Download capture",params:"[id]",required:!0});const Ws=["sig","name","rssi","snr","dist","heard"],hf={get:["name","role","lat","lon","radio","freq","tx","bw","sf","cr","af","txdelay","direct.txdelay","rxdelay","mode","repeat","flood.max","flood.advert.interval","advert.interval","duty","duty.max","multi.acks","int.thresh","agc.reset.interval","public.key","prv.key"],set:["name","lat","lon","freq","tx","bw","sf","cr","af","txdelay","direct.txdelay","rxdelay","mode","repeat","flood.max","flood.advert.interval","advert.interval","duty","log","multi.acks","int.thresh","agc.reset.interval","prv.key"],convert:["hex","base64"],neighbors:Ws,nb:Ws,"get neighbors":Ws,"get neighbor":Ws,"set mode":["forward","monitor"],"set duty":["on","off"],"set repeat":["on","off"],"set tx":["10","14","17","20","22"],"set sf":["7","8","9","10","11","12"],"set bw":["125","250","500"],"set cr":["5","6","7","8"],"set af":["0.5","1.0","1.5","2.0"],"set txdelay":["0.5","0.7","1.0","1.5"],"set direct.txdelay":["0.3","0.5","0.7"],"set log":["debug","info","warning","error"],"start cap":["30","60","120","300"]},Ii=["  @@@@@@   @@@@@@@   @@@@@@@@  @@@  @@@  @@@  @@@   @@@@@@   @@@@@@@   "," @@@@@@@@  @@@@@@@@  @@@@@@@@  @@@@ @@@  @@@  @@@  @@@@@@@@  @@@@@@@@  ","@@!  @@@  @@!  @@@  @@!       @@!@!@@@  @@!  @@@  @@!  @@@  @@!  @@@  ","!@!  @!@  !@!  @!@  !@!       !@!!@!@!  !@!  @!@  !@!  @!@  !@!  @!@  ","@!@  !@!  @!@@!@!   @!!!:!    @!@ !!@!  @!@!@!@!  @!@  !@!  @!@@!@!   ","!@!  !!!  !!@!!!    !!!!!:    !@!  !!!  !!!@!!!!  !@!  !!!  !!@!!!    ","!!:  !!!  !!:       !!:       !!:  !!!  !!:  !!!  !!:  !!!  !!:       ",":!:  !:!  :!:       :!:       :!:  !:!  :!:  !:!  :!:  !:!  :!:       ","::::: ::   ::        :: ::::   ::   ::  ::   :::  ::::: ::   ::       "," : :  :    :        : :: ::   ::    :    :   : :   : :  :    :        "];function ds(){return/Android|iPhone|iPad|iPod/i.test(navigator.userAgent)||window.innerWidth<640}function cf(e,t){const s=e.toLowerCase(),i=s.trim();if(!i)return[];const r=s.length>i.length&&s.endsWith(" ");if(!i.includes(" ")&&!r)return Qs.filter(h=>h.cmd.toLowerCase().startsWith(i));const n=r?i:i.substring(0,i.lastIndexOf(" ")),o=r?"":i.substring(i.lastIndexOf(" ")+1);if(n==="ping"&&t.length>0)return t.filter(h=>h.toLowerCase().startsWith(o)).slice(0,10).map(h=>({cmd:`ping ${h}`,desc:`→ ${h}`}));const a=hf[n];if(a){const h=a.filter(l=>l.toLowerCase().startsWith(o)).map(l=>({cmd:`${n} ${l}`,desc:`→ ${l}`}));if(!r&&o){const l=new Set(h.map(c=>c.cmd));for(const c of Qs){const d=c.cmd.toLowerCase();d.startsWith(i)&&!l.has(d)&&(h.push(c),l.add(d))}}return h}return Qs.filter(h=>h.cmd.toLowerCase().startsWith(i))}function xf(){const e=pl(),{addCommand:t}=vo(),s=U.useRef(null),i=U.useRef(null),r=U.useRef(null),n=U.useRef(null),o=U.useRef(""),a=U.useRef(-1),h=U.useRef(""),l=U.useRef(!1),c=U.useRef(null),d=U.useRef(!1),u=U.useRef(!1),f=U.useRef(!1),_=U.useRef(!1),p=U.useRef([]),g=U.useRef(()=>{}),k=ml(),[q,H]=U.useState("C0dE"),[T,N]=U.useState(!1),F=U.useRef(null),Z=7,me=280,X="C0dE",oe=U.useCallback(E=>{F.current&&(clearInterval(F.current),F.current=null);const A=X.padEnd(Z),W=A+"  "+E+"  "+A;let O=0;const K=W.length-Z;N(!0),H(W.slice(0,Z)),F.current=setInterval(()=>{if(O++,O>K){clearInterval(F.current),F.current=null,N(!1),H(X);return}H(W.slice(O,O+Z))},me)},[]);U.useEffect(()=>{const E=W_(oe),A=setInterval(()=>{Math.random()<.02&&oe(zr())},45e3);return()=>{E(),clearInterval(A),F.current&&clearInterval(F.current)}},[oe]);const[J,P]=U.useState(!1),S=U.useRef(null);U.useEffect(()=>{const E=j_(()=>{S.current&&clearTimeout(S.current),P(!0),S.current=setTimeout(()=>P(!1),5e3)});return()=>{E(),S.current&&clearTimeout(S.current)}},[]);const[L,C]=U.useState({show:!1,options:[],selectedIndex:0,input:""}),M=U.useRef([]),I=U.useRef(0);U.useEffect(()=>{e!=null&&e.neighbors&&(p.current=Object.values(e.neighbors).map(E=>E.node_name||E.name).filter(E=>!!E).sort())},[e==null?void 0:e.neighbors]);const R=U.useCallback(()=>{var E;(E=i.current)==null||E.write(iu(gl()))},[]),V=U.useCallback(()=>{const E=i.current;E&&(E.write(Fs),R(),E.write(o.current))},[R]),ee=U.useCallback(E=>{const A=cf(E,p.current);M.current=A,I.current=0;const W=A.length>0&&E.trim().length>0;C({show:W,options:A,selectedIndex:0,input:E.trim()})},[]),Se=U.useCallback(()=>{M.current=[],I.current=0,C({show:!1,options:[],selectedIndex:0,input:""})},[]),$e=U.useCallback(E=>{var W;const A=M.current[E];A&&(o.current=A.required?A.cmd+" ":A.cmd,V(),A.required?ee(o.current):Se(),(W=i.current)==null||W.focus())},[V,ee,Se]),Ne=U.useCallback(async E=>{const A=i.current;if(!A)return;const W=E.trim();if(!W){R();return}l.current=!0;const O=new AbortController;c.current=O,t(W),a.current=-1;let K=0;const ue={get cols(){return A.cols},get rows(){return A.rows},write(te,be="default"){const zt=(be==="default"?te:Un(te,be)).split(`
`);for(const Dt of zt)A.writeln(Dt);return K=wr(zt,A.cols),String(K)},update(te,be,Mt){if(f.current)A.write(hu);else if(K>0)for(let gt=0;gt<K;gt++)A.write(au()),A.write(Fs);const Dt=(Mt?Un(be,Mt):be).split(`
`);if(f.current){for(const gt of Dt)A.write(gt+lu+`\r
`);A.write(cu)}else for(const gt of Dt)A.writeln(gt);K=wr(Dt,A.cols)},clear(){A.clear(),K=0},enterFullscreen(){A.write(du+uu),f.current=!0,K=0},exitFullscreen(){A.write(qn+Kn),f.current=!1,K=0}};A.writeln("");const je=za.find(W);if(je){const te=W.split(/\s+/);try{await je.execute({output:ue,args:te,rawInput:W,cols:A.cols,signal:O.signal})}catch(be){be instanceof DOMException&&be.name==="AbortError"||ue.write(`Error: ${be instanceof Error?be.message:"Command failed"}`,"error")}}else ue.write(`Unknown command: ${W}
Type 'help' for available commands.`,"error");c.current=null,l.current=!1,A.writeln(""),R()},[t,R]),re=U.useCallback(E=>{const A=i.current;if(!A||!u.current)return;if(l.current){for(let K=0;K<E.length;K++)E.charCodeAt(K)===3&&c.current&&(c.current.abort(),A.writeln("^C"));return}const W=vo.getState().commandHistory,O=K=>requestAnimationFrame(()=>{var ue;return(ue=document.querySelector(`[data-ac-index="${K}"]`))==null?void 0:ue.scrollIntoView({block:"nearest"})});for(let K=0;K<E.length;K++){const ue=E.charCodeAt(K);if(ue===13){if(M.current.length>0){const te=M.current[I.current];te&&(o.current=te.cmd,V())}Se();const je=o.current;o.current="",A.writeln(""),Ne(je);continue}if(ue===127||ue===8){o.current.length>0&&(o.current=o.current.slice(0,-1),A.write("\b \b"),ee(o.current));continue}if(ue===3){o.current="",Se(),A.writeln("^C"),R();continue}if(ue===12){A.clear(),Se(),V();continue}if(ue===9){M.current.length>0&&$e(I.current);continue}if(ue===27){if(E.charCodeAt(K+1)===91){const je=E.charCodeAt(K+2);if(K+=2,je===65){if(M.current.length>0){const te=Math.max(I.current-1,0);I.current=te,C(be=>({...be,selectedIndex:te})),O(te)}else W.length>0&&(a.current===-1&&(h.current=o.current),a.current<W.length-1&&(a.current++,o.current=W[W.length-1-a.current]||"",V()));continue}if(je===66){if(M.current.length>0){const te=Math.min(I.current+1,M.current.length-1);I.current=te,C(be=>({...be,selectedIndex:te})),O(te)}else a.current>0?(a.current--,o.current=W[W.length-1-a.current]||"",V()):a.current===0&&(a.current=-1,o.current=h.current,V());continue}if(je===67||je===68)continue;continue}M.current.length>0&&Se();continue}ue>=32&&(o.current+=E[K],A.write(E[K]),a.current=-1,ee(o.current))}},[Se,ee,$e,R,V,Ne]);U.useEffect(()=>{g.current=re},[re]);const Ge=U.useCallback(async()=>{const E=i.current;if(!E||d.current)return;d.current=!0,_.current=!1;const A="\x1B[94m",W="\x1B[0m",O=()=>_.current,K=Ii.length,ue=Do-1;try{const te=vs(Ii,0);for(const be of te)E.writeln(be);await new Promise(be=>{let Mt=0;const zt=setInterval(()=>{if(O()){clearInterval(zt),be();return}if(Mt>=ue){clearInterval(zt),be();return}Mt++,E.write(`\x1B[${K}F`);const Dt=vs(Ii,Mt);for(const gt of Dt)E.write(`\x1B[2K${gt}
`)},Lo)})}finally{Mo()}if(O()||(E.writeln(""),E.write(w("● Initializing terminal...")),await new Promise(te=>setTimeout(te,300)),O())||(E.write(Fs),E.writeln(`${A}✓ Initializing terminal...${W}`),E.write(w("● Connecting to repeater...")),await new Promise(te=>setTimeout(te,500)),O()))return;E.write(Fs),vl.getState().health==="connected"?E.writeln(`${A}✓ Connected to repeater${W}`):E.writeln(su("~ Connection status unknown")),E.writeln(w("Ready. Type 'help' for commands.")),E.writeln(""),R(),u.current=!0},[R]);U.useEffect(()=>{const E=s.current;if(!E)return;const A=ds()?12:13,W=new Wd({theme:La(),fontFamily:'"JetBrains Mono", "IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',fontSize:A,lineHeight:ds()?1.1:1,cursorBlink:!1,cursorStyle:"underline",scrollback:1e4,convertEol:!0,allowTransparency:!0,rightClickSelectsWord:!1}),O=new jd;W.loadAddon(O),W.loadAddon(new Xd),W.open(E),O.fit(),i.current=W,r.current=O;const K=W.onData(te=>g.current(te)),ue=mu(W),je=new ResizeObserver(()=>{requestAnimationFrame(()=>O.fit())});return je.observe(E),Ge(),ds()||W.focus(),()=>{var te;_.current=!0,(te=c.current)==null||te.abort(),f.current&&(W.write(qn+Kn),f.current=!1),K.dispose(),ue(),je.disconnect(),W.dispose(),i.current=null,r.current=null,d.current=!1,u.current=!1}},[]);const We=U.useCallback(E=>{const A=E.target.value;A.length>0&&(re(A),E.target.value="")},[re]),ut=U.useCallback(E=>{E.key==="Enter"?(E.preventDefault(),re("\r")):E.key==="Backspace"?(E.preventDefault(),re("")):E.key==="ArrowUp"?(E.preventDefault(),re("\x1B[A")):E.key==="ArrowDown"&&(E.preventDefault(),re("\x1B[B"))},[re]),ss=U.useCallback(()=>{var E,A;ds()?(E=n.current)==null||E.focus():(A=i.current)==null||A.focus()},[]);U.useEffect(()=>{if(!ds())return;const E=()=>{var K;const O=(K=s.current)==null?void 0:K.querySelector(".xterm-viewport");O&&(O.scrollTop=O.scrollHeight),requestAnimationFrame(()=>{var ue;return(ue=r.current)==null?void 0:ue.fit()})},A=window.visualViewport;if(A){const O=()=>{A.height<window.innerHeight*.75&&E()};return A.addEventListener("resize",O),()=>A.removeEventListener("resize",O)}const W=n.current;if(W){const O=()=>setTimeout(E,300);return W.addEventListener("focus",O),()=>W.removeEventListener("focus",O)}},[]);const nt=U.useCallback(E=>{o.current=E+" ",V(),ee(o.current),setTimeout(()=>{var A;(A=s.current)==null||A.click()},400)},[V,ee]);return m.jsx(wl,{children:m.jsx(bl,{ready:!0,children:m.jsxs("div",{className:"terminal-card flex flex-col gap-1 sm:gap-1.5",children:[m.jsxs("div",{className:"card-terminal-header flex-wrap",children:[m.jsx("span",{className:"seven-seg-panel",children:m.jsx(xl,{text:q,minChars:7,size:24,noCycle:T})}),m.jsx("div",{className:"header-well self-stretch flex-col sm:order-first",children:m.jsxs("div",{className:`indicator-key${k==="connected"?" indicator-key--active":k==="degraded"?" indicator-key--sending":""}`,children:[m.jsx("span",{className:"indicator-key__label",children:"ONLINE"}),m.jsx("span",{className:"indicator-key__led"})]})}),m.jsx("div",{className:"card-terminal-ridge flex-1 min-w-4 sm:hidden"}),m.jsxs("div",{className:"header-well flex items-center gap-1 sm:order-last",children:[m.jsx(lf,{onUseCommand:nt}),m.jsx(tf,{})]}),m.jsx("div",{className:"card-terminal-ridge flex-1 min-w-8 hidden sm:block"})]}),m.jsx(Cl,{noPadding:!0,isLoaded:!0,className:"flex flex-col flex-1 min-h-0 overflow-hidden card-terminal",onClick:ss,children:m.jsxs("div",{className:"card-terminal-well flex-1 min-h-0 flex flex-col overflow-hidden",children:[m.jsxs("div",{className:"flex-1 min-h-0 terminal-gutter relative",children:[m.jsx("div",{ref:s,className:"h-full w-full"}),J&&m.jsxs("div",{className:"absolute inset-0 z-10 flex items-center justify-center",onClick:()=>P(!1),children:[m.jsx("div",{className:"absolute inset-0 animate-[partytime-bg_5s_ease-out_forwards]",style:{background:"rgba(0,0,0,0.82)"}}),m.jsxs("div",{className:"relative z-10 animate-[partytime-crt_5s_ease-out_forwards] partytime-glow",children:[m.jsx("img",{src:"/assets/partytime.gif",alt:"No way.",className:"max-h-[60vh] max-w-[70vw] object-contain rounded"}),m.jsx("div",{className:"absolute inset-0 pointer-events-none rounded partytime-scanlines"})]})]})]}),L.show&&L.options.length>0&&m.jsxs("div",{className:"flex-shrink-0 overflow-hidden terminal-completions",style:{borderTop:"1px solid var(--terminal-border)",background:"var(--terminal-bg-input)"},children:[m.jsx("div",{className:"overflow-y-auto",style:{maxHeight:"176px"},children:L.options.map((E,A)=>{const W=A===L.selectedIndex,O=L.input.length;return m.jsxs("div",{"data-ac-index":A,onClick:()=>$e(A),className:ti("terminal-ac-option",W?"text-sys-blue":"text-fg-primary"),style:{background:W?"var(--terminal-autocomplete-hover)":void 0},onMouseEnter:K=>{W||(K.currentTarget.style.background="var(--terminal-autocomplete-hover)")},onMouseLeave:K=>{W||(K.currentTarget.style.background="")},children:[m.jsx("span",{className:"terminal-ac-option__indicator",children:W?"▸":""}),m.jsxs("span",{className:"terminal-ac-option__cmd",children:[m.jsx("span",{className:"font-semibold text-sys-blue",children:E.cmd.substring(0,O)}),E.cmd.substring(O)]}),m.jsx("span",{className:"terminal-ac-option__desc",children:E.desc})]},E.cmd)})}),m.jsxs("div",{className:"terminal-ac-hints",children:[m.jsx("span",{className:"hidden sm:inline",children:"Tab · ↑↓ · Esc"}),m.jsx("span",{className:"sm:hidden",children:"Tap to select"}),m.jsxs("span",{children:[L.options.length," match",L.options.length!==1?"es":""]})]})]}),m.jsxs("div",{className:"terminal-mobile-input-bar sm:hidden",children:[m.jsx("input",{ref:n,type:"text",className:"terminal-mobile-input",onChange:We,onKeyDown:ut,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,enterKeyHint:"send","aria-label":"Terminal input",placeholder:"Type command..."}),m.jsx("button",{type:"button",className:"terminal-send-btn",onClick:()=>re("\r"),"aria-label":"Run command",children:m.jsx(Bl,{})})]}),m.jsxs("div",{className:"terminal-status-bar",children:[m.jsx("span",{className:"hidden sm:inline",children:"↑↓ History · Tab · Esc"}),m.jsx("span",{className:"sm:hidden",children:"Tap input to type"}),(e==null?void 0:e.version)&&m.jsxs("span",{children:["pyMC v",e.version]})]})]})})]})})})}export{xf as default};
