/**
 * 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
 */
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var he=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?Z.isErrorNoTelemetry(e)?new Z(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)}},ze=new he;function ee(o){Ve(o)||ze.onUnexpectedError(o)}var fe="Canceled";function Ve(o){return o instanceof X?!0:o instanceof Error&&o.name===fe&&o.message===fe}var X=class extends Error{constructor(){super(fe),this.name=this.message}};var Z=class o extends Error{constructor(e){super(e),this.name="CodeExpectedError"}static fromError(e){if(e instanceof o)return e;let t=new o;return t.message=e.message,t.stack=e.stack,t}static isErrorNoTelemetry(e){return e.name==="CodeExpectedError"}};function pe(o,e){let t=this,n=!1,i;return function(){if(n)return i;if(n=!0,e)try{i=o.apply(t,arguments)}finally{e()}else i=o.apply(t,arguments);return i}}function je(o,e,t=0,n=o.length){let i=t,s=n;for(;i<s;){let u=Math.floor((i+s)/2);e(o[u])?i=u+1:s=u}return i-1}var te=class te{constructor(e){this._array=e;this._findLastMonotonousLastIdx=0}findLastMonotonous(e){if(te.assertInvariants){if(this._prevFindLastPredicate){for(let n of this._array)if(this._prevFindLastPredicate(n)&&!e(n))throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.")}this._prevFindLastPredicate=e}let t=je(this._array,e,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=t+1,t===-1?void 0:this._array[t]}};te.assertInvariants=!1;var ye=te;var Ee;(l=>{function o(r){return r<0}l.isLessThan=o;function e(r){return r<=0}l.isLessThanOrEqual=e;function t(r){return r>0}l.isGreaterThan=t;function n(r){return r===0}l.isNeitherLessOrGreaterThan=n,l.greaterThan=1,l.lessThan=-1,l.neitherLessOrGreaterThan=0})(Ee||={});function De(o,e){return(t,n)=>e(o(t),o(n))}var we=(o,e)=>o-e;var F=class F{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(e){return new F(t=>this.iterate(n=>e(n)?t(n):!0))}map(e){return new F(t=>this.iterate(n=>t(e(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>e(n)?(t=n,!1):!0),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(i=>((n||Ee.isGreaterThan(e(i,t)))&&(n=!1,t=i),!0)),t}};F.empty=new F(e=>{});var Ie=F;function Ce(o,e){let t=Object.create(null);for(let n of o){let i=e(n),s=t[i];s||(s=t[i]=[]),s.push(n)}return t}var Le,ke,Se=class{constructor(e,t){this.toKey=t;this._map=new Map;this[Le]="SetWithKey";for(let n of e)this.add(n)}get size(){return this._map.size}add(e){let t=this.toKey(e);return this._map.set(t,e),this}delete(e){return this._map.delete(this.toKey(e))}has(e){return this._map.has(this.toKey(e))}*entries(){for(let e of this._map.values())yield[e,e]}keys(){return this.values()}*values(){for(let e of this._map.values())yield e}clear(){this._map.clear()}forEach(e,t){this._map.forEach(n=>e.call(t,n,n,this))}[(ke=Symbol.iterator,Le=Symbol.toStringTag,ke)](){return this.values()}};var ne=class{constructor(){this.map=new Map}add(e,t){let n=this.map.get(e);n||(n=new Set,this.map.set(e,n)),n.add(t)}delete(e,t){let n=this.map.get(e);n&&(n.delete(t),n.size===0&&this.map.delete(e))}forEach(e,t){let n=this.map.get(e);n&&n.forEach(t)}get(e){let t=this.map.get(e);return t||new Set}};var Te;(j=>{function o(T){return T&&typeof T=="object"&&typeof T[Symbol.iterator]=="function"}j.is=o;let e=Object.freeze([]);function t(){return e}j.empty=t;function*n(T){yield T}j.single=n;function i(T){return o(T)?T:n(T)}j.wrap=i;function s(T){return T||e}j.from=s;function*u(T){for(let g=T.length-1;g>=0;g--)yield T[g]}j.reverse=u;function l(T){return!T||T[Symbol.iterator]().next().done===!0}j.isEmpty=l;function r(T){return T[Symbol.iterator]().next().value}j.first=r;function f(T,g){let x=0;for(let L of T)if(g(L,x++))return!0;return!1}j.some=f;function v(T,g){for(let x of T)if(g(x))return x}j.find=v;function*b(T,g){for(let x of T)g(x)&&(yield x)}j.filter=b;function*w(T,g){let x=0;for(let L of T)yield g(L,x++)}j.map=w;function*k(T,g){let x=0;for(let L of T)yield*g(L,x++)}j.flatMap=k;function*A(...T){for(let g of T)yield*g}j.concat=A;function O(T,g,x){let L=x;for(let K of T)L=g(L,K);return L}j.reduce=O;function*I(T,g,x=T.length){for(g<0&&(g+=T.length),x<0?x+=T.length:x>T.length&&(x=T.length);g<x;g++)yield T[g]}j.slice=I;function E(T,g=Number.POSITIVE_INFINITY){let x=[];if(g===0)return[x,T];let L=T[Symbol.iterator]();for(let K=0;K<g;K++){let ce=L.next();if(ce.done)return[x,j.empty()];x.push(ce.value)}return[x,{[Symbol.iterator](){return L}}]}j.consume=E;async function y(T){let g=[];for await(let x of T)g.push(x);return Promise.resolve(g)}j.asyncToArray=y})(Te||={});var Ke=!1,P=null,ie=class ie{constructor(){this.livingDisposables=new Map}getDisposableData(e){let t=this.livingDisposables.get(e);return t||(t={parent:null,source:null,isSingleton:!1,value:e,idx:ie.idx++},this.livingDisposables.set(e,t)),t}trackDisposable(e){let t=this.getDisposableData(e);t.source||(t.source=new Error().stack)}setParent(e,t){let n=this.getDisposableData(e);n.parent=t}markAsDisposed(e){this.livingDisposables.delete(e)}markAsSingleton(e){this.getDisposableData(e).isSingleton=!0}getRootParent(e,t){let n=t.get(e);if(n)return n;let i=e.parent?this.getRootParent(this.getDisposableData(e.parent),t):e;return t.set(e,i),i}getTrackedDisposables(){let e=new Map;return[...this.livingDisposables.entries()].filter(([,n])=>n.source!==null&&!this.getRootParent(n,e).isSingleton).flatMap(([n])=>n)}computeLeakingDisposables(e=10,t){let n;if(t)n=t;else{let r=new Map,f=[...this.livingDisposables.values()].filter(b=>b.source!==null&&!this.getRootParent(b,r).isSingleton);if(f.length===0)return;let v=new Set(f.map(b=>b.value));if(n=f.filter(b=>!(b.parent&&v.has(b.parent))),n.length===0)throw new Error("There are cyclic diposable chains!")}if(!n)return;function i(r){function f(b,w){for(;b.length>0&&w.some(k=>typeof k=="string"?k===b[0]:b[0].match(k));)b.shift()}let v=r.source.split(`
`).map(b=>b.trim().replace("at ","")).filter(b=>b!=="");return f(v,["Error",/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),v.reverse()}let s=new ne;for(let r of n){let f=i(r);for(let v=0;v<=f.length;v++)s.add(f.slice(0,v).join(`
`),r)}n.sort(De(r=>r.idx,we));let u="",l=0;for(let r of n.slice(0,e)){l++;let f=i(r),v=[];for(let b=0;b<f.length;b++){let w=f[b];w=`(shared with ${s.get(f.slice(0,b+1).join(`
`)).size}/${n.length} leaks) at ${w}`;let A=s.get(f.slice(0,b).join(`
`)),O=Ce([...A].map(I=>i(I)[b]),I=>I);delete O[f[b]];for(let[I,E]of Object.entries(O))v.unshift(`    - stacktraces of ${E.length} other leaks continue with ${I}`);v.unshift(w)}u+=`


==================== Leaking disposable ${l}/${n.length}: ${r.value.constructor.name} ====================
${v.join(`
`)}
============================================================

`}return n.length>e&&(u+=`


... and ${n.length-e} more leaking disposables

`),{leaks:n,details:u}}};ie.idx=0;var Re=ie;function Qe(o){P=o}if(Ke){let o="__is_disposable_tracked__";Qe(new class{trackDisposable(e){let t=new Error("Potentially leaked disposable").stack;setTimeout(()=>{e[o]||console.log(t)},3e3)}setParent(e,t){if(e&&e!==C.None)try{e[o]=!0}catch{}}markAsDisposed(e){if(e&&e!==C.None)try{e[o]=!0}catch{}}markAsSingleton(e){}})}function re(o){return P?.trackDisposable(o),o}function oe(o){P?.markAsDisposed(o)}function $(o,e){P?.setParent(o,e)}function $e(o,e){if(P)for(let t of o)P.setParent(t,e)}function U(o){if(Te.is(o)){let e=[];for(let t of o)if(t)try{t.dispose()}catch(n){e.push(n)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"Encountered errors while disposing of store");return Array.isArray(o)?[]:o}else if(o)return o.dispose(),o}function ae(...o){let e=q(()=>U(o));return $e(o,e),e}function q(o){let e=re({dispose:pe(()=>{oe(e),o()})});return e}var se=class se{constructor(){this._toDispose=new Set;this._isDisposed=!1;re(this)}dispose(){this._isDisposed||(oe(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{U(this._toDispose)}finally{this._toDispose.clear()}}add(e){if(!e)return e;if(e===this)throw new Error("Cannot register a disposable on itself!");return $(e,this),this._isDisposed?se.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(e),e}delete(e){if(e){if(e===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),$(e,null))}};se.DISABLE_DISPOSED_WARNING=!1;var N=se,C=class{constructor(){this._store=new N;re(this),$(this._store,this)}dispose(){oe(this),this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};C.None=Object.freeze({dispose(){}});var H=class{constructor(){this._isDisposed=!1;re(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&$(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,oe(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&$(e,null),e}};var W=class W{constructor(e){this.element=e,this.next=W.Undefined,this.prev=W.Undefined}};W.Undefined=new W(void 0);var Oe=W;var He=globalThis.performance&&typeof globalThis.performance.now=="function",le=class o{static create(e){return new o(e)}constructor(e){this._now=He&&e===!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}};var qe=!1,Ae=!1,Be=!1,Ge;(G=>{G.None=()=>C.None;function e(h){if(Be){let{onDidAddListener:a}=h,c=B.create(),d=0;h.onDidAddListener=()=>{++d===2&&(console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here"),c.print()),a?.()}}}function t(h,a){return w(h,()=>{},0,void 0,!0,void 0,a)}G.defer=t;function n(h){return(a,c=null,d)=>{let p=!1,m;return m=h(_=>{if(!p)return m?m.dispose():p=!0,a.call(c,_)},null,d),p&&m.dispose(),m}}G.once=n;function i(h,a,c){return v((d,p=null,m)=>h(_=>d.call(p,a(_)),null,m),c)}G.map=i;function s(h,a,c){return v((d,p=null,m)=>h(_=>{a(_),d.call(p,_)},null,m),c)}G.forEach=s;function u(h,a,c){return v((d,p=null,m)=>h(_=>a(_)&&d.call(p,_),null,m),c)}G.filter=u;function l(h){return h}G.signal=l;function r(...h){return(a,c=null,d)=>{let p=ae(...h.map(m=>m(_=>a.call(c,_))));return b(p,d)}}G.any=r;function f(h,a,c,d){let p=c;return i(h,m=>(p=a(p,m),p),d)}G.reduce=f;function v(h,a){let c,d={onWillAddFirstListener(){c=h(p.fire,p)},onDidRemoveLastListener(){c?.dispose()}};a||e(d);let p=new R(d);return a?.add(p),p.event}function b(h,a){return a instanceof Array?a.push(h):a&&a.add(h),h}function w(h,a,c=100,d=!1,p=!1,m,_){let D,S,M,Y=0,Q,xe={leakWarningThreshold:m,onWillAddFirstListener(){D=h(Ue=>{Y++,S=a(S,Ue),d&&!M&&(J.fire(S),S=void 0),Q=()=>{let We=S;S=void 0,M=void 0,(!d||Y>1)&&J.fire(We),Y=0},typeof c=="number"?(clearTimeout(M),M=setTimeout(Q,c)):M===void 0&&(M=0,queueMicrotask(Q))})},onWillRemoveListener(){p&&Y>0&&Q?.()},onDidRemoveLastListener(){Q=void 0,D.dispose()}};_||e(xe);let J=new R(xe);return _?.add(J),J.event}G.debounce=w;function k(h,a=0,c){return G.debounce(h,(d,p)=>d?(d.push(p),d):[p],a,void 0,!0,void 0,c)}G.accumulate=k;function A(h,a=(d,p)=>d===p,c){let d=!0,p;return u(h,m=>{let _=d||!a(m,p);return d=!1,p=m,_},c)}G.latch=A;function O(h,a,c){return[G.filter(h,a,c),G.filter(h,d=>!a(d),c)]}G.split=O;function I(h,a=!1,c=[],d){let p=c.slice(),m=h(S=>{p?p.push(S):D.fire(S)});d&&d.add(m);let _=()=>{p?.forEach(S=>D.fire(S)),p=null},D=new R({onWillAddFirstListener(){m||(m=h(S=>D.fire(S)),d&&d.add(m))},onDidAddFirstListener(){p&&(a?setTimeout(_):_())},onDidRemoveLastListener(){m&&m.dispose(),m=null}});return d&&d.add(D),D.event}G.buffer=I;function E(h,a){return(d,p,m)=>{let _=a(new j);return h(function(D){let S=_.evaluate(D);S!==y&&d.call(p,S)},void 0,m)}}G.chain=E;let y=Symbol("HaltChainable");class j{constructor(){this.steps=[]}map(a){return this.steps.push(a),this}forEach(a){return this.steps.push(c=>(a(c),c)),this}filter(a){return this.steps.push(c=>a(c)?c:y),this}reduce(a,c){let d=c;return this.steps.push(p=>(d=a(d,p),d)),this}latch(a=(c,d)=>c===d){let c=!0,d;return this.steps.push(p=>{let m=c||!a(p,d);return c=!1,d=p,m?p:y}),this}evaluate(a){for(let c of this.steps)if(a=c(a),a===y)break;return a}}function T(h,a,c=d=>d){let d=(...D)=>_.fire(c(...D)),p=()=>h.on(a,d),m=()=>h.removeListener(a,d),_=new R({onWillAddFirstListener:p,onDidRemoveLastListener:m});return _.event}G.fromNodeEventEmitter=T;function g(h,a,c=d=>d){let d=(...D)=>_.fire(c(...D)),p=()=>h.addEventListener(a,d),m=()=>h.removeEventListener(a,d),_=new R({onWillAddFirstListener:p,onDidRemoveLastListener:m});return _.event}G.fromDOMEventEmitter=g;function x(h){return new Promise(a=>n(h)(a))}G.toPromise=x;function L(h){let a=new R;return h.then(c=>{a.fire(c)},()=>{a.fire(void 0)}).finally(()=>{a.dispose()}),a.event}G.fromPromise=L;function K(h,a){return h(c=>a.fire(c))}G.forward=K;function ce(h,a,c){return a(c),h(d=>a(d))}G.runAndSubscribe=ce;class Ne{constructor(a,c){this._observable=a;this._counter=0;this._hasChanged=!1;let d={onWillAddFirstListener:()=>{a.addObserver(this)},onDidRemoveLastListener:()=>{a.removeObserver(this)}};c||e(d),this.emitter=new R(d),c&&c.add(this.emitter)}beginUpdate(a){this._counter++}handlePossibleChange(a){}handleChange(a,c){this._hasChanged=!0}endUpdate(a){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function tt(h,a){return new Ne(h,a).emitter.event}G.fromObservable=tt;function nt(h){return(a,c,d)=>{let p=0,m=!1,_={beginUpdate(){p++},endUpdate(){p--,p===0&&(h.reportChanges(),m&&(m=!1,a.call(c)))},handlePossibleChange(){},handleChange(){m=!0}};h.addObserver(_),h.reportChanges();let D={dispose(){h.removeObserver(_)}};return d instanceof N?d.add(D):Array.isArray(d)&&d.push(D),D}}G.fromObservableLight=nt})(Ge||={});var z=class z{constructor(e){this.listenerCount=0;this.invocationCount=0;this.elapsedOverall=0;this.durations=[];this.name=`${e}_${z._idPool++}`,z.all.add(this)}start(e){this._stopWatch=new le,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};z.all=new Set,z._idPool=0;var me=z,Me=-1;var de=class de{constructor(e,t,n=(de._idPool++).toString(16).padStart(3,"0")){this._errorHandler=e;this.threshold=t;this.name=n;this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t<n)return;this._stacks||(this._stacks=new Map);let i=this._stacks.get(e.value)||0;if(this._stacks.set(e.value,i+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=n*.5;let[s,u]=this.getMostFrequentStack(),l=`[${this.name}] potential listener LEAK detected, having ${t} listeners already. MOST frequent listener (${u}):`;console.warn(l),console.warn(s);let r=new be(l,s);this._errorHandler(r)}return()=>{let s=this._stacks.get(e.value)||0;this._stacks.set(e.value,s-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,i]of this._stacks)(!e||t<i)&&(e=[n,i],t=i);return e}};de._idPool=1;var ve=de,B=class o{constructor(e){this.value=e}static create(){let e=new Error;return new o(e.stack??"")}print(){console.warn(this.value.split(`
`).slice(2).join(`
`))}},be=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},ge=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},Ye=0,V=class{constructor(e){this.value=e;this.id=Ye++}},Je=2,Xe=(o,e)=>{if(o instanceof V)e(o);else for(let t=0;t<o.length;t++){let n=o[t];n&&e(n)}},ue;if(qe){let o=[];setInterval(()=>{o.length!==0&&(console.warn("[LEAKING LISTENERS] GC'ed these listeners that were NOT yet disposed:"),console.warn(o.join(`
`)),o.length=0)},3e3),ue=new FinalizationRegistry(e=>{typeof e=="string"&&o.push(e)})}var R=class{constructor(e){this._size=0;this._options=e,this._leakageMon=Me>0||this._options?.leakWarningThreshold?new ve(e?.onListenerError??ee,this._options?.leakWarningThreshold??Me):void 0,this._perfMon=this._options?._profName?new me(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){if(!this._disposed){if(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners){if(Ae){let e=this._listeners;queueMicrotask(()=>{Xe(e,t=>t.stack?.print())})}this._listeners=void 0,this._size=0}this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose()}}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let r=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(r);let f=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],v=new ge(`${r}. HINT: Stack shows most frequent listener (${f[1]}-times)`,f[0]);return(this._options?.onListenerError||ee)(v),C.None}if(this._disposed)return C.None;t&&(e=e.bind(t));let i=new V(e),s,u;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(i.stack=B.create(),s=this._leakageMon.check(i.stack,this._size+1)),Ae&&(i.stack=u??B.create()),this._listeners?this._listeners instanceof V?(this._deliveryQueue??=new _e,this._listeners=[this._listeners,i]):this._listeners.push(i):(this._options?.onWillAddFirstListener?.(this),this._listeners=i,this._options?.onDidAddFirstListener?.(this)),this._size++;let l=q(()=>{ue?.unregister(l),s?.(),this._removeListener(i)});if(n instanceof N?n.add(l):Array.isArray(n)&&n.push(l),ue){let r=new Error().stack.split(`
`).slice(2,3).join(`
`).trim(),f=/(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(r);ue.register(l,f?.[2]??r,l)}return l},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-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--,t[n]=void 0;let i=this._deliveryQueue.current===this;if(this._size*Je<=t.length){let s=0;for(let u=0;u<t.length;u++)t[u]?t[s++]=t[u]:i&&(this._deliveryQueue.end--,s<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=s}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||ee;if(!n){e.value(t);return}try{e.value(t)}catch(i){n(i)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof V)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}this._perfMon?.stop()}hasListeners(){return this._size>0}};var _e=class{constructor(){this.i=-1;this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}};var Fe=" ~!@#$%^&*()+`-=[]{}|\\;:\"',./<>?",Ze=15*1e3,et=1e3,Pe=class extends C{constructor(t){super();this._highlightedLines=new Set;this._highlightDecorations=[];this._selectedDecoration=this._register(new H);this._linesCacheTimeoutId=0;this._linesCacheDisposables=new H;this._onDidChangeResults=this._register(new R);this.onDidChangeResults=this._onDidChangeResults.event;this._highlightLimit=t?.highlightLimit??et}activate(t){this._terminal=t,this._register(this._terminal.onWriteParsed(()=>this._updateMatches())),this._register(this._terminal.onResize(()=>this._updateMatches())),this._register(q(()=>this.clearDecorations()))}_updateMatches(){this._highlightTimeout&&window.clearTimeout(this._highlightTimeout),this._cachedSearchTerm&&this._lastSearchOptions?.decorations&&(this._highlightTimeout=setTimeout(()=>{let t=this._cachedSearchTerm;this._cachedSearchTerm=void 0,this.findPrevious(t,{...this._lastSearchOptions,incremental:!0,noScroll:!0})},200))}clearDecorations(t){this._selectedDecoration.clear(),U(this._highlightDecorations),this._highlightDecorations=[],this._highlightedLines.clear(),t||(this._cachedSearchTerm=void 0)}clearActiveDecoration(){this._selectedDecoration.clear()}findNext(t,n){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let i=this._lastSearchOptions?this._didOptionsChange(this._lastSearchOptions,n):!0;this._lastSearchOptions=n,n?.decorations&&(this._cachedSearchTerm===void 0||t!==this._cachedSearchTerm||i)&&this._highlightAllMatches(t,n);let s=this._findNextAndSelect(t,n);return this._fireResults(n),this._cachedSearchTerm=t,s}_highlightAllMatches(t,n){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");if(!t||t.length===0){this.clearDecorations();return}n=n||{},this.clearDecorations(!0);let i=[],s,u=this._find(t,0,0,n);for(;u&&(s?.row!==u.row||s?.col!==u.col)&&!(i.length>=this._highlightLimit);)s=u,i.push(s),u=this._find(t,s.col+s.term.length>=this._terminal.cols?s.row+1:s.row,s.col+s.term.length>=this._terminal.cols?0:s.col+1,n);for(let l of i){let r=this._createResultDecoration(l,n.decorations);r&&(this._highlightedLines.add(r.marker.line),this._highlightDecorations.push({decoration:r,match:l,dispose(){r.dispose()}}))}}_find(t,n,i,s){if(!this._terminal||!t||t.length===0){this._terminal?.clearSelection(),this.clearDecorations();return}if(i>this._terminal.cols)throw new Error(`Invalid col: ${i} to search in terminal of ${this._terminal.cols} cols`);let u;this._initLinesCache();let l={startRow:n,startCol:i};if(u=this._findInLine(t,l,s),!u)for(let r=n+1;r<this._terminal.buffer.active.baseY+this._terminal.rows&&(l.startRow=r,l.startCol=0,u=this._findInLine(t,l,s),!u);r++);return u}_findNextAndSelect(t,n){if(!this._terminal||!t||t.length===0)return this._terminal?.clearSelection(),this.clearDecorations(),!1;let i=this._terminal.getSelectionPosition();this._terminal.clearSelection();let s=0,u=0;i&&(this._cachedSearchTerm===t?(s=i.end.x,u=i.end.y):(s=i.start.x,u=i.start.y)),this._initLinesCache();let l={startRow:u,startCol:s},r=this._findInLine(t,l,n);if(!r)for(let f=u+1;f<this._terminal.buffer.active.baseY+this._terminal.rows&&(l.startRow=f,l.startCol=0,r=this._findInLine(t,l,n),!r);f++);if(!r&&u!==0)for(let f=0;f<u&&(l.startRow=f,l.startCol=0,r=this._findInLine(t,l,n),!r);f++);return!r&&i&&(l.startRow=i.start.y,l.startCol=0,r=this._findInLine(t,l,n)),this._selectResult(r,n?.decorations,n?.noScroll)}findPrevious(t,n){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let i=this._lastSearchOptions?this._didOptionsChange(this._lastSearchOptions,n):!0;this._lastSearchOptions=n,n?.decorations&&(this._cachedSearchTerm===void 0||t!==this._cachedSearchTerm||i)&&this._highlightAllMatches(t,n);let s=this._findPreviousAndSelect(t,n);return this._fireResults(n),this._cachedSearchTerm=t,s}_didOptionsChange(t,n){return n?t.caseSensitive!==n.caseSensitive||t.regex!==n.regex||t.wholeWord!==n.wholeWord:!1}_fireResults(t){if(t?.decorations){let n=-1;if(this._selectedDecoration.value){let i=this._selectedDecoration.value.match;for(let s=0;s<this._highlightDecorations.length;s++){let u=this._highlightDecorations[s].match;if(u.row===i.row&&u.col===i.col&&u.size===i.size){n=s;break}}}this._onDidChangeResults.fire({resultIndex:n,resultCount:this._highlightDecorations.length})}}_findPreviousAndSelect(t,n){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");if(!this._terminal||!t||t.length===0)return this._terminal?.clearSelection(),this.clearDecorations(),!1;let i=this._terminal.getSelectionPosition();this._terminal.clearSelection();let s=this._terminal.buffer.active.baseY+this._terminal.rows-1,u=this._terminal.cols,l=!0;this._initLinesCache();let r={startRow:s,startCol:u},f;if(i&&(r.startRow=s=i.start.y,r.startCol=u=i.start.x,this._cachedSearchTerm!==t&&(f=this._findInLine(t,r,n,!1),f||(r.startRow=s=i.end.y,r.startCol=u=i.end.x))),f||(f=this._findInLine(t,r,n,l)),!f){r.startCol=Math.max(r.startCol,this._terminal.cols);for(let v=s-1;v>=0&&(r.startRow=v,f=this._findInLine(t,r,n,l),!f);v--);}if(!f&&s!==this._terminal.buffer.active.baseY+this._terminal.rows-1)for(let v=this._terminal.buffer.active.baseY+this._terminal.rows-1;v>=s&&(r.startRow=v,f=this._findInLine(t,r,n,l),!f);v--);return this._selectResult(f,n?.decorations,n?.noScroll)}_initLinesCache(){let t=this._terminal;this._linesCache||(this._linesCache=new Array(t.buffer.active.length),this._linesCacheDisposables.value=ae(t.onLineFeed(()=>this._destroyLinesCache()),t.onCursorMove(()=>this._destroyLinesCache()),t.onResize(()=>this._destroyLinesCache()))),window.clearTimeout(this._linesCacheTimeoutId),this._linesCacheTimeoutId=window.setTimeout(()=>this._destroyLinesCache(),Ze)}_destroyLinesCache(){this._linesCache=void 0,this._linesCacheDisposables.clear(),this._linesCacheTimeoutId&&(window.clearTimeout(this._linesCacheTimeoutId),this._linesCacheTimeoutId=0)}_isWholeWord(t,n,i){return(t===0||Fe.includes(n[t-1]))&&(t+i.length===n.length||Fe.includes(n[t+i.length]))}_findInLine(t,n,i={},s=!1){let u=this._terminal,l=n.startRow,r=n.startCol;if(u.buffer.active.getLine(l)?.isWrapped){if(s){n.startCol+=u.cols;return}return n.startRow--,n.startCol+=u.cols,this._findInLine(t,n,i)}let v=this._linesCache?.[l];v||(v=this._translateBufferLineToStringWithWrap(l,!0),this._linesCache&&(this._linesCache[l]=v));let[b,w]=v,k=this._bufferColsToStringOffset(l,r),A=i.caseSensitive?t:t.toLowerCase(),O=i.caseSensitive?b:b.toLowerCase(),I=-1;if(i.regex){let E=RegExp(A,"g"),y;if(s)for(;y=E.exec(O.slice(0,k));)I=E.lastIndex-y[0].length,t=y[0],E.lastIndex-=t.length-1;else y=E.exec(O.slice(k)),y&&y[0].length>0&&(I=k+(E.lastIndex-y[0].length),t=y[0])}else s?k-A.length>=0&&(I=O.lastIndexOf(A,k-A.length)):I=O.indexOf(A,k);if(I>=0){if(i.wholeWord&&!this._isWholeWord(I,O,t))return;let E=0;for(;E<w.length-1&&I>=w[E+1];)E++;let y=E;for(;y<w.length-1&&I+t.length>=w[y+1];)y++;let j=I-w[E],T=I+t.length-w[y],g=this._stringLengthToBufferSize(l+E,j),L=this._stringLengthToBufferSize(l+y,T)-g+u.cols*(y-E);return{term:t,col:g,row:l+E,size:L}}}_stringLengthToBufferSize(t,n){let i=this._terminal.buffer.active.getLine(t);if(!i)return 0;for(let s=0;s<n;s++){let u=i.getCell(s);if(!u)break;let l=u.getChars();l.length>1&&(n-=l.length-1);let r=i.getCell(s+1);r&&r.getWidth()===0&&n++}return n}_bufferColsToStringOffset(t,n){let i=this._terminal,s=t,u=0,l=i.buffer.active.getLine(s);for(;n>0&&l;){for(let r=0;r<n&&r<i.cols;r++){let f=l.getCell(r);if(!f)break;f.getWidth()&&(u+=f.getCode()===0?1:f.getChars().length)}if(s++,l=i.buffer.active.getLine(s),l&&!l.isWrapped)break;n-=i.cols}return u}_translateBufferLineToStringWithWrap(t,n){let i=this._terminal,s=[],u=[0],l=i.buffer.active.getLine(t);for(;l;){let r=i.buffer.active.getLine(t+1),f=r?r.isWrapped:!1,v=l.translateToString(!f&&n);if(f&&r){let b=l.getCell(l.length-1);b&&b.getCode()===0&&b.getWidth()===1&&r.getCell(0)?.getWidth()===2&&(v=v.slice(0,-1))}if(s.push(v),f)u.push(u[u.length-1]+v.length);else break;t++,l=r}return[s.join(""),u]}_selectResult(t,n,i){let s=this._terminal;if(this._selectedDecoration.clear(),!t)return s.clearSelection(),!1;if(s.select(t.col,t.row,t.size),n){let u=s.registerMarker(-s.buffer.active.baseY-s.buffer.active.cursorY+t.row);if(u){let l=s.registerDecoration({marker:u,x:t.col,width:t.size,backgroundColor:n.activeMatchBackground,layer:"top",overviewRulerOptions:{color:n.activeMatchColorOverviewRuler}});if(l){let r=[];r.push(u),r.push(l.onRender(f=>this._applyStyles(f,n.activeMatchBorder,!0))),r.push(l.onDispose(()=>U(r))),this._selectedDecoration.value={decoration:l,match:t,dispose(){l.dispose()}}}}}if(!i&&(t.row>=s.buffer.active.viewportY+s.rows||t.row<s.buffer.active.viewportY)){let u=t.row-s.buffer.active.viewportY;u-=Math.floor(s.rows/2),s.scrollLines(u)}return!0}_applyStyles(t,n,i){t.classList.contains("xterm-find-result-decoration")||(t.classList.add("xterm-find-result-decoration"),n&&(t.style.outline=`1px solid ${n}`)),i&&t.classList.add("xterm-find-active-result-decoration")}_createResultDecoration(t,n){let i=this._terminal,s=i.registerMarker(-i.buffer.active.baseY-i.buffer.active.cursorY+t.row);if(!s)return;let u=i.registerDecoration({marker:s,x:t.col,width:t.size,backgroundColor:n.matchBackground,overviewRulerOptions:this._highlightedLines.has(s.line)?void 0:{color:n.matchOverviewRuler,position:"center"}});if(u){let l=[];l.push(s),l.push(u.onRender(r=>this._applyStyles(r,n.matchBorder,!1))),l.push(u.onDispose(()=>U(l)))}return u}};export{Pe as SearchAddon};
//# sourceMappingURL=addon-search.mjs.map
