/**
 * 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 st=Object.create;var be=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var At=Object.getOwnPropertyNames;var ot=Object.getPrototypeOf,at=Object.prototype.hasOwnProperty;var N=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var lt=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of At(e))!at.call(r,s)&&s!==t&&be(r,s,{get:()=>e[s],enumerable:!(i=nt(e,s))||i.enumerable});return r};var Y=(r,e,t)=>(t=r!=null?st(ot(r)):{},lt(e||!r||!r.__esModule?be(t,"default",{value:r,enumerable:!0}):t,r));var W=N(u=>{"use strict";Object.defineProperty(u,"__esModule",{value:!0});u.DEFAULT_FOREGROUND=u.DEFAULT_BACKGROUND=u.PALETTE_ANSI_256=u.PALETTE_VT340_GREY=u.PALETTE_VT340_COLOR=u.normalizeHLS=u.normalizeRGB=u.nearestColorIndex=u.fromRGBA8888=u.toRGBA8888=u.alpha=u.blue=u.green=u.red=u.BIG_ENDIAN=void 0;u.BIG_ENDIAN=new Uint8Array(new Uint32Array([4278190080]).buffer)[0]===255;u.BIG_ENDIAN&&console.warn("BE platform detected. This version of node-sixel works only on LE properly.");function we(r){return r&255}u.red=we;function xe(r){return r>>>8&255}u.green=xe;function ye(r){return r>>>16&255}u.blue=ye;function ct(r){return r>>>24&255}u.alpha=ct;function m(r,e,t,i=255){return((i&255)<<24|(t&255)<<16|(e&255)<<8|r&255)>>>0}u.toRGBA8888=m;function dt(r){return[r&255,r>>8&255,r>>16&255,r>>>24]}u.fromRGBA8888=dt;function ht(r,e){let t=we(r),i=xe(r),s=ye(r),n=Number.MAX_SAFE_INTEGER,A=-1;for(let o=0;o<e.length;++o){let a=t-e[o][0],c=i-e[o][1],h=s-e[o][2],l=a*a+c*c+h*h;if(!l)return o;l<n&&(n=l,A=o)}return A}u.nearestColorIndex=ht;function de(r,e,t){return Math.max(r,Math.min(t,e))}function he(r,e,t){return t<0&&(t+=1),t>1&&(t-=1),t*6<1?e+(r-e)*6*t:t*2<1?r:t*3<2?e+(r-e)*(4-t*6):e}function gt(r,e,t){if(!t){let n=Math.round(e*255);return m(n,n,n)}let i=e<.5?e*(1+t):e+t-e*t,s=2*e-i;return m(de(0,255,Math.round(he(i,s,r+1/3)*255)),de(0,255,Math.round(he(i,s,r)*255)),de(0,255,Math.round(he(i,s,r-1/3)*255)))}function g(r,e,t){return(4278190080|Math.round(t/100*255)<<16|Math.round(e/100*255)<<8|Math.round(r/100*255))>>>0}u.normalizeRGB=g;function ut(r,e,t){return gt((r+240%360)/360,e/100,t/100)}u.normalizeHLS=ut;u.PALETTE_VT340_COLOR=new Uint32Array([g(0,0,0),g(20,20,80),g(80,13,13),g(20,80,20),g(80,20,80),g(20,80,80),g(80,80,20),g(53,53,53),g(26,26,26),g(33,33,60),g(60,26,26),g(33,60,33),g(60,33,60),g(33,60,60),g(60,60,33),g(80,80,80)]);u.PALETTE_VT340_GREY=new Uint32Array([g(0,0,0),g(13,13,13),g(26,26,26),g(40,40,40),g(6,6,6),g(20,20,20),g(33,33,33),g(46,46,46),g(0,0,0),g(13,13,13),g(26,26,26),g(40,40,40),g(6,6,6),g(20,20,20),g(33,33,33),g(46,46,46)]);u.PALETTE_ANSI_256=(()=>{let r=[m(0,0,0),m(205,0,0),m(0,205,0),m(205,205,0),m(0,0,238),m(205,0,205),m(0,250,205),m(229,229,229),m(127,127,127),m(255,0,0),m(0,255,0),m(255,255,0),m(92,92,255),m(255,0,255),m(0,255,255),m(255,255,255)],e=[0,95,135,175,215,255];for(let t=0;t<6;++t)for(let i=0;i<6;++i)for(let s=0;s<6;++s)r.push(m(e[t],e[i],e[s]));for(let t=8;t<=238;t+=10)r.push(m(t,t,t));return new Uint32Array(r)})();u.DEFAULT_BACKGROUND=m(0,0,0,255);u.DEFAULT_FOREGROUND=m(255,255,255,255)});var Ke=N(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.InWasm=void 0;function R(r){if(typeof Buffer<"u")return Buffer.from(r,"base64");let e=atob(r),t=new Uint8Array(e.length);for(let i=0;i<t.length;++i)t[i]=e.charCodeAt(i);return t}function Tt(r){if(r.d){let{t:e,s:t,d:i}=r,s,n,A=WebAssembly;return e===2?t?()=>s||(s=R(i)):()=>Promise.resolve(s||(s=R(i))):e===1?t?()=>n||(n=new A.Module(s||(s=R(i)))):()=>n?Promise.resolve(n):A.compile(s||(s=R(i))).then(o=>n=o):t?o=>new A.Instance(n||(n=new A.Module(s||(s=R(i)))),o):o=>n?A.instantiate(n,o):A.instantiate(s||(s=R(i)),o).then(a=>(n=a.module)&&a.instance)}if(typeof _wasmCtx>"u")throw new Error('must run "inwasm"');_wasmCtx.add(r)}re.InWasm=Tt});var Oe=N(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});var bt=Ke(),wt=(0,bt.InWasm)({s:1,t:0,d:"AGFzbQEAAAABBQFgAAF/Ag8BA2VudgZtZW1vcnkCAAEDAwIAAAcNAgNkZWMAAANlbmQAAQqxAwKuAQEFf0GIKCgCAEGgKGohAUGEKCgCACIAQYAoKAIAQQFrQXxxIgJIBEAgAkGgKGohAyAAQaAoaiEAA0AgAC0AA0ECdCgCgCAgAC0AAkECdCgCgBggAC0AAUECdCgCgBAgAC0AAEECdCgCgAhycnIiBEH///8HSwRAQQEPCyABIAQ2AgAgAUEDaiEBIABBBGoiACADSQ0ACwtBhCggAjYCAEGIKCABQaAoazYCAEEAC/4BAQZ/AkBBgCgoAgAiAUGEKCgCACIAa0EFTgRAQQEhAxAADQFBgCgoAgAhAUGEKCgCACEAC0EBIQMgASAAayIEQQJIDQAgAEGhKGotAABBAnQoAoAQIABBoChqLQAAQQJ0KAKACHIhAQJAIARBAkYEQEEBIQIMAQtBASECIAAtAKIoIgVBPUcEQEECIQIgBUECdCgCgBggAXIhAQsgBEEERw0AIAAtAKMoIgBBPUYNACACQQFqIQIgAEECdCgCgCAgAXIhAQsgAUH///8HSw0AQYgoKAIAQaAoaiABNgIAQYgoQYgoKAIAIAJqIgA2AgAgAEGQKCgCAEchAwsgAwsAdglwcm9kdWNlcnMBDHByb2Nlc3NlZC1ieQEFY2xhbmdWMTguMC4wIChodHRwczovL2dpdGh1Yi5jb20vbGx2bS9sbHZtLXByb2plY3QgZDFlNjg1ZGY0NWRjNTk0NGI0M2QyNTQ3ZDAxMzhjZDRhM2VlNGVmZSkALA90YXJnZXRfZmVhdHVyZXMCKw9tdXRhYmxlLWdsb2JhbHMrCHNpZ24tZXh0"}),x=new Uint8Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").map(r=>r.charCodeAt(0))),L=new Uint32Array(1024);L.fill(4278190080);for(let r=0;r<x.length;++r)L[x[r]]=r<<2;for(let r=0;r<x.length;++r)L[256+x[r]]=r>>4|(r<<4&255)<<8;for(let r=0;r<x.length;++r)L[512+x[r]]=r>>2<<8|(r<<6&255)<<16;for(let r=0;r<x.length;++r)L[768+x[r]]=r<<16;var xt=new Uint8Array(0),me=class{constructor(e){this.keepSize=e}get data8(){return this._inst?this._d.subarray(0,this._m32[1282]):xt}release(){this._inst&&(this._mem.buffer.byteLength>this.keepSize?this._inst=this._m32=this._d=this._mem=null:(this._m32[1280]=0,this._m32[1281]=0,this._m32[1282]=0))}init(e){let t=this._m32,i=(Math.ceil(e/3)+1288)*4;this._inst?this._mem.buffer.byteLength<i&&(this._mem.grow(Math.ceil((i-this._mem.buffer.byteLength)/65536)),t=new Uint32Array(this._mem.buffer,0),this._d=new Uint8Array(this._mem.buffer,1288*4)):(this._mem=new WebAssembly.Memory({initial:Math.ceil(i/65536)}),this._inst=wt({env:{memory:this._mem}}),t=new Uint32Array(this._mem.buffer,0),t.set(L,256),this._d=new Uint8Array(this._mem.buffer,1288*4)),t[1284]=e,t[1283]=Math.ceil(e/3)*4,t[1280]=0,t[1281]=0,t[1282]=0,this._m32=t}put(e,t,i){if(!this._inst)return 1;let s=this._m32;return i-t+s[1280]>s[1283]?1:(this._d.set(e.subarray(t,i),s[1280]),s[1280]+=i-t,s[1280]-s[1281]>=131072?this._inst.exports.dec():0)}end(){return this._inst?this._inst.exports.end():1}};Ce.default=me});var je=N(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.LIMITS=void 0;oe.LIMITS={CHUNK_SIZE:16384,PALETTE_SIZE:4096,MAX_WIDTH:16384,BYTES:" "}});var Xe=N(b=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});b.decodeAsync=b.decode=b.Decoder=b.DecoderAsync=void 0;var U=W(),Q=je();function kt(r){if(typeof Buffer<"u")return Buffer.from(r,"base64");let e=atob(r),t=new Uint8Array(e.length);for(let i=0;i<t.length;++i)t[i]=e.charCodeAt(i);return t}var Ve=kt(Q.LIMITS.BYTES),K,ae=new Uint32Array,_e=class{constructor(){this.bandHandler=e=>1,this.modeHandler=e=>1}handle_band(e){return this.bandHandler(e)}mode_parsed(e){return this.modeHandler(e)}},Mt={memoryLimit:2048*65536,sixelColor:U.DEFAULT_FOREGROUND,fillColor:U.DEFAULT_BACKGROUND,palette:U.PALETTE_VT340_COLOR,paletteLimit:Q.LIMITS.PALETTE_SIZE,truncate:!0};function Ze(r){let e=new _e,t={env:{handle_band:e.handle_band.bind(e),mode_parsed:e.mode_parsed.bind(e)}};return WebAssembly.instantiate(K||Ve,t).then(i=>(K=K||i.module,new O(r,i.instance||i,e)))}b.DecoderAsync=Ze;var O=class{constructor(e,t,i){if(this._PIXEL_OFFSET=Q.LIMITS.MAX_WIDTH+4,this._canvas=ae,this._bandWidths=[],this._maxWidth=0,this._minWidth=Q.LIMITS.MAX_WIDTH,this._lastOffset=0,this._currentHeight=0,this._opts=Object.assign({},Mt,e),this._opts.paletteLimit>Q.LIMITS.PALETTE_SIZE)throw new Error(`DecoderOptions.paletteLimit must not exceed ${Q.LIMITS.PALETTE_SIZE}`);if(t)i.bandHandler=this._handle_band.bind(this),i.modeHandler=this._initCanvas.bind(this);else{let s=K||(K=new WebAssembly.Module(Ve));t=new WebAssembly.Instance(s,{env:{handle_band:this._handle_band.bind(this),mode_parsed:this._initCanvas.bind(this)}})}this._instance=t,this._wasm=this._instance.exports,this._chunk=new Uint8Array(this._wasm.memory.buffer,this._wasm.get_chunk_address(),Q.LIMITS.CHUNK_SIZE),this._states=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_state_address(),12),this._palette=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_palette_address(),Q.LIMITS.PALETTE_SIZE),this._palette.set(this._opts.palette),this._pSrc=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_p0_address()),this._wasm.init(U.DEFAULT_FOREGROUND,0,this._opts.paletteLimit,0)}get _fillColor(){return this._states[0]}get _truncate(){return this._states[8]}get _rasterWidth(){return this._states[6]}get _rasterHeight(){return this._states[7]}get _width(){return this._states[2]?this._states[2]-4:0}get _height(){return this._states[3]}get _level(){return this._states[9]}get _mode(){return this._states[10]}get _paletteLimit(){return this._states[11]}_initCanvas(e){if(e===2){let t=this.width*this.height;if(t>this._canvas.length){if(this._opts.memoryLimit&&t*4>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");this._canvas=new Uint32Array(t)}this._maxWidth=this._width}else if(e===1)if(this._level===2){let t=Math.min(this._rasterWidth,Q.LIMITS.MAX_WIDTH)*this._rasterHeight;if(t>this._canvas.length){if(this._opts.memoryLimit&&t*4>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");this._canvas=new Uint32Array(t)}}else this._canvas.length<65536&&(this._canvas=new Uint32Array(65536));return 0}_realloc(e,t){let i=e+t;if(i>this._canvas.length){if(this._opts.memoryLimit&&i*4>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");let s=new Uint32Array(Math.ceil(i/65536)*65536);s.set(this._canvas),this._canvas=s}}_handle_band(e){let t=this._PIXEL_OFFSET,i=this._lastOffset;if(this._mode===2){let s=this.height-this._currentHeight,n=0;for(;n<6&&s>0;)this._canvas.set(this._pSrc.subarray(t*n,t*n+e),i+e*n),n++,s--;this._lastOffset+=e*n,this._currentHeight+=n}else if(this._mode===1){this._realloc(i,e*6),this._maxWidth=Math.max(this._maxWidth,e),this._minWidth=Math.min(this._minWidth,e);for(let s=0;s<6;++s)this._canvas.set(this._pSrc.subarray(t*s,t*s+e),i+e*s);this._bandWidths.push(e),this._lastOffset+=e*6,this._currentHeight+=6}return 0}get width(){return this._mode!==1?this._width:Math.max(this._maxWidth,this._wasm.current_width())}get height(){return this._mode!==1?this._height:this._wasm.current_width()?this._bandWidths.length*6+this._wasm.current_height():this._bandWidths.length*6}get palette(){return this._palette.subarray(0,this._paletteLimit)}get memoryUsage(){return this._canvas.byteLength+this._wasm.memory.buffer.byteLength+8*this._bandWidths.length}get properties(){return{width:this.width,height:this.height,mode:this._mode,level:this._level,truncate:!!this._truncate,paletteLimit:this._paletteLimit,fillColor:this._fillColor,memUsage:this.memoryUsage,rasterAttributes:{numerator:this._states[4],denominator:this._states[5],width:this._rasterWidth,height:this._rasterHeight}}}init(e=this._opts.fillColor,t=this._opts.palette,i=this._opts.paletteLimit,s=this._opts.truncate){this._wasm.init(this._opts.sixelColor,e,i,s?1:0),t&&this._palette.set(t.subarray(0,Q.LIMITS.PALETTE_SIZE)),this._bandWidths.length=0,this._maxWidth=0,this._minWidth=Q.LIMITS.MAX_WIDTH,this._lastOffset=0,this._currentHeight=0}decode(e,t=0,i=e.length){let s=t;for(;s<i;){let n=Math.min(i-s,Q.LIMITS.CHUNK_SIZE);this._chunk.set(e.subarray(s,s+=n)),this._wasm.decode(0,n)}}decodeString(e,t=0,i=e.length){let s=t;for(;s<i;){let n=Math.min(i-s,Q.LIMITS.CHUNK_SIZE);for(let A=0,o=s;A<n;++A,++o)this._chunk[A]=e.charCodeAt(o);s+=n,this._wasm.decode(0,n)}}get data32(){if(this._mode===0||!this.width||!this.height)return ae;let e=this._wasm.current_width();if(this._mode===2){let t=this.height-this._currentHeight;if(t>0){let i=this._PIXEL_OFFSET,s=this._lastOffset,n=0;for(;n<6&&t>0;)this._canvas.set(this._pSrc.subarray(i*n,i*n+e),s+e*n),n++,t--;t&&this._canvas.fill(this._fillColor,s+e*n)}return this._canvas.subarray(0,this.width*this.height)}if(this._mode===1){if(this._minWidth===this._maxWidth){let n=!1;if(e)if(e!==this._minWidth)n=!0;else{let A=this._PIXEL_OFFSET,o=this._lastOffset;this._realloc(o,e*6);for(let a=0;a<6;++a)this._canvas.set(this._pSrc.subarray(A*a,A*a+e),o+e*a)}if(!n)return this._canvas.subarray(0,this.width*this.height)}let t=new Uint32Array(this.width*this.height);t.fill(this._fillColor);let i=0,s=0;for(let n=0;n<this._bandWidths.length;++n){let A=this._bandWidths[n];for(let o=0;o<6;++o)t.set(this._canvas.subarray(s,s+=A),i),i+=this.width}if(e){let n=this._PIXEL_OFFSET,A=this._wasm.current_height();for(let o=0;o<A;++o)t.set(this._pSrc.subarray(n*o,n*o+e),i+this.width*o)}return t}return ae}get data8(){return new Uint8ClampedArray(this.data32.buffer,0,this.width*this.height*4)}release(){this._canvas=ae,this._bandWidths.length=0,this._maxWidth=0,this._minWidth=Q.LIMITS.MAX_WIDTH,this._wasm.init(U.DEFAULT_FOREGROUND,0,this._opts.paletteLimit,0)}};b.Decoder=O;function Rt(r,e){let t=new O(e);return t.init(),typeof r=="string"?t.decodeString(r):t.decode(r),{width:t.width,height:t.height,data32:t.data32,data8:t.data8}}b.decode=Rt;async function Lt(r,e){let t=await Ze(e);return t.init(),typeof r=="string"?t.decodeString(r):t.decode(r),{width:t.width,height:t.height,data32:t.data32,data8:t.data8}}b.decodeAsync=Lt});var fe=Y(W());var ge=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)}},Jt=new ge;var z=class r extends Error{constructor(e){super(e),this.name="CodeExpectedError"}static fromError(e){if(e instanceof r)return e;let t=new r;return t.message=e.message,t.stack=e.stack,t}static isErrorNoTelemetry(e){return e.name==="CodeExpectedError"}};function It(r,e,t=0,i=r.length){let s=t,n=i;for(;s<n;){let A=Math.floor((s+n)/2);e(r[A])?s=A+1:n=A}return s-1}var q=class q{constructor(e){this._array=e;this._findLastMonotonousLastIdx=0}findLastMonotonous(e){if(q.assertInvariants){if(this._prevFindLastPredicate){for(let i of this._array)if(this._prevFindLastPredicate(i)&&!e(i))throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.")}this._prevFindLastPredicate=e}let t=It(this._array,e,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=t+1,t===-1?void 0:this._array[t]}};q.assertInvariants=!1;var ve=q;var ke;(o=>{function r(a){return a<0}o.isLessThan=r;function e(a){return a<=0}o.isLessThanOrEqual=e;function t(a){return a>0}o.isGreaterThan=t;function i(a){return a===0}o.isNeitherLessOrGreaterThan=i,o.greaterThan=1,o.lessThan=-1,o.neitherLessOrGreaterThan=0})(ke||={});function Me(r,e){return(t,i)=>e(r(t),r(i))}var Re=(r,e)=>r-e;var M=class M{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 M(t=>this.iterate(i=>e(i)?t(i):!0))}map(e){return new M(t=>this.iterate(i=>t(e(i))))}some(e){let t=!1;return this.iterate(i=>(t=e(i),!t)),t}findFirst(e){let t;return this.iterate(i=>e(i)?(t=i,!1):!0),t}findLast(e){let t;return this.iterate(i=>(e(i)&&(t=i),!0)),t}findLastMaxBy(e){let t,i=!0;return this.iterate(s=>((i||ke.isGreaterThan(e(s,t)))&&(i=!1,t=s),!0)),t}};M.empty=new M(e=>{});var Se=M;function Fe(r,e){let t=Object.create(null);for(let i of r){let s=e(i),n=t[s];n||(n=t[s]=[]),n.push(i)}return t}var Ne,He,Le=class{constructor(e,t){this.toKey=t;this._map=new Map;this[Ne]="SetWithKey";for(let i of e)this.add(i)}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(i=>e.call(t,i,i,this))}[(He=Symbol.iterator,Ne=Symbol.toStringTag,He)](){return this.values()}};var j=class{constructor(){this.map=new Map}add(e,t){let i=this.map.get(e);i||(i=new Set,this.map.set(e,i)),i.add(t)}delete(e,t){let i=this.map.get(e);i&&(i.delete(t),i.size===0&&this.map.delete(e))}forEach(e,t){let i=this.map.get(e);i&&i.forEach(t)}get(e){let t=this.map.get(e);return t||new Set}};function Ge(r,e){let t=this,i=!1,s;return function(){if(i)return s;if(i=!0,e)try{s=r.apply(t,arguments)}finally{e()}else s=r.apply(t,arguments);return s}}var ue;(rt=>{function r(d){return d&&typeof d=="object"&&typeof d[Symbol.iterator]=="function"}rt.is=r;let e=Object.freeze([]);function t(){return e}rt.empty=t;function*i(d){yield d}rt.single=i;function s(d){return r(d)?d:i(d)}rt.wrap=s;function n(d){return d||e}rt.from=n;function*A(d){for(let p=d.length-1;p>=0;p--)yield d[p]}rt.reverse=A;function o(d){return!d||d[Symbol.iterator]().next().done===!0}rt.isEmpty=o;function a(d){return d[Symbol.iterator]().next().value}rt.first=a;function c(d,p){let f=0;for(let D of d)if(p(D,f++))return!0;return!1}rt.some=c;function h(d,p){for(let f of d)if(p(f))return f}rt.find=h;function*l(d,p){for(let f of d)p(f)&&(yield f)}rt.filter=l;function*I(d,p){let f=0;for(let D of d)yield p(D,f++)}rt.map=I;function*E(d,p){let f=0;for(let D of d)yield*p(D,f++)}rt.flatMap=E;function*C(...d){for(let p of d)yield*p}rt.concat=C;function _(d,p,f){let D=f;for(let P of d)D=p(D,P);return D}rt.reduce=_;function*B(d,p,f=d.length){for(p<0&&(p+=d.length),f<0?f+=d.length:f>d.length&&(f=d.length);p<f;p++)yield d[p]}rt.slice=B;function y(d,p=Number.POSITIVE_INFINITY){let f=[];if(p===0)return[f,d];let D=d[Symbol.iterator]();for(let P=0;P<p;P++){let Te=D.next();if(Te.done)return[f,rt.empty()];f.push(Te.value)}return[f,{[Symbol.iterator](){return D}}]}rt.consume=y;async function k(d){let p=[];for await(let f of d)p.push(f);return Promise.resolve(p)}rt.asyncToArray=k})(ue||={});var pt=!1,$=null,Z=class Z{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:Z.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 i=this.getDisposableData(e);i.parent=t}markAsDisposed(e){this.livingDisposables.delete(e)}markAsSingleton(e){this.getDisposableData(e).isSingleton=!0}getRootParent(e,t){let i=t.get(e);if(i)return i;let s=e.parent?this.getRootParent(this.getDisposableData(e.parent),t):e;return t.set(e,s),s}getTrackedDisposables(){let e=new Map;return[...this.livingDisposables.entries()].filter(([,i])=>i.source!==null&&!this.getRootParent(i,e).isSingleton).flatMap(([i])=>i)}computeLeakingDisposables(e=10,t){let i;if(t)i=t;else{let a=new Map,c=[...this.livingDisposables.values()].filter(l=>l.source!==null&&!this.getRootParent(l,a).isSingleton);if(c.length===0)return;let h=new Set(c.map(l=>l.value));if(i=c.filter(l=>!(l.parent&&h.has(l.parent))),i.length===0)throw new Error("There are cyclic diposable chains!")}if(!i)return;function s(a){function c(l,I){for(;l.length>0&&I.some(E=>typeof E=="string"?E===l[0]:l[0].match(E));)l.shift()}let h=a.source.split(`
`).map(l=>l.trim().replace("at ","")).filter(l=>l!=="");return c(h,["Error",/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),h.reverse()}let n=new j;for(let a of i){let c=s(a);for(let h=0;h<=c.length;h++)n.add(c.slice(0,h).join(`
`),a)}i.sort(Me(a=>a.idx,Re));let A="",o=0;for(let a of i.slice(0,e)){o++;let c=s(a),h=[];for(let l=0;l<c.length;l++){let I=c[l];I=`(shared with ${n.get(c.slice(0,l+1).join(`
`)).size}/${i.length} leaks) at ${I}`;let C=n.get(c.slice(0,l).join(`
`)),_=Fe([...C].map(B=>s(B)[l]),B=>B);delete _[c[l]];for(let[B,y]of Object.entries(_))h.unshift(`    - stacktraces of ${y.length} other leaks continue with ${B}`);h.unshift(I)}A+=`


==================== Leaking disposable ${o}/${i.length}: ${a.value.constructor.name} ====================
${h.join(`
`)}
============================================================

`}return i.length>e&&(A+=`


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

`),{leaks:i,details:A}}};Z.idx=0;var Je=Z;function ft(r){$=r}if(pt){let r="__is_disposable_tracked__";ft(new class{trackDisposable(e){let t=new Error("Potentially leaked disposable").stack;setTimeout(()=>{e[r]||console.log(t)},3e3)}setParent(e,t){if(e&&e!==v.None)try{e[r]=!0}catch{}}markAsDisposed(e){if(e&&e!==v.None)try{e[r]=!0}catch{}}markAsSingleton(e){}})}function ee(r){return $?.trackDisposable(r),r}function te(r){$?.markAsDisposed(r)}function H(r,e){$?.setParent(r,e)}function mt(r){if(ue.is(r)){let e=[];for(let t of r)if(t)try{t.dispose()}catch(i){e.push(i)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"Encountered errors while disposing of store");return Array.isArray(r)?[]:r}else if(r)return r.dispose(),r}function Ue(r){let e=ee({dispose:Ge(()=>{te(e),r()})});return e}var X=class X{constructor(){this._toDispose=new Set;this._isDisposed=!1;ee(this)}dispose(){this._isDisposed||(te(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{mt(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 H(e,this),this._isDisposed?X.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),H(e,null))}};X.DISABLE_DISPOSED_WARNING=!1;var Ie=X,v=class{constructor(){this._store=new Ie;ee(this),H(this._store,this)}dispose(){te(this),this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};v.None=Object.freeze({dispose(){}});var V=class{constructor(){this._isDisposed=!1;ee(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&H(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,te(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&H(e,null),e}};var Ct=4096,pe=24,T=class r extends v{constructor(t){super();this._terminal=t;this._optionsRefresh=this._register(new V);this._oldOpen=this._terminal._core.open,this._terminal._core.open=i=>{this._oldOpen?.call(this._terminal._core,i),this._open()},this._terminal._core.screenElement&&this._open(),this._optionsRefresh.value=this._terminal._core.optionsService.onOptionChange(i=>{i==="fontSize"&&(this.rescaleCanvas(),this._renderService?.refreshRows(0,this._terminal.rows))}),this._register(Ue(()=>{this.removeLayerFromDom(),this._terminal._core&&this._oldOpen&&(this._terminal._core.open=this._oldOpen,this._oldOpen=void 0),this._renderService&&this._oldSetRenderer&&(this._renderService.setRenderer=this._oldSetRenderer,this._oldSetRenderer=void 0),this._renderService=void 0,this.canvas=void 0,this._ctx=void 0,this._placeholderBitmap?.close(),this._placeholderBitmap=void 0,this._placeholder=void 0}))}static createCanvas(t,i,s){let n=(t||document).createElement("canvas");return n.width=i|0,n.height=s|0,n}static createImageData(t,i,s,n){if(typeof ImageData!="function"){let A=t.createImageData(i,s);return n&&A.data.set(new Uint8ClampedArray(n,0,i*s*4)),A}return n?new ImageData(new Uint8ClampedArray(n,0,i*s*4),i,s):new ImageData(i,s)}static createImageBitmap(t){return typeof createImageBitmap!="function"?Promise.resolve(void 0):createImageBitmap(t)}showPlaceholder(t){t?!this._placeholder&&this.cellSize.height!==-1&&this._createPlaceHolder(Math.max(this.cellSize.height+1,pe)):(this._placeholderBitmap?.close(),this._placeholderBitmap=void 0,this._placeholder=void 0),this._renderService?.refreshRows(0,this._terminal.rows)}get dimensions(){return this._renderService?.dimensions}get cellSize(){return{width:this.dimensions?.css.cell.width||-1,height:this.dimensions?.css.cell.height||-1}}clearLines(t,i){this._ctx?.clearRect(0,t*(this.dimensions?.css.cell.height||0),this.dimensions?.css.canvas.width||0,(++i-t)*(this.dimensions?.css.cell.height||0))}clearAll(){this._ctx?.clearRect(0,0,this.canvas?.width||0,this.canvas?.height||0)}draw(t,i,s,n,A=1){if(!this._ctx)return;let{width:o,height:a}=this.cellSize;if(o===-1||a===-1)return;this._rescaleImage(t,o,a);let c=t.actual,h=Math.ceil(c.width/o),l=i%h*o,I=Math.floor(i/h)*a,E=s*o,C=n*a,_=A*o+l>c.width?c.width-l:A*o,B=I+a>c.height?c.height-I:a;this._ctx.drawImage(c,Math.floor(l),Math.floor(I),Math.ceil(_),Math.ceil(B),Math.floor(E),Math.floor(C),Math.ceil(_),Math.ceil(B))}extractTile(t,i){let{width:s,height:n}=this.cellSize;if(s===-1||n===-1)return;this._rescaleImage(t,s,n);let A=t.actual,o=Math.ceil(A.width/s),a=i%o*s,c=Math.floor(i/o)*n,h=s+a>A.width?A.width-a:s,l=c+n>A.height?A.height-c:n,I=r.createCanvas(this.document,h,l),E=I.getContext("2d");if(E)return E.drawImage(A,Math.floor(a),Math.floor(c),Math.floor(h),Math.floor(l),0,0,Math.floor(h),Math.floor(l)),I}drawPlaceholder(t,i,s=1){if(this._ctx){let{width:n,height:A}=this.cellSize;if(n===-1||A===-1||(this._placeholder?A>=this._placeholder.height&&this._createPlaceHolder(A+1):this._createPlaceHolder(Math.max(A+1,pe)),!this._placeholder))return;this._ctx.drawImage(this._placeholderBitmap||this._placeholder,t*n,i*A%2?0:1,n*s,A,t*n,i*A,n*s,A)}}rescaleCanvas(){this.canvas&&(this.canvas.width!==this.dimensions.css.canvas.width||this.canvas.height!==this.dimensions.css.canvas.height)&&(this.canvas.width=this.dimensions.css.canvas.width||0,this.canvas.height=this.dimensions.css.canvas.height||0)}_rescaleImage(t,i,s){if(i===t.actualCellSize.width&&s===t.actualCellSize.height)return;let{width:n,height:A}=t.origCellSize;if(i===n&&s===A){t.actual=t.orig,t.actualCellSize.width=n,t.actualCellSize.height=A;return}let o=r.createCanvas(this.document,Math.ceil(t.orig.width*i/n),Math.ceil(t.orig.height*s/A)),a=o.getContext("2d");a&&(a.drawImage(t.orig,0,0,o.width,o.height),t.actual=o,t.actualCellSize.width=i,t.actualCellSize.height=s)}_open(){this._renderService=this._terminal._core._renderService,this._oldSetRenderer=this._renderService.setRenderer.bind(this._renderService),this._renderService.setRenderer=t=>{this.removeLayerFromDom(),this._oldSetRenderer?.call(this._renderService,t)}}insertLayerToDom(){this.document&&this._terminal._core.screenElement?this.canvas||(this.canvas=r.createCanvas(this.document,this.dimensions?.css.canvas.width||0,this.dimensions?.css.canvas.height||0),this.canvas.classList.add("xterm-image-layer"),this._terminal._core.screenElement.appendChild(this.canvas),this._ctx=this.canvas.getContext("2d",{alpha:!0,desynchronized:!0}),this.clearAll()):console.warn("image addon: cannot insert output canvas to DOM, missing document or screenElement")}removeLayerFromDom(){this.canvas&&(this._ctx=void 0,this.canvas.remove(),this.canvas=void 0)}_createPlaceHolder(t=pe){this._placeholderBitmap?.close(),this._placeholderBitmap=void 0;let i=32,s=r.createCanvas(this.document,i,t),n=s.getContext("2d",{alpha:!1});if(!n)return;let A=r.createImageData(n,i,t),o=new Uint32Array(A.data.buffer),a=(0,fe.toRGBA8888)(0,0,0),c=(0,fe.toRGBA8888)(255,255,255);o.fill(a);for(let I=0;I<t;++I){let E=I%2,C=I*i;for(let _=0;_<i;_+=2)o[C+_+E]=c}n.putImageData(A,0,0);let h=screen.width+i-1&~(i-1)||Ct;this._placeholder=r.createCanvas(this.document,h,t);let l=this._placeholder.getContext("2d",{alpha:!1});if(!l){this._placeholder=void 0;return}for(let I=0;I<h;I+=i)l.drawImage(s,I,0);r.createImageBitmap(this._placeholder).then(I=>this._placeholderBitmap=I)}get document(){return this._terminal._core._coreBrowserService?.window.document}};var S={width:7,height:14},G=class r{constructor(e=0,t=0,i=-1,s=-1){this.imageId=i;this.tileId=s;this._ext=0;this._urlId=0;this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}get urlId(){return this._urlId}set urlId(e){this._urlId=e}clone(){return new r(this._ext,this._urlId,this.imageId,this.tileId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0&&this.imageId===-1}},F=new G,ie=class{constructor(e,t,i){this._terminal=e;this._renderer=t;this._opts=i;this._images=new Map;this._lastId=0;this._lowestId=0;this._fullyCleared=!1;this._needsFullClear=!1;this._pixelLimit=25e5;try{this.setLimit(this._opts.storageLimit)}catch(s){console.error(s.message),console.warn(`storageLimit is set to ${this.getLimit()} MB`)}this._viewportMetrics={cols:this._terminal.cols,rows:this._terminal.rows}}dispose(){this.reset()}reset(){for(let e of this._images.values())e.marker?.dispose();this._images.clear(),this._renderer.clearAll()}getLimit(){return this._pixelLimit*4/1e6}setLimit(e){if(e<.5||e>1e3)throw RangeError("invalid storageLimit, should be at least 0.5 MB and not exceed 1G");this._pixelLimit=e/4*1e6>>>0,this._evictOldest(0)}getUsage(){return this._getStoredPixels()*4/1e6}_getStoredPixels(){let e=0;for(let t of this._images.values())t.orig&&(e+=t.orig.width*t.orig.height,t.actual&&t.actual!==t.orig&&(e+=t.actual.width*t.actual.height));return e}_delImg(e){let t=this._images.get(e);this._images.delete(e),t&&window.ImageBitmap&&t.orig instanceof ImageBitmap&&t.orig.close()}wipeAlternate(){let e=[];for(let[t,i]of this._images.entries())i.bufferType==="alternate"&&(i.marker?.dispose(),e.push(t));for(let t of e)this._delImg(t);this._needsFullClear=!0,this._fullyCleared=!1}advanceCursor(e){if(this._opts.sixelScrolling){let t=this._renderer.cellSize;(t.width===-1||t.height===-1)&&(t=S);let i=Math.ceil(e/t.height);for(let s=1;s<i;++s)this._terminal._core._inputHandler.lineFeed()}}addImage(e){this._evictOldest(e.width*e.height);let t=this._renderer.cellSize;(t.width===-1||t.height===-1)&&(t=S);let i=Math.ceil(e.width/t.width),s=Math.ceil(e.height/t.height),n=++this._lastId,A=this._terminal._core.buffer,o=this._terminal.cols,a=this._terminal.rows,c=A.x,h=A.y,l=c,I=0;this._opts.sixelScrolling||(A.x=0,A.y=0,l=0),this._terminal._core._inputHandler._dirtyRowTracker.markDirty(A.y);for(let B=0;B<s;++B){let y=A.lines.get(A.y+A.ybase);for(let k=0;k<i&&!(l+k>=o);++k)this._writeToCell(y,l+k,n,B*i+k),I++;if(this._opts.sixelScrolling)B<s-1&&this._terminal._core._inputHandler.lineFeed();else if(++A.y>=a)break;A.x=l}this._terminal._core._inputHandler._dirtyRowTracker.markDirty(A.y),this._opts.sixelScrolling?A.x=l:(A.x=c,A.y=h);let E=[];for(let[B,y]of this._images.entries())y.tileCount<1&&(y.marker?.dispose(),E.push(B));for(let B of E)this._delImg(B);let C=this._terminal.registerMarker(0);C?.onDispose(()=>{this._images.get(n)&&this._delImg(n)}),this._terminal.buffer.active.type==="alternate"&&this._evictOnAlternate();let _={orig:e,origCellSize:t,actual:e,actualCellSize:{...t},marker:C||void 0,tileCount:I,bufferType:this._terminal.buffer.active.type};this._images.set(n,_)}render(e){if(!this._renderer.canvas&&this._images.size&&(this._renderer.insertLayerToDom(),!this._renderer.canvas))return;if(this._renderer.rescaleCanvas(),!this._images.size){this._fullyCleared||(this._renderer.clearAll(),this._fullyCleared=!0,this._needsFullClear=!1),this._renderer.canvas&&this._renderer.removeLayerFromDom();return}this._needsFullClear&&(this._renderer.clearAll(),this._fullyCleared=!0,this._needsFullClear=!1);let{start:t,end:i}=e,s=this._terminal._core.buffer,n=this._terminal._core.cols;this._renderer.clearLines(t,i);for(let A=t;A<=i;++A){let o=s.lines.get(A+s.ydisp);if(!o)return;for(let a=0;a<n;++a)if(o.getBg(a)&268435456){let c=o._extendedAttrs[a]||F,h=c.imageId;if(h===void 0||h===-1)continue;let l=this._images.get(h);if(c.tileId!==-1){let I=c.tileId,E=a,C=1;for(;++a<n&&o.getBg(a)&268435456&&(c=o._extendedAttrs[a]||F)&&c.imageId===h&&c.tileId===I+C;)C++;a--,l?l.actual&&this._renderer.draw(l,I,E,A,C):this._opts.showPlaceholder&&this._renderer.drawPlaceholder(E,A,C),this._fullyCleared=!1}}}}viewportResize(e){if(!this._images.size){this._viewportMetrics=e;return}if(this._viewportMetrics.cols>=e.cols){this._viewportMetrics=e;return}let t=this._terminal._core.buffer,i=t.lines.length,s=this._viewportMetrics.cols-1;for(let n=0;n<i;++n){let A=t.lines.get(n);if(A.getBg(s)&268435456){let o=A._extendedAttrs[s]||F,a=o.imageId;if(a===void 0||a===-1)continue;let c=this._images.get(a);if(!c)continue;let h=Math.ceil((c.actual?.width||0)/c.actualCellSize.width);if(o.tileId%h+1>=h)continue;let l=!1;for(let C=s+1;C>e.cols;++C)if(A._data[C*3+0]&4194303){l=!0;break}if(l)continue;let I=Math.min(e.cols,h-o.tileId%h+s),E=o.tileId;for(let C=s+1;C<I;++C)this._writeToCell(A,C,a,++E),c.tileCount++}}this._viewportMetrics=e}getImageAtBufferCell(e,t){let s=this._terminal._core.buffer.lines.get(t);if(s&&s.getBg(e)&268435456){let n=s._extendedAttrs[e]||F;if(n.imageId&&n.imageId!==-1){let A=this._images.get(n.imageId)?.orig;if(window.ImageBitmap&&A instanceof ImageBitmap){let o=T.createCanvas(window.document,A.width,A.height);return o.getContext("2d")?.drawImage(A,0,0,A.width,A.height),o}return A}}}extractTileAtBufferCell(e,t){let s=this._terminal._core.buffer.lines.get(t);if(s&&s.getBg(e)&268435456){let n=s._extendedAttrs[e]||F;if(n.imageId&&n.imageId!==-1&&n.tileId!==-1){let A=this._images.get(n.imageId);if(A)return this._renderer.extractTile(A,n.tileId)}}}_evictOldest(e){let t=this._getStoredPixels(),i=t;for(;this._pixelLimit<i+e&&this._images.size;){let s=this._images.get(++this._lowestId);s&&s.orig&&(i-=s.orig.width*s.orig.height,s.actual&&s.orig!==s.actual&&(i-=s.actual.width*s.actual.height),s.marker?.dispose(),this._delImg(this._lowestId))}return t-i}_writeToCell(e,t,i,s){if(e._data[t*3+2]&268435456){let n=e._extendedAttrs[t];if(n){if(n.imageId!==void 0){let A=this._images.get(n.imageId);A&&A.tileCount--,n.imageId=i,n.tileId=s;return}e._extendedAttrs[t]=new G(n.ext,n.urlId,i,s);return}}e._data[t*3+2]|=268435456,e._extendedAttrs[t]=new G(0,0,i,s)}_evictOnAlternate(){for(let i of this._images.values())i.bufferType==="alternate"&&(i.tileCount=0);let e=this._terminal._core.buffer;for(let i=0;i<this._terminal.rows;++i){let s=e.lines.get(i);if(s){for(let n=0;n<this._terminal.cols;++n)if(s._data[n*3+2]&268435456){let A=s._extendedAttrs[n]?.imageId;if(A){let o=this._images.get(A);o&&o.tileCount++}}}}let t=[];for(let[i,s]of this._images.entries())s.bufferType==="alternate"&&!s.tileCount&&(s.marker?.dispose(),t.push(i));for(let i of t)this._delImg(i)}};var qe=Y(Oe());function se(r){let e="";for(let t=0;t<r.length;++t)e+=String.fromCharCode(r[t]);return e}function Ee(r){let e=0;for(let t=0;t<r.length;++t){if(r[t]<48||r[t]>57)throw new Error("illegal char");e=e*10+r[t]-48}return e}function Pe(r){let e=se(r);if(!e.match(/^((auto)|(\d+?((px)|(%)){0,1}))$/))throw new Error("illegal size");return e}function yt(r){if(typeof Buffer<"u")return Buffer.from(se(r),"base64").toString();let e=atob(se(r)),t=new Uint8Array(e.length);for(let i=0;i<t.length;++i)t[i]=e.charCodeAt(i);return new TextDecoder().decode(t)}var Ye={inline:Ee,size:Ee,name:yt,width:Pe,height:Pe,preserveAspectRatio:Ee},We=[70,105,108,101],Be=1024,ne=class{constructor(){this.state=0;this._buffer=new Uint32Array(Be);this._position=0;this._key="";this.fields={}}reset(){this._buffer.fill(0),this.state=0,this._position=0,this.fields={},this._key=""}parse(e,t,i){let s=this.state,n=this._position,A=this._buffer;if(s===1||s===4||s===0&&n>6)return-1;for(let o=t;o<i;++o){let a=e[o];switch(a){case 59:if(!this._storeValue(n))return this._a();s=2,n=0;break;case 61:if(s===0){for(let c=0;c<We.length;++c)if(A[c]!==We[c])return this._a();s=2,n=0}else if(s===2){if(!this._storeKey(n))return this._a();s=3,n=0}else if(s===3){if(n>=Be)return this._a();A[n++]=a}break;case 58:return s===3&&!this._storeValue(n)?this._a():(this.state=4,o+1);default:if(n>=Be)return this._a();A[n++]=a}}return this.state=s,this._position=n,-2}_a(){return this.state=1,-1}_storeKey(e){let t=se(this._buffer.subarray(0,e));return t?(this._key=t,this.fields[t]=null,!0):!1}_storeValue(e){if(this._key){try{let t=this._buffer.slice(0,e);this.fields[this._key]=Ye[this._key]?Ye[this._key](t):t}catch{return!1}return!0}return!1}};var J={mime:"unsupported",width:0,height:0};function ze(r){if(r.length<24)return J;let e=new Uint32Array(r.buffer,r.byteOffset,6);if(e[0]===1196314761&&e[1]===169478669&&e[3]===1380206665)return{mime:"image/png",width:r[16]<<24|r[17]<<16|r[18]<<8|r[19],height:r[20]<<24|r[21]<<16|r[22]<<8|r[23]};if(r[0]===255&&r[1]===216&&r[2]===255){let[t,i]=vt(r);return{mime:"image/jpeg",width:t,height:i}}return e[0]===944130375&&(r[4]===55||r[4]===57)&&r[5]===97?{mime:"image/gif",width:r[7]<<8|r[6],height:r[9]<<8|r[8]}:J}function vt(r){let e=r.length,t=4,i=r[t]<<8|r[t+1];for(;;){if(t+=i,t>=e)return[0,0];if(r[t]!==255)return[0,0];if(r[t+1]===192||r[t+1]===194)return t+8<e?[r[t+7]<<8|r[t+8],r[t+5]<<8|r[t+6]]:[0,0];t+=2,i=r[t]<<8|r[t+1]}}var St=4194304,Qe={name:"Unnamed file",size:0,width:"auto",height:"auto",preserveAspectRatio:1,inline:0},Ae=class{constructor(e,t,i,s){this._opts=e;this._renderer=t;this._storage=i;this._coreTerminal=s;this._aborted=!1;this._hp=new ne;this._header=Qe;this._dec=new qe.default(St);this._metrics=J}reset(){}start(){this._aborted=!1,this._header=Qe,this._metrics=J,this._hp.reset()}put(e,t,i){if(!this._aborted)if(this._hp.state===4)this._dec.put(e,t,i)&&(this._dec.release(),this._aborted=!0);else{let s=this._hp.parse(e,t,i);if(s===-1){this._aborted=!0;return}if(s>0){if(this._header=Object.assign({},Qe,this._hp.fields),!this._header.inline||!this._header.size||this._header.size>this._opts.iipSizeLimit){this._aborted=!0;return}this._dec.init(this._header.size),this._dec.put(e,s,i)&&(this._dec.release(),this._aborted=!0)}}}end(e){if(this._aborted)return!0;let t=0,i=0,s=!0;if((s=e)&&(s=!this._dec.end())&&(this._metrics=ze(this._dec.data8),(s=this._metrics.mime!=="unsupported")&&(t=this._metrics.width,i=this._metrics.height,(s=t&&i&&t*i<this._opts.pixelLimit)&&([t,i]=this._resize(t,i).map(Math.floor),s=t&&i&&t*i<this._opts.pixelLimit))),!s)return this._dec.release(),!0;let n=new Blob([this._dec.data8],{type:this._metrics.mime});if(this._dec.release(),!window.createImageBitmap){let A=URL.createObjectURL(n),o=new Image;return new Promise(a=>{o.addEventListener("load",()=>{URL.revokeObjectURL(A);let c=T.createCanvas(window.document,t,i);c.getContext("2d")?.drawImage(o,0,0,t,i),this._storage.addImage(c),a(!0)}),o.src=A,setTimeout(()=>a(!0),1e3)})}return createImageBitmap(n,{resizeWidth:t,resizeHeight:i}).then(A=>(this._storage.addImage(A),!0))}_resize(e,t){let i=this._renderer.dimensions?.css.cell.width||S.width,s=this._renderer.dimensions?.css.cell.height||S.height,n=this._renderer.dimensions?.css.canvas.width||i*this._coreTerminal.cols,A=this._renderer.dimensions?.css.canvas.height||s*this._coreTerminal.rows,o=this._dim(this._header.width,n,i),a=this._dim(this._header.height,A,s);if(!o&&!a){let c=n/e,h=(A-s)/t,l=Math.min(c,h);return l<1?[e*l,t*l]:[e,t]}return o?this._header.preserveAspectRatio||!o||!a?[o,t*o/e]:[o,a]:[e*a/t,a]}_dim(e,t,i){return e==="auto"?0:e.endsWith("%")?parseInt(e.slice(0,-1))*t/100:e.endsWith("px")?parseInt(e.slice(0,-2)):parseInt(e)*i}};var w=Y(W());var $e=Y(Xe());var Nt=4194304,De=w.PALETTE_ANSI_256;De.set(w.PALETTE_VT340_COLOR);var ce=class{constructor(e,t,i){this._opts=e;this._storage=t;this._coreTerminal=i;this._size=0;this._aborted=!1;(0,$e.DecoderAsync)({memoryLimit:this._opts.pixelLimit*4,palette:De,paletteLimit:this._opts.sixelPaletteLimit}).then(s=>this._dec=s)}reset(){this._dec&&(this._dec.release(),this._dec._palette.fill(0),this._dec.init(0,De,this._opts.sixelPaletteLimit))}hook(e){if(this._size=0,this._aborted=!1,this._dec){let t=e.params[1]===1?0:Ht(this._coreTerminal._core._inputHandler._curAttrData,this._coreTerminal._core._themeService?.colors);this._dec.init(t,null,this._opts.sixelPaletteLimit)}}put(e,t,i){if(!(this._aborted||!this._dec)){if(this._size+=i-t,this._size>this._opts.sixelSizeLimit){console.warn("SIXEL: too much data, aborting"),this._aborted=!0,this._dec.release();return}try{this._dec.decode(e,t,i)}catch(s){console.warn(`SIXEL: error while decoding image - ${s}`),this._aborted=!0,this._dec.release()}}}unhook(e){if(this._aborted||!e||!this._dec)return!0;let t=this._dec.width,i=this._dec.height;if(!t||!i)return i&&this._storage.advanceCursor(i),!0;let s=T.createCanvas(void 0,t,i);return s.getContext("2d")?.putImageData(new ImageData(this._dec.data8,t,i),0,0),this._dec.memoryUsage>Nt&&this._dec.release(),this._storage.addImage(s),!0}};function Ht(r,e){let t=0;if(!e)return t;if(r.isInverse())if(r.isFgDefault())t=le(e.foreground.rgba);else if(r.isFgRGB()){let i=r.constructor.toColorRGB(r.getFgColor());t=(0,w.toRGBA8888)(...i)}else t=le(e.ansi[r.getFgColor()].rgba);else if(r.isBgDefault())t=le(e.background.rgba);else if(r.isBgRGB()){let i=r.constructor.toColorRGB(r.getBgColor());t=(0,w.toRGBA8888)(...i)}else t=le(e.ansi[r.getBgColor()].rgba);return t}function le(r){return w.BIG_ENDIAN?r:(r&255)<<24|(r>>>8&255)<<16|(r>>>16&255)<<8|r>>>24&255}var et={enableSizeReports:!0,pixelLimit:16777216,sixelSupport:!0,sixelScrolling:!0,sixelPaletteLimit:256,sixelSizeLimit:25e6,storageLimit:128,showPlaceholder:!0,iipSupport:!0,iipSizeLimit:2e7},tt=4096;var it=class{constructor(e){this._disposables=[];this._handlers=new Map;this._opts=Object.assign({},et,e),this._defaultOpts=Object.assign({},et,e)}dispose(){for(let e of this._disposables)e.dispose();this._disposables.length=0,this._handlers.clear()}_disposeLater(...e){for(let t of e)this._disposables.push(t)}activate(e){if(this._terminal=e,this._renderer=new T(e),this._storage=new ie(e,this._renderer,this._opts),this._opts.enableSizeReports){let t=e.options.windowOptions||{};t.getWinSizePixels=!0,t.getCellSizePixels=!0,t.getWinSizeChars=!0,e.options.windowOptions=t}if(this._disposeLater(this._renderer,this._storage,e.parser.registerCsiHandler({prefix:"?",final:"h"},t=>this._decset(t)),e.parser.registerCsiHandler({prefix:"?",final:"l"},t=>this._decrst(t)),e.parser.registerCsiHandler({final:"c"},t=>this._da1(t)),e.parser.registerCsiHandler({prefix:"?",final:"S"},t=>this._xtermGraphicsAttributes(t)),e.onRender(t=>this._storage?.render(t)),e.parser.registerCsiHandler({intermediates:"!",final:"p"},()=>this.reset()),e.parser.registerEscHandler({final:"c"},()=>this.reset()),e._core._inputHandler.onRequestReset(()=>this.reset()),e.buffer.onBufferChange(()=>this._storage?.wipeAlternate()),e.onResize(t=>this._storage?.viewportResize(t))),this._opts.sixelSupport){let t=new ce(this._opts,this._storage,e);this._handlers.set("sixel",t),this._disposeLater(e._core._inputHandler._parser.registerDcsHandler({final:"q"},t))}if(this._opts.iipSupport){let t=new Ae(this._opts,this._renderer,this._storage,e);this._handlers.set("iip",t),this._disposeLater(e._core._inputHandler._parser.registerOscHandler(1337,t))}}reset(){this._opts.sixelScrolling=this._defaultOpts.sixelScrolling,this._opts.sixelPaletteLimit=this._defaultOpts.sixelPaletteLimit,this._storage?.reset();for(let e of this._handlers.values())e.reset();return!1}get storageLimit(){return this._storage?.getLimit()||-1}set storageLimit(e){this._storage?.setLimit(e),this._opts.storageLimit=e}get storageUsage(){return this._storage?this._storage.getUsage():-1}get showPlaceholder(){return this._opts.showPlaceholder}set showPlaceholder(e){this._opts.showPlaceholder=e,this._renderer?.showPlaceholder(e)}getImageAtBufferCell(e,t){return this._storage?.getImageAtBufferCell(e,t)}extractTileAtBufferCell(e,t){return this._storage?.extractTileAtBufferCell(e,t)}_report(e){this._terminal?._core.coreService.triggerDataEvent(e)}_decset(e){for(let t=0;t<e.length;++t)switch(e[t]){case 80:this._opts.sixelScrolling=!1;break}return!1}_decrst(e){for(let t=0;t<e.length;++t)switch(e[t]){case 80:this._opts.sixelScrolling=!0;break}return!1}_da1(e){return e[0]?!0:this._opts.sixelSupport?(this._report("\x1B[?62;4;9;22c"),!0):!1}_xtermGraphicsAttributes(e){if(e.length<2)return!0;if(e[0]===1)switch(e[1]){case 1:return this._report(`\x1B[?${e[0]};0;${this._opts.sixelPaletteLimit}S`),!0;case 2:this._opts.sixelPaletteLimit=this._defaultOpts.sixelPaletteLimit,this._report(`\x1B[?${e[0]};0;${this._opts.sixelPaletteLimit}S`);for(let t of this._handlers.values())t.reset();return!0;case 3:return e.length>2&&!(e[2]instanceof Array)&&e[2]<=tt?(this._opts.sixelPaletteLimit=e[2],this._report(`\x1B[?${e[0]};0;${this._opts.sixelPaletteLimit}S`)):this._report(`\x1B[?${e[0]};2S`),!0;case 4:return this._report(`\x1B[?${e[0]};0;${tt}S`),!0;default:return this._report(`\x1B[?${e[0]};2S`),!0}if(e[0]===2)switch(e[1]){case 1:let t=this._renderer?.dimensions?.css.canvas.width,i=this._renderer?.dimensions?.css.canvas.height;if(!t||!i){let n=S;t=(this._terminal?.cols||80)*n.width,i=(this._terminal?.rows||24)*n.height}if(t*i<this._opts.pixelLimit)this._report(`\x1B[?${e[0]};0;${t.toFixed(0)};${i.toFixed(0)}S`);else{let n=Math.floor(Math.sqrt(this._opts.pixelLimit));this._report(`\x1B[?${e[0]};0;${n};${n}S`)}return!0;case 4:let s=Math.floor(Math.sqrt(this._opts.pixelLimit));return this._report(`\x1B[?${e[0]};0;${s};${s}S`),!0;default:return this._report(`\x1B[?${e[0]};2S`),!0}return this._report(`\x1B[?${e[0]};1S`),!0}};export{it as ImageAddon};
//# sourceMappingURL=addon-image.mjs.map
