airloom 0.1.21 → 0.1.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,17 @@
1
- var Zd=Object.defineProperty;var Qd=(e,t,i)=>t in e?Zd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;var Ze=(e,t,i)=>Qd(e,typeof t!="symbol"?t+"":t,i);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const h of a)if(h.type==="childList")for(const d of h.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&n(d)}).observe(document,{childList:!0,subtree:!0});function i(a){const h={};return a.integrity&&(h.integrity=a.integrity),a.referrerPolicy&&(h.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?h.credentials="include":a.crossOrigin==="anonymous"?h.credentials="omit":h.credentials="same-origin",h}function n(a){if(a.ep)return;a.ep=!0;const h=i(a);fetch(a.href,h)}})();const ef="modulepreload",tf=function(e,t){return new URL(e,t).href},Bl={},Wh=function(t,i,n){let a=Promise.resolve();if(i&&i.length>0){let d=function(R){return Promise.all(R.map(k=>Promise.resolve(k).then(B=>({status:"fulfilled",value:B}),B=>({status:"rejected",reason:B}))))};const g=document.getElementsByTagName("link"),v=document.querySelector("meta[property=csp-nonce]"),p=(v==null?void 0:v.nonce)||(v==null?void 0:v.getAttribute("nonce"));a=d(i.map(R=>{if(R=tf(R,n),R in Bl)return;Bl[R]=!0;const k=R.endsWith(".css"),B=k?'[rel="stylesheet"]':"";if(!!n)for(let U=g.length-1;U>=0;U--){const Z=g[U];if(Z.href===R&&(!k||Z.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${R}"]${B}`))return;const P=document.createElement("link");if(P.rel=k?"stylesheet":ef,k||(P.as="script"),P.crossOrigin="",P.href=R,p&&P.setAttribute("nonce",p),document.head.appendChild(P),k)return new Promise((U,Z)=>{P.addEventListener("load",U),P.addEventListener("error",()=>Z(new Error(`Unable to preload CSS for ${R}`)))})}))}function h(d){const g=new Event("vite:preloadError",{cancelable:!0});if(g.payload=d,window.dispatchEvent(g),!g.defaultPrevented)throw d}return a.then(d=>{for(const g of d||[])g.status==="rejected"&&h(g.reason);return t().catch(h)})};var Ki=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function sf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function rf(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var i=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};i.prototype=t.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(i,n,a.get?a:{enumerable:!0,get:function(){return e[n]}})}),i}var jr={exports:{}},Il;function nf(){if(Il)return jr.exports;Il=1;var e=typeof Reflect=="object"?Reflect:null,t=e&&typeof e.apply=="function"?e.apply:function(W,E,ae){return Function.prototype.apply.call(W,E,ae)},i;e&&typeof e.ownKeys=="function"?i=e.ownKeys:Object.getOwnPropertySymbols?i=function(W){return Object.getOwnPropertyNames(W).concat(Object.getOwnPropertySymbols(W))}:i=function(W){return Object.getOwnPropertyNames(W)};function n(H){console&&console.warn&&console.warn(H)}var a=Number.isNaN||function(W){return W!==W};function h(){h.init.call(this)}jr.exports=h,jr.exports.once=_e,h.EventEmitter=h,h.prototype._events=void 0,h.prototype._eventsCount=0,h.prototype._maxListeners=void 0;var d=10;function g(H){if(typeof H!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof H)}Object.defineProperty(h,"defaultMaxListeners",{enumerable:!0,get:function(){return d},set:function(H){if(typeof H!="number"||H<0||a(H))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+H+".");d=H}}),h.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},h.prototype.setMaxListeners=function(W){if(typeof W!="number"||W<0||a(W))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+W+".");return this._maxListeners=W,this};function v(H){return H._maxListeners===void 0?h.defaultMaxListeners:H._maxListeners}h.prototype.getMaxListeners=function(){return v(this)},h.prototype.emit=function(W){for(var E=[],ae=1;ae<arguments.length;ae++)E.push(arguments[ae]);var be=W==="error",ze=this._events;if(ze!==void 0)be=be&&ze.error===void 0;else if(!be)return!1;if(be){var Be;if(E.length>0&&(Be=E[0]),Be instanceof Error)throw Be;var xe=new Error("Unhandled error."+(Be?" ("+Be.message+")":""));throw xe.context=Be,xe}var ce=ze[W];if(ce===void 0)return!1;if(typeof ce=="function")t(ce,this,E);else for(var f=ce.length,re=P(ce,f),ae=0;ae<f;++ae)t(re[ae],this,E);return!0};function p(H,W,E,ae){var be,ze,Be;if(g(E),ze=H._events,ze===void 0?(ze=H._events=Object.create(null),H._eventsCount=0):(ze.newListener!==void 0&&(H.emit("newListener",W,E.listener?E.listener:E),ze=H._events),Be=ze[W]),Be===void 0)Be=ze[W]=E,++H._eventsCount;else if(typeof Be=="function"?Be=ze[W]=ae?[E,Be]:[Be,E]:ae?Be.unshift(E):Be.push(E),be=v(H),be>0&&Be.length>be&&!Be.warned){Be.warned=!0;var xe=new Error("Possible EventEmitter memory leak detected. "+Be.length+" "+String(W)+" listeners added. Use emitter.setMaxListeners() to increase limit");xe.name="MaxListenersExceededWarning",xe.emitter=H,xe.type=W,xe.count=Be.length,n(xe)}return H}h.prototype.addListener=function(W,E){return p(this,W,E,!1)},h.prototype.on=h.prototype.addListener,h.prototype.prependListener=function(W,E){return p(this,W,E,!0)};function R(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function k(H,W,E){var ae={fired:!1,wrapFn:void 0,target:H,type:W,listener:E},be=R.bind(ae);return be.listener=E,ae.wrapFn=be,be}h.prototype.once=function(W,E){return g(E),this.on(W,k(this,W,E)),this},h.prototype.prependOnceListener=function(W,E){return g(E),this.prependListener(W,k(this,W,E)),this},h.prototype.removeListener=function(W,E){var ae,be,ze,Be,xe;if(g(E),be=this._events,be===void 0)return this;if(ae=be[W],ae===void 0)return this;if(ae===E||ae.listener===E)--this._eventsCount===0?this._events=Object.create(null):(delete be[W],be.removeListener&&this.emit("removeListener",W,ae.listener||E));else if(typeof ae!="function"){for(ze=-1,Be=ae.length-1;Be>=0;Be--)if(ae[Be]===E||ae[Be].listener===E){xe=ae[Be].listener,ze=Be;break}if(ze<0)return this;ze===0?ae.shift():U(ae,ze),ae.length===1&&(be[W]=ae[0]),be.removeListener!==void 0&&this.emit("removeListener",W,xe||E)}return this},h.prototype.off=h.prototype.removeListener,h.prototype.removeAllListeners=function(W){var E,ae,be;if(ae=this._events,ae===void 0)return this;if(ae.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):ae[W]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete ae[W]),this;if(arguments.length===0){var ze=Object.keys(ae),Be;for(be=0;be<ze.length;++be)Be=ze[be],Be!=="removeListener"&&this.removeAllListeners(Be);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(E=ae[W],typeof E=="function")this.removeListener(W,E);else if(E!==void 0)for(be=E.length-1;be>=0;be--)this.removeListener(W,E[be]);return this};function B(H,W,E){var ae=H._events;if(ae===void 0)return[];var be=ae[W];return be===void 0?[]:typeof be=="function"?E?[be.listener||be]:[be]:E?Z(be):P(be,be.length)}h.prototype.listeners=function(W){return B(this,W,!0)},h.prototype.rawListeners=function(W){return B(this,W,!1)},h.listenerCount=function(H,W){return typeof H.listenerCount=="function"?H.listenerCount(W):L.call(H,W)},h.prototype.listenerCount=L;function L(H){var W=this._events;if(W!==void 0){var E=W[H];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}h.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]};function P(H,W){for(var E=new Array(W),ae=0;ae<W;++ae)E[ae]=H[ae];return E}function U(H,W){for(;W+1<H.length;W++)H[W]=H[W+1];H.pop()}function Z(H){for(var W=new Array(H.length),E=0;E<W.length;++E)W[E]=H[E].listener||H[E];return W}function _e(H,W){return new Promise(function(E,ae){function be(Be){H.removeListener(W,ze),ae(Be)}function ze(){typeof H.removeListener=="function"&&H.removeListener("error",be),E([].slice.call(arguments))}Ne(H,W,ze,{once:!0}),W!=="error"&&rt(H,be,{once:!0})})}function rt(H,W,E){typeof H.on=="function"&&Ne(H,"error",W,E)}function Ne(H,W,E,ae){if(typeof H.on=="function")ae.once?H.once(W,E):H.on(W,E);else if(typeof H.addEventListener=="function")H.addEventListener(W,function be(ze){ae.once&&H.removeEventListener(W,be),E(ze)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof H)}return jr.exports}var Fh=nf();function of(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(const i of e)t+=String.fromCharCode(i);return btoa(t)}function af(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));const t=atob(e),i=new Uint8Array(t.length);for(let n=0;n<t.length;n++)i[n]=t.charCodeAt(n);return i}function lf(e){return new TextEncoder().encode(JSON.stringify(e))}function hf(e){const t=JSON.parse(new TextDecoder().decode(e));if(!t||typeof t!="object"||typeof t.type!="string"||typeof t.id!="string")throw new Error("Invalid channel message: missing type or id field");return t}function cf(e){const t=JSON.parse(e);if(!t||typeof t!="object"||typeof t.relay!="string"||typeof t.session!="string"||typeof t.v!="number")throw new Error("Invalid pairing data: missing required fields");if(t.transport!==void 0&&t.transport!=="ws"&&t.transport!=="ably")throw new Error('Invalid pairing data: transport must be "ws" or "ably"');if(t.token!==void 0&&typeof t.token!="string")throw new Error("Invalid pairing data: token must be a string");if(t.transport==="ably"&&!t.token)throw new Error("Invalid pairing data: Ably transport requires a token");return t}function uf(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var $n={exports:{}};const df={},ff=Object.freeze(Object.defineProperty({__proto__:null,default:df},Symbol.toStringTag,{value:"Module"})),_f=rf(ff);var Dl;function gf(){return Dl||(Dl=1,(function(e){(function(t){var i=function(m){var S,y=new Float64Array(16);if(m)for(S=0;S<m.length;S++)y[S]=m[S];return y},n=function(){throw new Error("no PRNG")},a=new Uint8Array(16),h=new Uint8Array(32);h[0]=9;var d=i(),g=i([1]),v=i([56129,1]),p=i([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),R=i([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),k=i([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),B=i([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),L=i([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function P(m,S,y,u){m[S]=y>>24&255,m[S+1]=y>>16&255,m[S+2]=y>>8&255,m[S+3]=y&255,m[S+4]=u>>24&255,m[S+5]=u>>16&255,m[S+6]=u>>8&255,m[S+7]=u&255}function U(m,S,y,u,w){var T,I=0;for(T=0;T<w;T++)I|=m[S+T]^y[u+T];return(1&I-1>>>8)-1}function Z(m,S,y,u){return U(m,S,y,u,16)}function _e(m,S,y,u){return U(m,S,y,u,32)}function rt(m,S,y,u){for(var w=u[0]&255|(u[1]&255)<<8|(u[2]&255)<<16|(u[3]&255)<<24,T=y[0]&255|(y[1]&255)<<8|(y[2]&255)<<16|(y[3]&255)<<24,I=y[4]&255|(y[5]&255)<<8|(y[6]&255)<<16|(y[7]&255)<<24,G=y[8]&255|(y[9]&255)<<8|(y[10]&255)<<16|(y[11]&255)<<24,X=y[12]&255|(y[13]&255)<<8|(y[14]&255)<<16|(y[15]&255)<<24,we=u[4]&255|(u[5]&255)<<8|(u[6]&255)<<16|(u[7]&255)<<24,le=S[0]&255|(S[1]&255)<<8|(S[2]&255)<<16|(S[3]&255)<<24,Ke=S[4]&255|(S[5]&255)<<8|(S[6]&255)<<16|(S[7]&255)<<24,fe=S[8]&255|(S[9]&255)<<8|(S[10]&255)<<16|(S[11]&255)<<24,ke=S[12]&255|(S[13]&255)<<8|(S[14]&255)<<16|(S[15]&255)<<24,Me=u[8]&255|(u[9]&255)<<8|(u[10]&255)<<16|(u[11]&255)<<24,He=y[16]&255|(y[17]&255)<<8|(y[18]&255)<<16|(y[19]&255)<<24,J=y[20]&255|(y[21]&255)<<8|(y[22]&255)<<16|(y[23]&255)<<24,Oe=y[24]&255|(y[25]&255)<<8|(y[26]&255)<<16|(y[27]&255)<<24,Te=y[28]&255|(y[29]&255)<<8|(y[30]&255)<<16|(y[31]&255)<<24,Ee=u[12]&255|(u[13]&255)<<8|(u[14]&255)<<16|(u[15]&255)<<24,ge=w,ie=T,he=I,ye=G,ve=X,ne=we,D=le,N=Ke,K=fe,j=ke,$=Me,Y=He,Ce=J,Ie=Oe,We=Te,Ue=Ee,x,Ge=0;Ge<20;Ge+=2)x=ge+Ce|0,ve^=x<<7|x>>>25,x=ve+ge|0,K^=x<<9|x>>>23,x=K+ve|0,Ce^=x<<13|x>>>19,x=Ce+K|0,ge^=x<<18|x>>>14,x=ne+ie|0,j^=x<<7|x>>>25,x=j+ne|0,Ie^=x<<9|x>>>23,x=Ie+j|0,ie^=x<<13|x>>>19,x=ie+Ie|0,ne^=x<<18|x>>>14,x=$+D|0,We^=x<<7|x>>>25,x=We+$|0,he^=x<<9|x>>>23,x=he+We|0,D^=x<<13|x>>>19,x=D+he|0,$^=x<<18|x>>>14,x=Ue+Y|0,ye^=x<<7|x>>>25,x=ye+Ue|0,N^=x<<9|x>>>23,x=N+ye|0,Y^=x<<13|x>>>19,x=Y+N|0,Ue^=x<<18|x>>>14,x=ge+ye|0,ie^=x<<7|x>>>25,x=ie+ge|0,he^=x<<9|x>>>23,x=he+ie|0,ye^=x<<13|x>>>19,x=ye+he|0,ge^=x<<18|x>>>14,x=ne+ve|0,D^=x<<7|x>>>25,x=D+ne|0,N^=x<<9|x>>>23,x=N+D|0,ve^=x<<13|x>>>19,x=ve+N|0,ne^=x<<18|x>>>14,x=$+j|0,Y^=x<<7|x>>>25,x=Y+$|0,K^=x<<9|x>>>23,x=K+Y|0,j^=x<<13|x>>>19,x=j+K|0,$^=x<<18|x>>>14,x=Ue+We|0,Ce^=x<<7|x>>>25,x=Ce+Ue|0,Ie^=x<<9|x>>>23,x=Ie+Ce|0,We^=x<<13|x>>>19,x=We+Ie|0,Ue^=x<<18|x>>>14;ge=ge+w|0,ie=ie+T|0,he=he+I|0,ye=ye+G|0,ve=ve+X|0,ne=ne+we|0,D=D+le|0,N=N+Ke|0,K=K+fe|0,j=j+ke|0,$=$+Me|0,Y=Y+He|0,Ce=Ce+J|0,Ie=Ie+Oe|0,We=We+Te|0,Ue=Ue+Ee|0,m[0]=ge>>>0&255,m[1]=ge>>>8&255,m[2]=ge>>>16&255,m[3]=ge>>>24&255,m[4]=ie>>>0&255,m[5]=ie>>>8&255,m[6]=ie>>>16&255,m[7]=ie>>>24&255,m[8]=he>>>0&255,m[9]=he>>>8&255,m[10]=he>>>16&255,m[11]=he>>>24&255,m[12]=ye>>>0&255,m[13]=ye>>>8&255,m[14]=ye>>>16&255,m[15]=ye>>>24&255,m[16]=ve>>>0&255,m[17]=ve>>>8&255,m[18]=ve>>>16&255,m[19]=ve>>>24&255,m[20]=ne>>>0&255,m[21]=ne>>>8&255,m[22]=ne>>>16&255,m[23]=ne>>>24&255,m[24]=D>>>0&255,m[25]=D>>>8&255,m[26]=D>>>16&255,m[27]=D>>>24&255,m[28]=N>>>0&255,m[29]=N>>>8&255,m[30]=N>>>16&255,m[31]=N>>>24&255,m[32]=K>>>0&255,m[33]=K>>>8&255,m[34]=K>>>16&255,m[35]=K>>>24&255,m[36]=j>>>0&255,m[37]=j>>>8&255,m[38]=j>>>16&255,m[39]=j>>>24&255,m[40]=$>>>0&255,m[41]=$>>>8&255,m[42]=$>>>16&255,m[43]=$>>>24&255,m[44]=Y>>>0&255,m[45]=Y>>>8&255,m[46]=Y>>>16&255,m[47]=Y>>>24&255,m[48]=Ce>>>0&255,m[49]=Ce>>>8&255,m[50]=Ce>>>16&255,m[51]=Ce>>>24&255,m[52]=Ie>>>0&255,m[53]=Ie>>>8&255,m[54]=Ie>>>16&255,m[55]=Ie>>>24&255,m[56]=We>>>0&255,m[57]=We>>>8&255,m[58]=We>>>16&255,m[59]=We>>>24&255,m[60]=Ue>>>0&255,m[61]=Ue>>>8&255,m[62]=Ue>>>16&255,m[63]=Ue>>>24&255}function Ne(m,S,y,u){for(var w=u[0]&255|(u[1]&255)<<8|(u[2]&255)<<16|(u[3]&255)<<24,T=y[0]&255|(y[1]&255)<<8|(y[2]&255)<<16|(y[3]&255)<<24,I=y[4]&255|(y[5]&255)<<8|(y[6]&255)<<16|(y[7]&255)<<24,G=y[8]&255|(y[9]&255)<<8|(y[10]&255)<<16|(y[11]&255)<<24,X=y[12]&255|(y[13]&255)<<8|(y[14]&255)<<16|(y[15]&255)<<24,we=u[4]&255|(u[5]&255)<<8|(u[6]&255)<<16|(u[7]&255)<<24,le=S[0]&255|(S[1]&255)<<8|(S[2]&255)<<16|(S[3]&255)<<24,Ke=S[4]&255|(S[5]&255)<<8|(S[6]&255)<<16|(S[7]&255)<<24,fe=S[8]&255|(S[9]&255)<<8|(S[10]&255)<<16|(S[11]&255)<<24,ke=S[12]&255|(S[13]&255)<<8|(S[14]&255)<<16|(S[15]&255)<<24,Me=u[8]&255|(u[9]&255)<<8|(u[10]&255)<<16|(u[11]&255)<<24,He=y[16]&255|(y[17]&255)<<8|(y[18]&255)<<16|(y[19]&255)<<24,J=y[20]&255|(y[21]&255)<<8|(y[22]&255)<<16|(y[23]&255)<<24,Oe=y[24]&255|(y[25]&255)<<8|(y[26]&255)<<16|(y[27]&255)<<24,Te=y[28]&255|(y[29]&255)<<8|(y[30]&255)<<16|(y[31]&255)<<24,Ee=u[12]&255|(u[13]&255)<<8|(u[14]&255)<<16|(u[15]&255)<<24,ge=w,ie=T,he=I,ye=G,ve=X,ne=we,D=le,N=Ke,K=fe,j=ke,$=Me,Y=He,Ce=J,Ie=Oe,We=Te,Ue=Ee,x,Ge=0;Ge<20;Ge+=2)x=ge+Ce|0,ve^=x<<7|x>>>25,x=ve+ge|0,K^=x<<9|x>>>23,x=K+ve|0,Ce^=x<<13|x>>>19,x=Ce+K|0,ge^=x<<18|x>>>14,x=ne+ie|0,j^=x<<7|x>>>25,x=j+ne|0,Ie^=x<<9|x>>>23,x=Ie+j|0,ie^=x<<13|x>>>19,x=ie+Ie|0,ne^=x<<18|x>>>14,x=$+D|0,We^=x<<7|x>>>25,x=We+$|0,he^=x<<9|x>>>23,x=he+We|0,D^=x<<13|x>>>19,x=D+he|0,$^=x<<18|x>>>14,x=Ue+Y|0,ye^=x<<7|x>>>25,x=ye+Ue|0,N^=x<<9|x>>>23,x=N+ye|0,Y^=x<<13|x>>>19,x=Y+N|0,Ue^=x<<18|x>>>14,x=ge+ye|0,ie^=x<<7|x>>>25,x=ie+ge|0,he^=x<<9|x>>>23,x=he+ie|0,ye^=x<<13|x>>>19,x=ye+he|0,ge^=x<<18|x>>>14,x=ne+ve|0,D^=x<<7|x>>>25,x=D+ne|0,N^=x<<9|x>>>23,x=N+D|0,ve^=x<<13|x>>>19,x=ve+N|0,ne^=x<<18|x>>>14,x=$+j|0,Y^=x<<7|x>>>25,x=Y+$|0,K^=x<<9|x>>>23,x=K+Y|0,j^=x<<13|x>>>19,x=j+K|0,$^=x<<18|x>>>14,x=Ue+We|0,Ce^=x<<7|x>>>25,x=Ce+Ue|0,Ie^=x<<9|x>>>23,x=Ie+Ce|0,We^=x<<13|x>>>19,x=We+Ie|0,Ue^=x<<18|x>>>14;m[0]=ge>>>0&255,m[1]=ge>>>8&255,m[2]=ge>>>16&255,m[3]=ge>>>24&255,m[4]=ne>>>0&255,m[5]=ne>>>8&255,m[6]=ne>>>16&255,m[7]=ne>>>24&255,m[8]=$>>>0&255,m[9]=$>>>8&255,m[10]=$>>>16&255,m[11]=$>>>24&255,m[12]=Ue>>>0&255,m[13]=Ue>>>8&255,m[14]=Ue>>>16&255,m[15]=Ue>>>24&255,m[16]=D>>>0&255,m[17]=D>>>8&255,m[18]=D>>>16&255,m[19]=D>>>24&255,m[20]=N>>>0&255,m[21]=N>>>8&255,m[22]=N>>>16&255,m[23]=N>>>24&255,m[24]=K>>>0&255,m[25]=K>>>8&255,m[26]=K>>>16&255,m[27]=K>>>24&255,m[28]=j>>>0&255,m[29]=j>>>8&255,m[30]=j>>>16&255,m[31]=j>>>24&255}function H(m,S,y,u){rt(m,S,y,u)}function W(m,S,y,u){Ne(m,S,y,u)}var E=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function ae(m,S,y,u,w,T,I){var G=new Uint8Array(16),X=new Uint8Array(64),we,le;for(le=0;le<16;le++)G[le]=0;for(le=0;le<8;le++)G[le]=T[le];for(;w>=64;){for(H(X,G,I,E),le=0;le<64;le++)m[S+le]=y[u+le]^X[le];for(we=1,le=8;le<16;le++)we=we+(G[le]&255)|0,G[le]=we&255,we>>>=8;w-=64,S+=64,u+=64}if(w>0)for(H(X,G,I,E),le=0;le<w;le++)m[S+le]=y[u+le]^X[le];return 0}function be(m,S,y,u,w){var T=new Uint8Array(16),I=new Uint8Array(64),G,X;for(X=0;X<16;X++)T[X]=0;for(X=0;X<8;X++)T[X]=u[X];for(;y>=64;){for(H(I,T,w,E),X=0;X<64;X++)m[S+X]=I[X];for(G=1,X=8;X<16;X++)G=G+(T[X]&255)|0,T[X]=G&255,G>>>=8;y-=64,S+=64}if(y>0)for(H(I,T,w,E),X=0;X<y;X++)m[S+X]=I[X];return 0}function ze(m,S,y,u,w){var T=new Uint8Array(32);W(T,u,w,E);for(var I=new Uint8Array(8),G=0;G<8;G++)I[G]=u[G+16];return be(m,S,y,I,T)}function Be(m,S,y,u,w,T,I){var G=new Uint8Array(32);W(G,T,I,E);for(var X=new Uint8Array(8),we=0;we<8;we++)X[we]=T[we+16];return ae(m,S,y,u,w,X,G)}var xe=function(m){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var S,y,u,w,T,I,G,X;S=m[0]&255|(m[1]&255)<<8,this.r[0]=S&8191,y=m[2]&255|(m[3]&255)<<8,this.r[1]=(S>>>13|y<<3)&8191,u=m[4]&255|(m[5]&255)<<8,this.r[2]=(y>>>10|u<<6)&7939,w=m[6]&255|(m[7]&255)<<8,this.r[3]=(u>>>7|w<<9)&8191,T=m[8]&255|(m[9]&255)<<8,this.r[4]=(w>>>4|T<<12)&255,this.r[5]=T>>>1&8190,I=m[10]&255|(m[11]&255)<<8,this.r[6]=(T>>>14|I<<2)&8191,G=m[12]&255|(m[13]&255)<<8,this.r[7]=(I>>>11|G<<5)&8065,X=m[14]&255|(m[15]&255)<<8,this.r[8]=(G>>>8|X<<8)&8191,this.r[9]=X>>>5&127,this.pad[0]=m[16]&255|(m[17]&255)<<8,this.pad[1]=m[18]&255|(m[19]&255)<<8,this.pad[2]=m[20]&255|(m[21]&255)<<8,this.pad[3]=m[22]&255|(m[23]&255)<<8,this.pad[4]=m[24]&255|(m[25]&255)<<8,this.pad[5]=m[26]&255|(m[27]&255)<<8,this.pad[6]=m[28]&255|(m[29]&255)<<8,this.pad[7]=m[30]&255|(m[31]&255)<<8};xe.prototype.blocks=function(m,S,y){for(var u=this.fin?0:2048,w,T,I,G,X,we,le,Ke,fe,ke,Me,He,J,Oe,Te,Ee,ge,ie,he,ye=this.h[0],ve=this.h[1],ne=this.h[2],D=this.h[3],N=this.h[4],K=this.h[5],j=this.h[6],$=this.h[7],Y=this.h[8],Ce=this.h[9],Ie=this.r[0],We=this.r[1],Ue=this.r[2],x=this.r[3],Ge=this.r[4],Fe=this.r[5],Ye=this.r[6],Pe=this.r[7],Je=this.r[8],Xe=this.r[9];y>=16;)w=m[S+0]&255|(m[S+1]&255)<<8,ye+=w&8191,T=m[S+2]&255|(m[S+3]&255)<<8,ve+=(w>>>13|T<<3)&8191,I=m[S+4]&255|(m[S+5]&255)<<8,ne+=(T>>>10|I<<6)&8191,G=m[S+6]&255|(m[S+7]&255)<<8,D+=(I>>>7|G<<9)&8191,X=m[S+8]&255|(m[S+9]&255)<<8,N+=(G>>>4|X<<12)&8191,K+=X>>>1&8191,we=m[S+10]&255|(m[S+11]&255)<<8,j+=(X>>>14|we<<2)&8191,le=m[S+12]&255|(m[S+13]&255)<<8,$+=(we>>>11|le<<5)&8191,Ke=m[S+14]&255|(m[S+15]&255)<<8,Y+=(le>>>8|Ke<<8)&8191,Ce+=Ke>>>5|u,fe=0,ke=fe,ke+=ye*Ie,ke+=ve*(5*Xe),ke+=ne*(5*Je),ke+=D*(5*Pe),ke+=N*(5*Ye),fe=ke>>>13,ke&=8191,ke+=K*(5*Fe),ke+=j*(5*Ge),ke+=$*(5*x),ke+=Y*(5*Ue),ke+=Ce*(5*We),fe+=ke>>>13,ke&=8191,Me=fe,Me+=ye*We,Me+=ve*Ie,Me+=ne*(5*Xe),Me+=D*(5*Je),Me+=N*(5*Pe),fe=Me>>>13,Me&=8191,Me+=K*(5*Ye),Me+=j*(5*Fe),Me+=$*(5*Ge),Me+=Y*(5*x),Me+=Ce*(5*Ue),fe+=Me>>>13,Me&=8191,He=fe,He+=ye*Ue,He+=ve*We,He+=ne*Ie,He+=D*(5*Xe),He+=N*(5*Je),fe=He>>>13,He&=8191,He+=K*(5*Pe),He+=j*(5*Ye),He+=$*(5*Fe),He+=Y*(5*Ge),He+=Ce*(5*x),fe+=He>>>13,He&=8191,J=fe,J+=ye*x,J+=ve*Ue,J+=ne*We,J+=D*Ie,J+=N*(5*Xe),fe=J>>>13,J&=8191,J+=K*(5*Je),J+=j*(5*Pe),J+=$*(5*Ye),J+=Y*(5*Fe),J+=Ce*(5*Ge),fe+=J>>>13,J&=8191,Oe=fe,Oe+=ye*Ge,Oe+=ve*x,Oe+=ne*Ue,Oe+=D*We,Oe+=N*Ie,fe=Oe>>>13,Oe&=8191,Oe+=K*(5*Xe),Oe+=j*(5*Je),Oe+=$*(5*Pe),Oe+=Y*(5*Ye),Oe+=Ce*(5*Fe),fe+=Oe>>>13,Oe&=8191,Te=fe,Te+=ye*Fe,Te+=ve*Ge,Te+=ne*x,Te+=D*Ue,Te+=N*We,fe=Te>>>13,Te&=8191,Te+=K*Ie,Te+=j*(5*Xe),Te+=$*(5*Je),Te+=Y*(5*Pe),Te+=Ce*(5*Ye),fe+=Te>>>13,Te&=8191,Ee=fe,Ee+=ye*Ye,Ee+=ve*Fe,Ee+=ne*Ge,Ee+=D*x,Ee+=N*Ue,fe=Ee>>>13,Ee&=8191,Ee+=K*We,Ee+=j*Ie,Ee+=$*(5*Xe),Ee+=Y*(5*Je),Ee+=Ce*(5*Pe),fe+=Ee>>>13,Ee&=8191,ge=fe,ge+=ye*Pe,ge+=ve*Ye,ge+=ne*Fe,ge+=D*Ge,ge+=N*x,fe=ge>>>13,ge&=8191,ge+=K*Ue,ge+=j*We,ge+=$*Ie,ge+=Y*(5*Xe),ge+=Ce*(5*Je),fe+=ge>>>13,ge&=8191,ie=fe,ie+=ye*Je,ie+=ve*Pe,ie+=ne*Ye,ie+=D*Fe,ie+=N*Ge,fe=ie>>>13,ie&=8191,ie+=K*x,ie+=j*Ue,ie+=$*We,ie+=Y*Ie,ie+=Ce*(5*Xe),fe+=ie>>>13,ie&=8191,he=fe,he+=ye*Xe,he+=ve*Je,he+=ne*Pe,he+=D*Ye,he+=N*Fe,fe=he>>>13,he&=8191,he+=K*Ge,he+=j*x,he+=$*Ue,he+=Y*We,he+=Ce*Ie,fe+=he>>>13,he&=8191,fe=(fe<<2)+fe|0,fe=fe+ke|0,ke=fe&8191,fe=fe>>>13,Me+=fe,ye=ke,ve=Me,ne=He,D=J,N=Oe,K=Te,j=Ee,$=ge,Y=ie,Ce=he,S+=16,y-=16;this.h[0]=ye,this.h[1]=ve,this.h[2]=ne,this.h[3]=D,this.h[4]=N,this.h[5]=K,this.h[6]=j,this.h[7]=$,this.h[8]=Y,this.h[9]=Ce},xe.prototype.finish=function(m,S){var y=new Uint16Array(10),u,w,T,I;if(this.leftover){for(I=this.leftover,this.buffer[I++]=1;I<16;I++)this.buffer[I]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(u=this.h[1]>>>13,this.h[1]&=8191,I=2;I<10;I++)this.h[I]+=u,u=this.h[I]>>>13,this.h[I]&=8191;for(this.h[0]+=u*5,u=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=u,u=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=u,y[0]=this.h[0]+5,u=y[0]>>>13,y[0]&=8191,I=1;I<10;I++)y[I]=this.h[I]+u,u=y[I]>>>13,y[I]&=8191;for(y[9]-=8192,w=(u^1)-1,I=0;I<10;I++)y[I]&=w;for(w=~w,I=0;I<10;I++)this.h[I]=this.h[I]&w|y[I];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,T=this.h[0]+this.pad[0],this.h[0]=T&65535,I=1;I<8;I++)T=(this.h[I]+this.pad[I]|0)+(T>>>16)|0,this.h[I]=T&65535;m[S+0]=this.h[0]>>>0&255,m[S+1]=this.h[0]>>>8&255,m[S+2]=this.h[1]>>>0&255,m[S+3]=this.h[1]>>>8&255,m[S+4]=this.h[2]>>>0&255,m[S+5]=this.h[2]>>>8&255,m[S+6]=this.h[3]>>>0&255,m[S+7]=this.h[3]>>>8&255,m[S+8]=this.h[4]>>>0&255,m[S+9]=this.h[4]>>>8&255,m[S+10]=this.h[5]>>>0&255,m[S+11]=this.h[5]>>>8&255,m[S+12]=this.h[6]>>>0&255,m[S+13]=this.h[6]>>>8&255,m[S+14]=this.h[7]>>>0&255,m[S+15]=this.h[7]>>>8&255},xe.prototype.update=function(m,S,y){var u,w;if(this.leftover){for(w=16-this.leftover,w>y&&(w=y),u=0;u<w;u++)this.buffer[this.leftover+u]=m[S+u];if(y-=w,S+=w,this.leftover+=w,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(y>=16&&(w=y-y%16,this.blocks(m,S,w),S+=w,y-=w),y){for(u=0;u<y;u++)this.buffer[this.leftover+u]=m[S+u];this.leftover+=y}};function ce(m,S,y,u,w,T){var I=new xe(T);return I.update(y,u,w),I.finish(m,S),0}function f(m,S,y,u,w,T){var I=new Uint8Array(16);return ce(I,0,y,u,w,T),Z(m,S,I,0)}function re(m,S,y,u,w){var T;if(y<32)return-1;for(Be(m,0,S,0,y,u,w),ce(m,16,m,32,y-32,m),T=0;T<16;T++)m[T]=0;return 0}function oe(m,S,y,u,w){var T,I=new Uint8Array(32);if(y<32||(ze(I,0,32,u,w),f(S,16,S,32,y-32,I)!==0))return-1;for(Be(m,0,S,0,y,u,w),T=0;T<32;T++)m[T]=0;return 0}function A(m,S){var y;for(y=0;y<16;y++)m[y]=S[y]|0}function Se(m){var S,y,u=1;for(S=0;S<16;S++)y=m[S]+u+65535,u=Math.floor(y/65536),m[S]=y-u*65536;m[0]+=u-1+37*(u-1)}function te(m,S,y){for(var u,w=~(y-1),T=0;T<16;T++)u=w&(m[T]^S[T]),m[T]^=u,S[T]^=u}function se(m,S){var y,u,w,T=i(),I=i();for(y=0;y<16;y++)I[y]=S[y];for(Se(I),Se(I),Se(I),u=0;u<2;u++){for(T[0]=I[0]-65517,y=1;y<15;y++)T[y]=I[y]-65535-(T[y-1]>>16&1),T[y-1]&=65535;T[15]=I[15]-32767-(T[14]>>16&1),w=T[15]>>16&1,T[14]&=65535,te(I,T,1-w)}for(y=0;y<16;y++)m[2*y]=I[y]&255,m[2*y+1]=I[y]>>8}function ct(m,S){var y=new Uint8Array(32),u=new Uint8Array(32);return se(y,m),se(u,S),_e(y,0,u,0)}function zt(m){var S=new Uint8Array(32);return se(S,m),S[0]&1}function Mt(m,S){var y;for(y=0;y<16;y++)m[y]=S[2*y]+(S[2*y+1]<<8);m[15]&=32767}function ut(m,S,y){for(var u=0;u<16;u++)m[u]=S[u]+y[u]}function je(m,S,y){for(var u=0;u<16;u++)m[u]=S[u]-y[u]}function Ae(m,S,y){var u,w,T=0,I=0,G=0,X=0,we=0,le=0,Ke=0,fe=0,ke=0,Me=0,He=0,J=0,Oe=0,Te=0,Ee=0,ge=0,ie=0,he=0,ye=0,ve=0,ne=0,D=0,N=0,K=0,j=0,$=0,Y=0,Ce=0,Ie=0,We=0,Ue=0,x=y[0],Ge=y[1],Fe=y[2],Ye=y[3],Pe=y[4],Je=y[5],Xe=y[6],gt=y[7],nt=y[8],ft=y[9],mt=y[10],qe=y[11],ue=y[12],Ot=y[13],ot=y[14],Bt=y[15];u=S[0],T+=u*x,I+=u*Ge,G+=u*Fe,X+=u*Ye,we+=u*Pe,le+=u*Je,Ke+=u*Xe,fe+=u*gt,ke+=u*nt,Me+=u*ft,He+=u*mt,J+=u*qe,Oe+=u*ue,Te+=u*Ot,Ee+=u*ot,ge+=u*Bt,u=S[1],I+=u*x,G+=u*Ge,X+=u*Fe,we+=u*Ye,le+=u*Pe,Ke+=u*Je,fe+=u*Xe,ke+=u*gt,Me+=u*nt,He+=u*ft,J+=u*mt,Oe+=u*qe,Te+=u*ue,Ee+=u*Ot,ge+=u*ot,ie+=u*Bt,u=S[2],G+=u*x,X+=u*Ge,we+=u*Fe,le+=u*Ye,Ke+=u*Pe,fe+=u*Je,ke+=u*Xe,Me+=u*gt,He+=u*nt,J+=u*ft,Oe+=u*mt,Te+=u*qe,Ee+=u*ue,ge+=u*Ot,ie+=u*ot,he+=u*Bt,u=S[3],X+=u*x,we+=u*Ge,le+=u*Fe,Ke+=u*Ye,fe+=u*Pe,ke+=u*Je,Me+=u*Xe,He+=u*gt,J+=u*nt,Oe+=u*ft,Te+=u*mt,Ee+=u*qe,ge+=u*ue,ie+=u*Ot,he+=u*ot,ye+=u*Bt,u=S[4],we+=u*x,le+=u*Ge,Ke+=u*Fe,fe+=u*Ye,ke+=u*Pe,Me+=u*Je,He+=u*Xe,J+=u*gt,Oe+=u*nt,Te+=u*ft,Ee+=u*mt,ge+=u*qe,ie+=u*ue,he+=u*Ot,ye+=u*ot,ve+=u*Bt,u=S[5],le+=u*x,Ke+=u*Ge,fe+=u*Fe,ke+=u*Ye,Me+=u*Pe,He+=u*Je,J+=u*Xe,Oe+=u*gt,Te+=u*nt,Ee+=u*ft,ge+=u*mt,ie+=u*qe,he+=u*ue,ye+=u*Ot,ve+=u*ot,ne+=u*Bt,u=S[6],Ke+=u*x,fe+=u*Ge,ke+=u*Fe,Me+=u*Ye,He+=u*Pe,J+=u*Je,Oe+=u*Xe,Te+=u*gt,Ee+=u*nt,ge+=u*ft,ie+=u*mt,he+=u*qe,ye+=u*ue,ve+=u*Ot,ne+=u*ot,D+=u*Bt,u=S[7],fe+=u*x,ke+=u*Ge,Me+=u*Fe,He+=u*Ye,J+=u*Pe,Oe+=u*Je,Te+=u*Xe,Ee+=u*gt,ge+=u*nt,ie+=u*ft,he+=u*mt,ye+=u*qe,ve+=u*ue,ne+=u*Ot,D+=u*ot,N+=u*Bt,u=S[8],ke+=u*x,Me+=u*Ge,He+=u*Fe,J+=u*Ye,Oe+=u*Pe,Te+=u*Je,Ee+=u*Xe,ge+=u*gt,ie+=u*nt,he+=u*ft,ye+=u*mt,ve+=u*qe,ne+=u*ue,D+=u*Ot,N+=u*ot,K+=u*Bt,u=S[9],Me+=u*x,He+=u*Ge,J+=u*Fe,Oe+=u*Ye,Te+=u*Pe,Ee+=u*Je,ge+=u*Xe,ie+=u*gt,he+=u*nt,ye+=u*ft,ve+=u*mt,ne+=u*qe,D+=u*ue,N+=u*Ot,K+=u*ot,j+=u*Bt,u=S[10],He+=u*x,J+=u*Ge,Oe+=u*Fe,Te+=u*Ye,Ee+=u*Pe,ge+=u*Je,ie+=u*Xe,he+=u*gt,ye+=u*nt,ve+=u*ft,ne+=u*mt,D+=u*qe,N+=u*ue,K+=u*Ot,j+=u*ot,$+=u*Bt,u=S[11],J+=u*x,Oe+=u*Ge,Te+=u*Fe,Ee+=u*Ye,ge+=u*Pe,ie+=u*Je,he+=u*Xe,ye+=u*gt,ve+=u*nt,ne+=u*ft,D+=u*mt,N+=u*qe,K+=u*ue,j+=u*Ot,$+=u*ot,Y+=u*Bt,u=S[12],Oe+=u*x,Te+=u*Ge,Ee+=u*Fe,ge+=u*Ye,ie+=u*Pe,he+=u*Je,ye+=u*Xe,ve+=u*gt,ne+=u*nt,D+=u*ft,N+=u*mt,K+=u*qe,j+=u*ue,$+=u*Ot,Y+=u*ot,Ce+=u*Bt,u=S[13],Te+=u*x,Ee+=u*Ge,ge+=u*Fe,ie+=u*Ye,he+=u*Pe,ye+=u*Je,ve+=u*Xe,ne+=u*gt,D+=u*nt,N+=u*ft,K+=u*mt,j+=u*qe,$+=u*ue,Y+=u*Ot,Ce+=u*ot,Ie+=u*Bt,u=S[14],Ee+=u*x,ge+=u*Ge,ie+=u*Fe,he+=u*Ye,ye+=u*Pe,ve+=u*Je,ne+=u*Xe,D+=u*gt,N+=u*nt,K+=u*ft,j+=u*mt,$+=u*qe,Y+=u*ue,Ce+=u*Ot,Ie+=u*ot,We+=u*Bt,u=S[15],ge+=u*x,ie+=u*Ge,he+=u*Fe,ye+=u*Ye,ve+=u*Pe,ne+=u*Je,D+=u*Xe,N+=u*gt,K+=u*nt,j+=u*ft,$+=u*mt,Y+=u*qe,Ce+=u*ue,Ie+=u*Ot,We+=u*ot,Ue+=u*Bt,T+=38*ie,I+=38*he,G+=38*ye,X+=38*ve,we+=38*ne,le+=38*D,Ke+=38*N,fe+=38*K,ke+=38*j,Me+=38*$,He+=38*Y,J+=38*Ce,Oe+=38*Ie,Te+=38*We,Ee+=38*Ue,w=1,u=T+w+65535,w=Math.floor(u/65536),T=u-w*65536,u=I+w+65535,w=Math.floor(u/65536),I=u-w*65536,u=G+w+65535,w=Math.floor(u/65536),G=u-w*65536,u=X+w+65535,w=Math.floor(u/65536),X=u-w*65536,u=we+w+65535,w=Math.floor(u/65536),we=u-w*65536,u=le+w+65535,w=Math.floor(u/65536),le=u-w*65536,u=Ke+w+65535,w=Math.floor(u/65536),Ke=u-w*65536,u=fe+w+65535,w=Math.floor(u/65536),fe=u-w*65536,u=ke+w+65535,w=Math.floor(u/65536),ke=u-w*65536,u=Me+w+65535,w=Math.floor(u/65536),Me=u-w*65536,u=He+w+65535,w=Math.floor(u/65536),He=u-w*65536,u=J+w+65535,w=Math.floor(u/65536),J=u-w*65536,u=Oe+w+65535,w=Math.floor(u/65536),Oe=u-w*65536,u=Te+w+65535,w=Math.floor(u/65536),Te=u-w*65536,u=Ee+w+65535,w=Math.floor(u/65536),Ee=u-w*65536,u=ge+w+65535,w=Math.floor(u/65536),ge=u-w*65536,T+=w-1+37*(w-1),w=1,u=T+w+65535,w=Math.floor(u/65536),T=u-w*65536,u=I+w+65535,w=Math.floor(u/65536),I=u-w*65536,u=G+w+65535,w=Math.floor(u/65536),G=u-w*65536,u=X+w+65535,w=Math.floor(u/65536),X=u-w*65536,u=we+w+65535,w=Math.floor(u/65536),we=u-w*65536,u=le+w+65535,w=Math.floor(u/65536),le=u-w*65536,u=Ke+w+65535,w=Math.floor(u/65536),Ke=u-w*65536,u=fe+w+65535,w=Math.floor(u/65536),fe=u-w*65536,u=ke+w+65535,w=Math.floor(u/65536),ke=u-w*65536,u=Me+w+65535,w=Math.floor(u/65536),Me=u-w*65536,u=He+w+65535,w=Math.floor(u/65536),He=u-w*65536,u=J+w+65535,w=Math.floor(u/65536),J=u-w*65536,u=Oe+w+65535,w=Math.floor(u/65536),Oe=u-w*65536,u=Te+w+65535,w=Math.floor(u/65536),Te=u-w*65536,u=Ee+w+65535,w=Math.floor(u/65536),Ee=u-w*65536,u=ge+w+65535,w=Math.floor(u/65536),ge=u-w*65536,T+=w-1+37*(w-1),m[0]=T,m[1]=I,m[2]=G,m[3]=X,m[4]=we,m[5]=le,m[6]=Ke,m[7]=fe,m[8]=ke,m[9]=Me,m[10]=He,m[11]=J,m[12]=Oe,m[13]=Te,m[14]=Ee,m[15]=ge}function at(m,S){Ae(m,S,S)}function oi(m,S){var y=i(),u;for(u=0;u<16;u++)y[u]=S[u];for(u=253;u>=0;u--)at(y,y),u!==2&&u!==4&&Ae(y,y,S);for(u=0;u<16;u++)m[u]=y[u]}function Ni(m,S){var y=i(),u;for(u=0;u<16;u++)y[u]=S[u];for(u=250;u>=0;u--)at(y,y),u!==1&&Ae(y,y,S);for(u=0;u<16;u++)m[u]=y[u]}function qt(m,S,y){var u=new Uint8Array(32),w=new Float64Array(80),T,I,G=i(),X=i(),we=i(),le=i(),Ke=i(),fe=i();for(I=0;I<31;I++)u[I]=S[I];for(u[31]=S[31]&127|64,u[0]&=248,Mt(w,y),I=0;I<16;I++)X[I]=w[I],le[I]=G[I]=we[I]=0;for(G[0]=le[0]=1,I=254;I>=0;--I)T=u[I>>>3]>>>(I&7)&1,te(G,X,T),te(we,le,T),ut(Ke,G,we),je(G,G,we),ut(we,X,le),je(X,X,le),at(le,Ke),at(fe,G),Ae(G,we,G),Ae(we,X,Ke),ut(Ke,G,we),je(G,G,we),at(X,G),je(we,le,fe),Ae(G,we,v),ut(G,G,le),Ae(we,we,G),Ae(G,le,fe),Ae(le,X,w),at(X,Ke),te(G,X,T),te(we,le,T);for(I=0;I<16;I++)w[I+16]=G[I],w[I+32]=we[I],w[I+48]=X[I],w[I+64]=le[I];var ke=w.subarray(32),Me=w.subarray(16);return oi(ke,ke),Ae(Me,Me,ke),se(m,Me),0}function ai(m,S){return qt(m,S,h)}function fi(m,S){return n(S,32),ai(m,S)}function Gt(m,S,y){var u=new Uint8Array(32);return qt(u,y,S),W(m,a,u,E)}var et=re,_i=oe;function Br(m,S,y,u,w,T){var I=new Uint8Array(32);return Gt(I,w,T),et(m,S,y,u,I)}function Ir(m,S,y,u,w,T){var I=new Uint8Array(32);return Gt(I,w,T),_i(m,S,y,u,I)}var Dr=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function zs(m,S,y,u){for(var w=new Int32Array(16),T=new Int32Array(16),I,G,X,we,le,Ke,fe,ke,Me,He,J,Oe,Te,Ee,ge,ie,he,ye,ve,ne,D,N,K,j,$,Y,Ce=m[0],Ie=m[1],We=m[2],Ue=m[3],x=m[4],Ge=m[5],Fe=m[6],Ye=m[7],Pe=S[0],Je=S[1],Xe=S[2],gt=S[3],nt=S[4],ft=S[5],mt=S[6],qe=S[7],ue=0;u>=128;){for(ve=0;ve<16;ve++)ne=8*ve+ue,w[ve]=y[ne+0]<<24|y[ne+1]<<16|y[ne+2]<<8|y[ne+3],T[ve]=y[ne+4]<<24|y[ne+5]<<16|y[ne+6]<<8|y[ne+7];for(ve=0;ve<80;ve++)if(I=Ce,G=Ie,X=We,we=Ue,le=x,Ke=Ge,fe=Fe,ke=Ye,Me=Pe,He=Je,J=Xe,Oe=gt,Te=nt,Ee=ft,ge=mt,ie=qe,D=Ye,N=qe,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=(x>>>14|nt<<18)^(x>>>18|nt<<14)^(nt>>>9|x<<23),N=(nt>>>14|x<<18)^(nt>>>18|x<<14)^(x>>>9|nt<<23),K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,D=x&Ge^~x&Fe,N=nt&ft^~nt&mt,K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,D=Dr[ve*2],N=Dr[ve*2+1],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,D=w[ve%16],N=T[ve%16],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,he=$&65535|Y<<16,ye=K&65535|j<<16,D=he,N=ye,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=(Ce>>>28|Pe<<4)^(Pe>>>2|Ce<<30)^(Pe>>>7|Ce<<25),N=(Pe>>>28|Ce<<4)^(Ce>>>2|Pe<<30)^(Ce>>>7|Pe<<25),K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,D=Ce&Ie^Ce&We^Ie&We,N=Pe&Je^Pe&Xe^Je&Xe,K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,ke=$&65535|Y<<16,ie=K&65535|j<<16,D=we,N=Oe,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=he,N=ye,K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,we=$&65535|Y<<16,Oe=K&65535|j<<16,Ie=I,We=G,Ue=X,x=we,Ge=le,Fe=Ke,Ye=fe,Ce=ke,Je=Me,Xe=He,gt=J,nt=Oe,ft=Te,mt=Ee,qe=ge,Pe=ie,ve%16===15)for(ne=0;ne<16;ne++)D=w[ne],N=T[ne],K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=w[(ne+9)%16],N=T[(ne+9)%16],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,he=w[(ne+1)%16],ye=T[(ne+1)%16],D=(he>>>1|ye<<31)^(he>>>8|ye<<24)^he>>>7,N=(ye>>>1|he<<31)^(ye>>>8|he<<24)^(ye>>>7|he<<25),K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,he=w[(ne+14)%16],ye=T[(ne+14)%16],D=(he>>>19|ye<<13)^(ye>>>29|he<<3)^he>>>6,N=(ye>>>19|he<<13)^(he>>>29|ye<<3)^(ye>>>6|he<<26),K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,w[ne]=$&65535|Y<<16,T[ne]=K&65535|j<<16;D=Ce,N=Pe,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=m[0],N=S[0],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,m[0]=Ce=$&65535|Y<<16,S[0]=Pe=K&65535|j<<16,D=Ie,N=Je,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=m[1],N=S[1],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,m[1]=Ie=$&65535|Y<<16,S[1]=Je=K&65535|j<<16,D=We,N=Xe,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=m[2],N=S[2],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,m[2]=We=$&65535|Y<<16,S[2]=Xe=K&65535|j<<16,D=Ue,N=gt,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=m[3],N=S[3],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,m[3]=Ue=$&65535|Y<<16,S[3]=gt=K&65535|j<<16,D=x,N=nt,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=m[4],N=S[4],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,m[4]=x=$&65535|Y<<16,S[4]=nt=K&65535|j<<16,D=Ge,N=ft,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=m[5],N=S[5],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,m[5]=Ge=$&65535|Y<<16,S[5]=ft=K&65535|j<<16,D=Fe,N=mt,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=m[6],N=S[6],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,m[6]=Fe=$&65535|Y<<16,S[6]=mt=K&65535|j<<16,D=Ye,N=qe,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=m[7],N=S[7],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,m[7]=Ye=$&65535|Y<<16,S[7]=qe=K&65535|j<<16,ue+=128,u-=128}return u}function gi(m,S,y){var u=new Int32Array(8),w=new Int32Array(8),T=new Uint8Array(256),I,G=y;for(u[0]=1779033703,u[1]=3144134277,u[2]=1013904242,u[3]=2773480762,u[4]=1359893119,u[5]=2600822924,u[6]=528734635,u[7]=1541459225,w[0]=4089235720,w[1]=2227873595,w[2]=4271175723,w[3]=1595750129,w[4]=2917565137,w[5]=725511199,w[6]=4215389547,w[7]=327033209,zs(u,w,S,y),y%=128,I=0;I<y;I++)T[I]=S[G-y+I];for(T[y]=128,y=256-128*(y<112?1:0),T[y-9]=0,P(T,y-8,G/536870912|0,G<<3),zs(u,w,T,y),I=0;I<8;I++)P(m,8*I,u[I],w[I]);return 0}function vi(m,S){var y=i(),u=i(),w=i(),T=i(),I=i(),G=i(),X=i(),we=i(),le=i();je(y,m[1],m[0]),je(le,S[1],S[0]),Ae(y,y,le),ut(u,m[0],m[1]),ut(le,S[0],S[1]),Ae(u,u,le),Ae(w,m[3],S[3]),Ae(w,w,R),Ae(T,m[2],S[2]),ut(T,T,T),je(I,u,y),je(G,T,w),ut(X,T,w),ut(we,u,y),Ae(m[0],I,G),Ae(m[1],we,X),Ae(m[2],X,G),Ae(m[3],I,we)}function ms(m,S,y){var u;for(u=0;u<4;u++)te(m[u],S[u],y)}function Hi(m,S){var y=i(),u=i(),w=i();oi(w,S[2]),Ae(y,S[0],w),Ae(u,S[1],w),se(m,u),m[31]^=zt(y)<<7}function ss(m,S,y){var u,w;for(A(m[0],d),A(m[1],g),A(m[2],g),A(m[3],d),w=255;w>=0;--w)u=y[w/8|0]>>(w&7)&1,ms(m,S,u),vi(S,m),vi(m,m),ms(m,S,u)}function it(m,S){var y=[i(),i(),i(),i()];A(y[0],k),A(y[1],B),A(y[2],g),Ae(y[3],k,B),ss(m,y,S)}function vs(m,S,y){var u=new Uint8Array(64),w=[i(),i(),i(),i()],T;for(y||n(S,32),gi(u,S,32),u[0]&=248,u[31]&=127,u[31]|=64,it(w,u),Hi(m,w),T=0;T<32;T++)S[T+32]=m[T];return 0}var rs=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function Ui(m,S){var y,u,w,T;for(u=63;u>=32;--u){for(y=0,w=u-32,T=u-12;w<T;++w)S[w]+=y-16*S[u]*rs[w-(u-32)],y=Math.floor((S[w]+128)/256),S[w]-=y*256;S[w]+=y,S[u]=0}for(y=0,w=0;w<32;w++)S[w]+=y-(S[31]>>4)*rs[w],y=S[w]>>8,S[w]&=255;for(w=0;w<32;w++)S[w]-=y*rs[w];for(u=0;u<32;u++)S[u+1]+=S[u]>>8,m[u]=S[u]&255}function ys(m){var S=new Float64Array(64),y;for(y=0;y<64;y++)S[y]=m[y];for(y=0;y<64;y++)m[y]=0;Ui(m,S)}function qs(m,S,y,u){var w=new Uint8Array(64),T=new Uint8Array(64),I=new Uint8Array(64),G,X,we=new Float64Array(64),le=[i(),i(),i(),i()];gi(w,u,32),w[0]&=248,w[31]&=127,w[31]|=64;var Ke=y+64;for(G=0;G<y;G++)m[64+G]=S[G];for(G=0;G<32;G++)m[32+G]=w[32+G];for(gi(I,m.subarray(32),y+32),ys(I),it(le,I),Hi(m,le),G=32;G<64;G++)m[G]=u[G];for(gi(T,m,y+64),ys(T),G=0;G<64;G++)we[G]=0;for(G=0;G<32;G++)we[G]=I[G];for(G=0;G<32;G++)for(X=0;X<32;X++)we[G+X]+=T[G]*w[X];return Ui(m.subarray(32),we),Ke}function Vt(m,S){var y=i(),u=i(),w=i(),T=i(),I=i(),G=i(),X=i();return A(m[2],g),Mt(m[1],S),at(w,m[1]),Ae(T,w,p),je(w,w,m[2]),ut(T,m[2],T),at(I,T),at(G,I),Ae(X,G,I),Ae(y,X,w),Ae(y,y,T),Ni(y,y),Ae(y,y,w),Ae(y,y,T),Ae(y,y,T),Ae(m[0],y,T),at(u,m[0]),Ae(u,u,T),ct(u,w)&&Ae(m[0],m[0],L),at(u,m[0]),Ae(u,u,T),ct(u,w)?-1:(zt(m[0])===S[31]>>7&&je(m[0],d,m[0]),Ae(m[3],m[0],m[1]),0)}function bt(m,S,y,u){var w,T=new Uint8Array(32),I=new Uint8Array(64),G=[i(),i(),i(),i()],X=[i(),i(),i(),i()];if(y<64||Vt(X,u))return-1;for(w=0;w<y;w++)m[w]=S[w];for(w=0;w<32;w++)m[w+32]=u[w];if(gi(I,m,y),ys(I),ss(G,X,I),it(X,S.subarray(32)),vi(G,X),Hi(T,G),y-=64,_e(S,0,T,0)){for(w=0;w<y;w++)m[w]=0;return-1}for(w=0;w<y;w++)m[w]=S[w+64];return y}var Kt=32,Wi=24,Fi=32,Oi=16,zi=32,qi=32,Ti=32,Gi=32,Ss=32,ns=Wi,Nr=Fi,bs=Oi,dt=64,yi=32,ji=64,ws=32,Gs=64;t.lowlevel={crypto_core_hsalsa20:W,crypto_stream_xor:Be,crypto_stream:ze,crypto_stream_salsa20_xor:ae,crypto_stream_salsa20:be,crypto_onetimeauth:ce,crypto_onetimeauth_verify:f,crypto_verify_16:Z,crypto_verify_32:_e,crypto_secretbox:re,crypto_secretbox_open:oe,crypto_scalarmult:qt,crypto_scalarmult_base:ai,crypto_box_beforenm:Gt,crypto_box_afternm:et,crypto_box:Br,crypto_box_open:Ir,crypto_box_keypair:fi,crypto_hash:gi,crypto_sign:qs,crypto_sign_keypair:vs,crypto_sign_open:bt,crypto_secretbox_KEYBYTES:Kt,crypto_secretbox_NONCEBYTES:Wi,crypto_secretbox_ZEROBYTES:Fi,crypto_secretbox_BOXZEROBYTES:Oi,crypto_scalarmult_BYTES:zi,crypto_scalarmult_SCALARBYTES:qi,crypto_box_PUBLICKEYBYTES:Ti,crypto_box_SECRETKEYBYTES:Gi,crypto_box_BEFORENMBYTES:Ss,crypto_box_NONCEBYTES:ns,crypto_box_ZEROBYTES:Nr,crypto_box_BOXZEROBYTES:bs,crypto_sign_BYTES:dt,crypto_sign_PUBLICKEYBYTES:yi,crypto_sign_SECRETKEYBYTES:ji,crypto_sign_SEEDBYTES:ws,crypto_hash_BYTES:Gs,gf:i,D:p,L:rs,pack25519:se,unpack25519:Mt,M:Ae,A:ut,S:at,Z:je,pow2523:Ni,add:vi,set25519:A,modL:Ui,scalarmult:ss,scalarbase:it};function Qt(m,S){if(m.length!==Kt)throw new Error("bad key size");if(S.length!==Wi)throw new Error("bad nonce size")}function bn(m,S){if(m.length!==Ti)throw new Error("bad public key size");if(S.length!==Gi)throw new Error("bad secret key size")}function Yt(){for(var m=0;m<arguments.length;m++)if(!(arguments[m]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function js(m){for(var S=0;S<m.length;S++)m[S]=0}t.randomBytes=function(m){var S=new Uint8Array(m);return n(S,m),S},t.secretbox=function(m,S,y){Yt(m,S,y),Qt(y,S);for(var u=new Uint8Array(Fi+m.length),w=new Uint8Array(u.length),T=0;T<m.length;T++)u[T+Fi]=m[T];return re(w,u,u.length,S,y),w.subarray(Oi)},t.secretbox.open=function(m,S,y){Yt(m,S,y),Qt(y,S);for(var u=new Uint8Array(Oi+m.length),w=new Uint8Array(u.length),T=0;T<m.length;T++)u[T+Oi]=m[T];return u.length<32||oe(w,u,u.length,S,y)!==0?null:w.subarray(Fi)},t.secretbox.keyLength=Kt,t.secretbox.nonceLength=Wi,t.secretbox.overheadLength=Oi,t.scalarMult=function(m,S){if(Yt(m,S),m.length!==qi)throw new Error("bad n size");if(S.length!==zi)throw new Error("bad p size");var y=new Uint8Array(zi);return qt(y,m,S),y},t.scalarMult.base=function(m){if(Yt(m),m.length!==qi)throw new Error("bad n size");var S=new Uint8Array(zi);return ai(S,m),S},t.scalarMult.scalarLength=qi,t.scalarMult.groupElementLength=zi,t.box=function(m,S,y,u){var w=t.box.before(y,u);return t.secretbox(m,S,w)},t.box.before=function(m,S){Yt(m,S),bn(m,S);var y=new Uint8Array(Ss);return Gt(y,m,S),y},t.box.after=t.secretbox,t.box.open=function(m,S,y,u){var w=t.box.before(y,u);return t.secretbox.open(m,S,w)},t.box.open.after=t.secretbox.open,t.box.keyPair=function(){var m=new Uint8Array(Ti),S=new Uint8Array(Gi);return fi(m,S),{publicKey:m,secretKey:S}},t.box.keyPair.fromSecretKey=function(m){if(Yt(m),m.length!==Gi)throw new Error("bad secret key size");var S=new Uint8Array(Ti);return ai(S,m),{publicKey:S,secretKey:new Uint8Array(m)}},t.box.publicKeyLength=Ti,t.box.secretKeyLength=Gi,t.box.sharedKeyLength=Ss,t.box.nonceLength=ns,t.box.overheadLength=t.secretbox.overheadLength,t.sign=function(m,S){if(Yt(m,S),S.length!==ji)throw new Error("bad secret key size");var y=new Uint8Array(dt+m.length);return qs(y,m,m.length,S),y},t.sign.open=function(m,S){if(Yt(m,S),S.length!==yi)throw new Error("bad public key size");var y=new Uint8Array(m.length),u=bt(y,m,m.length,S);if(u<0)return null;for(var w=new Uint8Array(u),T=0;T<w.length;T++)w[T]=y[T];return w},t.sign.detached=function(m,S){for(var y=t.sign(m,S),u=new Uint8Array(dt),w=0;w<u.length;w++)u[w]=y[w];return u},t.sign.detached.verify=function(m,S,y){if(Yt(m,S,y),S.length!==dt)throw new Error("bad signature size");if(y.length!==yi)throw new Error("bad public key size");var u=new Uint8Array(dt+m.length),w=new Uint8Array(dt+m.length),T;for(T=0;T<dt;T++)u[T]=S[T];for(T=0;T<m.length;T++)u[T+dt]=m[T];return bt(w,u,u.length,y)>=0},t.sign.keyPair=function(){var m=new Uint8Array(yi),S=new Uint8Array(ji);return vs(m,S),{publicKey:m,secretKey:S}},t.sign.keyPair.fromSecretKey=function(m){if(Yt(m),m.length!==ji)throw new Error("bad secret key size");for(var S=new Uint8Array(yi),y=0;y<S.length;y++)S[y]=m[32+y];return{publicKey:S,secretKey:new Uint8Array(m)}},t.sign.keyPair.fromSeed=function(m){if(Yt(m),m.length!==ws)throw new Error("bad seed size");for(var S=new Uint8Array(yi),y=new Uint8Array(ji),u=0;u<32;u++)y[u]=m[u];return vs(S,y,!0),{publicKey:S,secretKey:y}},t.sign.publicKeyLength=yi,t.sign.secretKeyLength=ji,t.sign.seedLength=ws,t.sign.signatureLength=dt,t.hash=function(m){Yt(m);var S=new Uint8Array(Gs);return gi(S,m,m.length),S},t.hash.hashLength=Gs,t.verify=function(m,S){return Yt(m,S),m.length===0||S.length===0||m.length!==S.length?!1:U(m,0,S,0,m.length)===0},t.setPRNG=function(m){n=m},(function(){var m=typeof self<"u"?self.crypto||self.msCrypto:null;if(m&&m.getRandomValues){var S=65536;t.setPRNG(function(y,u){var w,T=new Uint8Array(u);for(w=0;w<u;w+=S)m.getRandomValues(T.subarray(w,w+Math.min(u-w,S)));for(w=0;w<u;w++)y[w]=T[w];js(T)})}else typeof uf<"u"&&(m=_f,m&&m.randomBytes&&t.setPRNG(function(y,u){var w,T=m.randomBytes(u);for(w=0;w<u;w++)y[w]=T[w];js(T)}))})()})(e.exports?e.exports:self.nacl=self.nacl||{})})($n)),$n.exports}var pf=gf();const ho=sf(pf),Hs=24,mf=16;function vf(e,t){const i=ho.randomBytes(Hs),n=ho.secretbox(e,i,t),a=new Uint8Array(Hs+n.length);return a.set(i),a.set(n,Hs),a}function yf(e,t){if(e.length<Hs+mf)throw new Error("Sealed data too short");const i=e.slice(0,Hs),n=e.slice(Hs),a=ho.secretbox.open(n,i,t);if(!a)throw new Error("Decryption failed - data may be tampered with");return a}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Sf(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function co(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function pn(e,...t){if(!Sf(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function da(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");co(e.outputLen),co(e.blockLen)}function an(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function bf(e,t){pn(e);const i=t.outputLen;if(e.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}function br(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Vn(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function wi(e,t){return e<<32-t|e>>>t}function wf(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function wr(e){return typeof e=="string"&&(e=wf(e)),pn(e),e}class zh{}function Cf(e){const t=n=>e().update(wr(n)).digest(),i=e();return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=()=>e(),t}function xf(e,t,i,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,i,n);const a=BigInt(32),h=BigInt(4294967295),d=Number(i>>a&h),g=Number(i&h),v=n?4:0,p=n?0:4;e.setUint32(t+v,d,n),e.setUint32(t+p,g,n)}function kf(e,t,i){return e&t^~e&i}function Ef(e,t,i){return e&t^e&i^t&i}class Rf extends zh{constructor(t,i,n,a){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=i,this.padOffset=n,this.isLE=a,this.buffer=new Uint8Array(t),this.view=Vn(this.buffer)}update(t){an(this),t=wr(t),pn(t);const{view:i,buffer:n,blockLen:a}=this,h=t.length;for(let d=0;d<h;){const g=Math.min(a-this.pos,h-d);if(g===a){const v=Vn(t);for(;a<=h-d;d+=a)this.process(v,d);continue}n.set(t.subarray(d,d+g),this.pos),this.pos+=g,d+=g,this.pos===a&&(this.process(i,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){an(this),bf(t,this),this.finished=!0;const{buffer:i,view:n,blockLen:a,isLE:h}=this;let{pos:d}=this;i[d++]=128,br(this.buffer.subarray(d)),this.padOffset>a-d&&(this.process(n,0),d=0);for(let k=d;k<a;k++)i[k]=0;xf(n,a-8,BigInt(this.length*8),h),this.process(n,0);const g=Vn(t),v=this.outputLen;if(v%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const p=v/4,R=this.get();if(p>R.length)throw new Error("_sha2: outputLen bigger than state");for(let k=0;k<p;k++)g.setUint32(4*k,R[k],h)}digest(){const{buffer:t,outputLen:i}=this;this.digestInto(t);const n=t.slice(0,i);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:i,buffer:n,length:a,finished:h,destroyed:d,pos:g}=this;return t.destroyed=d,t.finished=h,t.length=a,t.pos=g,a%i&&t.buffer.set(n),t}clone(){return this._cloneInto()}}const Yi=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Af=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ji=new Uint32Array(64);class Mf extends Rf{constructor(t=32){super(64,t,8,!1),this.A=Yi[0]|0,this.B=Yi[1]|0,this.C=Yi[2]|0,this.D=Yi[3]|0,this.E=Yi[4]|0,this.F=Yi[5]|0,this.G=Yi[6]|0,this.H=Yi[7]|0}get(){const{A:t,B:i,C:n,D:a,E:h,F:d,G:g,H:v}=this;return[t,i,n,a,h,d,g,v]}set(t,i,n,a,h,d,g,v){this.A=t|0,this.B=i|0,this.C=n|0,this.D=a|0,this.E=h|0,this.F=d|0,this.G=g|0,this.H=v|0}process(t,i){for(let k=0;k<16;k++,i+=4)Ji[k]=t.getUint32(i,!1);for(let k=16;k<64;k++){const B=Ji[k-15],L=Ji[k-2],P=wi(B,7)^wi(B,18)^B>>>3,U=wi(L,17)^wi(L,19)^L>>>10;Ji[k]=U+Ji[k-7]+P+Ji[k-16]|0}let{A:n,B:a,C:h,D:d,E:g,F:v,G:p,H:R}=this;for(let k=0;k<64;k++){const B=wi(g,6)^wi(g,11)^wi(g,25),L=R+B+kf(g,v,p)+Af[k]+Ji[k]|0,U=(wi(n,2)^wi(n,13)^wi(n,22))+Ef(n,a,h)|0;R=p,p=v,v=g,g=d+L|0,d=h,h=a,a=n,n=L+U|0}n=n+this.A|0,a=a+this.B|0,h=h+this.C|0,d=d+this.D|0,g=g+this.E|0,v=v+this.F|0,p=p+this.G|0,R=R+this.H|0,this.set(n,a,h,d,g,v,p,R)}roundClean(){br(Ji)}destroy(){this.set(0,0,0,0,0,0,0,0),br(this.buffer)}}const Of=Cf(()=>new Mf),Mr=Of;class qh extends zh{constructor(t,i){super(),this.finished=!1,this.destroyed=!1,da(t);const n=wr(i);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const a=this.blockLen,h=new Uint8Array(a);h.set(n.length>a?t.create().update(n).digest():n);for(let d=0;d<h.length;d++)h[d]^=54;this.iHash.update(h),this.oHash=t.create();for(let d=0;d<h.length;d++)h[d]^=106;this.oHash.update(h),br(h)}update(t){return an(this),this.iHash.update(t),this}digestInto(t){an(this),pn(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:i,iHash:n,finished:a,destroyed:h,blockLen:d,outputLen:g}=this;return t=t,t.finished=a,t.destroyed=h,t.blockLen=d,t.outputLen=g,t.oHash=i._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const fa=(e,t,i)=>new qh(e,t).update(i).digest();fa.create=(e,t)=>new qh(e,t);function Tf(e,t,i){return da(e),i===void 0&&(i=new Uint8Array(e.outputLen)),fa(e,wr(i),wr(t))}const Kn=Uint8Array.from([0]),Pf=Uint8Array.of();function Lf(e,t,i,n=32){da(e),co(n);const a=e.outputLen;if(n>255*a)throw new Error("Length should be <= 255*HashLen");const h=Math.ceil(n/a),d=new Uint8Array(h*a),g=fa.create(e,t),v=g._cloneInto(),p=new Uint8Array(g.outputLen);for(let R=0;R<h;R++)Kn[0]=R+1,v.update(R===0?Pf:p).update(i).update(Kn).digestInto(p),d.set(p,a*R),g._cloneInto(v);return g.destroy(),v.destroy(),br(p,Kn),d.slice(0,n)}const Bf=(e,t,i,n,a)=>Lf(e,Tf(e,t,i),n,a);function If(e){const t=Mr(new TextEncoder().encode(`airloom-session:${e}`));return Array.from(t.slice(0,16),i=>i.toString(16).padStart(2,"0")).join("")}function _a(e,t){const i=new TextEncoder().encode("airloom-v1");return Bf(Mr,e,i,"airloom-encryption",32)}function Df(e){return e.replace(/[-\s]/g,"").toUpperCase()}class Nf{constructor(t,i,n){Ze(this,"_ended",!1);this.id=t,this.sendFn=i,this.meta=n}write(t){if(this._ended)throw new Error("Cannot write after stream has ended");this.sendFn({type:"stream_chunk",id:this.id,data:t})}end(){this._ended||(this._ended=!0,this.sendFn({type:"stream_end",id:this.id}))}get ended(){return this._ended}}class Hf extends Fh.EventEmitter{constructor(i,n){super();Ze(this,"id");Ze(this,"meta");Ze(this,"_ended",!1);this.id=i,this.meta=n}_pushChunk(i){this._ended||this.emit("data",i)}_end(){this._ended||(this._ended=!0,this.emit("end"))}get ended(){return this._ended}}class Uf extends Fh.EventEmitter{constructor(i){super();Ze(this,"adapter");Ze(this,"encryptionKey");Ze(this,"role");Ze(this,"streams",new Map);Ze(this,"_ready",!1);Ze(this,"msgCounter",0);this.adapter=i.adapter,this.encryptionKey=i.encryptionKey??null,this.role=i.role,this.setupHandlers()}setupHandlers(){this.adapter.onMessage(i=>{this.handlePayload(i)}),this.adapter.onPeerJoined(()=>{this.encryptionKey&&(this._ready=!0,this.emit("ready"))}),this.adapter.onPeerLeft(()=>{this._ready=!1,this.emit("peer_left")}),this.adapter.onError(i=>this.emit("error",i)),this.adapter.onDisconnect(()=>this.emit("disconnect"))}handlePayload(i){try{if(!this.encryptionKey){this.emit("error",new Error("Received data but no encryption key"));return}const n=af(i),a=yf(n,this.encryptionKey),h=hf(a);this.handleMessage(h)}catch(n){this.emit("error",n)}}handleMessage(i){switch(i.type){case"message":this.emit("message",i.data);break;case"stream_start":{const n=new Hf(i.id,i.meta);this.streams.set(i.id,n),this.emit("stream",n);break}case"stream_chunk":{const n=this.streams.get(i.id);n&&n._pushChunk(i.data);break}case"stream_end":{const n=this.streams.get(i.id);n&&(n._end(),this.streams.delete(i.id));break}}}sendRaw(i){if(!this.encryptionKey)throw new Error("No encryption key established");const n=lf(i),a=vf(n,this.encryptionKey);this.adapter.send(of(a))}send(i){const n=`msg-${++this.msgCounter}`;this.sendRaw({type:"message",id:n,data:i})}createStream(i){const n=`stream-${++this.msgCounter}`;return this.sendRaw({type:"stream_start",id:n,meta:i}),new Nf(n,a=>this.sendRaw(a),i)}async connect(i){await this.adapter.connect(i,this.role)}get ready(){return this._ready}waitForReady(i=3e4){return this._ready?Promise.resolve():new Promise((n,a)=>{const h=()=>{clearTimeout(p),this.removeListener("ready",d),this.removeListener("error",g),this.removeListener("disconnect",v)},d=()=>{h(),n()},g=R=>{h(),a(R)},v=()=>{h(),a(new Error("Disconnected before ready"))},p=setTimeout(()=>{h(),a(new Error("Timed out waiting for peer"))},i);this.once("ready",d),this.once("error",g),this.once("disconnect",v)})}close(){for(const i of this.streams.values())i._end();this.streams.clear(),this.adapter.close(),this.removeAllListeners()}}class Wf{constructor(t){Ze(this,"ws",null);Ze(this,"url");Ze(this,"_connected",!1);Ze(this,"messageHandlers",[]);Ze(this,"peerJoinedHandlers",[]);Ze(this,"peerLeftHandlers",[]);Ze(this,"errorHandlers",[]);Ze(this,"disconnectHandlers",[]);Ze(this,"reconnectAttempts",0);Ze(this,"maxReconnectAttempts",5);Ze(this,"reconnectTimer",null);Ze(this,"shouldReconnect",!1);Ze(this,"sessionToken",null);Ze(this,"role",null);this.url=t}get connected(){return this._connected}async connect(t,i){return this.sessionToken=t,this.role=i,this.doConnect()}async doConnect(){const t=await this.createWebSocket(this.url);return new Promise((i,n)=>{t.onopen=()=>{this._connected=!0,this.shouldReconnect=!0,this.reconnectAttempts=0;const a=this.role==="host"?{type:"create",sessionToken:this.sessionToken}:{type:"join",sessionToken:this.sessionToken};t.send(JSON.stringify(a)),i()},t.onmessage=a=>{const h=a.data,d=typeof h=="string"?h:typeof Buffer<"u"&&Buffer.isBuffer(h)?h.toString("utf-8"):new TextDecoder().decode(h);try{const g=JSON.parse(d);switch(g.type){case"created":case"joined":break;case"peer_joined":this.peerJoinedHandlers.forEach(v=>v());break;case"peer_left":this.peerLeftHandlers.forEach(v=>v());break;case"forward":this.messageHandlers.forEach(v=>v(g.payload));break;case"error":this.errorHandlers.forEach(v=>v(new Error(g.message)));break}}catch(g){this.errorHandlers.forEach(v=>v(g instanceof Error?g:new Error(String(g))))}},t.onclose=()=>{const a=this._connected;this._connected=!1,a&&this.disconnectHandlers.forEach(h=>h()),this.shouldReconnect&&!this.reconnectTimer&&this.attemptReconnect()},t.onerror=a=>{const h=a instanceof Error?a:new Error("WebSocket error");this.errorHandlers.forEach(d=>d(h)),this._connected||(this.shouldReconnect=!1,n(h))},this.ws=t})}async createWebSocket(t){if(typeof globalThis.WebSocket<"u")return new globalThis.WebSocket(t);try{const{default:i}=await Wh(async()=>{const{default:n}=await import("./browser-B9RMX6OC.js").then(a=>a.b);return{default:n}},[],import.meta.url);return new i(t)}catch{throw new Error('No WebSocket implementation available. Install the "ws" package for Node.js.')}}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts||!this.sessionToken||!this.role)return;this.reconnectAttempts++;const t=Math.min(1e3*Math.pow(2,this.reconnectAttempts-1),3e4);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.doConnect().catch(()=>{})},t)}send(t){!this.ws||!this._connected||this.ws.send(JSON.stringify({type:"forward",payload:t}))}onMessage(t){this.messageHandlers.push(t)}onPeerJoined(t){this.peerJoinedHandlers.push(t)}onPeerLeft(t){this.peerLeftHandlers.push(t)}onError(t){this.errorHandlers.push(t)}onDisconnect(t){this.disconnectHandlers.push(t)}close(){var t;this.shouldReconnect=!1,this.maxReconnectAttempts=0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),(t=this.ws)==null||t.close(),this.ws=null,this._connected=!1}}var Zr={exports:{}};/*@license Copyright 2015-2022 Ably Real-time Ltd (ably.com)
1
+ var Zd=Object.defineProperty;var Qd=(e,t,i)=>t in e?Zd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;var Qe=(e,t,i)=>Qd(e,typeof t!="symbol"?t+"":t,i);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const h of a)if(h.type==="childList")for(const d of h.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&n(d)}).observe(document,{childList:!0,subtree:!0});function i(a){const h={};return a.integrity&&(h.integrity=a.integrity),a.referrerPolicy&&(h.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?h.credentials="include":a.crossOrigin==="anonymous"?h.credentials="omit":h.credentials="same-origin",h}function n(a){if(a.ep)return;a.ep=!0;const h=i(a);fetch(a.href,h)}})();const ef="modulepreload",tf=function(e,t){return new URL(e,t).href},Bl={},Wh=function(t,i,n){let a=Promise.resolve();if(i&&i.length>0){let d=function(R){return Promise.all(R.map(k=>Promise.resolve(k).then(B=>({status:"fulfilled",value:B}),B=>({status:"rejected",reason:B}))))};const g=document.getElementsByTagName("link"),v=document.querySelector("meta[property=csp-nonce]"),m=(v==null?void 0:v.nonce)||(v==null?void 0:v.getAttribute("nonce"));a=d(i.map(R=>{if(R=tf(R,n),R in Bl)return;Bl[R]=!0;const k=R.endsWith(".css"),B=k?'[rel="stylesheet"]':"";if(!!n)for(let U=g.length-1;U>=0;U--){const Z=g[U];if(Z.href===R&&(!k||Z.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${R}"]${B}`))return;const P=document.createElement("link");if(P.rel=k?"stylesheet":ef,k||(P.as="script"),P.crossOrigin="",P.href=R,m&&P.setAttribute("nonce",m),document.head.appendChild(P),k)return new Promise((U,Z)=>{P.addEventListener("load",U),P.addEventListener("error",()=>Z(new Error(`Unable to preload CSS for ${R}`)))})}))}function h(d){const g=new Event("vite:preloadError",{cancelable:!0});if(g.payload=d,window.dispatchEvent(g),!g.defaultPrevented)throw d}return a.then(d=>{for(const g of d||[])g.status==="rejected"&&h(g.reason);return t().catch(h)})};var Ki=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function sf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function rf(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var i=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};i.prototype=t.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(i,n,a.get?a:{enumerable:!0,get:function(){return e[n]}})}),i}var jr={exports:{}},Il;function nf(){if(Il)return jr.exports;Il=1;var e=typeof Reflect=="object"?Reflect:null,t=e&&typeof e.apply=="function"?e.apply:function(W,E,ae){return Function.prototype.apply.call(W,E,ae)},i;e&&typeof e.ownKeys=="function"?i=e.ownKeys:Object.getOwnPropertySymbols?i=function(W){return Object.getOwnPropertyNames(W).concat(Object.getOwnPropertySymbols(W))}:i=function(W){return Object.getOwnPropertyNames(W)};function n(H){console&&console.warn&&console.warn(H)}var a=Number.isNaN||function(W){return W!==W};function h(){h.init.call(this)}jr.exports=h,jr.exports.once=_e,h.EventEmitter=h,h.prototype._events=void 0,h.prototype._eventsCount=0,h.prototype._maxListeners=void 0;var d=10;function g(H){if(typeof H!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof H)}Object.defineProperty(h,"defaultMaxListeners",{enumerable:!0,get:function(){return d},set:function(H){if(typeof H!="number"||H<0||a(H))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+H+".");d=H}}),h.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},h.prototype.setMaxListeners=function(W){if(typeof W!="number"||W<0||a(W))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+W+".");return this._maxListeners=W,this};function v(H){return H._maxListeners===void 0?h.defaultMaxListeners:H._maxListeners}h.prototype.getMaxListeners=function(){return v(this)},h.prototype.emit=function(W){for(var E=[],ae=1;ae<arguments.length;ae++)E.push(arguments[ae]);var be=W==="error",ze=this._events;if(ze!==void 0)be=be&&ze.error===void 0;else if(!be)return!1;if(be){var Be;if(E.length>0&&(Be=E[0]),Be instanceof Error)throw Be;var xe=new Error("Unhandled error."+(Be?" ("+Be.message+")":""));throw xe.context=Be,xe}var ce=ze[W];if(ce===void 0)return!1;if(typeof ce=="function")t(ce,this,E);else for(var f=ce.length,re=P(ce,f),ae=0;ae<f;++ae)t(re[ae],this,E);return!0};function m(H,W,E,ae){var be,ze,Be;if(g(E),ze=H._events,ze===void 0?(ze=H._events=Object.create(null),H._eventsCount=0):(ze.newListener!==void 0&&(H.emit("newListener",W,E.listener?E.listener:E),ze=H._events),Be=ze[W]),Be===void 0)Be=ze[W]=E,++H._eventsCount;else if(typeof Be=="function"?Be=ze[W]=ae?[E,Be]:[Be,E]:ae?Be.unshift(E):Be.push(E),be=v(H),be>0&&Be.length>be&&!Be.warned){Be.warned=!0;var xe=new Error("Possible EventEmitter memory leak detected. "+Be.length+" "+String(W)+" listeners added. Use emitter.setMaxListeners() to increase limit");xe.name="MaxListenersExceededWarning",xe.emitter=H,xe.type=W,xe.count=Be.length,n(xe)}return H}h.prototype.addListener=function(W,E){return m(this,W,E,!1)},h.prototype.on=h.prototype.addListener,h.prototype.prependListener=function(W,E){return m(this,W,E,!0)};function R(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function k(H,W,E){var ae={fired:!1,wrapFn:void 0,target:H,type:W,listener:E},be=R.bind(ae);return be.listener=E,ae.wrapFn=be,be}h.prototype.once=function(W,E){return g(E),this.on(W,k(this,W,E)),this},h.prototype.prependOnceListener=function(W,E){return g(E),this.prependListener(W,k(this,W,E)),this},h.prototype.removeListener=function(W,E){var ae,be,ze,Be,xe;if(g(E),be=this._events,be===void 0)return this;if(ae=be[W],ae===void 0)return this;if(ae===E||ae.listener===E)--this._eventsCount===0?this._events=Object.create(null):(delete be[W],be.removeListener&&this.emit("removeListener",W,ae.listener||E));else if(typeof ae!="function"){for(ze=-1,Be=ae.length-1;Be>=0;Be--)if(ae[Be]===E||ae[Be].listener===E){xe=ae[Be].listener,ze=Be;break}if(ze<0)return this;ze===0?ae.shift():U(ae,ze),ae.length===1&&(be[W]=ae[0]),be.removeListener!==void 0&&this.emit("removeListener",W,xe||E)}return this},h.prototype.off=h.prototype.removeListener,h.prototype.removeAllListeners=function(W){var E,ae,be;if(ae=this._events,ae===void 0)return this;if(ae.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):ae[W]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete ae[W]),this;if(arguments.length===0){var ze=Object.keys(ae),Be;for(be=0;be<ze.length;++be)Be=ze[be],Be!=="removeListener"&&this.removeAllListeners(Be);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(E=ae[W],typeof E=="function")this.removeListener(W,E);else if(E!==void 0)for(be=E.length-1;be>=0;be--)this.removeListener(W,E[be]);return this};function B(H,W,E){var ae=H._events;if(ae===void 0)return[];var be=ae[W];return be===void 0?[]:typeof be=="function"?E?[be.listener||be]:[be]:E?Z(be):P(be,be.length)}h.prototype.listeners=function(W){return B(this,W,!0)},h.prototype.rawListeners=function(W){return B(this,W,!1)},h.listenerCount=function(H,W){return typeof H.listenerCount=="function"?H.listenerCount(W):L.call(H,W)},h.prototype.listenerCount=L;function L(H){var W=this._events;if(W!==void 0){var E=W[H];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}h.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]};function P(H,W){for(var E=new Array(W),ae=0;ae<W;++ae)E[ae]=H[ae];return E}function U(H,W){for(;W+1<H.length;W++)H[W]=H[W+1];H.pop()}function Z(H){for(var W=new Array(H.length),E=0;E<W.length;++E)W[E]=H[E].listener||H[E];return W}function _e(H,W){return new Promise(function(E,ae){function be(Be){H.removeListener(W,ze),ae(Be)}function ze(){typeof H.removeListener=="function"&&H.removeListener("error",be),E([].slice.call(arguments))}Ne(H,W,ze,{once:!0}),W!=="error"&&rt(H,be,{once:!0})})}function rt(H,W,E){typeof H.on=="function"&&Ne(H,"error",W,E)}function Ne(H,W,E,ae){if(typeof H.on=="function")ae.once?H.once(W,E):H.on(W,E);else if(typeof H.addEventListener=="function")H.addEventListener(W,function be(ze){ae.once&&H.removeEventListener(W,be),E(ze)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof H)}return jr.exports}var Fh=nf();function of(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(const i of e)t+=String.fromCharCode(i);return btoa(t)}function af(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));const t=atob(e),i=new Uint8Array(t.length);for(let n=0;n<t.length;n++)i[n]=t.charCodeAt(n);return i}function lf(e){return new TextEncoder().encode(JSON.stringify(e))}function hf(e){const t=JSON.parse(new TextDecoder().decode(e));if(!t||typeof t!="object"||typeof t.type!="string"||typeof t.id!="string")throw new Error("Invalid channel message: missing type or id field");return t}function cf(e){const t=JSON.parse(e);if(!t||typeof t!="object"||typeof t.relay!="string"||typeof t.session!="string"||typeof t.v!="number")throw new Error("Invalid pairing data: missing required fields");if(t.transport!==void 0&&t.transport!=="ws"&&t.transport!=="ably")throw new Error('Invalid pairing data: transport must be "ws" or "ably"');if(t.token!==void 0&&typeof t.token!="string")throw new Error("Invalid pairing data: token must be a string");if(t.transport==="ably"&&!t.token)throw new Error("Invalid pairing data: Ably transport requires a token");return t}function uf(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var $n={exports:{}};const df={},ff=Object.freeze(Object.defineProperty({__proto__:null,default:df},Symbol.toStringTag,{value:"Module"})),_f=rf(ff);var Dl;function gf(){return Dl||(Dl=1,(function(e){(function(t){var i=function(p){var S,y=new Float64Array(16);if(p)for(S=0;S<p.length;S++)y[S]=p[S];return y},n=function(){throw new Error("no PRNG")},a=new Uint8Array(16),h=new Uint8Array(32);h[0]=9;var d=i(),g=i([1]),v=i([56129,1]),m=i([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),R=i([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),k=i([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),B=i([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),L=i([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function P(p,S,y,u){p[S]=y>>24&255,p[S+1]=y>>16&255,p[S+2]=y>>8&255,p[S+3]=y&255,p[S+4]=u>>24&255,p[S+5]=u>>16&255,p[S+6]=u>>8&255,p[S+7]=u&255}function U(p,S,y,u,w){var T,I=0;for(T=0;T<w;T++)I|=p[S+T]^y[u+T];return(1&I-1>>>8)-1}function Z(p,S,y,u){return U(p,S,y,u,16)}function _e(p,S,y,u){return U(p,S,y,u,32)}function rt(p,S,y,u){for(var w=u[0]&255|(u[1]&255)<<8|(u[2]&255)<<16|(u[3]&255)<<24,T=y[0]&255|(y[1]&255)<<8|(y[2]&255)<<16|(y[3]&255)<<24,I=y[4]&255|(y[5]&255)<<8|(y[6]&255)<<16|(y[7]&255)<<24,G=y[8]&255|(y[9]&255)<<8|(y[10]&255)<<16|(y[11]&255)<<24,X=y[12]&255|(y[13]&255)<<8|(y[14]&255)<<16|(y[15]&255)<<24,we=u[4]&255|(u[5]&255)<<8|(u[6]&255)<<16|(u[7]&255)<<24,le=S[0]&255|(S[1]&255)<<8|(S[2]&255)<<16|(S[3]&255)<<24,Ke=S[4]&255|(S[5]&255)<<8|(S[6]&255)<<16|(S[7]&255)<<24,fe=S[8]&255|(S[9]&255)<<8|(S[10]&255)<<16|(S[11]&255)<<24,ke=S[12]&255|(S[13]&255)<<8|(S[14]&255)<<16|(S[15]&255)<<24,Me=u[8]&255|(u[9]&255)<<8|(u[10]&255)<<16|(u[11]&255)<<24,He=y[16]&255|(y[17]&255)<<8|(y[18]&255)<<16|(y[19]&255)<<24,J=y[20]&255|(y[21]&255)<<8|(y[22]&255)<<16|(y[23]&255)<<24,Oe=y[24]&255|(y[25]&255)<<8|(y[26]&255)<<16|(y[27]&255)<<24,Te=y[28]&255|(y[29]&255)<<8|(y[30]&255)<<16|(y[31]&255)<<24,Ee=u[12]&255|(u[13]&255)<<8|(u[14]&255)<<16|(u[15]&255)<<24,ge=w,ie=T,he=I,ye=G,ve=X,ne=we,D=le,N=Ke,K=fe,j=ke,$=Me,Y=He,Ce=J,Ie=Oe,We=Te,Ue=Ee,x,Ge=0;Ge<20;Ge+=2)x=ge+Ce|0,ve^=x<<7|x>>>25,x=ve+ge|0,K^=x<<9|x>>>23,x=K+ve|0,Ce^=x<<13|x>>>19,x=Ce+K|0,ge^=x<<18|x>>>14,x=ne+ie|0,j^=x<<7|x>>>25,x=j+ne|0,Ie^=x<<9|x>>>23,x=Ie+j|0,ie^=x<<13|x>>>19,x=ie+Ie|0,ne^=x<<18|x>>>14,x=$+D|0,We^=x<<7|x>>>25,x=We+$|0,he^=x<<9|x>>>23,x=he+We|0,D^=x<<13|x>>>19,x=D+he|0,$^=x<<18|x>>>14,x=Ue+Y|0,ye^=x<<7|x>>>25,x=ye+Ue|0,N^=x<<9|x>>>23,x=N+ye|0,Y^=x<<13|x>>>19,x=Y+N|0,Ue^=x<<18|x>>>14,x=ge+ye|0,ie^=x<<7|x>>>25,x=ie+ge|0,he^=x<<9|x>>>23,x=he+ie|0,ye^=x<<13|x>>>19,x=ye+he|0,ge^=x<<18|x>>>14,x=ne+ve|0,D^=x<<7|x>>>25,x=D+ne|0,N^=x<<9|x>>>23,x=N+D|0,ve^=x<<13|x>>>19,x=ve+N|0,ne^=x<<18|x>>>14,x=$+j|0,Y^=x<<7|x>>>25,x=Y+$|0,K^=x<<9|x>>>23,x=K+Y|0,j^=x<<13|x>>>19,x=j+K|0,$^=x<<18|x>>>14,x=Ue+We|0,Ce^=x<<7|x>>>25,x=Ce+Ue|0,Ie^=x<<9|x>>>23,x=Ie+Ce|0,We^=x<<13|x>>>19,x=We+Ie|0,Ue^=x<<18|x>>>14;ge=ge+w|0,ie=ie+T|0,he=he+I|0,ye=ye+G|0,ve=ve+X|0,ne=ne+we|0,D=D+le|0,N=N+Ke|0,K=K+fe|0,j=j+ke|0,$=$+Me|0,Y=Y+He|0,Ce=Ce+J|0,Ie=Ie+Oe|0,We=We+Te|0,Ue=Ue+Ee|0,p[0]=ge>>>0&255,p[1]=ge>>>8&255,p[2]=ge>>>16&255,p[3]=ge>>>24&255,p[4]=ie>>>0&255,p[5]=ie>>>8&255,p[6]=ie>>>16&255,p[7]=ie>>>24&255,p[8]=he>>>0&255,p[9]=he>>>8&255,p[10]=he>>>16&255,p[11]=he>>>24&255,p[12]=ye>>>0&255,p[13]=ye>>>8&255,p[14]=ye>>>16&255,p[15]=ye>>>24&255,p[16]=ve>>>0&255,p[17]=ve>>>8&255,p[18]=ve>>>16&255,p[19]=ve>>>24&255,p[20]=ne>>>0&255,p[21]=ne>>>8&255,p[22]=ne>>>16&255,p[23]=ne>>>24&255,p[24]=D>>>0&255,p[25]=D>>>8&255,p[26]=D>>>16&255,p[27]=D>>>24&255,p[28]=N>>>0&255,p[29]=N>>>8&255,p[30]=N>>>16&255,p[31]=N>>>24&255,p[32]=K>>>0&255,p[33]=K>>>8&255,p[34]=K>>>16&255,p[35]=K>>>24&255,p[36]=j>>>0&255,p[37]=j>>>8&255,p[38]=j>>>16&255,p[39]=j>>>24&255,p[40]=$>>>0&255,p[41]=$>>>8&255,p[42]=$>>>16&255,p[43]=$>>>24&255,p[44]=Y>>>0&255,p[45]=Y>>>8&255,p[46]=Y>>>16&255,p[47]=Y>>>24&255,p[48]=Ce>>>0&255,p[49]=Ce>>>8&255,p[50]=Ce>>>16&255,p[51]=Ce>>>24&255,p[52]=Ie>>>0&255,p[53]=Ie>>>8&255,p[54]=Ie>>>16&255,p[55]=Ie>>>24&255,p[56]=We>>>0&255,p[57]=We>>>8&255,p[58]=We>>>16&255,p[59]=We>>>24&255,p[60]=Ue>>>0&255,p[61]=Ue>>>8&255,p[62]=Ue>>>16&255,p[63]=Ue>>>24&255}function Ne(p,S,y,u){for(var w=u[0]&255|(u[1]&255)<<8|(u[2]&255)<<16|(u[3]&255)<<24,T=y[0]&255|(y[1]&255)<<8|(y[2]&255)<<16|(y[3]&255)<<24,I=y[4]&255|(y[5]&255)<<8|(y[6]&255)<<16|(y[7]&255)<<24,G=y[8]&255|(y[9]&255)<<8|(y[10]&255)<<16|(y[11]&255)<<24,X=y[12]&255|(y[13]&255)<<8|(y[14]&255)<<16|(y[15]&255)<<24,we=u[4]&255|(u[5]&255)<<8|(u[6]&255)<<16|(u[7]&255)<<24,le=S[0]&255|(S[1]&255)<<8|(S[2]&255)<<16|(S[3]&255)<<24,Ke=S[4]&255|(S[5]&255)<<8|(S[6]&255)<<16|(S[7]&255)<<24,fe=S[8]&255|(S[9]&255)<<8|(S[10]&255)<<16|(S[11]&255)<<24,ke=S[12]&255|(S[13]&255)<<8|(S[14]&255)<<16|(S[15]&255)<<24,Me=u[8]&255|(u[9]&255)<<8|(u[10]&255)<<16|(u[11]&255)<<24,He=y[16]&255|(y[17]&255)<<8|(y[18]&255)<<16|(y[19]&255)<<24,J=y[20]&255|(y[21]&255)<<8|(y[22]&255)<<16|(y[23]&255)<<24,Oe=y[24]&255|(y[25]&255)<<8|(y[26]&255)<<16|(y[27]&255)<<24,Te=y[28]&255|(y[29]&255)<<8|(y[30]&255)<<16|(y[31]&255)<<24,Ee=u[12]&255|(u[13]&255)<<8|(u[14]&255)<<16|(u[15]&255)<<24,ge=w,ie=T,he=I,ye=G,ve=X,ne=we,D=le,N=Ke,K=fe,j=ke,$=Me,Y=He,Ce=J,Ie=Oe,We=Te,Ue=Ee,x,Ge=0;Ge<20;Ge+=2)x=ge+Ce|0,ve^=x<<7|x>>>25,x=ve+ge|0,K^=x<<9|x>>>23,x=K+ve|0,Ce^=x<<13|x>>>19,x=Ce+K|0,ge^=x<<18|x>>>14,x=ne+ie|0,j^=x<<7|x>>>25,x=j+ne|0,Ie^=x<<9|x>>>23,x=Ie+j|0,ie^=x<<13|x>>>19,x=ie+Ie|0,ne^=x<<18|x>>>14,x=$+D|0,We^=x<<7|x>>>25,x=We+$|0,he^=x<<9|x>>>23,x=he+We|0,D^=x<<13|x>>>19,x=D+he|0,$^=x<<18|x>>>14,x=Ue+Y|0,ye^=x<<7|x>>>25,x=ye+Ue|0,N^=x<<9|x>>>23,x=N+ye|0,Y^=x<<13|x>>>19,x=Y+N|0,Ue^=x<<18|x>>>14,x=ge+ye|0,ie^=x<<7|x>>>25,x=ie+ge|0,he^=x<<9|x>>>23,x=he+ie|0,ye^=x<<13|x>>>19,x=ye+he|0,ge^=x<<18|x>>>14,x=ne+ve|0,D^=x<<7|x>>>25,x=D+ne|0,N^=x<<9|x>>>23,x=N+D|0,ve^=x<<13|x>>>19,x=ve+N|0,ne^=x<<18|x>>>14,x=$+j|0,Y^=x<<7|x>>>25,x=Y+$|0,K^=x<<9|x>>>23,x=K+Y|0,j^=x<<13|x>>>19,x=j+K|0,$^=x<<18|x>>>14,x=Ue+We|0,Ce^=x<<7|x>>>25,x=Ce+Ue|0,Ie^=x<<9|x>>>23,x=Ie+Ce|0,We^=x<<13|x>>>19,x=We+Ie|0,Ue^=x<<18|x>>>14;p[0]=ge>>>0&255,p[1]=ge>>>8&255,p[2]=ge>>>16&255,p[3]=ge>>>24&255,p[4]=ne>>>0&255,p[5]=ne>>>8&255,p[6]=ne>>>16&255,p[7]=ne>>>24&255,p[8]=$>>>0&255,p[9]=$>>>8&255,p[10]=$>>>16&255,p[11]=$>>>24&255,p[12]=Ue>>>0&255,p[13]=Ue>>>8&255,p[14]=Ue>>>16&255,p[15]=Ue>>>24&255,p[16]=D>>>0&255,p[17]=D>>>8&255,p[18]=D>>>16&255,p[19]=D>>>24&255,p[20]=N>>>0&255,p[21]=N>>>8&255,p[22]=N>>>16&255,p[23]=N>>>24&255,p[24]=K>>>0&255,p[25]=K>>>8&255,p[26]=K>>>16&255,p[27]=K>>>24&255,p[28]=j>>>0&255,p[29]=j>>>8&255,p[30]=j>>>16&255,p[31]=j>>>24&255}function H(p,S,y,u){rt(p,S,y,u)}function W(p,S,y,u){Ne(p,S,y,u)}var E=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function ae(p,S,y,u,w,T,I){var G=new Uint8Array(16),X=new Uint8Array(64),we,le;for(le=0;le<16;le++)G[le]=0;for(le=0;le<8;le++)G[le]=T[le];for(;w>=64;){for(H(X,G,I,E),le=0;le<64;le++)p[S+le]=y[u+le]^X[le];for(we=1,le=8;le<16;le++)we=we+(G[le]&255)|0,G[le]=we&255,we>>>=8;w-=64,S+=64,u+=64}if(w>0)for(H(X,G,I,E),le=0;le<w;le++)p[S+le]=y[u+le]^X[le];return 0}function be(p,S,y,u,w){var T=new Uint8Array(16),I=new Uint8Array(64),G,X;for(X=0;X<16;X++)T[X]=0;for(X=0;X<8;X++)T[X]=u[X];for(;y>=64;){for(H(I,T,w,E),X=0;X<64;X++)p[S+X]=I[X];for(G=1,X=8;X<16;X++)G=G+(T[X]&255)|0,T[X]=G&255,G>>>=8;y-=64,S+=64}if(y>0)for(H(I,T,w,E),X=0;X<y;X++)p[S+X]=I[X];return 0}function ze(p,S,y,u,w){var T=new Uint8Array(32);W(T,u,w,E);for(var I=new Uint8Array(8),G=0;G<8;G++)I[G]=u[G+16];return be(p,S,y,I,T)}function Be(p,S,y,u,w,T,I){var G=new Uint8Array(32);W(G,T,I,E);for(var X=new Uint8Array(8),we=0;we<8;we++)X[we]=T[we+16];return ae(p,S,y,u,w,X,G)}var xe=function(p){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var S,y,u,w,T,I,G,X;S=p[0]&255|(p[1]&255)<<8,this.r[0]=S&8191,y=p[2]&255|(p[3]&255)<<8,this.r[1]=(S>>>13|y<<3)&8191,u=p[4]&255|(p[5]&255)<<8,this.r[2]=(y>>>10|u<<6)&7939,w=p[6]&255|(p[7]&255)<<8,this.r[3]=(u>>>7|w<<9)&8191,T=p[8]&255|(p[9]&255)<<8,this.r[4]=(w>>>4|T<<12)&255,this.r[5]=T>>>1&8190,I=p[10]&255|(p[11]&255)<<8,this.r[6]=(T>>>14|I<<2)&8191,G=p[12]&255|(p[13]&255)<<8,this.r[7]=(I>>>11|G<<5)&8065,X=p[14]&255|(p[15]&255)<<8,this.r[8]=(G>>>8|X<<8)&8191,this.r[9]=X>>>5&127,this.pad[0]=p[16]&255|(p[17]&255)<<8,this.pad[1]=p[18]&255|(p[19]&255)<<8,this.pad[2]=p[20]&255|(p[21]&255)<<8,this.pad[3]=p[22]&255|(p[23]&255)<<8,this.pad[4]=p[24]&255|(p[25]&255)<<8,this.pad[5]=p[26]&255|(p[27]&255)<<8,this.pad[6]=p[28]&255|(p[29]&255)<<8,this.pad[7]=p[30]&255|(p[31]&255)<<8};xe.prototype.blocks=function(p,S,y){for(var u=this.fin?0:2048,w,T,I,G,X,we,le,Ke,fe,ke,Me,He,J,Oe,Te,Ee,ge,ie,he,ye=this.h[0],ve=this.h[1],ne=this.h[2],D=this.h[3],N=this.h[4],K=this.h[5],j=this.h[6],$=this.h[7],Y=this.h[8],Ce=this.h[9],Ie=this.r[0],We=this.r[1],Ue=this.r[2],x=this.r[3],Ge=this.r[4],Fe=this.r[5],Ye=this.r[6],Pe=this.r[7],Je=this.r[8],Xe=this.r[9];y>=16;)w=p[S+0]&255|(p[S+1]&255)<<8,ye+=w&8191,T=p[S+2]&255|(p[S+3]&255)<<8,ve+=(w>>>13|T<<3)&8191,I=p[S+4]&255|(p[S+5]&255)<<8,ne+=(T>>>10|I<<6)&8191,G=p[S+6]&255|(p[S+7]&255)<<8,D+=(I>>>7|G<<9)&8191,X=p[S+8]&255|(p[S+9]&255)<<8,N+=(G>>>4|X<<12)&8191,K+=X>>>1&8191,we=p[S+10]&255|(p[S+11]&255)<<8,j+=(X>>>14|we<<2)&8191,le=p[S+12]&255|(p[S+13]&255)<<8,$+=(we>>>11|le<<5)&8191,Ke=p[S+14]&255|(p[S+15]&255)<<8,Y+=(le>>>8|Ke<<8)&8191,Ce+=Ke>>>5|u,fe=0,ke=fe,ke+=ye*Ie,ke+=ve*(5*Xe),ke+=ne*(5*Je),ke+=D*(5*Pe),ke+=N*(5*Ye),fe=ke>>>13,ke&=8191,ke+=K*(5*Fe),ke+=j*(5*Ge),ke+=$*(5*x),ke+=Y*(5*Ue),ke+=Ce*(5*We),fe+=ke>>>13,ke&=8191,Me=fe,Me+=ye*We,Me+=ve*Ie,Me+=ne*(5*Xe),Me+=D*(5*Je),Me+=N*(5*Pe),fe=Me>>>13,Me&=8191,Me+=K*(5*Ye),Me+=j*(5*Fe),Me+=$*(5*Ge),Me+=Y*(5*x),Me+=Ce*(5*Ue),fe+=Me>>>13,Me&=8191,He=fe,He+=ye*Ue,He+=ve*We,He+=ne*Ie,He+=D*(5*Xe),He+=N*(5*Je),fe=He>>>13,He&=8191,He+=K*(5*Pe),He+=j*(5*Ye),He+=$*(5*Fe),He+=Y*(5*Ge),He+=Ce*(5*x),fe+=He>>>13,He&=8191,J=fe,J+=ye*x,J+=ve*Ue,J+=ne*We,J+=D*Ie,J+=N*(5*Xe),fe=J>>>13,J&=8191,J+=K*(5*Je),J+=j*(5*Pe),J+=$*(5*Ye),J+=Y*(5*Fe),J+=Ce*(5*Ge),fe+=J>>>13,J&=8191,Oe=fe,Oe+=ye*Ge,Oe+=ve*x,Oe+=ne*Ue,Oe+=D*We,Oe+=N*Ie,fe=Oe>>>13,Oe&=8191,Oe+=K*(5*Xe),Oe+=j*(5*Je),Oe+=$*(5*Pe),Oe+=Y*(5*Ye),Oe+=Ce*(5*Fe),fe+=Oe>>>13,Oe&=8191,Te=fe,Te+=ye*Fe,Te+=ve*Ge,Te+=ne*x,Te+=D*Ue,Te+=N*We,fe=Te>>>13,Te&=8191,Te+=K*Ie,Te+=j*(5*Xe),Te+=$*(5*Je),Te+=Y*(5*Pe),Te+=Ce*(5*Ye),fe+=Te>>>13,Te&=8191,Ee=fe,Ee+=ye*Ye,Ee+=ve*Fe,Ee+=ne*Ge,Ee+=D*x,Ee+=N*Ue,fe=Ee>>>13,Ee&=8191,Ee+=K*We,Ee+=j*Ie,Ee+=$*(5*Xe),Ee+=Y*(5*Je),Ee+=Ce*(5*Pe),fe+=Ee>>>13,Ee&=8191,ge=fe,ge+=ye*Pe,ge+=ve*Ye,ge+=ne*Fe,ge+=D*Ge,ge+=N*x,fe=ge>>>13,ge&=8191,ge+=K*Ue,ge+=j*We,ge+=$*Ie,ge+=Y*(5*Xe),ge+=Ce*(5*Je),fe+=ge>>>13,ge&=8191,ie=fe,ie+=ye*Je,ie+=ve*Pe,ie+=ne*Ye,ie+=D*Fe,ie+=N*Ge,fe=ie>>>13,ie&=8191,ie+=K*x,ie+=j*Ue,ie+=$*We,ie+=Y*Ie,ie+=Ce*(5*Xe),fe+=ie>>>13,ie&=8191,he=fe,he+=ye*Xe,he+=ve*Je,he+=ne*Pe,he+=D*Ye,he+=N*Fe,fe=he>>>13,he&=8191,he+=K*Ge,he+=j*x,he+=$*Ue,he+=Y*We,he+=Ce*Ie,fe+=he>>>13,he&=8191,fe=(fe<<2)+fe|0,fe=fe+ke|0,ke=fe&8191,fe=fe>>>13,Me+=fe,ye=ke,ve=Me,ne=He,D=J,N=Oe,K=Te,j=Ee,$=ge,Y=ie,Ce=he,S+=16,y-=16;this.h[0]=ye,this.h[1]=ve,this.h[2]=ne,this.h[3]=D,this.h[4]=N,this.h[5]=K,this.h[6]=j,this.h[7]=$,this.h[8]=Y,this.h[9]=Ce},xe.prototype.finish=function(p,S){var y=new Uint16Array(10),u,w,T,I;if(this.leftover){for(I=this.leftover,this.buffer[I++]=1;I<16;I++)this.buffer[I]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(u=this.h[1]>>>13,this.h[1]&=8191,I=2;I<10;I++)this.h[I]+=u,u=this.h[I]>>>13,this.h[I]&=8191;for(this.h[0]+=u*5,u=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=u,u=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=u,y[0]=this.h[0]+5,u=y[0]>>>13,y[0]&=8191,I=1;I<10;I++)y[I]=this.h[I]+u,u=y[I]>>>13,y[I]&=8191;for(y[9]-=8192,w=(u^1)-1,I=0;I<10;I++)y[I]&=w;for(w=~w,I=0;I<10;I++)this.h[I]=this.h[I]&w|y[I];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,T=this.h[0]+this.pad[0],this.h[0]=T&65535,I=1;I<8;I++)T=(this.h[I]+this.pad[I]|0)+(T>>>16)|0,this.h[I]=T&65535;p[S+0]=this.h[0]>>>0&255,p[S+1]=this.h[0]>>>8&255,p[S+2]=this.h[1]>>>0&255,p[S+3]=this.h[1]>>>8&255,p[S+4]=this.h[2]>>>0&255,p[S+5]=this.h[2]>>>8&255,p[S+6]=this.h[3]>>>0&255,p[S+7]=this.h[3]>>>8&255,p[S+8]=this.h[4]>>>0&255,p[S+9]=this.h[4]>>>8&255,p[S+10]=this.h[5]>>>0&255,p[S+11]=this.h[5]>>>8&255,p[S+12]=this.h[6]>>>0&255,p[S+13]=this.h[6]>>>8&255,p[S+14]=this.h[7]>>>0&255,p[S+15]=this.h[7]>>>8&255},xe.prototype.update=function(p,S,y){var u,w;if(this.leftover){for(w=16-this.leftover,w>y&&(w=y),u=0;u<w;u++)this.buffer[this.leftover+u]=p[S+u];if(y-=w,S+=w,this.leftover+=w,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(y>=16&&(w=y-y%16,this.blocks(p,S,w),S+=w,y-=w),y){for(u=0;u<y;u++)this.buffer[this.leftover+u]=p[S+u];this.leftover+=y}};function ce(p,S,y,u,w,T){var I=new xe(T);return I.update(y,u,w),I.finish(p,S),0}function f(p,S,y,u,w,T){var I=new Uint8Array(16);return ce(I,0,y,u,w,T),Z(p,S,I,0)}function re(p,S,y,u,w){var T;if(y<32)return-1;for(Be(p,0,S,0,y,u,w),ce(p,16,p,32,y-32,p),T=0;T<16;T++)p[T]=0;return 0}function oe(p,S,y,u,w){var T,I=new Uint8Array(32);if(y<32||(ze(I,0,32,u,w),f(S,16,S,32,y-32,I)!==0))return-1;for(Be(p,0,S,0,y,u,w),T=0;T<32;T++)p[T]=0;return 0}function A(p,S){var y;for(y=0;y<16;y++)p[y]=S[y]|0}function Se(p){var S,y,u=1;for(S=0;S<16;S++)y=p[S]+u+65535,u=Math.floor(y/65536),p[S]=y-u*65536;p[0]+=u-1+37*(u-1)}function te(p,S,y){for(var u,w=~(y-1),T=0;T<16;T++)u=w&(p[T]^S[T]),p[T]^=u,S[T]^=u}function se(p,S){var y,u,w,T=i(),I=i();for(y=0;y<16;y++)I[y]=S[y];for(Se(I),Se(I),Se(I),u=0;u<2;u++){for(T[0]=I[0]-65517,y=1;y<15;y++)T[y]=I[y]-65535-(T[y-1]>>16&1),T[y-1]&=65535;T[15]=I[15]-32767-(T[14]>>16&1),w=T[15]>>16&1,T[14]&=65535,te(I,T,1-w)}for(y=0;y<16;y++)p[2*y]=I[y]&255,p[2*y+1]=I[y]>>8}function ct(p,S){var y=new Uint8Array(32),u=new Uint8Array(32);return se(y,p),se(u,S),_e(y,0,u,0)}function zt(p){var S=new Uint8Array(32);return se(S,p),S[0]&1}function Mt(p,S){var y;for(y=0;y<16;y++)p[y]=S[2*y]+(S[2*y+1]<<8);p[15]&=32767}function ut(p,S,y){for(var u=0;u<16;u++)p[u]=S[u]+y[u]}function je(p,S,y){for(var u=0;u<16;u++)p[u]=S[u]-y[u]}function Ae(p,S,y){var u,w,T=0,I=0,G=0,X=0,we=0,le=0,Ke=0,fe=0,ke=0,Me=0,He=0,J=0,Oe=0,Te=0,Ee=0,ge=0,ie=0,he=0,ye=0,ve=0,ne=0,D=0,N=0,K=0,j=0,$=0,Y=0,Ce=0,Ie=0,We=0,Ue=0,x=y[0],Ge=y[1],Fe=y[2],Ye=y[3],Pe=y[4],Je=y[5],Xe=y[6],gt=y[7],nt=y[8],ft=y[9],mt=y[10],qe=y[11],ue=y[12],Ot=y[13],ot=y[14],Bt=y[15];u=S[0],T+=u*x,I+=u*Ge,G+=u*Fe,X+=u*Ye,we+=u*Pe,le+=u*Je,Ke+=u*Xe,fe+=u*gt,ke+=u*nt,Me+=u*ft,He+=u*mt,J+=u*qe,Oe+=u*ue,Te+=u*Ot,Ee+=u*ot,ge+=u*Bt,u=S[1],I+=u*x,G+=u*Ge,X+=u*Fe,we+=u*Ye,le+=u*Pe,Ke+=u*Je,fe+=u*Xe,ke+=u*gt,Me+=u*nt,He+=u*ft,J+=u*mt,Oe+=u*qe,Te+=u*ue,Ee+=u*Ot,ge+=u*ot,ie+=u*Bt,u=S[2],G+=u*x,X+=u*Ge,we+=u*Fe,le+=u*Ye,Ke+=u*Pe,fe+=u*Je,ke+=u*Xe,Me+=u*gt,He+=u*nt,J+=u*ft,Oe+=u*mt,Te+=u*qe,Ee+=u*ue,ge+=u*Ot,ie+=u*ot,he+=u*Bt,u=S[3],X+=u*x,we+=u*Ge,le+=u*Fe,Ke+=u*Ye,fe+=u*Pe,ke+=u*Je,Me+=u*Xe,He+=u*gt,J+=u*nt,Oe+=u*ft,Te+=u*mt,Ee+=u*qe,ge+=u*ue,ie+=u*Ot,he+=u*ot,ye+=u*Bt,u=S[4],we+=u*x,le+=u*Ge,Ke+=u*Fe,fe+=u*Ye,ke+=u*Pe,Me+=u*Je,He+=u*Xe,J+=u*gt,Oe+=u*nt,Te+=u*ft,Ee+=u*mt,ge+=u*qe,ie+=u*ue,he+=u*Ot,ye+=u*ot,ve+=u*Bt,u=S[5],le+=u*x,Ke+=u*Ge,fe+=u*Fe,ke+=u*Ye,Me+=u*Pe,He+=u*Je,J+=u*Xe,Oe+=u*gt,Te+=u*nt,Ee+=u*ft,ge+=u*mt,ie+=u*qe,he+=u*ue,ye+=u*Ot,ve+=u*ot,ne+=u*Bt,u=S[6],Ke+=u*x,fe+=u*Ge,ke+=u*Fe,Me+=u*Ye,He+=u*Pe,J+=u*Je,Oe+=u*Xe,Te+=u*gt,Ee+=u*nt,ge+=u*ft,ie+=u*mt,he+=u*qe,ye+=u*ue,ve+=u*Ot,ne+=u*ot,D+=u*Bt,u=S[7],fe+=u*x,ke+=u*Ge,Me+=u*Fe,He+=u*Ye,J+=u*Pe,Oe+=u*Je,Te+=u*Xe,Ee+=u*gt,ge+=u*nt,ie+=u*ft,he+=u*mt,ye+=u*qe,ve+=u*ue,ne+=u*Ot,D+=u*ot,N+=u*Bt,u=S[8],ke+=u*x,Me+=u*Ge,He+=u*Fe,J+=u*Ye,Oe+=u*Pe,Te+=u*Je,Ee+=u*Xe,ge+=u*gt,ie+=u*nt,he+=u*ft,ye+=u*mt,ve+=u*qe,ne+=u*ue,D+=u*Ot,N+=u*ot,K+=u*Bt,u=S[9],Me+=u*x,He+=u*Ge,J+=u*Fe,Oe+=u*Ye,Te+=u*Pe,Ee+=u*Je,ge+=u*Xe,ie+=u*gt,he+=u*nt,ye+=u*ft,ve+=u*mt,ne+=u*qe,D+=u*ue,N+=u*Ot,K+=u*ot,j+=u*Bt,u=S[10],He+=u*x,J+=u*Ge,Oe+=u*Fe,Te+=u*Ye,Ee+=u*Pe,ge+=u*Je,ie+=u*Xe,he+=u*gt,ye+=u*nt,ve+=u*ft,ne+=u*mt,D+=u*qe,N+=u*ue,K+=u*Ot,j+=u*ot,$+=u*Bt,u=S[11],J+=u*x,Oe+=u*Ge,Te+=u*Fe,Ee+=u*Ye,ge+=u*Pe,ie+=u*Je,he+=u*Xe,ye+=u*gt,ve+=u*nt,ne+=u*ft,D+=u*mt,N+=u*qe,K+=u*ue,j+=u*Ot,$+=u*ot,Y+=u*Bt,u=S[12],Oe+=u*x,Te+=u*Ge,Ee+=u*Fe,ge+=u*Ye,ie+=u*Pe,he+=u*Je,ye+=u*Xe,ve+=u*gt,ne+=u*nt,D+=u*ft,N+=u*mt,K+=u*qe,j+=u*ue,$+=u*Ot,Y+=u*ot,Ce+=u*Bt,u=S[13],Te+=u*x,Ee+=u*Ge,ge+=u*Fe,ie+=u*Ye,he+=u*Pe,ye+=u*Je,ve+=u*Xe,ne+=u*gt,D+=u*nt,N+=u*ft,K+=u*mt,j+=u*qe,$+=u*ue,Y+=u*Ot,Ce+=u*ot,Ie+=u*Bt,u=S[14],Ee+=u*x,ge+=u*Ge,ie+=u*Fe,he+=u*Ye,ye+=u*Pe,ve+=u*Je,ne+=u*Xe,D+=u*gt,N+=u*nt,K+=u*ft,j+=u*mt,$+=u*qe,Y+=u*ue,Ce+=u*Ot,Ie+=u*ot,We+=u*Bt,u=S[15],ge+=u*x,ie+=u*Ge,he+=u*Fe,ye+=u*Ye,ve+=u*Pe,ne+=u*Je,D+=u*Xe,N+=u*gt,K+=u*nt,j+=u*ft,$+=u*mt,Y+=u*qe,Ce+=u*ue,Ie+=u*Ot,We+=u*ot,Ue+=u*Bt,T+=38*ie,I+=38*he,G+=38*ye,X+=38*ve,we+=38*ne,le+=38*D,Ke+=38*N,fe+=38*K,ke+=38*j,Me+=38*$,He+=38*Y,J+=38*Ce,Oe+=38*Ie,Te+=38*We,Ee+=38*Ue,w=1,u=T+w+65535,w=Math.floor(u/65536),T=u-w*65536,u=I+w+65535,w=Math.floor(u/65536),I=u-w*65536,u=G+w+65535,w=Math.floor(u/65536),G=u-w*65536,u=X+w+65535,w=Math.floor(u/65536),X=u-w*65536,u=we+w+65535,w=Math.floor(u/65536),we=u-w*65536,u=le+w+65535,w=Math.floor(u/65536),le=u-w*65536,u=Ke+w+65535,w=Math.floor(u/65536),Ke=u-w*65536,u=fe+w+65535,w=Math.floor(u/65536),fe=u-w*65536,u=ke+w+65535,w=Math.floor(u/65536),ke=u-w*65536,u=Me+w+65535,w=Math.floor(u/65536),Me=u-w*65536,u=He+w+65535,w=Math.floor(u/65536),He=u-w*65536,u=J+w+65535,w=Math.floor(u/65536),J=u-w*65536,u=Oe+w+65535,w=Math.floor(u/65536),Oe=u-w*65536,u=Te+w+65535,w=Math.floor(u/65536),Te=u-w*65536,u=Ee+w+65535,w=Math.floor(u/65536),Ee=u-w*65536,u=ge+w+65535,w=Math.floor(u/65536),ge=u-w*65536,T+=w-1+37*(w-1),w=1,u=T+w+65535,w=Math.floor(u/65536),T=u-w*65536,u=I+w+65535,w=Math.floor(u/65536),I=u-w*65536,u=G+w+65535,w=Math.floor(u/65536),G=u-w*65536,u=X+w+65535,w=Math.floor(u/65536),X=u-w*65536,u=we+w+65535,w=Math.floor(u/65536),we=u-w*65536,u=le+w+65535,w=Math.floor(u/65536),le=u-w*65536,u=Ke+w+65535,w=Math.floor(u/65536),Ke=u-w*65536,u=fe+w+65535,w=Math.floor(u/65536),fe=u-w*65536,u=ke+w+65535,w=Math.floor(u/65536),ke=u-w*65536,u=Me+w+65535,w=Math.floor(u/65536),Me=u-w*65536,u=He+w+65535,w=Math.floor(u/65536),He=u-w*65536,u=J+w+65535,w=Math.floor(u/65536),J=u-w*65536,u=Oe+w+65535,w=Math.floor(u/65536),Oe=u-w*65536,u=Te+w+65535,w=Math.floor(u/65536),Te=u-w*65536,u=Ee+w+65535,w=Math.floor(u/65536),Ee=u-w*65536,u=ge+w+65535,w=Math.floor(u/65536),ge=u-w*65536,T+=w-1+37*(w-1),p[0]=T,p[1]=I,p[2]=G,p[3]=X,p[4]=we,p[5]=le,p[6]=Ke,p[7]=fe,p[8]=ke,p[9]=Me,p[10]=He,p[11]=J,p[12]=Oe,p[13]=Te,p[14]=Ee,p[15]=ge}function at(p,S){Ae(p,S,S)}function oi(p,S){var y=i(),u;for(u=0;u<16;u++)y[u]=S[u];for(u=253;u>=0;u--)at(y,y),u!==2&&u!==4&&Ae(y,y,S);for(u=0;u<16;u++)p[u]=y[u]}function Ni(p,S){var y=i(),u;for(u=0;u<16;u++)y[u]=S[u];for(u=250;u>=0;u--)at(y,y),u!==1&&Ae(y,y,S);for(u=0;u<16;u++)p[u]=y[u]}function qt(p,S,y){var u=new Uint8Array(32),w=new Float64Array(80),T,I,G=i(),X=i(),we=i(),le=i(),Ke=i(),fe=i();for(I=0;I<31;I++)u[I]=S[I];for(u[31]=S[31]&127|64,u[0]&=248,Mt(w,y),I=0;I<16;I++)X[I]=w[I],le[I]=G[I]=we[I]=0;for(G[0]=le[0]=1,I=254;I>=0;--I)T=u[I>>>3]>>>(I&7)&1,te(G,X,T),te(we,le,T),ut(Ke,G,we),je(G,G,we),ut(we,X,le),je(X,X,le),at(le,Ke),at(fe,G),Ae(G,we,G),Ae(we,X,Ke),ut(Ke,G,we),je(G,G,we),at(X,G),je(we,le,fe),Ae(G,we,v),ut(G,G,le),Ae(we,we,G),Ae(G,le,fe),Ae(le,X,w),at(X,Ke),te(G,X,T),te(we,le,T);for(I=0;I<16;I++)w[I+16]=G[I],w[I+32]=we[I],w[I+48]=X[I],w[I+64]=le[I];var ke=w.subarray(32),Me=w.subarray(16);return oi(ke,ke),Ae(Me,Me,ke),se(p,Me),0}function ai(p,S){return qt(p,S,h)}function fi(p,S){return n(S,32),ai(p,S)}function Gt(p,S,y){var u=new Uint8Array(32);return qt(u,y,S),W(p,a,u,E)}var et=re,_i=oe;function Br(p,S,y,u,w,T){var I=new Uint8Array(32);return Gt(I,w,T),et(p,S,y,u,I)}function Ir(p,S,y,u,w,T){var I=new Uint8Array(32);return Gt(I,w,T),_i(p,S,y,u,I)}var Dr=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function zs(p,S,y,u){for(var w=new Int32Array(16),T=new Int32Array(16),I,G,X,we,le,Ke,fe,ke,Me,He,J,Oe,Te,Ee,ge,ie,he,ye,ve,ne,D,N,K,j,$,Y,Ce=p[0],Ie=p[1],We=p[2],Ue=p[3],x=p[4],Ge=p[5],Fe=p[6],Ye=p[7],Pe=S[0],Je=S[1],Xe=S[2],gt=S[3],nt=S[4],ft=S[5],mt=S[6],qe=S[7],ue=0;u>=128;){for(ve=0;ve<16;ve++)ne=8*ve+ue,w[ve]=y[ne+0]<<24|y[ne+1]<<16|y[ne+2]<<8|y[ne+3],T[ve]=y[ne+4]<<24|y[ne+5]<<16|y[ne+6]<<8|y[ne+7];for(ve=0;ve<80;ve++)if(I=Ce,G=Ie,X=We,we=Ue,le=x,Ke=Ge,fe=Fe,ke=Ye,Me=Pe,He=Je,J=Xe,Oe=gt,Te=nt,Ee=ft,ge=mt,ie=qe,D=Ye,N=qe,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=(x>>>14|nt<<18)^(x>>>18|nt<<14)^(nt>>>9|x<<23),N=(nt>>>14|x<<18)^(nt>>>18|x<<14)^(x>>>9|nt<<23),K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,D=x&Ge^~x&Fe,N=nt&ft^~nt&mt,K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,D=Dr[ve*2],N=Dr[ve*2+1],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,D=w[ve%16],N=T[ve%16],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,he=$&65535|Y<<16,ye=K&65535|j<<16,D=he,N=ye,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=(Ce>>>28|Pe<<4)^(Pe>>>2|Ce<<30)^(Pe>>>7|Ce<<25),N=(Pe>>>28|Ce<<4)^(Ce>>>2|Pe<<30)^(Ce>>>7|Pe<<25),K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,D=Ce&Ie^Ce&We^Ie&We,N=Pe&Je^Pe&Xe^Je&Xe,K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,ke=$&65535|Y<<16,ie=K&65535|j<<16,D=we,N=Oe,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=he,N=ye,K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,we=$&65535|Y<<16,Oe=K&65535|j<<16,Ie=I,We=G,Ue=X,x=we,Ge=le,Fe=Ke,Ye=fe,Ce=ke,Je=Me,Xe=He,gt=J,nt=Oe,ft=Te,mt=Ee,qe=ge,Pe=ie,ve%16===15)for(ne=0;ne<16;ne++)D=w[ne],N=T[ne],K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=w[(ne+9)%16],N=T[(ne+9)%16],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,he=w[(ne+1)%16],ye=T[(ne+1)%16],D=(he>>>1|ye<<31)^(he>>>8|ye<<24)^he>>>7,N=(ye>>>1|he<<31)^(ye>>>8|he<<24)^(ye>>>7|he<<25),K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,he=w[(ne+14)%16],ye=T[(ne+14)%16],D=(he>>>19|ye<<13)^(ye>>>29|he<<3)^he>>>6,N=(ye>>>19|he<<13)^(he>>>29|ye<<3)^(ye>>>6|he<<26),K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,w[ne]=$&65535|Y<<16,T[ne]=K&65535|j<<16;D=Ce,N=Pe,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=p[0],N=S[0],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,p[0]=Ce=$&65535|Y<<16,S[0]=Pe=K&65535|j<<16,D=Ie,N=Je,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=p[1],N=S[1],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,p[1]=Ie=$&65535|Y<<16,S[1]=Je=K&65535|j<<16,D=We,N=Xe,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=p[2],N=S[2],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,p[2]=We=$&65535|Y<<16,S[2]=Xe=K&65535|j<<16,D=Ue,N=gt,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=p[3],N=S[3],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,p[3]=Ue=$&65535|Y<<16,S[3]=gt=K&65535|j<<16,D=x,N=nt,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=p[4],N=S[4],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,p[4]=x=$&65535|Y<<16,S[4]=nt=K&65535|j<<16,D=Ge,N=ft,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=p[5],N=S[5],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,p[5]=Ge=$&65535|Y<<16,S[5]=ft=K&65535|j<<16,D=Fe,N=mt,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=p[6],N=S[6],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,p[6]=Fe=$&65535|Y<<16,S[6]=mt=K&65535|j<<16,D=Ye,N=qe,K=N&65535,j=N>>>16,$=D&65535,Y=D>>>16,D=p[7],N=S[7],K+=N&65535,j+=N>>>16,$+=D&65535,Y+=D>>>16,j+=K>>>16,$+=j>>>16,Y+=$>>>16,p[7]=Ye=$&65535|Y<<16,S[7]=qe=K&65535|j<<16,ue+=128,u-=128}return u}function gi(p,S,y){var u=new Int32Array(8),w=new Int32Array(8),T=new Uint8Array(256),I,G=y;for(u[0]=1779033703,u[1]=3144134277,u[2]=1013904242,u[3]=2773480762,u[4]=1359893119,u[5]=2600822924,u[6]=528734635,u[7]=1541459225,w[0]=4089235720,w[1]=2227873595,w[2]=4271175723,w[3]=1595750129,w[4]=2917565137,w[5]=725511199,w[6]=4215389547,w[7]=327033209,zs(u,w,S,y),y%=128,I=0;I<y;I++)T[I]=S[G-y+I];for(T[y]=128,y=256-128*(y<112?1:0),T[y-9]=0,P(T,y-8,G/536870912|0,G<<3),zs(u,w,T,y),I=0;I<8;I++)P(p,8*I,u[I],w[I]);return 0}function vi(p,S){var y=i(),u=i(),w=i(),T=i(),I=i(),G=i(),X=i(),we=i(),le=i();je(y,p[1],p[0]),je(le,S[1],S[0]),Ae(y,y,le),ut(u,p[0],p[1]),ut(le,S[0],S[1]),Ae(u,u,le),Ae(w,p[3],S[3]),Ae(w,w,R),Ae(T,p[2],S[2]),ut(T,T,T),je(I,u,y),je(G,T,w),ut(X,T,w),ut(we,u,y),Ae(p[0],I,G),Ae(p[1],we,X),Ae(p[2],X,G),Ae(p[3],I,we)}function ms(p,S,y){var u;for(u=0;u<4;u++)te(p[u],S[u],y)}function Hi(p,S){var y=i(),u=i(),w=i();oi(w,S[2]),Ae(y,S[0],w),Ae(u,S[1],w),se(p,u),p[31]^=zt(y)<<7}function ss(p,S,y){var u,w;for(A(p[0],d),A(p[1],g),A(p[2],g),A(p[3],d),w=255;w>=0;--w)u=y[w/8|0]>>(w&7)&1,ms(p,S,u),vi(S,p),vi(p,p),ms(p,S,u)}function it(p,S){var y=[i(),i(),i(),i()];A(y[0],k),A(y[1],B),A(y[2],g),Ae(y[3],k,B),ss(p,y,S)}function vs(p,S,y){var u=new Uint8Array(64),w=[i(),i(),i(),i()],T;for(y||n(S,32),gi(u,S,32),u[0]&=248,u[31]&=127,u[31]|=64,it(w,u),Hi(p,w),T=0;T<32;T++)S[T+32]=p[T];return 0}var rs=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function Ui(p,S){var y,u,w,T;for(u=63;u>=32;--u){for(y=0,w=u-32,T=u-12;w<T;++w)S[w]+=y-16*S[u]*rs[w-(u-32)],y=Math.floor((S[w]+128)/256),S[w]-=y*256;S[w]+=y,S[u]=0}for(y=0,w=0;w<32;w++)S[w]+=y-(S[31]>>4)*rs[w],y=S[w]>>8,S[w]&=255;for(w=0;w<32;w++)S[w]-=y*rs[w];for(u=0;u<32;u++)S[u+1]+=S[u]>>8,p[u]=S[u]&255}function ys(p){var S=new Float64Array(64),y;for(y=0;y<64;y++)S[y]=p[y];for(y=0;y<64;y++)p[y]=0;Ui(p,S)}function qs(p,S,y,u){var w=new Uint8Array(64),T=new Uint8Array(64),I=new Uint8Array(64),G,X,we=new Float64Array(64),le=[i(),i(),i(),i()];gi(w,u,32),w[0]&=248,w[31]&=127,w[31]|=64;var Ke=y+64;for(G=0;G<y;G++)p[64+G]=S[G];for(G=0;G<32;G++)p[32+G]=w[32+G];for(gi(I,p.subarray(32),y+32),ys(I),it(le,I),Hi(p,le),G=32;G<64;G++)p[G]=u[G];for(gi(T,p,y+64),ys(T),G=0;G<64;G++)we[G]=0;for(G=0;G<32;G++)we[G]=I[G];for(G=0;G<32;G++)for(X=0;X<32;X++)we[G+X]+=T[G]*w[X];return Ui(p.subarray(32),we),Ke}function Vt(p,S){var y=i(),u=i(),w=i(),T=i(),I=i(),G=i(),X=i();return A(p[2],g),Mt(p[1],S),at(w,p[1]),Ae(T,w,m),je(w,w,p[2]),ut(T,p[2],T),at(I,T),at(G,I),Ae(X,G,I),Ae(y,X,w),Ae(y,y,T),Ni(y,y),Ae(y,y,w),Ae(y,y,T),Ae(y,y,T),Ae(p[0],y,T),at(u,p[0]),Ae(u,u,T),ct(u,w)&&Ae(p[0],p[0],L),at(u,p[0]),Ae(u,u,T),ct(u,w)?-1:(zt(p[0])===S[31]>>7&&je(p[0],d,p[0]),Ae(p[3],p[0],p[1]),0)}function bt(p,S,y,u){var w,T=new Uint8Array(32),I=new Uint8Array(64),G=[i(),i(),i(),i()],X=[i(),i(),i(),i()];if(y<64||Vt(X,u))return-1;for(w=0;w<y;w++)p[w]=S[w];for(w=0;w<32;w++)p[w+32]=u[w];if(gi(I,p,y),ys(I),ss(G,X,I),it(X,S.subarray(32)),vi(G,X),Hi(T,G),y-=64,_e(S,0,T,0)){for(w=0;w<y;w++)p[w]=0;return-1}for(w=0;w<y;w++)p[w]=S[w+64];return y}var Kt=32,Wi=24,Fi=32,Mi=16,zi=32,qi=32,Oi=32,Gi=32,Ss=32,ns=Wi,Nr=Fi,bs=Mi,dt=64,yi=32,ji=64,ws=32,Gs=64;t.lowlevel={crypto_core_hsalsa20:W,crypto_stream_xor:Be,crypto_stream:ze,crypto_stream_salsa20_xor:ae,crypto_stream_salsa20:be,crypto_onetimeauth:ce,crypto_onetimeauth_verify:f,crypto_verify_16:Z,crypto_verify_32:_e,crypto_secretbox:re,crypto_secretbox_open:oe,crypto_scalarmult:qt,crypto_scalarmult_base:ai,crypto_box_beforenm:Gt,crypto_box_afternm:et,crypto_box:Br,crypto_box_open:Ir,crypto_box_keypair:fi,crypto_hash:gi,crypto_sign:qs,crypto_sign_keypair:vs,crypto_sign_open:bt,crypto_secretbox_KEYBYTES:Kt,crypto_secretbox_NONCEBYTES:Wi,crypto_secretbox_ZEROBYTES:Fi,crypto_secretbox_BOXZEROBYTES:Mi,crypto_scalarmult_BYTES:zi,crypto_scalarmult_SCALARBYTES:qi,crypto_box_PUBLICKEYBYTES:Oi,crypto_box_SECRETKEYBYTES:Gi,crypto_box_BEFORENMBYTES:Ss,crypto_box_NONCEBYTES:ns,crypto_box_ZEROBYTES:Nr,crypto_box_BOXZEROBYTES:bs,crypto_sign_BYTES:dt,crypto_sign_PUBLICKEYBYTES:yi,crypto_sign_SECRETKEYBYTES:ji,crypto_sign_SEEDBYTES:ws,crypto_hash_BYTES:Gs,gf:i,D:m,L:rs,pack25519:se,unpack25519:Mt,M:Ae,A:ut,S:at,Z:je,pow2523:Ni,add:vi,set25519:A,modL:Ui,scalarmult:ss,scalarbase:it};function Qt(p,S){if(p.length!==Kt)throw new Error("bad key size");if(S.length!==Wi)throw new Error("bad nonce size")}function bn(p,S){if(p.length!==Oi)throw new Error("bad public key size");if(S.length!==Gi)throw new Error("bad secret key size")}function Yt(){for(var p=0;p<arguments.length;p++)if(!(arguments[p]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function js(p){for(var S=0;S<p.length;S++)p[S]=0}t.randomBytes=function(p){var S=new Uint8Array(p);return n(S,p),S},t.secretbox=function(p,S,y){Yt(p,S,y),Qt(y,S);for(var u=new Uint8Array(Fi+p.length),w=new Uint8Array(u.length),T=0;T<p.length;T++)u[T+Fi]=p[T];return re(w,u,u.length,S,y),w.subarray(Mi)},t.secretbox.open=function(p,S,y){Yt(p,S,y),Qt(y,S);for(var u=new Uint8Array(Mi+p.length),w=new Uint8Array(u.length),T=0;T<p.length;T++)u[T+Mi]=p[T];return u.length<32||oe(w,u,u.length,S,y)!==0?null:w.subarray(Fi)},t.secretbox.keyLength=Kt,t.secretbox.nonceLength=Wi,t.secretbox.overheadLength=Mi,t.scalarMult=function(p,S){if(Yt(p,S),p.length!==qi)throw new Error("bad n size");if(S.length!==zi)throw new Error("bad p size");var y=new Uint8Array(zi);return qt(y,p,S),y},t.scalarMult.base=function(p){if(Yt(p),p.length!==qi)throw new Error("bad n size");var S=new Uint8Array(zi);return ai(S,p),S},t.scalarMult.scalarLength=qi,t.scalarMult.groupElementLength=zi,t.box=function(p,S,y,u){var w=t.box.before(y,u);return t.secretbox(p,S,w)},t.box.before=function(p,S){Yt(p,S),bn(p,S);var y=new Uint8Array(Ss);return Gt(y,p,S),y},t.box.after=t.secretbox,t.box.open=function(p,S,y,u){var w=t.box.before(y,u);return t.secretbox.open(p,S,w)},t.box.open.after=t.secretbox.open,t.box.keyPair=function(){var p=new Uint8Array(Oi),S=new Uint8Array(Gi);return fi(p,S),{publicKey:p,secretKey:S}},t.box.keyPair.fromSecretKey=function(p){if(Yt(p),p.length!==Gi)throw new Error("bad secret key size");var S=new Uint8Array(Oi);return ai(S,p),{publicKey:S,secretKey:new Uint8Array(p)}},t.box.publicKeyLength=Oi,t.box.secretKeyLength=Gi,t.box.sharedKeyLength=Ss,t.box.nonceLength=ns,t.box.overheadLength=t.secretbox.overheadLength,t.sign=function(p,S){if(Yt(p,S),S.length!==ji)throw new Error("bad secret key size");var y=new Uint8Array(dt+p.length);return qs(y,p,p.length,S),y},t.sign.open=function(p,S){if(Yt(p,S),S.length!==yi)throw new Error("bad public key size");var y=new Uint8Array(p.length),u=bt(y,p,p.length,S);if(u<0)return null;for(var w=new Uint8Array(u),T=0;T<w.length;T++)w[T]=y[T];return w},t.sign.detached=function(p,S){for(var y=t.sign(p,S),u=new Uint8Array(dt),w=0;w<u.length;w++)u[w]=y[w];return u},t.sign.detached.verify=function(p,S,y){if(Yt(p,S,y),S.length!==dt)throw new Error("bad signature size");if(y.length!==yi)throw new Error("bad public key size");var u=new Uint8Array(dt+p.length),w=new Uint8Array(dt+p.length),T;for(T=0;T<dt;T++)u[T]=S[T];for(T=0;T<p.length;T++)u[T+dt]=p[T];return bt(w,u,u.length,y)>=0},t.sign.keyPair=function(){var p=new Uint8Array(yi),S=new Uint8Array(ji);return vs(p,S),{publicKey:p,secretKey:S}},t.sign.keyPair.fromSecretKey=function(p){if(Yt(p),p.length!==ji)throw new Error("bad secret key size");for(var S=new Uint8Array(yi),y=0;y<S.length;y++)S[y]=p[32+y];return{publicKey:S,secretKey:new Uint8Array(p)}},t.sign.keyPair.fromSeed=function(p){if(Yt(p),p.length!==ws)throw new Error("bad seed size");for(var S=new Uint8Array(yi),y=new Uint8Array(ji),u=0;u<32;u++)y[u]=p[u];return vs(S,y,!0),{publicKey:S,secretKey:y}},t.sign.publicKeyLength=yi,t.sign.secretKeyLength=ji,t.sign.seedLength=ws,t.sign.signatureLength=dt,t.hash=function(p){Yt(p);var S=new Uint8Array(Gs);return gi(S,p,p.length),S},t.hash.hashLength=Gs,t.verify=function(p,S){return Yt(p,S),p.length===0||S.length===0||p.length!==S.length?!1:U(p,0,S,0,p.length)===0},t.setPRNG=function(p){n=p},(function(){var p=typeof self<"u"?self.crypto||self.msCrypto:null;if(p&&p.getRandomValues){var S=65536;t.setPRNG(function(y,u){var w,T=new Uint8Array(u);for(w=0;w<u;w+=S)p.getRandomValues(T.subarray(w,w+Math.min(u-w,S)));for(w=0;w<u;w++)y[w]=T[w];js(T)})}else typeof uf<"u"&&(p=_f,p&&p.randomBytes&&t.setPRNG(function(y,u){var w,T=p.randomBytes(u);for(w=0;w<u;w++)y[w]=T[w];js(T)}))})()})(e.exports?e.exports:self.nacl=self.nacl||{})})($n)),$n.exports}var pf=gf();const ho=sf(pf),Hs=24,mf=16;function vf(e,t){const i=ho.randomBytes(Hs),n=ho.secretbox(e,i,t),a=new Uint8Array(Hs+n.length);return a.set(i),a.set(n,Hs),a}function yf(e,t){if(e.length<Hs+mf)throw new Error("Sealed data too short");const i=e.slice(0,Hs),n=e.slice(Hs),a=ho.secretbox.open(n,i,t);if(!a)throw new Error("Decryption failed - data may be tampered with");return a}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Sf(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function co(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function pn(e,...t){if(!Sf(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function da(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");co(e.outputLen),co(e.blockLen)}function an(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function bf(e,t){pn(e);const i=t.outputLen;if(e.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}function br(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Vn(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function wi(e,t){return e<<32-t|e>>>t}function wf(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function wr(e){return typeof e=="string"&&(e=wf(e)),pn(e),e}class zh{}function Cf(e){const t=n=>e().update(wr(n)).digest(),i=e();return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=()=>e(),t}function xf(e,t,i,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,i,n);const a=BigInt(32),h=BigInt(4294967295),d=Number(i>>a&h),g=Number(i&h),v=n?4:0,m=n?0:4;e.setUint32(t+v,d,n),e.setUint32(t+m,g,n)}function kf(e,t,i){return e&t^~e&i}function Ef(e,t,i){return e&t^e&i^t&i}class Rf extends zh{constructor(t,i,n,a){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=i,this.padOffset=n,this.isLE=a,this.buffer=new Uint8Array(t),this.view=Vn(this.buffer)}update(t){an(this),t=wr(t),pn(t);const{view:i,buffer:n,blockLen:a}=this,h=t.length;for(let d=0;d<h;){const g=Math.min(a-this.pos,h-d);if(g===a){const v=Vn(t);for(;a<=h-d;d+=a)this.process(v,d);continue}n.set(t.subarray(d,d+g),this.pos),this.pos+=g,d+=g,this.pos===a&&(this.process(i,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){an(this),bf(t,this),this.finished=!0;const{buffer:i,view:n,blockLen:a,isLE:h}=this;let{pos:d}=this;i[d++]=128,br(this.buffer.subarray(d)),this.padOffset>a-d&&(this.process(n,0),d=0);for(let k=d;k<a;k++)i[k]=0;xf(n,a-8,BigInt(this.length*8),h),this.process(n,0);const g=Vn(t),v=this.outputLen;if(v%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const m=v/4,R=this.get();if(m>R.length)throw new Error("_sha2: outputLen bigger than state");for(let k=0;k<m;k++)g.setUint32(4*k,R[k],h)}digest(){const{buffer:t,outputLen:i}=this;this.digestInto(t);const n=t.slice(0,i);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:i,buffer:n,length:a,finished:h,destroyed:d,pos:g}=this;return t.destroyed=d,t.finished=h,t.length=a,t.pos=g,a%i&&t.buffer.set(n),t}clone(){return this._cloneInto()}}const Yi=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Af=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ji=new Uint32Array(64);class Mf extends Rf{constructor(t=32){super(64,t,8,!1),this.A=Yi[0]|0,this.B=Yi[1]|0,this.C=Yi[2]|0,this.D=Yi[3]|0,this.E=Yi[4]|0,this.F=Yi[5]|0,this.G=Yi[6]|0,this.H=Yi[7]|0}get(){const{A:t,B:i,C:n,D:a,E:h,F:d,G:g,H:v}=this;return[t,i,n,a,h,d,g,v]}set(t,i,n,a,h,d,g,v){this.A=t|0,this.B=i|0,this.C=n|0,this.D=a|0,this.E=h|0,this.F=d|0,this.G=g|0,this.H=v|0}process(t,i){for(let k=0;k<16;k++,i+=4)Ji[k]=t.getUint32(i,!1);for(let k=16;k<64;k++){const B=Ji[k-15],L=Ji[k-2],P=wi(B,7)^wi(B,18)^B>>>3,U=wi(L,17)^wi(L,19)^L>>>10;Ji[k]=U+Ji[k-7]+P+Ji[k-16]|0}let{A:n,B:a,C:h,D:d,E:g,F:v,G:m,H:R}=this;for(let k=0;k<64;k++){const B=wi(g,6)^wi(g,11)^wi(g,25),L=R+B+kf(g,v,m)+Af[k]+Ji[k]|0,U=(wi(n,2)^wi(n,13)^wi(n,22))+Ef(n,a,h)|0;R=m,m=v,v=g,g=d+L|0,d=h,h=a,a=n,n=L+U|0}n=n+this.A|0,a=a+this.B|0,h=h+this.C|0,d=d+this.D|0,g=g+this.E|0,v=v+this.F|0,m=m+this.G|0,R=R+this.H|0,this.set(n,a,h,d,g,v,m,R)}roundClean(){br(Ji)}destroy(){this.set(0,0,0,0,0,0,0,0),br(this.buffer)}}const Of=Cf(()=>new Mf),Mr=Of;class qh extends zh{constructor(t,i){super(),this.finished=!1,this.destroyed=!1,da(t);const n=wr(i);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const a=this.blockLen,h=new Uint8Array(a);h.set(n.length>a?t.create().update(n).digest():n);for(let d=0;d<h.length;d++)h[d]^=54;this.iHash.update(h),this.oHash=t.create();for(let d=0;d<h.length;d++)h[d]^=106;this.oHash.update(h),br(h)}update(t){return an(this),this.iHash.update(t),this}digestInto(t){an(this),pn(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:i,iHash:n,finished:a,destroyed:h,blockLen:d,outputLen:g}=this;return t=t,t.finished=a,t.destroyed=h,t.blockLen=d,t.outputLen=g,t.oHash=i._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const fa=(e,t,i)=>new qh(e,t).update(i).digest();fa.create=(e,t)=>new qh(e,t);function Tf(e,t,i){return da(e),i===void 0&&(i=new Uint8Array(e.outputLen)),fa(e,wr(i),wr(t))}const Kn=Uint8Array.from([0]),Pf=Uint8Array.of();function Lf(e,t,i,n=32){da(e),co(n);const a=e.outputLen;if(n>255*a)throw new Error("Length should be <= 255*HashLen");const h=Math.ceil(n/a),d=new Uint8Array(h*a),g=fa.create(e,t),v=g._cloneInto(),m=new Uint8Array(g.outputLen);for(let R=0;R<h;R++)Kn[0]=R+1,v.update(R===0?Pf:m).update(i).update(Kn).digestInto(m),d.set(m,a*R),g._cloneInto(v);return g.destroy(),v.destroy(),br(m,Kn),d.slice(0,n)}const Bf=(e,t,i,n,a)=>Lf(e,Tf(e,t,i),n,a);function If(e){const t=Mr(new TextEncoder().encode(`airloom-session:${e}`));return Array.from(t.slice(0,16),i=>i.toString(16).padStart(2,"0")).join("")}function _a(e,t){const i=new TextEncoder().encode("airloom-v1");return Bf(Mr,e,i,"airloom-encryption",32)}function Df(e){return e.replace(/[-\s]/g,"").toUpperCase()}class Nf{constructor(t,i,n){Qe(this,"_ended",!1);this.id=t,this.sendFn=i,this.meta=n}write(t){if(this._ended)throw new Error("Cannot write after stream has ended");this.sendFn({type:"stream_chunk",id:this.id,data:t})}end(){this._ended||(this._ended=!0,this.sendFn({type:"stream_end",id:this.id}))}get ended(){return this._ended}}class Hf extends Fh.EventEmitter{constructor(i,n){super();Qe(this,"id");Qe(this,"meta");Qe(this,"_ended",!1);this.id=i,this.meta=n}_pushChunk(i){this._ended||this.emit("data",i)}_end(){this._ended||(this._ended=!0,this.emit("end"))}get ended(){return this._ended}}class Uf extends Fh.EventEmitter{constructor(i){super();Qe(this,"adapter");Qe(this,"encryptionKey");Qe(this,"role");Qe(this,"streams",new Map);Qe(this,"_ready",!1);Qe(this,"msgCounter",0);this.adapter=i.adapter,this.encryptionKey=i.encryptionKey??null,this.role=i.role,this.setupHandlers()}setupHandlers(){this.adapter.onMessage(i=>{this.handlePayload(i)}),this.adapter.onPeerJoined(()=>{this.encryptionKey&&(this._ready=!0,this.emit("ready"))}),this.adapter.onPeerLeft(()=>{this._ready=!1,this.emit("peer_left")}),this.adapter.onError(i=>this.emit("error",i)),this.adapter.onDisconnect(()=>this.emit("disconnect"))}handlePayload(i){try{if(!this.encryptionKey){this.emit("error",new Error("Received data but no encryption key"));return}const n=af(i),a=yf(n,this.encryptionKey),h=hf(a);this.handleMessage(h)}catch(n){this.emit("error",n)}}handleMessage(i){switch(i.type){case"message":this.emit("message",i.data);break;case"stream_start":{const n=new Hf(i.id,i.meta);this.streams.set(i.id,n),this.emit("stream",n);break}case"stream_chunk":{const n=this.streams.get(i.id);n&&n._pushChunk(i.data);break}case"stream_end":{const n=this.streams.get(i.id);n&&(n._end(),this.streams.delete(i.id));break}}}sendRaw(i){if(!this.encryptionKey)throw new Error("No encryption key established");const n=lf(i),a=vf(n,this.encryptionKey);this.adapter.send(of(a))}send(i){const n=`msg-${++this.msgCounter}`;this.sendRaw({type:"message",id:n,data:i})}createStream(i){const n=`stream-${++this.msgCounter}`;return this.sendRaw({type:"stream_start",id:n,meta:i}),new Nf(n,a=>this.sendRaw(a),i)}async connect(i){await this.adapter.connect(i,this.role)}get ready(){return this._ready}waitForReady(i=3e4){return this._ready?Promise.resolve():new Promise((n,a)=>{const h=()=>{clearTimeout(m),this.removeListener("ready",d),this.removeListener("error",g),this.removeListener("disconnect",v)},d=()=>{h(),n()},g=R=>{h(),a(R)},v=()=>{h(),a(new Error("Disconnected before ready"))},m=setTimeout(()=>{h(),a(new Error("Timed out waiting for peer"))},i);this.once("ready",d),this.once("error",g),this.once("disconnect",v)})}close(){for(const i of this.streams.values())i._end();this.streams.clear(),this.adapter.close(),this.removeAllListeners()}}class Wf{constructor(t){Qe(this,"ws",null);Qe(this,"url");Qe(this,"_connected",!1);Qe(this,"messageHandlers",[]);Qe(this,"peerJoinedHandlers",[]);Qe(this,"peerLeftHandlers",[]);Qe(this,"errorHandlers",[]);Qe(this,"disconnectHandlers",[]);Qe(this,"reconnectAttempts",0);Qe(this,"maxReconnectAttempts",5);Qe(this,"reconnectTimer",null);Qe(this,"shouldReconnect",!1);Qe(this,"sessionToken",null);Qe(this,"role",null);this.url=t}get connected(){return this._connected}async connect(t,i){return this.sessionToken=t,this.role=i,this.doConnect()}async doConnect(){const t=await this.createWebSocket(this.url);return new Promise((i,n)=>{t.onopen=()=>{this._connected=!0,this.shouldReconnect=!0,this.reconnectAttempts=0;const a=this.role==="host"?{type:"create",sessionToken:this.sessionToken}:{type:"join",sessionToken:this.sessionToken};t.send(JSON.stringify(a)),i()},t.onmessage=a=>{const h=a.data,d=typeof h=="string"?h:typeof Buffer<"u"&&Buffer.isBuffer(h)?h.toString("utf-8"):new TextDecoder().decode(h);try{const g=JSON.parse(d);switch(g.type){case"created":case"joined":break;case"peer_joined":this.peerJoinedHandlers.forEach(v=>v());break;case"peer_left":this.peerLeftHandlers.forEach(v=>v());break;case"forward":this.messageHandlers.forEach(v=>v(g.payload));break;case"error":this.errorHandlers.forEach(v=>v(new Error(g.message)));break}}catch(g){this.errorHandlers.forEach(v=>v(g instanceof Error?g:new Error(String(g))))}},t.onclose=()=>{const a=this._connected;this._connected=!1,a&&this.disconnectHandlers.forEach(h=>h()),this.shouldReconnect&&!this.reconnectTimer&&this.attemptReconnect()},t.onerror=a=>{const h=a instanceof Error?a:new Error("WebSocket error");this.errorHandlers.forEach(d=>d(h)),this._connected||(this.shouldReconnect=!1,n(h))},this.ws=t})}async createWebSocket(t){if(typeof globalThis.WebSocket<"u")return new globalThis.WebSocket(t);try{const{default:i}=await Wh(async()=>{const{default:n}=await import("./browser-2h9wHAy0.js").then(a=>a.b);return{default:n}},[],import.meta.url);return new i(t)}catch{throw new Error('No WebSocket implementation available. Install the "ws" package for Node.js.')}}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts||!this.sessionToken||!this.role)return;this.reconnectAttempts++;const t=Math.min(1e3*Math.pow(2,this.reconnectAttempts-1),3e4);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.doConnect().catch(()=>{})},t)}send(t){!this.ws||!this._connected||this.ws.send(JSON.stringify({type:"forward",payload:t}))}onMessage(t){this.messageHandlers.push(t)}onPeerJoined(t){this.peerJoinedHandlers.push(t)}onPeerLeft(t){this.peerLeftHandlers.push(t)}onError(t){this.errorHandlers.push(t)}onDisconnect(t){this.disconnectHandlers.push(t)}close(){var t;this.shouldReconnect=!1,this.maxReconnectAttempts=0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),(t=this.ws)==null||t.close(),this.ws=null,this._connected=!1}}var Zr={exports:{}};/*@license Copyright 2015-2022 Ably Real-time Ltd (ably.com)
2
2
 
3
3
  Ably JavaScript Library v2.20.0
4
4
  https://github.com/ably/ably-js
5
5
 
6
- Released under the Apache Licence v2.0*/var Ff=Zr.exports,Nl;function zf(){return Nl||(Nl=1,(function(e,t){(function(i,n){e.exports=n()})(Ff,()=>{var i={},n={exports:i},a=Object.defineProperty,h=Object.defineProperties,d=Object.getOwnPropertyDescriptor,g=Object.getOwnPropertyDescriptors,v=Object.getOwnPropertyNames,p=Object.getOwnPropertySymbols,R=Object.prototype.hasOwnProperty,k=Object.prototype.propertyIsEnumerable,B=(s,r,o)=>r in s?a(s,r,{enumerable:!0,configurable:!0,writable:!0,value:o}):s[r]=o,L=(s,r)=>{for(var o in r||(r={}))R.call(r,o)&&B(s,o,r[o]);if(p)for(var o of p(r))k.call(r,o)&&B(s,o,r[o]);return s},P=(s,r)=>h(s,g(r)),U=(s,r)=>{var o={};for(var l in s)R.call(s,l)&&r.indexOf(l)<0&&(o[l]=s[l]);if(s!=null&&p)for(var l of p(s))r.indexOf(l)<0&&k.call(s,l)&&(o[l]=s[l]);return o},Z=(s,r)=>{for(var o in r)a(s,o,{get:r[o],enumerable:!0})},_e=(s,r,o,l)=>{if(r&&typeof r=="object"||typeof r=="function")for(let c of v(r))!R.call(s,c)&&c!==o&&a(s,c,{get:()=>r[c],enumerable:!(l=d(r,c))||l.enumerable});return s},rt=s=>_e(a({},"__esModule",{value:!0}),s),Ne=function(s,r){this[0]=s,this[1]=r},H=(s,r,o)=>{var l=(b,C,O,M)=>{try{var z=o[b](C),q=(C=z.value)instanceof Ne,Q=z.done;Promise.resolve(q?C[0]:C).then(F=>q?l(b==="return"?b:"next",C[1]?{done:F.done,value:F.value}:F,O,M):O({value:F,done:Q})).catch(F=>l("throw",F,O,M))}catch(F){M(F)}},c=b=>_[b]=C=>new Promise((O,M)=>l(b,C,O,M)),_={};return o=o.apply(s,r),_[Symbol.asyncIterator]=()=>_,c("next"),c("throw"),c("return"),_},W={};Z(W,{ErrorInfo:()=>A,Realtime:()=>Dn,Rest:()=>On,default:()=>Jd,makeProtocolMessageFromDeserialized:()=>ll,msgpack:()=>Gn}),n.exports=rt(W);var E=class{},ae=typeof Ki<"u"?Ki:typeof window<"u"?window:self;function be(s,r){return`${s}`.padStart(r?3:2,"0")}function ze(s){return E.Config.logTimestamps?function(r){const o=new Date;s(be(o.getHours())+":"+be(o.getMinutes())+":"+be(o.getSeconds())+"."+be(o.getMilliseconds(),1)+" "+r)}:function(r){s(r)}}var Be=()=>{var s;let r,o;return typeof((s=ae==null?void 0:ae.console)==null?void 0:s.log)=="function"?(r=function(...l){console.log.apply(console,l)},o=console.warn?function(...l){console.warn.apply(console,l)}:r):r=o=function(){},[r,o].map(ze)},xe=class dr{constructor(){this.deprecated=(r,o)=>{this.deprecationWarning(`${r} is deprecated and will be removed in a future version. ${o}`)},this.shouldLog=r=>r<=this.logLevel,this.setLog=(r,o)=>{r!==void 0&&(this.logLevel=r),o!==void 0&&(this.logHandler=this.logErrorHandler=o)},this.logLevel=dr.defaultLogLevel,this.logHandler=dr.defaultLogHandler,this.logErrorHandler=dr.defaultLogErrorHandler}static initLogHandlers(){const[r,o]=Be();this.defaultLogHandler=r,this.defaultLogErrorHandler=o,this.defaultLogger=new dr}static logActionNoStrip(r,o,l,c){r.logAction(o,l,c)}logAction(r,o,l){this.shouldLog(r)&&(r===1?this.logErrorHandler:this.logHandler)("Ably: "+o+": "+l,r)}renamedClientOption(r,o){this.deprecationWarning(`The \`${r}\` client option has been renamed to \`${o}\`. Please update your code to use \`${o}\` instead. \`${r}\` will be removed in a future version.`)}renamedMethod(r,o,l){this.deprecationWarning(`\`${r}\`’s \`${o}\` method has been renamed to \`${l}\`. Please update your code to use \`${l}\` instead. \`${o}\` will be removed in a future version.`)}deprecationWarning(r){this.shouldLog(1)&&this.logErrorHandler(`Ably: Deprecation warning - ${r}`,1)}};xe.defaultLogLevel=1,xe.LOG_NONE=0,xe.LOG_ERROR=1,xe.LOG_MAJOR=2,xe.LOG_MINOR=3,xe.LOG_MICRO=4,xe.logAction=(s,r,o,l)=>{xe.logActionNoStrip(s,r,o,l)};var ce=xe,f=ce,re={};Z(re,{Format:()=>zs,allSame:()=>Dr,allToLowerCase:()=>Wi,allToUpperCase:()=>Fi,arrChooseN:()=>qs,arrDeleteValue:()=>Gt,arrEquals:()=>Nr,arrIntersect:()=>ai,arrIntersectOb:()=>fi,arrPopRandomElement:()=>gi,arrWithoutValue:()=>et,cheapRandStr:()=>Ui,containsValue:()=>Ni,copy:()=>ct,createMissingPluginError:()=>bs,dataSizeBytes:()=>rs,decodeBody:()=>bt,encodeBody:()=>Kt,ensureArray:()=>zt,forInOwnNonNullProperties:()=>Ir,getBackoffCoefficient:()=>Oi,getGlobalObject:()=>Ti,getJitterCoefficient:()=>zi,getRetryTime:()=>qi,inherits:()=>oi,inspectBody:()=>vs,inspectError:()=>it,intersect:()=>qt,isEmpty:()=>ut,isErrorInfoOrPartialErrorInfo:()=>ss,isNil:()=>je,isObject:()=>Mt,keysArray:()=>_i,listenerToAsyncIterator:()=>ji,matchDerivedChannel:()=>Ss,mixin:()=>se,parseQueryString:()=>Hi,prototypicalClone:()=>at,randomString:()=>ys,shallowClone:()=>Ae,shallowEquals:()=>Gi,stringifyValues:()=>ms,throwMissingPluginError:()=>dt,toBase64:()=>ns,toQueryString:()=>vi,valuesArray:()=>Br,whenPromiseSettles:()=>Vt,withTimeoutAsync:()=>yi});function oe(s){let r="["+s.constructor.name;return s.message&&(r+=": "+s.message),s.statusCode&&(r+="; statusCode="+s.statusCode),s.code&&(r+="; code="+s.code),s.cause&&(r+="; cause="+it(s.cause)),s.detail&&Object.keys(s.detail).length>0&&(r+="; detail="+JSON.stringify(s.detail)),s.href&&!(s.message&&s.message.indexOf("help.ably.io")>-1)&&(r+="; see "+s.href+" "),r+="]",r}var A=class uo extends Error{constructor(r,o,l,c,_){super(r),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,uo.prototype),this.code=o,this.statusCode=l,this.cause=c,this.detail=_}toString(){return oe(this)}static fromValues(r){const{message:o,code:l,statusCode:c,detail:_}=r;if(typeof o!="string"||typeof l!="number"||typeof c!="number"||!je(_)&&(typeof _!="object"||Array.isArray(_)))throw new Error("ErrorInfo.fromValues(): invalid values: "+E.Config.inspect(r));const b=Object.assign(new uo(o,l,c,void 0,_),r);return b.code&&!b.href&&(b.href="https://help.ably.io/error/"+b.code),b}},Se=class fo extends Error{constructor(r,o,l,c,_){super(r),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,fo.prototype),this.code=o,this.statusCode=l,this.cause=c,this.detail=_}toString(){return oe(this)}static fromValues(r){const{message:o,code:l,statusCode:c,detail:_}=r;if(typeof o!="string"||!je(l)&&typeof l!="number"||!je(c)&&typeof c!="number"||!je(_)&&(typeof _!="object"||Array.isArray(_)))throw new Error("PartialErrorInfo.fromValues(): invalid values: "+E.Config.inspect(r));const b=Object.assign(new fo(o,l,c,void 0,_),r);return b.code&&!b.href&&(b.href="https://help.ably.io/error/"+b.code),b}};function te(s){return Math.floor(Math.random()*s.length)}function se(s,...r){for(let o=0;o<r.length;o++){const l=r[o];if(!l)break;for(const c in l)Object.prototype.hasOwnProperty.call(l,c)&&(s[c]=l[c])}return s}function ct(s){return se({},s)}function zt(s){return je(s)?[]:Array.isArray(s)?s:[s]}function Mt(s){return Object.prototype.toString.call(s)=="[object Object]"}function ut(s){for(const r in s)return!1;return!0}function je(s){return s==null}function Ae(s){const r=new Object;for(const o in s)r[o]=s[o];return r}function at(s,r){class o{}o.prototype=s;const l=new o;return r&&se(l,r),l}var oi=function(s,r){if(E.Config.inherits){E.Config.inherits(s,r);return}s.super_=r,s.prototype=at(r.prototype,{constructor:s})};function Ni(s,r){for(const o in s)if(s[o]==r)return!0;return!1}function qt(s,r){return Array.isArray(r)?ai(s,r):fi(s,r)}function ai(s,r){const o=[];for(let l=0;l<s.length;l++){const c=s[l];r.indexOf(c)!=-1&&o.push(c)}return o}function fi(s,r){const o=[];for(let l=0;l<s.length;l++){const c=s[l];c in r&&o.push(c)}return o}function Gt(s,r){const o=s.indexOf(r),l=o!=-1;return l&&s.splice(o,1),l}function et(s,r){const o=s.slice();return Gt(o,r),o}function _i(s,r){const o=[];for(const l in s)r&&!Object.prototype.hasOwnProperty.call(s,l)||o.push(l);return o}function Br(s,r){const o=[];for(const l in s)r&&!Object.prototype.hasOwnProperty.call(s,l)||o.push(s[l]);return o}function Ir(s,r){for(const o in s)Object.prototype.hasOwnProperty.call(s,o)&&s[o]&&r(o)}function Dr(s,r){if(s.length===0)return!0;const o=s[0][r];return s.every(function(l){return l[r]===o})}var zs=(s=>(s.msgpack="msgpack",s.json="json",s))(zs||{});function gi(s){return s.splice(te(s),1)[0]}function vi(s){const r=[];if(s)for(const o in s)r.push(encodeURIComponent(o)+"="+encodeURIComponent(s[o]));return r.length?"?"+r.join("&"):""}function ms(s){return Object.fromEntries(Object.entries(s).map(([r,o])=>[r,String(o)]))}function Hi(s){let r;const o=/([^?&=]+)=?([^&]*)/g,l={};for(;r=o.exec(s);)l[decodeURIComponent(r[1])]=decodeURIComponent(r[2]);return l}function ss(s){return typeof s=="object"&&s!==null&&(s instanceof A||s instanceof Se)}function it(s){var r,o;return s instanceof Error||((r=s==null?void 0:s.constructor)==null?void 0:r.name)==="ErrorInfo"||((o=s==null?void 0:s.constructor)==null?void 0:o.name)==="PartialErrorInfo"?s.toString():E.Config.inspect(s)}function vs(s){return E.BufferUtils.isBuffer(s)?s.toString():typeof s=="string"?s:E.Config.inspect(s)}function rs(s){if(E.BufferUtils.isBuffer(s))return E.BufferUtils.byteLength(s);if(typeof s=="string")return E.Config.stringByteSize(s);if(typeof s=="number")return 8;if(typeof s=="boolean")return 1;throw new Error(`Expected input of Utils.dataSizeBytes to be a string, a number, a boolean or a buffer, but was: ${typeof s}`)}function Ui(){return String(Math.random()).substr(2)}var ys=async s=>{const r=await E.Config.getRandomArrayBuffer(s);return E.BufferUtils.base64Encode(r)};function qs(s,r){const o=Math.min(r,s.length),l=s.slice(),c=[];for(let _=0;_<o;_++)c.push(gi(l));return c}function Vt(s,r){s.then(o=>{r==null||r(null,o)}).catch(o=>{r==null||r(o)})}function bt(s,r,o){return o=="msgpack"?(r||dt("MsgPack"),r.decode(s)):JSON.parse(String(s))}function Kt(s,r,o){return o=="msgpack"?(r||dt("MsgPack"),r.encode(s,!0)):JSON.stringify(s)}function Wi(s){return s.map(function(r){return r&&r.toLowerCase()})}function Fi(s){return s.map(function(r){return r&&r.toUpperCase()})}function Oi(s){return Math.min((s+2)/3,2)}function zi(){return 1-Math.random()*.2}function qi(s,r){return s*Oi(r)*zi()}function Ti(){return typeof Ki<"u"?Ki:typeof window<"u"?window:self}function Gi(s,r){return Object.keys(s).every(o=>s[o]===r[o])&&Object.keys(r).every(o=>r[o]===s[o])}function Ss(s){const r=/^(\[([^?]*)(?:(.*))\])?(.+)$/,o=s.match(r);if(!o||!o.length||o.length<5)throw new A("regex match failed",400,40010);if(o[2])throw new A(`cannot use a derived option with a ${o[2]} channel`,400,40010);return{qualifierParam:o[3]||"",channelName:o[4]}}function ns(s){const r=E.BufferUtils,o=r.utf8Encode(s);return r.base64Encode(o)}function Nr(s,r){return s.length===r.length&&s.every(function(o,l){return o===r[l]})}function bs(s){return new A(`${s} plugin not provided`,40019,400)}function dt(s){throw bs(s)}async function yi(s,r=5e3,o="Timeout expired"){const l=new A(o,5e4,500);return Promise.race([s,new Promise((c,_)=>setTimeout(()=>_(l),r))])}function ji(s){return H(this,null,function*(){const r=[];let o=null;const l=s(c=>{if(o){const _=o;o=null,_(c)}else r.push(c)});try{for(;;)if(r.length>0)yield r.shift();else{if(o)throw new A("Concurrent next() calls are not supported",4e4,400);yield yield new Ne(new Promise(_=>{o=_}))}}finally{l()}})}var ws="2.20.0",Gs="ably-js/"+ws,Qt={ENDPOINT:"main",ENVIRONMENT:"",REST_HOST:"rest.ably.io",REALTIME_HOST:"realtime.ably.io",FALLBACK_HOSTS:["main.a.fallback.ably-realtime.com","main.b.fallback.ably-realtime.com","main.c.fallback.ably-realtime.com","main.d.fallback.ably-realtime.com","main.e.fallback.ably-realtime.com"],PORT:80,TLS_PORT:443,TIMEOUTS:{disconnectedRetryTimeout:15e3,suspendedRetryTimeout:3e4,httpRequestTimeout:1e4,httpMaxRetryDuration:15e3,channelRetryTimeout:15e3,fallbackRetryTimeout:6e5,connectionStateTtl:12e4,realtimeRequestTimeout:1e4,recvTimeout:9e4,webSocketConnectTimeout:1e4,webSocketSlowTimeout:4e3},httpMaxRetryCount:3,maxMessageSize:65536,version:ws,protocolVersion:6,agent:Gs,getPort:bn,getHttpScheme:Yt,getPrimaryDomainFromEndpoint:m,getEndpointFallbackHosts:S,getFallbackHosts:u,getHosts:w,checkHost:T,objectifyOptions:X,normaliseOptions:le,defaultGetHeaders:Me,defaultPostHeaders:He};function bn(s,r){return r||s.tls?s.tlsPort:s.port}function Yt(s){return s.tls?"https://":"http://"}function js(s){return s.includes(".")||s.includes("::")||s==="localhost"}function m(s){return js(s)?s:s.startsWith("nonprod:")?`${s.replace("nonprod:","")}.realtime.ably-nonprod.net`:`${s}.realtime.ably.net`}function S(s){if(js(s))return[];if(s.startsWith("nonprod:")){const r=s.replace("nonprod:","");return y(r,"ably-realtime-nonprod.com")}return y(s,"ably-realtime.com")}function y(s,r){return["a","b","c","d","e"].map(o=>`${s}.${o}.fallback.${r}`)}function u(s){const r=s.fallbackHosts,o=typeof s.httpMaxRetryCount<"u"?s.httpMaxRetryCount:Qt.httpMaxRetryCount;return r?qs(r,o):[]}function w(s){return[s.primaryDomain].concat(u(s))}function T(s){if(typeof s!="string")throw new A("host must be a string; was a "+typeof s,4e4,400);if(!s.length)throw new A("host must not be zero-length",4e4,400)}function I(s){const r={};for(const o in Qt.TIMEOUTS)r[o]=s[o]||Qt.TIMEOUTS[o];return r}function G(s){let r=Qt.agent;if(s.agents)for(var o in s.agents)r+=" "+o+"/"+s.agents[o];return r}function X(s,r,o,l,c){if(s===void 0){const b=r?`${o} must be initialized with either a client options object, an Ably API key, or an Ably Token`:`${o} must be initialized with a client options object`;throw f.logAction(l,f.LOG_ERROR,`${o}()`,b),new Error(b)}let _;if(typeof s=="string")if(s.indexOf(":")==-1){if(!r){const b=`${o} cannot be initialized with just an Ably Token; you must provide a client options object with a \`plugins\` property. (Set this Ably Token as the object’s \`token\` property.)`;throw f.logAction(l,f.LOG_ERROR,`${o}()`,b),new Error(b)}_={token:s}}else{if(!r){const b=`${o} cannot be initialized with just an Ably API key; you must provide a client options object with a \`plugins\` property. (Set this Ably API key as the object’s \`key\` property.)`;throw f.logAction(l,f.LOG_ERROR,`${o}()`,b),new Error(b)}_={key:s}}else _=s;return c&&(_=P(L({},_),{plugins:L(L({},c),_.plugins)})),_}function we(s){if(s.endpoint&&(s.environment||s.restHost||s.realtimeHost))throw new A("The `endpoint` option cannot be used in conjunction with the `environment`, `restHost`, or `realtimeHost` options.",40106,400);if(s.environment&&(s.restHost||s.realtimeHost))throw new A("The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",40106,400)}function le(s,r,o){const l=o??f.defaultLogger;s.environment&&l.deprecated("The `environment` client option","Use the `endpoint` client option instead."),s.restHost&&l.deprecated("The `restHost` client option","Use the `endpoint` client option instead."),s.realtimeHost&&l.deprecated("The `realtimeHost` client option","Use the `endpoint` client option instead."),we(s),typeof s.recover=="function"&&s.closeOnUnload===!0&&(f.logAction(l,f.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),s.recover=void 0),"closeOnUnload"in s||(s.closeOnUnload=!s.recover),"queueMessages"in s||(s.queueMessages=!0);const c=s.endpoint||Qt.ENDPOINT;!s.fallbackHosts&&!s.restHost&&!s.realtimeHost&&!s.port&&!s.tlsPort&&(s.fallbackHosts=S(s.environment||c));const _=s.environment&&`${s.environment}.realtime.ably.net`,C=s.restHost||s.realtimeHost||_||m(c);(s.fallbackHosts||[]).concat(C).forEach(T),s.port=s.port||Qt.PORT,s.tlsPort=s.tlsPort||Qt.TLS_PORT,"tls"in s||(s.tls=!0);const O=I(s);r?"useBinaryProtocol"in s?s.useBinaryProtocol=E.Config.supportsBinary&&s.useBinaryProtocol:s.useBinaryProtocol=E.Config.preferBinary:s.useBinaryProtocol=!1;const M={};s.clientId&&(M["X-Ably-ClientId"]=E.BufferUtils.base64Encode(E.BufferUtils.utf8Encode(s.clientId))),"idempotentRestPublishing"in s||(s.idempotentRestPublishing=!0);let z=null,q=s.connectivityCheckUrl;if(s.connectivityCheckUrl){let[F,pe]=s.connectivityCheckUrl.split("?");z=pe?Hi(pe):{},F.indexOf("://")===-1&&(F="https://"+F),q=F}let Q=s.wsConnectivityCheckUrl;return Q&&Q.indexOf("://")===-1&&(Q="wss://"+Q),P(L({},s),{primaryDomain:C,maxMessageSize:s.maxMessageSize||Qt.maxMessageSize,timeouts:O,connectivityCheckParams:z,connectivityCheckUrl:q,wsConnectivityCheckUrl:Q,headers:M})}function Ke(s,r,o){const l=o||{};if(l.cipher){s||dt("Crypto");const c=s.getCipher(l.cipher,r);l.cipher=c.cipherParams,l.channelCipher=c.cipher}else"cipher"in l&&(l.cipher=void 0,l.channelCipher=null);return l}var fe={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},ke={protocolVersion:Qt.protocolVersion};function Me(s,{format:r,protocolVersion:o=ke.protocolVersion}={}){return{accept:fe[r??(s.useBinaryProtocol?"msgpack":"json")],"X-Ably-Version":o.toString(),"Ably-Agent":G(s)}}function He(s,{format:r,protocolVersion:o=ke.protocolVersion}={}){const l=fe[r??(s.useBinaryProtocol?"msgpack":"json")];return{accept:l,"content-type":l,"X-Ably-Version":o.toString(),"Ably-Agent":G(s)}}var J=Qt;function Oe(s){return Object.assign(Qt,s)}var Te=class Gh{constructor(r,o){this.logger=r,this.members=o||[]}call(r,o){for(const l of this.members)if(l)try{l(r,o)}catch(c){f.logAction(this.logger,f.LOG_ERROR,"Multicaster multiple callback handler","Unexpected exception: "+c+"; stack = "+c.stack)}}push(...r){this.members.push(...r)}createPromise(){return new Promise((r,o)=>{this.push((l,c)=>{l?o(l):r(c)})})}resolveAll(r){this.call(null,r)}rejectAll(r){this.call(r)}static create(r,o){const l=new Gh(r,o);return Object.assign((c,_)=>l.call(c,_),{push:c=>l.push(c),createPromise:()=>l.createPromise(),resolveAll:c=>l.resolveAll(c),rejectAll:c=>l.rejectAll(c)})}},Ee=Te,ge=(s=>(s.Get="get",s.Delete="delete",s.Post="post",s.Put="put",s.Patch="patch",s))(ge||{}),ie=ge,he=(s=>(s[s.Success=200]="Success",s[s.NoContent=204]="NoContent",s[s.BadRequest=400]="BadRequest",s[s.Unauthorized=401]="Unauthorized",s[s.Forbidden=403]="Forbidden",s[s.RequestTimeout=408]="RequestTimeout",s[s.InternalServerError=500]="InternalServerError",s))(he||{});function ye(s){return s>=200&&s<400}var ve=he,ne=Math.pow(2,17);function D(){return("000000"+Math.floor(Math.random()*1e16)).slice(-16)}function N(s){return!!s.connection}function K(s){return ss(s)?(s.code||(s.statusCode===403?s.code=40300:(s.code=40170,s.statusCode=401)),s):new A(it(s),s.code||40170,s.statusCode||401)}var j=(s,r)=>{const o=E.BufferUtils,l=o.utf8Encode(s),c=o.utf8Encode(r),_=o.hmacSha256(l,c);return o.base64Encode(_)};function $(s){if(!s)return"";typeof s=="string"&&(s=JSON.parse(s));const r=Object.create(null),o=_i(s,!0);if(!o)return"";o.sort();for(let l=0;l<o.length;l++)r[o[l]]=s[o[l]].sort();return JSON.stringify(r)}function Y(s,r){if(s.authCallback)f.logAction(r,f.LOG_MINOR,"Auth()","using token auth with authCallback");else if(s.authUrl)f.logAction(r,f.LOG_MINOR,"Auth()","using token auth with authUrl");else if(s.key)f.logAction(r,f.LOG_MINOR,"Auth()","using token auth with client-side signing");else if(s.tokenDetails)f.logAction(r,f.LOG_MINOR,"Auth()","using token auth with supplied token only");else{const o="authOptions must include valid authentication parameters";throw f.logAction(r,f.LOG_ERROR,"Auth()",o),new Error(o)}}function Ce(s){return"useTokenAuth"in s&&!s.useTokenAuth}function Ie(s){return s.useTokenAuth||!Ce(s)&&(s.authCallback||s.authUrl||s.token||s.tokenDetails)}function We(s){return!s.key&&!s.authCallback&&!s.authUrl}var Ue=0;function x(){return Ue++}var Ge=class{constructor(s,r){if(this.authOptions={},this.client=s,this.tokenParams=r.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,Ie(r))We(r)&&f.logAction(this.logger,f.LOG_ERROR,"Auth()","Warning: library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),this._saveTokenOptions(r.defaultTokenParams,r),Y(this.authOptions,this.logger);else{if(!r.key){const o="No authentication options provided; need one of: key, authUrl, or authCallback (or for testing only, token or tokenDetails)";throw f.logAction(this.logger,f.LOG_ERROR,"Auth()",o),new A(o,40160,401)}f.logAction(this.logger,f.LOG_MINOR,"Auth()","anonymous, using basic auth"),this._saveBasicOptions(r)}}get logger(){return this.client.logger}async authorize(s,r){if(r&&r.key&&this.authOptions.key!==r.key)throw new A("Unable to update auth options with incompatible key",40102,401);try{let o=await this._forceNewToken(s??null,r??null);return N(this.client)?new Promise((l,c)=>{this.client.connection.connectionManager.onAuthUpdated(o,(_,b)=>_?c(_):l(b))}):o}catch(o){throw this.client.connection&&o.statusCode===ve.Forbidden&&this.client.connection.connectionManager.actOnErrorFromAuthorize(o),o}}async _forceNewToken(s,r){this.tokenDetails=null,this._saveTokenOptions(s,r),Y(this.authOptions,this.logger);try{return this._ensureValidAuthCredentials(!0)}finally{delete this.tokenParams.timestamp,delete this.authOptions.queryTime}}async requestToken(s,r){const o=r||this.authOptions,l=s||ct(this.tokenParams);let c,_=this.client;if(o.authCallback)f.logAction(this.logger,f.LOG_MINOR,"Auth.requestToken()","using token auth with authCallback"),c=o.authCallback;else if(o.authUrl)f.logAction(this.logger,f.LOG_MINOR,"Auth.requestToken()","using token auth with authUrl"),c=(C,O)=>{const M=se({accept:"application/json, text/plain"},o.authHeaders),z=o.authMethod&&o.authMethod.toLowerCase()==="post";let q;const Q=o.authUrl.indexOf("?");Q>-1&&(q=Hi(o.authUrl.slice(Q)),o.authUrl=o.authUrl.slice(0,Q),z||(o.authParams=se(q,o.authParams)));const F=se({},o.authParams||{},C),pe=me=>{var Re,st;let lt=(Re=me.body)!=null?Re:null,_t=null;if(me.error)f.logAction(this.logger,f.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+it(me.error));else{const jt=(st=me.headers["content-type"])!=null?st:null;Array.isArray(jt)?_t=jt.join(", "):_t=jt,f.logAction(this.logger,f.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received; content-type: "+_t+"; body: "+vs(lt))}if(me.error){O(me.error,null);return}if(me.unpacked){O(null,lt);return}if(E.BufferUtils.isBuffer(lt)&&(lt=lt.toString()),!_t){O(new A("authUrl response is missing a content-type header",40170,401),null);return}const De=_t.indexOf("application/json")>-1,si=_t.indexOf("text/plain")>-1||_t.indexOf("application/jwt")>-1;if(!De&&!si){O(new A("authUrl responded with unacceptable content-type "+_t+", should be either text/plain, application/jwt or application/json",40170,401),null);return}if(De){if(lt.length>ne){O(new A("authUrl response exceeded max permitted length",40170,401),null);return}try{lt=JSON.parse(lt)}catch(jt){O(new A("Unexpected error processing authURL response; err = "+jt.message,40170,401),null);return}}O(null,lt,_t)};if(f.logAction(this.logger,f.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Requesting token from "+o.authUrl+"; Params: "+JSON.stringify(F)+"; method: "+(z?"POST":"GET")),z){const me=M||{};me["content-type"]="application/x-www-form-urlencoded";const Re=vi(F).slice(1);Vt(this.client.http.doUri(ie.Post,o.authUrl,me,Re,q),(st,lt)=>pe(st||lt))}else Vt(this.client.http.doUri(ie.Get,o.authUrl,M||{},null,F),(me,Re)=>pe(me||Re))};else if(o.key)f.logAction(this.logger,f.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"),c=(C,O)=>{Vt(this.createTokenRequest(C,o),(M,z)=>O(M,z??null))};else{const C="Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)";throw f.logAction(this.logger,f.LOG_ERROR,"Auth()","library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),new A(C,40171,403)}"capability"in l&&(l.capability=$(l.capability));const b=(C,O)=>{const M=C.keyName,z="/keys/"+M+"/requestToken",q=function(F){return _.baseUri(F)+z},Q=J.defaultPostHeaders(this.client.options,{format:"json"});o.requestHeaders&&se(Q,o.requestHeaders),f.logAction(this.logger,f.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST to "+z+"; Token params: "+JSON.stringify(C)),Vt(this.client.http.do(ie.Post,q,Q,JSON.stringify(C),null),(F,pe)=>F?O(F):O(pe.error,pe.body,pe.unpacked))};return new Promise((C,O)=>{let M=!1,z=this.client.options.timeouts.realtimeRequestTimeout,q=setTimeout(()=>{M=!0;const Q="Token request callback timed out after "+z/1e3+" seconds";f.logAction(this.logger,f.LOG_ERROR,"Auth.requestToken()",Q),O(new A(Q,40170,401))},z);c(l,(Q,F,pe)=>{if(M)return;if(clearTimeout(q),Q){f.logAction(this.logger,f.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+it(Q)),O(K(Q));return}if(typeof F=="string"){F.length===0?O(new A("Token string is empty",40170,401)):F.length>ne?O(new A("Token string exceeded max permitted length (was "+F.length+" bytes)",40170,401)):F==="undefined"||F==="null"?O(new A("Token string was literal null/undefined",40170,401)):F[0]==="{"&&!(pe&&pe.indexOf("application/jwt")>-1)?O(new A("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",40170,401)):C({token:F});return}if(typeof F!="object"||F===null){const Re="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof F;f.logAction(this.logger,f.LOG_ERROR,"Auth.requestToken()",Re),O(new A(Re,40170,401));return}const me=JSON.stringify(F).length;if(me>ne&&!o.suppressMaxLengthCheck){O(new A("Token request/details object exceeded max permitted stringified size (was "+me+" bytes)",40170,401));return}if("issued"in F){C(F);return}if(!("keyName"in F)){const Re="Expected token request callback to call back with a token string, token request object, or token details object";f.logAction(this.logger,f.LOG_ERROR,"Auth.requestToken()",Re),O(new A(Re,40170,401));return}b(F,(Re,st,lt)=>{if(Re){f.logAction(this.logger,f.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+it(Re)),O(K(Re));return}lt||(st=JSON.parse(st)),f.logAction(this.logger,f.LOG_MINOR,"Auth.getToken()","token received"),C(st)})})})}async createTokenRequest(s,r){r=r||this.authOptions,s=s||ct(this.tokenParams);const o=r.key;if(!o)throw new A("No key specified",40101,403);const l=o.split(":"),c=l[0],_=l[1];if(!_)throw new A("Invalid key specified",40101,403);if(s.clientId==="")throw new A("clientId can’t be an empty string",40012,400);"capability"in s&&(s.capability=$(s.capability));const b=se({keyName:c},s),C=s.clientId||"",O=s.ttl||"",M=s.capability||"";b.timestamp||(b.timestamp=await this._getTimestamp(r&&r.queryTime));const z=b.nonce||(b.nonce=D()),q=b.timestamp,Q=b.keyName+`
6
+ Released under the Apache Licence v2.0*/var Ff=Zr.exports,Nl;function zf(){return Nl||(Nl=1,(function(e,t){(function(i,n){e.exports=n()})(Ff,()=>{var i={},n={exports:i},a=Object.defineProperty,h=Object.defineProperties,d=Object.getOwnPropertyDescriptor,g=Object.getOwnPropertyDescriptors,v=Object.getOwnPropertyNames,m=Object.getOwnPropertySymbols,R=Object.prototype.hasOwnProperty,k=Object.prototype.propertyIsEnumerable,B=(s,r,o)=>r in s?a(s,r,{enumerable:!0,configurable:!0,writable:!0,value:o}):s[r]=o,L=(s,r)=>{for(var o in r||(r={}))R.call(r,o)&&B(s,o,r[o]);if(m)for(var o of m(r))k.call(r,o)&&B(s,o,r[o]);return s},P=(s,r)=>h(s,g(r)),U=(s,r)=>{var o={};for(var l in s)R.call(s,l)&&r.indexOf(l)<0&&(o[l]=s[l]);if(s!=null&&m)for(var l of m(s))r.indexOf(l)<0&&k.call(s,l)&&(o[l]=s[l]);return o},Z=(s,r)=>{for(var o in r)a(s,o,{get:r[o],enumerable:!0})},_e=(s,r,o,l)=>{if(r&&typeof r=="object"||typeof r=="function")for(let c of v(r))!R.call(s,c)&&c!==o&&a(s,c,{get:()=>r[c],enumerable:!(l=d(r,c))||l.enumerable});return s},rt=s=>_e(a({},"__esModule",{value:!0}),s),Ne=function(s,r){this[0]=s,this[1]=r},H=(s,r,o)=>{var l=(b,C,O,M)=>{try{var z=o[b](C),q=(C=z.value)instanceof Ne,Q=z.done;Promise.resolve(q?C[0]:C).then(F=>q?l(b==="return"?b:"next",C[1]?{done:F.done,value:F.value}:F,O,M):O({value:F,done:Q})).catch(F=>l("throw",F,O,M))}catch(F){M(F)}},c=b=>_[b]=C=>new Promise((O,M)=>l(b,C,O,M)),_={};return o=o.apply(s,r),_[Symbol.asyncIterator]=()=>_,c("next"),c("throw"),c("return"),_},W={};Z(W,{ErrorInfo:()=>A,Realtime:()=>Dn,Rest:()=>On,default:()=>Jd,makeProtocolMessageFromDeserialized:()=>ll,msgpack:()=>Gn}),n.exports=rt(W);var E=class{},ae=typeof Ki<"u"?Ki:typeof window<"u"?window:self;function be(s,r){return`${s}`.padStart(r?3:2,"0")}function ze(s){return E.Config.logTimestamps?function(r){const o=new Date;s(be(o.getHours())+":"+be(o.getMinutes())+":"+be(o.getSeconds())+"."+be(o.getMilliseconds(),1)+" "+r)}:function(r){s(r)}}var Be=()=>{var s;let r,o;return typeof((s=ae==null?void 0:ae.console)==null?void 0:s.log)=="function"?(r=function(...l){console.log.apply(console,l)},o=console.warn?function(...l){console.warn.apply(console,l)}:r):r=o=function(){},[r,o].map(ze)},xe=class dr{constructor(){this.deprecated=(r,o)=>{this.deprecationWarning(`${r} is deprecated and will be removed in a future version. ${o}`)},this.shouldLog=r=>r<=this.logLevel,this.setLog=(r,o)=>{r!==void 0&&(this.logLevel=r),o!==void 0&&(this.logHandler=this.logErrorHandler=o)},this.logLevel=dr.defaultLogLevel,this.logHandler=dr.defaultLogHandler,this.logErrorHandler=dr.defaultLogErrorHandler}static initLogHandlers(){const[r,o]=Be();this.defaultLogHandler=r,this.defaultLogErrorHandler=o,this.defaultLogger=new dr}static logActionNoStrip(r,o,l,c){r.logAction(o,l,c)}logAction(r,o,l){this.shouldLog(r)&&(r===1?this.logErrorHandler:this.logHandler)("Ably: "+o+": "+l,r)}renamedClientOption(r,o){this.deprecationWarning(`The \`${r}\` client option has been renamed to \`${o}\`. Please update your code to use \`${o}\` instead. \`${r}\` will be removed in a future version.`)}renamedMethod(r,o,l){this.deprecationWarning(`\`${r}\`’s \`${o}\` method has been renamed to \`${l}\`. Please update your code to use \`${l}\` instead. \`${o}\` will be removed in a future version.`)}deprecationWarning(r){this.shouldLog(1)&&this.logErrorHandler(`Ably: Deprecation warning - ${r}`,1)}};xe.defaultLogLevel=1,xe.LOG_NONE=0,xe.LOG_ERROR=1,xe.LOG_MAJOR=2,xe.LOG_MINOR=3,xe.LOG_MICRO=4,xe.logAction=(s,r,o,l)=>{xe.logActionNoStrip(s,r,o,l)};var ce=xe,f=ce,re={};Z(re,{Format:()=>zs,allSame:()=>Dr,allToLowerCase:()=>Wi,allToUpperCase:()=>Fi,arrChooseN:()=>qs,arrDeleteValue:()=>Gt,arrEquals:()=>Nr,arrIntersect:()=>ai,arrIntersectOb:()=>fi,arrPopRandomElement:()=>gi,arrWithoutValue:()=>et,cheapRandStr:()=>Ui,containsValue:()=>Ni,copy:()=>ct,createMissingPluginError:()=>bs,dataSizeBytes:()=>rs,decodeBody:()=>bt,encodeBody:()=>Kt,ensureArray:()=>zt,forInOwnNonNullProperties:()=>Ir,getBackoffCoefficient:()=>Mi,getGlobalObject:()=>Oi,getJitterCoefficient:()=>zi,getRetryTime:()=>qi,inherits:()=>oi,inspectBody:()=>vs,inspectError:()=>it,intersect:()=>qt,isEmpty:()=>ut,isErrorInfoOrPartialErrorInfo:()=>ss,isNil:()=>je,isObject:()=>Mt,keysArray:()=>_i,listenerToAsyncIterator:()=>ji,matchDerivedChannel:()=>Ss,mixin:()=>se,parseQueryString:()=>Hi,prototypicalClone:()=>at,randomString:()=>ys,shallowClone:()=>Ae,shallowEquals:()=>Gi,stringifyValues:()=>ms,throwMissingPluginError:()=>dt,toBase64:()=>ns,toQueryString:()=>vi,valuesArray:()=>Br,whenPromiseSettles:()=>Vt,withTimeoutAsync:()=>yi});function oe(s){let r="["+s.constructor.name;return s.message&&(r+=": "+s.message),s.statusCode&&(r+="; statusCode="+s.statusCode),s.code&&(r+="; code="+s.code),s.cause&&(r+="; cause="+it(s.cause)),s.detail&&Object.keys(s.detail).length>0&&(r+="; detail="+JSON.stringify(s.detail)),s.href&&!(s.message&&s.message.indexOf("help.ably.io")>-1)&&(r+="; see "+s.href+" "),r+="]",r}var A=class uo extends Error{constructor(r,o,l,c,_){super(r),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,uo.prototype),this.code=o,this.statusCode=l,this.cause=c,this.detail=_}toString(){return oe(this)}static fromValues(r){const{message:o,code:l,statusCode:c,detail:_}=r;if(typeof o!="string"||typeof l!="number"||typeof c!="number"||!je(_)&&(typeof _!="object"||Array.isArray(_)))throw new Error("ErrorInfo.fromValues(): invalid values: "+E.Config.inspect(r));const b=Object.assign(new uo(o,l,c,void 0,_),r);return b.code&&!b.href&&(b.href="https://help.ably.io/error/"+b.code),b}},Se=class fo extends Error{constructor(r,o,l,c,_){super(r),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,fo.prototype),this.code=o,this.statusCode=l,this.cause=c,this.detail=_}toString(){return oe(this)}static fromValues(r){const{message:o,code:l,statusCode:c,detail:_}=r;if(typeof o!="string"||!je(l)&&typeof l!="number"||!je(c)&&typeof c!="number"||!je(_)&&(typeof _!="object"||Array.isArray(_)))throw new Error("PartialErrorInfo.fromValues(): invalid values: "+E.Config.inspect(r));const b=Object.assign(new fo(o,l,c,void 0,_),r);return b.code&&!b.href&&(b.href="https://help.ably.io/error/"+b.code),b}};function te(s){return Math.floor(Math.random()*s.length)}function se(s,...r){for(let o=0;o<r.length;o++){const l=r[o];if(!l)break;for(const c in l)Object.prototype.hasOwnProperty.call(l,c)&&(s[c]=l[c])}return s}function ct(s){return se({},s)}function zt(s){return je(s)?[]:Array.isArray(s)?s:[s]}function Mt(s){return Object.prototype.toString.call(s)=="[object Object]"}function ut(s){for(const r in s)return!1;return!0}function je(s){return s==null}function Ae(s){const r=new Object;for(const o in s)r[o]=s[o];return r}function at(s,r){class o{}o.prototype=s;const l=new o;return r&&se(l,r),l}var oi=function(s,r){if(E.Config.inherits){E.Config.inherits(s,r);return}s.super_=r,s.prototype=at(r.prototype,{constructor:s})};function Ni(s,r){for(const o in s)if(s[o]==r)return!0;return!1}function qt(s,r){return Array.isArray(r)?ai(s,r):fi(s,r)}function ai(s,r){const o=[];for(let l=0;l<s.length;l++){const c=s[l];r.indexOf(c)!=-1&&o.push(c)}return o}function fi(s,r){const o=[];for(let l=0;l<s.length;l++){const c=s[l];c in r&&o.push(c)}return o}function Gt(s,r){const o=s.indexOf(r),l=o!=-1;return l&&s.splice(o,1),l}function et(s,r){const o=s.slice();return Gt(o,r),o}function _i(s,r){const o=[];for(const l in s)r&&!Object.prototype.hasOwnProperty.call(s,l)||o.push(l);return o}function Br(s,r){const o=[];for(const l in s)r&&!Object.prototype.hasOwnProperty.call(s,l)||o.push(s[l]);return o}function Ir(s,r){for(const o in s)Object.prototype.hasOwnProperty.call(s,o)&&s[o]&&r(o)}function Dr(s,r){if(s.length===0)return!0;const o=s[0][r];return s.every(function(l){return l[r]===o})}var zs=(s=>(s.msgpack="msgpack",s.json="json",s))(zs||{});function gi(s){return s.splice(te(s),1)[0]}function vi(s){const r=[];if(s)for(const o in s)r.push(encodeURIComponent(o)+"="+encodeURIComponent(s[o]));return r.length?"?"+r.join("&"):""}function ms(s){return Object.fromEntries(Object.entries(s).map(([r,o])=>[r,String(o)]))}function Hi(s){let r;const o=/([^?&=]+)=?([^&]*)/g,l={};for(;r=o.exec(s);)l[decodeURIComponent(r[1])]=decodeURIComponent(r[2]);return l}function ss(s){return typeof s=="object"&&s!==null&&(s instanceof A||s instanceof Se)}function it(s){var r,o;return s instanceof Error||((r=s==null?void 0:s.constructor)==null?void 0:r.name)==="ErrorInfo"||((o=s==null?void 0:s.constructor)==null?void 0:o.name)==="PartialErrorInfo"?s.toString():E.Config.inspect(s)}function vs(s){return E.BufferUtils.isBuffer(s)?s.toString():typeof s=="string"?s:E.Config.inspect(s)}function rs(s){if(E.BufferUtils.isBuffer(s))return E.BufferUtils.byteLength(s);if(typeof s=="string")return E.Config.stringByteSize(s);if(typeof s=="number")return 8;if(typeof s=="boolean")return 1;throw new Error(`Expected input of Utils.dataSizeBytes to be a string, a number, a boolean or a buffer, but was: ${typeof s}`)}function Ui(){return String(Math.random()).substr(2)}var ys=async s=>{const r=await E.Config.getRandomArrayBuffer(s);return E.BufferUtils.base64Encode(r)};function qs(s,r){const o=Math.min(r,s.length),l=s.slice(),c=[];for(let _=0;_<o;_++)c.push(gi(l));return c}function Vt(s,r){s.then(o=>{r==null||r(null,o)}).catch(o=>{r==null||r(o)})}function bt(s,r,o){return o=="msgpack"?(r||dt("MsgPack"),r.decode(s)):JSON.parse(String(s))}function Kt(s,r,o){return o=="msgpack"?(r||dt("MsgPack"),r.encode(s,!0)):JSON.stringify(s)}function Wi(s){return s.map(function(r){return r&&r.toLowerCase()})}function Fi(s){return s.map(function(r){return r&&r.toUpperCase()})}function Mi(s){return Math.min((s+2)/3,2)}function zi(){return 1-Math.random()*.2}function qi(s,r){return s*Mi(r)*zi()}function Oi(){return typeof Ki<"u"?Ki:typeof window<"u"?window:self}function Gi(s,r){return Object.keys(s).every(o=>s[o]===r[o])&&Object.keys(r).every(o=>r[o]===s[o])}function Ss(s){const r=/^(\[([^?]*)(?:(.*))\])?(.+)$/,o=s.match(r);if(!o||!o.length||o.length<5)throw new A("regex match failed",400,40010);if(o[2])throw new A(`cannot use a derived option with a ${o[2]} channel`,400,40010);return{qualifierParam:o[3]||"",channelName:o[4]}}function ns(s){const r=E.BufferUtils,o=r.utf8Encode(s);return r.base64Encode(o)}function Nr(s,r){return s.length===r.length&&s.every(function(o,l){return o===r[l]})}function bs(s){return new A(`${s} plugin not provided`,40019,400)}function dt(s){throw bs(s)}async function yi(s,r=5e3,o="Timeout expired"){const l=new A(o,5e4,500);return Promise.race([s,new Promise((c,_)=>setTimeout(()=>_(l),r))])}function ji(s){return H(this,null,function*(){const r=[];let o=null;const l=s(c=>{if(o){const _=o;o=null,_(c)}else r.push(c)});try{for(;;)if(r.length>0)yield r.shift();else{if(o)throw new A("Concurrent next() calls are not supported",4e4,400);yield yield new Ne(new Promise(_=>{o=_}))}}finally{l()}})}var ws="2.20.0",Gs="ably-js/"+ws,Qt={ENDPOINT:"main",ENVIRONMENT:"",REST_HOST:"rest.ably.io",REALTIME_HOST:"realtime.ably.io",FALLBACK_HOSTS:["main.a.fallback.ably-realtime.com","main.b.fallback.ably-realtime.com","main.c.fallback.ably-realtime.com","main.d.fallback.ably-realtime.com","main.e.fallback.ably-realtime.com"],PORT:80,TLS_PORT:443,TIMEOUTS:{disconnectedRetryTimeout:15e3,suspendedRetryTimeout:3e4,httpRequestTimeout:1e4,httpMaxRetryDuration:15e3,channelRetryTimeout:15e3,fallbackRetryTimeout:6e5,connectionStateTtl:12e4,realtimeRequestTimeout:1e4,recvTimeout:9e4,webSocketConnectTimeout:1e4,webSocketSlowTimeout:4e3},httpMaxRetryCount:3,maxMessageSize:65536,version:ws,protocolVersion:6,agent:Gs,getPort:bn,getHttpScheme:Yt,getPrimaryDomainFromEndpoint:p,getEndpointFallbackHosts:S,getFallbackHosts:u,getHosts:w,checkHost:T,objectifyOptions:X,normaliseOptions:le,defaultGetHeaders:Me,defaultPostHeaders:He};function bn(s,r){return r||s.tls?s.tlsPort:s.port}function Yt(s){return s.tls?"https://":"http://"}function js(s){return s.includes(".")||s.includes("::")||s==="localhost"}function p(s){return js(s)?s:s.startsWith("nonprod:")?`${s.replace("nonprod:","")}.realtime.ably-nonprod.net`:`${s}.realtime.ably.net`}function S(s){if(js(s))return[];if(s.startsWith("nonprod:")){const r=s.replace("nonprod:","");return y(r,"ably-realtime-nonprod.com")}return y(s,"ably-realtime.com")}function y(s,r){return["a","b","c","d","e"].map(o=>`${s}.${o}.fallback.${r}`)}function u(s){const r=s.fallbackHosts,o=typeof s.httpMaxRetryCount<"u"?s.httpMaxRetryCount:Qt.httpMaxRetryCount;return r?qs(r,o):[]}function w(s){return[s.primaryDomain].concat(u(s))}function T(s){if(typeof s!="string")throw new A("host must be a string; was a "+typeof s,4e4,400);if(!s.length)throw new A("host must not be zero-length",4e4,400)}function I(s){const r={};for(const o in Qt.TIMEOUTS)r[o]=s[o]||Qt.TIMEOUTS[o];return r}function G(s){let r=Qt.agent;if(s.agents)for(var o in s.agents)r+=" "+o+"/"+s.agents[o];return r}function X(s,r,o,l,c){if(s===void 0){const b=r?`${o} must be initialized with either a client options object, an Ably API key, or an Ably Token`:`${o} must be initialized with a client options object`;throw f.logAction(l,f.LOG_ERROR,`${o}()`,b),new Error(b)}let _;if(typeof s=="string")if(s.indexOf(":")==-1){if(!r){const b=`${o} cannot be initialized with just an Ably Token; you must provide a client options object with a \`plugins\` property. (Set this Ably Token as the object’s \`token\` property.)`;throw f.logAction(l,f.LOG_ERROR,`${o}()`,b),new Error(b)}_={token:s}}else{if(!r){const b=`${o} cannot be initialized with just an Ably API key; you must provide a client options object with a \`plugins\` property. (Set this Ably API key as the object’s \`key\` property.)`;throw f.logAction(l,f.LOG_ERROR,`${o}()`,b),new Error(b)}_={key:s}}else _=s;return c&&(_=P(L({},_),{plugins:L(L({},c),_.plugins)})),_}function we(s){if(s.endpoint&&(s.environment||s.restHost||s.realtimeHost))throw new A("The `endpoint` option cannot be used in conjunction with the `environment`, `restHost`, or `realtimeHost` options.",40106,400);if(s.environment&&(s.restHost||s.realtimeHost))throw new A("The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",40106,400)}function le(s,r,o){const l=o??f.defaultLogger;s.environment&&l.deprecated("The `environment` client option","Use the `endpoint` client option instead."),s.restHost&&l.deprecated("The `restHost` client option","Use the `endpoint` client option instead."),s.realtimeHost&&l.deprecated("The `realtimeHost` client option","Use the `endpoint` client option instead."),we(s),typeof s.recover=="function"&&s.closeOnUnload===!0&&(f.logAction(l,f.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),s.recover=void 0),"closeOnUnload"in s||(s.closeOnUnload=!s.recover),"queueMessages"in s||(s.queueMessages=!0);const c=s.endpoint||Qt.ENDPOINT;!s.fallbackHosts&&!s.restHost&&!s.realtimeHost&&!s.port&&!s.tlsPort&&(s.fallbackHosts=S(s.environment||c));const _=s.environment&&`${s.environment}.realtime.ably.net`,C=s.restHost||s.realtimeHost||_||p(c);(s.fallbackHosts||[]).concat(C).forEach(T),s.port=s.port||Qt.PORT,s.tlsPort=s.tlsPort||Qt.TLS_PORT,"tls"in s||(s.tls=!0);const O=I(s);r?"useBinaryProtocol"in s?s.useBinaryProtocol=E.Config.supportsBinary&&s.useBinaryProtocol:s.useBinaryProtocol=E.Config.preferBinary:s.useBinaryProtocol=!1;const M={};s.clientId&&(M["X-Ably-ClientId"]=E.BufferUtils.base64Encode(E.BufferUtils.utf8Encode(s.clientId))),"idempotentRestPublishing"in s||(s.idempotentRestPublishing=!0);let z=null,q=s.connectivityCheckUrl;if(s.connectivityCheckUrl){let[F,pe]=s.connectivityCheckUrl.split("?");z=pe?Hi(pe):{},F.indexOf("://")===-1&&(F="https://"+F),q=F}let Q=s.wsConnectivityCheckUrl;return Q&&Q.indexOf("://")===-1&&(Q="wss://"+Q),P(L({},s),{primaryDomain:C,maxMessageSize:s.maxMessageSize||Qt.maxMessageSize,timeouts:O,connectivityCheckParams:z,connectivityCheckUrl:q,wsConnectivityCheckUrl:Q,headers:M})}function Ke(s,r,o){const l=o||{};if(l.cipher){s||dt("Crypto");const c=s.getCipher(l.cipher,r);l.cipher=c.cipherParams,l.channelCipher=c.cipher}else"cipher"in l&&(l.cipher=void 0,l.channelCipher=null);return l}var fe={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},ke={protocolVersion:Qt.protocolVersion};function Me(s,{format:r,protocolVersion:o=ke.protocolVersion}={}){return{accept:fe[r??(s.useBinaryProtocol?"msgpack":"json")],"X-Ably-Version":o.toString(),"Ably-Agent":G(s)}}function He(s,{format:r,protocolVersion:o=ke.protocolVersion}={}){const l=fe[r??(s.useBinaryProtocol?"msgpack":"json")];return{accept:l,"content-type":l,"X-Ably-Version":o.toString(),"Ably-Agent":G(s)}}var J=Qt;function Oe(s){return Object.assign(Qt,s)}var Te=class Gh{constructor(r,o){this.logger=r,this.members=o||[]}call(r,o){for(const l of this.members)if(l)try{l(r,o)}catch(c){f.logAction(this.logger,f.LOG_ERROR,"Multicaster multiple callback handler","Unexpected exception: "+c+"; stack = "+c.stack)}}push(...r){this.members.push(...r)}createPromise(){return new Promise((r,o)=>{this.push((l,c)=>{l?o(l):r(c)})})}resolveAll(r){this.call(null,r)}rejectAll(r){this.call(r)}static create(r,o){const l=new Gh(r,o);return Object.assign((c,_)=>l.call(c,_),{push:c=>l.push(c),createPromise:()=>l.createPromise(),resolveAll:c=>l.resolveAll(c),rejectAll:c=>l.rejectAll(c)})}},Ee=Te,ge=(s=>(s.Get="get",s.Delete="delete",s.Post="post",s.Put="put",s.Patch="patch",s))(ge||{}),ie=ge,he=(s=>(s[s.Success=200]="Success",s[s.NoContent=204]="NoContent",s[s.BadRequest=400]="BadRequest",s[s.Unauthorized=401]="Unauthorized",s[s.Forbidden=403]="Forbidden",s[s.RequestTimeout=408]="RequestTimeout",s[s.InternalServerError=500]="InternalServerError",s))(he||{});function ye(s){return s>=200&&s<400}var ve=he,ne=Math.pow(2,17);function D(){return("000000"+Math.floor(Math.random()*1e16)).slice(-16)}function N(s){return!!s.connection}function K(s){return ss(s)?(s.code||(s.statusCode===403?s.code=40300:(s.code=40170,s.statusCode=401)),s):new A(it(s),s.code||40170,s.statusCode||401)}var j=(s,r)=>{const o=E.BufferUtils,l=o.utf8Encode(s),c=o.utf8Encode(r),_=o.hmacSha256(l,c);return o.base64Encode(_)};function $(s){if(!s)return"";typeof s=="string"&&(s=JSON.parse(s));const r=Object.create(null),o=_i(s,!0);if(!o)return"";o.sort();for(let l=0;l<o.length;l++)r[o[l]]=s[o[l]].sort();return JSON.stringify(r)}function Y(s,r){if(s.authCallback)f.logAction(r,f.LOG_MINOR,"Auth()","using token auth with authCallback");else if(s.authUrl)f.logAction(r,f.LOG_MINOR,"Auth()","using token auth with authUrl");else if(s.key)f.logAction(r,f.LOG_MINOR,"Auth()","using token auth with client-side signing");else if(s.tokenDetails)f.logAction(r,f.LOG_MINOR,"Auth()","using token auth with supplied token only");else{const o="authOptions must include valid authentication parameters";throw f.logAction(r,f.LOG_ERROR,"Auth()",o),new Error(o)}}function Ce(s){return"useTokenAuth"in s&&!s.useTokenAuth}function Ie(s){return s.useTokenAuth||!Ce(s)&&(s.authCallback||s.authUrl||s.token||s.tokenDetails)}function We(s){return!s.key&&!s.authCallback&&!s.authUrl}var Ue=0;function x(){return Ue++}var Ge=class{constructor(s,r){if(this.authOptions={},this.client=s,this.tokenParams=r.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,Ie(r))We(r)&&f.logAction(this.logger,f.LOG_ERROR,"Auth()","Warning: library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),this._saveTokenOptions(r.defaultTokenParams,r),Y(this.authOptions,this.logger);else{if(!r.key){const o="No authentication options provided; need one of: key, authUrl, or authCallback (or for testing only, token or tokenDetails)";throw f.logAction(this.logger,f.LOG_ERROR,"Auth()",o),new A(o,40160,401)}f.logAction(this.logger,f.LOG_MINOR,"Auth()","anonymous, using basic auth"),this._saveBasicOptions(r)}}get logger(){return this.client.logger}async authorize(s,r){if(r&&r.key&&this.authOptions.key!==r.key)throw new A("Unable to update auth options with incompatible key",40102,401);try{let o=await this._forceNewToken(s??null,r??null);return N(this.client)?new Promise((l,c)=>{this.client.connection.connectionManager.onAuthUpdated(o,(_,b)=>_?c(_):l(b))}):o}catch(o){throw this.client.connection&&o.statusCode===ve.Forbidden&&this.client.connection.connectionManager.actOnErrorFromAuthorize(o),o}}async _forceNewToken(s,r){this.tokenDetails=null,this._saveTokenOptions(s,r),Y(this.authOptions,this.logger);try{return this._ensureValidAuthCredentials(!0)}finally{delete this.tokenParams.timestamp,delete this.authOptions.queryTime}}async requestToken(s,r){const o=r||this.authOptions,l=s||ct(this.tokenParams);let c,_=this.client;if(o.authCallback)f.logAction(this.logger,f.LOG_MINOR,"Auth.requestToken()","using token auth with authCallback"),c=o.authCallback;else if(o.authUrl)f.logAction(this.logger,f.LOG_MINOR,"Auth.requestToken()","using token auth with authUrl"),c=(C,O)=>{const M=se({accept:"application/json, text/plain"},o.authHeaders),z=o.authMethod&&o.authMethod.toLowerCase()==="post";let q;const Q=o.authUrl.indexOf("?");Q>-1&&(q=Hi(o.authUrl.slice(Q)),o.authUrl=o.authUrl.slice(0,Q),z||(o.authParams=se(q,o.authParams)));const F=se({},o.authParams||{},C),pe=me=>{var Re,st;let lt=(Re=me.body)!=null?Re:null,_t=null;if(me.error)f.logAction(this.logger,f.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+it(me.error));else{const jt=(st=me.headers["content-type"])!=null?st:null;Array.isArray(jt)?_t=jt.join(", "):_t=jt,f.logAction(this.logger,f.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received; content-type: "+_t+"; body: "+vs(lt))}if(me.error){O(me.error,null);return}if(me.unpacked){O(null,lt);return}if(E.BufferUtils.isBuffer(lt)&&(lt=lt.toString()),!_t){O(new A("authUrl response is missing a content-type header",40170,401),null);return}const De=_t.indexOf("application/json")>-1,si=_t.indexOf("text/plain")>-1||_t.indexOf("application/jwt")>-1;if(!De&&!si){O(new A("authUrl responded with unacceptable content-type "+_t+", should be either text/plain, application/jwt or application/json",40170,401),null);return}if(De){if(lt.length>ne){O(new A("authUrl response exceeded max permitted length",40170,401),null);return}try{lt=JSON.parse(lt)}catch(jt){O(new A("Unexpected error processing authURL response; err = "+jt.message,40170,401),null);return}}O(null,lt,_t)};if(f.logAction(this.logger,f.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Requesting token from "+o.authUrl+"; Params: "+JSON.stringify(F)+"; method: "+(z?"POST":"GET")),z){const me=M||{};me["content-type"]="application/x-www-form-urlencoded";const Re=vi(F).slice(1);Vt(this.client.http.doUri(ie.Post,o.authUrl,me,Re,q),(st,lt)=>pe(st||lt))}else Vt(this.client.http.doUri(ie.Get,o.authUrl,M||{},null,F),(me,Re)=>pe(me||Re))};else if(o.key)f.logAction(this.logger,f.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"),c=(C,O)=>{Vt(this.createTokenRequest(C,o),(M,z)=>O(M,z??null))};else{const C="Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)";throw f.logAction(this.logger,f.LOG_ERROR,"Auth()","library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),new A(C,40171,403)}"capability"in l&&(l.capability=$(l.capability));const b=(C,O)=>{const M=C.keyName,z="/keys/"+M+"/requestToken",q=function(F){return _.baseUri(F)+z},Q=J.defaultPostHeaders(this.client.options,{format:"json"});o.requestHeaders&&se(Q,o.requestHeaders),f.logAction(this.logger,f.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST to "+z+"; Token params: "+JSON.stringify(C)),Vt(this.client.http.do(ie.Post,q,Q,JSON.stringify(C),null),(F,pe)=>F?O(F):O(pe.error,pe.body,pe.unpacked))};return new Promise((C,O)=>{let M=!1,z=this.client.options.timeouts.realtimeRequestTimeout,q=setTimeout(()=>{M=!0;const Q="Token request callback timed out after "+z/1e3+" seconds";f.logAction(this.logger,f.LOG_ERROR,"Auth.requestToken()",Q),O(new A(Q,40170,401))},z);c(l,(Q,F,pe)=>{if(M)return;if(clearTimeout(q),Q){f.logAction(this.logger,f.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+it(Q)),O(K(Q));return}if(typeof F=="string"){F.length===0?O(new A("Token string is empty",40170,401)):F.length>ne?O(new A("Token string exceeded max permitted length (was "+F.length+" bytes)",40170,401)):F==="undefined"||F==="null"?O(new A("Token string was literal null/undefined",40170,401)):F[0]==="{"&&!(pe&&pe.indexOf("application/jwt")>-1)?O(new A("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",40170,401)):C({token:F});return}if(typeof F!="object"||F===null){const Re="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof F;f.logAction(this.logger,f.LOG_ERROR,"Auth.requestToken()",Re),O(new A(Re,40170,401));return}const me=JSON.stringify(F).length;if(me>ne&&!o.suppressMaxLengthCheck){O(new A("Token request/details object exceeded max permitted stringified size (was "+me+" bytes)",40170,401));return}if("issued"in F){C(F);return}if(!("keyName"in F)){const Re="Expected token request callback to call back with a token string, token request object, or token details object";f.logAction(this.logger,f.LOG_ERROR,"Auth.requestToken()",Re),O(new A(Re,40170,401));return}b(F,(Re,st,lt)=>{if(Re){f.logAction(this.logger,f.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+it(Re)),O(K(Re));return}lt||(st=JSON.parse(st)),f.logAction(this.logger,f.LOG_MINOR,"Auth.getToken()","token received"),C(st)})})})}async createTokenRequest(s,r){r=r||this.authOptions,s=s||ct(this.tokenParams);const o=r.key;if(!o)throw new A("No key specified",40101,403);const l=o.split(":"),c=l[0],_=l[1];if(!_)throw new A("Invalid key specified",40101,403);if(s.clientId==="")throw new A("clientId can’t be an empty string",40012,400);"capability"in s&&(s.capability=$(s.capability));const b=se({keyName:c},s),C=s.clientId||"",O=s.ttl||"",M=s.capability||"";b.timestamp||(b.timestamp=await this._getTimestamp(r&&r.queryTime));const z=b.nonce||(b.nonce=D()),q=b.timestamp,Q=b.keyName+`
7
7
  `+O+`
8
8
  `+M+`
9
9
  `+C+`
10
10
  `+q+`
11
11
  `+z+`
12
- `;return b.mac=b.mac||j(Q,_),f.logAction(this.logger,f.LOG_MINOR,"Auth.getTokenRequest()","generated signed request"),b}async getAuthParams(){if(this.method=="basic")return{key:this.key};{let s=await this._ensureValidAuthCredentials(!1);if(!s)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{access_token:s.token}}}async getAuthHeaders(){if(this.method=="basic")return{authorization:"Basic "+this.basicKey};{const s=await this._ensureValidAuthCredentials(!1);if(!s)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{authorization:"Bearer "+ns(s.token)}}}_saveBasicOptions(s){this.method="basic",this.key=s.key,this.basicKey=ns(s.key),this.authOptions=s||{},"clientId"in s&&this._userSetClientId(s.clientId)}_saveTokenOptions(s,r){this.method="token",s&&(this.tokenParams=s),r&&(r.token&&(r.tokenDetails=typeof r.token=="string"?{token:r.token}:r.token),r.tokenDetails&&(this.tokenDetails=r.tokenDetails),"clientId"in r&&this._userSetClientId(r.clientId),this.authOptions=r)}async _ensureValidAuthCredentials(s){const r=this.tokenDetails;if(r){if(this._tokenClientIdMismatch(r.clientId))throw new A("Mismatch between clientId in token ("+r.clientId+") and current clientId ("+this.clientId+")",40102,403);if(!this.client.isTimeOffsetSet()||!r.expires||r.expires>=this.client.getTimestampUsingOffset())return f.logAction(this.logger,f.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+r.expires),r;f.logAction(this.logger,f.LOG_MINOR,"Auth.getToken()","deleting expired token"),this.tokenDetails=null}const o=(this.waitingForTokenRequest||(this.waitingForTokenRequest=Ee.create(this.logger))).createPromise();if(this.currentTokenRequestId!==null&&!s)return o;const l=this.currentTokenRequestId=x();let c,_=null;try{c=await this.requestToken(this.tokenParams,this.authOptions)}catch(C){_=C}if(this.currentTokenRequestId>l)return f.logAction(this.logger,f.LOG_MINOR,"Auth._ensureValidAuthCredentials()","Discarding token request response; overtaken by newer one"),o;this.currentTokenRequestId=null;const b=this.waitingForTokenRequest;return this.waitingForTokenRequest=null,_?(b==null||b.rejectAll(_),o):(b==null||b.resolveAll(this.tokenDetails=c),o)}_userSetClientId(s){if(typeof s=="string"||s===null){if(s==="*")throw new A('Can’t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, instantiate the library with {defaultTokenParams: {clientId: "*"}}), or if calling authorize(), pass it in as a tokenParam: authorize({clientId: "*"}, authOptions)',40012,400);{const r=this._uncheckedSetClientId(s);if(r)throw r}}else throw new A("clientId must be either a string or null",40012,400)}_uncheckedSetClientId(s){if(this._tokenClientIdMismatch(s)){const r="Unexpected clientId mismatch: client has "+this.clientId+", requested "+s,o=new A(r,40102,401);return f.logAction(this.logger,f.LOG_ERROR,"Auth._uncheckedSetClientId()",r),o}else return this.clientId=this.tokenParams.clientId=s,null}_tokenClientIdMismatch(s){return!!(this.clientId&&this.clientId!=="*"&&s&&s!=="*"&&this.clientId!==s)}static isTokenErr(s){return s.code&&s.code>=40140&&s.code<40150}revokeTokens(s,r){return this.client.rest.revokeTokens(s,r)}async _getTimestamp(s){return this.client.getTimestamp(s||!!this.authOptions.queryTime)}},Fe=Ge;function Ye(s){const r=[];if(s)for(const o in s)r.push(o+"="+s[o]);return r.join("&")}function Pe(s,r){return s+(r?"?":"")+Ye(r)}function Je(s,r,o,l,c){s.error?f.logActionNoStrip(c,f.LOG_MICRO,"Http."+r+"()","Received Error; "+Pe(o,l)+"; Error: "+it(s.error)):f.logActionNoStrip(c,f.LOG_MICRO,"Http."+r+"()","Received; "+Pe(o,l)+"; Headers: "+Ye(s.headers)+"; StatusCode: "+s.statusCode+"; Body"+(E.BufferUtils.isBuffer(s.body)?" (Base64): "+E.BufferUtils.base64Encode(s.body):": "+s.body))}function Xe(s,r,o,l,c){c.shouldLog(f.LOG_MICRO)&&f.logActionNoStrip(c,f.LOG_MICRO,"Http."+s+"()","Sending; "+Pe(r,l)+"; Body"+(E.BufferUtils.isBuffer(o)?" (Base64): "+E.BufferUtils.base64Encode(o):": "+o))}var gt=class{constructor(s){this.client=s,this.platformHttp=new E.Http(s),this.checkConnectivity=this.platformHttp.checkConnectivity?()=>this.platformHttp.checkConnectivity():void 0}get logger(){var s,r;return(r=(s=this.client)==null?void 0:s.logger)!=null?r:f.defaultLogger}get supportsAuthHeaders(){return this.platformHttp.supportsAuthHeaders}get supportsLinkHeaders(){return this.platformHttp.supportsLinkHeaders}_getHosts(s){const r=s.connection,o=r&&r.connectionManager.host;return o?[o].concat(J.getFallbackHosts(s.options)):J.getHosts(s.options)}async do(s,r,o,l,c){try{const _=this.client;if(!_)return{error:new A("http.do called without client",5e4,500)};const b=typeof r=="function"?r:function(q){return _.baseUri(q)+r},C=_._currentFallback;if(C)if(C.validUntil>Date.now()){const q=await this.doUri(s,b(C.host),o,l,c);return q.error&&this.platformHttp.shouldFallback(q.error)?(_._currentFallback=null,this.do(s,r,o,l,c)):q}else _._currentFallback=null;const O=this._getHosts(_);if(O.length===1)return this.doUri(s,b(O[0]),o,l,c);let M=null;const z=async(q,Q)=>{const F=q.shift();M=M??new Date;const pe=await this.doUri(s,b(F),o,l,c);return pe.error&&this.platformHttp.shouldFallback(pe.error)&&q.length?Date.now()-M.getTime()>_.options.timeouts.httpMaxRetryDuration?{error:new A(`Timeout for trying fallback hosts retries. Total elapsed time exceeded the ${_.options.timeouts.httpMaxRetryDuration}ms limit`,50003,500)}:z(q,!0):(Q&&(_._currentFallback={host:F,validUntil:Date.now()+_.options.timeouts.fallbackRetryTimeout}),pe)};return z(O)}catch(_){return{error:new A(`Unexpected error in Http.do: ${it(_)}`,500,5e4)}}}async doUri(s,r,o,l,c){try{Xe(s,r,l,c,this.logger);const _=await this.platformHttp.doUri(s,r,o,l,c);return this.logger.shouldLog(f.LOG_MICRO)&&Je(_,s,r,c,this.logger),_}catch(_){return{error:new A(`Unexpected error in Http.doUri: ${it(_)}`,500,5e4)}}}};function nt(s,r,o,l){try{o.apply(r,l)}catch(c){f.logAction(s,f.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+c+"; stack = "+(c&&c.stack))}}function ft(s,r,o){let l,c,_;for(let b=0;b<s.length;b++)if(l=s[b],o&&(l=l[o]),Array.isArray(l)){for(;(c=l.indexOf(r))!==-1;)l.splice(c,1);o&&l.length===0&&delete s[b][o]}else if(Mt(l))for(_ in l)Object.prototype.hasOwnProperty.call(l,_)&&Array.isArray(l[_])&&ft([l],r,_)}var mt=class{constructor(s){this.logger=s,this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null)}on(...s){if(s.length===1){const r=s[0];if(typeof r=="function")this.any.push(r);else throw new Error("EventListener.on(): Invalid arguments: "+E.Config.inspect(s))}if(s.length===2){const[r,o]=s;if(typeof o!="function")throw new Error("EventListener.on(): Invalid arguments: "+E.Config.inspect(s));if(je(r))this.any.push(o);else if(Array.isArray(r))r.forEach(l=>{this.on(l,o)});else{if(typeof r!="string")throw new Error("EventListener.on(): Invalid arguments: "+E.Config.inspect(s));(this.events[r]||(this.events[r]=[])).push(o)}}}off(...s){if(s.length==0||je(s[0])&&je(s[1])){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null);return}const[r,o]=s;let l=null,c=null;if(s.length===1||!o)typeof r=="function"?l=r:c=r;else{if(typeof o!="function")throw new Error("EventEmitter.off(): invalid arguments:"+E.Config.inspect(s));[c,l]=[r,o]}if(l&&je(c)){ft([this.any,this.events,this.anyOnce,this.eventsOnce],l);return}if(Array.isArray(c)){c.forEach(_=>{this.off(_,l)});return}if(typeof c!="string")throw new Error("EventEmitter.off(): invalid arguments:"+E.Config.inspect(s));l?ft([this.events,this.eventsOnce],l,c):(delete this.events[c],delete this.eventsOnce[c])}listeners(s){if(s){const r=this.events[s]||[];return this.eventsOnce[s]&&Array.prototype.push.apply(r,this.eventsOnce[s]),r.length?r:null}return this.any.length?this.any:null}emit(s,...r){const o={event:s},l=[];this.anyOnce.length&&(Array.prototype.push.apply(l,this.anyOnce),this.anyOnce=[]),this.any.length&&Array.prototype.push.apply(l,this.any);const c=this.eventsOnce[s];c&&(Array.prototype.push.apply(l,c),delete this.eventsOnce[s]);const _=this.events[s];_&&Array.prototype.push.apply(l,_),l.forEach(b=>{nt(this.logger,o,b,r)})}once(...s){const r=s.length;if(r===0||r===1&&typeof s[0]!="function"){const c=s[0];return new Promise(_=>{this.once(c,_)})}const[o,l]=s;if(s.length===1&&typeof o=="function")this.anyOnce.push(o);else if(je(o)){if(typeof l!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+E.Config.inspect(s));this.anyOnce.push(l)}else if(Array.isArray(o)){const c=this,_=function(){const b=Array.prototype.slice.call(arguments);if(o.forEach(function(C){c.off(C,_)}),typeof l!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+E.Config.inspect(s));l.apply(this,b)};o.forEach(function(b){c.on(b,_)})}else{if(typeof o!="string")throw new Error("EventEmitter.once(): Invalid arguments:"+E.Config.inspect(s));const c=this.eventsOnce[o]||(this.eventsOnce[o]=[]);if(l){if(typeof l!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+E.Config.inspect(s));c.push(l)}}}async whenState(s,r){if(typeof s!="string"||typeof r!="string")throw new Error("whenState requires a valid state String argument");return s===r?null:this.once(s)}},qe=mt,ue={HEARTBEAT:0,ACK:1,NACK:2,CONNECT:3,CONNECTED:4,DISCONNECT:5,DISCONNECTED:6,CLOSE:7,CLOSED:8,ERROR:9,ATTACH:10,ATTACHED:11,DETACH:12,DETACHED:13,PRESENCE:14,MESSAGE:15,SYNC:16,AUTH:17,ACTIVATE:18,OBJECT:19,OBJECT_SYNC:20,ANNOTATION:21},Ot=[];Object.keys(ue).forEach(function(s){Ot[ue[s]]=s});var ot={HAS_PRESENCE:1,HAS_BACKLOG:2,RESUMED:4,TRANSIENT:16,ATTACH_RESUME:32,HAS_OBJECTS:128,PRESENCE:65536,PUBLISH:1<<17,SUBSCRIBE:1<<18,PRESENCE_SUBSCRIBE:1<<19,ANNOTATION_PUBLISH:1<<21,ANNOTATION_SUBSCRIBE:1<<22,OBJECT_SUBSCRIBE:1<<24,OBJECT_PUBLISH:1<<25},Bt=Object.keys(ot);ot.MODE_ALL=ot.PRESENCE|ot.PUBLISH|ot.SUBSCRIBE|ot.PRESENCE_SUBSCRIBE|ot.ANNOTATION_PUBLISH|ot.ANNOTATION_SUBSCRIBE|ot.OBJECT_SUBSCRIBE|ot.OBJECT_PUBLISH;var Ra=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function Vc(s){return!s||!s.channelOptions?{channelOptions:s,plugins:{},baseEncodedPreviousPayload:void 0}:s}function Aa(s,r,o){if(o&&o.cipher){s||dt("Crypto");const l=s.getCipher(o.cipher,r);return{cipher:l.cipherParams,channelCipher:l.cipher}}return o??{}}async function Kc(s,r){const{data:o,encoding:l}=await Ma(s.data,s.encoding,r);return s.data=o,s.encoding=l,s}async function Ma(s,r,o){let l=o.channelCipher,c=s,_=r?r+"/":"";E.BufferUtils.isBuffer(c)||(c=E.BufferUtils.utf8Encode(String(c)),_=_+"utf-8/");const b=await l.encrypt(c);return _=_+"cipher+"+l.algorithm,{data:b,encoding:_}}async function wn(s,r){const{data:o,encoding:l}=Oa(s.data,s.encoding);return s.data=o,s.encoding=l,r!=null&&r.cipher?Kc(s,r):s}function Oa(s,r){if(typeof s=="string"||E.BufferUtils.isBuffer(s)||s===null||s===void 0)return{data:s,encoding:r};if(Mt(s)||Array.isArray(s))return{data:JSON.stringify(s),encoding:r?r+"/json":"json"};throw new A("Data type is unsupported",40013,400)}async function Cn(s,r){const{data:o,encoding:l,error:c}=await Ta(s.data,s.encoding,r);if(s.data=o,s.encoding=l,c)throw c}async function Ta(s,r,o){const l=Vc(o);let c=s,_=s,b=r,C;if(r){const O=r.split("/");let M,z=O.length,q="";try{for(;(M=z)>0;){const Q=O[--z].match(/([-\w]+)(\+([\w-]+))?/);if(!Q)break;switch(q=Q[1],q){case"base64":_=E.BufferUtils.base64Decode(String(_)),M==O.length&&(c=_);continue;case"utf-8":_=E.BufferUtils.utf8Decode(_);continue;case"json":_=JSON.parse(_);continue;case"cipher":if(l.channelOptions!=null&&l.channelOptions.cipher&&l.channelOptions.channelCipher){const F=Q[3],pe=l.channelOptions.channelCipher;if(F!=pe.algorithm)throw new Error("Unable to decrypt message with given cipher; incompatible cipher params");_=await pe.decrypt(_);continue}else throw new Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!l.plugins||!l.plugins.vcdiff)throw new A("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if(typeof Uint8Array>"u")throw new A("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{let F=l.baseEncodedPreviousPayload;typeof F=="string"&&(F=E.BufferUtils.utf8Encode(F));const pe=E.BufferUtils.toBuffer(F);_=E.BufferUtils.toBuffer(_),_=E.BufferUtils.arrayBufferViewToBuffer(l.plugins.vcdiff.decode(_,pe)),c=_}catch(F){throw new A("Vcdiff delta decode failed with "+F,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(Q){const F=Q;C=new A(`Error processing the ${q} encoding, decoder returned ‘${F.message}’`,F.code||40013,400)}finally{b=M<=0?null:O.slice(0,M).join("/")}}return C?{error:C,data:_,encoding:b}:(l.baseEncodedPreviousPayload=c,{data:_,encoding:b})}function xn(...s){const r=s.length>0?"json":"msgpack",{data:o,encoding:l}=Pa(this.data,this.encoding,r);return Object.assign({},this,{encoding:l,data:o})}function Pa(s,r,o){return!s||!E.BufferUtils.isBuffer(s)?{data:s,encoding:r}:o==="msgpack"?{data:E.BufferUtils.toBuffer(s),encoding:r}:{data:E.BufferUtils.base64Encode(s),encoding:r?r+"/base64":"base64"}}var Hr={encryptData:Ma,encodeData:Oa,encodeDataForWire:Pa,decodeData:Ta};function Ur(s){const{id:r,connectionId:o,timestamp:l}=s;let c;switch(s.action){case ue.MESSAGE:{c=s.messages;break}case ue.PRESENCE:case ue.SYNC:c=s.presence;break;case ue.ANNOTATION:c=s.annotations;break;case ue.OBJECT:case ue.OBJECT_SYNC:c=s.state;break;default:throw new A("Unexpected action "+s.action,4e4,400)}for(let _=0;_<c.length;_++){const b=c[_];b.connectionId||(b.connectionId=o),b.timestamp||(b.timestamp=l),r&&!b.id&&(b.id=r+":"+_)}}function Cs(s,r){let o="["+r;for(const l in s)l==="data"?typeof s.data=="string"?o+="; data="+s.data:E.BufferUtils.isBuffer(s.data)?o+="; data (buffer)="+E.BufferUtils.base64Encode(s.data):typeof s.data<"u"&&(o+="; data (json)="+JSON.stringify(s.data)):l&&(l==="extras"||l==="operation")?o+="; "+l+"="+JSON.stringify(s[l]):l==="version"?o+="; version="+JSON.stringify(s[l]):l==="annotations"?o+="; annotations="+JSON.stringify(s[l]):s[l]!==void 0&&(o+="; "+l+"="+s[l]);return o+="]",o}var xs=class{},La=class{constructor(s){this.Platform=E,this.ErrorInfo=A,this.Logger=f,this.Defaults=J,this.Utils=re,this.EventEmitter=qe,this.MessageEncoding=Hr;var r,o,l,c,_,b,C,O,M,z;this._additionalHTTPRequestImplementations=(r=s.plugins)!=null?r:null,this.logger=new f,this.logger.setLog(s.logLevel,s.logHandler),f.logAction(this.logger,f.LOG_MICRO,"BaseClient()","initialized with clientOptions "+E.Config.inspect(s)),this._MsgPack=(l=(o=s.plugins)==null?void 0:o.MsgPack)!=null?l:null;const q=this.options=J.normaliseOptions(s,this._MsgPack,this.logger);if(q.key){const Q=q.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!Q){const F="invalid key parameter";throw f.logAction(this.logger,f.LOG_ERROR,"BaseClient()",F),new A(F,40400,404)}q.keyName=Q[1],q.keySecret=Q[2]}if("clientId"in q)if(typeof q.clientId=="string"||q.clientId===null){if(q.clientId==="*")throw new A('Can’t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, use {defaultTokenParams: {clientId: "*"}})',40012,400)}else throw new A("clientId must be either a string or null",40012,400);f.logAction(this.logger,f.LOG_MINOR,"BaseClient()","started; version = "+J.version),this._currentFallback=null,this.serverTimeOffset=null,this.http=new gt(this),this.auth=new Fe(this,q),this._rest=(c=s.plugins)!=null&&c.Rest?new s.plugins.Rest(this):null,this._Crypto=(b=(_=s.plugins)==null?void 0:_.Crypto)!=null?b:null,this.__FilteredSubscriptions=(O=(C=s.plugins)==null?void 0:C.MessageInteractions)!=null?O:null,this._Annotations=(z=(M=s.plugins)==null?void 0:M.Annotations)!=null?z:null}get rest(){return this._rest||dt("Rest"),this._rest}get _FilteredSubscriptions(){return this.__FilteredSubscriptions||dt("MessageInteractions"),this.__FilteredSubscriptions}get channels(){return this.rest.channels}get push(){return this.rest.push}device(){var s;return(!((s=this.options.plugins)!=null&&s.Push)||!this.push.LocalDevice)&&dt("Push"),this._device||(this._device=this.push.LocalDevice.load(this)),this._device}baseUri(s){return J.getHttpScheme(this.options)+s+":"+J.getPort(this.options,!1)}async stats(s){return this.rest.stats(s)}async time(s){return this.rest.time(s)}async request(s,r,o,l,c,_){return this.rest.request(s,r,o,l,c,_)}batchPublish(s){return this.rest.batchPublish(s)}batchPresence(s){return this.rest.batchPresence(s)}setLog(s){this.logger.setLog(s.level,s.handler)}async getTimestamp(s){return!this.isTimeOffsetSet()&&s?this.time():this.getTimestampUsingOffset()}getTimestampUsingOffset(){return Date.now()+(this.serverTimeOffset||0)}isTimeOffsetSet(){return this.serverTimeOffset!==null}};La.Platform=E;var Ba=La,Yc=class Bs{toJSON(){var r,o,l;return{id:this.id,deviceSecret:this.deviceSecret,platform:this.platform,formFactor:this.formFactor,clientId:this.clientId,metadata:this.metadata,deviceIdentityToken:this.deviceIdentityToken,push:{recipient:(r=this.push)==null?void 0:r.recipient,state:(o=this.push)==null?void 0:o.state,error:(l=this.push)==null?void 0:l.error}}}toString(){var r,o,l,c;let _="[DeviceDetails";return this.id&&(_+="; id="+this.id),this.platform&&(_+="; platform="+this.platform),this.formFactor&&(_+="; formFactor="+this.formFactor),this.clientId&&(_+="; clientId="+this.clientId),this.metadata&&(_+="; metadata="+this.metadata),this.deviceIdentityToken&&(_+="; deviceIdentityToken="+JSON.stringify(this.deviceIdentityToken)),(r=this.push)!=null&&r.recipient&&(_+="; push.recipient="+JSON.stringify(this.push.recipient)),(o=this.push)!=null&&o.state&&(_+="; push.state="+this.push.state),(l=this.push)!=null&&l.error&&(_+="; push.error="+JSON.stringify(this.push.error)),(c=this.push)!=null&&c.metadata&&(_+="; push.metadata="+this.push.metadata),_+="]",_}static toRequestBody(r,o,l){return Kt(r,o,l)}static fromResponseBody(r,o,l){return l&&(r=bt(r,o,l)),Array.isArray(r)?Bs.fromValuesArray(r):Bs.fromValues(r)}static fromValues(r){return r.error=r.error&&A.fromValues(r.error),Object.assign(new Bs,r)}static fromLocalDevice(r){return Object.assign(new Bs,r)}static fromValuesArray(r){const o=r.length,l=new Array(o);for(let c=0;c<o;c++)l[c]=Bs.fromValues(r[c]);return l}},ks=Yc;async function Ia(s,r,o,l){if(s.http.supportsAuthHeaders){const c=await s.auth.getAuthHeaders();return l(se(c,r),o)}else{const c=await s.auth.getAuthParams();return l(r,se(c,o))}}function Jc(s,r,o){if(s.err&&!s.body)return{err:s.err};if(s.statusCode===ve.NoContent)return P(L({},s),{body:[],unpacked:!0});let l=s.body;if(!s.unpacked)try{l=bt(l,r,o)}catch(C){return ss(C)?{err:C}:{err:new Se(it(C),null)}}if(!l)return{err:new Se("unenvelope(): Response body is missing",null)};const{statusCode:c,response:_,headers:b}=l;if(c===void 0)return P(L({},s),{body:l,unpacked:!0});if(c<200||c>=300){let C=_&&_.error||s.err;return C||(C=new Error("Error in unenveloping "+l),C.statusCode=c),{err:C,body:_,headers:b,unpacked:!0,statusCode:c}}return{err:s.err,body:_,headers:b,unpacked:!0,statusCode:c}}function Xc(s,r,o,l,c){s.err?f.logAction(c,f.LOG_MICRO,"Resource."+r+"()","Received Error; "+Pe(o,l)+"; Error: "+it(s.err)):f.logAction(c,f.LOG_MICRO,"Resource."+r+"()","Received; "+Pe(o,l)+"; Headers: "+Ye(s.headers)+"; StatusCode: "+s.statusCode+"; Body: "+(E.BufferUtils.isBuffer(s.body)?" (Base64): "+E.BufferUtils.base64Encode(s.body):": "+E.Config.inspect(s.body)))}var Zc=class Is{static async get(r,o,l,c,_,b){return Is.do(ie.Get,r,o,null,l,c,_,b??!1)}static async delete(r,o,l,c,_,b){return Is.do(ie.Delete,r,o,null,l,c,_,b)}static async post(r,o,l,c,_,b,C){return Is.do(ie.Post,r,o,l,c,_,b,C)}static async patch(r,o,l,c,_,b,C){return Is.do(ie.Patch,r,o,l,c,_,b,C)}static async put(r,o,l,c,_,b,C){return Is.do(ie.Put,r,o,l,c,_,b,C)}static async do(r,o,l,c,_,b,C,O){C&&((b=b||{}).envelope=C);const M=o.logger;async function z(Q,F){var pe;if(M.shouldLog(f.LOG_MICRO)){let Re=c;if(((pe=Q["content-type"])==null?void 0:pe.indexOf("msgpack"))>0)try{o._MsgPack||dt("MsgPack"),Re=o._MsgPack.decode(c)}catch(st){f.logAction(M,f.LOG_MICRO,"Resource."+r+"()","Sending MsgPack Decoding Error: "+it(st))}f.logAction(M,f.LOG_MICRO,"Resource."+r+"()","Sending; "+Pe(l,F)+"; Body: "+Re)}const me=await o.http.do(r,l,Q,c,F);return me.error&&Fe.isTokenErr(me.error)?(await o.auth.authorize(null,null),Ia(o,Q,F,z)):{err:me.error,body:me.body,headers:me.headers,unpacked:me.unpacked,statusCode:me.statusCode}}let q=await Ia(o,_,b,z);if(C&&(q=Jc(q,o._MsgPack,C)),M.shouldLog(f.LOG_MICRO)&&Xc(q,r,l,b,M),O){if(q.err)throw q.err;{const Q=L({},q);return delete Q.err,Q}}return q}},wt=Zc;function Qc(s){const r=s.match(/^\.\/(\w+)\?(.*)$/);return r&&r[2]&&Hi(r[2])}function eu(s){typeof s=="string"&&(s=s.split(","));const r={};for(let o=0;o<s.length;o++){const l=s[o].match(/^\s*<(.+)>;\s*rel="(\w+)"$/);if(l){const c=Qc(l[1]);c&&(r[l[2]]=c)}}return r}function tu(s,r,o){return!(o&&(r||typeof s.code=="number"))}var iu=class{constructor(s,r,o,l,c,_){this.client=s,this.path=r,this.headers=o,this.envelope=l??null,this.bodyHandler=c,this.useHttpPaginatedResponse=_||!1}get logger(){return this.client.logger}async get(s){const r=await wt.get(this.client,this.path,this.headers,s,this.envelope,!1);return this.handlePage(r)}async delete(s){const r=await wt.delete(this.client,this.path,this.headers,s,this.envelope,!1);return this.handlePage(r)}async post(s,r){const o=await wt.post(this.client,this.path,r,this.headers,s,this.envelope,!1);return this.handlePage(o)}async put(s,r){const o=await wt.put(this.client,this.path,r,this.headers,s,this.envelope,!1);return this.handlePage(o)}async patch(s,r){const o=await wt.patch(this.client,this.path,r,this.headers,s,this.envelope,!1);return this.handlePage(o)}async handlePage(s){if(s.err&&tu(s.err,s.body,this.useHttpPaginatedResponse))throw f.logAction(this.logger,f.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+it(s.err)),s.err;let r,o,l;try{r=s.statusCode==ve.NoContent?[]:await this.bodyHandler(s.body,s.headers||{},s.unpacked)}catch(c){throw s.err||c}return s.headers&&(o=s.headers.Link||s.headers.link)&&(l=eu(o)),this.useHttpPaginatedResponse?new su(this,r,s.headers||{},s.statusCode,l,s.err):new Da(this,r,l)}},Da=class{constructor(s,r,o){this.resource=s,this.items=r,this._relParams=o}async first(){if(this.hasFirst())return this.get(this._relParams.first);throw new A("No link to the first page of results",40400,404)}async current(){if(this.hasCurrent())return this.get(this._relParams.current);throw new A("No link to the current page of results",40400,404)}async next(){return this.hasNext()?this.get(this._relParams.next):null}hasFirst(){return this._relParams!=null&&"first"in this._relParams}hasCurrent(){return this._relParams!=null&&"current"in this._relParams}hasNext(){return this._relParams!=null&&"next"in this._relParams}isLast(){return!this.hasNext()}async get(s){const r=this.resource,o=await wt.get(r.client,r.path,r.headers,s,r.envelope,!1);return r.handlePage(o)}},su=class extends Da{constructor(s,r,o,l,c,_){super(s,r,c),this.statusCode=l,this.success=l<300&&l>=200,this.headers=o,this.errorCode=_&&_.code,this.errorMessage=_&&_.message,this.errorDetail=_==null?void 0:_.detail}toJSON(){return{items:this.items,statusCode:this.statusCode,success:this.success,headers:this.headers,errorCode:this.errorCode,errorMessage:this.errorMessage,errorDetail:this.errorDetail}}},pi=iu,Na=class fr{toJSON(){return{channel:this.channel,deviceId:this.deviceId,clientId:this.clientId}}toString(){let r="[PushChannelSubscription";return this.channel&&(r+="; channel="+this.channel),this.deviceId&&(r+="; deviceId="+this.deviceId),this.clientId&&(r+="; clientId="+this.clientId),r+="]",r}static fromResponseBody(r,o,l){return l&&(r=bt(r,o,l)),Array.isArray(r)?fr.fromValuesArray(r):fr.fromValues(r)}static fromValues(r){return Object.assign(new fr,r)}static fromValuesArray(r){const o=r.length,l=new Array(o);for(let c=0;c<o;c++)l[c]=fr.fromValues(r[c]);return l}};Na.toRequestBody=Kt;var ru=Na,Wr=ru,nu=class{constructor(s){var r;this.client=s,this.admin=new ou(s),E.Config.push&&((r=s.options.plugins)!=null&&r.Push)&&(this.stateMachine=new s.options.plugins.Push.ActivationStateMachine(s),this.LocalDevice=s.options.plugins.Push.localDeviceFactory(ks))}async activate(s,r){await new Promise((o,l)=>{var c;if(!((c=this.client.options.plugins)!=null&&c.Push)){l(bs("Push"));return}if(!this.stateMachine){l(new A("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.activatedCallback){l(new A("Activation already in progress",4e4,400));return}this.stateMachine.activatedCallback=_=>{if(_){l(_);return}o()},this.stateMachine.updateFailedCallback=r,this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledActivate(this.stateMachine,s))})}async deactivate(s){await new Promise((r,o)=>{var l;if(!((l=this.client.options.plugins)!=null&&l.Push)){o(bs("Push"));return}if(!this.stateMachine){o(new A("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.deactivatedCallback){o(new A("Deactivation already in progress",4e4,400));return}this.stateMachine.deactivatedCallback=c=>{if(c){o(c);return}r()},this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledDeactivate(this.stateMachine,s))})}},ou=class{constructor(s){this.client=s,this.deviceRegistrations=new au(s),this.channelSubscriptions=new lu(s)}async publish(s,r){const o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",c=J.defaultPostHeaders(o.options),_={},b=se({recipient:s},r);se(c,o.options.headers),o.options.pushFullWait&&se(_,{fullWait:"true"});const C=Kt(b,o._MsgPack,l);await wt.post(o,"/push/publish",C,c,_,null,!0)}},au=class{constructor(s){this.client=s}async save(s){const r=this.client,o=ks.fromValues(s),l=r.options.useBinaryProtocol?"msgpack":"json",c=J.defaultPostHeaders(r.options),_={};se(c,r.options.headers),r.options.pushFullWait&&se(_,{fullWait:"true"});const b=Kt(o,r._MsgPack,l),C=await wt.put(r,"/push/deviceRegistrations/"+encodeURIComponent(s.id),b,c,_,null,!0);return ks.fromResponseBody(C.body,r._MsgPack,C.unpacked?void 0:l)}async get(s){const r=this.client,o=r.options.useBinaryProtocol?"msgpack":"json",l=J.defaultGetHeaders(r.options),c=s.id||s;if(typeof c!="string"||!c.length)throw new A("First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails",4e4,400);se(l,r.options.headers);const _=await wt.get(r,"/push/deviceRegistrations/"+encodeURIComponent(c),l,{},null,!0);return ks.fromResponseBody(_.body,r._MsgPack,_.unpacked?void 0:o)}async list(s){const r=this.client,o=r.options.useBinaryProtocol?"msgpack":"json",l=this.client.http.supportsLinkHeaders?void 0:o,c=J.defaultGetHeaders(r.options);return se(c,r.options.headers),new pi(r,"/push/deviceRegistrations",c,l,async function(_,b,C){return ks.fromResponseBody(_,r._MsgPack,C?void 0:o)}).get(s)}async remove(s){const r=this.client,o=J.defaultGetHeaders(r.options),l={},c=s.id||s;if(typeof c!="string"||!c.length)throw new A("First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails",4e4,400);se(o,r.options.headers),r.options.pushFullWait&&se(l,{fullWait:"true"}),await wt.delete(r,"/push/deviceRegistrations/"+encodeURIComponent(c),o,l,null,!0)}async removeWhere(s){const r=this.client,o=r.options.useBinaryProtocol?"msgpack":"json",l=J.defaultGetHeaders(r.options,{format:o});se(l,r.options.headers),r.options.pushFullWait&&se(s,{fullWait:"true"}),await wt.delete(r,"/push/deviceRegistrations",l,s,null,!0)}},lu=class jh{constructor(r){this.remove=jh.prototype.removeWhere,this.client=r}async save(r){const o=this.client,l=Wr.fromValues(r),c=o.options.useBinaryProtocol?"msgpack":"json",_=J.defaultPostHeaders(o.options),b={};se(_,o.options.headers),o.options.pushFullWait&&se(b,{fullWait:"true"});const C=Kt(l,o._MsgPack,c),O=await wt.post(o,"/push/channelSubscriptions",C,_,b,null,!0);return Wr.fromResponseBody(O.body,o._MsgPack,O.unpacked?void 0:c)}async list(r){const o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",c=this.client.http.supportsLinkHeaders?void 0:l,_=J.defaultGetHeaders(o.options);return se(_,o.options.headers),new pi(o,"/push/channelSubscriptions",_,c,async function(b,C,O){return Wr.fromResponseBody(b,o._MsgPack,O?void 0:l)}).get(r)}async removeWhere(r){const o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",c=J.defaultGetHeaders(o.options,{format:l});se(c,o.options.headers),o.options.pushFullWait&&se(r,{fullWait:"true"}),await wt.delete(o,"/push/channelSubscriptions",c,r,null,!0)}async listChannels(r){const o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",c=this.client.http.supportsLinkHeaders?void 0:l,_=J.defaultGetHeaders(o.options);return se(_,o.options.headers),o.options.pushFullWait&&se(r,{fullWait:"true"}),new pi(o,"/push/channels",_,c,async function(b,C,O){const M=!O&&l?bt(b,o._MsgPack,l):b;for(let z=0;z<M.length;z++)M[z]=String(M[z]);return M}).get(r)}},hu=nu,Ha=["absent","present","enter","leave","update"];async function Ua(s,r,o,l){const c=Aa(r,s,l??null);return $s.fromValues(o).decode(c,s)}async function cu(s,r,o,l){return Promise.all(o.map(function(c){return Ua(s,r,c,l)}))}async function uu(s,r){return $s.fromValues(s).decode(r.channelOptions,r.logger)}async function Wa(s,r){return Promise.all(s.map(function(o){return uu(o,r)}))}var Fa=class _r extends xs{isSynthesized(){return!this.id||!this.connectionId?!0:this.id.substring(this.connectionId.length,0)!==this.connectionId}parseId(){if(!this.id)throw new Error("parseId(): Presence message does not contain an id");const r=this.id.split(":");return{connectionId:r[0],msgSerial:parseInt(r[1],10),index:parseInt(r[2],10)}}async encode(r){const o=Object.assign(new $s,this,{action:Ha.indexOf(this.action||"present")});return wn(o,r)}static fromValues(r){return Object.assign(new _r,r)}static fromValuesArray(r){return r.map(o=>_r.fromValues(o))}static fromData(r){return r instanceof _r?r:_r.fromValues({data:r})}toString(){return Cs(this,"PresenceMessage")}},$s=class _o extends xs{toJSON(...r){return xn.call(this,...r)}static fromValues(r){return Object.assign(new _o,r)}static fromValuesArray(r){return r.map(o=>_o.fromValues(o))}async decode(r,o){const l=Object.assign(new Fa,P(L({},this),{action:Ha[this.action]}));try{await Cn(l,r)}catch(c){f.logAction(o,f.LOG_ERROR,"WirePresenceMessage.decode()",it(c))}return l}toString(){return Cs(this,"WirePresenceMessage")}},$i=Fa,du=class{constructor(s){this.channel=s}get logger(){return this.channel.logger}async get(s){f.logAction(this.logger,f.LOG_MICRO,"RestPresence.get()","channel = "+this.channel.name);const r=this.channel.client,o=r.options.useBinaryProtocol?"msgpack":"json",l=this.channel.client.http.supportsLinkHeaders?void 0:o,c=J.defaultGetHeaders(r.options);return se(c,r.options.headers),new pi(r,this.channel.client.rest.presenceMixin.basePath(this),c,l,async(_,b,C)=>{const O=C?_:bt(_,r._MsgPack,o);return Wa(O,this.channel)}).get(s)}async history(s){return f.logAction(this.logger,f.LOG_MICRO,"RestPresence.history()","channel = "+this.channel.name),this.channel.client.rest.presenceMixin.history(this,s)}},fu=du,za=["message.create","message.update","message.delete","meta","message.summary","message.append"];function _u(s){return za[s||0]||"unknown"}function gu(s){let r=0;return s.name&&(r+=s.name.length),s.clientId&&(r+=s.clientId.length),s.extras&&(r+=JSON.stringify(s.extras).length),s.data&&(r+=rs(s.data)),r}async function qa(s,r,o,l){const c=Aa(r,s,l??null);return Vs.fromValues(o).decode(c,s)}async function pu(s,r,o,l){return Promise.all(o.map(function(c){return qa(s,r,c,l)}))}async function Ga(s,r){return Vs.fromValues(s).decode(r.channelOptions,r.logger)}async function ja(s,r){return Promise.all(s.map(function(o){return Ga(o,r)}))}async function $a(s,r){return Promise.all(s.map(o=>o.encode(r)))}var Va=Kt;function Ka(s){let r,o=0;for(let l=0;l<s.length;l++)r=s[l],o+=r.size||(r.size=gu(r));return o}var Ya=class go extends xs{expandFields(){if(this.version||(this.version={}),!this.version.serial&&this.serial&&(this.version.serial=this.serial),!this.version.timestamp&&this.timestamp&&(this.version.timestamp=this.timestamp),this.annotations?this.annotations.summary||(this.annotations.summary={}):this.annotations={summary:{}},this.annotations&&this.annotations.summary)for(const[r,o]of Object.entries(this.annotations.summary))if(r.endsWith(":distinct.v1")||r.endsWith(":unique.v1")||r.endsWith(":multiple.v1"))for(const[,l]of Object.entries(o))l.clipped||(l.clipped=!1);else r.endsWith(":flag.v1")&&(o.clipped||(o.clipped=!1))}async encode(r){const o=Object.assign(new Vs,this,{action:za.indexOf(this.action||"message.create")});return wn(o,r)}static fromValues(r){return Object.assign(new go,r)}static fromValuesArray(r){return r.map(o=>go.fromValues(o))}toString(){return Cs(this,"Message")}},Vs=class po extends xs{toJSON(...r){return xn.call(this,...r)}static fromValues(r){return Object.assign(new po,r)}static fromValuesArray(r){return r.map(o=>po.fromValues(o))}async decodeWithErr(r,o){const l=Object.assign(new Ya,P(L({},this),{action:_u(this.action)}));let c;try{await Cn(l,r)}catch(_){f.logAction(o,f.LOG_ERROR,"WireMessage.decode()",it(_)),c=_}return l.expandFields(),{decoded:l,err:c}}async decode(r,o){const{decoded:l}=await this.decodeWithErr(r,o);return l}toString(){return Cs(this,"WireMessage")}},Si=Ya,mu=9;function vu(s){return s.every(function(r){return!r.id})}var yu=class{constructor(s,r,o){this._annotations=null;var l,c;f.logAction(s.logger,f.LOG_MINOR,"RestChannel()","started; name = "+r),this.name=r,this.client=s,this.presence=new fu(this),this.channelOptions=Ke((l=s._Crypto)!=null?l:null,this.logger,o),(c=s.options.plugins)!=null&&c.Push&&(this._push=new s.options.plugins.Push.PushChannel(this)),s._Annotations&&(this._annotations=new s._Annotations.RestAnnotations(this))}get annotations(){return this._annotations||dt("Annotations"),this._annotations}get push(){return this._push||dt("Push"),this._push}get logger(){return this.client.logger}setOptions(s){var r;this.channelOptions=Ke((r=this.client._Crypto)!=null?r:null,this.logger,s)}async history(s){return f.logAction(this.logger,f.LOG_MICRO,"RestChannel.history()","channel = "+this.name),this.client.rest.channelMixin.history(this,s)}async publish(...s){const r=s[0],o=s[1];let l,c;if(typeof r=="string"||r===null)l=[Si.fromValues({name:r,data:o})],c=s[2];else if(Mt(r))l=[Si.fromValues(r)],c=s[1];else if(Array.isArray(r))l=Si.fromValuesArray(r),c=s[1];else throw new A("The single-argument form of publish() expects a message object or an array of message objects",40013,400);c||(c={});const _=this.client,b=_.options,C=b.useBinaryProtocol?"msgpack":"json",O=_.options.idempotentRestPublishing,M=J.defaultPostHeaders(_.options);if(se(M,b.headers),O&&vu(l)){const F=await ys(mu);l.forEach(function(pe,me){pe.id=F+":"+me.toString()})}const z=await $a(l,this.channelOptions),q=Ka(z),Q=b.maxMessageSize;if(q>Q)throw new A(`Maximum size of messages that can be published at once exceeded (was ${q} bytes; limit is ${Q} bytes)`,40009,400);return this._publish(Va(z,_._MsgPack,C),M,c)}async _publish(s,r,o){const l=this.client,c=l.options.useBinaryProtocol?"msgpack":"json",{body:_,unpacked:b}=await wt.post(l,l.rest.channelMixin.basePath(this)+"/messages",s,r,o,null,!0),C=(b?_:bt(_,l._MsgPack,c))||{};return delete C.channel,delete C.messageId,C}async status(){return this.client.rest.channelMixin.status(this)}async getMessage(s){return f.logAction(this.logger,f.LOG_MICRO,"RestChannel.getMessage()","channel = "+this.name),this.client.rest.channelMixin.getMessage(this,s)}async updateMessage(s,r,o){return f.logAction(this.logger,f.LOG_MICRO,"RestChannel.updateMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.update",s,r,o)}async deleteMessage(s,r,o){return f.logAction(this.logger,f.LOG_MICRO,"RestChannel.deleteMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.delete",s,r,o)}async appendMessage(s,r,o){return f.logAction(this.logger,f.LOG_MICRO,"RestChannel.appendMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.append",s,r,o)}async getMessageVersions(s,r){return f.logAction(this.logger,f.LOG_MICRO,"RestChannel.getMessageVersions()","channel = "+this.name),this.client.rest.channelMixin.getMessageVersions(this,s,r)}},Su=yu,bu=class $h{constructor(r){this.entries=r&&r.entries||void 0,this.schema=r&&r.schema||void 0,this.appId=r&&r.appId||void 0,this.inProgress=r&&r.inProgress||void 0,this.unit=r&&r.unit||void 0,this.intervalId=r&&r.intervalId||void 0}static fromValues(r){return new $h(r)}},wu=bu,Ja=class{static basePath(s){return"/channels/"+encodeURIComponent(s.name)}static history(s,r){const o=s.client,l=o.options.useBinaryProtocol?"msgpack":"json",c=s.client.http.supportsLinkHeaders?void 0:l,_=J.defaultGetHeaders(o.options);return se(_,o.options.headers),new pi(o,this.basePath(s)+"/messages",_,c,async function(b,C,O){const M=O?b:bt(b,o._MsgPack,l);return ja(M,s)}).get(r)}static async status(s){const r=s.client.options.useBinaryProtocol?"msgpack":"json",o=J.defaultPostHeaders(s.client.options);return(await wt.get(s.client,this.basePath(s),o,{},r,!0)).body}static async getMessage(s,r){const o=typeof r=="string"?r:r.serial;if(!o)throw new A('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);const l=s.client,c=l.options.useBinaryProtocol?"msgpack":"json",_=J.defaultGetHeaders(l.options);se(_,l.options.headers);const{body:b,unpacked:C}=await wt.get(l,this.basePath(s)+"/messages/"+encodeURIComponent(o),_,{},null,!0),O=C?b:bt(b,l._MsgPack,c);return Ga(O,s)}static async updateDeleteMessage(s,r,o,l,c){if(!o.serial)throw new A('This message lacks a serial and cannot be updated. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);const _=s.client,b=_.options.useBinaryProtocol?"msgpack":"json",C=J.defaultPostHeaders(_.options);se(C,_.options.headers);const O=Si.fromValues(o);O.action=r,O.version=l;const M=await O.encode(s.channelOptions),z=Va(M,_._MsgPack,b);let q=wt.patch;const{body:Q,unpacked:F}=await q(_,this.basePath(s)+"/messages/"+encodeURIComponent(o.serial),z,C,c||{},null,!0);return(F?Q:bt(Q,_._MsgPack,b))||{versionSerial:null}}static getMessageVersions(s,r,o){const l=typeof r=="string"?r:r.serial;if(!l)throw new A('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);const c=s.client,_=c.options.useBinaryProtocol?"msgpack":"json",b=s.client.http.supportsLinkHeaders?void 0:_,C=J.defaultGetHeaders(c.options);return se(C,c.options.headers),new pi(c,this.basePath(s)+"/messages/"+encodeURIComponent(l)+"/versions",C,b,async(O,M,z)=>{const q=z?O:bt(O,c._MsgPack,_);return ja(q,s)}).get(o||{})}},Cu=class{static basePath(s){return Ja.basePath(s.channel)+"/presence"}static async history(s,r){const o=s.channel.client,l=o.options.useBinaryProtocol?"msgpack":"json",c=s.channel.client.http.supportsLinkHeaders?void 0:l,_=J.defaultGetHeaders(o.options);return se(_,o.options.headers),new pi(o,this.basePath(s)+"/history",_,c,async(b,C,O)=>{const M=O?b:bt(b,o._MsgPack,l);return Wa(M,s.channel)}).get(r)}},Xa=class{constructor(s){this.channelMixin=Ja,this.presenceMixin=Cu,this.Resource=wt,this.PaginatedResource=pi,this.DeviceDetails=ks,this.PushChannelSubscription=Wr,this.client=s,this.channels=new xu(this.client),this.push=new hu(this.client)}async stats(s){const r=J.defaultGetHeaders(this.client.options),o=this.client.options.useBinaryProtocol?"msgpack":"json",l=this.client.http.supportsLinkHeaders?void 0:o;return se(r,this.client.options.headers),new pi(this.client,"/stats",r,l,async(c,_,b)=>{const C=b?c:bt(c,this.client._MsgPack,o);for(let O=0;O<C.length;O++)C[O]=wu.fromValues(C[O]);return C}).get(s)}async time(s){const r=J.defaultGetHeaders(this.client.options,{format:"json"});this.client.options.headers&&se(r,this.client.options.headers);const o=C=>this.client.baseUri(C)+"/time";let{error:l,body:c,unpacked:_}=await this.client.http.do(ie.Get,o,r,null,s);if(l)throw l;_||(c=JSON.parse(c));const b=c[0];if(!b)throw new A("Internal error (unexpected result type from GET /time)",5e4,500);return this.client.serverTimeOffset=b-Date.now(),b}async request(s,r,o,l,c,_){var b;const[C,O,M]=this.client.options.useBinaryProtocol?(this.client._MsgPack||dt("MsgPack"),[this.client._MsgPack.encode,this.client._MsgPack.decode,"msgpack"]):[JSON.stringify,JSON.parse,"json"],z=this.client.http.supportsLinkHeaders?void 0:M;l=l||{};const q=s.toLowerCase(),Q=q=="get"?J.defaultGetHeaders(this.client.options,{format:M,protocolVersion:o}):J.defaultPostHeaders(this.client.options,{format:M,protocolVersion:o});typeof c!="string"&&(c=(b=C(c))!=null?b:null),se(Q,this.client.options.headers),_&&se(Q,_);const F=new pi(this.client,r,Q,z,async function(pe,me,Re){return zt(Re?pe:O(pe))},!0);if(!E.Http.methods.includes(q))throw new A("Unsupported method "+q,40500,405);return E.Http.methodsWithBody.includes(q)?F[q](l,c):F[q](l)}async batchPublish(s){let r,o;Array.isArray(s)?(r=s,o=!1):(r=[s],o=!0);const l=this.client.options.useBinaryProtocol?"msgpack":"json",c=J.defaultPostHeaders(this.client.options);this.client.options.headers&&se(c,this.client.options.headers);const _=Kt(r,this.client._MsgPack,l),b=await wt.post(this.client,"/messages",_,c,{},null,!0),C=b.unpacked?b.body:bt(b.body,this.client._MsgPack,l);return o?C[0]:C}async batchPresence(s){const r=this.client.options.useBinaryProtocol?"msgpack":"json",o=J.defaultGetHeaders(this.client.options);this.client.options.headers&&se(o,this.client.options.headers);const l=s.join(","),c=await wt.get(this.client,"/presence",o,{channels:l},null,!0);return c.unpacked?c.body:bt(c.body,this.client._MsgPack,r)}async revokeTokens(s,r){if(Ie(this.client.options))throw new A("Cannot revoke tokens when using token auth",40162,401);const o=this.client.options.keyName;let l=r??{};const c=L({targets:s.map(M=>`${M.type}:${M.value}`)},l),_=this.client.options.useBinaryProtocol?"msgpack":"json",b=J.defaultPostHeaders(this.client.options);this.client.options.headers&&se(b,this.client.options.headers);const C=Kt(c,this.client._MsgPack,_),O=await wt.post(this.client,`/keys/${o}/revokeTokens`,C,b,{},null,!0);return O.unpacked?O.body:bt(O.body,this.client._MsgPack,_)}},xu=class{constructor(s){this.client=s,this.all=Object.create(null)}get(s,r){s=String(s);let o=this.all[s];return o?r&&o.setOptions(r):this.all[s]=o=new Su(this.client,s,r),o}release(s){delete this.all[String(s)]}},ku=class extends Ba{constructor(s){super(J.objectifyOptions(s,!1,"BaseRest",f.defaultLogger,{Rest:Xa}))}},Za={Rest:Xa},Qa=class extends Si{static async fromEncoded(s,r){return qa(f.defaultLogger,E.Crypto,s,r)}static async fromEncodedArray(s,r){return pu(f.defaultLogger,E.Crypto,s,r)}static fromValues(s){return Si.fromValues(s)}},el=class extends $i{static async fromEncoded(s,r){return Ua(f.defaultLogger,E.Crypto,s,r)}static async fromEncodedArray(s,r){return cu(f.defaultLogger,E.Crypto,s,r)}static fromValues(s){return $i.fromValues(s)}},tl=["annotation.create","annotation.delete"];async function il(s,r,o){return Es.fromValues(r).decode(o||{},s)}async function Eu(s,r,o){return Promise.all(r.map(function(l){return il(s,l,o)}))}async function Ru(s,r){return Es.fromValues(s).decode(r.channelOptions,r.logger)}async function Au(s,r){return Promise.all(s.map(function(o){return Ru(o,r)}))}var sl=class mo extends xs{async encode(){const r=Object.assign(new Es,this,{action:tl.indexOf(this.action||"annotation.create")});return wn(r,{})}static fromValues(r){return Object.assign(new mo,r)}static fromValuesArray(r){return r.map(o=>mo.fromValues(o))}toString(){return Cs(this,"Annotation")}},Es=class vo extends xs{toJSON(...r){return xn.call(this,...r)}static fromValues(r){return Object.assign(new vo,r)}static fromValuesArray(r){return r.map(o=>vo.fromValues(o))}async decode(r,o){const l=Object.assign(new sl,P(L({},this),{action:tl[this.action]}));try{await Cn(l,r)}catch(c){f.logAction(o,f.LOG_ERROR,"WireAnnotation.decode()",it(c))}return l}toString(){return Cs(this,"WireAnnotation")}},Ks=sl,rl=class extends Ks{static async fromEncoded(s,r){return il(f.defaultLogger,s,r)}static async fromEncodedArray(s,r){return Eu(f.defaultLogger,s,r)}static fromValues(s){return Ks.fromValues(s)}};function nl(s){let r;switch(typeof s){case"string":r=s;break;case"object":r=s.serial;break}if(!r||typeof r!="string")throw new A("First argument of annotations.publish() must be either a Message (or at least an object with a string `serial` property) or a message serial (string)",40003,400);return r}function ol(s,r){const o=nl(s);if(!r||typeof r!="object")throw new A("Second argument of annotations.publish() must be an object (the intended annotation to publish)",40003,400);const l=Ks.fromValues(r);return l.messageSerial=o,l.action||(l.action="annotation.create"),l}function al(s,r){return s.client.rest.channelMixin.basePath(s)+"/messages/"+encodeURIComponent(r)+"/annotations"}var Mu=class{constructor(s){this.channel=s}async publish(s,r){const o=ol(s,r),l=await o.encode(),c=this.channel.client,_=c.options,b=_.useBinaryProtocol?"msgpack":"json",C=J.defaultPostHeaders(c.options),O={};se(C,c.options.headers);const M=Kt([l],c._MsgPack,b);await wt.post(c,al(this.channel,o.messageSerial),M,C,O,null,!0)}async delete(s,r){return r.action="annotation.delete",this.publish(s,r)}async get(s,r){const o=this.channel.client,l=nl(s),c=o.options.useBinaryProtocol?"msgpack":"json",_=o.http.supportsLinkHeaders?void 0:c,b=J.defaultGetHeaders(o.options);return se(b,o.options.headers),new pi(o,al(this.channel,l),b,_,async(C,O,M)=>{const z=M?C:bt(C,o._MsgPack,c);return Au(z,this.channel)}).get(r)}},kn=Mu,Ou=Kt;function Fr(s){const r=[];if(s)for(let o=0;o<s.length;o++)r.push(s[o].toString());return"[ "+r.join(", ")+" ]"}function Tu(s,r,o,l,c,_){const b=bt(s,r,_);return En(b,o,l,c)}function En(s,r,o,l){let c;s.error&&(c=A.fromValues(s.error));let _;s.messages&&(_=Vs.fromValuesArray(s.messages));let b;r&&s.presence&&(b=r.WirePresenceMessage.fromValuesArray(s.presence));let C;o&&s.annotations&&(C=o.WireAnnotation.fromValuesArray(s.annotations));let O;return l&&s.state&&(O=l.WireObjectMessage.fromValuesArray(s.state,re,Hr)),Object.assign(new An,P(L({},s),{presence:b,messages:_,annotations:C,state:O,error:c}))}function ll(s){return r=>{var o;return En(r,{WirePresenceMessage:$s},{WireAnnotation:Es},(o=s==null?void 0:s.LiveObjectsPlugin)!=null?o:null)}}function ei(s){return Object.assign(new An,s)}function Rn(s,r,o,l){let c="[ProtocolMessage";s.action!==void 0&&(c+="; action="+Ot[s.action]||s.action);const _=["id","channel","channelSerial","connectionId","count","msgSerial","timestamp"];let b;for(let C=0;C<_.length;C++)b=_[C],s[b]!==void 0&&(c+="; "+b+"="+s[b]);if(s.messages&&(c+="; messages="+Fr(Vs.fromValuesArray(s.messages))),s.presence&&r&&(c+="; presence="+Fr(r.WirePresenceMessage.fromValuesArray(s.presence))),s.annotations&&o&&(c+="; annotations="+Fr(o.WireAnnotation.fromValuesArray(s.annotations))),s.state&&l&&(c+="; state="+Fr(l.WireObjectMessage.fromValuesArray(s.state,re,Hr))),s.error&&(c+="; error="+A.fromValues(s.error).toString()),s.auth&&s.auth.accessToken&&(c+="; token="+s.auth.accessToken),s.flags&&(c+="; flags="+Bt.filter(s.hasFlag).join(",")),s.params){let C="";Ir(s.params,function(O){C.length>0&&(C+="; "),C+=O+"="+s.params[O]}),C.length>0&&(c+="; params=["+C+"]")}return c+="]",c}var An=class{constructor(){this.hasFlag=s=>(this.flags&ot[s])>0}setFlag(s){return this.flags=this.flags|ot[s]}getMode(){return(this.flags||0)&ot.MODE_ALL}encodeModesToFlags(s){s.forEach(r=>this.setFlag(r))}decodeModesFromFlags(){const s=[];return Ra.forEach(r=>{this.hasFlag(r)&&s.push(r)}),s.length>0?s:void 0}},Pu=An,Lu=class{constructor(s,r,o,l,c){this.previous=s,this.current=r,r==="attached"&&(this.resumed=o,this.hasBacklog=l),c&&(this.reason=c)}},Mn=Lu;function Bu(s){if(s&&"params"in s&&!Mt(s.params))return new A("options.params must be an object",4e4,400);if(s&&"modes"in s){if(!Array.isArray(s.modes))return new A("options.modes must be an array",4e4,400);for(let r=0;r<s.modes.length;r++){const o=s.modes[r];if(!o||typeof o!="string"||!Ra.includes(String.prototype.toUpperCase.call(o)))return new A("Invalid channel mode: "+o,4e4,400)}}}var Iu=class yo extends qe{constructor(r,o,l){var c,_,b;super(r.logger),this._annotations=null,this._mode=0,this.retryCount=0,this.history=async function(C){f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name);const O=this.client.rest.channelMixin;if(C&&C.untilAttach){if(this.state!=="attached")throw new A("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new A("untilAttach was specified and channel is attached, but attachSerial is not defined",4e4,400);delete C.untilAttach,C.from_serial=this.properties.attachSerial}return O.history(this,C)},this.whenState=C=>qe.prototype.whenState.call(this,C,this.state),f.logAction(this.logger,f.LOG_MINOR,"RealtimeChannel()","started; name = "+o),this.name=o,this.channelOptions=Ke((c=r._Crypto)!=null?c:null,this.logger,l),this.client=r,this._presence=r._RealtimePresence?new r._RealtimePresence.RealtimePresence(this):null,r._Annotations&&(this._annotations=new r._Annotations.RealtimeAnnotations(this)),this.connectionManager=r.connection.connectionManager,this.state="initialized",this.subscriptions=new qe(this.logger),this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(l),this.errorReason=null,this._attachResume=!1,this._decodingContext={channelOptions:this.channelOptions,plugins:r.options.plugins||{},baseEncodedPreviousPayload:void 0},this._lastPayload={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},this._attachedReceived=new qe(this.logger),this.internalStateChanges=new qe(this.logger),(_=r.options.plugins)!=null&&_.Push&&(this._push=new r.options.plugins.Push.PushChannel(this)),(b=r.options.plugins)!=null&&b.LiveObjects&&(this._object=new r.options.plugins.LiveObjects.RealtimeObject(this))}get presence(){return this._presence||dt("RealtimePresence"),this._presence}get annotations(){return this._annotations||dt("Annotations"),this._annotations}get push(){return this._push||dt("Push"),this._push}get object(){return this._object||dt("LiveObjects"),this._object}emit(r,...o){super.emit(r,...o),this.internalStateChanges.emit(r,...o)}invalidStateError(){return new A("Channel operation failed as channel state is "+this.state,90001,400,this.errorReason||void 0)}static processListenerArgs(r){return r=Array.prototype.slice.call(r),typeof r[0]=="function"&&r.unshift(null),r}async setOptions(r){var o;const l=this.channelOptions,c=Bu(r);if(c)throw c;if(this.channelOptions=Ke((o=this.client._Crypto)!=null?o:null,this.logger,r),this._decodingContext&&(this._decodingContext.channelOptions=this.channelOptions),this._shouldReattachToSetOptions(r,l))return this.attachImpl(),new Promise((_,b)=>{const C=()=>{this._attachedReceived.off(O),this.internalStateChanges.off(M)},O=()=>{C(),_()},M=z=>{C(),b(z.reason)};this._attachedReceived.once("attached",O),this.internalStateChanges.once(["detached","failed"],M)})}_shouldReattachToSetOptions(r,o){if(!(this.state==="attached"||this.state==="attaching"))return!1;if(r!=null&&r.params){const l=hl(r.params),c=hl(o.params);if(Object.keys(l).length!==Object.keys(c).length||!Gi(c,l))return!0}return!!(r!=null&&r.modes&&(!o.modes||!Nr(r.modes,o.modes)))}async publish(...r){const o=r[0],l=r[1];let c,_;if(typeof o=="string"||o===null||o===void 0)c=[Si.fromValues({name:o,data:l})],_=r[2];else if(Mt(o))c=[Si.fromValues(o)],_=r[1];else if(Array.isArray(o))c=Si.fromValuesArray(o),_=r[1];else throw new A("The single-argument form of publish() expects a message object or an array of message objects",40013,400);const b=this.client.options.maxMessageSize,C=await $a(c,this.channelOptions),O=Ka(C);if(O>b)throw new A(`Maximum size of messages that can be published at once exceeded (was ${O} bytes; limit is ${b} bytes)`,40009,400);this.throwIfUnpublishableState(),f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.publish()","sending message; channel state is "+this.state+", message count = "+C.length);const M=ei({action:ue.MESSAGE,channel:this.name,messages:C,params:_?ms(_):void 0});return this.sendAndAwaitAck(M)}throwIfUnpublishableState(){if(!this.connectionManager.activeState())throw this.connectionManager.getError();if(this.state==="failed"||this.state==="suspended")throw this.invalidStateError()}onEvent(r){f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.onEvent()","received message");const o=this.subscriptions;for(let l=0;l<r.length;l++){const c=r[l];o.emit(c.name,c)}}async attach(){return this.state==="attached"?null:new Promise((r,o)=>{this._attach(!1,null,(l,c)=>l?o(l):r(c))})}_attach(r,o,l){l||(l=_=>{_&&f.logAction(this.logger,f.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+_.toString())});const c=this.connectionManager;if(!c.activeState()){l(c.getError());return}(this.state!=="attaching"||r)&&this.requestState("attaching",o),this.internalStateChanges.once(function(_){switch(this.event){case"attached":l==null||l(null,_);break;case"detached":case"suspended":case"failed":l==null||l(_.reason||c.getError()||new A("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":l==null||l(new A("Attach request superseded by a subsequent detach request",9e4,409));break}})}attachImpl(){f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.attachImpl()","sending ATTACH message");const r=ei({action:ue.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&r.encodeModesToFlags(Fi(this.channelOptions.modes)),this._attachResume&&r.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(r.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.send(r)}async detach(){const r=this.connectionManager;switch(this.state){case"suspended":this.notifyState("detached");return;case"detached":return;case"failed":throw new A("Unable to detach; channel state = failed",90001,400);default:if(r.state.state!=="connected"){this.notifyState("detached");return}this.requestState("detaching");case"detaching":return new Promise((o,l)=>{this.internalStateChanges.once(function(c){switch(this.event){case"detached":o();break;case"attached":case"suspended":case"failed":l(c.reason||r.getError()||new A("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":l(new A("Detach request superseded by a subsequent attach request",9e4,409));break}})})}}detachImpl(){f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.detach()","sending DETACH message");const r=ei({action:ue.DETACH,channel:this.name});this.send(r)}async subscribe(...r){const[o,l]=yo.processListenerArgs(r);if(this.state==="failed")throw A.fromValues(this.invalidStateError());return o&&typeof o=="object"&&!Array.isArray(o)?this.client._FilteredSubscriptions.subscribeFilter(this,o,l):this.subscriptions.on(o,l),this.channelOptions.attachOnSubscribe!==!1?this.attach():null}unsubscribe(...r){var o;const[l,c]=yo.processListenerArgs(r);if(typeof l=="object"&&!c||(o=this.filteredSubscriptions)!=null&&o.has(c)){this.client._FilteredSubscriptions.getAndDeleteFilteredSubscriptions(this,l,c).forEach(_=>this.subscriptions.off(_));return}this.subscriptions.off(l,c)}sync(){switch(this.state){case"initialized":case"detaching":case"detached":throw new Se("Unable to sync to channel; not attached",4e4)}const r=this.connectionManager;if(!r.activeState())throw r.getError();const o=ei({action:ue.SYNC,channel:this.name});this.syncChannelSerial&&(o.channelSerial=this.syncChannelSerial),r.send(o)}send(r){this.connectionManager.send(r)}async sendAndAwaitAck(r){return new Promise((o,l)=>{this.connectionManager.send(r,this.client.options.queueMessages,(c,_)=>{c?l(c):o(_)})})}async sendPresence(r){const o=ei({action:ue.PRESENCE,channel:this.name,presence:r});await this.sendAndAwaitAck(o)}async sendState(r){const o=ei({action:ue.OBJECT,channel:this.name,state:r});return this.sendAndAwaitAck(o)}async processMessage(r){(r.action===ue.ATTACHED||r.action===ue.MESSAGE||r.action===ue.PRESENCE||r.action===ue.OBJECT||r.action===ue.ANNOTATION)&&this.setChannelSerial(r.channelSerial);let o,l=!1;switch(r.action){case ue.ATTACHED:{this.properties.attachSerial=r.channelSerial,this._mode=r.getMode(),this.params=r.params||{};const c=r.decodeModesFromFlags();this.modes=c&&Wi(c)||void 0;const _=r.hasFlag("RESUMED"),b=r.hasFlag("HAS_PRESENCE"),C=r.hasFlag("HAS_BACKLOG"),O=r.hasFlag("HAS_OBJECTS");if(this._attachedReceived.emit("attached"),this.state==="attached"){_||this._presence&&this._presence.onAttached(b),this._object&&this._object.onAttached(O);const M=new Mn(this.state,this.state,_,C,r.error);(!_||this.channelOptions.updateOnAttached)&&this.emit("update",M)}else this.state==="detaching"?this.checkPendingState():this.notifyState("attached",r.error,_,b,C,O);break}case ue.DETACHED:{const c=r.error?A.fromValues(r.error):new A("Channel detached",90001,404);this.state==="detaching"?this.notifyState("detached",c):this.state==="attaching"?this.notifyState("suspended",c):(this.state==="attached"||this.state==="suspended")&&this.requestState("attaching",c);break}case ue.SYNC:if(l=!0,o=this.syncChannelSerial=r.channelSerial,!r.presence)break;case ue.PRESENCE:{if(!r.presence)break;Ur(r);const c=this.channelOptions;if(this._presence){const _=await Promise.all(r.presence.map(b=>b.decode(c,this.logger)));this._presence.setPresence(_,l,o)}break}case ue.OBJECT:case ue.OBJECT_SYNC:{if(!this._object||!r.state)return;Ur(r);const c=this.client.connection.connectionManager.getActiveTransportFormat(),_=r.state.map(b=>b.decode(this.client,c));r.action===ue.OBJECT?this._object.handleObjectMessages(_):this._object.handleObjectSyncMessages(_,r.channelSerial);break}case ue.MESSAGE:{if(this.state!=="attached"){f.logAction(this.logger,f.LOG_MAJOR,"RealtimeChannel.processMessage()",'Message "'+r.id+'" skipped as this channel "'+this.name+'" state is not "attached" (state is "'+this.state+'").');return}Ur(r);const c=r.messages,_=c[0],b=c[c.length-1];if(_.extras&&_.extras.delta&&_.extras.delta.from!==this._lastPayload.messageId){const O='Delta message decode failure - previous message not available for message "'+r.id+'" on this channel "'+this.name+'".';f.logAction(this.logger,f.LOG_ERROR,"RealtimeChannel.processMessage()",O),this._startDecodeFailureRecovery(new A(O,40018,400));break}let C=[];for(let O=0;O<c.length;O++){const{decoded:M,err:z}=await c[O].decodeWithErr(this._decodingContext,this.logger);if(C[O]=M,z)switch(z.code){case 40018:this._startDecodeFailureRecovery(z);return;case 40019:case 40021:this.notifyState("failed",z);return}}this._lastPayload.messageId=b.id,this._lastPayload.protocolMessageChannelSerial=r.channelSerial,this.onEvent(C);break}case ue.ANNOTATION:{Ur(r);const c=this.channelOptions;if(this._annotations){const _=await Promise.all((r.annotations||[]).map(b=>b.decode(c,this.logger)));this._annotations._processIncoming(_)}break}case ue.ERROR:{const c=r.error;c&&c.code==80016?this.checkPendingState():this.notifyState("failed",A.fromValues(c));break}default:f.logAction(this.logger,f.LOG_MAJOR,"RealtimeChannel.processMessage()","Protocol error: unrecognised message action ("+r.action+")")}}_startDecodeFailureRecovery(r){this._lastPayload.decodeFailureRecoveryInProgress||(f.logAction(this.logger,f.LOG_MAJOR,"RealtimeChannel.processMessage()","Starting decode failure recovery process."),this._lastPayload.decodeFailureRecoveryInProgress=!0,this._attach(!0,r,()=>{this._lastPayload.decodeFailureRecoveryInProgress=!1}))}onAttached(){f.logAction(this.logger,f.LOG_MINOR,"RealtimeChannel.onAttached","activating channel; name = "+this.name)}notifyState(r,o,l,c,_,b){if(f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.notifyState","name = "+this.name+", current state = "+this.state+", notifying state "+r),this.clearStateTimer(),["detached","suspended","failed"].includes(r)&&(this.properties.channelSerial=null),r===this.state)return;this._presence&&this._presence.actOnChannelState(r,c,o),this._object&&this._object.actOnChannelState(r,b),r==="suspended"&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),o&&(this.errorReason=o);const C=new Mn(this.state,r,l,_,o),O='Channel state for channel "'+this.name+'"',M=r+(o?"; reason: "+o:"");r==="failed"?f.logAction(this.logger,f.LOG_ERROR,O,M):f.logAction(this.logger,f.LOG_MAJOR,O,M),r!=="attaching"&&r!=="suspended"&&(this.retryCount=0),r==="attached"&&this.onAttached(),r==="attached"?this._attachResume=!0:(r==="detaching"||r==="failed")&&(this._attachResume=!1),this.state=r,this.emit(r,C)}requestState(r,o){f.logAction(this.logger,f.LOG_MINOR,"RealtimeChannel.requestState","name = "+this.name+", state = "+r),this.notifyState(r,o),this.checkPendingState()}checkPendingState(){if(!this.connectionManager.state.sendEvents){f.logAction(this.logger,f.LOG_MINOR,"RealtimeChannel.checkPendingState","sendEvents is false; state is "+this.connectionManager.state.state);return}switch(f.logAction(this.logger,f.LOG_MINOR,"RealtimeChannel.checkPendingState","name = "+this.name+", state = "+this.state),this.state){case"attaching":this.startStateTimerIfNotRunning(),this.attachImpl();break;case"detaching":this.startStateTimerIfNotRunning(),this.detachImpl();break;case"attached":this.sync();break}}timeoutPendingState(){switch(this.state){case"attaching":{const r=new A("Channel attach timed out",90007,408);this.notifyState("suspended",r);break}case"detaching":{const r=new A("Channel detach timed out",90007,408);this.notifyState("attached",r);break}default:this.checkPendingState();break}}startStateTimerIfNotRunning(){this.stateTimer||(this.stateTimer=setTimeout(()=>{f.logAction(this.logger,f.LOG_MINOR,"RealtimeChannel.startStateTimerIfNotRunning","timer expired"),this.stateTimer=null,this.timeoutPendingState()},this.client.options.timeouts.realtimeRequestTimeout))}clearStateTimer(){const r=this.stateTimer;r&&(clearTimeout(r),this.stateTimer=null)}startRetryTimer(){if(this.retryTimer)return;this.retryCount++;const r=qi(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(()=>{this.state==="suspended"&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,f.logAction(this.logger,f.LOG_MINOR,"RealtimeChannel retry timer expired","attempting a new attach"),this.requestState("attaching"))},r)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}getReleaseErr(){const r=this.state;return r==="initialized"||r==="detached"||r==="failed"?null:new A("Can only release a channel in a state where there is no possibility of further updates from the server being received (initialized, detached, or failed); was "+r,90001,400)}setChannelSerial(r){f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.setChannelSerial()","Updating channel serial; serial = "+r+"; previous = "+this.properties.channelSerial),r&&(this.properties.channelSerial=r)}async status(){return this.client.rest.channelMixin.status(this)}async getMessage(r){return f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.getMessage()","channel = "+this.name),this.client.rest.channelMixin.getMessage(this,r)}async updateMessage(r,o,l){return f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.updateMessage()","channel = "+this.name),this.sendUpdate(r,"message.update",o,l)}async deleteMessage(r,o,l){return f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.deleteMessage()","channel = "+this.name),this.sendUpdate(r,"message.delete",o,l)}async appendMessage(r,o,l){return f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.appendMessage()","channel = "+this.name),this.sendUpdate(r,"message.append",o,l)}async sendUpdate(r,o,l,c){var _;if(!r.serial)throw new A('This message lacks a serial and cannot be updated. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);this.throwIfUnpublishableState();const C=await Si.fromValues(P(L({},r),{action:o,version:l})).encode(this.channelOptions),O=ei({action:ue.MESSAGE,channel:this.name,messages:[C],params:c?ms(c):void 0});return{versionSerial:(_=(await this.sendAndAwaitAck(O)).serials[0])!=null?_:null}}async getMessageVersions(r,o){return f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.getMessageVersions()","channel = "+this.name),this.client.rest.channelMixin.getMessageVersions(this,r,o)}async ensureAttached(){switch(this.state){case"attached":case"suspended":break;case"initialized":case"detached":case"detaching":case"attaching":await this.attach();break;case"failed":default:throw A.fromValues(this.invalidStateError())}}};function hl(s){const r=s||{},{agent:o}=r;return U(r,["agent"])}var Ys=Iu,Du=class{constructor(s){this.channel=s,this.logger=s.logger,this.subscriptions=new qe(this.logger)}async publish(s,r){const o=this.channel.name,l=ol(s,r),c=await l.encode();this.channel.throwIfUnpublishableState(),f.logAction(this.logger,f.LOG_MICRO,"RealtimeAnnotations.publish()","channelName = "+o+", sending annotation with messageSerial = "+l.messageSerial+", type = "+l.type);const _=ei({action:ue.ANNOTATION,channel:o,annotations:[c]});await this.channel.sendAndAwaitAck(_)}async delete(s,r){r.action="annotation.delete",await this.publish(s,r)}async subscribe(...s){const r=Ys.processListenerArgs(s),o=r[0],l=r[1],c=this.channel;if(c.state==="failed")throw A.fromValues(c.invalidStateError());if(this.subscriptions.on(o,l),this.channel.channelOptions.attachOnSubscribe!==!1&&await c.attach(),(this.channel.state==="attached"&&this.channel._mode&ot.ANNOTATION_SUBSCRIBE)===0)throw new A("You are trying to add an annotation listener, but you haven't requested the annotation_subscribe channel mode in ChannelOptions, so this won't do anything (we only deliver annotations to clients who have explicitly requested them)",93001,400)}unsubscribe(...s){const r=Ys.processListenerArgs(s),o=r[0],l=r[1];this.subscriptions.off(o,l)}_processIncoming(s){for(const r of s)this.subscriptions.emit(r.type||"",r)}async get(s,r){return kn.prototype.get.call(this,s,r)}},cl=Du,os=class Qr extends ku{constructor(r){var o,l;if(!Qr._MsgPack)throw new Error("Expected DefaultRest._MsgPack to have been set");super(J.objectifyOptions(r,!0,"Rest",f.defaultLogger,P(L({},Za),{Crypto:(o=Qr.Crypto)!=null?o:void 0,MsgPack:(l=Qr._MsgPack)!=null?l:void 0,Annotations:{Annotation:Ks,WireAnnotation:Es,RealtimeAnnotations:cl,RestAnnotations:kn}})))}static get Crypto(){if(this._Crypto===null)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(r){this._Crypto=r}};os._Crypto=null,os.Message=Qa,os.PresenceMessage=el,os.Annotation=rl,os._MsgPack=null,os._Http=gt;var On=os,Nu=class extends qe{constructor(s){super(s),this.messages=[]}count(){return this.messages.length}push(s){this.messages.push(s)}shift(){return this.messages.shift()}last(){return this.messages[this.messages.length-1]}copyAll(){return this.messages.slice()}append(s){this.messages.push.apply(this.messages,s)}prepend(s){this.messages.unshift.apply(this.messages,s)}completeMessages(s,r,o){f.logAction(this.logger,f.LOG_MICRO,"MessageQueue.completeMessages()",s=="all"?"(all)":"serial = "+s.serial+"; count = "+s.count),r=r||null;const l=this.messages;if(l.length===0)throw new Error("MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue");let c=[];if(s==="all")c=l.splice(0);else{const _=l[0];if(_){const b=_.message.msgSerial,C=s.serial+s.count;C>b&&(c=l.splice(0,C-b))}}for(let _=0;_<c.length;_++){const b=c[_],C=o==null?void 0:o[_];b.callback(r,C)}l.length==0&&this.emit("idle")}completeAllMessages(s){this.completeMessages("all",s)}resetSendAttempted(){for(let s of this.messages)s.sendAttempted=!1}clear(){f.logAction(this.logger,f.LOG_MICRO,"MessageQueue.clear()","clearing "+this.messages.length+" messages"),this.messages=[],this.emit("idle")}},ul=Nu,dl=class{constructor(s,r){this.message=s,this.callback=r,this.merged=!1;const o=s.action;this.sendAttempted=!1,this.ackRequired=typeof o=="number"&&[ue.MESSAGE,ue.PRESENCE,ue.ANNOTATION,ue.OBJECT].includes(o)}},Hu=class extends qe{constructor(s){super(s.logger),this.transport=s,this.messageQueue=new ul(this.logger),s.on("ack",(r,o,l)=>{this.onAck(r,o,l)}),s.on("nack",(r,o,l)=>{this.onNack(r,o,l)})}onAck(s,r,o){f.logAction(this.logger,f.LOG_MICRO,"Protocol.onAck()","serial = "+s+"; count = "+r),this.messageQueue.completeMessages({serial:s,count:r},null,o)}onNack(s,r,o){f.logAction(this.logger,f.LOG_ERROR,"Protocol.onNack()","serial = "+s+"; count = "+r+"; err = "+it(o)),o||(o=new A("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages({serial:s,count:r},o)}onceIdle(s){const r=this.messageQueue;if(r.count()===0){s();return}r.once("idle",s)}send(s){s.ackRequired&&this.messageQueue.push(s),this.logger.shouldLog(f.LOG_MICRO)&&f.logActionNoStrip(this.logger,f.LOG_MICRO,"Protocol.send()","sending msg; "+Rn(s.message,this.transport.connectionManager.realtime._RealtimePresence,this.transport.connectionManager.realtime._Annotations,this.transport.connectionManager.realtime._liveObjectsPlugin)),s.sendAttempted=!0,this.transport.send(s.message)}getTransport(){return this.transport}getPendingMessages(){return this.messageQueue.copyAll()}clearPendingMessages(){return this.messageQueue.clear()}finish(){const s=this.transport;this.onceIdle(function(){s.disconnect()})}},Uu=Hu,Wu=class{constructor(s,r,o,l){this.previous=s,this.current=r,o&&(this.retryIn=o),l&&(this.reason=l)}},zr=Wu,Vi={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},Fu={disconnected:()=>A.fromValues({statusCode:400,code:Vi.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>A.fromValues({statusCode:400,code:Vi.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>A.fromValues({statusCode:400,code:Vi.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>A.fromValues({statusCode:400,code:Vi.CLOSING,message:"Connection closing"}),closed:()=>A.fromValues({statusCode:400,code:Vi.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>A.fromValues({statusCode:500,code:Vi.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>A.fromValues({statusCode:500,code:Vi.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})};function zu(s){return!s.statusCode||!s.code||s.statusCode>=500?!0:Object.values(Vi).includes(s.code)}var as=Fu,qu=ei({action:ue.CLOSE}),Gu=ei({action:ue.DISCONNECT}),ju=class extends qe{constructor(s,r,o,l){super(s.logger),l&&(o.format=void 0,o.heartbeats=!0),this.connectionManager=s,this.auth=r,this.params=o,this.timeouts=o.options.timeouts,this.format=o.format,this.isConnected=!1,this.isFinished=!1,this.isDisposed=!1,this.maxIdleInterval=null,this.idleTimer=null,this.lastActivity=null}connect(){}close(){this.isConnected&&this.requestClose(),this.finish("closed",as.closed())}disconnect(s){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",s||as.disconnected())}fail(s){this.isConnected&&this.requestDisconnect(),this.finish("failed",s||as.failed())}finish(s,r){var o;this.isFinished||(this.isFinished=!0,this.isConnected=!1,this.maxIdleInterval=null,clearTimeout((o=this.idleTimer)!=null?o:void 0),this.idleTimer=null,this.emit(s,r),this.dispose())}onProtocolMessage(s){switch(this.logger.shouldLog(f.LOG_MICRO)&&f.logActionNoStrip(this.logger,f.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+Rn(s,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),s.action){case ue.HEARTBEAT:f.logActionNoStrip(this.logger,f.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",s.id);break;case ue.CONNECTED:this.onConnect(s),this.emit("connected",s.error,s.connectionId,s.connectionDetails,s);break;case ue.CLOSED:this.onClose(s);break;case ue.DISCONNECTED:this.onDisconnect(s);break;case ue.ACK:this.emit("ack",s.msgSerial,s.count,s.res);break;case ue.NACK:this.emit("nack",s.msgSerial,s.count,s.error);break;case ue.SYNC:this.connectionManager.onChannelMessage(s,this);break;case ue.ACTIVATE:break;case ue.AUTH:Vt(this.auth.authorize(),r=>{r&&f.logAction(this.logger,f.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+it(r))});break;case ue.ERROR:if(f.logAction(this.logger,f.LOG_MINOR,"Transport.onProtocolMessage()","received error action; connectionId = "+this.connectionManager.connectionId+"; err = "+E.Config.inspect(s.error)+(s.channel?", channel: "+s.channel:"")),s.channel===void 0){this.onFatalError(s);break}this.connectionManager.onChannelMessage(s,this);break;default:this.connectionManager.onChannelMessage(s,this)}}onConnect(s){if(this.isConnected=!0,!s.connectionDetails)throw new Error("Transport.onConnect(): Connect message recieved without connectionDetails");const r=s.connectionDetails.maxIdleInterval;r&&(this.maxIdleInterval=r+this.timeouts.realtimeRequestTimeout,this.onActivity())}onDisconnect(s){const r=s&&s.error;f.logAction(this.logger,f.LOG_MINOR,"Transport.onDisconnect()","err = "+it(r)),this.finish("disconnected",r)}onFatalError(s){const r=s&&s.error;f.logAction(this.logger,f.LOG_MINOR,"Transport.onFatalError()","err = "+it(r)),this.finish("failed",r)}onClose(s){const r=s&&s.error;f.logAction(this.logger,f.LOG_MINOR,"Transport.onClose()","err = "+it(r)),this.finish("closed",r)}requestClose(){f.logAction(this.logger,f.LOG_MINOR,"Transport.requestClose()",""),this.send(qu)}requestDisconnect(){f.logAction(this.logger,f.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(Gu)}ping(s){const r={action:ue.HEARTBEAT};s&&(r.id=s),this.send(ei(r))}dispose(){f.logAction(this.logger,f.LOG_MINOR,"Transport.dispose()",""),this.isDisposed=!0,this.off()}onActivity(){this.maxIdleInterval&&(this.lastActivity=this.connectionManager.lastActivity=Date.now(),this.setIdleTimer(this.maxIdleInterval+100))}setIdleTimer(s){this.idleTimer||(this.idleTimer=setTimeout(()=>{this.onIdleTimerExpire()},s))}onIdleTimerExpire(){if(!this.lastActivity||!this.maxIdleInterval)throw new Error("Transport.onIdleTimerExpire(): lastActivity/maxIdleInterval not set");this.idleTimer=null;const s=Date.now()-this.lastActivity,r=this.maxIdleInterval-s;if(r<=0){const o="No activity seen from realtime in "+s+"ms; assuming connection has dropped";f.logAction(this.logger,f.LOG_ERROR,"Transport.onIdleTimerExpire()",o),this.disconnect(new A(o,80003,408))}else this.setIdleTimer(r+100)}static tryConnect(s,r,o,l,c){const _=new s(r,o,l);let b;const C=function(M){clearTimeout(b),c({event:this.event,error:M})},O=r.options.timeouts.realtimeRequestTimeout;return b=setTimeout(()=>{_.off(["preconnect","disconnected","failed"]),_.dispose(),C.call({event:"disconnected"},new A("Timeout waiting for transport to indicate itself viable",5e4,500))},O),_.on(["failed","disconnected"],C),_.on("preconnect",function(){f.logAction(r.logger,f.LOG_MINOR,"Transport.tryConnect()","viable transport "+_),clearTimeout(b),_.off(["failed","disconnected"],C),c(null,_)}),_.connect(),_}static isAvailable(){throw new A("isAvailable not implemented for transport",5e4,500)}},Rs=ju,ti;(s=>{s.WebSocket="web_socket",s.Comet="comet",s.XhrPolling="xhr_polling"})(ti||(ti={}));var $u=typeof Ki<"u"?Ki:typeof window<"u"?window:self,Tn=()=>{var s;return typeof E.WebStorage<"u"&&((s=E.WebStorage)==null?void 0:s.localSupported)},Js=()=>{var s;return typeof E.WebStorage<"u"&&((s=E.WebStorage)==null?void 0:s.sessionSupported)},fl=function(){},Pn="ably-transport-preference";function Ln(s){try{return JSON.parse(s)}catch{return null}}var Vu=class{constructor(s,r,o,l){this.options=s,this.host=r,this.mode=o,this.connectionKey=l,this.format=s.useBinaryProtocol?"msgpack":"json"}getConnectParams(s){const r=s?ct(s):{},o=this.options;switch(this.mode){case"resume":r.resume=this.connectionKey;break;case"recover":{const l=Ln(o.recover);l&&(r.recover=l.connectionKey);break}}return o.clientId!==void 0&&(r.clientId=o.clientId),o.echoMessages===!1&&(r.echo="false"),this.format!==void 0&&(r.format=this.format),this.stream!==void 0&&(r.stream=this.stream),this.heartbeats!==void 0&&(r.heartbeats=this.heartbeats),r.v=J.protocolVersion,r.agent=G(this.options),o.transportParams!==void 0&&se(r,o.transportParams),r}toString(){let s="[mode="+this.mode;return this.host&&(s+=",host="+this.host),this.connectionKey&&(s+=",connectionKey="+this.connectionKey),this.format&&(s+=",format="+this.format),s+="]",s}},Ku=class Vh extends qe{constructor(r,o){super(r.logger),this.supportedTransports={},this.disconnectedRetryCount=0,this.pendingChannelMessagesState={isProcessing:!1,queue:[]},this.realtime=r,this.initTransports(),this.options=o;const l=o.timeouts,c=l.webSocketConnectTimeout+l.realtimeRequestTimeout;if(this.states={initialized:{state:"initialized",terminal:!1,queueEvents:!0,sendEvents:!1,failState:"disconnected"},connecting:{state:"connecting",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:c,failState:"disconnected"},connected:{state:"connected",terminal:!1,queueEvents:!1,sendEvents:!0,failState:"disconnected"},disconnected:{state:"disconnected",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:l.disconnectedRetryTimeout,failState:"disconnected"},suspended:{state:"suspended",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:l.suspendedRetryTimeout,failState:"suspended"},closing:{state:"closing",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:l.realtimeRequestTimeout,failState:"closed"},closed:{state:"closed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"closed"},failed:{state:"failed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"failed"}},this.state=this.states.initialized,this.errorReason=null,this.queuedMessages=new ul(this.logger),this.msgSerial=0,this.connectionDetails=void 0,this.connectionId=void 0,this.connectionKey=void 0,this.connectionStateTtl=l.connectionStateTtl,this.maxIdleInterval=null,this.transports=qt(o.transports||J.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(ti.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(ti.XhrPolling)?this.baseTransport=ti.XhrPolling:this.transports.includes(ti.Comet)&&(this.baseTransport=ti.Comet),this.domains=J.getHosts(o),this.activeProtocol=null,this.host=null,this.lastAutoReconnectAttempt=null,this.lastActivity=null,this.forceFallbackHost=!1,this.connectCounter=0,this.wsCheckResult=null,this.webSocketSlowTimer=null,this.webSocketGiveUpTimer=null,this.abandonedWebSocket=!1,f.logAction(this.logger,f.LOG_MINOR,"Realtime.ConnectionManager()","started"),f.logAction(this.logger,f.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(o.transports||J.defaultTransports)+"]"),f.logAction(this.logger,f.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+this.transports+"]"),f.logAction(this.logger,f.LOG_MICRO,"Realtime.ConnectionManager()","http domains = ["+this.domains+"]"),!this.transports.length){const b="no requested transports available";throw f.logAction(this.logger,f.LOG_ERROR,"realtime.ConnectionManager()",b),new Error(b)}const _=E.Config.addEventListener;_&&(Js()&&typeof o.recover=="function"&&_("beforeunload",this.persistConnection.bind(this)),o.closeOnUnload===!0&&_("beforeunload",()=>{f.logAction(this.logger,f.LOG_MAJOR,"Realtime.ConnectionManager()","beforeunload event has triggered the connection to close as closeOnUnload is true"),this.requestState({state:"closing"})}),_("online",()=>{var b;this.state==this.states.disconnected||this.state==this.states.suspended?(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager caught browser ‘online’ event","reattempting connection"),this.requestState({state:"connecting"})):this.state==this.states.connecting&&((b=this.pendingTransport)==null||b.off(),this.disconnectAllTransports(),this.startConnect())}),_("offline",()=>{this.state==this.states.connected&&(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager caught browser ‘offline’ event","disconnecting active transport"),this.disconnectAllTransports())}))}static supportedTransports(r){const o={supportedTransports:{}};return this.initTransports(r,o),o.supportedTransports}static initTransports(r,o){const l=L(L({},E.Transports.bundledImplementations),r);[ti.WebSocket,...E.Transports.order].forEach(c=>{const _=l[c];_&&_.isAvailable()&&(o.supportedTransports[c]=_)})}initTransports(){Vh.initTransports(this.realtime._additionalTransportImplementations,this)}createTransportParams(r,o){return new Vu(this.options,r,o,this.connectionKey)}getTransportParams(r){(l=>{if(this.connectionKey){l("resume");return}if(typeof this.options.recover=="string"){l("recover");return}const c=this.options.recover,_=this.getSessionRecoverData(),b=this.sessionRecoveryName();if(_&&typeof c=="function"){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data (recovery scope: "+b+")"),c(_,C=>{C?(this.options.recover=_.recoveryKey,l("recover")):l("clean")});return}l("clean")})(l=>{const c=this.createTransportParams(null,l);if(l==="recover"){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+this.options.recover);const _=Ln(this.options.recover);_&&(this.msgSerial=_.msgSerial)}else f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+c.toString());r(c)})}tryATransport(r,o,l){f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+o),this.proposedTransport=Rs.tryConnect(this.supportedTransports[o],this,this.realtime.auth,r,(c,_)=>{const b=this.state;if(b==this.states.closing||b==this.states.closed||b==this.states.failed){_&&(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+b.state+" while we were attempting the transport; closing "+_),_.close()),l(!0);return}if(c){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+o+" "+c.event+", err: "+c.error.toString()),Fe.isTokenErr(c.error)&&!(this.errorReason&&Fe.isTokenErr(this.errorReason))?(this.errorReason=c.error,Vt(this.realtime.auth._forceNewToken(null,null),C=>{if(C){this.actOnErrorFromAuthorize(C);return}this.tryATransport(r,o,l)})):c.event==="failed"?(this.notifyState({state:"failed",error:c.error}),l(!0)):c.event==="disconnected"&&(zu(c.error)?l(!1):(this.notifyState({state:this.states.connecting.failState,error:c.error}),l(!0)));return}f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.tryATransport()","viable transport "+o+"; setting pending"),this.setTransportPending(_,r),l(null,_)})}setTransportPending(r,o){const l=o.mode;f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.setTransportPending()","transport = "+r+"; mode = "+l),this.pendingTransport=r,this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),r.once("connected",(_,b,C)=>{this.activateTransport(_,r,b,C),l==="recover"&&this.options.recover&&(delete this.options.recover,this.unpersistConnection())});const c=this;r.on(["disconnected","closed","failed"],function(_){c.deactivateTransport(r,this.event,_)}),this.emit("transport.pending",r)}activateTransport(r,o,l,c){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+o),r&&f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+r),l&&f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+l),c&&f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(c)),this.persistTransportPreference(o);const _=this.state,b=this.states.connected.state;if(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.activateTransport()","current state = "+_.state),_.state==this.states.closing.state||_.state==this.states.closed.state||_.state==this.states.failed.state)return f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),o.disconnect(),!1;if(delete this.pendingTransport,!o.isConnected)return f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.activateTransport()","Declining to activate transport "+o+" since it appears to no longer be connected"),!1;const C=this.activeProtocol;this.activeProtocol=new Uu(o),this.host=o.params.host;const O=c.connectionKey;if(O&&this.connectionKey!=O&&this.setConnection(l,c,!!r),this.onConnectionDetailsUpdate(c,o),E.Config.nextTick(()=>{o.on("connected",(M,z,q)=>{this.onConnectionDetailsUpdate(q,o),this.emit("update",new zr(b,b,null,M))})}),_.state===this.states.connected.state?r&&(this.errorReason=this.realtime.connection.errorReason=r,this.emit("update",new zr(b,b,null,r))):(this.notifyState({state:"connected",error:r}),this.errorReason=this.realtime.connection.errorReason=r||null),this.emit("transport.active",o),C)if(C.messageQueue.count()>0&&f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+C.transport.shortName+", new one is "+o.shortName+") finishing with "+C.messageQueue.count()+" messages still pending"),C.transport===o){const M="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+o.shortName+"; stack = "+new Error().stack;f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.activateTransport()",M)}else C.finish();return!0}deactivateTransport(r,o,l){const c=this.activeProtocol,_=c&&c.getTransport()===r,b=r===this.pendingTransport,C=this.noTransportsScheduledForActivation();if(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.deactivateTransport()","transport = "+r),f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.deactivateTransport()","state = "+o+(_?"; was active":b?"; was pending":"")+(C?"":"; another transport is scheduled for activation")),l&&l.message&&f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.deactivateTransport()","reason = "+l.message),_&&(f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.deactivateTransport()","Getting, clearing, and requeuing "+this.activeProtocol.messageQueue.count()+" pending messages"),this.queuePendingMessages(c.getPendingMessages()),c.clearPendingMessages(),this.activeProtocol=this.host=null),this.emit("transport.inactive",r),_&&C||_&&o==="failed"||o==="closed"||c===null&&b){if(o==="disconnected"&&l&&l.statusCode>500&&this.domains.length>1){this.unpersistTransportPreference(),this.forceFallbackHost=!0,this.notifyState({state:o,error:l,retryImmediately:!0});return}const O=o==="failed"&&Fe.isTokenErr(l)?"disconnected":o;this.notifyState({state:O,error:l});return}}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(r,o,l){const c=this.connectionId;(c&&c!==r||!c&&l)&&(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.setConnection()","Resetting msgSerial"),this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId!==r&&f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.setConnection()","New connectionId; reattaching any attached channels"),this.realtime.connection.id=this.connectionId=r,this.realtime.connection.key=this.connectionKey=o.connectionKey}clearConnection(){this.realtime.connection.id=this.connectionId=void 0,this.realtime.connection.key=this.connectionKey=void 0,this.msgSerial=0,this.queuedMessages.resetSendAttempted(),this.unpersistConnection()}createRecoveryKey(){return this.connectionKey?JSON.stringify({connectionKey:this.connectionKey,msgSerial:this.msgSerial,channelSerials:this.realtime.channels.channelSerials()}):null}checkConnectionStateFreshness(){if(!this.lastActivity||!this.connectionId)return;const r=Date.now()-this.lastActivity;r>this.connectionStateTtl+this.maxIdleInterval&&(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.checkConnectionStateFreshness()","Last known activity from realtime was "+r+"ms ago; discarding connection state"),this.clearConnection(),this.states.connecting.failState="suspended")}persistConnection(){if(Js()){const r=this.createRecoveryKey();r&&this.setSessionRecoverData({recoveryKey:r,disconnectedAt:Date.now(),location:$u.location,clientId:this.realtime.auth.clientId})}}unpersistConnection(){this.clearSessionRecoverData()}getActiveTransportFormat(){var r;return(r=this.activeProtocol)==null?void 0:r.getTransport().format}getError(){if(this.errorReason){const r=Se.fromValues(this.errorReason);return r.cause=this.errorReason,r}return this.getStateError()}getStateError(){var r,o;return(o=(r=as)[this.state.state])==null?void 0:o.call(r)}activeState(){return this.state.queueEvents||this.state.sendEvents}enactStateChange(r){const o="Connection state",l=r.current+(r.reason?"; reason: "+r.reason:"");r.current==="failed"?f.logAction(this.logger,f.LOG_ERROR,o,l):f.logAction(this.logger,f.LOG_MAJOR,o,l),f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.enactStateChange","setting new state: "+r.current+"; reason = "+(r.reason&&r.reason.message));const c=this.state=this.states[r.current];r.reason&&(this.errorReason=r.reason,this.realtime.connection.errorReason=r.reason),(c.terminal||c.state==="suspended")&&this.clearConnection(),this.emit("connectionstate",r)}startTransitionTimer(r){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+r.state),this.transitionTimer&&(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer)),this.transitionTimer=setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager "+r.state+" timer expired","requesting new state: "+r.failState),this.notifyState({state:r.failState}))},r.retryDelay)}cancelTransitionTimer(){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()",""),this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)}startSuspendTimer(){this.suspendTimer||(this.suspendTimer=setTimeout(()=>{this.suspendTimer&&(this.suspendTimer=null,f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager suspend timer expired","requesting new state: suspended"),this.states.connecting.failState="suspended",this.notifyState({state:"suspended"}))},this.connectionStateTtl))}checkSuspendTimer(r){r!=="disconnected"&&r!=="suspended"&&r!=="connecting"&&this.cancelSuspendTimer()}cancelSuspendTimer(){this.states.connecting.failState="disconnected",this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)}startRetryTimer(r){this.retryTimer=setTimeout(()=>{f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager retry timer expired","retrying"),this.retryTimer=null,this.requestState({state:"connecting"})},r)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}startWebSocketSlowTimer(){this.webSocketSlowTimer=setTimeout(()=>{f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager WebSocket slow timer","checking connectivity"),this.checkWsConnectivity().then(()=>{f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager WebSocket slow timer","ws connectivity check succeeded"),this.wsCheckResult=!0}).catch(()=>{f.logAction(this.logger,f.LOG_MAJOR,"ConnectionManager WebSocket slow timer","ws connectivity check failed"),this.wsCheckResult=!1}),this.realtime.http.checkConnectivity&&Vt(this.realtime.http.checkConnectivity(),(r,o)=>{r||!o?(f.logAction(this.logger,f.LOG_MAJOR,"ConnectionManager WebSocket slow timer","http connectivity check failed"),this.cancelWebSocketGiveUpTimer(),this.notifyState({state:"disconnected",error:new A("Unable to connect (network unreachable)",80003,404)})):f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager WebSocket slow timer","http connectivity check succeeded")})},this.options.timeouts.webSocketSlowTimeout)}cancelWebSocketSlowTimer(){this.webSocketSlowTimer&&(clearTimeout(this.webSocketSlowTimer),this.webSocketSlowTimer=null)}startWebSocketGiveUpTimer(r){this.webSocketGiveUpTimer=setTimeout(()=>{var o,l;this.wsCheckResult||(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager WebSocket give up timer","websocket connection took more than 10s; "+(this.baseTransport?"trying base transport":"")),this.baseTransport?(this.abandonedWebSocket=!0,(o=this.proposedTransport)==null||o.dispose(),(l=this.pendingTransport)==null||l.dispose(),this.connectBase(r,++this.connectCounter)):f.logAction(this.logger,f.LOG_MAJOR,"ConnectionManager WebSocket give up timer","websocket connectivity appears to be unavailable but no other transports to try"))},this.options.timeouts.webSocketConnectTimeout)}cancelWebSocketGiveUpTimer(){this.webSocketGiveUpTimer&&(clearTimeout(this.webSocketGiveUpTimer),this.webSocketGiveUpTimer=null)}notifyState(r){var o,l;const c=r.state,_=c==="disconnected"&&(this.state===this.states.connected||r.retryImmediately||this.state===this.states.connecting&&r.error&&Fe.isTokenErr(r.error)&&!(this.errorReason&&Fe.isTokenErr(this.errorReason)));if(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+c+(_?"; will retry connection immediately":"")),c==this.state.state||(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.checkSuspendTimer(r.state),(c==="suspended"||c==="connected")&&(this.disconnectedRetryCount=0),this.state.terminal))return;const b=this.states[r.state];let C=b.retryDelay;b.state==="disconnected"&&(this.disconnectedRetryCount++,C=qi(b.retryDelay,this.disconnectedRetryCount));const O=new zr(this.state.state,b.state,C,r.error||((l=(o=as)[b.state])==null?void 0:l.call(o)));if(_){const M=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=Date.now(),this.requestState({state:"connecting"}))},z=this.lastAutoReconnectAttempt&&Date.now()-this.lastAutoReconnectAttempt+1;z&&z<1e3?(f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+z+"ms ago, waiting another "+(1e3-z)+"ms before trying again"),setTimeout(M,1e3-z)):E.Config.nextTick(M)}else(c==="disconnected"||c==="suspended")&&this.startRetryTimer(C);(c==="disconnected"&&!_||c==="suspended"||b.terminal)&&E.Config.nextTick(()=>{this.disconnectAllTransports()}),c=="connected"&&!this.activeProtocol&&f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol"),this.enactStateChange(O),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(c,O.reason),this.failQueuedMessages(O.reason))}requestState(r){var o,l;const c=r.state;if(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+c+"; current state: "+this.state.state),c==this.state.state||(this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(c),c=="connecting"&&this.state.state=="connected")||c=="closing"&&this.state.state=="closed")return;const _=this.states[c],b=new zr(this.state.state,_.state,null,r.error||((l=(o=as)[_.state])==null?void 0:l.call(o)));this.enactStateChange(b),c=="connecting"&&E.Config.nextTick(()=>{this.startConnect()}),c=="closing"&&this.closeImpl()}startConnect(){if(this.state!==this.states.connecting){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state);return}const r=this.realtime.auth,o=++this.connectCounter,l=()=>{this.checkConnectionStateFreshness(),this.getTransportParams(c=>{if(c.mode==="recover"&&c.options.recover){const _=Ln(c.options.recover);_&&this.realtime.channels.recoverChannels(_.channelSerials)}o===this.connectCounter&&this.connectImpl(c,o)})};if(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.startConnect()","starting connection"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),r.method==="basic")l();else{const c=_=>{o===this.connectCounter&&(_?this.actOnErrorFromAuthorize(_):l())};this.errorReason&&Fe.isTokenErr(this.errorReason)?Vt(r._forceNewToken(null,null),c):Vt(r._ensureValidAuthCredentials(!1),c)}}connectImpl(r,o){const l=this.state.state;if(l!==this.states.connecting.state){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect, but was "+l);return}const c=this.getTransportPreference();c&&c===this.baseTransport&&this.webSocketTransportAvailable&&this.checkWsConnectivity().then(()=>{this.unpersistTransportPreference(),this.state===this.states.connecting&&(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.connectImpl():","web socket connectivity available, cancelling connection attempt with "+this.baseTransport),this.disconnectAllTransports(),this.connectWs(r,++this.connectCounter))}).catch(fl),c&&c===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(r,o):this.connectWs(r,o)}connectWs(r,o){f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.connectWs()"),this.wsCheckResult=null,this.abandonedWebSocket=!1,this.startWebSocketSlowTimer(),this.startWebSocketGiveUpTimer(r),this.tryTransportWithFallbacks("web_socket",r,!0,o,()=>this.wsCheckResult!==!1&&!this.abandonedWebSocket)}connectBase(r,o){f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.connectBase()"),this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,r,!1,o,()=>!0):this.notifyState({state:"disconnected",error:new A("No transports left to try",8e4,404)})}tryTransportWithFallbacks(r,o,l,c,_){f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.tryTransportWithFallbacks()",r);const b=q=>{this.notifyState({state:this.states.connecting.failState,error:q})},C=this.domains.slice(),O=(q,Q)=>{if(c===this.connectCounter){if(!_()){Q&&Q.dispose();return}!Q&&!q&&z()}},M=C.shift();if(!M){b(new A("Unable to connect (no available host)",80003,404));return}o.host=M;const z=()=>{if(!C.length){b(new A("Unable to connect (and no more fallback hosts to try)",80003,404));return}if(!this.realtime.http.checkConnectivity){b(new Se("Internal error: Http.checkConnectivity not set",null,500));return}Vt(this.realtime.http.checkConnectivity(),(q,Q)=>{if(c===this.connectCounter&&_()){if(q){b(q);return}if(!Q){b(new A("Unable to connect (network unreachable)",80003,404));return}o.host=gi(C),this.tryATransport(o,r,O)}})};if(this.forceFallbackHost&&C.length){this.forceFallbackHost=!1,z();return}this.tryATransport(o,r,O)}closeImpl(){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.closeImpl()","closing connection"),this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),this.pendingTransport&&(f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.closeImpl()","Closing pending transport: "+this.pendingTransport),this.pendingTransport.close()),this.activeProtocol&&(f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.closeImpl()","Closing active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().close()),this.notifyState({state:"closed"})}onAuthUpdated(r,o){var l;switch(this.state.state){case"connected":{f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Sending AUTH message on active transport");const c=(l=this.activeProtocol)==null?void 0:l.getTransport();c&&c.onAuthUpdated&&c.onAuthUpdated(r);const _=ei({action:ue.AUTH,auth:{accessToken:r.token}});this.send(_);const b=()=>{this.off(C),o(null,r)},C=O=>{O.current==="failed"&&(this.off(b),this.off(C),o(O.reason||this.getStateError()))};this.once("connectiondetails",b),this.on("connectionstate",C);break}case"connecting":f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Aborting current connection attempts in order to start again with the new auth details"),this.disconnectAllTransports();default:{f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Connection state is "+this.state.state+"; waiting until either connected or failed");const c=_=>{switch(_.current){case"connected":this.off(c),o(null,r);break;case"failed":case"closed":case"suspended":this.off(c),o(_.reason||this.getStateError());break}};this.on("connectionstate",c),this.state.state==="connecting"?this.startConnect():this.requestState({state:"connecting"})}}}disconnectAllTransports(){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.disconnectAllTransports()","Disconnecting all transports"),this.connectCounter++,this.pendingTransport&&(f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting pending transport: "+this.pendingTransport),this.pendingTransport.disconnect()),delete this.pendingTransport,this.proposedTransport&&(f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting proposed transport: "+this.pendingTransport),this.proposedTransport.disconnect()),delete this.pendingTransport,this.activeProtocol&&(f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())}send(r,o,l){l=l||fl;const c=this.state;if(c.sendEvents){f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new dl(r,l));return}if(!(o&&c.queueEvents)){const b="rejecting event, queueEvent was "+o+", state was "+c.state;f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.send()",b),l(this.errorReason||new A(b,9e4,400));return}this.logger.shouldLog(f.LOG_MICRO)&&f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.send()","queueing msg; "+Rn(r,this.realtime._RealtimePresence,this.realtime._Annotations,this.realtime._liveObjectsPlugin)),this.queue(r,l)}sendImpl(r){const o=r.message;r.ackRequired&&!r.sendAttempted&&(o.msgSerial=this.msgSerial++);try{this.activeProtocol.send(r)}catch(l){f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+l.stack)}}queue(r,o){f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.queue()","queueing event"),this.queuedMessages.push(new dl(r,o))}sendQueuedMessages(){f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.sendQueuedMessages()","sending "+this.queuedMessages.count()+" queued messages");let r;for(;r=this.queuedMessages.shift();)this.sendImpl(r)}queuePendingMessages(r){r&&r.length&&(f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.queuePendingMessages()","queueing "+r.length+" pending messages"),this.queuedMessages.prepend(r))}failQueuedMessages(r){const o=this.queuedMessages.count();o>0&&(f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+o+" queued messages, err = "+it(r)),this.queuedMessages.completeAllMessages(r))}onChannelMessage(r,o){this.pendingChannelMessagesState.queue.push({message:r,transport:o}),this.pendingChannelMessagesState.isProcessing||this.processNextPendingChannelMessage()}processNextPendingChannelMessage(){if(this.pendingChannelMessagesState.queue.length>0){this.pendingChannelMessagesState.isProcessing=!0;const r=this.pendingChannelMessagesState.queue.shift();this.processChannelMessage(r.message).catch(o=>{f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.processNextPendingChannelMessage() received error ",o)}).finally(()=>{this.pendingChannelMessagesState.isProcessing=!1,this.processNextPendingChannelMessage()})}}async processChannelMessage(r){await this.realtime.channels.processChannelMessage(r)}async ping(){var r;if(this.state.state!=="connected")throw new A("Unable to ping service; not connected",4e4,400);const o=(r=this.activeProtocol)==null?void 0:r.getTransport();if(!o)throw this.getStateError();f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.ping()","transport = "+o);const l=Date.now(),c=Ui();return yi(new Promise(_=>{const b=C=>{C===c&&(o.off("heartbeat",b),_(Date.now()-l))};o.on("heartbeat",b),o.ping(c)}),this.options.timeouts.realtimeRequestTimeout,"Timeout waiting for heartbeat response")}abort(r){this.activeProtocol.getTransport().fail(r)}getTransportPreference(){var r,o;return this.transportPreference||Tn()&&((o=(r=E.WebStorage)==null?void 0:r.get)==null?void 0:o.call(r,Pn))}persistTransportPreference(r){var o,l;this.transportPreference=r.shortName,Tn()&&((l=(o=E.WebStorage)==null?void 0:o.set)==null||l.call(o,Pn,r.shortName))}unpersistTransportPreference(){var r,o;this.transportPreference=null,Tn()&&((o=(r=E.WebStorage)==null?void 0:r.remove)==null||o.call(r,Pn))}actOnErrorFromAuthorize(r){if(r.code===40171)this.notifyState({state:"failed",error:r});else if(r.code===40102)this.notifyState({state:"failed",error:r});else if(r.statusCode===ve.Forbidden){const o="Client configured authentication provider returned 403; failing the connection";f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",o),this.notifyState({state:"failed",error:new A(o,80019,403,r)})}else{const o="Client configured authentication provider request failed";f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.actOnErrorFromAuthorize",o),this.notifyState({state:this.state.failState,error:new A(o,80019,401,r)})}}onConnectionDetailsUpdate(r,o){if(!r)return;this.connectionDetails=r,r.maxMessageSize&&(this.options.maxMessageSize=r.maxMessageSize);const l=r.clientId;if(l){const _=this.realtime.auth._uncheckedSetClientId(l);if(_){f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",_.message),o.fail(_);return}}const c=r.connectionStateTtl;c&&(this.connectionStateTtl=c),this.maxIdleInterval=r.maxIdleInterval,this.emit("connectiondetails",r)}checkWsConnectivity(){const r=this.options.wsConnectivityCheckUrl||J.wsConnectivityCheckUrl,o=new E.Config.WebSocket(r);return new Promise((l,c)=>{let _=!1;o.onopen=()=>{_||(_=!0,l(),o.close())},o.onclose=o.onerror=()=>{_||(_=!0,c())}})}sessionRecoveryName(){return this.options.recoveryKeyStorageName||"ably-connection-recovery"}getSessionRecoverData(){var r,o;return Js()&&((o=(r=E.WebStorage)==null?void 0:r.getSession)==null?void 0:o.call(r,this.sessionRecoveryName()))}setSessionRecoverData(r){var o,l;return Js()&&((l=(o=E.WebStorage)==null?void 0:o.setSession)==null?void 0:l.call(o,this.sessionRecoveryName(),r))}clearSessionRecoverData(){var r,o;return Js()&&((o=(r=E.WebStorage)==null?void 0:r.removeSession)==null?void 0:o.call(r,this.sessionRecoveryName()))}},_l=Ku,Yu=class extends qe{constructor(s,r){super(s.logger),this.whenState=o=>qe.prototype.whenState.call(this,o,this.state),this.ably=s,this.connectionManager=new _l(s,r),this.state=this.connectionManager.state.state,this.key=void 0,this.id=void 0,this.errorReason=null,this.connectionManager.on("connectionstate",o=>{const l=this.state=o.current;E.Config.nextTick(()=>{this.emit(l,o)})}),this.connectionManager.on("update",o=>{E.Config.nextTick(()=>{this.emit("update",o)})})}connect(){f.logAction(this.logger,f.LOG_MINOR,"Connection.connect()",""),this.connectionManager.requestState({state:"connecting"})}async ping(){return f.logAction(this.logger,f.LOG_MINOR,"Connection.ping()",""),this.connectionManager.ping()}close(){f.logAction(this.logger,f.LOG_MINOR,"Connection.close()","connectionKey = "+this.key),this.connectionManager.requestState({state:"closing"})}get recoveryKey(){return this.logger.deprecationWarning("The `Connection.recoveryKey` attribute has been replaced by the `Connection.createRecoveryKey()` method. Replace your usage of `recoveryKey` with the return value of `createRecoveryKey()`. `recoveryKey` will be removed in a future version."),this.createRecoveryKey()}createRecoveryKey(){return this.connectionManager.createRecoveryKey()}},Ju=Yu,gl=class Kh extends Ba{constructor(r){var o,l,c,_;if(super(J.objectifyOptions(r,!1,"BaseRealtime",f.defaultLogger)),f.logAction(this.logger,f.LOG_MINOR,"Realtime()",""),typeof EdgeRuntime=="string")throw new A(`Ably.Realtime instance cannot be used in Vercel Edge runtime. If you are running Vercel Edge functions, please replace your "new Ably.Realtime()" with "new Ably.Rest()" and use Ably Rest API instead of the Realtime API. If you are server-rendering your application in the Vercel Edge runtime, please use the condition "if (typeof EdgeRuntime === 'string')" to prevent instantiating Ably.Realtime instance during SSR in the Vercel Edge runtime.`,4e4,400);this._additionalTransportImplementations=Kh.transportImplementationsFromPlugins(this.options.plugins),this._RealtimePresence=(l=(o=this.options.plugins)==null?void 0:o.RealtimePresence)!=null?l:null,this._liveObjectsPlugin=(_=(c=this.options.plugins)==null?void 0:c.LiveObjects)!=null?_:null,this.connection=new Ju(this,this.options),this._channels=new Zu(this),this.options.autoConnect!==!1&&this.connect()}static transportImplementationsFromPlugins(r){const o={};return r!=null&&r.WebSocketTransport&&(o[ti.WebSocket]=r.WebSocketTransport),r!=null&&r.XHRPolling&&(o[ti.XhrPolling]=r.XHRPolling),o}get channels(){return this._channels}get clientId(){return this.auth.clientId}connect(){f.logAction(this.logger,f.LOG_MINOR,"Realtime.connect()",""),this.connection.connect()}close(){f.logAction(this.logger,f.LOG_MINOR,"Realtime.close()",""),this.connection.close()}};gl.EventEmitter=qe;var Xu=gl,Zu=class extends qe{constructor(s){super(s.logger),this.realtime=s,this.all=Object.create(null),s.connection.connectionManager.on("transport.active",()=>{this.onTransportActive()})}channelSerials(){let s={};for(const r of _i(this.all,!0)){const o=this.all[r];o.properties.channelSerial&&(s[r]=o.properties.channelSerial)}return s}recoverChannels(s){for(const r of _i(s,!0)){const o=this.get(r);o.properties.channelSerial=s[r]}}async processChannelMessage(s){const r=s.channel;if(r===void 0){f.logAction(this.logger,f.LOG_ERROR,"Channels.processChannelMessage()","received event unspecified channel, action = "+s.action);return}const o=this.all[r];if(!o){f.logAction(this.logger,f.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+r);return}await o.processMessage(s)}onTransportActive(){for(const s in this.all){const r=this.all[s];r.state==="attaching"||r.state==="detaching"?r.checkPendingState():r.state==="suspended"?r._attach(!1,null):r.state==="attached"&&r.requestState("attaching")}}propogateConnectionInterruption(s,r){const o={closing:"detached",closed:"detached",failed:"failed",suspended:"suspended"},l=["attaching","attached","detaching","suspended"],c=o[s];for(const _ in this.all){const b=this.all[_];l.includes(b.state)&&b.notifyState(c,r)}}get(s,r){s=String(s);let o=this.all[s];if(!o)o=this.all[s]=new Ys(this.realtime,s,r);else if(r){if(o._shouldReattachToSetOptions(r,o.channelOptions))throw new A("Channels.get() cannot be used to set channel options that would cause the channel to reattach. Please, use RealtimeChannel.setOptions() instead.",4e4,400);o.setOptions(r)}return o}getDerived(s,r,o){if(r.filter){const l=ns(r.filter),c=Ss(s);s=`[filter=${l}${c.qualifierParam}]${c.channelName}`}return this.get(s,o)}release(s){s=String(s);const r=this.all[s];if(!r)return;const o=r.getReleaseErr();if(o)throw o;delete this.all[s]}},Qu=Xu;function ed(s,r){if(s.isSynthesized()||r.isSynthesized())return s.timestamp>=r.timestamp;const o=s.parseId(),l=r.parseId();return o.msgSerial===l.msgSerial?o.index>l.index:o.msgSerial>l.msgSerial}var Bn=class extends qe{constructor(s,r,o=ed){super(s.logger),this.presence=s,this.map=Object.create(null),this.syncInProgress=!1,this.residualMembers=null,this.memberKey=r,this.newerThan=o}get(s){return this.map[s]}getClient(s){const r=this.map,o=[];for(const l in r){const c=r[l];c.clientId==s&&c.action!="absent"&&o.push(c)}return o}list(s){const r=this.map,o=s&&s.clientId,l=s&&s.connectionId,c=[];for(const _ in r){const b=r[_];b.action!=="absent"&&(o&&o!=b.clientId||l&&l!=b.connectionId||c.push(b))}return c}put(s){(s.action==="enter"||s.action==="update")&&(s=$i.fromValues(s),s.action="present");const r=this.map,o=this.memberKey(s);this.residualMembers&&delete this.residualMembers[o];const l=r[o];return l&&!this.newerThan(s,l)?!1:(r[o]=s,!0)}values(){const s=this.map,r=[];for(const o in s){const l=s[o];l.action!="absent"&&r.push(l)}return r}remove(s){const r=this.map,o=this.memberKey(s),l=r[o];return l&&!this.newerThan(s,l)?!1:(this.syncInProgress?(s=$i.fromValues(s),s.action="absent",r[o]=s):delete r[o],!!l)}startSync(){const s=this.map,r=this.syncInProgress;f.logAction(this.logger,f.LOG_MINOR,"PresenceMap.startSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+r),this.syncInProgress||(this.residualMembers=ct(s),this.setInProgress(!0))}endSync(){const s=this.map,r=this.syncInProgress;if(f.logAction(this.logger,f.LOG_MINOR,"PresenceMap.endSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+r),r){for(const o in s)s[o].action==="absent"&&delete s[o];this.presence._synthesizeLeaves(Br(this.residualMembers));for(const o in this.residualMembers)delete s[o];this.residualMembers=null,this.setInProgress(!1)}this.emit("sync")}async waitSync(){const s=this.syncInProgress;f.logAction(this.logger,f.LOG_MINOR,"PresenceMap.waitSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+s),s&&await this.once("sync")}clear(){this.map={},this.setInProgress(!1),this.residualMembers=null}setInProgress(s){f.logAction(this.logger,f.LOG_MICRO,"PresenceMap.setInProgress()","inProgress = "+s),this.syncInProgress=s,this.presence.syncComplete=!s}};function td(s){return s.channel.client.auth.clientId}function In(s){const r=s.channel.client,o=r.auth.clientId;return(!o||o==="*")&&r.connection.state==="connected"}var id=class extends qe{constructor(s){super(s.logger),this.channel=s,this.syncComplete=!1,this.members=new Bn(this,r=>r.clientId+":"+r.connectionId),this._myMembers=new Bn(this,r=>r.clientId),this.subscriptions=new qe(this.logger),this.pendingPresence=[]}async enter(s){if(In(this))throw new A("clientId must be specified to enter a presence channel",40012,400);return this._enterOrUpdateClient(void 0,void 0,s,"enter")}async update(s){if(In(this))throw new A("clientId must be specified to update presence data",40012,400);return this._enterOrUpdateClient(void 0,void 0,s,"update")}async enterClient(s,r){return this._enterOrUpdateClient(void 0,s,r,"enter")}async updateClient(s,r){return this._enterOrUpdateClient(void 0,s,r,"update")}async _enterOrUpdateClient(s,r,o,l){const c=this.channel;if(!c.connectionManager.activeState())throw c.connectionManager.getError();f.logAction(this.logger,f.LOG_MICRO,"RealtimePresence."+l+"Client()","channel = "+c.name+", id = "+s+", client = "+(r||"(implicit) "+td(this)));const _=$i.fromData(o);_.action=l,s&&(_.id=s),r&&(_.clientId=r);const b=await _.encode(c.channelOptions);switch(c.state){case"attached":return c.sendPresence([b]);case"initialized":case"detached":c.attach();case"attaching":return new Promise((C,O)=>{this.pendingPresence.push({presence:b,callback:M=>M?O(M):C()})});default:{const C=new Se("Unable to "+l+" presence channel while in "+c.state+" state",90001);throw C.code=90001,C}}}async leave(s){if(In(this))throw new A("clientId must have been specified to enter or leave a presence channel",40012,400);return this.leaveClient(void 0,s)}async leaveClient(s,r){const o=this.channel;if(!o.connectionManager.activeState())throw o.connectionManager.getError();f.logAction(this.logger,f.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+this.channel.name+", client = "+s);const l=$i.fromData(r);l.action="leave",s&&(l.clientId=s);const c=await l.encode(o.channelOptions);switch(o.state){case"attached":return o.sendPresence([c]);case"attaching":return new Promise((_,b)=>{this.pendingPresence.push({presence:c,callback:C=>C?b(C):_()})});case"initialized":case"failed":throw new Se("Unable to leave presence channel (incompatible state)",90001);default:throw o.invalidStateError()}}async get(s){const r=!s||("waitForSync"in s?s.waitForSync:!0);function o(c){return s?c.list(s):c.values()}if(this.channel.state==="suspended"){if(r)throw A.fromValues({statusCode:400,code:91005,message:"Presence state is out of sync due to channel being in the SUSPENDED state"});return o(this.members)}await this.channel.ensureAttached();const l=this.members;return r&&await l.waitSync(),o(this.members)}async history(s){f.logAction(this.logger,f.LOG_MICRO,"RealtimePresence.history()","channel = "+this.name);const r=this.channel.client.rest.presenceMixin;if(s&&s.untilAttach)if(this.channel.state==="attached")delete s.untilAttach,s.from_serial=this.channel.properties.attachSerial;else throw new A("option untilAttach requires the channel to be attached, was: "+this.channel.state,4e4,400);return r.history(this,s)}setPresence(s,r,o){f.logAction(this.logger,f.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+s.length+" participants; syncChannelSerial = "+o);let l,c;const _=this.members,b=this._myMembers,C=[],O=this.channel.connectionManager.connectionId;r&&(this.members.startSync(),o&&(c=o.match(/^[\w-]+:(.*)$/))&&(l=c[1]));for(let M of s)switch(M.action){case"leave":_.remove(M)&&C.push(M),M.connectionId===O&&!M.isSynthesized()&&b.remove(M);break;case"enter":case"present":case"update":_.put(M)&&C.push(M),M.connectionId===O&&b.put(M);break}r&&!l&&(_.endSync(),this.channel.syncChannelSerial=null);for(let M=0;M<C.length;M++){const z=C[M];this.subscriptions.emit(z.action,z)}}onAttached(s){f.logAction(this.logger,f.LOG_MINOR,"RealtimePresence.onAttached()","channel = "+this.channel.name+", hasPresence = "+s),s?this.members.startSync():(this._synthesizeLeaves(this.members.values()),this.members.clear()),this._ensureMyMembersPresent();const r=this.pendingPresence,o=r.length;if(o){this.pendingPresence=[];const l=[],c=Ee.create(this.logger);f.logAction(this.logger,f.LOG_MICRO,"RealtimePresence.onAttached","sending "+o+" queued presence messages");for(let _=0;_<o;_++){const b=r[_];l.push(b.presence),c.push(b.callback)}this.channel.sendPresence(l).then(()=>c()).catch(_=>c(_))}}actOnChannelState(s,r,o){switch(s){case"attached":this.onAttached(r);break;case"detached":case"failed":this._clearMyMembers(),this.members.clear();case"suspended":this.failPendingPresence(o);break}}failPendingPresence(s){if(this.pendingPresence.length){f.logAction(this.logger,f.LOG_MINOR,"RealtimeChannel.failPendingPresence","channel; name = "+this.channel.name+", err = "+it(s));for(let r=0;r<this.pendingPresence.length;r++)try{this.pendingPresence[r].callback(s)}catch{}this.pendingPresence=[]}}_clearMyMembers(){this._myMembers.clear()}_ensureMyMembersPresent(){const s=this._myMembers,r=this.channel.connectionManager.connectionId;for(const o in s.map){const l=s.map[o];f.logAction(this.logger,f.LOG_MICRO,"RealtimePresence._ensureMyMembersPresent()",'Auto-reentering clientId "'+l.clientId+'" into the presence set');const c=l.connectionId===r?l.id:void 0;this._enterOrUpdateClient(c,l.clientId,l.data,"enter").catch(_=>{const b=new A("Presence auto re-enter failed",91004,400,_);f.logAction(this.logger,f.LOG_ERROR,"RealtimePresence._ensureMyMembersPresent()","Presence auto re-enter failed; reason = "+it(_));const C=new Mn(this.channel.state,this.channel.state,!0,!1,b);this.channel.emit("update",C)})}}_synthesizeLeaves(s){const r=this.subscriptions;s.forEach(function(o){const l=$i.fromValues({action:"leave",connectionId:o.connectionId,clientId:o.clientId,data:o.data,encoding:o.encoding,timestamp:Date.now()});r.emit("leave",l)})}async subscribe(...s){const r=Ys.processListenerArgs(s),o=r[0],l=r[1],c=this.channel;if(c.state==="failed")throw A.fromValues(c.invalidStateError());this.subscriptions.on(o,l),c.channelOptions.attachOnSubscribe!==!1&&await c.attach()}unsubscribe(...s){const r=Ys.processListenerArgs(s),o=r[0],l=r[1];this.subscriptions.off(o,l)}},sd=id,rd=ti.WebSocket;function nd(s){return!!s.on}var od=class extends Rs{constructor(s,r,o){super(s,r,o),this.shortName=rd,o.heartbeats=E.Config.useProtocolHeartbeats,this.wsHost=o.host}static isAvailable(){return!!E.Config.WebSocket}createWebSocket(s,r){return this.uri=s+vi(r),new E.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){f.logAction(this.logger,f.LOG_MINOR,"WebSocketTransport.connect()","starting"),Rs.prototype.connect.call(this);const s=this,r=this.params,o=r.options,c=(o.tls?"wss://":"ws://")+this.wsHost+":"+J.getPort(o)+"/";f.logAction(this.logger,f.LOG_MINOR,"WebSocketTransport.connect()","uri: "+c),Vt(this.auth.getAuthParams(),function(_,b){if(s.isDisposed)return;let C="";for(const M in b)C+=" "+M+": "+b[M]+";";if(f.logAction(s.logger,f.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+C+" err: "+_),_){s.disconnect(_);return}const O=r.getConnectParams(b);try{const M=s.wsConnection=s.createWebSocket(c,O);M.binaryType=E.Config.binaryType,M.onopen=function(){s.onWsOpen()},M.onclose=function(z){s.onWsClose(z)},M.onmessage=function(z){s.onWsData(z.data)},M.onerror=function(z){s.onWsError(z)},nd(M)&&M.on("ping",function(){s.onActivity()})}catch(M){f.logAction(s.logger,f.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(M.stack||M.message)),s.disconnect(M)}})}send(s){const r=this.wsConnection;if(!r){f.logAction(this.logger,f.LOG_ERROR,"WebSocketTransport.send()","No socket connection");return}try{r.send(Ou(s,this.connectionManager.realtime._MsgPack,this.params.format))}catch(o){const l="Exception from ws connection when trying to send: "+it(o);f.logAction(this.logger,f.LOG_ERROR,"WebSocketTransport.send()",l),this.finish("disconnected",new A(l,5e4,500))}}onWsData(s){f.logAction(this.logger,f.LOG_MICRO,"WebSocketTransport.onWsData()","data received; length = "+s.length+"; type = "+typeof s);try{this.onProtocolMessage(Tu(s,this.connectionManager.realtime._MsgPack,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin,this.format))}catch(r){f.logAction(this.logger,f.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+r.stack)}}onWsOpen(){f.logAction(this.logger,f.LOG_MINOR,"WebSocketTransport.onWsOpen()","opened WebSocket"),this.emit("preconnect")}onWsClose(s){let r,o;if(typeof s=="object"?(o=s.code,r=s.wasClean||o===1e3):(o=s,r=o==1e3),delete this.wsConnection,r){f.logAction(this.logger,f.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket");const l=new A("Websocket closed",80003,400);this.finish("disconnected",l)}else{const l="Unclean disconnection of WebSocket ; code = "+o,c=new A(l,80003,400);f.logAction(this.logger,f.LOG_MINOR,"WebSocketTransport.onWsClose()",l),this.finish("disconnected",c)}this.emit("disposed")}onWsError(s){f.logAction(this.logger,f.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+s.message),E.Config.nextTick(()=>{this.disconnect(Error(s.message))})}dispose(){f.logAction(this.logger,f.LOG_MINOR,"WebSocketTransport.dispose()",""),this.isDisposed=!0;const s=this.wsConnection;s&&(s.onmessage=function(){},delete this.wsConnection,E.Config.nextTick(()=>{if(f.logAction(this.logger,f.LOG_MICRO,"WebSocketTransport.dispose()","closing websocket"),!s)throw new Error("WebSocketTransport.dispose(): wsConnection is not defined");s.close()}))}},pl=od,ad=class{static subscribeFilter(s,r,o){const l=c=>{var _,b,C,O,M,z;const q={name:c.name,refTimeserial:(b=(_=c.extras)==null?void 0:_.ref)==null?void 0:b.timeserial,refType:(O=(C=c.extras)==null?void 0:C.ref)==null?void 0:O.type,isRef:!!((z=(M=c.extras)==null?void 0:M.ref)!=null&&z.timeserial),clientId:c.clientId};Object.entries(r).find(([Q,F])=>F!==void 0?q[Q]!==F:!1)||o(c)};this.addFilteredSubscription(s,r,o,l),s.subscriptions.on(l)}static addFilteredSubscription(s,r,o,l){var c;if(s.filteredSubscriptions||(s.filteredSubscriptions=new Map),s.filteredSubscriptions.has(o)){const _=s.filteredSubscriptions.get(o);_.set(r,((c=_==null?void 0:_.get(r))==null?void 0:c.concat(l))||[l])}else s.filteredSubscriptions.set(o,new Map([[r,[l]]]))}static getAndDeleteFilteredSubscriptions(s,r,o){if(!s.filteredSubscriptions)return[];if(!o&&r)return Array.from(s.filteredSubscriptions.entries()).map(([_,b])=>{var C;let O=b.get(r);return b.delete(r),b.size===0&&((C=s.filteredSubscriptions)==null||C.delete(_)),O}).reduce((_,b)=>b?_.concat(...b):_,[]);if(!o||!s.filteredSubscriptions.has(o))return[];const l=s.filteredSubscriptions.get(o);if(!r){const _=Array.from(l.values()).reduce((b,C)=>b.concat(...C),[]);return s.filteredSubscriptions.delete(o),_}let c=l.get(r);return l.delete(r),c||[]}},li=class So extends Qu{constructor(r){var o;const l=So._MsgPack;if(!l)throw new Error("Expected DefaultRealtime._MsgPack to have been set");super(J.objectifyOptions(r,!0,"Realtime",f.defaultLogger,P(L({},Za),{Crypto:(o=So.Crypto)!=null?o:void 0,MsgPack:l,RealtimePresence:{RealtimePresence:sd,PresenceMessage:$i,WirePresenceMessage:$s},Annotations:{Annotation:Ks,WireAnnotation:Es,RealtimeAnnotations:cl,RestAnnotations:kn},WebSocketTransport:pl,MessageInteractions:ad})))}static get Crypto(){if(this._Crypto===null)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(r){this._Crypto=r}};li.Utils=re,li.ConnectionManager=_l,li.ProtocolMessage=Pu,li._Crypto=null,li.Message=Qa,li.PresenceMessage=el,li.Annotation=rl,li._MsgPack=null,li._Http=gt,li._PresenceMap=Bn,li._MessageEncoding=Hr;var Dn=li,Nn=Uint8Array,Xs=Uint32Array,Hn=Math.pow,ml=new Xs(8),vl=[],Zs=new Xs(64);function yl(s){return(s-(s|0))*Hn(2,32)|0}for(var Qs=2,er=0;er<64;){for(Un=!0,qr=2;qr<=Qs/2;qr++)Qs%qr===0&&(Un=!1);Un&&(er<8&&(ml[er]=yl(Hn(Qs,1/2))),vl[er]=yl(Hn(Qs,1/3)),er++),Qs++}var Un,qr,ld=!!new Nn(new Xs([1]).buffer)[0];function Wn(s){return ld?s>>>24|(s>>>16&255)<<8|(s&65280)<<8|s<<24:s}function bi(s,r){return s>>>r|s<<32-r}function Gr(s){var r=ml.slice(),o=s.length,l=o*8,c=512-(l+64)%512-1+l+65,_=new Nn(c/8),b=new Xs(_.buffer);_.set(s,0),_[o]=128,b[b.length-1]=Wn(l);for(var C,O=0;O<c/32;O+=16){var M=r.slice();for(C=0;C<64;C++){var z;if(C<16)z=Wn(b[O+C]);else{var q=Zs[C-15],Q=Zs[C-2];z=Zs[C-7]+Zs[C-16]+(bi(q,7)^bi(q,18)^q>>>3)+(bi(Q,17)^bi(Q,19)^Q>>>10)}Zs[C]=z|=0;for(var F=(bi(M[4],6)^bi(M[4],11)^bi(M[4],25))+(M[4]&M[5]^~M[4]&M[6])+M[7]+z+vl[C],pe=(bi(M[0],2)^bi(M[0],13)^bi(M[0],22))+(M[0]&M[1]^M[2]&(M[0]^M[1])),me=7;me>0;me--)M[me]=M[me-1];M[0]=F+pe|0,M[4]=M[4]+F|0}for(C=0;C<8;C++)r[C]=r[C]+M[C]|0}return new Nn(new Xs(r.map(function(Re){return Wn(Re)})).buffer)}function hd(s,r){if(s.length>64&&(s=Gr(s)),s.length<64){const C=new Uint8Array(64);C.set(s,0),s=C}for(var o=new Uint8Array(64),l=new Uint8Array(64),c=0;c<64;c++)o[c]=54^s[c],l[c]=92^s[c];var _=new Uint8Array(r.length+64);_.set(o,0),_.set(r,64);var b=new Uint8Array(96);return b.set(l,0),b.set(Gr(_),64),Gr(b)}var cd=class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}uint8ViewToBase64(s){let r="";const o=this.base64CharSet,l=s.byteLength,c=l%3,_=l-c;let b,C,O,M,z;for(let q=0;q<_;q=q+3)z=s[q]<<16|s[q+1]<<8|s[q+2],b=(z&16515072)>>18,C=(z&258048)>>12,O=(z&4032)>>6,M=z&63,r+=o[b]+o[C]+o[O]+o[M];return c==1?(z=s[_],b=(z&252)>>2,C=(z&3)<<4,r+=o[b]+o[C]+"=="):c==2&&(z=s[_]<<8|s[_+1],b=(z&64512)>>10,C=(z&1008)>>4,O=(z&15)<<2,r+=o[b]+o[C]+o[O]+"="),r}base64ToArrayBuffer(s){const r=atob==null?void 0:atob(s),o=r.length,l=new Uint8Array(o);for(let c=0;c<o;c++){const _=r.charCodeAt(c);l[c]=_}return this.toArrayBuffer(l)}isBuffer(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}toBuffer(s){if(!ArrayBuffer)throw new Error("Can't convert to Buffer: browser does not support the necessary types");if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return new Uint8Array(this.toArrayBuffer(s));throw new Error("BufferUtils.toBuffer expected an ArrayBuffer or a view onto one")}toArrayBuffer(s){if(!ArrayBuffer)throw new Error("Can't convert to ArrayBuffer: browser does not support the necessary types");if(s instanceof ArrayBuffer)return s;if(ArrayBuffer.isView(s))return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);throw new Error("BufferUtils.toArrayBuffer expected an ArrayBuffer or a view onto one")}base64Encode(s){return this.uint8ViewToBase64(this.toBuffer(s))}base64UrlEncode(s){return this.base64Encode(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}base64Decode(s){if(ArrayBuffer&&E.Config.atob)return this.base64ToArrayBuffer(s);throw new Error("Expected ArrayBuffer to exist and Platform.Config.atob to be configured")}hexEncode(s){return this.toBuffer(s).reduce((o,l)=>o+l.toString(16).padStart(2,"0"),"")}hexDecode(s){if(s.length%2!==0)throw new Error("Can't create a byte array from a hex string of odd length");const r=new Uint8Array(s.length/2);for(let o=0;o<r.length;o++)r[o]=parseInt(s.slice(2*o,2*(o+1)),16);return this.toArrayBuffer(r)}utf8Encode(s){if(E.Config.TextEncoder){const r=new E.Config.TextEncoder().encode(s);return this.toArrayBuffer(r)}else throw new Error("Expected TextEncoder to be configured")}utf8Decode(s){if(!this.isBuffer(s))throw new Error("Expected input of utf8decode to be an arraybuffer or typed array");if(TextDecoder)return new TextDecoder().decode(s);throw new Error("Expected TextDecoder to be configured")}areBuffersEqual(s,r){if(!s||!r)return!1;const o=this.toArrayBuffer(s),l=this.toArrayBuffer(r);if(o.byteLength!=l.byteLength)return!1;const c=new Uint8Array(o),_=new Uint8Array(l);for(var b=0;b<c.length;b++)if(c[b]!=_[b])return!1;return!0}byteLength(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)?s.byteLength:-1}arrayBufferViewToBuffer(s){return this.toArrayBuffer(s)}concat(s){const r=s.reduce((c,_)=>c+_.byteLength,0),o=new Uint8Array(r);let l=0;for(const c of s){const _=this.toBuffer(c);o.set(_,l),l+=_.byteLength}return o.buffer}sha256(s){const r=Gr(this.toBuffer(s));return this.toArrayBuffer(r)}hmacSha256(s,r){const o=hd(this.toBuffer(r),this.toBuffer(s));return this.toArrayBuffer(o)}},Sl=new cd,ud=function(s,r){var o="aes",l=256,c="cbc",_=16;function b(Q){if(Q.algorithm==="aes"&&Q.mode==="cbc"){if(Q.keyLength===128||Q.keyLength===256)return;throw new Error("Unsupported key length "+Q.keyLength+" for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)")}}function C(Q){return Q.replace("_","/").replace("-","+")}function O(Q){return Q instanceof M}class M{constructor(F,pe,me,Re){this.algorithm=F,this.keyLength=pe,this.mode=me,this.key=Re}}class z{static getDefaultParams(F){var pe;if(!F.key)throw new Error("Crypto.getDefaultParams: a key is required");typeof F.key=="string"?pe=r.toArrayBuffer(r.base64Decode(C(F.key))):F.key instanceof ArrayBuffer?pe=F.key:pe=r.toArrayBuffer(F.key);var me=F.algorithm||o,Re=pe.byteLength*8,st=F.mode||c,lt=new M(me,Re,st,pe);if(F.keyLength&&F.keyLength!==lt.keyLength)throw new Error("Crypto.getDefaultParams: a keyLength of "+F.keyLength+" was specified, but the key actually has length "+lt.keyLength);return b(lt),lt}static async generateRandomKey(F){try{return s.getRandomArrayBuffer((F||l)/8)}catch(pe){throw new A("Failed to generate random key: "+pe.message,400,5e4)}}static getCipher(F,pe){var me,Re=O(F)?F:this.getDefaultParams(F);return{cipherParams:Re,cipher:new q(Re,(me=F.iv)!=null?me:null,pe)}}}z.CipherParams=M;class q{constructor(F,pe,me){if(this.logger=me,!crypto.subtle)throw isSecureContext?new Error("Crypto operations are not possible since the browser’s SubtleCrypto class is unavailable (reason unknown)."):new Error("Crypto operations are is not possible since the current environment is a non-secure context and hence the browser’s SubtleCrypto class is not available.");this.algorithm=F.algorithm+"-"+String(F.keyLength)+"-"+F.mode,this.webCryptoAlgorithm=F.algorithm+"-"+F.mode,this.key=r.toArrayBuffer(F.key),this.iv=pe?r.toArrayBuffer(pe):null}concat(F,pe){const me=new ArrayBuffer(F.byteLength+pe.byteLength),Re=new DataView(me),st=new DataView(r.toArrayBuffer(F));for(let _t=0;_t<st.byteLength;_t++)Re.setInt8(_t,st.getInt8(_t));const lt=new DataView(r.toArrayBuffer(pe));for(let _t=0;_t<lt.byteLength;_t++)Re.setInt8(st.byteLength+_t,lt.getInt8(_t));return me}async encrypt(F){f.logAction(this.logger,f.LOG_MICRO,"CBCCipher.encrypt()","");const pe=await this.getIv(),me=await crypto.subtle.importKey("raw",this.key,this.webCryptoAlgorithm,!1,["encrypt"]),Re=await crypto.subtle.encrypt({name:this.webCryptoAlgorithm,iv:pe},me,F);return this.concat(pe,Re)}async decrypt(F){f.logAction(this.logger,f.LOG_MICRO,"CBCCipher.decrypt()","");const pe=r.toArrayBuffer(F),me=pe.slice(0,_),Re=pe.slice(_),st=await crypto.subtle.importKey("raw",this.key,this.webCryptoAlgorithm,!1,["decrypt"]);return crypto.subtle.decrypt({name:this.webCryptoAlgorithm,iv:me},st,Re)}async getIv(){if(this.iv){var F=this.iv;return this.iv=null,F}const pe=await s.getRandomArrayBuffer(_);return r.toArrayBuffer(pe)}}return z},bl=(s=>(s[s.REQ_SEND=0]="REQ_SEND",s[s.REQ_RECV=1]="REQ_RECV",s[s.REQ_RECV_POLL=2]="REQ_RECV_POLL",s[s.REQ_RECV_STREAM=3]="REQ_RECV_STREAM",s))(bl||{}),Pi=bl;function wl(){return new A("No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.",400,4e4)}var tr,Cl=(tr=class{constructor(s){this.checksInProgress=null,this.checkConnectivity=void 0,this.supportsAuthHeaders=!1,this.supportsLinkHeaders=!1;var r;this.client=s??null;const o=(s==null?void 0:s.options.connectivityCheckUrl)||J.connectivityCheckUrl,l=(r=s==null?void 0:s.options.connectivityCheckParams)!=null?r:null,c=!(s!=null&&s.options.connectivityCheckUrl),_=L(L({},Cl.bundledRequestImplementations),s==null?void 0:s._additionalHTTPRequestImplementations),b=_.XHRRequest,C=_.FetchRequest,O=!!(b||C);if(!O)throw wl();E.Config.xhrSupported&&b?(this.supportsAuthHeaders=!0,this.Request=async function(M,z,q,Q,F){return new Promise(pe=>{var me;const Re=b.createRequest(z,q,Q,F,Pi.REQ_SEND,(me=s&&s.options.timeouts)!=null?me:null,this.logger,M);Re.once("complete",(st,lt,_t,De,si)=>pe({error:st,body:lt,headers:_t,unpacked:De,statusCode:si})),Re.exec()})},s!=null&&s.options.disableConnectivityCheck?this.checkConnectivity=async function(){return!0}:this.checkConnectivity=async function(){var M;f.logAction(this.logger,f.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Sending; "+o);const z=await this.doUri(ie.Get,o,null,null,l);let q=!1;return c?q=!z.error&&((M=z.body)==null?void 0:M.replace(/\n/,""))=="yes":q=!z.error&&ye(z.statusCode),f.logAction(this.logger,f.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Result: "+q),q}):E.Config.fetchSupported&&C?(this.supportsAuthHeaders=!0,this.Request=async(M,z,q,Q,F)=>C(M,s??null,z,q,Q,F),s!=null&&s.options.disableConnectivityCheck?this.checkConnectivity=async function(){return!0}:this.checkConnectivity=async function(){var M;f.logAction(this.logger,f.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Sending; "+o);const z=await this.doUri(ie.Get,o,null,null,null),q=!z.error&&((M=z.body)==null?void 0:M.replace(/\n/,""))=="yes";return f.logAction(this.logger,f.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Result: "+q),q}):this.Request=async()=>({error:O?new Se("no supported HTTP transports available",null,400):wl()})}get logger(){var s,r;return(r=(s=this.client)==null?void 0:s.logger)!=null?r:f.defaultLogger}async doUri(s,r,o,l,c){return this.Request?this.Request(s,r,o,c,l):{error:new Se("Request invoked before assigned to",null,500)}}shouldFallback(s){const r=s.statusCode;return r===408&&!s.code||r===400&&!s.code||r>=500&&r<=504}},tr.methods=[ie.Get,ie.Delete,ie.Post,ie.Put,ie.Patch],tr.methodsWithoutBody=[ie.Get,ie.Delete],tr.methodsWithBody=[ie.Post,ie.Put,ie.Patch],tr),xl=Cl,As="ablyjs-storage-test",Ms=typeof Ki<"u"?Ki:typeof window<"u"?window:self,dd=class{constructor(){try{Ms.sessionStorage.setItem(As,As),Ms.sessionStorage.removeItem(As),this.sessionSupported=!0}catch{this.sessionSupported=!1}try{Ms.localStorage.setItem(As,As),Ms.localStorage.removeItem(As),this.localSupported=!0}catch{this.localSupported=!1}}get(s){return this._get(s,!1)}getSession(s){return this._get(s,!0)}remove(s){return this._remove(s,!1)}removeSession(s){return this._remove(s,!0)}set(s,r,o){return this._set(s,r,o,!1)}setSession(s,r,o){return this._set(s,r,o,!0)}_set(s,r,o,l){const c={value:r};return o&&(c.expires=Date.now()+o),this.storageInterface(l).setItem(s,JSON.stringify(c))}_get(s,r){if(r&&!this.sessionSupported)throw new Error("Session Storage not supported");if(!r&&!this.localSupported)throw new Error("Local Storage not supported");const o=this.storageInterface(r).getItem(s);if(!o)return null;const l=JSON.parse(o);return l.expires&&l.expires<Date.now()?(this.storageInterface(r).removeItem(s),null):l.value}_remove(s,r){return this.storageInterface(r).removeItem(s)}storageInterface(s){return s?Ms.sessionStorage:Ms.localStorage}},kl=new dd,Et=Ti(),fd=typeof EdgeRuntime=="string";typeof Window>"u"&&typeof WorkerGlobalScope>"u"&&!fd&&console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");function _d(){const s=Et.location;return!Et.WebSocket||!s||!s.origin||s.origin.indexOf("http")>-1}function gd(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}var pd=Et.navigator&&Et.navigator.userAgent.toString(),md=Et.location&&Et.location.href,vd={agent:"browser",logTimestamps:!0,userAgent:pd,currentUrl:md,binaryType:"arraybuffer",WebSocket:Et.WebSocket,fetchSupported:!!Et.fetch,xhrSupported:Et.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,allowComet:_d(),useProtocolHeartbeats:!0,supportsBinary:!!Et.TextDecoder,preferBinary:!1,ArrayBuffer:Et.ArrayBuffer,atob:Et.atob,nextTick:typeof Et.queueMicrotask=="function"?s=>Et.queueMicrotask(s):s=>Promise.resolve().then(s),addEventListener:Et.addEventListener,inspect:JSON.stringify,stringByteSize:function(s){return Et.TextDecoder&&new Et.TextEncoder().encode(s).length||s.length},TextEncoder:Et.TextEncoder,TextDecoder:Et.TextDecoder,getRandomArrayBuffer:async function(s){const r=new Uint8Array(s);return Et.crypto.getRandomValues(r),r.buffer},isWebworker:gd(),push:{platform:"browser",formFactor:"desktop",storage:kl}},El=vd;function yd(s){const r=[80015,80017,80030];return s.code?Fe.isTokenErr(s)?!1:r.includes(s.code)?!0:s.code>=4e4&&s.code<5e4:!1}function Fn(s){return yd(s)?[ei({action:ue.ERROR,error:s})]:[ei({action:ue.DISCONNECTED,error:s})]}var Sd=class extends Rs{constructor(s,r,o){super(s,r,o,!0),this.onAuthUpdated=l=>{this.authParams={access_token:l.token}},this.stream="stream"in o?o.stream:!0,this.sendRequest=null,this.recvRequest=null,this.pendingCallback=null,this.pendingItems=null}connect(){f.logAction(this.logger,f.LOG_MINOR,"CometTransport.connect()","starting"),Rs.prototype.connect.call(this);const s=this.params,r=s.options,o=s.host||r.primaryDomain,l=J.getPort(r),c=r.tls?"https://":"http://";this.baseUri=c+o+":"+l+"/comet/";const _=this.baseUri+"connect";f.logAction(this.logger,f.LOG_MINOR,"CometTransport.connect()","uri: "+_),Vt(this.auth.getAuthParams(),(b,C)=>{if(b){this.disconnect(b);return}if(this.isDisposed)return;this.authParams=C;const O=this.params.getConnectParams(C);"stream"in O&&(this.stream=O.stream),f.logAction(this.logger,f.LOG_MINOR,"CometTransport.connect()","connectParams:"+vi(O));let M=!1;const z=this.recvRequest=this.createRequest(_,null,O,null,this.stream?Pi.REQ_RECV_STREAM:Pi.REQ_RECV);z.on("data",q=>{this.recvRequest&&(M||(M=!0,this.emit("preconnect")),this.onData(q))}),z.on("complete",q=>{if(this.recvRequest||(q=q||new A("Request cancelled",80003,400)),this.recvRequest=null,!M&&!q&&(M=!0,this.emit("preconnect")),this.onActivity(),q){q.code?this.onData(Fn(q)):this.disconnect(q);return}E.Config.nextTick(()=>{this.recv()})}),z.exec()})}requestClose(){f.logAction(this.logger,f.LOG_MINOR,"CometTransport.requestClose()"),this._requestCloseOrDisconnect(!0)}requestDisconnect(){f.logAction(this.logger,f.LOG_MINOR,"CometTransport.requestDisconnect()"),this._requestCloseOrDisconnect(!1)}_requestCloseOrDisconnect(s){const r=s?this.closeUri:this.disconnectUri;if(r){const o=this.createRequest(r,null,this.authParams,null,Pi.REQ_SEND);o.on("complete",l=>{l&&(f.logAction(this.logger,f.LOG_ERROR,"CometTransport.request"+(s?"Close()":"Disconnect()"),"request returned err = "+it(l)),this.finish("disconnected",l))}),o.exec()}}dispose(){f.logAction(this.logger,f.LOG_MINOR,"CometTransport.dispose()",""),this.isDisposed||(this.isDisposed=!0,this.recvRequest&&(f.logAction(this.logger,f.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null),this.finish("disconnected",as.disconnected()),E.Config.nextTick(()=>{this.emit("disposed")}))}onConnect(s){var r;if(this.isDisposed)return;const o=(r=s.connectionDetails)==null?void 0:r.connectionKey;Rs.prototype.onConnect.call(this,s);const l=this.baseUri+o;f.logAction(this.logger,f.LOG_MICRO,"CometTransport.onConnect()","baseUri = "+l),this.sendUri=l+"/send",this.recvUri=l+"/recv",this.closeUri=l+"/close",this.disconnectUri=l+"/disconnect"}send(s){if(this.sendRequest){this.pendingItems=this.pendingItems||[],this.pendingItems.push(s);return}const r=this.pendingItems||[];r.push(s),this.pendingItems=null,this.sendItems(r)}sendAnyPending(){const s=this.pendingItems;s&&(this.pendingItems=null,this.sendItems(s))}sendItems(s){const r=this.sendRequest=this.createRequest(this.sendUri,null,this.authParams,this.encodeRequest(s),Pi.REQ_SEND);r.on("complete",(o,l)=>{if(o&&f.logAction(this.logger,f.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+it(o)),this.sendRequest=null,o){o.code?this.onData(Fn(o)):this.disconnect(o);return}l&&this.onData(l),this.pendingItems&&E.Config.nextTick(()=>{this.sendRequest||this.sendAnyPending()})}),r.exec()}recv(){if(this.recvRequest||!this.isConnected)return;const s=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,this.stream?Pi.REQ_RECV_STREAM:Pi.REQ_RECV_POLL);s.on("data",r=>{this.onData(r)}),s.on("complete",r=>{if(this.recvRequest=null,this.onActivity(),r){r.code?this.onData(Fn(r)):this.disconnect(r);return}E.Config.nextTick(()=>{this.recv()})}),s.exec()}onData(s){try{const r=this.decodeResponse(s);if(r&&r.length)for(let o=0;o<r.length;o++)this.onProtocolMessage(En(r[o],this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin))}catch(r){f.logAction(this.logger,f.LOG_ERROR,"CometTransport.onData()","Unexpected exception handing channel event: "+r.stack)}}encodeRequest(s){return JSON.stringify(s)}decodeResponse(s){return typeof s=="string"?JSON.parse(s):s}},bd=Sd;function wd(s,r){return Wi(_i(r)).includes("x-ably-errorcode")}function Cd(s,r){if(wd(s,r))return s.error&&A.fromValues(s.error)}var xd=function(){},kd=0,Rl={};function Ed(s,r){return s.getResponseHeader&&s.getResponseHeader(r)}function Rd(s){return s.getResponseHeader&&(s.getResponseHeader("transfer-encoding")||!s.getResponseHeader("content-length"))}function Ad(s){const r=s.getAllResponseHeaders().trim().split(`\r
13
- `),o={};for(let l=0;l<r.length;l++){const c=r[l].split(":").map(_=>_.trim());o[c[0].toLowerCase()]=c[1]}return o}var Md=class Yh extends qe{constructor(r,o,l,c,_,b,C,O){super(C),l=l||{},l.rnd=Ui(),this.uri=r+vi(l),this.headers=o||{},this.body=c,this.method=O?O.toUpperCase():je(c)?"GET":"POST",this.requestMode=_,this.timeouts=b,this.timedOut=!1,this.requestComplete=!1,this.id=String(++kd),Rl[this.id]=this}static createRequest(r,o,l,c,_,b,C,O){const M=b||J.TIMEOUTS;return new Yh(r,o,ct(l),c,_,M,C,O)}complete(r,o,l,c,_){this.requestComplete||(this.requestComplete=!0,!r&&o&&this.emit("data",o),this.emit("complete",r,o,l,c,_),this.dispose())}abort(){this.dispose()}exec(){let r=this.headers;const o=this.requestMode==Pi.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout,l=this.timer=setTimeout(()=>{this.timedOut=!0,_.abort()},o),c=this.method,_=this.xhr=new XMLHttpRequest,b=r.accept;let C=this.body,O="text";b?b.indexOf("application/x-msgpack")===0&&(O="arraybuffer"):r.accept="application/json",C&&(r["content-type"]||(r["content-type"]="application/json")).indexOf("application/json")>-1&&typeof C!="string"&&(C=JSON.stringify(C)),_.open(c,this.uri,!0),_.responseType=O,"authorization"in r&&(_.withCredentials=!0);for(const De in r)_.setRequestHeader(De,r[De]);const M=(De,si,jt,nr)=>{var Os;let jn=si+" (event type: "+De.type+")";(Os=this==null?void 0:this.xhr)!=null&&Os.statusText&&(jn+=", current statusText is "+this.xhr.statusText),f.logAction(this.logger,f.LOG_ERROR,"Request.on"+De.type+"()",jn),this.complete(new Se(jn,jt,nr))};_.onerror=De=>{M(De,"XHR error occurred",null,400)},_.onabort=De=>{this.timedOut?M(De,"Request aborted due to request timeout expiring",null,408):M(De,"Request cancelled",null,400)},_.ontimeout=De=>{M(De,"Request timed out",null,408)};let z,q,Q,F=0,pe=!1;const me=()=>{if(clearTimeout(l),Q=q<400,q==204){this.complete(null,null,null,null,q);return}z=this.requestMode==Pi.REQ_RECV_STREAM&&Q&&Rd(_)},Re=()=>{let De;try{const jt=Ed(_,"content-type");if(jt?jt.indexOf("application/json")>=0:_.responseType=="text"){const Os=_.responseType==="arraybuffer"?E.BufferUtils.utf8Decode(_.response):String(_.responseText);Os.length?De=JSON.parse(Os):De=Os,pe=!0}else De=_.response;De.response!==void 0?(q=De.statusCode,Q=q<400,r=De.headers,De=De.response):r=Ad(_)}catch(jt){this.complete(new Se("Malformed response body from server: "+jt.message,null,400));return}if(Q||Array.isArray(De)){this.complete(null,De,r,pe,q);return}let si=Cd(De,r);si||(si=new Se("Error response received from server: "+q+" body was: "+E.Config.inspect(De),null,q)),this.complete(si,De,r,pe,q)};function st(){const De=_.responseText,si=De.length-1;let jt,nr;for(;F<si&&(jt=De.indexOf(`
14
- `,F))>-1;)nr=De.slice(F,jt),F=jt+1,lt(nr)}const lt=De=>{try{De=JSON.parse(De)}catch(si){this.complete(new Se("Malformed response body from server: "+si.message,null,400));return}this.emit("data",De)},_t=()=>{st(),this.streamComplete=!0,E.Config.nextTick(()=>{this.complete()})};_.onreadystatechange=()=>{const De=_.readyState;De<3||_.status!==0&&(q===void 0&&(q=_.status,me()),De==3&&z?st():De==4&&(z?_t():Re()))},_.send(C)}dispose(){const r=this.xhr;if(r){r.onreadystatechange=r.onerror=r.onabort=r.ontimeout=xd,this.xhr=null;const o=this.timer;o&&(clearTimeout(o),this.timer=null),this.requestComplete||r.abort()}delete Rl[this.id]}},Al=Md,Ml=ti.XhrPolling,Od=class extends bd{constructor(s,r,o){super(s,r,o),this.shortName=Ml,o.stream=!1,this.shortName=Ml}static isAvailable(){return!!(E.Config.xhrSupported&&E.Config.allowComet)}toString(){return"XHRPollingTransport; uri="+this.baseUri+"; isConnected="+this.isConnected}createRequest(s,r,o,l,c){return Al.createRequest(s,r,o,l,c,this.timeouts,this.logger)}},Td=Od,Pd=["xhr_polling"],Ld={order:Pd,bundledImplementations:{web_socket:pl,xhr_polling:Td}},Bd=Ld,Id={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[ti.XhrPolling,ti.WebSocket]},Dd=Id;function Nd(s){if(s===void 0)return"undefined";let r,o;if(s instanceof ArrayBuffer?(o="ArrayBuffer",r=new DataView(s)):s instanceof DataView&&(o="DataView",r=s),!r)return JSON.stringify(s);const l=[];for(let c=0;c<s.byteLength;c++){if(c>20){l.push("...");break}let _=r.getUint8(c).toString(16);_.length===1&&(_="0"+_),l.push(_)}return"<"+o+" "+l.join(" ")+">"}function ir(s,r,o){const c=new TextEncoder().encode(o);for(let _=0;_<c.length;_++)s.setUint8(r+_,c[_])}function Ol(s,r,o){return new TextDecoder().decode(s.buffer.slice(r,r+o))}function zn(s){return new TextEncoder().encode(s).length}function Hd(s,r){const o=rr(s,r);if(o===0)return;const l=new ArrayBuffer(o),c=new DataView(l);return sr(s,c,0,r),l}var qn=65536*65536,Tl=1/qn;function Ud(s,r){return r=r||0,s.getInt32(r)*qn+s.getUint32(r+4)}function Wd(s,r){return r=r||0,s.getUint32(r)*qn+s.getUint32(r+4)}function Fd(s,r,o){o<9223372036854776e3?(s.setInt32(r,Math.floor(o*Tl)),s.setInt32(r+4,o&-1)):(s.setUint32(r,2147483647),s.setUint32(r+4,2147483647))}function zd(s,r,o){o<18446744073709552e3?(s.setUint32(r,Math.floor(o*Tl)),s.setInt32(r+4,o&-1)):(s.setUint32(r,4294967295),s.setUint32(r+4,4294967295))}var qd=class{constructor(s,r){this.map=o=>{const l={};for(let c=0;c<o;c++){const _=this.parse();l[_]=this.parse()}return l},this.bin=o=>{const l=new ArrayBuffer(o);return new Uint8Array(l).set(new Uint8Array(this.view.buffer,this.offset,o),0),this.offset+=o,l},this.buf=this.bin,this.str=o=>{const l=Ol(this.view,this.offset,o);return this.offset+=o,l},this.array=o=>{const l=new Array(o);for(let c=0;c<o;c++)l[c]=this.parse();return l},this.ext=o=>(this.offset+=o,{type:this.view.getInt8(this.offset),data:this.buf(o)}),this.parse=()=>{const o=this.view.getUint8(this.offset);let l,c;if((o&128)===0)return this.offset++,o;if((o&240)===128)return c=o&15,this.offset++,this.map(c);if((o&240)===144)return c=o&15,this.offset++,this.array(c);if((o&224)===160)return c=o&31,this.offset++,this.str(c);if((o&224)===224)return l=this.view.getInt8(this.offset),this.offset++,l;switch(o){case 192:return this.offset++,null;case 193:this.offset++;return;case 194:return this.offset++,!1;case 195:return this.offset++,!0;case 196:return c=this.view.getUint8(this.offset+1),this.offset+=2,this.bin(c);case 197:return c=this.view.getUint16(this.offset+1),this.offset+=3,this.bin(c);case 198:return c=this.view.getUint32(this.offset+1),this.offset+=5,this.bin(c);case 199:return c=this.view.getUint8(this.offset+1),this.offset+=2,this.ext(c);case 200:return c=this.view.getUint16(this.offset+1),this.offset+=3,this.ext(c);case 201:return c=this.view.getUint32(this.offset+1),this.offset+=5,this.ext(c);case 202:return l=this.view.getFloat32(this.offset+1),this.offset+=5,l;case 203:return l=this.view.getFloat64(this.offset+1),this.offset+=9,l;case 204:return l=this.view.getUint8(this.offset+1),this.offset+=2,l;case 205:return l=this.view.getUint16(this.offset+1),this.offset+=3,l;case 206:return l=this.view.getUint32(this.offset+1),this.offset+=5,l;case 207:return l=Wd(this.view,this.offset+1),this.offset+=9,l;case 208:return l=this.view.getInt8(this.offset+1),this.offset+=2,l;case 209:return l=this.view.getInt16(this.offset+1),this.offset+=3,l;case 210:return l=this.view.getInt32(this.offset+1),this.offset+=5,l;case 211:return l=Ud(this.view,this.offset+1),this.offset+=9,l;case 212:return c=1,this.offset++,this.ext(c);case 213:return c=2,this.offset++,this.ext(c);case 214:return c=4,this.offset++,this.ext(c);case 215:return c=8,this.offset++,this.ext(c);case 216:return c=16,this.offset++,this.ext(c);case 217:return c=this.view.getUint8(this.offset+1),this.offset+=2,this.str(c);case 218:return c=this.view.getUint16(this.offset+1),this.offset+=3,this.str(c);case 219:return c=this.view.getUint32(this.offset+1),this.offset+=5,this.str(c);case 220:return c=this.view.getUint16(this.offset+1),this.offset+=3,this.array(c);case 221:return c=this.view.getUint32(this.offset+1),this.offset+=5,this.array(c);case 222:return c=this.view.getUint16(this.offset+1),this.offset+=3,this.map(c);case 223:return c=this.view.getUint32(this.offset+1),this.offset+=5,this.map(c)}throw new Error("Unknown type 0x"+o.toString(16))},this.offset=r||0,this.view=s}};function Gd(s){const r=new DataView(s),o=new qd(r),l=o.parse();if(o.offset!==s.byteLength)throw new Error(s.byteLength-o.offset+" trailing bytes");return l}function Pl(s,r){return Object.keys(s).filter(function(o){const l=s[o],c=typeof l;return(!r||l!=null)&&(c!=="function"||!!l.toJSON)})}function sr(s,r,o,l){const c=typeof s;if(typeof s=="string"){const _=zn(s);if(_<32)return r.setUint8(o,_|160),ir(r,o+1,s),1+_;if(_<256)return r.setUint8(o,217),r.setUint8(o+1,_),ir(r,o+2,s),2+_;if(_<65536)return r.setUint8(o,218),r.setUint16(o+1,_),ir(r,o+3,s),3+_;if(_<4294967296)return r.setUint8(o,219),r.setUint32(o+1,_),ir(r,o+5,s),5+_}if(ArrayBuffer.isView&&ArrayBuffer.isView(s)&&(s=s.buffer),s instanceof ArrayBuffer){const _=s.byteLength;if(_<256)return r.setUint8(o,196),r.setUint8(o+1,_),new Uint8Array(r.buffer).set(new Uint8Array(s),o+2),2+_;if(_<65536)return r.setUint8(o,197),r.setUint16(o+1,_),new Uint8Array(r.buffer).set(new Uint8Array(s),o+3),3+_;if(_<4294967296)return r.setUint8(o,198),r.setUint32(o+1,_),new Uint8Array(r.buffer).set(new Uint8Array(s),o+5),5+_}if(typeof s=="number"){if(Math.floor(s)!==s)return r.setUint8(o,203),r.setFloat64(o+1,s),9;if(s>=0){if(s<128)return r.setUint8(o,s),1;if(s<256)return r.setUint8(o,204),r.setUint8(o+1,s),2;if(s<65536)return r.setUint8(o,205),r.setUint16(o+1,s),3;if(s<4294967296)return r.setUint8(o,206),r.setUint32(o+1,s),5;if(s<18446744073709552e3)return r.setUint8(o,207),zd(r,o+1,s),9;throw new Error("Number too big 0x"+s.toString(16))}if(s>=-32)return r.setInt8(o,s),1;if(s>=-128)return r.setUint8(o,208),r.setInt8(o+1,s),2;if(s>=-32768)return r.setUint8(o,209),r.setInt16(o+1,s),3;if(s>=-2147483648)return r.setUint8(o,210),r.setInt32(o+1,s),5;if(s>=-9223372036854776e3)return r.setUint8(o,211),Fd(r,o+1,s),9;throw new Error("Number too small -0x"+(-s).toString(16).substr(1))}if(c==="undefined")return l?0:(r.setUint8(o,212),r.setUint8(o+1,0),r.setUint8(o+2,0),3);if(s===null)return l?0:(r.setUint8(o,192),1);if(c==="boolean")return r.setUint8(o,s?195:194),1;if(typeof s.toJSON=="function")return sr(s.toJSON(),r,o,l);if(c==="object"){let _,b=0,C;const O=Array.isArray(s);if(O?_=s.length:(C=Pl(s,l),_=C.length),_<16?(r.setUint8(o,_|(O?144:128)),b=1):_<65536?(r.setUint8(o,O?220:222),r.setUint16(o+1,_),b=3):_<4294967296&&(r.setUint8(o,O?221:223),r.setUint32(o+1,_),b=5),O)for(let M=0;M<_;M++)b+=sr(s[M],r,o+b,l);else if(C)for(let M=0;M<_;M++){const z=C[M];b+=sr(z,r,o+b),b+=sr(s[z],r,o+b,l)}return b}if(c==="function")return 0;throw new Error("Unknown type "+c)}function rr(s,r){const o=typeof s;if(o==="string"){const l=zn(s);if(l<32)return 1+l;if(l<256)return 2+l;if(l<65536)return 3+l;if(l<4294967296)return 5+l}if(ArrayBuffer.isView&&ArrayBuffer.isView(s)&&(s=s.buffer),s instanceof ArrayBuffer){const l=s.byteLength;if(l<256)return 2+l;if(l<65536)return 3+l;if(l<4294967296)return 5+l}if(typeof s=="number"){if(Math.floor(s)!==s)return 9;if(s>=0){if(s<128)return 1;if(s<256)return 2;if(s<65536)return 3;if(s<4294967296)return 5;if(s<18446744073709552e3)return 9;throw new Error("Number too big 0x"+s.toString(16))}if(s>=-32)return 1;if(s>=-128)return 2;if(s>=-32768)return 3;if(s>=-2147483648)return 5;if(s>=-9223372036854776e3)return 9;throw new Error("Number too small -0x"+s.toString(16).substr(1))}if(o==="boolean")return 1;if(s===null)return r?0:1;if(s===void 0)return r?0:3;if(typeof s.toJSON=="function")return rr(s.toJSON(),r);if(o==="object"){let l,c=0;if(Array.isArray(s)){l=s.length;for(let _=0;_<l;_++)c+=rr(s[_],r)}else{const _=Pl(s,r);l=_.length;for(let b=0;b<l;b++){const C=_[b];c+=rr(C)+rr(s[C],r)}}if(l<16)return 1+c;if(l<65536)return 3+c;if(l<4294967296)return 5+c;throw new Error("Array or object too long 0x"+l.toString(16))}if(o==="function")return 0;throw new Error("Unknown type "+o)}var Gn={encode:Hd,decode:Gd,inspect:Nd,utf8Write:ir,utf8Read:Ol,utf8ByteCount:zn};function jd(s,r){return!!r.get("x-ably-errorcode")}function $d(s,r){if(jd(s,r))return s.error&&A.fromValues(s.error)}function Vd(s){const r={};return s.forEach((o,l)=>{r[l]=o}),r}async function Kd(s,r,o,l,c,_){const b=new Headers(l||{}),C=s?s.toUpperCase():je(_)?"GET":"POST",O=new AbortController;let M;const z=new Promise(F=>{M=setTimeout(()=>{O.abort(),F({error:new Se("Request timed out",null,408)})},r?r.options.timeouts.httpRequestTimeout:J.TIMEOUTS.httpRequestTimeout)}),q={method:C,headers:b,body:_,signal:O.signal};E.Config.isWebworker||(q.credentials=b.has("authorization")?"include":"same-origin");const Q=(async()=>{try{const F=new URLSearchParams(c||{});F.set("rnd",Ui());const pe=o+"?"+F,me=await Ti().fetch(pe,q);if(clearTimeout(M),me.status==204)return{error:null,statusCode:me.status};const Re=me.headers.get("Content-Type");let st;Re&&Re.indexOf("application/x-msgpack")>-1?st=await me.arrayBuffer():Re&&Re.indexOf("application/json")>-1?st=await me.json():st=await me.text();const lt=!!Re&&Re.indexOf("application/x-msgpack")===-1,_t=Vd(me.headers);return me.ok?{error:null,body:st,headers:_t,unpacked:lt,statusCode:me.status}:{error:$d(st,me.headers)||new Se("Error response received from server: "+me.status+" body was: "+E.Config.inspect(st),null,me.status),body:st,headers:_t,unpacked:lt,statusCode:me.status}}catch(F){return clearTimeout(M),{error:F}}})();return Promise.race([z,Q])}var Yd={XHRRequest:Al,FetchRequest:Kd},Ll=ud(El,Sl);E.Crypto=Ll,E.BufferUtils=Sl,E.Http=xl,E.Config=El,E.Transports=Bd,E.WebStorage=kl;for(const s of[On,Dn])s.Crypto=Ll,s._MsgPack=Gn;xl.bundledRequestImplementations=Yd,f.initLogHandlers(),E.Defaults=Oe(Dd),E.Config.agent&&(E.Defaults.agent+=" "+E.Config.agent);var Jd={ErrorInfo:A,Rest:On,Realtime:Dn,msgpack:Gn,makeProtocolMessageFromDeserialized:ll};if(typeof n.exports=="object"&&typeof i=="object"){var Xd=(s,r,o,l)=>{if(r&&typeof r=="object"||typeof r=="function")for(let c of Object.getOwnPropertyNames(r))!Object.prototype.hasOwnProperty.call(s,c)&&c!==o&&Object.defineProperty(s,c,{get:()=>r[c],enumerable:!(l=Object.getOwnPropertyDescriptor(r,c))||l.enumerable});return s};n.exports=Xd(n.exports,i)}return n.exports})})(Zr)),Zr.exports}var qf=zf();class Gf{constructor(t){Ze(this,"ably",null);Ze(this,"channel",null);Ze(this,"opts");Ze(this,"_connected",!1);Ze(this,"clientId",null);Ze(this,"messageHandlers",[]);Ze(this,"peerJoinedHandlers",[]);Ze(this,"peerLeftHandlers",[]);Ze(this,"errorHandlers",[]);Ze(this,"disconnectHandlers",[]);if(!t.key&&!t.token)throw new Error("Ably API key or token is required");this.opts=t}get connected(){return this._connected}async connect(t,i){this.clientId=`airloom-${i}-${Date.now()}`;const n={clientId:this.clientId,queryTime:!0};this.opts.key?n.key=this.opts.key:n.token=this.opts.token,this.ably=new qf.Realtime(n),await new Promise((d,g)=>{this.ably.connection.once("connected",()=>d()),this.ably.connection.once("failed",v=>{var p;g(new Error(((p=v==null?void 0:v.reason)==null?void 0:p.message)??"Ably connection failed"))})}),this._connected=!0,this.ably.connection.on("disconnected",()=>{this._connected=!1,this.disconnectHandlers.forEach(d=>d())}),this.ably.connection.on("connected",()=>{this._connected=!0,this.channel&&this.channel.presence.get().then(d=>{d.some(v=>v.clientId!==this.clientId)&&this.peerJoinedHandlers.forEach(v=>v())}).catch(()=>{})}),this.ably.connection.on("failed",d=>{var v;this._connected=!1;const g=new Error(((v=d==null?void 0:d.reason)==null?void 0:v.message)??"Ably connection failed");this.errorHandlers.forEach(p=>p(g))}),this.channel=this.ably.channels.get(`airloom:${t}`),this.channel.subscribe("forward",d=>{d.clientId!==this.clientId&&typeof d.data=="string"&&this.messageHandlers.forEach(g=>g(d.data))}),this.channel.presence.subscribe("enter",d=>{d.clientId!==this.clientId&&this.peerJoinedHandlers.forEach(g=>g())}),this.channel.presence.subscribe("leave",d=>{d.clientId!==this.clientId&&this.peerLeftHandlers.forEach(g=>g())}),await this.channel.presence.enter({role:i}),(await this.channel.presence.get()).some(d=>d.clientId!==this.clientId)&&this.peerJoinedHandlers.forEach(d=>d())}send(t){!this.channel||!this._connected||this.channel.publish("forward",t)}onMessage(t){this.messageHandlers.push(t)}onPeerJoined(t){this.peerJoinedHandlers.push(t)}onPeerLeft(t){this.peerLeftHandlers.push(t)}onError(t){this.errorHandlers.push(t)}onDisconnect(t){this.disconnectHandlers.push(t)}close(){var t,i,n;(t=this.channel)==null||t.presence.leave().catch(()=>{}),(i=this.channel)==null||i.detach().catch(()=>{});try{(n=this.ably)==null||n.close()}catch{}this.channel=null,this.ably=null,this._connected=!1}}/**
12
+ `;return b.mac=b.mac||j(Q,_),f.logAction(this.logger,f.LOG_MINOR,"Auth.getTokenRequest()","generated signed request"),b}async getAuthParams(){if(this.method=="basic")return{key:this.key};{let s=await this._ensureValidAuthCredentials(!1);if(!s)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{access_token:s.token}}}async getAuthHeaders(){if(this.method=="basic")return{authorization:"Basic "+this.basicKey};{const s=await this._ensureValidAuthCredentials(!1);if(!s)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{authorization:"Bearer "+ns(s.token)}}}_saveBasicOptions(s){this.method="basic",this.key=s.key,this.basicKey=ns(s.key),this.authOptions=s||{},"clientId"in s&&this._userSetClientId(s.clientId)}_saveTokenOptions(s,r){this.method="token",s&&(this.tokenParams=s),r&&(r.token&&(r.tokenDetails=typeof r.token=="string"?{token:r.token}:r.token),r.tokenDetails&&(this.tokenDetails=r.tokenDetails),"clientId"in r&&this._userSetClientId(r.clientId),this.authOptions=r)}async _ensureValidAuthCredentials(s){const r=this.tokenDetails;if(r){if(this._tokenClientIdMismatch(r.clientId))throw new A("Mismatch between clientId in token ("+r.clientId+") and current clientId ("+this.clientId+")",40102,403);if(!this.client.isTimeOffsetSet()||!r.expires||r.expires>=this.client.getTimestampUsingOffset())return f.logAction(this.logger,f.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+r.expires),r;f.logAction(this.logger,f.LOG_MINOR,"Auth.getToken()","deleting expired token"),this.tokenDetails=null}const o=(this.waitingForTokenRequest||(this.waitingForTokenRequest=Ee.create(this.logger))).createPromise();if(this.currentTokenRequestId!==null&&!s)return o;const l=this.currentTokenRequestId=x();let c,_=null;try{c=await this.requestToken(this.tokenParams,this.authOptions)}catch(C){_=C}if(this.currentTokenRequestId>l)return f.logAction(this.logger,f.LOG_MINOR,"Auth._ensureValidAuthCredentials()","Discarding token request response; overtaken by newer one"),o;this.currentTokenRequestId=null;const b=this.waitingForTokenRequest;return this.waitingForTokenRequest=null,_?(b==null||b.rejectAll(_),o):(b==null||b.resolveAll(this.tokenDetails=c),o)}_userSetClientId(s){if(typeof s=="string"||s===null){if(s==="*")throw new A('Can’t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, instantiate the library with {defaultTokenParams: {clientId: "*"}}), or if calling authorize(), pass it in as a tokenParam: authorize({clientId: "*"}, authOptions)',40012,400);{const r=this._uncheckedSetClientId(s);if(r)throw r}}else throw new A("clientId must be either a string or null",40012,400)}_uncheckedSetClientId(s){if(this._tokenClientIdMismatch(s)){const r="Unexpected clientId mismatch: client has "+this.clientId+", requested "+s,o=new A(r,40102,401);return f.logAction(this.logger,f.LOG_ERROR,"Auth._uncheckedSetClientId()",r),o}else return this.clientId=this.tokenParams.clientId=s,null}_tokenClientIdMismatch(s){return!!(this.clientId&&this.clientId!=="*"&&s&&s!=="*"&&this.clientId!==s)}static isTokenErr(s){return s.code&&s.code>=40140&&s.code<40150}revokeTokens(s,r){return this.client.rest.revokeTokens(s,r)}async _getTimestamp(s){return this.client.getTimestamp(s||!!this.authOptions.queryTime)}},Fe=Ge;function Ye(s){const r=[];if(s)for(const o in s)r.push(o+"="+s[o]);return r.join("&")}function Pe(s,r){return s+(r?"?":"")+Ye(r)}function Je(s,r,o,l,c){s.error?f.logActionNoStrip(c,f.LOG_MICRO,"Http."+r+"()","Received Error; "+Pe(o,l)+"; Error: "+it(s.error)):f.logActionNoStrip(c,f.LOG_MICRO,"Http."+r+"()","Received; "+Pe(o,l)+"; Headers: "+Ye(s.headers)+"; StatusCode: "+s.statusCode+"; Body"+(E.BufferUtils.isBuffer(s.body)?" (Base64): "+E.BufferUtils.base64Encode(s.body):": "+s.body))}function Xe(s,r,o,l,c){c.shouldLog(f.LOG_MICRO)&&f.logActionNoStrip(c,f.LOG_MICRO,"Http."+s+"()","Sending; "+Pe(r,l)+"; Body"+(E.BufferUtils.isBuffer(o)?" (Base64): "+E.BufferUtils.base64Encode(o):": "+o))}var gt=class{constructor(s){this.client=s,this.platformHttp=new E.Http(s),this.checkConnectivity=this.platformHttp.checkConnectivity?()=>this.platformHttp.checkConnectivity():void 0}get logger(){var s,r;return(r=(s=this.client)==null?void 0:s.logger)!=null?r:f.defaultLogger}get supportsAuthHeaders(){return this.platformHttp.supportsAuthHeaders}get supportsLinkHeaders(){return this.platformHttp.supportsLinkHeaders}_getHosts(s){const r=s.connection,o=r&&r.connectionManager.host;return o?[o].concat(J.getFallbackHosts(s.options)):J.getHosts(s.options)}async do(s,r,o,l,c){try{const _=this.client;if(!_)return{error:new A("http.do called without client",5e4,500)};const b=typeof r=="function"?r:function(q){return _.baseUri(q)+r},C=_._currentFallback;if(C)if(C.validUntil>Date.now()){const q=await this.doUri(s,b(C.host),o,l,c);return q.error&&this.platformHttp.shouldFallback(q.error)?(_._currentFallback=null,this.do(s,r,o,l,c)):q}else _._currentFallback=null;const O=this._getHosts(_);if(O.length===1)return this.doUri(s,b(O[0]),o,l,c);let M=null;const z=async(q,Q)=>{const F=q.shift();M=M??new Date;const pe=await this.doUri(s,b(F),o,l,c);return pe.error&&this.platformHttp.shouldFallback(pe.error)&&q.length?Date.now()-M.getTime()>_.options.timeouts.httpMaxRetryDuration?{error:new A(`Timeout for trying fallback hosts retries. Total elapsed time exceeded the ${_.options.timeouts.httpMaxRetryDuration}ms limit`,50003,500)}:z(q,!0):(Q&&(_._currentFallback={host:F,validUntil:Date.now()+_.options.timeouts.fallbackRetryTimeout}),pe)};return z(O)}catch(_){return{error:new A(`Unexpected error in Http.do: ${it(_)}`,500,5e4)}}}async doUri(s,r,o,l,c){try{Xe(s,r,l,c,this.logger);const _=await this.platformHttp.doUri(s,r,o,l,c);return this.logger.shouldLog(f.LOG_MICRO)&&Je(_,s,r,c,this.logger),_}catch(_){return{error:new A(`Unexpected error in Http.doUri: ${it(_)}`,500,5e4)}}}};function nt(s,r,o,l){try{o.apply(r,l)}catch(c){f.logAction(s,f.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+c+"; stack = "+(c&&c.stack))}}function ft(s,r,o){let l,c,_;for(let b=0;b<s.length;b++)if(l=s[b],o&&(l=l[o]),Array.isArray(l)){for(;(c=l.indexOf(r))!==-1;)l.splice(c,1);o&&l.length===0&&delete s[b][o]}else if(Mt(l))for(_ in l)Object.prototype.hasOwnProperty.call(l,_)&&Array.isArray(l[_])&&ft([l],r,_)}var mt=class{constructor(s){this.logger=s,this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null)}on(...s){if(s.length===1){const r=s[0];if(typeof r=="function")this.any.push(r);else throw new Error("EventListener.on(): Invalid arguments: "+E.Config.inspect(s))}if(s.length===2){const[r,o]=s;if(typeof o!="function")throw new Error("EventListener.on(): Invalid arguments: "+E.Config.inspect(s));if(je(r))this.any.push(o);else if(Array.isArray(r))r.forEach(l=>{this.on(l,o)});else{if(typeof r!="string")throw new Error("EventListener.on(): Invalid arguments: "+E.Config.inspect(s));(this.events[r]||(this.events[r]=[])).push(o)}}}off(...s){if(s.length==0||je(s[0])&&je(s[1])){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null);return}const[r,o]=s;let l=null,c=null;if(s.length===1||!o)typeof r=="function"?l=r:c=r;else{if(typeof o!="function")throw new Error("EventEmitter.off(): invalid arguments:"+E.Config.inspect(s));[c,l]=[r,o]}if(l&&je(c)){ft([this.any,this.events,this.anyOnce,this.eventsOnce],l);return}if(Array.isArray(c)){c.forEach(_=>{this.off(_,l)});return}if(typeof c!="string")throw new Error("EventEmitter.off(): invalid arguments:"+E.Config.inspect(s));l?ft([this.events,this.eventsOnce],l,c):(delete this.events[c],delete this.eventsOnce[c])}listeners(s){if(s){const r=this.events[s]||[];return this.eventsOnce[s]&&Array.prototype.push.apply(r,this.eventsOnce[s]),r.length?r:null}return this.any.length?this.any:null}emit(s,...r){const o={event:s},l=[];this.anyOnce.length&&(Array.prototype.push.apply(l,this.anyOnce),this.anyOnce=[]),this.any.length&&Array.prototype.push.apply(l,this.any);const c=this.eventsOnce[s];c&&(Array.prototype.push.apply(l,c),delete this.eventsOnce[s]);const _=this.events[s];_&&Array.prototype.push.apply(l,_),l.forEach(b=>{nt(this.logger,o,b,r)})}once(...s){const r=s.length;if(r===0||r===1&&typeof s[0]!="function"){const c=s[0];return new Promise(_=>{this.once(c,_)})}const[o,l]=s;if(s.length===1&&typeof o=="function")this.anyOnce.push(o);else if(je(o)){if(typeof l!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+E.Config.inspect(s));this.anyOnce.push(l)}else if(Array.isArray(o)){const c=this,_=function(){const b=Array.prototype.slice.call(arguments);if(o.forEach(function(C){c.off(C,_)}),typeof l!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+E.Config.inspect(s));l.apply(this,b)};o.forEach(function(b){c.on(b,_)})}else{if(typeof o!="string")throw new Error("EventEmitter.once(): Invalid arguments:"+E.Config.inspect(s));const c=this.eventsOnce[o]||(this.eventsOnce[o]=[]);if(l){if(typeof l!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+E.Config.inspect(s));c.push(l)}}}async whenState(s,r){if(typeof s!="string"||typeof r!="string")throw new Error("whenState requires a valid state String argument");return s===r?null:this.once(s)}},qe=mt,ue={HEARTBEAT:0,ACK:1,NACK:2,CONNECT:3,CONNECTED:4,DISCONNECT:5,DISCONNECTED:6,CLOSE:7,CLOSED:8,ERROR:9,ATTACH:10,ATTACHED:11,DETACH:12,DETACHED:13,PRESENCE:14,MESSAGE:15,SYNC:16,AUTH:17,ACTIVATE:18,OBJECT:19,OBJECT_SYNC:20,ANNOTATION:21},Ot=[];Object.keys(ue).forEach(function(s){Ot[ue[s]]=s});var ot={HAS_PRESENCE:1,HAS_BACKLOG:2,RESUMED:4,TRANSIENT:16,ATTACH_RESUME:32,HAS_OBJECTS:128,PRESENCE:65536,PUBLISH:1<<17,SUBSCRIBE:1<<18,PRESENCE_SUBSCRIBE:1<<19,ANNOTATION_PUBLISH:1<<21,ANNOTATION_SUBSCRIBE:1<<22,OBJECT_SUBSCRIBE:1<<24,OBJECT_PUBLISH:1<<25},Bt=Object.keys(ot);ot.MODE_ALL=ot.PRESENCE|ot.PUBLISH|ot.SUBSCRIBE|ot.PRESENCE_SUBSCRIBE|ot.ANNOTATION_PUBLISH|ot.ANNOTATION_SUBSCRIBE|ot.OBJECT_SUBSCRIBE|ot.OBJECT_PUBLISH;var Ra=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function Vc(s){return!s||!s.channelOptions?{channelOptions:s,plugins:{},baseEncodedPreviousPayload:void 0}:s}function Aa(s,r,o){if(o&&o.cipher){s||dt("Crypto");const l=s.getCipher(o.cipher,r);return{cipher:l.cipherParams,channelCipher:l.cipher}}return o??{}}async function Kc(s,r){const{data:o,encoding:l}=await Ma(s.data,s.encoding,r);return s.data=o,s.encoding=l,s}async function Ma(s,r,o){let l=o.channelCipher,c=s,_=r?r+"/":"";E.BufferUtils.isBuffer(c)||(c=E.BufferUtils.utf8Encode(String(c)),_=_+"utf-8/");const b=await l.encrypt(c);return _=_+"cipher+"+l.algorithm,{data:b,encoding:_}}async function wn(s,r){const{data:o,encoding:l}=Oa(s.data,s.encoding);return s.data=o,s.encoding=l,r!=null&&r.cipher?Kc(s,r):s}function Oa(s,r){if(typeof s=="string"||E.BufferUtils.isBuffer(s)||s===null||s===void 0)return{data:s,encoding:r};if(Mt(s)||Array.isArray(s))return{data:JSON.stringify(s),encoding:r?r+"/json":"json"};throw new A("Data type is unsupported",40013,400)}async function Cn(s,r){const{data:o,encoding:l,error:c}=await Ta(s.data,s.encoding,r);if(s.data=o,s.encoding=l,c)throw c}async function Ta(s,r,o){const l=Vc(o);let c=s,_=s,b=r,C;if(r){const O=r.split("/");let M,z=O.length,q="";try{for(;(M=z)>0;){const Q=O[--z].match(/([-\w]+)(\+([\w-]+))?/);if(!Q)break;switch(q=Q[1],q){case"base64":_=E.BufferUtils.base64Decode(String(_)),M==O.length&&(c=_);continue;case"utf-8":_=E.BufferUtils.utf8Decode(_);continue;case"json":_=JSON.parse(_);continue;case"cipher":if(l.channelOptions!=null&&l.channelOptions.cipher&&l.channelOptions.channelCipher){const F=Q[3],pe=l.channelOptions.channelCipher;if(F!=pe.algorithm)throw new Error("Unable to decrypt message with given cipher; incompatible cipher params");_=await pe.decrypt(_);continue}else throw new Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!l.plugins||!l.plugins.vcdiff)throw new A("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if(typeof Uint8Array>"u")throw new A("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{let F=l.baseEncodedPreviousPayload;typeof F=="string"&&(F=E.BufferUtils.utf8Encode(F));const pe=E.BufferUtils.toBuffer(F);_=E.BufferUtils.toBuffer(_),_=E.BufferUtils.arrayBufferViewToBuffer(l.plugins.vcdiff.decode(_,pe)),c=_}catch(F){throw new A("Vcdiff delta decode failed with "+F,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(Q){const F=Q;C=new A(`Error processing the ${q} encoding, decoder returned ‘${F.message}’`,F.code||40013,400)}finally{b=M<=0?null:O.slice(0,M).join("/")}}return C?{error:C,data:_,encoding:b}:(l.baseEncodedPreviousPayload=c,{data:_,encoding:b})}function xn(...s){const r=s.length>0?"json":"msgpack",{data:o,encoding:l}=Pa(this.data,this.encoding,r);return Object.assign({},this,{encoding:l,data:o})}function Pa(s,r,o){return!s||!E.BufferUtils.isBuffer(s)?{data:s,encoding:r}:o==="msgpack"?{data:E.BufferUtils.toBuffer(s),encoding:r}:{data:E.BufferUtils.base64Encode(s),encoding:r?r+"/base64":"base64"}}var Hr={encryptData:Ma,encodeData:Oa,encodeDataForWire:Pa,decodeData:Ta};function Ur(s){const{id:r,connectionId:o,timestamp:l}=s;let c;switch(s.action){case ue.MESSAGE:{c=s.messages;break}case ue.PRESENCE:case ue.SYNC:c=s.presence;break;case ue.ANNOTATION:c=s.annotations;break;case ue.OBJECT:case ue.OBJECT_SYNC:c=s.state;break;default:throw new A("Unexpected action "+s.action,4e4,400)}for(let _=0;_<c.length;_++){const b=c[_];b.connectionId||(b.connectionId=o),b.timestamp||(b.timestamp=l),r&&!b.id&&(b.id=r+":"+_)}}function Cs(s,r){let o="["+r;for(const l in s)l==="data"?typeof s.data=="string"?o+="; data="+s.data:E.BufferUtils.isBuffer(s.data)?o+="; data (buffer)="+E.BufferUtils.base64Encode(s.data):typeof s.data<"u"&&(o+="; data (json)="+JSON.stringify(s.data)):l&&(l==="extras"||l==="operation")?o+="; "+l+"="+JSON.stringify(s[l]):l==="version"?o+="; version="+JSON.stringify(s[l]):l==="annotations"?o+="; annotations="+JSON.stringify(s[l]):s[l]!==void 0&&(o+="; "+l+"="+s[l]);return o+="]",o}var xs=class{},La=class{constructor(s){this.Platform=E,this.ErrorInfo=A,this.Logger=f,this.Defaults=J,this.Utils=re,this.EventEmitter=qe,this.MessageEncoding=Hr;var r,o,l,c,_,b,C,O,M,z;this._additionalHTTPRequestImplementations=(r=s.plugins)!=null?r:null,this.logger=new f,this.logger.setLog(s.logLevel,s.logHandler),f.logAction(this.logger,f.LOG_MICRO,"BaseClient()","initialized with clientOptions "+E.Config.inspect(s)),this._MsgPack=(l=(o=s.plugins)==null?void 0:o.MsgPack)!=null?l:null;const q=this.options=J.normaliseOptions(s,this._MsgPack,this.logger);if(q.key){const Q=q.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!Q){const F="invalid key parameter";throw f.logAction(this.logger,f.LOG_ERROR,"BaseClient()",F),new A(F,40400,404)}q.keyName=Q[1],q.keySecret=Q[2]}if("clientId"in q)if(typeof q.clientId=="string"||q.clientId===null){if(q.clientId==="*")throw new A('Can’t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, use {defaultTokenParams: {clientId: "*"}})',40012,400)}else throw new A("clientId must be either a string or null",40012,400);f.logAction(this.logger,f.LOG_MINOR,"BaseClient()","started; version = "+J.version),this._currentFallback=null,this.serverTimeOffset=null,this.http=new gt(this),this.auth=new Fe(this,q),this._rest=(c=s.plugins)!=null&&c.Rest?new s.plugins.Rest(this):null,this._Crypto=(b=(_=s.plugins)==null?void 0:_.Crypto)!=null?b:null,this.__FilteredSubscriptions=(O=(C=s.plugins)==null?void 0:C.MessageInteractions)!=null?O:null,this._Annotations=(z=(M=s.plugins)==null?void 0:M.Annotations)!=null?z:null}get rest(){return this._rest||dt("Rest"),this._rest}get _FilteredSubscriptions(){return this.__FilteredSubscriptions||dt("MessageInteractions"),this.__FilteredSubscriptions}get channels(){return this.rest.channels}get push(){return this.rest.push}device(){var s;return(!((s=this.options.plugins)!=null&&s.Push)||!this.push.LocalDevice)&&dt("Push"),this._device||(this._device=this.push.LocalDevice.load(this)),this._device}baseUri(s){return J.getHttpScheme(this.options)+s+":"+J.getPort(this.options,!1)}async stats(s){return this.rest.stats(s)}async time(s){return this.rest.time(s)}async request(s,r,o,l,c,_){return this.rest.request(s,r,o,l,c,_)}batchPublish(s){return this.rest.batchPublish(s)}batchPresence(s){return this.rest.batchPresence(s)}setLog(s){this.logger.setLog(s.level,s.handler)}async getTimestamp(s){return!this.isTimeOffsetSet()&&s?this.time():this.getTimestampUsingOffset()}getTimestampUsingOffset(){return Date.now()+(this.serverTimeOffset||0)}isTimeOffsetSet(){return this.serverTimeOffset!==null}};La.Platform=E;var Ba=La,Yc=class Bs{toJSON(){var r,o,l;return{id:this.id,deviceSecret:this.deviceSecret,platform:this.platform,formFactor:this.formFactor,clientId:this.clientId,metadata:this.metadata,deviceIdentityToken:this.deviceIdentityToken,push:{recipient:(r=this.push)==null?void 0:r.recipient,state:(o=this.push)==null?void 0:o.state,error:(l=this.push)==null?void 0:l.error}}}toString(){var r,o,l,c;let _="[DeviceDetails";return this.id&&(_+="; id="+this.id),this.platform&&(_+="; platform="+this.platform),this.formFactor&&(_+="; formFactor="+this.formFactor),this.clientId&&(_+="; clientId="+this.clientId),this.metadata&&(_+="; metadata="+this.metadata),this.deviceIdentityToken&&(_+="; deviceIdentityToken="+JSON.stringify(this.deviceIdentityToken)),(r=this.push)!=null&&r.recipient&&(_+="; push.recipient="+JSON.stringify(this.push.recipient)),(o=this.push)!=null&&o.state&&(_+="; push.state="+this.push.state),(l=this.push)!=null&&l.error&&(_+="; push.error="+JSON.stringify(this.push.error)),(c=this.push)!=null&&c.metadata&&(_+="; push.metadata="+this.push.metadata),_+="]",_}static toRequestBody(r,o,l){return Kt(r,o,l)}static fromResponseBody(r,o,l){return l&&(r=bt(r,o,l)),Array.isArray(r)?Bs.fromValuesArray(r):Bs.fromValues(r)}static fromValues(r){return r.error=r.error&&A.fromValues(r.error),Object.assign(new Bs,r)}static fromLocalDevice(r){return Object.assign(new Bs,r)}static fromValuesArray(r){const o=r.length,l=new Array(o);for(let c=0;c<o;c++)l[c]=Bs.fromValues(r[c]);return l}},ks=Yc;async function Ia(s,r,o,l){if(s.http.supportsAuthHeaders){const c=await s.auth.getAuthHeaders();return l(se(c,r),o)}else{const c=await s.auth.getAuthParams();return l(r,se(c,o))}}function Jc(s,r,o){if(s.err&&!s.body)return{err:s.err};if(s.statusCode===ve.NoContent)return P(L({},s),{body:[],unpacked:!0});let l=s.body;if(!s.unpacked)try{l=bt(l,r,o)}catch(C){return ss(C)?{err:C}:{err:new Se(it(C),null)}}if(!l)return{err:new Se("unenvelope(): Response body is missing",null)};const{statusCode:c,response:_,headers:b}=l;if(c===void 0)return P(L({},s),{body:l,unpacked:!0});if(c<200||c>=300){let C=_&&_.error||s.err;return C||(C=new Error("Error in unenveloping "+l),C.statusCode=c),{err:C,body:_,headers:b,unpacked:!0,statusCode:c}}return{err:s.err,body:_,headers:b,unpacked:!0,statusCode:c}}function Xc(s,r,o,l,c){s.err?f.logAction(c,f.LOG_MICRO,"Resource."+r+"()","Received Error; "+Pe(o,l)+"; Error: "+it(s.err)):f.logAction(c,f.LOG_MICRO,"Resource."+r+"()","Received; "+Pe(o,l)+"; Headers: "+Ye(s.headers)+"; StatusCode: "+s.statusCode+"; Body: "+(E.BufferUtils.isBuffer(s.body)?" (Base64): "+E.BufferUtils.base64Encode(s.body):": "+E.Config.inspect(s.body)))}var Zc=class Is{static async get(r,o,l,c,_,b){return Is.do(ie.Get,r,o,null,l,c,_,b??!1)}static async delete(r,o,l,c,_,b){return Is.do(ie.Delete,r,o,null,l,c,_,b)}static async post(r,o,l,c,_,b,C){return Is.do(ie.Post,r,o,l,c,_,b,C)}static async patch(r,o,l,c,_,b,C){return Is.do(ie.Patch,r,o,l,c,_,b,C)}static async put(r,o,l,c,_,b,C){return Is.do(ie.Put,r,o,l,c,_,b,C)}static async do(r,o,l,c,_,b,C,O){C&&((b=b||{}).envelope=C);const M=o.logger;async function z(Q,F){var pe;if(M.shouldLog(f.LOG_MICRO)){let Re=c;if(((pe=Q["content-type"])==null?void 0:pe.indexOf("msgpack"))>0)try{o._MsgPack||dt("MsgPack"),Re=o._MsgPack.decode(c)}catch(st){f.logAction(M,f.LOG_MICRO,"Resource."+r+"()","Sending MsgPack Decoding Error: "+it(st))}f.logAction(M,f.LOG_MICRO,"Resource."+r+"()","Sending; "+Pe(l,F)+"; Body: "+Re)}const me=await o.http.do(r,l,Q,c,F);return me.error&&Fe.isTokenErr(me.error)?(await o.auth.authorize(null,null),Ia(o,Q,F,z)):{err:me.error,body:me.body,headers:me.headers,unpacked:me.unpacked,statusCode:me.statusCode}}let q=await Ia(o,_,b,z);if(C&&(q=Jc(q,o._MsgPack,C)),M.shouldLog(f.LOG_MICRO)&&Xc(q,r,l,b,M),O){if(q.err)throw q.err;{const Q=L({},q);return delete Q.err,Q}}return q}},wt=Zc;function Qc(s){const r=s.match(/^\.\/(\w+)\?(.*)$/);return r&&r[2]&&Hi(r[2])}function eu(s){typeof s=="string"&&(s=s.split(","));const r={};for(let o=0;o<s.length;o++){const l=s[o].match(/^\s*<(.+)>;\s*rel="(\w+)"$/);if(l){const c=Qc(l[1]);c&&(r[l[2]]=c)}}return r}function tu(s,r,o){return!(o&&(r||typeof s.code=="number"))}var iu=class{constructor(s,r,o,l,c,_){this.client=s,this.path=r,this.headers=o,this.envelope=l??null,this.bodyHandler=c,this.useHttpPaginatedResponse=_||!1}get logger(){return this.client.logger}async get(s){const r=await wt.get(this.client,this.path,this.headers,s,this.envelope,!1);return this.handlePage(r)}async delete(s){const r=await wt.delete(this.client,this.path,this.headers,s,this.envelope,!1);return this.handlePage(r)}async post(s,r){const o=await wt.post(this.client,this.path,r,this.headers,s,this.envelope,!1);return this.handlePage(o)}async put(s,r){const o=await wt.put(this.client,this.path,r,this.headers,s,this.envelope,!1);return this.handlePage(o)}async patch(s,r){const o=await wt.patch(this.client,this.path,r,this.headers,s,this.envelope,!1);return this.handlePage(o)}async handlePage(s){if(s.err&&tu(s.err,s.body,this.useHttpPaginatedResponse))throw f.logAction(this.logger,f.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+it(s.err)),s.err;let r,o,l;try{r=s.statusCode==ve.NoContent?[]:await this.bodyHandler(s.body,s.headers||{},s.unpacked)}catch(c){throw s.err||c}return s.headers&&(o=s.headers.Link||s.headers.link)&&(l=eu(o)),this.useHttpPaginatedResponse?new su(this,r,s.headers||{},s.statusCode,l,s.err):new Da(this,r,l)}},Da=class{constructor(s,r,o){this.resource=s,this.items=r,this._relParams=o}async first(){if(this.hasFirst())return this.get(this._relParams.first);throw new A("No link to the first page of results",40400,404)}async current(){if(this.hasCurrent())return this.get(this._relParams.current);throw new A("No link to the current page of results",40400,404)}async next(){return this.hasNext()?this.get(this._relParams.next):null}hasFirst(){return this._relParams!=null&&"first"in this._relParams}hasCurrent(){return this._relParams!=null&&"current"in this._relParams}hasNext(){return this._relParams!=null&&"next"in this._relParams}isLast(){return!this.hasNext()}async get(s){const r=this.resource,o=await wt.get(r.client,r.path,r.headers,s,r.envelope,!1);return r.handlePage(o)}},su=class extends Da{constructor(s,r,o,l,c,_){super(s,r,c),this.statusCode=l,this.success=l<300&&l>=200,this.headers=o,this.errorCode=_&&_.code,this.errorMessage=_&&_.message,this.errorDetail=_==null?void 0:_.detail}toJSON(){return{items:this.items,statusCode:this.statusCode,success:this.success,headers:this.headers,errorCode:this.errorCode,errorMessage:this.errorMessage,errorDetail:this.errorDetail}}},pi=iu,Na=class fr{toJSON(){return{channel:this.channel,deviceId:this.deviceId,clientId:this.clientId}}toString(){let r="[PushChannelSubscription";return this.channel&&(r+="; channel="+this.channel),this.deviceId&&(r+="; deviceId="+this.deviceId),this.clientId&&(r+="; clientId="+this.clientId),r+="]",r}static fromResponseBody(r,o,l){return l&&(r=bt(r,o,l)),Array.isArray(r)?fr.fromValuesArray(r):fr.fromValues(r)}static fromValues(r){return Object.assign(new fr,r)}static fromValuesArray(r){const o=r.length,l=new Array(o);for(let c=0;c<o;c++)l[c]=fr.fromValues(r[c]);return l}};Na.toRequestBody=Kt;var ru=Na,Wr=ru,nu=class{constructor(s){var r;this.client=s,this.admin=new ou(s),E.Config.push&&((r=s.options.plugins)!=null&&r.Push)&&(this.stateMachine=new s.options.plugins.Push.ActivationStateMachine(s),this.LocalDevice=s.options.plugins.Push.localDeviceFactory(ks))}async activate(s,r){await new Promise((o,l)=>{var c;if(!((c=this.client.options.plugins)!=null&&c.Push)){l(bs("Push"));return}if(!this.stateMachine){l(new A("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.activatedCallback){l(new A("Activation already in progress",4e4,400));return}this.stateMachine.activatedCallback=_=>{if(_){l(_);return}o()},this.stateMachine.updateFailedCallback=r,this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledActivate(this.stateMachine,s))})}async deactivate(s){await new Promise((r,o)=>{var l;if(!((l=this.client.options.plugins)!=null&&l.Push)){o(bs("Push"));return}if(!this.stateMachine){o(new A("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.deactivatedCallback){o(new A("Deactivation already in progress",4e4,400));return}this.stateMachine.deactivatedCallback=c=>{if(c){o(c);return}r()},this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledDeactivate(this.stateMachine,s))})}},ou=class{constructor(s){this.client=s,this.deviceRegistrations=new au(s),this.channelSubscriptions=new lu(s)}async publish(s,r){const o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",c=J.defaultPostHeaders(o.options),_={},b=se({recipient:s},r);se(c,o.options.headers),o.options.pushFullWait&&se(_,{fullWait:"true"});const C=Kt(b,o._MsgPack,l);await wt.post(o,"/push/publish",C,c,_,null,!0)}},au=class{constructor(s){this.client=s}async save(s){const r=this.client,o=ks.fromValues(s),l=r.options.useBinaryProtocol?"msgpack":"json",c=J.defaultPostHeaders(r.options),_={};se(c,r.options.headers),r.options.pushFullWait&&se(_,{fullWait:"true"});const b=Kt(o,r._MsgPack,l),C=await wt.put(r,"/push/deviceRegistrations/"+encodeURIComponent(s.id),b,c,_,null,!0);return ks.fromResponseBody(C.body,r._MsgPack,C.unpacked?void 0:l)}async get(s){const r=this.client,o=r.options.useBinaryProtocol?"msgpack":"json",l=J.defaultGetHeaders(r.options),c=s.id||s;if(typeof c!="string"||!c.length)throw new A("First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails",4e4,400);se(l,r.options.headers);const _=await wt.get(r,"/push/deviceRegistrations/"+encodeURIComponent(c),l,{},null,!0);return ks.fromResponseBody(_.body,r._MsgPack,_.unpacked?void 0:o)}async list(s){const r=this.client,o=r.options.useBinaryProtocol?"msgpack":"json",l=this.client.http.supportsLinkHeaders?void 0:o,c=J.defaultGetHeaders(r.options);return se(c,r.options.headers),new pi(r,"/push/deviceRegistrations",c,l,async function(_,b,C){return ks.fromResponseBody(_,r._MsgPack,C?void 0:o)}).get(s)}async remove(s){const r=this.client,o=J.defaultGetHeaders(r.options),l={},c=s.id||s;if(typeof c!="string"||!c.length)throw new A("First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails",4e4,400);se(o,r.options.headers),r.options.pushFullWait&&se(l,{fullWait:"true"}),await wt.delete(r,"/push/deviceRegistrations/"+encodeURIComponent(c),o,l,null,!0)}async removeWhere(s){const r=this.client,o=r.options.useBinaryProtocol?"msgpack":"json",l=J.defaultGetHeaders(r.options,{format:o});se(l,r.options.headers),r.options.pushFullWait&&se(s,{fullWait:"true"}),await wt.delete(r,"/push/deviceRegistrations",l,s,null,!0)}},lu=class jh{constructor(r){this.remove=jh.prototype.removeWhere,this.client=r}async save(r){const o=this.client,l=Wr.fromValues(r),c=o.options.useBinaryProtocol?"msgpack":"json",_=J.defaultPostHeaders(o.options),b={};se(_,o.options.headers),o.options.pushFullWait&&se(b,{fullWait:"true"});const C=Kt(l,o._MsgPack,c),O=await wt.post(o,"/push/channelSubscriptions",C,_,b,null,!0);return Wr.fromResponseBody(O.body,o._MsgPack,O.unpacked?void 0:c)}async list(r){const o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",c=this.client.http.supportsLinkHeaders?void 0:l,_=J.defaultGetHeaders(o.options);return se(_,o.options.headers),new pi(o,"/push/channelSubscriptions",_,c,async function(b,C,O){return Wr.fromResponseBody(b,o._MsgPack,O?void 0:l)}).get(r)}async removeWhere(r){const o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",c=J.defaultGetHeaders(o.options,{format:l});se(c,o.options.headers),o.options.pushFullWait&&se(r,{fullWait:"true"}),await wt.delete(o,"/push/channelSubscriptions",c,r,null,!0)}async listChannels(r){const o=this.client,l=o.options.useBinaryProtocol?"msgpack":"json",c=this.client.http.supportsLinkHeaders?void 0:l,_=J.defaultGetHeaders(o.options);return se(_,o.options.headers),o.options.pushFullWait&&se(r,{fullWait:"true"}),new pi(o,"/push/channels",_,c,async function(b,C,O){const M=!O&&l?bt(b,o._MsgPack,l):b;for(let z=0;z<M.length;z++)M[z]=String(M[z]);return M}).get(r)}},hu=nu,Ha=["absent","present","enter","leave","update"];async function Ua(s,r,o,l){const c=Aa(r,s,l??null);return $s.fromValues(o).decode(c,s)}async function cu(s,r,o,l){return Promise.all(o.map(function(c){return Ua(s,r,c,l)}))}async function uu(s,r){return $s.fromValues(s).decode(r.channelOptions,r.logger)}async function Wa(s,r){return Promise.all(s.map(function(o){return uu(o,r)}))}var Fa=class _r extends xs{isSynthesized(){return!this.id||!this.connectionId?!0:this.id.substring(this.connectionId.length,0)!==this.connectionId}parseId(){if(!this.id)throw new Error("parseId(): Presence message does not contain an id");const r=this.id.split(":");return{connectionId:r[0],msgSerial:parseInt(r[1],10),index:parseInt(r[2],10)}}async encode(r){const o=Object.assign(new $s,this,{action:Ha.indexOf(this.action||"present")});return wn(o,r)}static fromValues(r){return Object.assign(new _r,r)}static fromValuesArray(r){return r.map(o=>_r.fromValues(o))}static fromData(r){return r instanceof _r?r:_r.fromValues({data:r})}toString(){return Cs(this,"PresenceMessage")}},$s=class _o extends xs{toJSON(...r){return xn.call(this,...r)}static fromValues(r){return Object.assign(new _o,r)}static fromValuesArray(r){return r.map(o=>_o.fromValues(o))}async decode(r,o){const l=Object.assign(new Fa,P(L({},this),{action:Ha[this.action]}));try{await Cn(l,r)}catch(c){f.logAction(o,f.LOG_ERROR,"WirePresenceMessage.decode()",it(c))}return l}toString(){return Cs(this,"WirePresenceMessage")}},$i=Fa,du=class{constructor(s){this.channel=s}get logger(){return this.channel.logger}async get(s){f.logAction(this.logger,f.LOG_MICRO,"RestPresence.get()","channel = "+this.channel.name);const r=this.channel.client,o=r.options.useBinaryProtocol?"msgpack":"json",l=this.channel.client.http.supportsLinkHeaders?void 0:o,c=J.defaultGetHeaders(r.options);return se(c,r.options.headers),new pi(r,this.channel.client.rest.presenceMixin.basePath(this),c,l,async(_,b,C)=>{const O=C?_:bt(_,r._MsgPack,o);return Wa(O,this.channel)}).get(s)}async history(s){return f.logAction(this.logger,f.LOG_MICRO,"RestPresence.history()","channel = "+this.channel.name),this.channel.client.rest.presenceMixin.history(this,s)}},fu=du,za=["message.create","message.update","message.delete","meta","message.summary","message.append"];function _u(s){return za[s||0]||"unknown"}function gu(s){let r=0;return s.name&&(r+=s.name.length),s.clientId&&(r+=s.clientId.length),s.extras&&(r+=JSON.stringify(s.extras).length),s.data&&(r+=rs(s.data)),r}async function qa(s,r,o,l){const c=Aa(r,s,l??null);return Vs.fromValues(o).decode(c,s)}async function pu(s,r,o,l){return Promise.all(o.map(function(c){return qa(s,r,c,l)}))}async function Ga(s,r){return Vs.fromValues(s).decode(r.channelOptions,r.logger)}async function ja(s,r){return Promise.all(s.map(function(o){return Ga(o,r)}))}async function $a(s,r){return Promise.all(s.map(o=>o.encode(r)))}var Va=Kt;function Ka(s){let r,o=0;for(let l=0;l<s.length;l++)r=s[l],o+=r.size||(r.size=gu(r));return o}var Ya=class go extends xs{expandFields(){if(this.version||(this.version={}),!this.version.serial&&this.serial&&(this.version.serial=this.serial),!this.version.timestamp&&this.timestamp&&(this.version.timestamp=this.timestamp),this.annotations?this.annotations.summary||(this.annotations.summary={}):this.annotations={summary:{}},this.annotations&&this.annotations.summary)for(const[r,o]of Object.entries(this.annotations.summary))if(r.endsWith(":distinct.v1")||r.endsWith(":unique.v1")||r.endsWith(":multiple.v1"))for(const[,l]of Object.entries(o))l.clipped||(l.clipped=!1);else r.endsWith(":flag.v1")&&(o.clipped||(o.clipped=!1))}async encode(r){const o=Object.assign(new Vs,this,{action:za.indexOf(this.action||"message.create")});return wn(o,r)}static fromValues(r){return Object.assign(new go,r)}static fromValuesArray(r){return r.map(o=>go.fromValues(o))}toString(){return Cs(this,"Message")}},Vs=class po extends xs{toJSON(...r){return xn.call(this,...r)}static fromValues(r){return Object.assign(new po,r)}static fromValuesArray(r){return r.map(o=>po.fromValues(o))}async decodeWithErr(r,o){const l=Object.assign(new Ya,P(L({},this),{action:_u(this.action)}));let c;try{await Cn(l,r)}catch(_){f.logAction(o,f.LOG_ERROR,"WireMessage.decode()",it(_)),c=_}return l.expandFields(),{decoded:l,err:c}}async decode(r,o){const{decoded:l}=await this.decodeWithErr(r,o);return l}toString(){return Cs(this,"WireMessage")}},Si=Ya,mu=9;function vu(s){return s.every(function(r){return!r.id})}var yu=class{constructor(s,r,o){this._annotations=null;var l,c;f.logAction(s.logger,f.LOG_MINOR,"RestChannel()","started; name = "+r),this.name=r,this.client=s,this.presence=new fu(this),this.channelOptions=Ke((l=s._Crypto)!=null?l:null,this.logger,o),(c=s.options.plugins)!=null&&c.Push&&(this._push=new s.options.plugins.Push.PushChannel(this)),s._Annotations&&(this._annotations=new s._Annotations.RestAnnotations(this))}get annotations(){return this._annotations||dt("Annotations"),this._annotations}get push(){return this._push||dt("Push"),this._push}get logger(){return this.client.logger}setOptions(s){var r;this.channelOptions=Ke((r=this.client._Crypto)!=null?r:null,this.logger,s)}async history(s){return f.logAction(this.logger,f.LOG_MICRO,"RestChannel.history()","channel = "+this.name),this.client.rest.channelMixin.history(this,s)}async publish(...s){const r=s[0],o=s[1];let l,c;if(typeof r=="string"||r===null)l=[Si.fromValues({name:r,data:o})],c=s[2];else if(Mt(r))l=[Si.fromValues(r)],c=s[1];else if(Array.isArray(r))l=Si.fromValuesArray(r),c=s[1];else throw new A("The single-argument form of publish() expects a message object or an array of message objects",40013,400);c||(c={});const _=this.client,b=_.options,C=b.useBinaryProtocol?"msgpack":"json",O=_.options.idempotentRestPublishing,M=J.defaultPostHeaders(_.options);if(se(M,b.headers),O&&vu(l)){const F=await ys(mu);l.forEach(function(pe,me){pe.id=F+":"+me.toString()})}const z=await $a(l,this.channelOptions),q=Ka(z),Q=b.maxMessageSize;if(q>Q)throw new A(`Maximum size of messages that can be published at once exceeded (was ${q} bytes; limit is ${Q} bytes)`,40009,400);return this._publish(Va(z,_._MsgPack,C),M,c)}async _publish(s,r,o){const l=this.client,c=l.options.useBinaryProtocol?"msgpack":"json",{body:_,unpacked:b}=await wt.post(l,l.rest.channelMixin.basePath(this)+"/messages",s,r,o,null,!0),C=(b?_:bt(_,l._MsgPack,c))||{};return delete C.channel,delete C.messageId,C}async status(){return this.client.rest.channelMixin.status(this)}async getMessage(s){return f.logAction(this.logger,f.LOG_MICRO,"RestChannel.getMessage()","channel = "+this.name),this.client.rest.channelMixin.getMessage(this,s)}async updateMessage(s,r,o){return f.logAction(this.logger,f.LOG_MICRO,"RestChannel.updateMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.update",s,r,o)}async deleteMessage(s,r,o){return f.logAction(this.logger,f.LOG_MICRO,"RestChannel.deleteMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.delete",s,r,o)}async appendMessage(s,r,o){return f.logAction(this.logger,f.LOG_MICRO,"RestChannel.appendMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.append",s,r,o)}async getMessageVersions(s,r){return f.logAction(this.logger,f.LOG_MICRO,"RestChannel.getMessageVersions()","channel = "+this.name),this.client.rest.channelMixin.getMessageVersions(this,s,r)}},Su=yu,bu=class $h{constructor(r){this.entries=r&&r.entries||void 0,this.schema=r&&r.schema||void 0,this.appId=r&&r.appId||void 0,this.inProgress=r&&r.inProgress||void 0,this.unit=r&&r.unit||void 0,this.intervalId=r&&r.intervalId||void 0}static fromValues(r){return new $h(r)}},wu=bu,Ja=class{static basePath(s){return"/channels/"+encodeURIComponent(s.name)}static history(s,r){const o=s.client,l=o.options.useBinaryProtocol?"msgpack":"json",c=s.client.http.supportsLinkHeaders?void 0:l,_=J.defaultGetHeaders(o.options);return se(_,o.options.headers),new pi(o,this.basePath(s)+"/messages",_,c,async function(b,C,O){const M=O?b:bt(b,o._MsgPack,l);return ja(M,s)}).get(r)}static async status(s){const r=s.client.options.useBinaryProtocol?"msgpack":"json",o=J.defaultPostHeaders(s.client.options);return(await wt.get(s.client,this.basePath(s),o,{},r,!0)).body}static async getMessage(s,r){const o=typeof r=="string"?r:r.serial;if(!o)throw new A('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);const l=s.client,c=l.options.useBinaryProtocol?"msgpack":"json",_=J.defaultGetHeaders(l.options);se(_,l.options.headers);const{body:b,unpacked:C}=await wt.get(l,this.basePath(s)+"/messages/"+encodeURIComponent(o),_,{},null,!0),O=C?b:bt(b,l._MsgPack,c);return Ga(O,s)}static async updateDeleteMessage(s,r,o,l,c){if(!o.serial)throw new A('This message lacks a serial and cannot be updated. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);const _=s.client,b=_.options.useBinaryProtocol?"msgpack":"json",C=J.defaultPostHeaders(_.options);se(C,_.options.headers);const O=Si.fromValues(o);O.action=r,O.version=l;const M=await O.encode(s.channelOptions),z=Va(M,_._MsgPack,b);let q=wt.patch;const{body:Q,unpacked:F}=await q(_,this.basePath(s)+"/messages/"+encodeURIComponent(o.serial),z,C,c||{},null,!0);return(F?Q:bt(Q,_._MsgPack,b))||{versionSerial:null}}static getMessageVersions(s,r,o){const l=typeof r=="string"?r:r.serial;if(!l)throw new A('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);const c=s.client,_=c.options.useBinaryProtocol?"msgpack":"json",b=s.client.http.supportsLinkHeaders?void 0:_,C=J.defaultGetHeaders(c.options);return se(C,c.options.headers),new pi(c,this.basePath(s)+"/messages/"+encodeURIComponent(l)+"/versions",C,b,async(O,M,z)=>{const q=z?O:bt(O,c._MsgPack,_);return ja(q,s)}).get(o||{})}},Cu=class{static basePath(s){return Ja.basePath(s.channel)+"/presence"}static async history(s,r){const o=s.channel.client,l=o.options.useBinaryProtocol?"msgpack":"json",c=s.channel.client.http.supportsLinkHeaders?void 0:l,_=J.defaultGetHeaders(o.options);return se(_,o.options.headers),new pi(o,this.basePath(s)+"/history",_,c,async(b,C,O)=>{const M=O?b:bt(b,o._MsgPack,l);return Wa(M,s.channel)}).get(r)}},Xa=class{constructor(s){this.channelMixin=Ja,this.presenceMixin=Cu,this.Resource=wt,this.PaginatedResource=pi,this.DeviceDetails=ks,this.PushChannelSubscription=Wr,this.client=s,this.channels=new xu(this.client),this.push=new hu(this.client)}async stats(s){const r=J.defaultGetHeaders(this.client.options),o=this.client.options.useBinaryProtocol?"msgpack":"json",l=this.client.http.supportsLinkHeaders?void 0:o;return se(r,this.client.options.headers),new pi(this.client,"/stats",r,l,async(c,_,b)=>{const C=b?c:bt(c,this.client._MsgPack,o);for(let O=0;O<C.length;O++)C[O]=wu.fromValues(C[O]);return C}).get(s)}async time(s){const r=J.defaultGetHeaders(this.client.options,{format:"json"});this.client.options.headers&&se(r,this.client.options.headers);const o=C=>this.client.baseUri(C)+"/time";let{error:l,body:c,unpacked:_}=await this.client.http.do(ie.Get,o,r,null,s);if(l)throw l;_||(c=JSON.parse(c));const b=c[0];if(!b)throw new A("Internal error (unexpected result type from GET /time)",5e4,500);return this.client.serverTimeOffset=b-Date.now(),b}async request(s,r,o,l,c,_){var b;const[C,O,M]=this.client.options.useBinaryProtocol?(this.client._MsgPack||dt("MsgPack"),[this.client._MsgPack.encode,this.client._MsgPack.decode,"msgpack"]):[JSON.stringify,JSON.parse,"json"],z=this.client.http.supportsLinkHeaders?void 0:M;l=l||{};const q=s.toLowerCase(),Q=q=="get"?J.defaultGetHeaders(this.client.options,{format:M,protocolVersion:o}):J.defaultPostHeaders(this.client.options,{format:M,protocolVersion:o});typeof c!="string"&&(c=(b=C(c))!=null?b:null),se(Q,this.client.options.headers),_&&se(Q,_);const F=new pi(this.client,r,Q,z,async function(pe,me,Re){return zt(Re?pe:O(pe))},!0);if(!E.Http.methods.includes(q))throw new A("Unsupported method "+q,40500,405);return E.Http.methodsWithBody.includes(q)?F[q](l,c):F[q](l)}async batchPublish(s){let r,o;Array.isArray(s)?(r=s,o=!1):(r=[s],o=!0);const l=this.client.options.useBinaryProtocol?"msgpack":"json",c=J.defaultPostHeaders(this.client.options);this.client.options.headers&&se(c,this.client.options.headers);const _=Kt(r,this.client._MsgPack,l),b=await wt.post(this.client,"/messages",_,c,{},null,!0),C=b.unpacked?b.body:bt(b.body,this.client._MsgPack,l);return o?C[0]:C}async batchPresence(s){const r=this.client.options.useBinaryProtocol?"msgpack":"json",o=J.defaultGetHeaders(this.client.options);this.client.options.headers&&se(o,this.client.options.headers);const l=s.join(","),c=await wt.get(this.client,"/presence",o,{channels:l},null,!0);return c.unpacked?c.body:bt(c.body,this.client._MsgPack,r)}async revokeTokens(s,r){if(Ie(this.client.options))throw new A("Cannot revoke tokens when using token auth",40162,401);const o=this.client.options.keyName;let l=r??{};const c=L({targets:s.map(M=>`${M.type}:${M.value}`)},l),_=this.client.options.useBinaryProtocol?"msgpack":"json",b=J.defaultPostHeaders(this.client.options);this.client.options.headers&&se(b,this.client.options.headers);const C=Kt(c,this.client._MsgPack,_),O=await wt.post(this.client,`/keys/${o}/revokeTokens`,C,b,{},null,!0);return O.unpacked?O.body:bt(O.body,this.client._MsgPack,_)}},xu=class{constructor(s){this.client=s,this.all=Object.create(null)}get(s,r){s=String(s);let o=this.all[s];return o?r&&o.setOptions(r):this.all[s]=o=new Su(this.client,s,r),o}release(s){delete this.all[String(s)]}},ku=class extends Ba{constructor(s){super(J.objectifyOptions(s,!1,"BaseRest",f.defaultLogger,{Rest:Xa}))}},Za={Rest:Xa},Qa=class extends Si{static async fromEncoded(s,r){return qa(f.defaultLogger,E.Crypto,s,r)}static async fromEncodedArray(s,r){return pu(f.defaultLogger,E.Crypto,s,r)}static fromValues(s){return Si.fromValues(s)}},el=class extends $i{static async fromEncoded(s,r){return Ua(f.defaultLogger,E.Crypto,s,r)}static async fromEncodedArray(s,r){return cu(f.defaultLogger,E.Crypto,s,r)}static fromValues(s){return $i.fromValues(s)}},tl=["annotation.create","annotation.delete"];async function il(s,r,o){return Es.fromValues(r).decode(o||{},s)}async function Eu(s,r,o){return Promise.all(r.map(function(l){return il(s,l,o)}))}async function Ru(s,r){return Es.fromValues(s).decode(r.channelOptions,r.logger)}async function Au(s,r){return Promise.all(s.map(function(o){return Ru(o,r)}))}var sl=class mo extends xs{async encode(){const r=Object.assign(new Es,this,{action:tl.indexOf(this.action||"annotation.create")});return wn(r,{})}static fromValues(r){return Object.assign(new mo,r)}static fromValuesArray(r){return r.map(o=>mo.fromValues(o))}toString(){return Cs(this,"Annotation")}},Es=class vo extends xs{toJSON(...r){return xn.call(this,...r)}static fromValues(r){return Object.assign(new vo,r)}static fromValuesArray(r){return r.map(o=>vo.fromValues(o))}async decode(r,o){const l=Object.assign(new sl,P(L({},this),{action:tl[this.action]}));try{await Cn(l,r)}catch(c){f.logAction(o,f.LOG_ERROR,"WireAnnotation.decode()",it(c))}return l}toString(){return Cs(this,"WireAnnotation")}},Ks=sl,rl=class extends Ks{static async fromEncoded(s,r){return il(f.defaultLogger,s,r)}static async fromEncodedArray(s,r){return Eu(f.defaultLogger,s,r)}static fromValues(s){return Ks.fromValues(s)}};function nl(s){let r;switch(typeof s){case"string":r=s;break;case"object":r=s.serial;break}if(!r||typeof r!="string")throw new A("First argument of annotations.publish() must be either a Message (or at least an object with a string `serial` property) or a message serial (string)",40003,400);return r}function ol(s,r){const o=nl(s);if(!r||typeof r!="object")throw new A("Second argument of annotations.publish() must be an object (the intended annotation to publish)",40003,400);const l=Ks.fromValues(r);return l.messageSerial=o,l.action||(l.action="annotation.create"),l}function al(s,r){return s.client.rest.channelMixin.basePath(s)+"/messages/"+encodeURIComponent(r)+"/annotations"}var Mu=class{constructor(s){this.channel=s}async publish(s,r){const o=ol(s,r),l=await o.encode(),c=this.channel.client,_=c.options,b=_.useBinaryProtocol?"msgpack":"json",C=J.defaultPostHeaders(c.options),O={};se(C,c.options.headers);const M=Kt([l],c._MsgPack,b);await wt.post(c,al(this.channel,o.messageSerial),M,C,O,null,!0)}async delete(s,r){return r.action="annotation.delete",this.publish(s,r)}async get(s,r){const o=this.channel.client,l=nl(s),c=o.options.useBinaryProtocol?"msgpack":"json",_=o.http.supportsLinkHeaders?void 0:c,b=J.defaultGetHeaders(o.options);return se(b,o.options.headers),new pi(o,al(this.channel,l),b,_,async(C,O,M)=>{const z=M?C:bt(C,o._MsgPack,c);return Au(z,this.channel)}).get(r)}},kn=Mu,Ou=Kt;function Fr(s){const r=[];if(s)for(let o=0;o<s.length;o++)r.push(s[o].toString());return"[ "+r.join(", ")+" ]"}function Tu(s,r,o,l,c,_){const b=bt(s,r,_);return En(b,o,l,c)}function En(s,r,o,l){let c;s.error&&(c=A.fromValues(s.error));let _;s.messages&&(_=Vs.fromValuesArray(s.messages));let b;r&&s.presence&&(b=r.WirePresenceMessage.fromValuesArray(s.presence));let C;o&&s.annotations&&(C=o.WireAnnotation.fromValuesArray(s.annotations));let O;return l&&s.state&&(O=l.WireObjectMessage.fromValuesArray(s.state,re,Hr)),Object.assign(new An,P(L({},s),{presence:b,messages:_,annotations:C,state:O,error:c}))}function ll(s){return r=>{var o;return En(r,{WirePresenceMessage:$s},{WireAnnotation:Es},(o=s==null?void 0:s.LiveObjectsPlugin)!=null?o:null)}}function ei(s){return Object.assign(new An,s)}function Rn(s,r,o,l){let c="[ProtocolMessage";s.action!==void 0&&(c+="; action="+Ot[s.action]||s.action);const _=["id","channel","channelSerial","connectionId","count","msgSerial","timestamp"];let b;for(let C=0;C<_.length;C++)b=_[C],s[b]!==void 0&&(c+="; "+b+"="+s[b]);if(s.messages&&(c+="; messages="+Fr(Vs.fromValuesArray(s.messages))),s.presence&&r&&(c+="; presence="+Fr(r.WirePresenceMessage.fromValuesArray(s.presence))),s.annotations&&o&&(c+="; annotations="+Fr(o.WireAnnotation.fromValuesArray(s.annotations))),s.state&&l&&(c+="; state="+Fr(l.WireObjectMessage.fromValuesArray(s.state,re,Hr))),s.error&&(c+="; error="+A.fromValues(s.error).toString()),s.auth&&s.auth.accessToken&&(c+="; token="+s.auth.accessToken),s.flags&&(c+="; flags="+Bt.filter(s.hasFlag).join(",")),s.params){let C="";Ir(s.params,function(O){C.length>0&&(C+="; "),C+=O+"="+s.params[O]}),C.length>0&&(c+="; params=["+C+"]")}return c+="]",c}var An=class{constructor(){this.hasFlag=s=>(this.flags&ot[s])>0}setFlag(s){return this.flags=this.flags|ot[s]}getMode(){return(this.flags||0)&ot.MODE_ALL}encodeModesToFlags(s){s.forEach(r=>this.setFlag(r))}decodeModesFromFlags(){const s=[];return Ra.forEach(r=>{this.hasFlag(r)&&s.push(r)}),s.length>0?s:void 0}},Pu=An,Lu=class{constructor(s,r,o,l,c){this.previous=s,this.current=r,r==="attached"&&(this.resumed=o,this.hasBacklog=l),c&&(this.reason=c)}},Mn=Lu;function Bu(s){if(s&&"params"in s&&!Mt(s.params))return new A("options.params must be an object",4e4,400);if(s&&"modes"in s){if(!Array.isArray(s.modes))return new A("options.modes must be an array",4e4,400);for(let r=0;r<s.modes.length;r++){const o=s.modes[r];if(!o||typeof o!="string"||!Ra.includes(String.prototype.toUpperCase.call(o)))return new A("Invalid channel mode: "+o,4e4,400)}}}var Iu=class yo extends qe{constructor(r,o,l){var c,_,b;super(r.logger),this._annotations=null,this._mode=0,this.retryCount=0,this.history=async function(C){f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name);const O=this.client.rest.channelMixin;if(C&&C.untilAttach){if(this.state!=="attached")throw new A("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new A("untilAttach was specified and channel is attached, but attachSerial is not defined",4e4,400);delete C.untilAttach,C.from_serial=this.properties.attachSerial}return O.history(this,C)},this.whenState=C=>qe.prototype.whenState.call(this,C,this.state),f.logAction(this.logger,f.LOG_MINOR,"RealtimeChannel()","started; name = "+o),this.name=o,this.channelOptions=Ke((c=r._Crypto)!=null?c:null,this.logger,l),this.client=r,this._presence=r._RealtimePresence?new r._RealtimePresence.RealtimePresence(this):null,r._Annotations&&(this._annotations=new r._Annotations.RealtimeAnnotations(this)),this.connectionManager=r.connection.connectionManager,this.state="initialized",this.subscriptions=new qe(this.logger),this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(l),this.errorReason=null,this._attachResume=!1,this._decodingContext={channelOptions:this.channelOptions,plugins:r.options.plugins||{},baseEncodedPreviousPayload:void 0},this._lastPayload={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},this._attachedReceived=new qe(this.logger),this.internalStateChanges=new qe(this.logger),(_=r.options.plugins)!=null&&_.Push&&(this._push=new r.options.plugins.Push.PushChannel(this)),(b=r.options.plugins)!=null&&b.LiveObjects&&(this._object=new r.options.plugins.LiveObjects.RealtimeObject(this))}get presence(){return this._presence||dt("RealtimePresence"),this._presence}get annotations(){return this._annotations||dt("Annotations"),this._annotations}get push(){return this._push||dt("Push"),this._push}get object(){return this._object||dt("LiveObjects"),this._object}emit(r,...o){super.emit(r,...o),this.internalStateChanges.emit(r,...o)}invalidStateError(){return new A("Channel operation failed as channel state is "+this.state,90001,400,this.errorReason||void 0)}static processListenerArgs(r){return r=Array.prototype.slice.call(r),typeof r[0]=="function"&&r.unshift(null),r}async setOptions(r){var o;const l=this.channelOptions,c=Bu(r);if(c)throw c;if(this.channelOptions=Ke((o=this.client._Crypto)!=null?o:null,this.logger,r),this._decodingContext&&(this._decodingContext.channelOptions=this.channelOptions),this._shouldReattachToSetOptions(r,l))return this.attachImpl(),new Promise((_,b)=>{const C=()=>{this._attachedReceived.off(O),this.internalStateChanges.off(M)},O=()=>{C(),_()},M=z=>{C(),b(z.reason)};this._attachedReceived.once("attached",O),this.internalStateChanges.once(["detached","failed"],M)})}_shouldReattachToSetOptions(r,o){if(!(this.state==="attached"||this.state==="attaching"))return!1;if(r!=null&&r.params){const l=hl(r.params),c=hl(o.params);if(Object.keys(l).length!==Object.keys(c).length||!Gi(c,l))return!0}return!!(r!=null&&r.modes&&(!o.modes||!Nr(r.modes,o.modes)))}async publish(...r){const o=r[0],l=r[1];let c,_;if(typeof o=="string"||o===null||o===void 0)c=[Si.fromValues({name:o,data:l})],_=r[2];else if(Mt(o))c=[Si.fromValues(o)],_=r[1];else if(Array.isArray(o))c=Si.fromValuesArray(o),_=r[1];else throw new A("The single-argument form of publish() expects a message object or an array of message objects",40013,400);const b=this.client.options.maxMessageSize,C=await $a(c,this.channelOptions),O=Ka(C);if(O>b)throw new A(`Maximum size of messages that can be published at once exceeded (was ${O} bytes; limit is ${b} bytes)`,40009,400);this.throwIfUnpublishableState(),f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.publish()","sending message; channel state is "+this.state+", message count = "+C.length);const M=ei({action:ue.MESSAGE,channel:this.name,messages:C,params:_?ms(_):void 0});return this.sendAndAwaitAck(M)}throwIfUnpublishableState(){if(!this.connectionManager.activeState())throw this.connectionManager.getError();if(this.state==="failed"||this.state==="suspended")throw this.invalidStateError()}onEvent(r){f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.onEvent()","received message");const o=this.subscriptions;for(let l=0;l<r.length;l++){const c=r[l];o.emit(c.name,c)}}async attach(){return this.state==="attached"?null:new Promise((r,o)=>{this._attach(!1,null,(l,c)=>l?o(l):r(c))})}_attach(r,o,l){l||(l=_=>{_&&f.logAction(this.logger,f.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+_.toString())});const c=this.connectionManager;if(!c.activeState()){l(c.getError());return}(this.state!=="attaching"||r)&&this.requestState("attaching",o),this.internalStateChanges.once(function(_){switch(this.event){case"attached":l==null||l(null,_);break;case"detached":case"suspended":case"failed":l==null||l(_.reason||c.getError()||new A("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":l==null||l(new A("Attach request superseded by a subsequent detach request",9e4,409));break}})}attachImpl(){f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.attachImpl()","sending ATTACH message");const r=ei({action:ue.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&r.encodeModesToFlags(Fi(this.channelOptions.modes)),this._attachResume&&r.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(r.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.send(r)}async detach(){const r=this.connectionManager;switch(this.state){case"suspended":this.notifyState("detached");return;case"detached":return;case"failed":throw new A("Unable to detach; channel state = failed",90001,400);default:if(r.state.state!=="connected"){this.notifyState("detached");return}this.requestState("detaching");case"detaching":return new Promise((o,l)=>{this.internalStateChanges.once(function(c){switch(this.event){case"detached":o();break;case"attached":case"suspended":case"failed":l(c.reason||r.getError()||new A("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":l(new A("Detach request superseded by a subsequent attach request",9e4,409));break}})})}}detachImpl(){f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.detach()","sending DETACH message");const r=ei({action:ue.DETACH,channel:this.name});this.send(r)}async subscribe(...r){const[o,l]=yo.processListenerArgs(r);if(this.state==="failed")throw A.fromValues(this.invalidStateError());return o&&typeof o=="object"&&!Array.isArray(o)?this.client._FilteredSubscriptions.subscribeFilter(this,o,l):this.subscriptions.on(o,l),this.channelOptions.attachOnSubscribe!==!1?this.attach():null}unsubscribe(...r){var o;const[l,c]=yo.processListenerArgs(r);if(typeof l=="object"&&!c||(o=this.filteredSubscriptions)!=null&&o.has(c)){this.client._FilteredSubscriptions.getAndDeleteFilteredSubscriptions(this,l,c).forEach(_=>this.subscriptions.off(_));return}this.subscriptions.off(l,c)}sync(){switch(this.state){case"initialized":case"detaching":case"detached":throw new Se("Unable to sync to channel; not attached",4e4)}const r=this.connectionManager;if(!r.activeState())throw r.getError();const o=ei({action:ue.SYNC,channel:this.name});this.syncChannelSerial&&(o.channelSerial=this.syncChannelSerial),r.send(o)}send(r){this.connectionManager.send(r)}async sendAndAwaitAck(r){return new Promise((o,l)=>{this.connectionManager.send(r,this.client.options.queueMessages,(c,_)=>{c?l(c):o(_)})})}async sendPresence(r){const o=ei({action:ue.PRESENCE,channel:this.name,presence:r});await this.sendAndAwaitAck(o)}async sendState(r){const o=ei({action:ue.OBJECT,channel:this.name,state:r});return this.sendAndAwaitAck(o)}async processMessage(r){(r.action===ue.ATTACHED||r.action===ue.MESSAGE||r.action===ue.PRESENCE||r.action===ue.OBJECT||r.action===ue.ANNOTATION)&&this.setChannelSerial(r.channelSerial);let o,l=!1;switch(r.action){case ue.ATTACHED:{this.properties.attachSerial=r.channelSerial,this._mode=r.getMode(),this.params=r.params||{};const c=r.decodeModesFromFlags();this.modes=c&&Wi(c)||void 0;const _=r.hasFlag("RESUMED"),b=r.hasFlag("HAS_PRESENCE"),C=r.hasFlag("HAS_BACKLOG"),O=r.hasFlag("HAS_OBJECTS");if(this._attachedReceived.emit("attached"),this.state==="attached"){_||this._presence&&this._presence.onAttached(b),this._object&&this._object.onAttached(O);const M=new Mn(this.state,this.state,_,C,r.error);(!_||this.channelOptions.updateOnAttached)&&this.emit("update",M)}else this.state==="detaching"?this.checkPendingState():this.notifyState("attached",r.error,_,b,C,O);break}case ue.DETACHED:{const c=r.error?A.fromValues(r.error):new A("Channel detached",90001,404);this.state==="detaching"?this.notifyState("detached",c):this.state==="attaching"?this.notifyState("suspended",c):(this.state==="attached"||this.state==="suspended")&&this.requestState("attaching",c);break}case ue.SYNC:if(l=!0,o=this.syncChannelSerial=r.channelSerial,!r.presence)break;case ue.PRESENCE:{if(!r.presence)break;Ur(r);const c=this.channelOptions;if(this._presence){const _=await Promise.all(r.presence.map(b=>b.decode(c,this.logger)));this._presence.setPresence(_,l,o)}break}case ue.OBJECT:case ue.OBJECT_SYNC:{if(!this._object||!r.state)return;Ur(r);const c=this.client.connection.connectionManager.getActiveTransportFormat(),_=r.state.map(b=>b.decode(this.client,c));r.action===ue.OBJECT?this._object.handleObjectMessages(_):this._object.handleObjectSyncMessages(_,r.channelSerial);break}case ue.MESSAGE:{if(this.state!=="attached"){f.logAction(this.logger,f.LOG_MAJOR,"RealtimeChannel.processMessage()",'Message "'+r.id+'" skipped as this channel "'+this.name+'" state is not "attached" (state is "'+this.state+'").');return}Ur(r);const c=r.messages,_=c[0],b=c[c.length-1];if(_.extras&&_.extras.delta&&_.extras.delta.from!==this._lastPayload.messageId){const O='Delta message decode failure - previous message not available for message "'+r.id+'" on this channel "'+this.name+'".';f.logAction(this.logger,f.LOG_ERROR,"RealtimeChannel.processMessage()",O),this._startDecodeFailureRecovery(new A(O,40018,400));break}let C=[];for(let O=0;O<c.length;O++){const{decoded:M,err:z}=await c[O].decodeWithErr(this._decodingContext,this.logger);if(C[O]=M,z)switch(z.code){case 40018:this._startDecodeFailureRecovery(z);return;case 40019:case 40021:this.notifyState("failed",z);return}}this._lastPayload.messageId=b.id,this._lastPayload.protocolMessageChannelSerial=r.channelSerial,this.onEvent(C);break}case ue.ANNOTATION:{Ur(r);const c=this.channelOptions;if(this._annotations){const _=await Promise.all((r.annotations||[]).map(b=>b.decode(c,this.logger)));this._annotations._processIncoming(_)}break}case ue.ERROR:{const c=r.error;c&&c.code==80016?this.checkPendingState():this.notifyState("failed",A.fromValues(c));break}default:f.logAction(this.logger,f.LOG_MAJOR,"RealtimeChannel.processMessage()","Protocol error: unrecognised message action ("+r.action+")")}}_startDecodeFailureRecovery(r){this._lastPayload.decodeFailureRecoveryInProgress||(f.logAction(this.logger,f.LOG_MAJOR,"RealtimeChannel.processMessage()","Starting decode failure recovery process."),this._lastPayload.decodeFailureRecoveryInProgress=!0,this._attach(!0,r,()=>{this._lastPayload.decodeFailureRecoveryInProgress=!1}))}onAttached(){f.logAction(this.logger,f.LOG_MINOR,"RealtimeChannel.onAttached","activating channel; name = "+this.name)}notifyState(r,o,l,c,_,b){if(f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.notifyState","name = "+this.name+", current state = "+this.state+", notifying state "+r),this.clearStateTimer(),["detached","suspended","failed"].includes(r)&&(this.properties.channelSerial=null),r===this.state)return;this._presence&&this._presence.actOnChannelState(r,c,o),this._object&&this._object.actOnChannelState(r,b),r==="suspended"&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),o&&(this.errorReason=o);const C=new Mn(this.state,r,l,_,o),O='Channel state for channel "'+this.name+'"',M=r+(o?"; reason: "+o:"");r==="failed"?f.logAction(this.logger,f.LOG_ERROR,O,M):f.logAction(this.logger,f.LOG_MAJOR,O,M),r!=="attaching"&&r!=="suspended"&&(this.retryCount=0),r==="attached"&&this.onAttached(),r==="attached"?this._attachResume=!0:(r==="detaching"||r==="failed")&&(this._attachResume=!1),this.state=r,this.emit(r,C)}requestState(r,o){f.logAction(this.logger,f.LOG_MINOR,"RealtimeChannel.requestState","name = "+this.name+", state = "+r),this.notifyState(r,o),this.checkPendingState()}checkPendingState(){if(!this.connectionManager.state.sendEvents){f.logAction(this.logger,f.LOG_MINOR,"RealtimeChannel.checkPendingState","sendEvents is false; state is "+this.connectionManager.state.state);return}switch(f.logAction(this.logger,f.LOG_MINOR,"RealtimeChannel.checkPendingState","name = "+this.name+", state = "+this.state),this.state){case"attaching":this.startStateTimerIfNotRunning(),this.attachImpl();break;case"detaching":this.startStateTimerIfNotRunning(),this.detachImpl();break;case"attached":this.sync();break}}timeoutPendingState(){switch(this.state){case"attaching":{const r=new A("Channel attach timed out",90007,408);this.notifyState("suspended",r);break}case"detaching":{const r=new A("Channel detach timed out",90007,408);this.notifyState("attached",r);break}default:this.checkPendingState();break}}startStateTimerIfNotRunning(){this.stateTimer||(this.stateTimer=setTimeout(()=>{f.logAction(this.logger,f.LOG_MINOR,"RealtimeChannel.startStateTimerIfNotRunning","timer expired"),this.stateTimer=null,this.timeoutPendingState()},this.client.options.timeouts.realtimeRequestTimeout))}clearStateTimer(){const r=this.stateTimer;r&&(clearTimeout(r),this.stateTimer=null)}startRetryTimer(){if(this.retryTimer)return;this.retryCount++;const r=qi(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(()=>{this.state==="suspended"&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,f.logAction(this.logger,f.LOG_MINOR,"RealtimeChannel retry timer expired","attempting a new attach"),this.requestState("attaching"))},r)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}getReleaseErr(){const r=this.state;return r==="initialized"||r==="detached"||r==="failed"?null:new A("Can only release a channel in a state where there is no possibility of further updates from the server being received (initialized, detached, or failed); was "+r,90001,400)}setChannelSerial(r){f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.setChannelSerial()","Updating channel serial; serial = "+r+"; previous = "+this.properties.channelSerial),r&&(this.properties.channelSerial=r)}async status(){return this.client.rest.channelMixin.status(this)}async getMessage(r){return f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.getMessage()","channel = "+this.name),this.client.rest.channelMixin.getMessage(this,r)}async updateMessage(r,o,l){return f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.updateMessage()","channel = "+this.name),this.sendUpdate(r,"message.update",o,l)}async deleteMessage(r,o,l){return f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.deleteMessage()","channel = "+this.name),this.sendUpdate(r,"message.delete",o,l)}async appendMessage(r,o,l){return f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.appendMessage()","channel = "+this.name),this.sendUpdate(r,"message.append",o,l)}async sendUpdate(r,o,l,c){var _;if(!r.serial)throw new A('This message lacks a serial and cannot be updated. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);this.throwIfUnpublishableState();const C=await Si.fromValues(P(L({},r),{action:o,version:l})).encode(this.channelOptions),O=ei({action:ue.MESSAGE,channel:this.name,messages:[C],params:c?ms(c):void 0});return{versionSerial:(_=(await this.sendAndAwaitAck(O)).serials[0])!=null?_:null}}async getMessageVersions(r,o){return f.logAction(this.logger,f.LOG_MICRO,"RealtimeChannel.getMessageVersions()","channel = "+this.name),this.client.rest.channelMixin.getMessageVersions(this,r,o)}async ensureAttached(){switch(this.state){case"attached":case"suspended":break;case"initialized":case"detached":case"detaching":case"attaching":await this.attach();break;case"failed":default:throw A.fromValues(this.invalidStateError())}}};function hl(s){const r=s||{},{agent:o}=r;return U(r,["agent"])}var Ys=Iu,Du=class{constructor(s){this.channel=s,this.logger=s.logger,this.subscriptions=new qe(this.logger)}async publish(s,r){const o=this.channel.name,l=ol(s,r),c=await l.encode();this.channel.throwIfUnpublishableState(),f.logAction(this.logger,f.LOG_MICRO,"RealtimeAnnotations.publish()","channelName = "+o+", sending annotation with messageSerial = "+l.messageSerial+", type = "+l.type);const _=ei({action:ue.ANNOTATION,channel:o,annotations:[c]});await this.channel.sendAndAwaitAck(_)}async delete(s,r){r.action="annotation.delete",await this.publish(s,r)}async subscribe(...s){const r=Ys.processListenerArgs(s),o=r[0],l=r[1],c=this.channel;if(c.state==="failed")throw A.fromValues(c.invalidStateError());if(this.subscriptions.on(o,l),this.channel.channelOptions.attachOnSubscribe!==!1&&await c.attach(),(this.channel.state==="attached"&&this.channel._mode&ot.ANNOTATION_SUBSCRIBE)===0)throw new A("You are trying to add an annotation listener, but you haven't requested the annotation_subscribe channel mode in ChannelOptions, so this won't do anything (we only deliver annotations to clients who have explicitly requested them)",93001,400)}unsubscribe(...s){const r=Ys.processListenerArgs(s),o=r[0],l=r[1];this.subscriptions.off(o,l)}_processIncoming(s){for(const r of s)this.subscriptions.emit(r.type||"",r)}async get(s,r){return kn.prototype.get.call(this,s,r)}},cl=Du,os=class Qr extends ku{constructor(r){var o,l;if(!Qr._MsgPack)throw new Error("Expected DefaultRest._MsgPack to have been set");super(J.objectifyOptions(r,!0,"Rest",f.defaultLogger,P(L({},Za),{Crypto:(o=Qr.Crypto)!=null?o:void 0,MsgPack:(l=Qr._MsgPack)!=null?l:void 0,Annotations:{Annotation:Ks,WireAnnotation:Es,RealtimeAnnotations:cl,RestAnnotations:kn}})))}static get Crypto(){if(this._Crypto===null)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(r){this._Crypto=r}};os._Crypto=null,os.Message=Qa,os.PresenceMessage=el,os.Annotation=rl,os._MsgPack=null,os._Http=gt;var On=os,Nu=class extends qe{constructor(s){super(s),this.messages=[]}count(){return this.messages.length}push(s){this.messages.push(s)}shift(){return this.messages.shift()}last(){return this.messages[this.messages.length-1]}copyAll(){return this.messages.slice()}append(s){this.messages.push.apply(this.messages,s)}prepend(s){this.messages.unshift.apply(this.messages,s)}completeMessages(s,r,o){f.logAction(this.logger,f.LOG_MICRO,"MessageQueue.completeMessages()",s=="all"?"(all)":"serial = "+s.serial+"; count = "+s.count),r=r||null;const l=this.messages;if(l.length===0)throw new Error("MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue");let c=[];if(s==="all")c=l.splice(0);else{const _=l[0];if(_){const b=_.message.msgSerial,C=s.serial+s.count;C>b&&(c=l.splice(0,C-b))}}for(let _=0;_<c.length;_++){const b=c[_],C=o==null?void 0:o[_];b.callback(r,C)}l.length==0&&this.emit("idle")}completeAllMessages(s){this.completeMessages("all",s)}resetSendAttempted(){for(let s of this.messages)s.sendAttempted=!1}clear(){f.logAction(this.logger,f.LOG_MICRO,"MessageQueue.clear()","clearing "+this.messages.length+" messages"),this.messages=[],this.emit("idle")}},ul=Nu,dl=class{constructor(s,r){this.message=s,this.callback=r,this.merged=!1;const o=s.action;this.sendAttempted=!1,this.ackRequired=typeof o=="number"&&[ue.MESSAGE,ue.PRESENCE,ue.ANNOTATION,ue.OBJECT].includes(o)}},Hu=class extends qe{constructor(s){super(s.logger),this.transport=s,this.messageQueue=new ul(this.logger),s.on("ack",(r,o,l)=>{this.onAck(r,o,l)}),s.on("nack",(r,o,l)=>{this.onNack(r,o,l)})}onAck(s,r,o){f.logAction(this.logger,f.LOG_MICRO,"Protocol.onAck()","serial = "+s+"; count = "+r),this.messageQueue.completeMessages({serial:s,count:r},null,o)}onNack(s,r,o){f.logAction(this.logger,f.LOG_ERROR,"Protocol.onNack()","serial = "+s+"; count = "+r+"; err = "+it(o)),o||(o=new A("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages({serial:s,count:r},o)}onceIdle(s){const r=this.messageQueue;if(r.count()===0){s();return}r.once("idle",s)}send(s){s.ackRequired&&this.messageQueue.push(s),this.logger.shouldLog(f.LOG_MICRO)&&f.logActionNoStrip(this.logger,f.LOG_MICRO,"Protocol.send()","sending msg; "+Rn(s.message,this.transport.connectionManager.realtime._RealtimePresence,this.transport.connectionManager.realtime._Annotations,this.transport.connectionManager.realtime._liveObjectsPlugin)),s.sendAttempted=!0,this.transport.send(s.message)}getTransport(){return this.transport}getPendingMessages(){return this.messageQueue.copyAll()}clearPendingMessages(){return this.messageQueue.clear()}finish(){const s=this.transport;this.onceIdle(function(){s.disconnect()})}},Uu=Hu,Wu=class{constructor(s,r,o,l){this.previous=s,this.current=r,o&&(this.retryIn=o),l&&(this.reason=l)}},zr=Wu,Vi={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},Fu={disconnected:()=>A.fromValues({statusCode:400,code:Vi.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>A.fromValues({statusCode:400,code:Vi.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>A.fromValues({statusCode:400,code:Vi.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>A.fromValues({statusCode:400,code:Vi.CLOSING,message:"Connection closing"}),closed:()=>A.fromValues({statusCode:400,code:Vi.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>A.fromValues({statusCode:500,code:Vi.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>A.fromValues({statusCode:500,code:Vi.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})};function zu(s){return!s.statusCode||!s.code||s.statusCode>=500?!0:Object.values(Vi).includes(s.code)}var as=Fu,qu=ei({action:ue.CLOSE}),Gu=ei({action:ue.DISCONNECT}),ju=class extends qe{constructor(s,r,o,l){super(s.logger),l&&(o.format=void 0,o.heartbeats=!0),this.connectionManager=s,this.auth=r,this.params=o,this.timeouts=o.options.timeouts,this.format=o.format,this.isConnected=!1,this.isFinished=!1,this.isDisposed=!1,this.maxIdleInterval=null,this.idleTimer=null,this.lastActivity=null}connect(){}close(){this.isConnected&&this.requestClose(),this.finish("closed",as.closed())}disconnect(s){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",s||as.disconnected())}fail(s){this.isConnected&&this.requestDisconnect(),this.finish("failed",s||as.failed())}finish(s,r){var o;this.isFinished||(this.isFinished=!0,this.isConnected=!1,this.maxIdleInterval=null,clearTimeout((o=this.idleTimer)!=null?o:void 0),this.idleTimer=null,this.emit(s,r),this.dispose())}onProtocolMessage(s){switch(this.logger.shouldLog(f.LOG_MICRO)&&f.logActionNoStrip(this.logger,f.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+Rn(s,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),s.action){case ue.HEARTBEAT:f.logActionNoStrip(this.logger,f.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",s.id);break;case ue.CONNECTED:this.onConnect(s),this.emit("connected",s.error,s.connectionId,s.connectionDetails,s);break;case ue.CLOSED:this.onClose(s);break;case ue.DISCONNECTED:this.onDisconnect(s);break;case ue.ACK:this.emit("ack",s.msgSerial,s.count,s.res);break;case ue.NACK:this.emit("nack",s.msgSerial,s.count,s.error);break;case ue.SYNC:this.connectionManager.onChannelMessage(s,this);break;case ue.ACTIVATE:break;case ue.AUTH:Vt(this.auth.authorize(),r=>{r&&f.logAction(this.logger,f.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+it(r))});break;case ue.ERROR:if(f.logAction(this.logger,f.LOG_MINOR,"Transport.onProtocolMessage()","received error action; connectionId = "+this.connectionManager.connectionId+"; err = "+E.Config.inspect(s.error)+(s.channel?", channel: "+s.channel:"")),s.channel===void 0){this.onFatalError(s);break}this.connectionManager.onChannelMessage(s,this);break;default:this.connectionManager.onChannelMessage(s,this)}}onConnect(s){if(this.isConnected=!0,!s.connectionDetails)throw new Error("Transport.onConnect(): Connect message recieved without connectionDetails");const r=s.connectionDetails.maxIdleInterval;r&&(this.maxIdleInterval=r+this.timeouts.realtimeRequestTimeout,this.onActivity())}onDisconnect(s){const r=s&&s.error;f.logAction(this.logger,f.LOG_MINOR,"Transport.onDisconnect()","err = "+it(r)),this.finish("disconnected",r)}onFatalError(s){const r=s&&s.error;f.logAction(this.logger,f.LOG_MINOR,"Transport.onFatalError()","err = "+it(r)),this.finish("failed",r)}onClose(s){const r=s&&s.error;f.logAction(this.logger,f.LOG_MINOR,"Transport.onClose()","err = "+it(r)),this.finish("closed",r)}requestClose(){f.logAction(this.logger,f.LOG_MINOR,"Transport.requestClose()",""),this.send(qu)}requestDisconnect(){f.logAction(this.logger,f.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(Gu)}ping(s){const r={action:ue.HEARTBEAT};s&&(r.id=s),this.send(ei(r))}dispose(){f.logAction(this.logger,f.LOG_MINOR,"Transport.dispose()",""),this.isDisposed=!0,this.off()}onActivity(){this.maxIdleInterval&&(this.lastActivity=this.connectionManager.lastActivity=Date.now(),this.setIdleTimer(this.maxIdleInterval+100))}setIdleTimer(s){this.idleTimer||(this.idleTimer=setTimeout(()=>{this.onIdleTimerExpire()},s))}onIdleTimerExpire(){if(!this.lastActivity||!this.maxIdleInterval)throw new Error("Transport.onIdleTimerExpire(): lastActivity/maxIdleInterval not set");this.idleTimer=null;const s=Date.now()-this.lastActivity,r=this.maxIdleInterval-s;if(r<=0){const o="No activity seen from realtime in "+s+"ms; assuming connection has dropped";f.logAction(this.logger,f.LOG_ERROR,"Transport.onIdleTimerExpire()",o),this.disconnect(new A(o,80003,408))}else this.setIdleTimer(r+100)}static tryConnect(s,r,o,l,c){const _=new s(r,o,l);let b;const C=function(M){clearTimeout(b),c({event:this.event,error:M})},O=r.options.timeouts.realtimeRequestTimeout;return b=setTimeout(()=>{_.off(["preconnect","disconnected","failed"]),_.dispose(),C.call({event:"disconnected"},new A("Timeout waiting for transport to indicate itself viable",5e4,500))},O),_.on(["failed","disconnected"],C),_.on("preconnect",function(){f.logAction(r.logger,f.LOG_MINOR,"Transport.tryConnect()","viable transport "+_),clearTimeout(b),_.off(["failed","disconnected"],C),c(null,_)}),_.connect(),_}static isAvailable(){throw new A("isAvailable not implemented for transport",5e4,500)}},Rs=ju,ti;(s=>{s.WebSocket="web_socket",s.Comet="comet",s.XhrPolling="xhr_polling"})(ti||(ti={}));var $u=typeof Ki<"u"?Ki:typeof window<"u"?window:self,Tn=()=>{var s;return typeof E.WebStorage<"u"&&((s=E.WebStorage)==null?void 0:s.localSupported)},Js=()=>{var s;return typeof E.WebStorage<"u"&&((s=E.WebStorage)==null?void 0:s.sessionSupported)},fl=function(){},Pn="ably-transport-preference";function Ln(s){try{return JSON.parse(s)}catch{return null}}var Vu=class{constructor(s,r,o,l){this.options=s,this.host=r,this.mode=o,this.connectionKey=l,this.format=s.useBinaryProtocol?"msgpack":"json"}getConnectParams(s){const r=s?ct(s):{},o=this.options;switch(this.mode){case"resume":r.resume=this.connectionKey;break;case"recover":{const l=Ln(o.recover);l&&(r.recover=l.connectionKey);break}}return o.clientId!==void 0&&(r.clientId=o.clientId),o.echoMessages===!1&&(r.echo="false"),this.format!==void 0&&(r.format=this.format),this.stream!==void 0&&(r.stream=this.stream),this.heartbeats!==void 0&&(r.heartbeats=this.heartbeats),r.v=J.protocolVersion,r.agent=G(this.options),o.transportParams!==void 0&&se(r,o.transportParams),r}toString(){let s="[mode="+this.mode;return this.host&&(s+=",host="+this.host),this.connectionKey&&(s+=",connectionKey="+this.connectionKey),this.format&&(s+=",format="+this.format),s+="]",s}},Ku=class Vh extends qe{constructor(r,o){super(r.logger),this.supportedTransports={},this.disconnectedRetryCount=0,this.pendingChannelMessagesState={isProcessing:!1,queue:[]},this.realtime=r,this.initTransports(),this.options=o;const l=o.timeouts,c=l.webSocketConnectTimeout+l.realtimeRequestTimeout;if(this.states={initialized:{state:"initialized",terminal:!1,queueEvents:!0,sendEvents:!1,failState:"disconnected"},connecting:{state:"connecting",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:c,failState:"disconnected"},connected:{state:"connected",terminal:!1,queueEvents:!1,sendEvents:!0,failState:"disconnected"},disconnected:{state:"disconnected",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:l.disconnectedRetryTimeout,failState:"disconnected"},suspended:{state:"suspended",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:l.suspendedRetryTimeout,failState:"suspended"},closing:{state:"closing",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:l.realtimeRequestTimeout,failState:"closed"},closed:{state:"closed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"closed"},failed:{state:"failed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"failed"}},this.state=this.states.initialized,this.errorReason=null,this.queuedMessages=new ul(this.logger),this.msgSerial=0,this.connectionDetails=void 0,this.connectionId=void 0,this.connectionKey=void 0,this.connectionStateTtl=l.connectionStateTtl,this.maxIdleInterval=null,this.transports=qt(o.transports||J.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(ti.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(ti.XhrPolling)?this.baseTransport=ti.XhrPolling:this.transports.includes(ti.Comet)&&(this.baseTransport=ti.Comet),this.domains=J.getHosts(o),this.activeProtocol=null,this.host=null,this.lastAutoReconnectAttempt=null,this.lastActivity=null,this.forceFallbackHost=!1,this.connectCounter=0,this.wsCheckResult=null,this.webSocketSlowTimer=null,this.webSocketGiveUpTimer=null,this.abandonedWebSocket=!1,f.logAction(this.logger,f.LOG_MINOR,"Realtime.ConnectionManager()","started"),f.logAction(this.logger,f.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(o.transports||J.defaultTransports)+"]"),f.logAction(this.logger,f.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+this.transports+"]"),f.logAction(this.logger,f.LOG_MICRO,"Realtime.ConnectionManager()","http domains = ["+this.domains+"]"),!this.transports.length){const b="no requested transports available";throw f.logAction(this.logger,f.LOG_ERROR,"realtime.ConnectionManager()",b),new Error(b)}const _=E.Config.addEventListener;_&&(Js()&&typeof o.recover=="function"&&_("beforeunload",this.persistConnection.bind(this)),o.closeOnUnload===!0&&_("beforeunload",()=>{f.logAction(this.logger,f.LOG_MAJOR,"Realtime.ConnectionManager()","beforeunload event has triggered the connection to close as closeOnUnload is true"),this.requestState({state:"closing"})}),_("online",()=>{var b;this.state==this.states.disconnected||this.state==this.states.suspended?(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager caught browser ‘online’ event","reattempting connection"),this.requestState({state:"connecting"})):this.state==this.states.connecting&&((b=this.pendingTransport)==null||b.off(),this.disconnectAllTransports(),this.startConnect())}),_("offline",()=>{this.state==this.states.connected&&(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager caught browser ‘offline’ event","disconnecting active transport"),this.disconnectAllTransports())}))}static supportedTransports(r){const o={supportedTransports:{}};return this.initTransports(r,o),o.supportedTransports}static initTransports(r,o){const l=L(L({},E.Transports.bundledImplementations),r);[ti.WebSocket,...E.Transports.order].forEach(c=>{const _=l[c];_&&_.isAvailable()&&(o.supportedTransports[c]=_)})}initTransports(){Vh.initTransports(this.realtime._additionalTransportImplementations,this)}createTransportParams(r,o){return new Vu(this.options,r,o,this.connectionKey)}getTransportParams(r){(l=>{if(this.connectionKey){l("resume");return}if(typeof this.options.recover=="string"){l("recover");return}const c=this.options.recover,_=this.getSessionRecoverData(),b=this.sessionRecoveryName();if(_&&typeof c=="function"){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data (recovery scope: "+b+")"),c(_,C=>{C?(this.options.recover=_.recoveryKey,l("recover")):l("clean")});return}l("clean")})(l=>{const c=this.createTransportParams(null,l);if(l==="recover"){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+this.options.recover);const _=Ln(this.options.recover);_&&(this.msgSerial=_.msgSerial)}else f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+c.toString());r(c)})}tryATransport(r,o,l){f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+o),this.proposedTransport=Rs.tryConnect(this.supportedTransports[o],this,this.realtime.auth,r,(c,_)=>{const b=this.state;if(b==this.states.closing||b==this.states.closed||b==this.states.failed){_&&(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+b.state+" while we were attempting the transport; closing "+_),_.close()),l(!0);return}if(c){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+o+" "+c.event+", err: "+c.error.toString()),Fe.isTokenErr(c.error)&&!(this.errorReason&&Fe.isTokenErr(this.errorReason))?(this.errorReason=c.error,Vt(this.realtime.auth._forceNewToken(null,null),C=>{if(C){this.actOnErrorFromAuthorize(C);return}this.tryATransport(r,o,l)})):c.event==="failed"?(this.notifyState({state:"failed",error:c.error}),l(!0)):c.event==="disconnected"&&(zu(c.error)?l(!1):(this.notifyState({state:this.states.connecting.failState,error:c.error}),l(!0)));return}f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.tryATransport()","viable transport "+o+"; setting pending"),this.setTransportPending(_,r),l(null,_)})}setTransportPending(r,o){const l=o.mode;f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.setTransportPending()","transport = "+r+"; mode = "+l),this.pendingTransport=r,this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),r.once("connected",(_,b,C)=>{this.activateTransport(_,r,b,C),l==="recover"&&this.options.recover&&(delete this.options.recover,this.unpersistConnection())});const c=this;r.on(["disconnected","closed","failed"],function(_){c.deactivateTransport(r,this.event,_)}),this.emit("transport.pending",r)}activateTransport(r,o,l,c){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+o),r&&f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+r),l&&f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+l),c&&f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(c)),this.persistTransportPreference(o);const _=this.state,b=this.states.connected.state;if(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.activateTransport()","current state = "+_.state),_.state==this.states.closing.state||_.state==this.states.closed.state||_.state==this.states.failed.state)return f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),o.disconnect(),!1;if(delete this.pendingTransport,!o.isConnected)return f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.activateTransport()","Declining to activate transport "+o+" since it appears to no longer be connected"),!1;const C=this.activeProtocol;this.activeProtocol=new Uu(o),this.host=o.params.host;const O=c.connectionKey;if(O&&this.connectionKey!=O&&this.setConnection(l,c,!!r),this.onConnectionDetailsUpdate(c,o),E.Config.nextTick(()=>{o.on("connected",(M,z,q)=>{this.onConnectionDetailsUpdate(q,o),this.emit("update",new zr(b,b,null,M))})}),_.state===this.states.connected.state?r&&(this.errorReason=this.realtime.connection.errorReason=r,this.emit("update",new zr(b,b,null,r))):(this.notifyState({state:"connected",error:r}),this.errorReason=this.realtime.connection.errorReason=r||null),this.emit("transport.active",o),C)if(C.messageQueue.count()>0&&f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+C.transport.shortName+", new one is "+o.shortName+") finishing with "+C.messageQueue.count()+" messages still pending"),C.transport===o){const M="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+o.shortName+"; stack = "+new Error().stack;f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.activateTransport()",M)}else C.finish();return!0}deactivateTransport(r,o,l){const c=this.activeProtocol,_=c&&c.getTransport()===r,b=r===this.pendingTransport,C=this.noTransportsScheduledForActivation();if(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.deactivateTransport()","transport = "+r),f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.deactivateTransport()","state = "+o+(_?"; was active":b?"; was pending":"")+(C?"":"; another transport is scheduled for activation")),l&&l.message&&f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.deactivateTransport()","reason = "+l.message),_&&(f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.deactivateTransport()","Getting, clearing, and requeuing "+this.activeProtocol.messageQueue.count()+" pending messages"),this.queuePendingMessages(c.getPendingMessages()),c.clearPendingMessages(),this.activeProtocol=this.host=null),this.emit("transport.inactive",r),_&&C||_&&o==="failed"||o==="closed"||c===null&&b){if(o==="disconnected"&&l&&l.statusCode>500&&this.domains.length>1){this.unpersistTransportPreference(),this.forceFallbackHost=!0,this.notifyState({state:o,error:l,retryImmediately:!0});return}const O=o==="failed"&&Fe.isTokenErr(l)?"disconnected":o;this.notifyState({state:O,error:l});return}}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(r,o,l){const c=this.connectionId;(c&&c!==r||!c&&l)&&(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.setConnection()","Resetting msgSerial"),this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId!==r&&f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.setConnection()","New connectionId; reattaching any attached channels"),this.realtime.connection.id=this.connectionId=r,this.realtime.connection.key=this.connectionKey=o.connectionKey}clearConnection(){this.realtime.connection.id=this.connectionId=void 0,this.realtime.connection.key=this.connectionKey=void 0,this.msgSerial=0,this.queuedMessages.resetSendAttempted(),this.unpersistConnection()}createRecoveryKey(){return this.connectionKey?JSON.stringify({connectionKey:this.connectionKey,msgSerial:this.msgSerial,channelSerials:this.realtime.channels.channelSerials()}):null}checkConnectionStateFreshness(){if(!this.lastActivity||!this.connectionId)return;const r=Date.now()-this.lastActivity;r>this.connectionStateTtl+this.maxIdleInterval&&(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.checkConnectionStateFreshness()","Last known activity from realtime was "+r+"ms ago; discarding connection state"),this.clearConnection(),this.states.connecting.failState="suspended")}persistConnection(){if(Js()){const r=this.createRecoveryKey();r&&this.setSessionRecoverData({recoveryKey:r,disconnectedAt:Date.now(),location:$u.location,clientId:this.realtime.auth.clientId})}}unpersistConnection(){this.clearSessionRecoverData()}getActiveTransportFormat(){var r;return(r=this.activeProtocol)==null?void 0:r.getTransport().format}getError(){if(this.errorReason){const r=Se.fromValues(this.errorReason);return r.cause=this.errorReason,r}return this.getStateError()}getStateError(){var r,o;return(o=(r=as)[this.state.state])==null?void 0:o.call(r)}activeState(){return this.state.queueEvents||this.state.sendEvents}enactStateChange(r){const o="Connection state",l=r.current+(r.reason?"; reason: "+r.reason:"");r.current==="failed"?f.logAction(this.logger,f.LOG_ERROR,o,l):f.logAction(this.logger,f.LOG_MAJOR,o,l),f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.enactStateChange","setting new state: "+r.current+"; reason = "+(r.reason&&r.reason.message));const c=this.state=this.states[r.current];r.reason&&(this.errorReason=r.reason,this.realtime.connection.errorReason=r.reason),(c.terminal||c.state==="suspended")&&this.clearConnection(),this.emit("connectionstate",r)}startTransitionTimer(r){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+r.state),this.transitionTimer&&(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer)),this.transitionTimer=setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager "+r.state+" timer expired","requesting new state: "+r.failState),this.notifyState({state:r.failState}))},r.retryDelay)}cancelTransitionTimer(){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()",""),this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)}startSuspendTimer(){this.suspendTimer||(this.suspendTimer=setTimeout(()=>{this.suspendTimer&&(this.suspendTimer=null,f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager suspend timer expired","requesting new state: suspended"),this.states.connecting.failState="suspended",this.notifyState({state:"suspended"}))},this.connectionStateTtl))}checkSuspendTimer(r){r!=="disconnected"&&r!=="suspended"&&r!=="connecting"&&this.cancelSuspendTimer()}cancelSuspendTimer(){this.states.connecting.failState="disconnected",this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)}startRetryTimer(r){this.retryTimer=setTimeout(()=>{f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager retry timer expired","retrying"),this.retryTimer=null,this.requestState({state:"connecting"})},r)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}startWebSocketSlowTimer(){this.webSocketSlowTimer=setTimeout(()=>{f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager WebSocket slow timer","checking connectivity"),this.checkWsConnectivity().then(()=>{f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager WebSocket slow timer","ws connectivity check succeeded"),this.wsCheckResult=!0}).catch(()=>{f.logAction(this.logger,f.LOG_MAJOR,"ConnectionManager WebSocket slow timer","ws connectivity check failed"),this.wsCheckResult=!1}),this.realtime.http.checkConnectivity&&Vt(this.realtime.http.checkConnectivity(),(r,o)=>{r||!o?(f.logAction(this.logger,f.LOG_MAJOR,"ConnectionManager WebSocket slow timer","http connectivity check failed"),this.cancelWebSocketGiveUpTimer(),this.notifyState({state:"disconnected",error:new A("Unable to connect (network unreachable)",80003,404)})):f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager WebSocket slow timer","http connectivity check succeeded")})},this.options.timeouts.webSocketSlowTimeout)}cancelWebSocketSlowTimer(){this.webSocketSlowTimer&&(clearTimeout(this.webSocketSlowTimer),this.webSocketSlowTimer=null)}startWebSocketGiveUpTimer(r){this.webSocketGiveUpTimer=setTimeout(()=>{var o,l;this.wsCheckResult||(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager WebSocket give up timer","websocket connection took more than 10s; "+(this.baseTransport?"trying base transport":"")),this.baseTransport?(this.abandonedWebSocket=!0,(o=this.proposedTransport)==null||o.dispose(),(l=this.pendingTransport)==null||l.dispose(),this.connectBase(r,++this.connectCounter)):f.logAction(this.logger,f.LOG_MAJOR,"ConnectionManager WebSocket give up timer","websocket connectivity appears to be unavailable but no other transports to try"))},this.options.timeouts.webSocketConnectTimeout)}cancelWebSocketGiveUpTimer(){this.webSocketGiveUpTimer&&(clearTimeout(this.webSocketGiveUpTimer),this.webSocketGiveUpTimer=null)}notifyState(r){var o,l;const c=r.state,_=c==="disconnected"&&(this.state===this.states.connected||r.retryImmediately||this.state===this.states.connecting&&r.error&&Fe.isTokenErr(r.error)&&!(this.errorReason&&Fe.isTokenErr(this.errorReason)));if(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+c+(_?"; will retry connection immediately":"")),c==this.state.state||(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.checkSuspendTimer(r.state),(c==="suspended"||c==="connected")&&(this.disconnectedRetryCount=0),this.state.terminal))return;const b=this.states[r.state];let C=b.retryDelay;b.state==="disconnected"&&(this.disconnectedRetryCount++,C=qi(b.retryDelay,this.disconnectedRetryCount));const O=new zr(this.state.state,b.state,C,r.error||((l=(o=as)[b.state])==null?void 0:l.call(o)));if(_){const M=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=Date.now(),this.requestState({state:"connecting"}))},z=this.lastAutoReconnectAttempt&&Date.now()-this.lastAutoReconnectAttempt+1;z&&z<1e3?(f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+z+"ms ago, waiting another "+(1e3-z)+"ms before trying again"),setTimeout(M,1e3-z)):E.Config.nextTick(M)}else(c==="disconnected"||c==="suspended")&&this.startRetryTimer(C);(c==="disconnected"&&!_||c==="suspended"||b.terminal)&&E.Config.nextTick(()=>{this.disconnectAllTransports()}),c=="connected"&&!this.activeProtocol&&f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol"),this.enactStateChange(O),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(c,O.reason),this.failQueuedMessages(O.reason))}requestState(r){var o,l;const c=r.state;if(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+c+"; current state: "+this.state.state),c==this.state.state||(this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(c),c=="connecting"&&this.state.state=="connected")||c=="closing"&&this.state.state=="closed")return;const _=this.states[c],b=new zr(this.state.state,_.state,null,r.error||((l=(o=as)[_.state])==null?void 0:l.call(o)));this.enactStateChange(b),c=="connecting"&&E.Config.nextTick(()=>{this.startConnect()}),c=="closing"&&this.closeImpl()}startConnect(){if(this.state!==this.states.connecting){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state);return}const r=this.realtime.auth,o=++this.connectCounter,l=()=>{this.checkConnectionStateFreshness(),this.getTransportParams(c=>{if(c.mode==="recover"&&c.options.recover){const _=Ln(c.options.recover);_&&this.realtime.channels.recoverChannels(_.channelSerials)}o===this.connectCounter&&this.connectImpl(c,o)})};if(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.startConnect()","starting connection"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),r.method==="basic")l();else{const c=_=>{o===this.connectCounter&&(_?this.actOnErrorFromAuthorize(_):l())};this.errorReason&&Fe.isTokenErr(this.errorReason)?Vt(r._forceNewToken(null,null),c):Vt(r._ensureValidAuthCredentials(!1),c)}}connectImpl(r,o){const l=this.state.state;if(l!==this.states.connecting.state){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect, but was "+l);return}const c=this.getTransportPreference();c&&c===this.baseTransport&&this.webSocketTransportAvailable&&this.checkWsConnectivity().then(()=>{this.unpersistTransportPreference(),this.state===this.states.connecting&&(f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.connectImpl():","web socket connectivity available, cancelling connection attempt with "+this.baseTransport),this.disconnectAllTransports(),this.connectWs(r,++this.connectCounter))}).catch(fl),c&&c===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(r,o):this.connectWs(r,o)}connectWs(r,o){f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.connectWs()"),this.wsCheckResult=null,this.abandonedWebSocket=!1,this.startWebSocketSlowTimer(),this.startWebSocketGiveUpTimer(r),this.tryTransportWithFallbacks("web_socket",r,!0,o,()=>this.wsCheckResult!==!1&&!this.abandonedWebSocket)}connectBase(r,o){f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.connectBase()"),this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,r,!1,o,()=>!0):this.notifyState({state:"disconnected",error:new A("No transports left to try",8e4,404)})}tryTransportWithFallbacks(r,o,l,c,_){f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.tryTransportWithFallbacks()",r);const b=q=>{this.notifyState({state:this.states.connecting.failState,error:q})},C=this.domains.slice(),O=(q,Q)=>{if(c===this.connectCounter){if(!_()){Q&&Q.dispose();return}!Q&&!q&&z()}},M=C.shift();if(!M){b(new A("Unable to connect (no available host)",80003,404));return}o.host=M;const z=()=>{if(!C.length){b(new A("Unable to connect (and no more fallback hosts to try)",80003,404));return}if(!this.realtime.http.checkConnectivity){b(new Se("Internal error: Http.checkConnectivity not set",null,500));return}Vt(this.realtime.http.checkConnectivity(),(q,Q)=>{if(c===this.connectCounter&&_()){if(q){b(q);return}if(!Q){b(new A("Unable to connect (network unreachable)",80003,404));return}o.host=gi(C),this.tryATransport(o,r,O)}})};if(this.forceFallbackHost&&C.length){this.forceFallbackHost=!1,z();return}this.tryATransport(o,r,O)}closeImpl(){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.closeImpl()","closing connection"),this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),this.pendingTransport&&(f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.closeImpl()","Closing pending transport: "+this.pendingTransport),this.pendingTransport.close()),this.activeProtocol&&(f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.closeImpl()","Closing active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().close()),this.notifyState({state:"closed"})}onAuthUpdated(r,o){var l;switch(this.state.state){case"connected":{f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Sending AUTH message on active transport");const c=(l=this.activeProtocol)==null?void 0:l.getTransport();c&&c.onAuthUpdated&&c.onAuthUpdated(r);const _=ei({action:ue.AUTH,auth:{accessToken:r.token}});this.send(_);const b=()=>{this.off(C),o(null,r)},C=O=>{O.current==="failed"&&(this.off(b),this.off(C),o(O.reason||this.getStateError()))};this.once("connectiondetails",b),this.on("connectionstate",C);break}case"connecting":f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Aborting current connection attempts in order to start again with the new auth details"),this.disconnectAllTransports();default:{f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Connection state is "+this.state.state+"; waiting until either connected or failed");const c=_=>{switch(_.current){case"connected":this.off(c),o(null,r);break;case"failed":case"closed":case"suspended":this.off(c),o(_.reason||this.getStateError());break}};this.on("connectionstate",c),this.state.state==="connecting"?this.startConnect():this.requestState({state:"connecting"})}}}disconnectAllTransports(){f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.disconnectAllTransports()","Disconnecting all transports"),this.connectCounter++,this.pendingTransport&&(f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting pending transport: "+this.pendingTransport),this.pendingTransport.disconnect()),delete this.pendingTransport,this.proposedTransport&&(f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting proposed transport: "+this.pendingTransport),this.proposedTransport.disconnect()),delete this.pendingTransport,this.activeProtocol&&(f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())}send(r,o,l){l=l||fl;const c=this.state;if(c.sendEvents){f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new dl(r,l));return}if(!(o&&c.queueEvents)){const b="rejecting event, queueEvent was "+o+", state was "+c.state;f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.send()",b),l(this.errorReason||new A(b,9e4,400));return}this.logger.shouldLog(f.LOG_MICRO)&&f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.send()","queueing msg; "+Rn(r,this.realtime._RealtimePresence,this.realtime._Annotations,this.realtime._liveObjectsPlugin)),this.queue(r,l)}sendImpl(r){const o=r.message;r.ackRequired&&!r.sendAttempted&&(o.msgSerial=this.msgSerial++);try{this.activeProtocol.send(r)}catch(l){f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+l.stack)}}queue(r,o){f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.queue()","queueing event"),this.queuedMessages.push(new dl(r,o))}sendQueuedMessages(){f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.sendQueuedMessages()","sending "+this.queuedMessages.count()+" queued messages");let r;for(;r=this.queuedMessages.shift();)this.sendImpl(r)}queuePendingMessages(r){r&&r.length&&(f.logAction(this.logger,f.LOG_MICRO,"ConnectionManager.queuePendingMessages()","queueing "+r.length+" pending messages"),this.queuedMessages.prepend(r))}failQueuedMessages(r){const o=this.queuedMessages.count();o>0&&(f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+o+" queued messages, err = "+it(r)),this.queuedMessages.completeAllMessages(r))}onChannelMessage(r,o){this.pendingChannelMessagesState.queue.push({message:r,transport:o}),this.pendingChannelMessagesState.isProcessing||this.processNextPendingChannelMessage()}processNextPendingChannelMessage(){if(this.pendingChannelMessagesState.queue.length>0){this.pendingChannelMessagesState.isProcessing=!0;const r=this.pendingChannelMessagesState.queue.shift();this.processChannelMessage(r.message).catch(o=>{f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.processNextPendingChannelMessage() received error ",o)}).finally(()=>{this.pendingChannelMessagesState.isProcessing=!1,this.processNextPendingChannelMessage()})}}async processChannelMessage(r){await this.realtime.channels.processChannelMessage(r)}async ping(){var r;if(this.state.state!=="connected")throw new A("Unable to ping service; not connected",4e4,400);const o=(r=this.activeProtocol)==null?void 0:r.getTransport();if(!o)throw this.getStateError();f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.ping()","transport = "+o);const l=Date.now(),c=Ui();return yi(new Promise(_=>{const b=C=>{C===c&&(o.off("heartbeat",b),_(Date.now()-l))};o.on("heartbeat",b),o.ping(c)}),this.options.timeouts.realtimeRequestTimeout,"Timeout waiting for heartbeat response")}abort(r){this.activeProtocol.getTransport().fail(r)}getTransportPreference(){var r,o;return this.transportPreference||Tn()&&((o=(r=E.WebStorage)==null?void 0:r.get)==null?void 0:o.call(r,Pn))}persistTransportPreference(r){var o,l;this.transportPreference=r.shortName,Tn()&&((l=(o=E.WebStorage)==null?void 0:o.set)==null||l.call(o,Pn,r.shortName))}unpersistTransportPreference(){var r,o;this.transportPreference=null,Tn()&&((o=(r=E.WebStorage)==null?void 0:r.remove)==null||o.call(r,Pn))}actOnErrorFromAuthorize(r){if(r.code===40171)this.notifyState({state:"failed",error:r});else if(r.code===40102)this.notifyState({state:"failed",error:r});else if(r.statusCode===ve.Forbidden){const o="Client configured authentication provider returned 403; failing the connection";f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",o),this.notifyState({state:"failed",error:new A(o,80019,403,r)})}else{const o="Client configured authentication provider request failed";f.logAction(this.logger,f.LOG_MINOR,"ConnectionManager.actOnErrorFromAuthorize",o),this.notifyState({state:this.state.failState,error:new A(o,80019,401,r)})}}onConnectionDetailsUpdate(r,o){if(!r)return;this.connectionDetails=r,r.maxMessageSize&&(this.options.maxMessageSize=r.maxMessageSize);const l=r.clientId;if(l){const _=this.realtime.auth._uncheckedSetClientId(l);if(_){f.logAction(this.logger,f.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",_.message),o.fail(_);return}}const c=r.connectionStateTtl;c&&(this.connectionStateTtl=c),this.maxIdleInterval=r.maxIdleInterval,this.emit("connectiondetails",r)}checkWsConnectivity(){const r=this.options.wsConnectivityCheckUrl||J.wsConnectivityCheckUrl,o=new E.Config.WebSocket(r);return new Promise((l,c)=>{let _=!1;o.onopen=()=>{_||(_=!0,l(),o.close())},o.onclose=o.onerror=()=>{_||(_=!0,c())}})}sessionRecoveryName(){return this.options.recoveryKeyStorageName||"ably-connection-recovery"}getSessionRecoverData(){var r,o;return Js()&&((o=(r=E.WebStorage)==null?void 0:r.getSession)==null?void 0:o.call(r,this.sessionRecoveryName()))}setSessionRecoverData(r){var o,l;return Js()&&((l=(o=E.WebStorage)==null?void 0:o.setSession)==null?void 0:l.call(o,this.sessionRecoveryName(),r))}clearSessionRecoverData(){var r,o;return Js()&&((o=(r=E.WebStorage)==null?void 0:r.removeSession)==null?void 0:o.call(r,this.sessionRecoveryName()))}},_l=Ku,Yu=class extends qe{constructor(s,r){super(s.logger),this.whenState=o=>qe.prototype.whenState.call(this,o,this.state),this.ably=s,this.connectionManager=new _l(s,r),this.state=this.connectionManager.state.state,this.key=void 0,this.id=void 0,this.errorReason=null,this.connectionManager.on("connectionstate",o=>{const l=this.state=o.current;E.Config.nextTick(()=>{this.emit(l,o)})}),this.connectionManager.on("update",o=>{E.Config.nextTick(()=>{this.emit("update",o)})})}connect(){f.logAction(this.logger,f.LOG_MINOR,"Connection.connect()",""),this.connectionManager.requestState({state:"connecting"})}async ping(){return f.logAction(this.logger,f.LOG_MINOR,"Connection.ping()",""),this.connectionManager.ping()}close(){f.logAction(this.logger,f.LOG_MINOR,"Connection.close()","connectionKey = "+this.key),this.connectionManager.requestState({state:"closing"})}get recoveryKey(){return this.logger.deprecationWarning("The `Connection.recoveryKey` attribute has been replaced by the `Connection.createRecoveryKey()` method. Replace your usage of `recoveryKey` with the return value of `createRecoveryKey()`. `recoveryKey` will be removed in a future version."),this.createRecoveryKey()}createRecoveryKey(){return this.connectionManager.createRecoveryKey()}},Ju=Yu,gl=class Kh extends Ba{constructor(r){var o,l,c,_;if(super(J.objectifyOptions(r,!1,"BaseRealtime",f.defaultLogger)),f.logAction(this.logger,f.LOG_MINOR,"Realtime()",""),typeof EdgeRuntime=="string")throw new A(`Ably.Realtime instance cannot be used in Vercel Edge runtime. If you are running Vercel Edge functions, please replace your "new Ably.Realtime()" with "new Ably.Rest()" and use Ably Rest API instead of the Realtime API. If you are server-rendering your application in the Vercel Edge runtime, please use the condition "if (typeof EdgeRuntime === 'string')" to prevent instantiating Ably.Realtime instance during SSR in the Vercel Edge runtime.`,4e4,400);this._additionalTransportImplementations=Kh.transportImplementationsFromPlugins(this.options.plugins),this._RealtimePresence=(l=(o=this.options.plugins)==null?void 0:o.RealtimePresence)!=null?l:null,this._liveObjectsPlugin=(_=(c=this.options.plugins)==null?void 0:c.LiveObjects)!=null?_:null,this.connection=new Ju(this,this.options),this._channels=new Zu(this),this.options.autoConnect!==!1&&this.connect()}static transportImplementationsFromPlugins(r){const o={};return r!=null&&r.WebSocketTransport&&(o[ti.WebSocket]=r.WebSocketTransport),r!=null&&r.XHRPolling&&(o[ti.XhrPolling]=r.XHRPolling),o}get channels(){return this._channels}get clientId(){return this.auth.clientId}connect(){f.logAction(this.logger,f.LOG_MINOR,"Realtime.connect()",""),this.connection.connect()}close(){f.logAction(this.logger,f.LOG_MINOR,"Realtime.close()",""),this.connection.close()}};gl.EventEmitter=qe;var Xu=gl,Zu=class extends qe{constructor(s){super(s.logger),this.realtime=s,this.all=Object.create(null),s.connection.connectionManager.on("transport.active",()=>{this.onTransportActive()})}channelSerials(){let s={};for(const r of _i(this.all,!0)){const o=this.all[r];o.properties.channelSerial&&(s[r]=o.properties.channelSerial)}return s}recoverChannels(s){for(const r of _i(s,!0)){const o=this.get(r);o.properties.channelSerial=s[r]}}async processChannelMessage(s){const r=s.channel;if(r===void 0){f.logAction(this.logger,f.LOG_ERROR,"Channels.processChannelMessage()","received event unspecified channel, action = "+s.action);return}const o=this.all[r];if(!o){f.logAction(this.logger,f.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+r);return}await o.processMessage(s)}onTransportActive(){for(const s in this.all){const r=this.all[s];r.state==="attaching"||r.state==="detaching"?r.checkPendingState():r.state==="suspended"?r._attach(!1,null):r.state==="attached"&&r.requestState("attaching")}}propogateConnectionInterruption(s,r){const o={closing:"detached",closed:"detached",failed:"failed",suspended:"suspended"},l=["attaching","attached","detaching","suspended"],c=o[s];for(const _ in this.all){const b=this.all[_];l.includes(b.state)&&b.notifyState(c,r)}}get(s,r){s=String(s);let o=this.all[s];if(!o)o=this.all[s]=new Ys(this.realtime,s,r);else if(r){if(o._shouldReattachToSetOptions(r,o.channelOptions))throw new A("Channels.get() cannot be used to set channel options that would cause the channel to reattach. Please, use RealtimeChannel.setOptions() instead.",4e4,400);o.setOptions(r)}return o}getDerived(s,r,o){if(r.filter){const l=ns(r.filter),c=Ss(s);s=`[filter=${l}${c.qualifierParam}]${c.channelName}`}return this.get(s,o)}release(s){s=String(s);const r=this.all[s];if(!r)return;const o=r.getReleaseErr();if(o)throw o;delete this.all[s]}},Qu=Xu;function ed(s,r){if(s.isSynthesized()||r.isSynthesized())return s.timestamp>=r.timestamp;const o=s.parseId(),l=r.parseId();return o.msgSerial===l.msgSerial?o.index>l.index:o.msgSerial>l.msgSerial}var Bn=class extends qe{constructor(s,r,o=ed){super(s.logger),this.presence=s,this.map=Object.create(null),this.syncInProgress=!1,this.residualMembers=null,this.memberKey=r,this.newerThan=o}get(s){return this.map[s]}getClient(s){const r=this.map,o=[];for(const l in r){const c=r[l];c.clientId==s&&c.action!="absent"&&o.push(c)}return o}list(s){const r=this.map,o=s&&s.clientId,l=s&&s.connectionId,c=[];for(const _ in r){const b=r[_];b.action!=="absent"&&(o&&o!=b.clientId||l&&l!=b.connectionId||c.push(b))}return c}put(s){(s.action==="enter"||s.action==="update")&&(s=$i.fromValues(s),s.action="present");const r=this.map,o=this.memberKey(s);this.residualMembers&&delete this.residualMembers[o];const l=r[o];return l&&!this.newerThan(s,l)?!1:(r[o]=s,!0)}values(){const s=this.map,r=[];for(const o in s){const l=s[o];l.action!="absent"&&r.push(l)}return r}remove(s){const r=this.map,o=this.memberKey(s),l=r[o];return l&&!this.newerThan(s,l)?!1:(this.syncInProgress?(s=$i.fromValues(s),s.action="absent",r[o]=s):delete r[o],!!l)}startSync(){const s=this.map,r=this.syncInProgress;f.logAction(this.logger,f.LOG_MINOR,"PresenceMap.startSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+r),this.syncInProgress||(this.residualMembers=ct(s),this.setInProgress(!0))}endSync(){const s=this.map,r=this.syncInProgress;if(f.logAction(this.logger,f.LOG_MINOR,"PresenceMap.endSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+r),r){for(const o in s)s[o].action==="absent"&&delete s[o];this.presence._synthesizeLeaves(Br(this.residualMembers));for(const o in this.residualMembers)delete s[o];this.residualMembers=null,this.setInProgress(!1)}this.emit("sync")}async waitSync(){const s=this.syncInProgress;f.logAction(this.logger,f.LOG_MINOR,"PresenceMap.waitSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+s),s&&await this.once("sync")}clear(){this.map={},this.setInProgress(!1),this.residualMembers=null}setInProgress(s){f.logAction(this.logger,f.LOG_MICRO,"PresenceMap.setInProgress()","inProgress = "+s),this.syncInProgress=s,this.presence.syncComplete=!s}};function td(s){return s.channel.client.auth.clientId}function In(s){const r=s.channel.client,o=r.auth.clientId;return(!o||o==="*")&&r.connection.state==="connected"}var id=class extends qe{constructor(s){super(s.logger),this.channel=s,this.syncComplete=!1,this.members=new Bn(this,r=>r.clientId+":"+r.connectionId),this._myMembers=new Bn(this,r=>r.clientId),this.subscriptions=new qe(this.logger),this.pendingPresence=[]}async enter(s){if(In(this))throw new A("clientId must be specified to enter a presence channel",40012,400);return this._enterOrUpdateClient(void 0,void 0,s,"enter")}async update(s){if(In(this))throw new A("clientId must be specified to update presence data",40012,400);return this._enterOrUpdateClient(void 0,void 0,s,"update")}async enterClient(s,r){return this._enterOrUpdateClient(void 0,s,r,"enter")}async updateClient(s,r){return this._enterOrUpdateClient(void 0,s,r,"update")}async _enterOrUpdateClient(s,r,o,l){const c=this.channel;if(!c.connectionManager.activeState())throw c.connectionManager.getError();f.logAction(this.logger,f.LOG_MICRO,"RealtimePresence."+l+"Client()","channel = "+c.name+", id = "+s+", client = "+(r||"(implicit) "+td(this)));const _=$i.fromData(o);_.action=l,s&&(_.id=s),r&&(_.clientId=r);const b=await _.encode(c.channelOptions);switch(c.state){case"attached":return c.sendPresence([b]);case"initialized":case"detached":c.attach();case"attaching":return new Promise((C,O)=>{this.pendingPresence.push({presence:b,callback:M=>M?O(M):C()})});default:{const C=new Se("Unable to "+l+" presence channel while in "+c.state+" state",90001);throw C.code=90001,C}}}async leave(s){if(In(this))throw new A("clientId must have been specified to enter or leave a presence channel",40012,400);return this.leaveClient(void 0,s)}async leaveClient(s,r){const o=this.channel;if(!o.connectionManager.activeState())throw o.connectionManager.getError();f.logAction(this.logger,f.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+this.channel.name+", client = "+s);const l=$i.fromData(r);l.action="leave",s&&(l.clientId=s);const c=await l.encode(o.channelOptions);switch(o.state){case"attached":return o.sendPresence([c]);case"attaching":return new Promise((_,b)=>{this.pendingPresence.push({presence:c,callback:C=>C?b(C):_()})});case"initialized":case"failed":throw new Se("Unable to leave presence channel (incompatible state)",90001);default:throw o.invalidStateError()}}async get(s){const r=!s||("waitForSync"in s?s.waitForSync:!0);function o(c){return s?c.list(s):c.values()}if(this.channel.state==="suspended"){if(r)throw A.fromValues({statusCode:400,code:91005,message:"Presence state is out of sync due to channel being in the SUSPENDED state"});return o(this.members)}await this.channel.ensureAttached();const l=this.members;return r&&await l.waitSync(),o(this.members)}async history(s){f.logAction(this.logger,f.LOG_MICRO,"RealtimePresence.history()","channel = "+this.name);const r=this.channel.client.rest.presenceMixin;if(s&&s.untilAttach)if(this.channel.state==="attached")delete s.untilAttach,s.from_serial=this.channel.properties.attachSerial;else throw new A("option untilAttach requires the channel to be attached, was: "+this.channel.state,4e4,400);return r.history(this,s)}setPresence(s,r,o){f.logAction(this.logger,f.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+s.length+" participants; syncChannelSerial = "+o);let l,c;const _=this.members,b=this._myMembers,C=[],O=this.channel.connectionManager.connectionId;r&&(this.members.startSync(),o&&(c=o.match(/^[\w-]+:(.*)$/))&&(l=c[1]));for(let M of s)switch(M.action){case"leave":_.remove(M)&&C.push(M),M.connectionId===O&&!M.isSynthesized()&&b.remove(M);break;case"enter":case"present":case"update":_.put(M)&&C.push(M),M.connectionId===O&&b.put(M);break}r&&!l&&(_.endSync(),this.channel.syncChannelSerial=null);for(let M=0;M<C.length;M++){const z=C[M];this.subscriptions.emit(z.action,z)}}onAttached(s){f.logAction(this.logger,f.LOG_MINOR,"RealtimePresence.onAttached()","channel = "+this.channel.name+", hasPresence = "+s),s?this.members.startSync():(this._synthesizeLeaves(this.members.values()),this.members.clear()),this._ensureMyMembersPresent();const r=this.pendingPresence,o=r.length;if(o){this.pendingPresence=[];const l=[],c=Ee.create(this.logger);f.logAction(this.logger,f.LOG_MICRO,"RealtimePresence.onAttached","sending "+o+" queued presence messages");for(let _=0;_<o;_++){const b=r[_];l.push(b.presence),c.push(b.callback)}this.channel.sendPresence(l).then(()=>c()).catch(_=>c(_))}}actOnChannelState(s,r,o){switch(s){case"attached":this.onAttached(r);break;case"detached":case"failed":this._clearMyMembers(),this.members.clear();case"suspended":this.failPendingPresence(o);break}}failPendingPresence(s){if(this.pendingPresence.length){f.logAction(this.logger,f.LOG_MINOR,"RealtimeChannel.failPendingPresence","channel; name = "+this.channel.name+", err = "+it(s));for(let r=0;r<this.pendingPresence.length;r++)try{this.pendingPresence[r].callback(s)}catch{}this.pendingPresence=[]}}_clearMyMembers(){this._myMembers.clear()}_ensureMyMembersPresent(){const s=this._myMembers,r=this.channel.connectionManager.connectionId;for(const o in s.map){const l=s.map[o];f.logAction(this.logger,f.LOG_MICRO,"RealtimePresence._ensureMyMembersPresent()",'Auto-reentering clientId "'+l.clientId+'" into the presence set');const c=l.connectionId===r?l.id:void 0;this._enterOrUpdateClient(c,l.clientId,l.data,"enter").catch(_=>{const b=new A("Presence auto re-enter failed",91004,400,_);f.logAction(this.logger,f.LOG_ERROR,"RealtimePresence._ensureMyMembersPresent()","Presence auto re-enter failed; reason = "+it(_));const C=new Mn(this.channel.state,this.channel.state,!0,!1,b);this.channel.emit("update",C)})}}_synthesizeLeaves(s){const r=this.subscriptions;s.forEach(function(o){const l=$i.fromValues({action:"leave",connectionId:o.connectionId,clientId:o.clientId,data:o.data,encoding:o.encoding,timestamp:Date.now()});r.emit("leave",l)})}async subscribe(...s){const r=Ys.processListenerArgs(s),o=r[0],l=r[1],c=this.channel;if(c.state==="failed")throw A.fromValues(c.invalidStateError());this.subscriptions.on(o,l),c.channelOptions.attachOnSubscribe!==!1&&await c.attach()}unsubscribe(...s){const r=Ys.processListenerArgs(s),o=r[0],l=r[1];this.subscriptions.off(o,l)}},sd=id,rd=ti.WebSocket;function nd(s){return!!s.on}var od=class extends Rs{constructor(s,r,o){super(s,r,o),this.shortName=rd,o.heartbeats=E.Config.useProtocolHeartbeats,this.wsHost=o.host}static isAvailable(){return!!E.Config.WebSocket}createWebSocket(s,r){return this.uri=s+vi(r),new E.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){f.logAction(this.logger,f.LOG_MINOR,"WebSocketTransport.connect()","starting"),Rs.prototype.connect.call(this);const s=this,r=this.params,o=r.options,c=(o.tls?"wss://":"ws://")+this.wsHost+":"+J.getPort(o)+"/";f.logAction(this.logger,f.LOG_MINOR,"WebSocketTransport.connect()","uri: "+c),Vt(this.auth.getAuthParams(),function(_,b){if(s.isDisposed)return;let C="";for(const M in b)C+=" "+M+": "+b[M]+";";if(f.logAction(s.logger,f.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+C+" err: "+_),_){s.disconnect(_);return}const O=r.getConnectParams(b);try{const M=s.wsConnection=s.createWebSocket(c,O);M.binaryType=E.Config.binaryType,M.onopen=function(){s.onWsOpen()},M.onclose=function(z){s.onWsClose(z)},M.onmessage=function(z){s.onWsData(z.data)},M.onerror=function(z){s.onWsError(z)},nd(M)&&M.on("ping",function(){s.onActivity()})}catch(M){f.logAction(s.logger,f.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(M.stack||M.message)),s.disconnect(M)}})}send(s){const r=this.wsConnection;if(!r){f.logAction(this.logger,f.LOG_ERROR,"WebSocketTransport.send()","No socket connection");return}try{r.send(Ou(s,this.connectionManager.realtime._MsgPack,this.params.format))}catch(o){const l="Exception from ws connection when trying to send: "+it(o);f.logAction(this.logger,f.LOG_ERROR,"WebSocketTransport.send()",l),this.finish("disconnected",new A(l,5e4,500))}}onWsData(s){f.logAction(this.logger,f.LOG_MICRO,"WebSocketTransport.onWsData()","data received; length = "+s.length+"; type = "+typeof s);try{this.onProtocolMessage(Tu(s,this.connectionManager.realtime._MsgPack,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin,this.format))}catch(r){f.logAction(this.logger,f.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+r.stack)}}onWsOpen(){f.logAction(this.logger,f.LOG_MINOR,"WebSocketTransport.onWsOpen()","opened WebSocket"),this.emit("preconnect")}onWsClose(s){let r,o;if(typeof s=="object"?(o=s.code,r=s.wasClean||o===1e3):(o=s,r=o==1e3),delete this.wsConnection,r){f.logAction(this.logger,f.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket");const l=new A("Websocket closed",80003,400);this.finish("disconnected",l)}else{const l="Unclean disconnection of WebSocket ; code = "+o,c=new A(l,80003,400);f.logAction(this.logger,f.LOG_MINOR,"WebSocketTransport.onWsClose()",l),this.finish("disconnected",c)}this.emit("disposed")}onWsError(s){f.logAction(this.logger,f.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+s.message),E.Config.nextTick(()=>{this.disconnect(Error(s.message))})}dispose(){f.logAction(this.logger,f.LOG_MINOR,"WebSocketTransport.dispose()",""),this.isDisposed=!0;const s=this.wsConnection;s&&(s.onmessage=function(){},delete this.wsConnection,E.Config.nextTick(()=>{if(f.logAction(this.logger,f.LOG_MICRO,"WebSocketTransport.dispose()","closing websocket"),!s)throw new Error("WebSocketTransport.dispose(): wsConnection is not defined");s.close()}))}},pl=od,ad=class{static subscribeFilter(s,r,o){const l=c=>{var _,b,C,O,M,z;const q={name:c.name,refTimeserial:(b=(_=c.extras)==null?void 0:_.ref)==null?void 0:b.timeserial,refType:(O=(C=c.extras)==null?void 0:C.ref)==null?void 0:O.type,isRef:!!((z=(M=c.extras)==null?void 0:M.ref)!=null&&z.timeserial),clientId:c.clientId};Object.entries(r).find(([Q,F])=>F!==void 0?q[Q]!==F:!1)||o(c)};this.addFilteredSubscription(s,r,o,l),s.subscriptions.on(l)}static addFilteredSubscription(s,r,o,l){var c;if(s.filteredSubscriptions||(s.filteredSubscriptions=new Map),s.filteredSubscriptions.has(o)){const _=s.filteredSubscriptions.get(o);_.set(r,((c=_==null?void 0:_.get(r))==null?void 0:c.concat(l))||[l])}else s.filteredSubscriptions.set(o,new Map([[r,[l]]]))}static getAndDeleteFilteredSubscriptions(s,r,o){if(!s.filteredSubscriptions)return[];if(!o&&r)return Array.from(s.filteredSubscriptions.entries()).map(([_,b])=>{var C;let O=b.get(r);return b.delete(r),b.size===0&&((C=s.filteredSubscriptions)==null||C.delete(_)),O}).reduce((_,b)=>b?_.concat(...b):_,[]);if(!o||!s.filteredSubscriptions.has(o))return[];const l=s.filteredSubscriptions.get(o);if(!r){const _=Array.from(l.values()).reduce((b,C)=>b.concat(...C),[]);return s.filteredSubscriptions.delete(o),_}let c=l.get(r);return l.delete(r),c||[]}},li=class So extends Qu{constructor(r){var o;const l=So._MsgPack;if(!l)throw new Error("Expected DefaultRealtime._MsgPack to have been set");super(J.objectifyOptions(r,!0,"Realtime",f.defaultLogger,P(L({},Za),{Crypto:(o=So.Crypto)!=null?o:void 0,MsgPack:l,RealtimePresence:{RealtimePresence:sd,PresenceMessage:$i,WirePresenceMessage:$s},Annotations:{Annotation:Ks,WireAnnotation:Es,RealtimeAnnotations:cl,RestAnnotations:kn},WebSocketTransport:pl,MessageInteractions:ad})))}static get Crypto(){if(this._Crypto===null)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(r){this._Crypto=r}};li.Utils=re,li.ConnectionManager=_l,li.ProtocolMessage=Pu,li._Crypto=null,li.Message=Qa,li.PresenceMessage=el,li.Annotation=rl,li._MsgPack=null,li._Http=gt,li._PresenceMap=Bn,li._MessageEncoding=Hr;var Dn=li,Nn=Uint8Array,Xs=Uint32Array,Hn=Math.pow,ml=new Xs(8),vl=[],Zs=new Xs(64);function yl(s){return(s-(s|0))*Hn(2,32)|0}for(var Qs=2,er=0;er<64;){for(Un=!0,qr=2;qr<=Qs/2;qr++)Qs%qr===0&&(Un=!1);Un&&(er<8&&(ml[er]=yl(Hn(Qs,1/2))),vl[er]=yl(Hn(Qs,1/3)),er++),Qs++}var Un,qr,ld=!!new Nn(new Xs([1]).buffer)[0];function Wn(s){return ld?s>>>24|(s>>>16&255)<<8|(s&65280)<<8|s<<24:s}function bi(s,r){return s>>>r|s<<32-r}function Gr(s){var r=ml.slice(),o=s.length,l=o*8,c=512-(l+64)%512-1+l+65,_=new Nn(c/8),b=new Xs(_.buffer);_.set(s,0),_[o]=128,b[b.length-1]=Wn(l);for(var C,O=0;O<c/32;O+=16){var M=r.slice();for(C=0;C<64;C++){var z;if(C<16)z=Wn(b[O+C]);else{var q=Zs[C-15],Q=Zs[C-2];z=Zs[C-7]+Zs[C-16]+(bi(q,7)^bi(q,18)^q>>>3)+(bi(Q,17)^bi(Q,19)^Q>>>10)}Zs[C]=z|=0;for(var F=(bi(M[4],6)^bi(M[4],11)^bi(M[4],25))+(M[4]&M[5]^~M[4]&M[6])+M[7]+z+vl[C],pe=(bi(M[0],2)^bi(M[0],13)^bi(M[0],22))+(M[0]&M[1]^M[2]&(M[0]^M[1])),me=7;me>0;me--)M[me]=M[me-1];M[0]=F+pe|0,M[4]=M[4]+F|0}for(C=0;C<8;C++)r[C]=r[C]+M[C]|0}return new Nn(new Xs(r.map(function(Re){return Wn(Re)})).buffer)}function hd(s,r){if(s.length>64&&(s=Gr(s)),s.length<64){const C=new Uint8Array(64);C.set(s,0),s=C}for(var o=new Uint8Array(64),l=new Uint8Array(64),c=0;c<64;c++)o[c]=54^s[c],l[c]=92^s[c];var _=new Uint8Array(r.length+64);_.set(o,0),_.set(r,64);var b=new Uint8Array(96);return b.set(l,0),b.set(Gr(_),64),Gr(b)}var cd=class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}uint8ViewToBase64(s){let r="";const o=this.base64CharSet,l=s.byteLength,c=l%3,_=l-c;let b,C,O,M,z;for(let q=0;q<_;q=q+3)z=s[q]<<16|s[q+1]<<8|s[q+2],b=(z&16515072)>>18,C=(z&258048)>>12,O=(z&4032)>>6,M=z&63,r+=o[b]+o[C]+o[O]+o[M];return c==1?(z=s[_],b=(z&252)>>2,C=(z&3)<<4,r+=o[b]+o[C]+"=="):c==2&&(z=s[_]<<8|s[_+1],b=(z&64512)>>10,C=(z&1008)>>4,O=(z&15)<<2,r+=o[b]+o[C]+o[O]+"="),r}base64ToArrayBuffer(s){const r=atob==null?void 0:atob(s),o=r.length,l=new Uint8Array(o);for(let c=0;c<o;c++){const _=r.charCodeAt(c);l[c]=_}return this.toArrayBuffer(l)}isBuffer(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}toBuffer(s){if(!ArrayBuffer)throw new Error("Can't convert to Buffer: browser does not support the necessary types");if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return new Uint8Array(this.toArrayBuffer(s));throw new Error("BufferUtils.toBuffer expected an ArrayBuffer or a view onto one")}toArrayBuffer(s){if(!ArrayBuffer)throw new Error("Can't convert to ArrayBuffer: browser does not support the necessary types");if(s instanceof ArrayBuffer)return s;if(ArrayBuffer.isView(s))return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);throw new Error("BufferUtils.toArrayBuffer expected an ArrayBuffer or a view onto one")}base64Encode(s){return this.uint8ViewToBase64(this.toBuffer(s))}base64UrlEncode(s){return this.base64Encode(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}base64Decode(s){if(ArrayBuffer&&E.Config.atob)return this.base64ToArrayBuffer(s);throw new Error("Expected ArrayBuffer to exist and Platform.Config.atob to be configured")}hexEncode(s){return this.toBuffer(s).reduce((o,l)=>o+l.toString(16).padStart(2,"0"),"")}hexDecode(s){if(s.length%2!==0)throw new Error("Can't create a byte array from a hex string of odd length");const r=new Uint8Array(s.length/2);for(let o=0;o<r.length;o++)r[o]=parseInt(s.slice(2*o,2*(o+1)),16);return this.toArrayBuffer(r)}utf8Encode(s){if(E.Config.TextEncoder){const r=new E.Config.TextEncoder().encode(s);return this.toArrayBuffer(r)}else throw new Error("Expected TextEncoder to be configured")}utf8Decode(s){if(!this.isBuffer(s))throw new Error("Expected input of utf8decode to be an arraybuffer or typed array");if(TextDecoder)return new TextDecoder().decode(s);throw new Error("Expected TextDecoder to be configured")}areBuffersEqual(s,r){if(!s||!r)return!1;const o=this.toArrayBuffer(s),l=this.toArrayBuffer(r);if(o.byteLength!=l.byteLength)return!1;const c=new Uint8Array(o),_=new Uint8Array(l);for(var b=0;b<c.length;b++)if(c[b]!=_[b])return!1;return!0}byteLength(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)?s.byteLength:-1}arrayBufferViewToBuffer(s){return this.toArrayBuffer(s)}concat(s){const r=s.reduce((c,_)=>c+_.byteLength,0),o=new Uint8Array(r);let l=0;for(const c of s){const _=this.toBuffer(c);o.set(_,l),l+=_.byteLength}return o.buffer}sha256(s){const r=Gr(this.toBuffer(s));return this.toArrayBuffer(r)}hmacSha256(s,r){const o=hd(this.toBuffer(r),this.toBuffer(s));return this.toArrayBuffer(o)}},Sl=new cd,ud=function(s,r){var o="aes",l=256,c="cbc",_=16;function b(Q){if(Q.algorithm==="aes"&&Q.mode==="cbc"){if(Q.keyLength===128||Q.keyLength===256)return;throw new Error("Unsupported key length "+Q.keyLength+" for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)")}}function C(Q){return Q.replace("_","/").replace("-","+")}function O(Q){return Q instanceof M}class M{constructor(F,pe,me,Re){this.algorithm=F,this.keyLength=pe,this.mode=me,this.key=Re}}class z{static getDefaultParams(F){var pe;if(!F.key)throw new Error("Crypto.getDefaultParams: a key is required");typeof F.key=="string"?pe=r.toArrayBuffer(r.base64Decode(C(F.key))):F.key instanceof ArrayBuffer?pe=F.key:pe=r.toArrayBuffer(F.key);var me=F.algorithm||o,Re=pe.byteLength*8,st=F.mode||c,lt=new M(me,Re,st,pe);if(F.keyLength&&F.keyLength!==lt.keyLength)throw new Error("Crypto.getDefaultParams: a keyLength of "+F.keyLength+" was specified, but the key actually has length "+lt.keyLength);return b(lt),lt}static async generateRandomKey(F){try{return s.getRandomArrayBuffer((F||l)/8)}catch(pe){throw new A("Failed to generate random key: "+pe.message,400,5e4)}}static getCipher(F,pe){var me,Re=O(F)?F:this.getDefaultParams(F);return{cipherParams:Re,cipher:new q(Re,(me=F.iv)!=null?me:null,pe)}}}z.CipherParams=M;class q{constructor(F,pe,me){if(this.logger=me,!crypto.subtle)throw isSecureContext?new Error("Crypto operations are not possible since the browser’s SubtleCrypto class is unavailable (reason unknown)."):new Error("Crypto operations are is not possible since the current environment is a non-secure context and hence the browser’s SubtleCrypto class is not available.");this.algorithm=F.algorithm+"-"+String(F.keyLength)+"-"+F.mode,this.webCryptoAlgorithm=F.algorithm+"-"+F.mode,this.key=r.toArrayBuffer(F.key),this.iv=pe?r.toArrayBuffer(pe):null}concat(F,pe){const me=new ArrayBuffer(F.byteLength+pe.byteLength),Re=new DataView(me),st=new DataView(r.toArrayBuffer(F));for(let _t=0;_t<st.byteLength;_t++)Re.setInt8(_t,st.getInt8(_t));const lt=new DataView(r.toArrayBuffer(pe));for(let _t=0;_t<lt.byteLength;_t++)Re.setInt8(st.byteLength+_t,lt.getInt8(_t));return me}async encrypt(F){f.logAction(this.logger,f.LOG_MICRO,"CBCCipher.encrypt()","");const pe=await this.getIv(),me=await crypto.subtle.importKey("raw",this.key,this.webCryptoAlgorithm,!1,["encrypt"]),Re=await crypto.subtle.encrypt({name:this.webCryptoAlgorithm,iv:pe},me,F);return this.concat(pe,Re)}async decrypt(F){f.logAction(this.logger,f.LOG_MICRO,"CBCCipher.decrypt()","");const pe=r.toArrayBuffer(F),me=pe.slice(0,_),Re=pe.slice(_),st=await crypto.subtle.importKey("raw",this.key,this.webCryptoAlgorithm,!1,["decrypt"]);return crypto.subtle.decrypt({name:this.webCryptoAlgorithm,iv:me},st,Re)}async getIv(){if(this.iv){var F=this.iv;return this.iv=null,F}const pe=await s.getRandomArrayBuffer(_);return r.toArrayBuffer(pe)}}return z},bl=(s=>(s[s.REQ_SEND=0]="REQ_SEND",s[s.REQ_RECV=1]="REQ_RECV",s[s.REQ_RECV_POLL=2]="REQ_RECV_POLL",s[s.REQ_RECV_STREAM=3]="REQ_RECV_STREAM",s))(bl||{}),Ti=bl;function wl(){return new A("No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.",400,4e4)}var tr,Cl=(tr=class{constructor(s){this.checksInProgress=null,this.checkConnectivity=void 0,this.supportsAuthHeaders=!1,this.supportsLinkHeaders=!1;var r;this.client=s??null;const o=(s==null?void 0:s.options.connectivityCheckUrl)||J.connectivityCheckUrl,l=(r=s==null?void 0:s.options.connectivityCheckParams)!=null?r:null,c=!(s!=null&&s.options.connectivityCheckUrl),_=L(L({},Cl.bundledRequestImplementations),s==null?void 0:s._additionalHTTPRequestImplementations),b=_.XHRRequest,C=_.FetchRequest,O=!!(b||C);if(!O)throw wl();E.Config.xhrSupported&&b?(this.supportsAuthHeaders=!0,this.Request=async function(M,z,q,Q,F){return new Promise(pe=>{var me;const Re=b.createRequest(z,q,Q,F,Ti.REQ_SEND,(me=s&&s.options.timeouts)!=null?me:null,this.logger,M);Re.once("complete",(st,lt,_t,De,si)=>pe({error:st,body:lt,headers:_t,unpacked:De,statusCode:si})),Re.exec()})},s!=null&&s.options.disableConnectivityCheck?this.checkConnectivity=async function(){return!0}:this.checkConnectivity=async function(){var M;f.logAction(this.logger,f.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Sending; "+o);const z=await this.doUri(ie.Get,o,null,null,l);let q=!1;return c?q=!z.error&&((M=z.body)==null?void 0:M.replace(/\n/,""))=="yes":q=!z.error&&ye(z.statusCode),f.logAction(this.logger,f.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Result: "+q),q}):E.Config.fetchSupported&&C?(this.supportsAuthHeaders=!0,this.Request=async(M,z,q,Q,F)=>C(M,s??null,z,q,Q,F),s!=null&&s.options.disableConnectivityCheck?this.checkConnectivity=async function(){return!0}:this.checkConnectivity=async function(){var M;f.logAction(this.logger,f.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Sending; "+o);const z=await this.doUri(ie.Get,o,null,null,null),q=!z.error&&((M=z.body)==null?void 0:M.replace(/\n/,""))=="yes";return f.logAction(this.logger,f.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Result: "+q),q}):this.Request=async()=>({error:O?new Se("no supported HTTP transports available",null,400):wl()})}get logger(){var s,r;return(r=(s=this.client)==null?void 0:s.logger)!=null?r:f.defaultLogger}async doUri(s,r,o,l,c){return this.Request?this.Request(s,r,o,c,l):{error:new Se("Request invoked before assigned to",null,500)}}shouldFallback(s){const r=s.statusCode;return r===408&&!s.code||r===400&&!s.code||r>=500&&r<=504}},tr.methods=[ie.Get,ie.Delete,ie.Post,ie.Put,ie.Patch],tr.methodsWithoutBody=[ie.Get,ie.Delete],tr.methodsWithBody=[ie.Post,ie.Put,ie.Patch],tr),xl=Cl,As="ablyjs-storage-test",Ms=typeof Ki<"u"?Ki:typeof window<"u"?window:self,dd=class{constructor(){try{Ms.sessionStorage.setItem(As,As),Ms.sessionStorage.removeItem(As),this.sessionSupported=!0}catch{this.sessionSupported=!1}try{Ms.localStorage.setItem(As,As),Ms.localStorage.removeItem(As),this.localSupported=!0}catch{this.localSupported=!1}}get(s){return this._get(s,!1)}getSession(s){return this._get(s,!0)}remove(s){return this._remove(s,!1)}removeSession(s){return this._remove(s,!0)}set(s,r,o){return this._set(s,r,o,!1)}setSession(s,r,o){return this._set(s,r,o,!0)}_set(s,r,o,l){const c={value:r};return o&&(c.expires=Date.now()+o),this.storageInterface(l).setItem(s,JSON.stringify(c))}_get(s,r){if(r&&!this.sessionSupported)throw new Error("Session Storage not supported");if(!r&&!this.localSupported)throw new Error("Local Storage not supported");const o=this.storageInterface(r).getItem(s);if(!o)return null;const l=JSON.parse(o);return l.expires&&l.expires<Date.now()?(this.storageInterface(r).removeItem(s),null):l.value}_remove(s,r){return this.storageInterface(r).removeItem(s)}storageInterface(s){return s?Ms.sessionStorage:Ms.localStorage}},kl=new dd,Et=Oi(),fd=typeof EdgeRuntime=="string";typeof Window>"u"&&typeof WorkerGlobalScope>"u"&&!fd&&console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");function _d(){const s=Et.location;return!Et.WebSocket||!s||!s.origin||s.origin.indexOf("http")>-1}function gd(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}var pd=Et.navigator&&Et.navigator.userAgent.toString(),md=Et.location&&Et.location.href,vd={agent:"browser",logTimestamps:!0,userAgent:pd,currentUrl:md,binaryType:"arraybuffer",WebSocket:Et.WebSocket,fetchSupported:!!Et.fetch,xhrSupported:Et.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,allowComet:_d(),useProtocolHeartbeats:!0,supportsBinary:!!Et.TextDecoder,preferBinary:!1,ArrayBuffer:Et.ArrayBuffer,atob:Et.atob,nextTick:typeof Et.queueMicrotask=="function"?s=>Et.queueMicrotask(s):s=>Promise.resolve().then(s),addEventListener:Et.addEventListener,inspect:JSON.stringify,stringByteSize:function(s){return Et.TextDecoder&&new Et.TextEncoder().encode(s).length||s.length},TextEncoder:Et.TextEncoder,TextDecoder:Et.TextDecoder,getRandomArrayBuffer:async function(s){const r=new Uint8Array(s);return Et.crypto.getRandomValues(r),r.buffer},isWebworker:gd(),push:{platform:"browser",formFactor:"desktop",storage:kl}},El=vd;function yd(s){const r=[80015,80017,80030];return s.code?Fe.isTokenErr(s)?!1:r.includes(s.code)?!0:s.code>=4e4&&s.code<5e4:!1}function Fn(s){return yd(s)?[ei({action:ue.ERROR,error:s})]:[ei({action:ue.DISCONNECTED,error:s})]}var Sd=class extends Rs{constructor(s,r,o){super(s,r,o,!0),this.onAuthUpdated=l=>{this.authParams={access_token:l.token}},this.stream="stream"in o?o.stream:!0,this.sendRequest=null,this.recvRequest=null,this.pendingCallback=null,this.pendingItems=null}connect(){f.logAction(this.logger,f.LOG_MINOR,"CometTransport.connect()","starting"),Rs.prototype.connect.call(this);const s=this.params,r=s.options,o=s.host||r.primaryDomain,l=J.getPort(r),c=r.tls?"https://":"http://";this.baseUri=c+o+":"+l+"/comet/";const _=this.baseUri+"connect";f.logAction(this.logger,f.LOG_MINOR,"CometTransport.connect()","uri: "+_),Vt(this.auth.getAuthParams(),(b,C)=>{if(b){this.disconnect(b);return}if(this.isDisposed)return;this.authParams=C;const O=this.params.getConnectParams(C);"stream"in O&&(this.stream=O.stream),f.logAction(this.logger,f.LOG_MINOR,"CometTransport.connect()","connectParams:"+vi(O));let M=!1;const z=this.recvRequest=this.createRequest(_,null,O,null,this.stream?Ti.REQ_RECV_STREAM:Ti.REQ_RECV);z.on("data",q=>{this.recvRequest&&(M||(M=!0,this.emit("preconnect")),this.onData(q))}),z.on("complete",q=>{if(this.recvRequest||(q=q||new A("Request cancelled",80003,400)),this.recvRequest=null,!M&&!q&&(M=!0,this.emit("preconnect")),this.onActivity(),q){q.code?this.onData(Fn(q)):this.disconnect(q);return}E.Config.nextTick(()=>{this.recv()})}),z.exec()})}requestClose(){f.logAction(this.logger,f.LOG_MINOR,"CometTransport.requestClose()"),this._requestCloseOrDisconnect(!0)}requestDisconnect(){f.logAction(this.logger,f.LOG_MINOR,"CometTransport.requestDisconnect()"),this._requestCloseOrDisconnect(!1)}_requestCloseOrDisconnect(s){const r=s?this.closeUri:this.disconnectUri;if(r){const o=this.createRequest(r,null,this.authParams,null,Ti.REQ_SEND);o.on("complete",l=>{l&&(f.logAction(this.logger,f.LOG_ERROR,"CometTransport.request"+(s?"Close()":"Disconnect()"),"request returned err = "+it(l)),this.finish("disconnected",l))}),o.exec()}}dispose(){f.logAction(this.logger,f.LOG_MINOR,"CometTransport.dispose()",""),this.isDisposed||(this.isDisposed=!0,this.recvRequest&&(f.logAction(this.logger,f.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null),this.finish("disconnected",as.disconnected()),E.Config.nextTick(()=>{this.emit("disposed")}))}onConnect(s){var r;if(this.isDisposed)return;const o=(r=s.connectionDetails)==null?void 0:r.connectionKey;Rs.prototype.onConnect.call(this,s);const l=this.baseUri+o;f.logAction(this.logger,f.LOG_MICRO,"CometTransport.onConnect()","baseUri = "+l),this.sendUri=l+"/send",this.recvUri=l+"/recv",this.closeUri=l+"/close",this.disconnectUri=l+"/disconnect"}send(s){if(this.sendRequest){this.pendingItems=this.pendingItems||[],this.pendingItems.push(s);return}const r=this.pendingItems||[];r.push(s),this.pendingItems=null,this.sendItems(r)}sendAnyPending(){const s=this.pendingItems;s&&(this.pendingItems=null,this.sendItems(s))}sendItems(s){const r=this.sendRequest=this.createRequest(this.sendUri,null,this.authParams,this.encodeRequest(s),Ti.REQ_SEND);r.on("complete",(o,l)=>{if(o&&f.logAction(this.logger,f.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+it(o)),this.sendRequest=null,o){o.code?this.onData(Fn(o)):this.disconnect(o);return}l&&this.onData(l),this.pendingItems&&E.Config.nextTick(()=>{this.sendRequest||this.sendAnyPending()})}),r.exec()}recv(){if(this.recvRequest||!this.isConnected)return;const s=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,this.stream?Ti.REQ_RECV_STREAM:Ti.REQ_RECV_POLL);s.on("data",r=>{this.onData(r)}),s.on("complete",r=>{if(this.recvRequest=null,this.onActivity(),r){r.code?this.onData(Fn(r)):this.disconnect(r);return}E.Config.nextTick(()=>{this.recv()})}),s.exec()}onData(s){try{const r=this.decodeResponse(s);if(r&&r.length)for(let o=0;o<r.length;o++)this.onProtocolMessage(En(r[o],this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin))}catch(r){f.logAction(this.logger,f.LOG_ERROR,"CometTransport.onData()","Unexpected exception handing channel event: "+r.stack)}}encodeRequest(s){return JSON.stringify(s)}decodeResponse(s){return typeof s=="string"?JSON.parse(s):s}},bd=Sd;function wd(s,r){return Wi(_i(r)).includes("x-ably-errorcode")}function Cd(s,r){if(wd(s,r))return s.error&&A.fromValues(s.error)}var xd=function(){},kd=0,Rl={};function Ed(s,r){return s.getResponseHeader&&s.getResponseHeader(r)}function Rd(s){return s.getResponseHeader&&(s.getResponseHeader("transfer-encoding")||!s.getResponseHeader("content-length"))}function Ad(s){const r=s.getAllResponseHeaders().trim().split(`\r
13
+ `),o={};for(let l=0;l<r.length;l++){const c=r[l].split(":").map(_=>_.trim());o[c[0].toLowerCase()]=c[1]}return o}var Md=class Yh extends qe{constructor(r,o,l,c,_,b,C,O){super(C),l=l||{},l.rnd=Ui(),this.uri=r+vi(l),this.headers=o||{},this.body=c,this.method=O?O.toUpperCase():je(c)?"GET":"POST",this.requestMode=_,this.timeouts=b,this.timedOut=!1,this.requestComplete=!1,this.id=String(++kd),Rl[this.id]=this}static createRequest(r,o,l,c,_,b,C,O){const M=b||J.TIMEOUTS;return new Yh(r,o,ct(l),c,_,M,C,O)}complete(r,o,l,c,_){this.requestComplete||(this.requestComplete=!0,!r&&o&&this.emit("data",o),this.emit("complete",r,o,l,c,_),this.dispose())}abort(){this.dispose()}exec(){let r=this.headers;const o=this.requestMode==Ti.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout,l=this.timer=setTimeout(()=>{this.timedOut=!0,_.abort()},o),c=this.method,_=this.xhr=new XMLHttpRequest,b=r.accept;let C=this.body,O="text";b?b.indexOf("application/x-msgpack")===0&&(O="arraybuffer"):r.accept="application/json",C&&(r["content-type"]||(r["content-type"]="application/json")).indexOf("application/json")>-1&&typeof C!="string"&&(C=JSON.stringify(C)),_.open(c,this.uri,!0),_.responseType=O,"authorization"in r&&(_.withCredentials=!0);for(const De in r)_.setRequestHeader(De,r[De]);const M=(De,si,jt,nr)=>{var Os;let jn=si+" (event type: "+De.type+")";(Os=this==null?void 0:this.xhr)!=null&&Os.statusText&&(jn+=", current statusText is "+this.xhr.statusText),f.logAction(this.logger,f.LOG_ERROR,"Request.on"+De.type+"()",jn),this.complete(new Se(jn,jt,nr))};_.onerror=De=>{M(De,"XHR error occurred",null,400)},_.onabort=De=>{this.timedOut?M(De,"Request aborted due to request timeout expiring",null,408):M(De,"Request cancelled",null,400)},_.ontimeout=De=>{M(De,"Request timed out",null,408)};let z,q,Q,F=0,pe=!1;const me=()=>{if(clearTimeout(l),Q=q<400,q==204){this.complete(null,null,null,null,q);return}z=this.requestMode==Ti.REQ_RECV_STREAM&&Q&&Rd(_)},Re=()=>{let De;try{const jt=Ed(_,"content-type");if(jt?jt.indexOf("application/json")>=0:_.responseType=="text"){const Os=_.responseType==="arraybuffer"?E.BufferUtils.utf8Decode(_.response):String(_.responseText);Os.length?De=JSON.parse(Os):De=Os,pe=!0}else De=_.response;De.response!==void 0?(q=De.statusCode,Q=q<400,r=De.headers,De=De.response):r=Ad(_)}catch(jt){this.complete(new Se("Malformed response body from server: "+jt.message,null,400));return}if(Q||Array.isArray(De)){this.complete(null,De,r,pe,q);return}let si=Cd(De,r);si||(si=new Se("Error response received from server: "+q+" body was: "+E.Config.inspect(De),null,q)),this.complete(si,De,r,pe,q)};function st(){const De=_.responseText,si=De.length-1;let jt,nr;for(;F<si&&(jt=De.indexOf(`
14
+ `,F))>-1;)nr=De.slice(F,jt),F=jt+1,lt(nr)}const lt=De=>{try{De=JSON.parse(De)}catch(si){this.complete(new Se("Malformed response body from server: "+si.message,null,400));return}this.emit("data",De)},_t=()=>{st(),this.streamComplete=!0,E.Config.nextTick(()=>{this.complete()})};_.onreadystatechange=()=>{const De=_.readyState;De<3||_.status!==0&&(q===void 0&&(q=_.status,me()),De==3&&z?st():De==4&&(z?_t():Re()))},_.send(C)}dispose(){const r=this.xhr;if(r){r.onreadystatechange=r.onerror=r.onabort=r.ontimeout=xd,this.xhr=null;const o=this.timer;o&&(clearTimeout(o),this.timer=null),this.requestComplete||r.abort()}delete Rl[this.id]}},Al=Md,Ml=ti.XhrPolling,Od=class extends bd{constructor(s,r,o){super(s,r,o),this.shortName=Ml,o.stream=!1,this.shortName=Ml}static isAvailable(){return!!(E.Config.xhrSupported&&E.Config.allowComet)}toString(){return"XHRPollingTransport; uri="+this.baseUri+"; isConnected="+this.isConnected}createRequest(s,r,o,l,c){return Al.createRequest(s,r,o,l,c,this.timeouts,this.logger)}},Td=Od,Pd=["xhr_polling"],Ld={order:Pd,bundledImplementations:{web_socket:pl,xhr_polling:Td}},Bd=Ld,Id={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[ti.XhrPolling,ti.WebSocket]},Dd=Id;function Nd(s){if(s===void 0)return"undefined";let r,o;if(s instanceof ArrayBuffer?(o="ArrayBuffer",r=new DataView(s)):s instanceof DataView&&(o="DataView",r=s),!r)return JSON.stringify(s);const l=[];for(let c=0;c<s.byteLength;c++){if(c>20){l.push("...");break}let _=r.getUint8(c).toString(16);_.length===1&&(_="0"+_),l.push(_)}return"<"+o+" "+l.join(" ")+">"}function ir(s,r,o){const c=new TextEncoder().encode(o);for(let _=0;_<c.length;_++)s.setUint8(r+_,c[_])}function Ol(s,r,o){return new TextDecoder().decode(s.buffer.slice(r,r+o))}function zn(s){return new TextEncoder().encode(s).length}function Hd(s,r){const o=rr(s,r);if(o===0)return;const l=new ArrayBuffer(o),c=new DataView(l);return sr(s,c,0,r),l}var qn=65536*65536,Tl=1/qn;function Ud(s,r){return r=r||0,s.getInt32(r)*qn+s.getUint32(r+4)}function Wd(s,r){return r=r||0,s.getUint32(r)*qn+s.getUint32(r+4)}function Fd(s,r,o){o<9223372036854776e3?(s.setInt32(r,Math.floor(o*Tl)),s.setInt32(r+4,o&-1)):(s.setUint32(r,2147483647),s.setUint32(r+4,2147483647))}function zd(s,r,o){o<18446744073709552e3?(s.setUint32(r,Math.floor(o*Tl)),s.setInt32(r+4,o&-1)):(s.setUint32(r,4294967295),s.setUint32(r+4,4294967295))}var qd=class{constructor(s,r){this.map=o=>{const l={};for(let c=0;c<o;c++){const _=this.parse();l[_]=this.parse()}return l},this.bin=o=>{const l=new ArrayBuffer(o);return new Uint8Array(l).set(new Uint8Array(this.view.buffer,this.offset,o),0),this.offset+=o,l},this.buf=this.bin,this.str=o=>{const l=Ol(this.view,this.offset,o);return this.offset+=o,l},this.array=o=>{const l=new Array(o);for(let c=0;c<o;c++)l[c]=this.parse();return l},this.ext=o=>(this.offset+=o,{type:this.view.getInt8(this.offset),data:this.buf(o)}),this.parse=()=>{const o=this.view.getUint8(this.offset);let l,c;if((o&128)===0)return this.offset++,o;if((o&240)===128)return c=o&15,this.offset++,this.map(c);if((o&240)===144)return c=o&15,this.offset++,this.array(c);if((o&224)===160)return c=o&31,this.offset++,this.str(c);if((o&224)===224)return l=this.view.getInt8(this.offset),this.offset++,l;switch(o){case 192:return this.offset++,null;case 193:this.offset++;return;case 194:return this.offset++,!1;case 195:return this.offset++,!0;case 196:return c=this.view.getUint8(this.offset+1),this.offset+=2,this.bin(c);case 197:return c=this.view.getUint16(this.offset+1),this.offset+=3,this.bin(c);case 198:return c=this.view.getUint32(this.offset+1),this.offset+=5,this.bin(c);case 199:return c=this.view.getUint8(this.offset+1),this.offset+=2,this.ext(c);case 200:return c=this.view.getUint16(this.offset+1),this.offset+=3,this.ext(c);case 201:return c=this.view.getUint32(this.offset+1),this.offset+=5,this.ext(c);case 202:return l=this.view.getFloat32(this.offset+1),this.offset+=5,l;case 203:return l=this.view.getFloat64(this.offset+1),this.offset+=9,l;case 204:return l=this.view.getUint8(this.offset+1),this.offset+=2,l;case 205:return l=this.view.getUint16(this.offset+1),this.offset+=3,l;case 206:return l=this.view.getUint32(this.offset+1),this.offset+=5,l;case 207:return l=Wd(this.view,this.offset+1),this.offset+=9,l;case 208:return l=this.view.getInt8(this.offset+1),this.offset+=2,l;case 209:return l=this.view.getInt16(this.offset+1),this.offset+=3,l;case 210:return l=this.view.getInt32(this.offset+1),this.offset+=5,l;case 211:return l=Ud(this.view,this.offset+1),this.offset+=9,l;case 212:return c=1,this.offset++,this.ext(c);case 213:return c=2,this.offset++,this.ext(c);case 214:return c=4,this.offset++,this.ext(c);case 215:return c=8,this.offset++,this.ext(c);case 216:return c=16,this.offset++,this.ext(c);case 217:return c=this.view.getUint8(this.offset+1),this.offset+=2,this.str(c);case 218:return c=this.view.getUint16(this.offset+1),this.offset+=3,this.str(c);case 219:return c=this.view.getUint32(this.offset+1),this.offset+=5,this.str(c);case 220:return c=this.view.getUint16(this.offset+1),this.offset+=3,this.array(c);case 221:return c=this.view.getUint32(this.offset+1),this.offset+=5,this.array(c);case 222:return c=this.view.getUint16(this.offset+1),this.offset+=3,this.map(c);case 223:return c=this.view.getUint32(this.offset+1),this.offset+=5,this.map(c)}throw new Error("Unknown type 0x"+o.toString(16))},this.offset=r||0,this.view=s}};function Gd(s){const r=new DataView(s),o=new qd(r),l=o.parse();if(o.offset!==s.byteLength)throw new Error(s.byteLength-o.offset+" trailing bytes");return l}function Pl(s,r){return Object.keys(s).filter(function(o){const l=s[o],c=typeof l;return(!r||l!=null)&&(c!=="function"||!!l.toJSON)})}function sr(s,r,o,l){const c=typeof s;if(typeof s=="string"){const _=zn(s);if(_<32)return r.setUint8(o,_|160),ir(r,o+1,s),1+_;if(_<256)return r.setUint8(o,217),r.setUint8(o+1,_),ir(r,o+2,s),2+_;if(_<65536)return r.setUint8(o,218),r.setUint16(o+1,_),ir(r,o+3,s),3+_;if(_<4294967296)return r.setUint8(o,219),r.setUint32(o+1,_),ir(r,o+5,s),5+_}if(ArrayBuffer.isView&&ArrayBuffer.isView(s)&&(s=s.buffer),s instanceof ArrayBuffer){const _=s.byteLength;if(_<256)return r.setUint8(o,196),r.setUint8(o+1,_),new Uint8Array(r.buffer).set(new Uint8Array(s),o+2),2+_;if(_<65536)return r.setUint8(o,197),r.setUint16(o+1,_),new Uint8Array(r.buffer).set(new Uint8Array(s),o+3),3+_;if(_<4294967296)return r.setUint8(o,198),r.setUint32(o+1,_),new Uint8Array(r.buffer).set(new Uint8Array(s),o+5),5+_}if(typeof s=="number"){if(Math.floor(s)!==s)return r.setUint8(o,203),r.setFloat64(o+1,s),9;if(s>=0){if(s<128)return r.setUint8(o,s),1;if(s<256)return r.setUint8(o,204),r.setUint8(o+1,s),2;if(s<65536)return r.setUint8(o,205),r.setUint16(o+1,s),3;if(s<4294967296)return r.setUint8(o,206),r.setUint32(o+1,s),5;if(s<18446744073709552e3)return r.setUint8(o,207),zd(r,o+1,s),9;throw new Error("Number too big 0x"+s.toString(16))}if(s>=-32)return r.setInt8(o,s),1;if(s>=-128)return r.setUint8(o,208),r.setInt8(o+1,s),2;if(s>=-32768)return r.setUint8(o,209),r.setInt16(o+1,s),3;if(s>=-2147483648)return r.setUint8(o,210),r.setInt32(o+1,s),5;if(s>=-9223372036854776e3)return r.setUint8(o,211),Fd(r,o+1,s),9;throw new Error("Number too small -0x"+(-s).toString(16).substr(1))}if(c==="undefined")return l?0:(r.setUint8(o,212),r.setUint8(o+1,0),r.setUint8(o+2,0),3);if(s===null)return l?0:(r.setUint8(o,192),1);if(c==="boolean")return r.setUint8(o,s?195:194),1;if(typeof s.toJSON=="function")return sr(s.toJSON(),r,o,l);if(c==="object"){let _,b=0,C;const O=Array.isArray(s);if(O?_=s.length:(C=Pl(s,l),_=C.length),_<16?(r.setUint8(o,_|(O?144:128)),b=1):_<65536?(r.setUint8(o,O?220:222),r.setUint16(o+1,_),b=3):_<4294967296&&(r.setUint8(o,O?221:223),r.setUint32(o+1,_),b=5),O)for(let M=0;M<_;M++)b+=sr(s[M],r,o+b,l);else if(C)for(let M=0;M<_;M++){const z=C[M];b+=sr(z,r,o+b),b+=sr(s[z],r,o+b,l)}return b}if(c==="function")return 0;throw new Error("Unknown type "+c)}function rr(s,r){const o=typeof s;if(o==="string"){const l=zn(s);if(l<32)return 1+l;if(l<256)return 2+l;if(l<65536)return 3+l;if(l<4294967296)return 5+l}if(ArrayBuffer.isView&&ArrayBuffer.isView(s)&&(s=s.buffer),s instanceof ArrayBuffer){const l=s.byteLength;if(l<256)return 2+l;if(l<65536)return 3+l;if(l<4294967296)return 5+l}if(typeof s=="number"){if(Math.floor(s)!==s)return 9;if(s>=0){if(s<128)return 1;if(s<256)return 2;if(s<65536)return 3;if(s<4294967296)return 5;if(s<18446744073709552e3)return 9;throw new Error("Number too big 0x"+s.toString(16))}if(s>=-32)return 1;if(s>=-128)return 2;if(s>=-32768)return 3;if(s>=-2147483648)return 5;if(s>=-9223372036854776e3)return 9;throw new Error("Number too small -0x"+s.toString(16).substr(1))}if(o==="boolean")return 1;if(s===null)return r?0:1;if(s===void 0)return r?0:3;if(typeof s.toJSON=="function")return rr(s.toJSON(),r);if(o==="object"){let l,c=0;if(Array.isArray(s)){l=s.length;for(let _=0;_<l;_++)c+=rr(s[_],r)}else{const _=Pl(s,r);l=_.length;for(let b=0;b<l;b++){const C=_[b];c+=rr(C)+rr(s[C],r)}}if(l<16)return 1+c;if(l<65536)return 3+c;if(l<4294967296)return 5+c;throw new Error("Array or object too long 0x"+l.toString(16))}if(o==="function")return 0;throw new Error("Unknown type "+o)}var Gn={encode:Hd,decode:Gd,inspect:Nd,utf8Write:ir,utf8Read:Ol,utf8ByteCount:zn};function jd(s,r){return!!r.get("x-ably-errorcode")}function $d(s,r){if(jd(s,r))return s.error&&A.fromValues(s.error)}function Vd(s){const r={};return s.forEach((o,l)=>{r[l]=o}),r}async function Kd(s,r,o,l,c,_){const b=new Headers(l||{}),C=s?s.toUpperCase():je(_)?"GET":"POST",O=new AbortController;let M;const z=new Promise(F=>{M=setTimeout(()=>{O.abort(),F({error:new Se("Request timed out",null,408)})},r?r.options.timeouts.httpRequestTimeout:J.TIMEOUTS.httpRequestTimeout)}),q={method:C,headers:b,body:_,signal:O.signal};E.Config.isWebworker||(q.credentials=b.has("authorization")?"include":"same-origin");const Q=(async()=>{try{const F=new URLSearchParams(c||{});F.set("rnd",Ui());const pe=o+"?"+F,me=await Oi().fetch(pe,q);if(clearTimeout(M),me.status==204)return{error:null,statusCode:me.status};const Re=me.headers.get("Content-Type");let st;Re&&Re.indexOf("application/x-msgpack")>-1?st=await me.arrayBuffer():Re&&Re.indexOf("application/json")>-1?st=await me.json():st=await me.text();const lt=!!Re&&Re.indexOf("application/x-msgpack")===-1,_t=Vd(me.headers);return me.ok?{error:null,body:st,headers:_t,unpacked:lt,statusCode:me.status}:{error:$d(st,me.headers)||new Se("Error response received from server: "+me.status+" body was: "+E.Config.inspect(st),null,me.status),body:st,headers:_t,unpacked:lt,statusCode:me.status}}catch(F){return clearTimeout(M),{error:F}}})();return Promise.race([z,Q])}var Yd={XHRRequest:Al,FetchRequest:Kd},Ll=ud(El,Sl);E.Crypto=Ll,E.BufferUtils=Sl,E.Http=xl,E.Config=El,E.Transports=Bd,E.WebStorage=kl;for(const s of[On,Dn])s.Crypto=Ll,s._MsgPack=Gn;xl.bundledRequestImplementations=Yd,f.initLogHandlers(),E.Defaults=Oe(Dd),E.Config.agent&&(E.Defaults.agent+=" "+E.Config.agent);var Jd={ErrorInfo:A,Rest:On,Realtime:Dn,msgpack:Gn,makeProtocolMessageFromDeserialized:ll};if(typeof n.exports=="object"&&typeof i=="object"){var Xd=(s,r,o,l)=>{if(r&&typeof r=="object"||typeof r=="function")for(let c of Object.getOwnPropertyNames(r))!Object.prototype.hasOwnProperty.call(s,c)&&c!==o&&Object.defineProperty(s,c,{get:()=>r[c],enumerable:!(l=Object.getOwnPropertyDescriptor(r,c))||l.enumerable});return s};n.exports=Xd(n.exports,i)}return n.exports})})(Zr)),Zr.exports}var qf=zf();class Gf{constructor(t){Qe(this,"ably",null);Qe(this,"channel",null);Qe(this,"opts");Qe(this,"_connected",!1);Qe(this,"clientId",null);Qe(this,"messageHandlers",[]);Qe(this,"peerJoinedHandlers",[]);Qe(this,"peerLeftHandlers",[]);Qe(this,"errorHandlers",[]);Qe(this,"disconnectHandlers",[]);if(!t.key&&!t.token)throw new Error("Ably API key or token is required");this.opts=t}get connected(){return this._connected}async connect(t,i){this.clientId=`airloom-${i}-${Date.now()}`;const n={clientId:this.clientId,queryTime:!0};this.opts.key?n.key=this.opts.key:n.token=this.opts.token,this.ably=new qf.Realtime(n),await new Promise((d,g)=>{this.ably.connection.once("connected",()=>d()),this.ably.connection.once("failed",v=>{var m;g(new Error(((m=v==null?void 0:v.reason)==null?void 0:m.message)??"Ably connection failed"))})}),this._connected=!0,this.ably.connection.on("disconnected",()=>{this._connected=!1,this.disconnectHandlers.forEach(d=>d())}),this.ably.connection.on("connected",()=>{this._connected=!0,this.channel&&this.channel.presence.get().then(d=>{d.some(v=>v.clientId!==this.clientId)&&this.peerJoinedHandlers.forEach(v=>v())}).catch(()=>{})}),this.ably.connection.on("failed",d=>{var v;this._connected=!1;const g=new Error(((v=d==null?void 0:d.reason)==null?void 0:v.message)??"Ably connection failed");this.errorHandlers.forEach(m=>m(g))}),this.channel=this.ably.channels.get(`airloom:${t}`),this.channel.subscribe("forward",d=>{d.clientId!==this.clientId&&typeof d.data=="string"&&this.messageHandlers.forEach(g=>g(d.data))}),this.channel.presence.subscribe("enter",d=>{d.clientId!==this.clientId&&this.peerJoinedHandlers.forEach(g=>g())}),this.channel.presence.subscribe("leave",d=>{d.clientId!==this.clientId&&this.peerLeftHandlers.forEach(g=>g())}),await this.channel.presence.enter({role:i}),(await this.channel.presence.get()).some(d=>d.clientId!==this.clientId)&&this.peerJoinedHandlers.forEach(d=>d())}send(t){!this.channel||!this._connected||this.channel.publish("forward",t)}onMessage(t){this.messageHandlers.push(t)}onPeerJoined(t){this.peerJoinedHandlers.push(t)}onPeerLeft(t){this.peerLeftHandlers.push(t)}onError(t){this.errorHandlers.push(t)}onDisconnect(t){this.disconnectHandlers.push(t)}close(){var t,i,n;(t=this.channel)==null||t.presence.leave().catch(()=>{}),(i=this.channel)==null||i.detach().catch(()=>{});try{(n=this.ably)==null||n.close()}catch{}this.channel=null,this.ably=null,this._connected=!1}}/**
15
15
  * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
16
16
  * @license MIT
17
17
  *
@@ -22,21 +22,21 @@ Released under the Apache Licence v2.0*/var Ff=Zr.exports,Nl;function zf(){retur
22
22
  * Fabrice Bellard's javascript vt100 for jslinux:
23
23
  * http://bellard.org/jslinux/
24
24
  * Copyright (c) 2011 Fabrice Bellard
25
- */var Jh=Object.defineProperty,jf=Object.getOwnPropertyDescriptor,$f=(e,t)=>{for(var i in t)Jh(e,i,{get:t[i],enumerable:!0})},xt=(e,t,i,n)=>{for(var a=n>1?void 0:n?jf(t,i):t,h=e.length-1,d;h>=0;h--)(d=e[h])&&(a=(n?d(t,i,a):d(a))||a);return n&&a&&Jh(t,i,a),a},de=(e,t)=>(i,n)=>t(i,n,e),Hl="Terminal input",bo={get:()=>Hl,set:e=>Hl=e},Ul="Too much output to announce, navigate to rows manually to read",wo={get:()=>Ul,set:e=>Ul=e};function Vf(e){return e.replace(/\r?\n/g,"\r")}function Kf(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function Yf(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function Jf(e,t,i,n){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");Xh(a,t,i,n)}}function Xh(e,t,i,n){e=Vf(e),e=Kf(e,i.decPrivateModes.bracketedPasteMode&&n.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function Zh(e,t,i){let n=i.getBoundingClientRect(),a=e.clientX-n.left-10,h=e.clientY-n.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${a}px`,t.style.top=`${h}px`,t.style.zIndex="1000",t.focus()}function Wl(e,t,i,n,a){Zh(e,t,i),a&&n.rightClickSelect(e),t.value=n.selectionText,t.select()}function es(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function mn(e,t=0,i=e.length){let n="";for(let a=t;a<i;++a){let h=e[a];h>65535?(h-=65536,n+=String.fromCharCode((h>>10)+55296)+String.fromCharCode(h%1024+56320)):n+=String.fromCharCode(h)}return n}var Xf=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let n=0,a=0;if(this._interim){let h=e.charCodeAt(a++);56320<=h&&h<=57343?t[n++]=(this._interim-55296)*1024+h-56320+65536:(t[n++]=this._interim,t[n++]=h),this._interim=0}for(let h=a;h<i;++h){let d=e.charCodeAt(h);if(55296<=d&&d<=56319){if(++h>=i)return this._interim=d,n;let g=e.charCodeAt(h);56320<=g&&g<=57343?t[n++]=(d-55296)*1024+g-56320+65536:(t[n++]=d,t[n++]=g);continue}d!==65279&&(t[n++]=d)}return n}},Zf=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let n=0,a,h,d,g,v=0,p=0;if(this.interim[0]){let B=!1,L=this.interim[0];L&=(L&224)===192?31:(L&240)===224?15:7;let P=0,U;for(;(U=this.interim[++P]&63)&&P<4;)L<<=6,L|=U;let Z=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,_e=Z-P;for(;p<_e;){if(p>=i)return 0;if(U=e[p++],(U&192)!==128){p--,B=!0;break}else this.interim[P++]=U,L<<=6,L|=U&63}B||(Z===2?L<128?p--:t[n++]=L:Z===3?L<2048||L>=55296&&L<=57343||L===65279||(t[n++]=L):L<65536||L>1114111||(t[n++]=L)),this.interim.fill(0)}let R=i-4,k=p;for(;k<i;){for(;k<R&&!((a=e[k])&128)&&!((h=e[k+1])&128)&&!((d=e[k+2])&128)&&!((g=e[k+3])&128);)t[n++]=a,t[n++]=h,t[n++]=d,t[n++]=g,k+=4;if(a=e[k++],a<128)t[n++]=a;else if((a&224)===192){if(k>=i)return this.interim[0]=a,n;if(h=e[k++],(h&192)!==128){k--;continue}if(v=(a&31)<<6|h&63,v<128){k--;continue}t[n++]=v}else if((a&240)===224){if(k>=i)return this.interim[0]=a,n;if(h=e[k++],(h&192)!==128){k--;continue}if(k>=i)return this.interim[0]=a,this.interim[1]=h,n;if(d=e[k++],(d&192)!==128){k--;continue}if(v=(a&15)<<12|(h&63)<<6|d&63,v<2048||v>=55296&&v<=57343||v===65279)continue;t[n++]=v}else if((a&248)===240){if(k>=i)return this.interim[0]=a,n;if(h=e[k++],(h&192)!==128){k--;continue}if(k>=i)return this.interim[0]=a,this.interim[1]=h,n;if(d=e[k++],(d&192)!==128){k--;continue}if(k>=i)return this.interim[0]=a,this.interim[1]=h,this.interim[2]=d,n;if(g=e[k++],(g&192)!==128){k--;continue}if(v=(a&7)<<18|(h&63)<<12|(d&63)<<6|g&63,v<65536||v>1114111)continue;t[n++]=v}}return n}},Qh="",ts=" ",Or=class ec{constructor(){this.fg=0,this.bg=0,this.extended=new ln}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 ec;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}},ln=class tc{constructor(t=0,i=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=i}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 tc(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},di=class ic extends Or{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new ln,this.combinedData=""}static fromCharData(t){let i=new ic;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?es(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 i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let n=t[1].charCodeAt(0);if(55296<=n&&n<=56319){let a=t[1].charCodeAt(1);56320<=a&&a<=57343?this.content=(n-55296)*1024+a-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Fl="di$target",Co="di$dependencies",Yn=new Map;function Qf(e){return e[Co]||[]}function Ut(e){if(Yn.has(e))return Yn.get(e);let t=function(i,n,a){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");e_(t,i,a)};return t._id=e,Yn.set(e,t),t}function e_(e,t,i){t[Fl]===t?t[Co].push({id:e,index:i}):(t[Co]=[{id:e,index:i}],t[Fl]=t)}var Xt=Ut("BufferService"),sc=Ut("CoreMouseService"),ps=Ut("CoreService"),t_=Ut("CharsetService"),ga=Ut("InstantiationService"),rc=Ut("LogService"),Zt=Ut("OptionsService"),nc=Ut("OscLinkService"),i_=Ut("UnicodeService"),Tr=Ut("DecorationService"),xo=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){var R;let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let n=[],a=this._optionsService.rawOptions.linkHandler,h=new di,d=i.getTrimmedLength(),g=-1,v=-1,p=!1;for(let k=0;k<d;k++)if(!(v===-1&&!i.hasContent(k))){if(i.loadCell(k,h),h.hasExtendedAttrs()&&h.extended.urlId)if(v===-1){v=k,g=h.extended.urlId;continue}else p=h.extended.urlId!==g;else v!==-1&&(p=!0);if(p||v!==-1&&k===d-1){let B=(R=this._oscLinkService.getLinkData(g))==null?void 0:R.uri;if(B){let L={start:{x:v+1,y:e},end:{x:k+(!p&&k===d-1?1:0),y:e}},P=!1;if(!(a!=null&&a.allowNonHttpProtocols))try{let U=new URL(B);["http:","https:"].includes(U.protocol)||(P=!0)}catch{P=!0}P||n.push({text:B,range:L,activate:(U,Z)=>a?a.activate(U,Z,L):s_(U,Z),hover:(U,Z)=>{var _e;return(_e=a==null?void 0:a.hover)==null?void 0:_e.call(a,U,Z,L)},leave:(U,Z)=>{var _e;return(_e=a==null?void 0:a.leave)==null?void 0:_e.call(a,U,Z,L)}})}p=!1,h.hasExtendedAttrs()&&h.extended.urlId?(v=k,g=h.extended.urlId):(v=-1,g=-1)}}t(n)}};xo=xt([de(0,Xt),de(1,Zt),de(2,nc)],xo);function s_(e,t){if(confirm(`Do you want to navigate to ${t}?
25
+ */var Jh=Object.defineProperty,jf=Object.getOwnPropertyDescriptor,$f=(e,t)=>{for(var i in t)Jh(e,i,{get:t[i],enumerable:!0})},xt=(e,t,i,n)=>{for(var a=n>1?void 0:n?jf(t,i):t,h=e.length-1,d;h>=0;h--)(d=e[h])&&(a=(n?d(t,i,a):d(a))||a);return n&&a&&Jh(t,i,a),a},de=(e,t)=>(i,n)=>t(i,n,e),Hl="Terminal input",bo={get:()=>Hl,set:e=>Hl=e},Ul="Too much output to announce, navigate to rows manually to read",wo={get:()=>Ul,set:e=>Ul=e};function Vf(e){return e.replace(/\r?\n/g,"\r")}function Kf(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function Yf(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function Jf(e,t,i,n){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");Xh(a,t,i,n)}}function Xh(e,t,i,n){e=Vf(e),e=Kf(e,i.decPrivateModes.bracketedPasteMode&&n.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function Zh(e,t,i){let n=i.getBoundingClientRect(),a=e.clientX-n.left-10,h=e.clientY-n.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${a}px`,t.style.top=`${h}px`,t.style.zIndex="1000",t.focus()}function Wl(e,t,i,n,a){Zh(e,t,i),a&&n.rightClickSelect(e),t.value=n.selectionText,t.select()}function es(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function mn(e,t=0,i=e.length){let n="";for(let a=t;a<i;++a){let h=e[a];h>65535?(h-=65536,n+=String.fromCharCode((h>>10)+55296)+String.fromCharCode(h%1024+56320)):n+=String.fromCharCode(h)}return n}var Xf=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let n=0,a=0;if(this._interim){let h=e.charCodeAt(a++);56320<=h&&h<=57343?t[n++]=(this._interim-55296)*1024+h-56320+65536:(t[n++]=this._interim,t[n++]=h),this._interim=0}for(let h=a;h<i;++h){let d=e.charCodeAt(h);if(55296<=d&&d<=56319){if(++h>=i)return this._interim=d,n;let g=e.charCodeAt(h);56320<=g&&g<=57343?t[n++]=(d-55296)*1024+g-56320+65536:(t[n++]=d,t[n++]=g);continue}d!==65279&&(t[n++]=d)}return n}},Zf=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let n=0,a,h,d,g,v=0,m=0;if(this.interim[0]){let B=!1,L=this.interim[0];L&=(L&224)===192?31:(L&240)===224?15:7;let P=0,U;for(;(U=this.interim[++P]&63)&&P<4;)L<<=6,L|=U;let Z=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,_e=Z-P;for(;m<_e;){if(m>=i)return 0;if(U=e[m++],(U&192)!==128){m--,B=!0;break}else this.interim[P++]=U,L<<=6,L|=U&63}B||(Z===2?L<128?m--:t[n++]=L:Z===3?L<2048||L>=55296&&L<=57343||L===65279||(t[n++]=L):L<65536||L>1114111||(t[n++]=L)),this.interim.fill(0)}let R=i-4,k=m;for(;k<i;){for(;k<R&&!((a=e[k])&128)&&!((h=e[k+1])&128)&&!((d=e[k+2])&128)&&!((g=e[k+3])&128);)t[n++]=a,t[n++]=h,t[n++]=d,t[n++]=g,k+=4;if(a=e[k++],a<128)t[n++]=a;else if((a&224)===192){if(k>=i)return this.interim[0]=a,n;if(h=e[k++],(h&192)!==128){k--;continue}if(v=(a&31)<<6|h&63,v<128){k--;continue}t[n++]=v}else if((a&240)===224){if(k>=i)return this.interim[0]=a,n;if(h=e[k++],(h&192)!==128){k--;continue}if(k>=i)return this.interim[0]=a,this.interim[1]=h,n;if(d=e[k++],(d&192)!==128){k--;continue}if(v=(a&15)<<12|(h&63)<<6|d&63,v<2048||v>=55296&&v<=57343||v===65279)continue;t[n++]=v}else if((a&248)===240){if(k>=i)return this.interim[0]=a,n;if(h=e[k++],(h&192)!==128){k--;continue}if(k>=i)return this.interim[0]=a,this.interim[1]=h,n;if(d=e[k++],(d&192)!==128){k--;continue}if(k>=i)return this.interim[0]=a,this.interim[1]=h,this.interim[2]=d,n;if(g=e[k++],(g&192)!==128){k--;continue}if(v=(a&7)<<18|(h&63)<<12|(d&63)<<6|g&63,v<65536||v>1114111)continue;t[n++]=v}}return n}},Qh="",ts=" ",Or=class ec{constructor(){this.fg=0,this.bg=0,this.extended=new ln}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 ec;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}},ln=class tc{constructor(t=0,i=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=i}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 tc(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},di=class ic extends Or{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new ln,this.combinedData=""}static fromCharData(t){let i=new ic;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?es(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 i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let n=t[1].charCodeAt(0);if(55296<=n&&n<=56319){let a=t[1].charCodeAt(1);56320<=a&&a<=57343?this.content=(n-55296)*1024+a-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Fl="di$target",Co="di$dependencies",Yn=new Map;function Qf(e){return e[Co]||[]}function Ut(e){if(Yn.has(e))return Yn.get(e);let t=function(i,n,a){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");e_(t,i,a)};return t._id=e,Yn.set(e,t),t}function e_(e,t,i){t[Fl]===t?t[Co].push({id:e,index:i}):(t[Co]=[{id:e,index:i}],t[Fl]=t)}var Xt=Ut("BufferService"),sc=Ut("CoreMouseService"),ps=Ut("CoreService"),t_=Ut("CharsetService"),ga=Ut("InstantiationService"),rc=Ut("LogService"),Zt=Ut("OptionsService"),nc=Ut("OscLinkService"),i_=Ut("UnicodeService"),Tr=Ut("DecorationService"),xo=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){var R;let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let n=[],a=this._optionsService.rawOptions.linkHandler,h=new di,d=i.getTrimmedLength(),g=-1,v=-1,m=!1;for(let k=0;k<d;k++)if(!(v===-1&&!i.hasContent(k))){if(i.loadCell(k,h),h.hasExtendedAttrs()&&h.extended.urlId)if(v===-1){v=k,g=h.extended.urlId;continue}else m=h.extended.urlId!==g;else v!==-1&&(m=!0);if(m||v!==-1&&k===d-1){let B=(R=this._oscLinkService.getLinkData(g))==null?void 0:R.uri;if(B){let L={start:{x:v+1,y:e},end:{x:k+(!m&&k===d-1?1:0),y:e}},P=!1;if(!(a!=null&&a.allowNonHttpProtocols))try{let U=new URL(B);["http:","https:"].includes(U.protocol)||(P=!0)}catch{P=!0}P||n.push({text:B,range:L,activate:(U,Z)=>a?a.activate(U,Z,L):s_(U,Z),hover:(U,Z)=>{var _e;return(_e=a==null?void 0:a.hover)==null?void 0:_e.call(a,U,Z,L)},leave:(U,Z)=>{var _e;return(_e=a==null?void 0:a.leave)==null?void 0:_e.call(a,U,Z,L)}})}m=!1,h.hasExtendedAttrs()&&h.extended.urlId?(v=k,g=h.extended.urlId):(v=-1,g=-1)}}t(n)}};xo=xt([de(0,Xt),de(1,Zt),de(2,nc)],xo);function s_(e,t){if(confirm(`Do you want to navigate to ${t}?
26
26
 
27
27
  WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var vn=Ut("CharSizeService"),Ii=Ut("CoreBrowserService"),pa=Ut("MouseService"),Di=Ut("RenderService"),r_=Ut("SelectionService"),oc=Ut("CharacterJoinerService"),Ws=Ut("ThemeService"),ac=Ut("LinkProviderService"),n_=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?zl.isErrorNoTelemetry(e)?new zl(e.message+`
28
28
 
29
29
  `+e.stack):new Error(e.message+`
30
30
 
31
- `+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)}},o_=new n_;function en(e){a_(e)||o_.onUnexpectedError(e)}var ko="Canceled";function a_(e){return e instanceof l_?!0:e instanceof Error&&e.name===ko&&e.message===ko}var l_=class extends Error{constructor(){super(ko),this.name=this.message}};function h_(e){return new Error(`Illegal argument: ${e}`)}var zl=class Eo extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Eo)return t;let i=new Eo;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Ro=class lc extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,lc.prototype)}};function ri(e,t=0){return e[e.length-(1+t)]}var c_;(e=>{function t(h){return h<0}e.isLessThan=t;function i(h){return h<=0}e.isLessThanOrEqual=i;function n(h){return h>0}e.isGreaterThan=n;function a(h){return h===0}e.isNeitherLessOrGreaterThan=a,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(c_||(c_={}));function u_(e,t){let i=this,n=!1,a;return function(){return n||(n=!0,t||(a=e.apply(i,arguments))),a}}var hc;(e=>{function t(H){return H&&typeof H=="object"&&typeof H[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function n(){return i}e.empty=n;function*a(H){yield H}e.single=a;function h(H){return t(H)?H:a(H)}e.wrap=h;function d(H){return H||i}e.from=d;function*g(H){for(let W=H.length-1;W>=0;W--)yield H[W]}e.reverse=g;function v(H){return!H||H[Symbol.iterator]().next().done===!0}e.isEmpty=v;function p(H){return H[Symbol.iterator]().next().value}e.first=p;function R(H,W){let E=0;for(let ae of H)if(W(ae,E++))return!0;return!1}e.some=R;function k(H,W){for(let E of H)if(W(E))return E}e.find=k;function*B(H,W){for(let E of H)W(E)&&(yield E)}e.filter=B;function*L(H,W){let E=0;for(let ae of H)yield W(ae,E++)}e.map=L;function*P(H,W){let E=0;for(let ae of H)yield*W(ae,E++)}e.flatMap=P;function*U(...H){for(let W of H)yield*W}e.concat=U;function Z(H,W,E){let ae=E;for(let be of H)ae=W(ae,be);return ae}e.reduce=Z;function*_e(H,W,E=H.length){for(W<0&&(W+=H.length),E<0?E+=H.length:E>H.length&&(E=H.length);W<E;W++)yield H[W]}e.slice=_e;function rt(H,W=Number.POSITIVE_INFINITY){let E=[];if(W===0)return[E,H];let ae=H[Symbol.iterator]();for(let be=0;be<W;be++){let ze=ae.next();if(ze.done)return[E,e.empty()];E.push(ze.value)}return[E,{[Symbol.iterator](){return ae}}]}e.consume=rt;async function Ne(H){let W=[];for await(let E of H)W.push(E);return Promise.resolve(W)}e.asyncToArray=Ne})(hc||(hc={}));function _s(e){if(hc.is(e)){let t=[];for(let i of e)if(i)try{i.dispose()}catch(n){t.push(n)}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 d_(...e){return vt(()=>_s(e))}function vt(e){return{dispose:u_(()=>{e()})}}var cc=class uc{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{_s(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?uc.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)}};cc.DISABLE_DISPOSED_WARNING=!1;var is=cc,Ve=class{constructor(){this._store=new is,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)}};Ve.None=Object.freeze({dispose(){}});var Us=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}},Bi=typeof window=="object"?window:globalThis,Ao=class Mo{constructor(t){this.element=t,this.next=Mo.Undefined,this.prev=Mo.Undefined}};Ao.Undefined=new Ao(void 0);var yt=Ao,ql=class{constructor(){this._first=yt.Undefined,this._last=yt.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===yt.Undefined}clear(){let e=this._first;for(;e!==yt.Undefined;){let t=e.next;e.prev=yt.Undefined,e.next=yt.Undefined,e=t}this._first=yt.Undefined,this._last=yt.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new yt(e);if(this._first===yt.Undefined)this._first=i,this._last=i;else if(t){let a=this._last;this._last=i,i.prev=a,a.next=i}else{let a=this._first;this._first=i,i.next=a,a.prev=i}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(i))}}shift(){if(this._first!==yt.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==yt.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==yt.Undefined&&e.next!==yt.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===yt.Undefined&&e.next===yt.Undefined?(this._first=yt.Undefined,this._last=yt.Undefined):e.next===yt.Undefined?(this._last=this._last.prev,this._last.next=yt.Undefined):e.prev===yt.Undefined&&(this._first=this._first.next,this._first.prev=yt.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==yt.Undefined;)yield e.element,e=e.next}},f_=globalThis.performance&&typeof globalThis.performance.now=="function",__=class dc{static create(t){return new dc(t)}constructor(t){this._now=f_&&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}},Ft;(e=>{e.None=()=>Ve.None;function t(ce,f){return k(ce,()=>{},0,void 0,!0,void 0,f)}e.defer=t;function i(ce){return(f,re=null,oe)=>{let A=!1,Se;return Se=ce(te=>{if(!A)return Se?Se.dispose():A=!0,f.call(re,te)},null,oe),A&&Se.dispose(),Se}}e.once=i;function n(ce,f,re){return p((oe,A=null,Se)=>ce(te=>oe.call(A,f(te)),null,Se),re)}e.map=n;function a(ce,f,re){return p((oe,A=null,Se)=>ce(te=>{f(te),oe.call(A,te)},null,Se),re)}e.forEach=a;function h(ce,f,re){return p((oe,A=null,Se)=>ce(te=>f(te)&&oe.call(A,te),null,Se),re)}e.filter=h;function d(ce){return ce}e.signal=d;function g(...ce){return(f,re=null,oe)=>{let A=d_(...ce.map(Se=>Se(te=>f.call(re,te))));return R(A,oe)}}e.any=g;function v(ce,f,re,oe){let A=re;return n(ce,Se=>(A=f(A,Se),A),oe)}e.reduce=v;function p(ce,f){let re,oe={onWillAddFirstListener(){re=ce(A.fire,A)},onDidRemoveLastListener(){re==null||re.dispose()}},A=new ee(oe);return f==null||f.add(A),A.event}function R(ce,f){return f instanceof Array?f.push(ce):f&&f.add(ce),ce}function k(ce,f,re=100,oe=!1,A=!1,Se,te){let se,ct,zt,Mt=0,ut,je={leakWarningThreshold:Se,onWillAddFirstListener(){se=ce(at=>{Mt++,ct=f(ct,at),oe&&!zt&&(Ae.fire(ct),ct=void 0),ut=()=>{let oi=ct;ct=void 0,zt=void 0,(!oe||Mt>1)&&Ae.fire(oi),Mt=0},typeof re=="number"?(clearTimeout(zt),zt=setTimeout(ut,re)):zt===void 0&&(zt=0,queueMicrotask(ut))})},onWillRemoveListener(){A&&Mt>0&&(ut==null||ut())},onDidRemoveLastListener(){ut=void 0,se.dispose()}},Ae=new ee(je);return te==null||te.add(Ae),Ae.event}e.debounce=k;function B(ce,f=0,re){return e.debounce(ce,(oe,A)=>oe?(oe.push(A),oe):[A],f,void 0,!0,void 0,re)}e.accumulate=B;function L(ce,f=(oe,A)=>oe===A,re){let oe=!0,A;return h(ce,Se=>{let te=oe||!f(Se,A);return oe=!1,A=Se,te},re)}e.latch=L;function P(ce,f,re){return[e.filter(ce,f,re),e.filter(ce,oe=>!f(oe),re)]}e.split=P;function U(ce,f=!1,re=[],oe){let A=re.slice(),Se=ce(ct=>{A?A.push(ct):se.fire(ct)});oe&&oe.add(Se);let te=()=>{A==null||A.forEach(ct=>se.fire(ct)),A=null},se=new ee({onWillAddFirstListener(){Se||(Se=ce(ct=>se.fire(ct)),oe&&oe.add(Se))},onDidAddFirstListener(){A&&(f?setTimeout(te):te())},onDidRemoveLastListener(){Se&&Se.dispose(),Se=null}});return oe&&oe.add(se),se.event}e.buffer=U;function Z(ce,f){return(re,oe,A)=>{let Se=f(new rt);return ce(function(te){let se=Se.evaluate(te);se!==_e&&re.call(oe,se)},void 0,A)}}e.chain=Z;let _e=Symbol("HaltChainable");class rt{constructor(){this.steps=[]}map(f){return this.steps.push(f),this}forEach(f){return this.steps.push(re=>(f(re),re)),this}filter(f){return this.steps.push(re=>f(re)?re:_e),this}reduce(f,re){let oe=re;return this.steps.push(A=>(oe=f(oe,A),oe)),this}latch(f=(re,oe)=>re===oe){let re=!0,oe;return this.steps.push(A=>{let Se=re||!f(A,oe);return re=!1,oe=A,Se?A:_e}),this}evaluate(f){for(let re of this.steps)if(f=re(f),f===_e)break;return f}}function Ne(ce,f,re=oe=>oe){let oe=(...se)=>te.fire(re(...se)),A=()=>ce.on(f,oe),Se=()=>ce.removeListener(f,oe),te=new ee({onWillAddFirstListener:A,onDidRemoveLastListener:Se});return te.event}e.fromNodeEventEmitter=Ne;function H(ce,f,re=oe=>oe){let oe=(...se)=>te.fire(re(...se)),A=()=>ce.addEventListener(f,oe),Se=()=>ce.removeEventListener(f,oe),te=new ee({onWillAddFirstListener:A,onDidRemoveLastListener:Se});return te.event}e.fromDOMEventEmitter=H;function W(ce){return new Promise(f=>i(ce)(f))}e.toPromise=W;function E(ce){let f=new ee;return ce.then(re=>{f.fire(re)},()=>{f.fire(void 0)}).finally(()=>{f.dispose()}),f.event}e.fromPromise=E;function ae(ce,f){return ce(re=>f.fire(re))}e.forward=ae;function be(ce,f,re){return f(re),ce(oe=>f(oe))}e.runAndSubscribe=be;class ze{constructor(f,re){this._observable=f,this._counter=0,this._hasChanged=!1;let oe={onWillAddFirstListener:()=>{f.addObserver(this)},onDidRemoveLastListener:()=>{f.removeObserver(this)}};this.emitter=new ee(oe),re&&re.add(this.emitter)}beginUpdate(f){this._counter++}handlePossibleChange(f){}handleChange(f,re){this._hasChanged=!0}endUpdate(f){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function Be(ce,f){return new ze(ce,f).emitter.event}e.fromObservable=Be;function xe(ce){return(f,re,oe)=>{let A=0,Se=!1,te={beginUpdate(){A++},endUpdate(){A--,A===0&&(ce.reportChanges(),Se&&(Se=!1,f.call(re)))},handlePossibleChange(){},handleChange(){Se=!0}};ce.addObserver(te),ce.reportChanges();let se={dispose(){ce.removeObserver(te)}};return oe instanceof is?oe.add(se):Array.isArray(oe)&&oe.push(se),se}}e.fromObservableLight=xe})(Ft||(Ft={}));var Oo=class To{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${To._idPool++}`,To.all.add(this)}start(t){this._stopWatch=new __,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}}};Oo.all=new Set,Oo._idPool=0;var g_=Oo,p_=-1,fc=class _c{constructor(t,i,n=(_c._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=n,this._warnCountdown=0}dispose(){var t;(t=this._stacks)==null||t.clear()}check(t,i){let n=this.threshold;if(n<=0||i<n)return;this._stacks||(this._stacks=new Map);let a=this._stacks.get(t.value)||0;if(this._stacks.set(t.value,a+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=n*.5;let[h,d]=this.getMostFrequentStack(),g=`[${this.name}] potential listener LEAK detected, having ${i} listeners already. MOST frequent listener (${d}):`;console.warn(g),console.warn(h);let v=new y_(g,h);this._errorHandler(v)}return()=>{let h=this._stacks.get(t.value)||0;this._stacks.set(t.value,h-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,i=0;for(let[n,a]of this._stacks)(!t||i<a)&&(t=[n,a],i=a);return t}};fc._idPool=1;var m_=fc,v_=class gc{constructor(t){this.value=t}static create(){let t=new Error;return new gc(t.stack??"")}print(){console.warn(this.value.split(`
31
+ `+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)}},o_=new n_;function en(e){a_(e)||o_.onUnexpectedError(e)}var ko="Canceled";function a_(e){return e instanceof l_?!0:e instanceof Error&&e.name===ko&&e.message===ko}var l_=class extends Error{constructor(){super(ko),this.name=this.message}};function h_(e){return new Error(`Illegal argument: ${e}`)}var zl=class Eo extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Eo)return t;let i=new Eo;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Ro=class lc extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,lc.prototype)}};function ri(e,t=0){return e[e.length-(1+t)]}var c_;(e=>{function t(h){return h<0}e.isLessThan=t;function i(h){return h<=0}e.isLessThanOrEqual=i;function n(h){return h>0}e.isGreaterThan=n;function a(h){return h===0}e.isNeitherLessOrGreaterThan=a,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(c_||(c_={}));function u_(e,t){let i=this,n=!1,a;return function(){return n||(n=!0,t||(a=e.apply(i,arguments))),a}}var hc;(e=>{function t(H){return H&&typeof H=="object"&&typeof H[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function n(){return i}e.empty=n;function*a(H){yield H}e.single=a;function h(H){return t(H)?H:a(H)}e.wrap=h;function d(H){return H||i}e.from=d;function*g(H){for(let W=H.length-1;W>=0;W--)yield H[W]}e.reverse=g;function v(H){return!H||H[Symbol.iterator]().next().done===!0}e.isEmpty=v;function m(H){return H[Symbol.iterator]().next().value}e.first=m;function R(H,W){let E=0;for(let ae of H)if(W(ae,E++))return!0;return!1}e.some=R;function k(H,W){for(let E of H)if(W(E))return E}e.find=k;function*B(H,W){for(let E of H)W(E)&&(yield E)}e.filter=B;function*L(H,W){let E=0;for(let ae of H)yield W(ae,E++)}e.map=L;function*P(H,W){let E=0;for(let ae of H)yield*W(ae,E++)}e.flatMap=P;function*U(...H){for(let W of H)yield*W}e.concat=U;function Z(H,W,E){let ae=E;for(let be of H)ae=W(ae,be);return ae}e.reduce=Z;function*_e(H,W,E=H.length){for(W<0&&(W+=H.length),E<0?E+=H.length:E>H.length&&(E=H.length);W<E;W++)yield H[W]}e.slice=_e;function rt(H,W=Number.POSITIVE_INFINITY){let E=[];if(W===0)return[E,H];let ae=H[Symbol.iterator]();for(let be=0;be<W;be++){let ze=ae.next();if(ze.done)return[E,e.empty()];E.push(ze.value)}return[E,{[Symbol.iterator](){return ae}}]}e.consume=rt;async function Ne(H){let W=[];for await(let E of H)W.push(E);return Promise.resolve(W)}e.asyncToArray=Ne})(hc||(hc={}));function _s(e){if(hc.is(e)){let t=[];for(let i of e)if(i)try{i.dispose()}catch(n){t.push(n)}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 d_(...e){return vt(()=>_s(e))}function vt(e){return{dispose:u_(()=>{e()})}}var cc=class uc{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{_s(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?uc.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)}};cc.DISABLE_DISPOSED_WARNING=!1;var is=cc,Ve=class{constructor(){this._store=new is,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)}};Ve.None=Object.freeze({dispose(){}});var Us=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}},Bi=typeof window=="object"?window:globalThis,Ao=class Mo{constructor(t){this.element=t,this.next=Mo.Undefined,this.prev=Mo.Undefined}};Ao.Undefined=new Ao(void 0);var yt=Ao,ql=class{constructor(){this._first=yt.Undefined,this._last=yt.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===yt.Undefined}clear(){let e=this._first;for(;e!==yt.Undefined;){let t=e.next;e.prev=yt.Undefined,e.next=yt.Undefined,e=t}this._first=yt.Undefined,this._last=yt.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new yt(e);if(this._first===yt.Undefined)this._first=i,this._last=i;else if(t){let a=this._last;this._last=i,i.prev=a,a.next=i}else{let a=this._first;this._first=i,i.next=a,a.prev=i}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(i))}}shift(){if(this._first!==yt.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==yt.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==yt.Undefined&&e.next!==yt.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===yt.Undefined&&e.next===yt.Undefined?(this._first=yt.Undefined,this._last=yt.Undefined):e.next===yt.Undefined?(this._last=this._last.prev,this._last.next=yt.Undefined):e.prev===yt.Undefined&&(this._first=this._first.next,this._first.prev=yt.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==yt.Undefined;)yield e.element,e=e.next}},f_=globalThis.performance&&typeof globalThis.performance.now=="function",__=class dc{static create(t){return new dc(t)}constructor(t){this._now=f_&&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}},Ft;(e=>{e.None=()=>Ve.None;function t(ce,f){return k(ce,()=>{},0,void 0,!0,void 0,f)}e.defer=t;function i(ce){return(f,re=null,oe)=>{let A=!1,Se;return Se=ce(te=>{if(!A)return Se?Se.dispose():A=!0,f.call(re,te)},null,oe),A&&Se.dispose(),Se}}e.once=i;function n(ce,f,re){return m((oe,A=null,Se)=>ce(te=>oe.call(A,f(te)),null,Se),re)}e.map=n;function a(ce,f,re){return m((oe,A=null,Se)=>ce(te=>{f(te),oe.call(A,te)},null,Se),re)}e.forEach=a;function h(ce,f,re){return m((oe,A=null,Se)=>ce(te=>f(te)&&oe.call(A,te),null,Se),re)}e.filter=h;function d(ce){return ce}e.signal=d;function g(...ce){return(f,re=null,oe)=>{let A=d_(...ce.map(Se=>Se(te=>f.call(re,te))));return R(A,oe)}}e.any=g;function v(ce,f,re,oe){let A=re;return n(ce,Se=>(A=f(A,Se),A),oe)}e.reduce=v;function m(ce,f){let re,oe={onWillAddFirstListener(){re=ce(A.fire,A)},onDidRemoveLastListener(){re==null||re.dispose()}},A=new ee(oe);return f==null||f.add(A),A.event}function R(ce,f){return f instanceof Array?f.push(ce):f&&f.add(ce),ce}function k(ce,f,re=100,oe=!1,A=!1,Se,te){let se,ct,zt,Mt=0,ut,je={leakWarningThreshold:Se,onWillAddFirstListener(){se=ce(at=>{Mt++,ct=f(ct,at),oe&&!zt&&(Ae.fire(ct),ct=void 0),ut=()=>{let oi=ct;ct=void 0,zt=void 0,(!oe||Mt>1)&&Ae.fire(oi),Mt=0},typeof re=="number"?(clearTimeout(zt),zt=setTimeout(ut,re)):zt===void 0&&(zt=0,queueMicrotask(ut))})},onWillRemoveListener(){A&&Mt>0&&(ut==null||ut())},onDidRemoveLastListener(){ut=void 0,se.dispose()}},Ae=new ee(je);return te==null||te.add(Ae),Ae.event}e.debounce=k;function B(ce,f=0,re){return e.debounce(ce,(oe,A)=>oe?(oe.push(A),oe):[A],f,void 0,!0,void 0,re)}e.accumulate=B;function L(ce,f=(oe,A)=>oe===A,re){let oe=!0,A;return h(ce,Se=>{let te=oe||!f(Se,A);return oe=!1,A=Se,te},re)}e.latch=L;function P(ce,f,re){return[e.filter(ce,f,re),e.filter(ce,oe=>!f(oe),re)]}e.split=P;function U(ce,f=!1,re=[],oe){let A=re.slice(),Se=ce(ct=>{A?A.push(ct):se.fire(ct)});oe&&oe.add(Se);let te=()=>{A==null||A.forEach(ct=>se.fire(ct)),A=null},se=new ee({onWillAddFirstListener(){Se||(Se=ce(ct=>se.fire(ct)),oe&&oe.add(Se))},onDidAddFirstListener(){A&&(f?setTimeout(te):te())},onDidRemoveLastListener(){Se&&Se.dispose(),Se=null}});return oe&&oe.add(se),se.event}e.buffer=U;function Z(ce,f){return(re,oe,A)=>{let Se=f(new rt);return ce(function(te){let se=Se.evaluate(te);se!==_e&&re.call(oe,se)},void 0,A)}}e.chain=Z;let _e=Symbol("HaltChainable");class rt{constructor(){this.steps=[]}map(f){return this.steps.push(f),this}forEach(f){return this.steps.push(re=>(f(re),re)),this}filter(f){return this.steps.push(re=>f(re)?re:_e),this}reduce(f,re){let oe=re;return this.steps.push(A=>(oe=f(oe,A),oe)),this}latch(f=(re,oe)=>re===oe){let re=!0,oe;return this.steps.push(A=>{let Se=re||!f(A,oe);return re=!1,oe=A,Se?A:_e}),this}evaluate(f){for(let re of this.steps)if(f=re(f),f===_e)break;return f}}function Ne(ce,f,re=oe=>oe){let oe=(...se)=>te.fire(re(...se)),A=()=>ce.on(f,oe),Se=()=>ce.removeListener(f,oe),te=new ee({onWillAddFirstListener:A,onDidRemoveLastListener:Se});return te.event}e.fromNodeEventEmitter=Ne;function H(ce,f,re=oe=>oe){let oe=(...se)=>te.fire(re(...se)),A=()=>ce.addEventListener(f,oe),Se=()=>ce.removeEventListener(f,oe),te=new ee({onWillAddFirstListener:A,onDidRemoveLastListener:Se});return te.event}e.fromDOMEventEmitter=H;function W(ce){return new Promise(f=>i(ce)(f))}e.toPromise=W;function E(ce){let f=new ee;return ce.then(re=>{f.fire(re)},()=>{f.fire(void 0)}).finally(()=>{f.dispose()}),f.event}e.fromPromise=E;function ae(ce,f){return ce(re=>f.fire(re))}e.forward=ae;function be(ce,f,re){return f(re),ce(oe=>f(oe))}e.runAndSubscribe=be;class ze{constructor(f,re){this._observable=f,this._counter=0,this._hasChanged=!1;let oe={onWillAddFirstListener:()=>{f.addObserver(this)},onDidRemoveLastListener:()=>{f.removeObserver(this)}};this.emitter=new ee(oe),re&&re.add(this.emitter)}beginUpdate(f){this._counter++}handlePossibleChange(f){}handleChange(f,re){this._hasChanged=!0}endUpdate(f){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function Be(ce,f){return new ze(ce,f).emitter.event}e.fromObservable=Be;function xe(ce){return(f,re,oe)=>{let A=0,Se=!1,te={beginUpdate(){A++},endUpdate(){A--,A===0&&(ce.reportChanges(),Se&&(Se=!1,f.call(re)))},handlePossibleChange(){},handleChange(){Se=!0}};ce.addObserver(te),ce.reportChanges();let se={dispose(){ce.removeObserver(te)}};return oe instanceof is?oe.add(se):Array.isArray(oe)&&oe.push(se),se}}e.fromObservableLight=xe})(Ft||(Ft={}));var Oo=class To{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${To._idPool++}`,To.all.add(this)}start(t){this._stopWatch=new __,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}}};Oo.all=new Set,Oo._idPool=0;var g_=Oo,p_=-1,fc=class _c{constructor(t,i,n=(_c._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=n,this._warnCountdown=0}dispose(){var t;(t=this._stacks)==null||t.clear()}check(t,i){let n=this.threshold;if(n<=0||i<n)return;this._stacks||(this._stacks=new Map);let a=this._stacks.get(t.value)||0;if(this._stacks.set(t.value,a+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=n*.5;let[h,d]=this.getMostFrequentStack(),g=`[${this.name}] potential listener LEAK detected, having ${i} listeners already. MOST frequent listener (${d}):`;console.warn(g),console.warn(h);let v=new y_(g,h);this._errorHandler(v)}return()=>{let h=this._stacks.get(t.value)||0;this._stacks.set(t.value,h-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,i=0;for(let[n,a]of this._stacks)(!t||i<a)&&(t=[n,a],i=a);return t}};fc._idPool=1;var m_=fc,v_=class gc{constructor(t){this.value=t}static create(){let t=new Error;return new gc(t.stack??"")}print(){console.warn(this.value.split(`
32
32
  `).slice(2).join(`
33
- `))}},y_=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},S_=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},b_=0,Jn=class{constructor(e){this.value=e,this.id=b_++}},w_=2,C_,ee=class{constructor(e){var t,i,n,a;this._size=0,this._options=e,this._leakageMon=(t=this._options)!=null&&t.leakWarningThreshold?new m_((e==null?void 0:e.onListenerError)??en,((i=this._options)==null?void 0:i.leakWarningThreshold)??p_):void 0,this._perfMon=(n=this._options)!=null&&n._profName?new g_(this._options._profName):void 0,this._deliveryQueue=(a=this._options)==null?void 0:a.deliveryQueue}dispose(){var e,t,i,n;this._disposed||(this._disposed=!0,((e=this._deliveryQueue)==null?void 0:e.current)===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),(i=(t=this._options)==null?void 0:t.onDidRemoveLastListener)==null||i.call(t),(n=this._leakageMon)==null||n.dispose())}get event(){return this._event??(this._event=(e,t,i)=>{var d,g,v,p,R;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let k=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(k);let B=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],L=new S_(`${k}. HINT: Stack shows most frequent listener (${B[1]}-times)`,B[0]);return(((d=this._options)==null?void 0:d.onListenerError)||en)(L),Ve.None}if(this._disposed)return Ve.None;t&&(e=e.bind(t));let n=new Jn(e),a;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(n.stack=v_.create(),a=this._leakageMon.check(n.stack,this._size+1)),this._listeners?this._listeners instanceof Jn?(this._deliveryQueue??(this._deliveryQueue=new x_),this._listeners=[this._listeners,n]):this._listeners.push(n):((v=(g=this._options)==null?void 0:g.onWillAddFirstListener)==null||v.call(g,this),this._listeners=n,(R=(p=this._options)==null?void 0:p.onDidAddFirstListener)==null||R.call(p,this)),this._size++;let h=vt(()=>{a==null||a(),this._removeListener(n)});return i instanceof is?i.add(h):Array.isArray(i)&&i.push(h),h}),this._event}_removeListener(e){var a,h,d,g;if((h=(a=this._options)==null?void 0:a.onWillRemoveListener)==null||h.call(a,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(g=(d=this._options)==null?void 0:d.onDidRemoveLastListener)==null||g.call(d,this),this._size=0;return}let t=this._listeners,i=t.indexOf(e);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--,t[i]=void 0;let n=this._deliveryQueue.current===this;if(this._size*w_<=t.length){let v=0;for(let p=0;p<t.length;p++)t[p]?t[v++]=t[p]:n&&(this._deliveryQueue.end--,v<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=v}}_deliver(e,t){var n;if(!e)return;let i=((n=this._options)==null?void 0:n.onListenerError)||en;if(!i){e.value(t);return}try{e.value(t)}catch(a){i(a)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){var t,i,n,a;if((t=this._deliveryQueue)!=null&&t.current&&(this._deliverQueue(this._deliveryQueue),(i=this._perfMon)==null||i.stop()),(n=this._perfMon)==null||n.start(this._size),this._listeners)if(this._listeners instanceof Jn)this._deliver(this._listeners,e);else{let h=this._deliveryQueue;h.enqueue(this,e,this._listeners.length),this._deliverQueue(h)}(a=this._perfMon)==null||a.stop()}hasListeners(){return this._size>0}},x_=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Po=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new ee,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new ee,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,i){if(this.getZoomLevel(i)===t)return;let n=this.getWindowId(i);this.mapWindowIdToZoomLevel.set(n,t),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,i){this.mapWindowIdToZoomFactor.set(this.getWindowId(i),t)}setFullscreen(t,i){if(this.isFullscreen(i)===t)return;let n=this.getWindowId(i);this.mapWindowIdToFullScreen.set(n,t),this._onDidChangeFullscreen.fire(n)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};Po.INSTANCE=new Po;var ma=Po;function k_(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}ma.INSTANCE.onDidChangeZoomLevel;function E_(e){return ma.INSTANCE.getZoomFactor(e)}ma.INSTANCE.onDidChangeFullscreen;var Fs=typeof navigator=="object"?navigator.userAgent:"",Lo=Fs.indexOf("Firefox")>=0,R_=Fs.indexOf("AppleWebKit")>=0,va=Fs.indexOf("Chrome")>=0,A_=!va&&Fs.indexOf("Safari")>=0;Fs.indexOf("Electron/")>=0;Fs.indexOf("Android")>=0;var Xn=!1;if(typeof Bi.matchMedia=="function"){let e=Bi.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=Bi.matchMedia("(display-mode: fullscreen)");Xn=e.matches,k_(Bi,e,({matches:i})=>{Xn&&t.matches||(Xn=i)})}var Ds="en",Bo=!1,Io=!1,tn=!1,pc=!1,$r,sn=Ds,Gl=Ds,M_,mi,ds=globalThis,Wt,Nh;typeof ds.vscode<"u"&&typeof ds.vscode.process<"u"?Wt=ds.vscode.process:typeof process<"u"&&typeof((Nh=process==null?void 0:process.versions)==null?void 0:Nh.node)=="string"&&(Wt=process);var Hh,O_=typeof((Hh=Wt==null?void 0:Wt.versions)==null?void 0:Hh.electron)=="string",T_=O_&&(Wt==null?void 0:Wt.type)==="renderer",Uh;if(typeof Wt=="object"){Bo=Wt.platform==="win32",Io=Wt.platform==="darwin",tn=Wt.platform==="linux",tn&&Wt.env.SNAP&&Wt.env.SNAP_REVISION,Wt.env.CI||Wt.env.BUILD_ARTIFACTSTAGINGDIRECTORY,$r=Ds,sn=Ds;let e=Wt.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);$r=t.userLocale,Gl=t.osLocale,sn=t.resolvedLanguage||Ds,M_=(Uh=t.languagePack)==null?void 0:Uh.translationsConfigFile}catch{}pc=!0}else typeof navigator=="object"&&!T_?(mi=navigator.userAgent,Bo=mi.indexOf("Windows")>=0,Io=mi.indexOf("Macintosh")>=0,(mi.indexOf("Macintosh")>=0||mi.indexOf("iPad")>=0||mi.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,tn=mi.indexOf("Linux")>=0,(mi==null?void 0:mi.indexOf("Mobi"))>=0,sn=globalThis._VSCODE_NLS_LANGUAGE||Ds,$r=navigator.language.toLowerCase(),Gl=$r):console.error("Unable to resolve platform.");var mc=Bo,Ai=Io,P_=tn,jl=pc,Mi=mi,Xi=sn,L_;(e=>{function t(){return Xi}e.value=t;function i(){return Xi.length===2?Xi==="en":Xi.length>=3?Xi[0]==="e"&&Xi[1]==="n"&&Xi[2]==="-":!1}e.isDefaultVariant=i;function n(){return Xi==="en"}e.isDefault=n})(L_||(L_={}));var B_=typeof ds.postMessage=="function"&&!ds.importScripts;(()=>{if(B_){let e=[];ds.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let n=0,a=e.length;n<a;n++){let h=e[n];if(h.id===i.data.vscodeScheduleAsyncWork){e.splice(n,1),h.callback();return}}});let t=0;return i=>{let n=++t;e.push({id:n,callback:i}),ds.postMessage({vscodeScheduleAsyncWork:n},"*")}}return e=>setTimeout(e)})();var I_=!!(Mi&&Mi.indexOf("Chrome")>=0);Mi&&Mi.indexOf("Firefox")>=0;!I_&&Mi&&Mi.indexOf("Safari")>=0;Mi&&Mi.indexOf("Edg/")>=0;Mi&&Mi.indexOf("Android")>=0;var Ts=typeof navigator=="object"?navigator:{};jl||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ts&&Ts.clipboard&&Ts.clipboard.writeText,jl||Ts&&Ts.clipboard&&Ts.clipboard.readText;var ya=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}},Zn=new ya,$l=new ya,Vl=new ya,D_=new Array(230),vc;(e=>{function t(g){return Zn.keyCodeToStr(g)}e.toString=t;function i(g){return Zn.strToKeyCode(g)}e.fromString=i;function n(g){return $l.keyCodeToStr(g)}e.toUserSettingsUS=n;function a(g){return Vl.keyCodeToStr(g)}e.toUserSettingsGeneral=a;function h(g){return $l.strToKeyCode(g)||Vl.strToKeyCode(g)}e.fromUserSettings=h;function d(g){if(g>=98&&g<=113)return null;switch(g){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return Zn.keyCodeToStr(g)}e.toElectronAccelerator=d})(vc||(vc={}));var N_=class yc{constructor(t,i,n,a,h){this.ctrlKey=t,this.shiftKey=i,this.altKey=n,this.metaKey=a,this.keyCode=h}equals(t){return t instanceof yc&&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",i=this.shiftKey?"1":"0",n=this.altKey?"1":"0",a=this.metaKey?"1":"0";return`K${t}${i}${n}${a}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new H_([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},H_=class{constructor(e){if(e.length===0)throw h_("chords");this.chords=e}getHashCode(){let e="";for(let t=0,i=this.chords.length;t<i;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 U_(e){if(e.charCode){let i=String.fromCharCode(e.charCode).toUpperCase();return vc.fromString(i)}let t=e.keyCode;if(t===3)return 7;if(Lo)switch(t){case 59:return 85;case 60:if(P_)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(Ai)return 57;break}else if(R_&&(Ai&&t===93||!Ai&&t===92))return 57;return D_[t]||0}var W_=Ai?256:2048,F_=512,z_=1024,q_=Ai?2048:256,Kl=class{constructor(e){var i;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=(i=t.getModifierState)==null?void 0:i.call(t,"AltGraph"),this.keyCode=U_(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|=W_),this.altKey&&(t|=F_),this.shiftKey&&(t|=z_),this.metaKey&&(t|=q_),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new N_(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},Yl=new WeakMap;function G_(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,i=e.parent.location;if(t.origin!=="null"&&i.origin!=="null"&&t.origin!==i.origin)return null}catch{return null}return e.parent}var j_=class{static getSameOriginWindowChain(e){let t=Yl.get(e);if(!t){t=[],Yl.set(e,t);let i=e,n;do n=G_(i),n?t.push({window:new WeakRef(i),iframeElement:i.frameElement||null}):t.push({window:new WeakRef(i),iframeElement:null}),i=n;while(i)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let i=0,n=0,a=this.getSameOriginWindowChain(e);for(let h of a){let d=h.window.deref();if(i+=(d==null?void 0:d.scrollY)??0,n+=(d==null?void 0:d.scrollX)??0,d===t||!h.iframeElement)break;let g=h.iframeElement.getBoundingClientRect();i+=g.top,n+=g.left}return{top:i,left:n}}},Vr=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 i=j_.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=i.left,this.posy-=i.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},Jl=class{constructor(e,t=0,i=0){var a;this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=i,this.deltaX=t;let n=!1;if(va){let h=navigator.userAgent.match(/Chrome\/(\d+)/);n=(h?parseInt(h[1]):123)<=122}if(e){let h=e,d=e,g=((a=e.view)==null?void 0:a.devicePixelRatio)||1;if(typeof h.wheelDeltaY<"u")n?this.deltaY=h.wheelDeltaY/(120*g):this.deltaY=h.wheelDeltaY/120;else if(typeof d.VERTICAL_AXIS<"u"&&d.axis===d.VERTICAL_AXIS)this.deltaY=-d.detail/3;else if(e.type==="wheel"){let v=e;v.deltaMode===v.DOM_DELTA_LINE?Lo&&!Ai?this.deltaY=-e.deltaY/3:this.deltaY=-e.deltaY:this.deltaY=-e.deltaY/40}if(typeof h.wheelDeltaX<"u")A_&&mc?this.deltaX=-(h.wheelDeltaX/120):n?this.deltaX=h.wheelDeltaX/(120*g):this.deltaX=h.wheelDeltaX/120;else if(typeof d.HORIZONTAL_AXIS<"u"&&d.axis===d.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type==="wheel"){let v=e;v.deltaMode===v.DOM_DELTA_LINE?Lo&&!Ai?this.deltaX=-e.deltaX/3:this.deltaX=-e.deltaX:this.deltaX=-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(n?this.deltaY=e.wheelDelta/(120*g):this.deltaY=e.wheelDelta/120)}}preventDefault(){var e;(e=this.browserEvent)==null||e.preventDefault()}stopPropagation(){var e;(e=this.browserEvent)==null||e.stopPropagation()}},Sc=Object.freeze(function(e,t){let i=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(i)}}}),$_;(e=>{function t(i){return i===e.None||i===e.Cancelled||i instanceof V_?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Ft.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Sc})})($_||($_={}));var V_=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?Sc:(this._emitter||(this._emitter=new ee),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Sa=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 Ro("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Ro("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},K_=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,i=globalThis){if(this.isDisposed)throw new Ro("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let n=i.setInterval(()=>{e()},t);this.disposable=vt(()=>{i.clearInterval(n),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Y_;(e=>{async function t(n){let a,h=await Promise.all(n.map(d=>d.then(g=>g,g=>{a||(a=g)})));if(typeof a<"u")throw a;return h}e.settled=t;function i(n){return new Promise(async(a,h)=>{try{await n(a,h)}catch(d){h(d)}})}e.withAsyncBody=i})(Y_||(Y_={}));var Xl=class ci{static fromArray(t){return new ci(i=>{i.emitMany(t)})}static fromPromise(t){return new ci(async i=>{i.emitMany(await t)})}static fromPromises(t){return new ci(async i=>{await Promise.all(t.map(async n=>i.emitOne(await n)))})}static merge(t){return new ci(async i=>{await Promise.all(t.map(async n=>{for await(let a of n)i.emitOne(a)}))})}constructor(t,i){this._state=0,this._results=[],this._error=null,this._onReturn=i,this._onStateChanged=new ee,queueMicrotask(async()=>{let n={emitOne:a=>this.emitOne(a),emitMany:a=>this.emitMany(a),reject:a=>this.reject(a)};try{await Promise.resolve(t(n)),this.resolve()}catch(a){this.reject(a)}finally{n.emitOne=void 0,n.emitMany=void 0,n.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 Ft.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>{var i;return(i=this._onReturn)==null||i.call(this),{done:!0,value:void 0}}}}static map(t,i){return new ci(async n=>{for await(let a of t)n.emitOne(i(a))})}map(t){return ci.map(this,t)}static filter(t,i){return new ci(async n=>{for await(let a of t)i(a)&&n.emitOne(a)})}filter(t){return ci.filter(this,t)}static coalesce(t){return ci.filter(t,i=>!!i)}coalesce(){return ci.coalesce(this)}static async toPromise(t){let i=[];for await(let n of t)i.push(n);return i}toPromise(){return ci.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())}};Xl.EMPTY=Xl.fromArray([]);var{getWindow:Ri,getWindowId:J_,onDidRegisterWindow:X_}=(function(){let e=new Map,t={window:Bi,disposables:new is};e.set(Bi.vscodeWindowId,t);let i=new ee,n=new ee,a=new ee;function h(d,g){return(typeof d=="number"?e.get(d):void 0)??(g?t:void 0)}return{onDidRegisterWindow:i.event,onWillUnregisterWindow:a.event,onDidUnregisterWindow:n.event,registerWindow(d){if(e.has(d.vscodeWindowId))return Ve.None;let g=new is,v={window:d,disposables:g.add(new is)};return e.set(d.vscodeWindowId,v),g.add(vt(()=>{e.delete(d.vscodeWindowId),n.fire(d)})),g.add(Le(d,It.BEFORE_UNLOAD,()=>{a.fire(d)})),i.fire(v),g},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(d){return d.vscodeWindowId},hasWindow(d){return e.has(d)},getWindowById:h,getWindow(d){var p;let g=d;if((p=g==null?void 0:g.ownerDocument)!=null&&p.defaultView)return g.ownerDocument.defaultView.window;let v=d;return v!=null&&v.view?v.view.window:Bi},getDocument(d){return Ri(d).document}}})(),Z_=class{constructor(e,t,i,n){this._node=e,this._type=t,this._handler=i,this._options=n||!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 Le(e,t,i,n){return new Z_(e,t,i,n)}var Zl=function(e,t,i,n){return Le(e,t,i,n)},ba,Q_=class extends K_{constructor(e){super(),this.defaultTarget=e&&Ri(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Ql=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){en(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,n=new Map,a=h=>{i.set(h,!1);let d=e.get(h)??[];for(t.set(h,d),e.set(h,[]),n.set(h,!0);d.length>0;)d.sort(Ql.sort),d.shift().execute();n.set(h,!1)};ba=(h,d,g=0)=>{let v=J_(h),p=new Ql(d,g),R=e.get(v);return R||(R=[],e.set(v,R)),R.push(p),i.get(v)||(i.set(v,!0),h.requestAnimationFrame(()=>a(v))),p}})();function eg(e){let t=e.getBoundingClientRect(),i=Ri(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var It={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"},tg=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=ii(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=ii(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=ii(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=ii(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=ii(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=ii(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=ii(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=ii(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=ii(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=ii(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=ii(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=ii(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=ii(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=ii(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 ii(e){return typeof e=="number"?`${e}px`:e}function Sr(e){return new tg(e)}var bc=class{constructor(){this._hooks=new is,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 i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,n,a){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=n,this._onStopCallback=a;let h=e;try{e.setPointerCapture(t),this._hooks.add(vt(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{h=Ri(e)}this._hooks.add(Le(h,It.POINTER_MOVE,d=>{if(d.buttons!==i){this.stopMonitoring(!0);return}d.preventDefault(),this._pointerMoveCallback(d)})),this._hooks.add(Le(h,It.POINTER_UP,d=>this.stopMonitoring(!0)))}};function ig(e,t,i){let n=null,a=null;if(typeof i.value=="function"?(n="value",a=i.value,a.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof i.get=="function"&&(n="get",a=i.get),!a)throw new Error("not supported");let h=`$memoize$${t}`;i[n]=function(...d){return this.hasOwnProperty(h)||Object.defineProperty(this,h,{configurable:!1,enumerable:!1,writable:!1,value:a.apply(this,d)}),this[h]}}var ki;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(ki||(ki={}));var gr=class $t extends Ve{constructor(){super(),this.dispatched=!1,this.targets=new ql,this.ignoreTargets=new ql,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Ft.runAndSubscribe(X_,({window:t,disposables:i})=>{i.add(Le(t.document,"touchstart",n=>this.onTouchStart(n),{passive:!1})),i.add(Le(t.document,"touchend",n=>this.onTouchEnd(t,n))),i.add(Le(t.document,"touchmove",n=>this.onTouchMove(n),{passive:!1}))},{window:Bi,disposables:this._store}))}static addTarget(t){if(!$t.isTouchDevice())return Ve.None;$t.INSTANCE||($t.INSTANCE=new $t);let i=$t.INSTANCE.targets.push(t);return vt(i)}static ignoreTarget(t){if(!$t.isTouchDevice())return Ve.None;$t.INSTANCE||($t.INSTANCE=new $t);let i=$t.INSTANCE.ignoreTargets.push(t);return vt(i)}static isTouchDevice(){return"ontouchstart"in Bi||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let n=0,a=t.targetTouches.length;n<a;n++){let h=t.targetTouches.item(n);this.activeTouches[h.identifier]={id:h.identifier,initialTarget:h.target,initialTimeStamp:i,initialPageX:h.pageX,initialPageY:h.pageY,rollingTimestamps:[i],rollingPageX:[h.pageX],rollingPageY:[h.pageY]};let d=this.newGestureEvent(ki.Start,h.target);d.pageX=h.pageX,d.pageY=h.pageY,this.dispatchEvent(d)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}onTouchEnd(t,i){let n=Date.now(),a=Object.keys(this.activeTouches).length;for(let h=0,d=i.changedTouches.length;h<d;h++){let g=i.changedTouches.item(h);if(!this.activeTouches.hasOwnProperty(String(g.identifier))){console.warn("move of an UNKNOWN touch",g);continue}let v=this.activeTouches[g.identifier],p=Date.now()-v.initialTimeStamp;if(p<$t.HOLD_DELAY&&Math.abs(v.initialPageX-ri(v.rollingPageX))<30&&Math.abs(v.initialPageY-ri(v.rollingPageY))<30){let R=this.newGestureEvent(ki.Tap,v.initialTarget);R.pageX=ri(v.rollingPageX),R.pageY=ri(v.rollingPageY),this.dispatchEvent(R)}else if(p>=$t.HOLD_DELAY&&Math.abs(v.initialPageX-ri(v.rollingPageX))<30&&Math.abs(v.initialPageY-ri(v.rollingPageY))<30){let R=this.newGestureEvent(ki.Contextmenu,v.initialTarget);R.pageX=ri(v.rollingPageX),R.pageY=ri(v.rollingPageY),this.dispatchEvent(R)}else if(a===1){let R=ri(v.rollingPageX),k=ri(v.rollingPageY),B=ri(v.rollingTimestamps)-v.rollingTimestamps[0],L=R-v.rollingPageX[0],P=k-v.rollingPageY[0],U=[...this.targets].filter(Z=>v.initialTarget instanceof Node&&Z.contains(v.initialTarget));this.inertia(t,U,n,Math.abs(L)/B,L>0?1:-1,R,Math.abs(P)/B,P>0?1:-1,k)}this.dispatchEvent(this.newGestureEvent(ki.End,v.initialTarget)),delete this.activeTouches[g.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,i){let n=document.createEvent("CustomEvent");return n.initEvent(t,!1,!0),n.initialTarget=i,n.tapCount=0,n}dispatchEvent(t){if(t.type===ki.Tap){let i=new Date().getTime(),n=0;i-this._lastSetTapCountTime>$t.CLEAR_TAP_COUNT_TIME?n=1:n=2,this._lastSetTapCountTime=i,t.tapCount=n}else(t.type===ki.Change||t.type===ki.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let n of this.ignoreTargets)if(n.contains(t.initialTarget))return;let i=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let a=0,h=t.initialTarget;for(;h&&h!==n;)a++,h=h.parentElement;i.push([a,n])}i.sort((n,a)=>n[0]-a[0]);for(let[n,a]of i)a.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,n,a,h,d,g,v,p){this.handle=ba(t,()=>{let R=Date.now(),k=R-n,B=0,L=0,P=!0;a+=$t.SCROLL_FRICTION*k,g+=$t.SCROLL_FRICTION*k,a>0&&(P=!1,B=h*a*k),g>0&&(P=!1,L=v*g*k);let U=this.newGestureEvent(ki.Change);U.translationX=B,U.translationY=L,i.forEach(Z=>Z.dispatchEvent(U)),P||this.inertia(t,i,R,a,h,d+B,g,v,p+L)})}onTouchMove(t){let i=Date.now();for(let n=0,a=t.changedTouches.length;n<a;n++){let h=t.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(h.identifier))){console.warn("end of an UNKNOWN touch",h);continue}let d=this.activeTouches[h.identifier],g=this.newGestureEvent(ki.Change,d.initialTarget);g.translationX=h.pageX-ri(d.rollingPageX),g.translationY=h.pageY-ri(d.rollingPageY),g.pageX=h.pageX,g.pageY=h.pageY,this.dispatchEvent(g),d.rollingPageX.length>3&&(d.rollingPageX.shift(),d.rollingPageY.shift(),d.rollingTimestamps.shift()),d.rollingPageX.push(h.pageX),d.rollingPageY.push(h.pageY),d.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};gr.SCROLL_FRICTION=-.005,gr.HOLD_DELAY=700,gr.CLEAR_TAP_COUNT_TIME=400,xt([ig],gr,"isTouchDevice",1);var sg=gr,wa=class extends Ve{onclick(e,t){this._register(Le(e,It.CLICK,i=>t(new Vr(Ri(e),i))))}onmousedown(e,t){this._register(Le(e,It.MOUSE_DOWN,i=>t(new Vr(Ri(e),i))))}onmouseover(e,t){this._register(Le(e,It.MOUSE_OVER,i=>t(new Vr(Ri(e),i))))}onmouseleave(e,t){this._register(Le(e,It.MOUSE_LEAVE,i=>t(new Vr(Ri(e),i))))}onkeydown(e,t){this._register(Le(e,It.KEY_DOWN,i=>t(new Kl(i))))}onkeyup(e,t){this._register(Le(e,It.KEY_UP,i=>t(new Kl(i))))}oninput(e,t){this._register(Le(e,It.INPUT,t))}onblur(e,t){this._register(Le(e,It.BLUR,t))}onfocus(e,t){this._register(Le(e,It.FOCUS,t))}onchange(e,t){this._register(Le(e,It.CHANGE,t))}ignoreGesture(e){return sg.ignoreTarget(e)}},eh=11,rg=class extends wa{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=eh+"px",this.domNode.style.height=eh+"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 bc),this._register(Zl(this.bgDomNode,It.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(Zl(this.domNode,It.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new Q_),this._pointerdownScheduleRepeatTimer=this._register(new Sa)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Ri(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},ng=class Do{constructor(t,i,n,a,h,d,g){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,n=n|0,a=a|0,h=h|0,d=d|0,g=g|0),this.rawScrollLeft=a,this.rawScrollTop=g,i<0&&(i=0),a+i>n&&(a=n-i),a<0&&(a=0),h<0&&(h=0),g+h>d&&(g=d-h),g<0&&(g=0),this.width=i,this.scrollWidth=n,this.scrollLeft=a,this.height=h,this.scrollHeight=d,this.scrollTop=g}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,i){return new Do(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new Do(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,i){let n=this.width!==t.width,a=this.scrollWidth!==t.scrollWidth,h=this.scrollLeft!==t.scrollLeft,d=this.height!==t.height,g=this.scrollHeight!==t.scrollHeight,v=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,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:n,scrollWidthChanged:a,scrollLeftChanged:h,heightChanged:d,scrollHeightChanged:g,scrollTopChanged:v}}},og=class extends Ve{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new ee),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new ng(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 n;let i=this._state.withScrollDimensions(e,t);this._setState(i,!!this._smoothScrolling),(n=this._smoothScrolling)==null||n.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 i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let n;t?n=new ih(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):n=this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=n}else{let i=this._state.withScrollPosition(e);this._smoothScrolling=ih.start(this._state,i,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 i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},th=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function Qn(e,t){let i=t-e;return function(n){return e+i*hg(n)}}function ag(e,t,i){return function(n){return n<i?e(n/i):t((n-i)/(1-i))}}var ih=class No{constructor(t,i,n,a){this.from=t,this.to=i,this.duration=a,this.startTime=n,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,i,n){if(Math.abs(t-i)>2.5*n){let a,h;return t<i?(a=t+.75*n,h=i-.75*n):(a=t-.75*n,h=i+.75*n),ag(Qn(t,a),Qn(h,i),.33)}return Qn(t,i)}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 i=(t-this.startTime)/this.duration;if(i<1){let n=this.scrollLeft(i),a=this.scrollTop(i);return new th(n,a,!1)}return new th(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,i,n){return No.start(t,i,n)}static start(t,i,n){n=n+10;let a=Date.now()-10;return new No(t,i,a,n)}};function lg(e){return Math.pow(e,3)}function hg(e){return 1-lg(1-e)}var cg=class extends Ve{constructor(e,t,i){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=i,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new Sa)}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":"")))}},ug=140,wc=class extends wa{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 cg(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new bc),this._shouldRender=!0,this.domNode=Sr(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(Le(this.domNode.domNode,It.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new rg(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,n){this.slider=Sr(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof n=="number"&&this.slider.setHeight(n),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Le(this.slider.domNode,It.POINTER_DOWN,a=>{a.button===0&&(a.preventDefault(),this._sliderPointerDown(a))})),this.onclick(this.slider.domNode,a=>{a.leftButton&&a.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,i=t+this._scrollbarState.getSliderPosition(),n=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),a=this._sliderPointerPosition(e);i<=a&&a<=n?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,i=e.offsetY;else{let a=eg(this.domNode.domNode);t=e.pageX-a.left,i=e.pageY-a.top}let n=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(n):this._scrollbarState.getDesiredScrollPositionFromOffset(n)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),n=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,a=>{let h=this._sliderOrthogonalPointerPosition(a),d=Math.abs(h-i);if(mc&&d>ug){this._setDesiredScrollPositionNow(n.getScrollPosition());return}let g=this._sliderPointerPosition(a)-t;this._setDesiredScrollPositionNow(n.getDesiredScrollPositionFromDelta(g))},()=>{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()}},Cc=class Ho{constructor(t,i,n,a,h,d){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(t),this._visibleSize=a,this._scrollSize=h,this._scrollPosition=d,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new Ho(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,n,a,h){let d=Math.max(0,n-t),g=Math.max(0,d-2*i),v=a>0&&a>n;if(!v)return{computedAvailableSize:Math.round(d),computedIsNeeded:v,computedSliderSize:Math.round(g),computedSliderRatio:0,computedSliderPosition:0};let p=Math.round(Math.max(20,Math.floor(n*g/a))),R=(g-p)/(a-n),k=h*R;return{computedAvailableSize:Math.round(d),computedIsNeeded:v,computedSliderSize:Math.round(p),computedSliderRatio:R,computedSliderPosition:Math.round(k)}}_refreshComputedValues(){let t=Ho._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 i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,n=this._scrollPosition;return i<this._computedSliderPosition?n-=this._visibleSize:n+=this._visibleSize,n}getDesiredScrollPositionFromDelta(t){if(!this._computedIsNeeded)return 0;let i=this._computedSliderPosition+t;return Math.round(i/this._computedSliderRatio)}},dg=class extends wc{constructor(e,t,i){let n=e.getScrollDimensions(),a=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new Cc(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,n.width,n.scrollWidth,a.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}},fg=class extends wc{constructor(e,t,i){let n=e.getScrollDimensions(),a=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new Cc(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,n.height,n.scrollHeight,a.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}},_g=500,sh=50,gg=class{constructor(e,t,i){this.timestamp=e,this.deltaX=t,this.deltaY=i,this.score=0}},Uo=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,i=0,n=1,a=this._rear;do{let h=a===this._front?t:Math.pow(2,-n);if(t-=h,i+=this._memory[a].score*h,a===this._front)break;a=(this._capacity+a-1)%this._capacity,n++}while(!0);return i<=.5}acceptStandardWheelEvent(t){if(va){let i=Ri(t.browserEvent),n=E_(i);this.accept(Date.now(),t.deltaX*n,t.deltaY*n)}else this.accept(Date.now(),t.deltaX,t.deltaY)}accept(t,i,n){let a=null,h=new gg(t,i,n);this._front===-1&&this._rear===-1?(this._memory[0]=h,this._front=0,this._rear=0):(a=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]=h),h.score=this._computeScore(h,a)}_computeScore(t,i){if(Math.abs(t.deltaX)>0&&Math.abs(t.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(n+=.25),i){let a=Math.abs(t.deltaX),h=Math.abs(t.deltaY),d=Math.abs(i.deltaX),g=Math.abs(i.deltaY),v=Math.max(Math.min(a,d),1),p=Math.max(Math.min(h,g),1),R=Math.max(a,d),k=Math.max(h,g);R%v===0&&k%p===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};Uo.INSTANCE=new Uo;var pg=Uo,mg=class extends wa{constructor(e,t,i){super(),this._onScroll=this._register(new ee),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new ee),this.onWillScroll=this._onWillScroll.event,this._options=yg(t),this._scrollable=i,this._register(this._scrollable.onScroll(a=>{this._onWillScroll.fire(a),this._onDidScroll(a),this._onScroll.fire(a)}));let n={onMouseWheel:a=>this._onMouseWheel(a),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new fg(this._scrollable,this._options,n)),this._horizontalScrollbar=this._register(new dg(this._scrollable,this._options,n)),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=Sr(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Sr(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Sr(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,a=>this._onMouseOver(a)),this.onmouseleave(this._listenOnDomNode,a=>this._onMouseLeave(a)),this._hideTimeout=this._register(new Sa),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=_s(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,Ai&&(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 Jl(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=_s(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new Jl(i))};this._mouseWheelToDispose.push(Le(this._listenOnDomNode,It.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=pg.INSTANCE;t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let h=e.deltaY*this._options.mouseWheelScrollSensitivity,d=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&d+h===0?d=h=0:Math.abs(h)>=Math.abs(d)?d=0:h=0),this._options.flipAxes&&([h,d]=[d,h]);let g=!Ai&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||g)&&!d&&(d=h,h=0),e.browserEvent&&e.browserEvent.altKey&&(d=d*this._options.fastScrollSensitivity,h=h*this._options.fastScrollSensitivity);let v=this._scrollable.getFutureScrollPosition(),p={};if(h){let R=sh*h,k=v.scrollTop-(R<0?Math.floor(R):Math.ceil(R));this._verticalScrollbar.writeScrollPosition(p,k)}if(d){let R=sh*d,k=v.scrollLeft-(R<0?Math.floor(R):Math.ceil(R));this._horizontalScrollbar.writeScrollPosition(p,k)}p=this._scrollable.validateScrollPosition(p),(v.scrollLeft!==p.scrollLeft||v.scrollTop!==p.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(p):this._scrollable.setScrollPositionNow(p),i=!0)}let n=i;!n&&this._options.alwaysConsumeMouseWheel&&(n=!0),!n&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(n=!0),n&&(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,i=e.scrollLeft>0,n=i?" left":"",a=t?" top":"",h=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${n}`),this._topShadowDomNode.setClassName(`shadow${a}`),this._topLeftShadowDomNode.setClassName(`shadow${h}${a}${n}`)}}_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(),_g)}},vg=class extends mg{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function yg(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,Ai&&(t.className+=" mac"),t}var Wo=class extends Ve{constructor(e,t,i,n,a,h,d,g){super(),this._bufferService=i,this._optionsService=d,this._renderService=g,this._onRequestScrollLines=this._register(new ee),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let v=this._register(new og({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:p=>ba(n.window,p)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{v.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new vg(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},v)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(a.onProtocolChange(p=>{this._scrollableElement.updateOptions({handleMouseWheel:!(p&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Ft.runAndSubscribe(h.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=h.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(vt(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=n.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(vt(()=>this._styleElement.remove())),this._register(Ft.runAndSubscribe(h.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${h.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${h.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${h.colors.scrollbarSliderActiveBackground.css};`,"}"].join(`
34
- `)})),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(p=>this._handleScroll(p)))}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),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};Wo=xt([de(2,Xt),de(3,Ii),de(4,sc),de(5,Ws),de(6,Zt),de(7,Di)],Wo);var Fo=class extends Ve{constructor(e,t,i,n,a){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=n,this._renderService=a,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(h=>this._removeDecoration(h))),this._register(vt(()=>{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 n;let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",((n=e==null?void 0:e.options)==null?void 0:n.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 i=e.options.x??0;return i&&i>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 i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=i?`${i*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()}};Fo=xt([de(1,Xt),de(2,Ii),de(3,Tr),de(4,Di)],Fo);var Sg=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,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},Ci={full:0,left:0,center:0,right:0},Zi={full:0,left:0,center:0,right:0},or={full:0,left:0,center:0,right:0},hn=class extends Ve{constructor(e,t,i,n,a,h,d,g){var p;super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=n,this._renderService=a,this._optionsService=h,this._themeService=d,this._coreBrowserService=g,this._colorZoneStore=new Sg,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(),(p=this._viewportElement.parentElement)==null||p.insertBefore(this._canvas,this._viewportElement),this._register(vt(()=>{var R;return(R=this._canvas)==null?void 0:R.remove()}));let v=this._canvas.getContext("2d");if(v)this._ctx=v;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);Zi.full=this._canvas.width,Zi.left=e,Zi.center=t,Zi.right=e,this._refreshDrawHeightConstants(),or.full=1,or.left=1,or.center=1+Zi.left,or.right=1+Zi.left+Zi.center}_refreshDrawHeightConstants(){Ci.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);Ci.left=t,Ci.center=t,Ci.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Ci.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Ci.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Ci.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Ci.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(or[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-Ci[e.position||"full"]/2),Zi[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+Ci[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}))}};hn=xt([de(2,Xt),de(3,Tr),de(4,Di),de(5,Zt),de(6,Ws),de(7,Ii)],hn);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=`
35
- `,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 rn;(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="Ÿ"))(rn||(rn={}));var xc;(e=>e.ST=`${V.ESC}\\`)(xc||(xc={}));var zo=class{constructor(e,t,i,n,a,h){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=n,this._coreService=a,this._renderService=h,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 i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!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,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!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),i=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,a=t*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=a+"px",this._compositionView.style.top=n+"px",this._compositionView.style.height=i+"px",this._compositionView.style.lineHeight=i+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";let h=this._compositionView.getBoundingClientRect();this._textarea.style.left=a+"px",this._textarea.style.top=n+"px",this._textarea.style.width=Math.max(h.width,1)+"px",this._textarea.style.height=Math.max(h.height,1)+"px",this._textarea.style.lineHeight=h.height+"px"}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};zo=xt([de(2,Xt),de(3,Zt),de(4,ps),de(5,Di)],zo);var Dt=0,Nt=0,Ht=0,Ct=0,rh={css:"#00000000",rgba:0},At;(e=>{function t(a,h,d,g){return g!==void 0?`#${ls(a)}${ls(h)}${ls(d)}${ls(g)}`:`#${ls(a)}${ls(h)}${ls(d)}`}e.toCss=t;function i(a,h,d,g=255){return(a<<24|h<<16|d<<8|g)>>>0}e.toRgba=i;function n(a,h,d,g){return{css:e.toCss(a,h,d,g),rgba:e.toRgba(a,h,d,g)}}e.toColor=n})(At||(At={}));var pt;(e=>{function t(v,p){if(Ct=(p.rgba&255)/255,Ct===1)return{css:p.css,rgba:p.rgba};let R=p.rgba>>24&255,k=p.rgba>>16&255,B=p.rgba>>8&255,L=v.rgba>>24&255,P=v.rgba>>16&255,U=v.rgba>>8&255;Dt=L+Math.round((R-L)*Ct),Nt=P+Math.round((k-P)*Ct),Ht=U+Math.round((B-U)*Ct);let Z=At.toCss(Dt,Nt,Ht),_e=At.toRgba(Dt,Nt,Ht);return{css:Z,rgba:_e}}e.blend=t;function i(v){return(v.rgba&255)===255}e.isOpaque=i;function n(v,p,R){let k=nn.ensureContrastRatio(v.rgba,p.rgba,R);if(k)return At.toColor(k>>24&255,k>>16&255,k>>8&255)}e.ensureContrastRatio=n;function a(v){let p=(v.rgba|255)>>>0;return[Dt,Nt,Ht]=nn.toChannels(p),{css:At.toCss(Dt,Nt,Ht),rgba:p}}e.opaque=a;function h(v,p){return Ct=Math.round(p*255),[Dt,Nt,Ht]=nn.toChannels(v.rgba),{css:At.toCss(Dt,Nt,Ht,Ct),rgba:At.toRgba(Dt,Nt,Ht,Ct)}}e.opacity=h;function d(v,p){return Ct=v.rgba&255,h(v,Ct*p/255)}e.multiplyOpacity=d;function g(v){return[v.rgba>>24&255,v.rgba>>16&255,v.rgba>>8&255]}e.toColorRGB=g})(pt||(pt={}));var St;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let h=a.getContext("2d",{willReadFrequently:!0});h&&(t=h,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function n(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return Dt=parseInt(a.slice(1,2).repeat(2),16),Nt=parseInt(a.slice(2,3).repeat(2),16),Ht=parseInt(a.slice(3,4).repeat(2),16),At.toColor(Dt,Nt,Ht);case 5:return Dt=parseInt(a.slice(1,2).repeat(2),16),Nt=parseInt(a.slice(2,3).repeat(2),16),Ht=parseInt(a.slice(3,4).repeat(2),16),Ct=parseInt(a.slice(4,5).repeat(2),16),At.toColor(Dt,Nt,Ht,Ct);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let h=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(h)return Dt=parseInt(h[1]),Nt=parseInt(h[2]),Ht=parseInt(h[3]),Ct=Math.round((h[5]===void 0?1:parseFloat(h[5]))*255),At.toColor(Dt,Nt,Ht,Ct);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Dt,Nt,Ht,Ct]=t.getImageData(0,0,1,1).data,Ct!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:At.toRgba(Dt,Nt,Ht,Ct),css:a}}e.toColor=n})(St||(St={}));var Jt;(e=>{function t(n){return i(n>>16&255,n>>8&255,n&255)}e.relativeLuminance=t;function i(n,a,h){let d=n/255,g=a/255,v=h/255,p=d<=.03928?d/12.92:Math.pow((d+.055)/1.055,2.4),R=g<=.03928?g/12.92:Math.pow((g+.055)/1.055,2.4),k=v<=.03928?v/12.92:Math.pow((v+.055)/1.055,2.4);return p*.2126+R*.7152+k*.0722}e.relativeLuminance2=i})(Jt||(Jt={}));var nn;(e=>{function t(d,g){if(Ct=(g&255)/255,Ct===1)return g;let v=g>>24&255,p=g>>16&255,R=g>>8&255,k=d>>24&255,B=d>>16&255,L=d>>8&255;return Dt=k+Math.round((v-k)*Ct),Nt=B+Math.round((p-B)*Ct),Ht=L+Math.round((R-L)*Ct),At.toRgba(Dt,Nt,Ht)}e.blend=t;function i(d,g,v){let p=Jt.relativeLuminance(d>>8),R=Jt.relativeLuminance(g>>8);if(Li(p,R)<v){if(R<p){let L=n(d,g,v),P=Li(p,Jt.relativeLuminance(L>>8));if(P<v){let U=a(d,g,v),Z=Li(p,Jt.relativeLuminance(U>>8));return P>Z?L:U}return L}let k=a(d,g,v),B=Li(p,Jt.relativeLuminance(k>>8));if(B<v){let L=n(d,g,v),P=Li(p,Jt.relativeLuminance(L>>8));return B>P?k:L}return k}}e.ensureContrastRatio=i;function n(d,g,v){let p=d>>24&255,R=d>>16&255,k=d>>8&255,B=g>>24&255,L=g>>16&255,P=g>>8&255,U=Li(Jt.relativeLuminance2(B,L,P),Jt.relativeLuminance2(p,R,k));for(;U<v&&(B>0||L>0||P>0);)B-=Math.max(0,Math.ceil(B*.1)),L-=Math.max(0,Math.ceil(L*.1)),P-=Math.max(0,Math.ceil(P*.1)),U=Li(Jt.relativeLuminance2(B,L,P),Jt.relativeLuminance2(p,R,k));return(B<<24|L<<16|P<<8|255)>>>0}e.reduceLuminance=n;function a(d,g,v){let p=d>>24&255,R=d>>16&255,k=d>>8&255,B=g>>24&255,L=g>>16&255,P=g>>8&255,U=Li(Jt.relativeLuminance2(B,L,P),Jt.relativeLuminance2(p,R,k));for(;U<v&&(B<255||L<255||P<255);)B=Math.min(255,B+Math.ceil((255-B)*.1)),L=Math.min(255,L+Math.ceil((255-L)*.1)),P=Math.min(255,P+Math.ceil((255-P)*.1)),U=Li(Jt.relativeLuminance2(B,L,P),Jt.relativeLuminance2(p,R,k));return(B<<24|L<<16|P<<8|255)>>>0}e.increaseLuminance=a;function h(d){return[d>>24&255,d>>16&255,d>>8&255,d&255]}e.toChannels=h})(nn||(nn={}));function ls(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Li(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var bg=class extends Or{constructor(e,t,i){super(),this.content=0,this.combinedData="",this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=i}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()]}},cn=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new di}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 i=[],n=t.translateToString(!0),a=0,h=0,d=0,g=t.getFg(0),v=t.getBg(0);for(let p=0;p<t.getTrimmedLength();p++)if(t.loadCell(p,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==g||this._workCell.bg!==v){if(p-a>1){let R=this._getJoinedRanges(n,d,h,t,a);for(let k=0;k<R.length;k++)i.push(R[k])}a=p,d=h,g=this._workCell.fg,v=this._workCell.bg}h+=this._workCell.getChars().length||ts.length}if(this._bufferService.cols-a>1){let p=this._getJoinedRanges(n,d,h,t,a);for(let R=0;R<p.length;R++)i.push(p[R])}return i}_getJoinedRanges(e,t,i,n,a){let h=e.substring(t,i),d=[];try{d=this._characterJoiners[0].handler(h)}catch(g){console.error(g)}for(let g=1;g<this._characterJoiners.length;g++)try{let v=this._characterJoiners[g].handler(h);for(let p=0;p<v.length;p++)cn._mergeRanges(d,v[p])}catch(v){console.error(v)}return this._stringRangesToCellRanges(d,n,a),d}_stringRangesToCellRanges(e,t,i){let n=0,a=!1,h=0,d=e[n];if(d){for(let g=i;g<this._bufferService.cols;g++){let v=t.getWidth(g),p=t.getString(g).length||ts.length;if(v!==0){if(!a&&d[0]<=h&&(d[0]=g,a=!0),d[1]<=h){if(d[1]=g,d=e[++n],!d)break;d[0]<=h?(d[0]=g,a=!0):a=!1}h+=p}}d&&(d[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let i=!1;for(let n=0;n<e.length;n++){let a=e[n];if(i){if(t[1]<=a[0])return e[n-1][1]=t[1],e;if(t[1]<=a[1])return e[n-1][1]=Math.max(t[1],a[1]),e.splice(n,1),e;e.splice(n,1),n--}else{if(t[1]<=a[0])return e.splice(n,0,t),e;if(t[1]<=a[1])return a[0]=Math.min(t[0],a[0]),e;t[0]<a[1]&&(a[0]=Math.min(t[0],a[0]),i=!0);continue}}return i?e[e.length-1][1]=t[1]:e.push(t),e}};cn=xt([de(0,Xt)],cn);function wg(e){return 57508<=e&&e<=57558}function Cg(e){return 9472<=e&&e<=9631}function xg(e){return wg(e)||Cg(e)}function kg(){return{css:{canvas:Kr(),cell:Kr()},device:{canvas:Kr(),cell:Kr(),char:{width:0,height:0,left:0,top:0}}}}function Kr(){return{width:0,height:0}}var qo=class{constructor(e,t,i,n,a,h,d){this._document=e,this._characterJoinerService=t,this._optionsService=i,this._coreBrowserService=n,this._coreService=a,this._decorationService=h,this._themeService=d,this._workCell=new di,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,i){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=i}createRow(e,t,i,n,a,h,d,g,v,p,R){let k=[],B=this._characterJoinerService.getJoinedCharacters(t),L=this._themeService.colors,P=e.getNoBgTrimmedLength();i&&P<h+1&&(P=h+1);let U,Z=0,_e="",rt=0,Ne=0,H=0,W=0,E=!1,ae=0,be=!1,ze=0,Be=0,xe=[],ce=p!==-1&&R!==-1;for(let f=0;f<P;f++){e.loadCell(f,this._workCell);let re=this._workCell.getWidth();if(re===0)continue;let oe=!1,A=f>=Be,Se=f,te=this._workCell;if(B.length>0&&f===B[0][0]&&A){let et=B.shift(),_i=this._isCellInSelection(et[0],t);for(rt=et[0]+1;rt<et[1];rt++)A&&(A=_i===this._isCellInSelection(rt,t));A&&(A=!i||h<et[0]||h>=et[1]),A?(oe=!0,te=new bg(this._workCell,e.translateToString(!0,et[0],et[1]),et[1]-et[0]),Se=et[1]-1,re=te.getWidth()):Be=et[1]}let se=this._isCellInSelection(f,t),ct=i&&f===h,zt=ce&&f>=p&&f<=R,Mt=!1;this._decorationService.forEachDecorationAtCell(f,t,void 0,et=>{Mt=!0});let ut=te.getChars()||ts;if(ut===" "&&(te.isUnderline()||te.isOverline())&&(ut=" "),ze=re*g-v.get(ut,te.isBold(),te.isItalic()),!U)U=this._document.createElement("span");else if(Z&&(se&&be||!se&&!be&&te.bg===Ne)&&(se&&be&&L.selectionForeground||te.fg===H)&&te.extended.ext===W&&zt===E&&ze===ae&&!ct&&!oe&&!Mt&&A){te.isInvisible()?_e+=ts:_e+=ut,Z++;continue}else Z&&(U.textContent=_e),U=this._document.createElement("span"),Z=0,_e="";if(Ne=te.bg,H=te.fg,W=te.extended.ext,E=zt,ae=ze,be=se,oe&&h>=f&&h<=Se&&(h=f),!this._coreService.isCursorHidden&&ct&&this._coreService.isCursorInitialized){if(xe.push("xterm-cursor"),this._coreBrowserService.isFocused)d&&xe.push("xterm-cursor-blink"),xe.push(n==="bar"?"xterm-cursor-bar":n==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(a)switch(a){case"outline":xe.push("xterm-cursor-outline");break;case"block":xe.push("xterm-cursor-block");break;case"bar":xe.push("xterm-cursor-bar");break;case"underline":xe.push("xterm-cursor-underline");break}}if(te.isBold()&&xe.push("xterm-bold"),te.isItalic()&&xe.push("xterm-italic"),te.isDim()&&xe.push("xterm-dim"),te.isInvisible()?_e=ts:_e=te.getChars()||ts,te.isUnderline()&&(xe.push(`xterm-underline-${te.extended.underlineStyle}`),_e===" "&&(_e=" "),!te.isUnderlineColorDefault()))if(te.isUnderlineColorRGB())U.style.textDecorationColor=`rgb(${Or.toColorRGB(te.getUnderlineColor()).join(",")})`;else{let et=te.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&te.isBold()&&et<8&&(et+=8),U.style.textDecorationColor=L.ansi[et].css}te.isOverline()&&(xe.push("xterm-overline"),_e===" "&&(_e=" ")),te.isStrikethrough()&&xe.push("xterm-strikethrough"),zt&&(U.style.textDecoration="underline");let je=te.getFgColor(),Ae=te.getFgColorMode(),at=te.getBgColor(),oi=te.getBgColorMode(),Ni=!!te.isInverse();if(Ni){let et=je;je=at,at=et;let _i=Ae;Ae=oi,oi=_i}let qt,ai,fi=!1;this._decorationService.forEachDecorationAtCell(f,t,void 0,et=>{et.options.layer!=="top"&&fi||(et.backgroundColorRGB&&(oi=50331648,at=et.backgroundColorRGB.rgba>>8&16777215,qt=et.backgroundColorRGB),et.foregroundColorRGB&&(Ae=50331648,je=et.foregroundColorRGB.rgba>>8&16777215,ai=et.foregroundColorRGB),fi=et.options.layer==="top")}),!fi&&se&&(qt=this._coreBrowserService.isFocused?L.selectionBackgroundOpaque:L.selectionInactiveBackgroundOpaque,at=qt.rgba>>8&16777215,oi=50331648,fi=!0,L.selectionForeground&&(Ae=50331648,je=L.selectionForeground.rgba>>8&16777215,ai=L.selectionForeground)),fi&&xe.push("xterm-decoration-top");let Gt;switch(oi){case 16777216:case 33554432:Gt=L.ansi[at],xe.push(`xterm-bg-${at}`);break;case 50331648:Gt=At.toColor(at>>16,at>>8&255,at&255),this._addStyle(U,`background-color:#${nh((at>>>0).toString(16),"0",6)}`);break;case 0:default:Ni?(Gt=L.foreground,xe.push("xterm-bg-257")):Gt=L.background}switch(qt||te.isDim()&&(qt=pt.multiplyOpacity(Gt,.5)),Ae){case 16777216:case 33554432:te.isBold()&&je<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(je+=8),this._applyMinimumContrast(U,Gt,L.ansi[je],te,qt,void 0)||xe.push(`xterm-fg-${je}`);break;case 50331648:let et=At.toColor(je>>16&255,je>>8&255,je&255);this._applyMinimumContrast(U,Gt,et,te,qt,ai)||this._addStyle(U,`color:#${nh(je.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(U,Gt,L.foreground,te,qt,ai)||Ni&&xe.push("xterm-fg-257")}xe.length&&(U.className=xe.join(" "),xe.length=0),!ct&&!oe&&!Mt&&A?Z++:U.textContent=_e,ze!==this.defaultSpacing&&(U.style.letterSpacing=`${ze}px`),k.push(U),f=Se}return U&&Z&&(U.textContent=_e),k}_applyMinimumContrast(e,t,i,n,a,h){if(this._optionsService.rawOptions.minimumContrastRatio===1||xg(n.getCode()))return!1;let d=this._getContrastCache(n),g;if(!a&&!h&&(g=d.getColor(t.rgba,i.rgba)),g===void 0){let v=this._optionsService.rawOptions.minimumContrastRatio/(n.isDim()?2:1);g=pt.ensureContrastRatio(a||t,h||i,v),d.setColor((a||t).rgba,(h||i).rgba,g??null)}return g?(this._addStyle(e,`color:${g.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 i=this._selectionStart,n=this._selectionEnd;return!i||!n?!1:this._columnSelectMode?i[0]<=n[0]?e>=i[0]&&t>=i[1]&&e<n[0]&&t<=n[1]:e<i[0]&&t>=i[1]&&e>=n[0]&&t<=n[1]:t>i[1]&&t<n[1]||i[1]===n[1]&&t===i[1]&&e>=i[0]&&e<n[0]||i[1]<n[1]&&t===n[1]&&e<n[0]||i[1]<n[1]&&t===i[1]&&e>=i[0]}};qo=xt([de(1,oc),de(2,Zt),de(3,Ii),de(4,ps),de(5,Tr),de(6,Ws)],qo);function nh(e,t,i){for(;e.length<i;)e=t+e;return e}var Eg=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 i=e.createElement("span");i.classList.add("xterm-char-measure-element");let n=e.createElement("span");n.classList.add("xterm-char-measure-element"),n.style.fontWeight="bold";let a=e.createElement("span");a.classList.add("xterm-char-measure-element"),a.style.fontStyle="italic";let h=e.createElement("span");h.classList.add("xterm-char-measure-element"),h.style.fontWeight="bold",h.style.fontStyle="italic",this._measureElements=[i,n,a,h],this._container.appendChild(i),this._container.appendChild(n),this._container.appendChild(a),this._container.appendChild(h),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,i,n){e===this._font&&t===this._fontSize&&i===this._weight&&n===this._weightBold||(this._font=e,this._fontSize=t,this._weight=i,this._weightBold=n,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${i}`,this._measureElements[1].style.fontWeight=`${n}`,this._measureElements[2].style.fontWeight=`${i}`,this._measureElements[3].style.fontWeight=`${n}`,this.clear())}get(e,t,i){let n=0;if(!t&&!i&&e.length===1&&(n=e.charCodeAt(0))<256){if(this._flat[n]!==-9999)return this._flat[n];let d=this._measure(e,0);return d>0&&(this._flat[n]=d),d}let a=e;t&&(a+="B"),i&&(a+="I");let h=this._holey.get(a);if(h===void 0){let d=0;t&&(d|=1),i&&(d|=2),h=this._measure(e,d),h>0&&this._holey.set(a,h)}return h}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},Rg=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,i,n=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1]){this.clear();return}let a=e.buffers.active.ydisp,h=t[1]-a,d=i[1]-a,g=Math.max(h,0),v=Math.min(d,e.rows-1);if(g>=e.rows||v<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=n,this.viewportStartRow=h,this.viewportEndRow=d,this.viewportCappedStartRow=g,this.viewportCappedEndRow=v,this.startCol=t[0],this.endCol=i[0]}isCellSelected(e,t,i){return this.hasSelection?(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t<this.endCol&&i<=this.viewportCappedEndRow:t<this.startCol&&i>=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol):!1}};function Ag(){return new Rg}var eo="xterm-dom-renderer-owner-",hi="xterm-rows",Yr="xterm-fg-",oh="xterm-bg-",ar="xterm-focus",Jr="xterm-selection",Mg=1,Go=class extends Ve{constructor(e,t,i,n,a,h,d,g,v,p,R,k,B,L){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=n,this._viewportElement=a,this._helperContainer=h,this._linkifier2=d,this._charSizeService=v,this._optionsService=p,this._bufferService=R,this._coreService=k,this._coreBrowserService=B,this._themeService=L,this._terminalClass=Mg++,this._rowElements=[],this._selectionRenderModel=Ag(),this.onRequestRedraw=this._register(new ee).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(hi),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(Jr),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=kg(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(P=>this._injectCss(P))),this._injectCss(this._themeService.colors),this._rowFactory=g.createInstance(qo,document),this._element.classList.add(eo+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(P=>this._handleLinkHover(P))),this._register(this._linkifier2.onHideLinkUnderline(P=>this._handleLinkLeave(P))),this._register(vt(()=>{this._element.classList.remove(eo+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new Eg(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 i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${hi} 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} .${hi} { 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} .${hi} .xterm-dim { color: ${pt.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 i=`blink_underline_${this._terminalClass}`,n=`blink_bar_${this._terminalClass}`,a=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${n} { 50% { box-shadow: none; }}`,t+=`@keyframes ${a} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${hi}.${ar} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${hi}.${ar} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${hi}.${ar} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${a} 1s step-end infinite;}${this._terminalSelector} .${hi} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${hi} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${hi} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${hi} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${hi} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Jr} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Jr} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Jr} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[h,d]of e.ansi.entries())t+=`${this._terminalSelector} .${Yr}${h} { color: ${d.css}; }${this._terminalSelector} .${Yr}${h}.xterm-dim { color: ${pt.multiplyOpacity(d,.5).css}; }${this._terminalSelector} .${oh}${h} { background-color: ${d.css}; }`;t+=`${this._terminalSelector} .${Yr}257 { color: ${pt.opaque(e.background).css}; }${this._terminalSelector} .${Yr}257.xterm-dim { color: ${pt.multiplyOpacity(pt.opaque(e.background),.5).css}; }${this._terminalSelector} .${oh}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 i=this._rowElements.length;i<=t;i++){let n=this._document.createElement("div");this._rowContainer.appendChild(n),this._rowElements.push(n)}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(ar),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ar),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let n=this._selectionRenderModel.viewportStartRow,a=this._selectionRenderModel.viewportEndRow,h=this._selectionRenderModel.viewportCappedStartRow,d=this._selectionRenderModel.viewportCappedEndRow,g=this._document.createDocumentFragment();if(i){let v=e[0]>t[0];g.appendChild(this._createSelectionElement(h,v?t[0]:e[0],v?e[0]:t[0],d-h+1))}else{let v=n===h?e[0]:0,p=h===a?t[0]:this._bufferService.cols;g.appendChild(this._createSelectionElement(h,v,p));let R=d-h-1;if(g.appendChild(this._createSelectionElement(h+1,0,this._bufferService.cols,R)),h!==d){let k=a===d?t[0]:this._bufferService.cols;g.appendChild(this._createSelectionElement(d,0,k))}}this._selectionContainer.appendChild(g)}_createSelectionElement(e,t,i,n=1){let a=this._document.createElement("div"),h=t*this.dimensions.css.cell.width,d=this.dimensions.css.cell.width*(i-t);return h+d>this.dimensions.css.canvas.width&&(d=this.dimensions.css.canvas.width-h),a.style.height=`${n*this.dimensions.css.cell.height}px`,a.style.top=`${e*this.dimensions.css.cell.height}px`,a.style.left=`${h}px`,a.style.width=`${d}px`,a}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 i=this._bufferService.buffer,n=i.ybase+i.y,a=Math.min(i.x,this._bufferService.cols-1),h=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,d=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,g=this._optionsService.rawOptions.cursorInactiveStyle;for(let v=e;v<=t;v++){let p=v+i.ydisp,R=this._rowElements[v],k=i.lines.get(p);if(!R||!k)break;R.replaceChildren(...this._rowFactory.createRow(k,p,p===n,d,g,a,h,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${eo}${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,i,n,a,h){i<0&&(e=0),n<0&&(t=0);let d=this._bufferService.rows-1;i=Math.max(Math.min(i,d),0),n=Math.max(Math.min(n,d),0),a=Math.min(a,this._bufferService.cols);let g=this._bufferService.buffer,v=g.ybase+g.y,p=Math.min(g.x,a-1),R=this._optionsService.rawOptions.cursorBlink,k=this._optionsService.rawOptions.cursorStyle,B=this._optionsService.rawOptions.cursorInactiveStyle;for(let L=i;L<=n;++L){let P=L+g.ydisp,U=this._rowElements[L],Z=g.lines.get(P);if(!U||!Z)break;U.replaceChildren(...this._rowFactory.createRow(Z,P,P===v,k,B,p,R,this.dimensions.css.cell.width,this._widthCache,h?L===i?e:0:-1,h?(L===n?t:a)-1:-1))}}};Go=xt([de(7,ga),de(8,vn),de(9,Zt),de(10,Xt),de(11,ps),de(12,Ii),de(13,Ws)],Go);var jo=class extends Ve{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new ee),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new Tg(this._optionsService))}catch{this._measureStrategy=this._register(new Og(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())}};jo=xt([de(2,Zt)],jo);var kc=class extends Ve{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)}},Og=class extends kc{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,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}},Tg=class extends kc{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}},Pg=class extends Ve{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new Lg(this._window)),this._onDprChange=this._register(new ee),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new ee),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(n=>this._screenDprMonitor.setWindow(n))),this._register(Ft.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Le(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Le(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}},Lg=class extends Ve{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new Us),this._onDprChange=this._register(new ee),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(vt(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Le(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)}},Bg=class extends Ve{constructor(){super(),this.linkProviders=[],this._register(vt(()=>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 Ca(e,t,i){let n=i.getBoundingClientRect(),a=e.getComputedStyle(i),h=parseInt(a.getPropertyValue("padding-left")),d=parseInt(a.getPropertyValue("padding-top"));return[t.clientX-n.left-h,t.clientY-n.top-d]}function Ig(e,t,i,n,a,h,d,g,v){if(!h)return;let p=Ca(e,t,i);if(p)return p[0]=Math.ceil((p[0]+(v?d/2:0))/d),p[1]=Math.ceil(p[1]/g),p[0]=Math.min(Math.max(p[0],1),n+(v?1:0)),p[1]=Math.min(Math.max(p[1],1),a),p}var $o=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,n,a){return Ig(window,e,t,i,n,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,a)}getMouseReportCoords(e,t){let i=Ca(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};$o=xt([de(0,Di),de(1,vn)],$o);var Dg=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,i){this._rowCount=i,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=[]}},Ec={};$f(Ec,{getSafariVersion:()=>Hg,isChromeOS:()=>Oc,isFirefox:()=>Rc,isIpad:()=>Ug,isIphone:()=>Wg,isLegacyEdge:()=>Ng,isLinux:()=>xa,isMac:()=>un,isNode:()=>yn,isSafari:()=>Ac,isWindows:()=>Mc});var yn=typeof process<"u"&&"title"in process,Pr=yn?"node":navigator.userAgent,Lr=yn?"node":navigator.platform,Rc=Pr.includes("Firefox"),Ng=Pr.includes("Edge"),Ac=/^((?!chrome|android).)*safari/i.test(Pr);function Hg(){if(!Ac)return 0;let e=Pr.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var un=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Lr),Ug=Lr==="iPad",Wg=Lr==="iPhone",Mc=["Windows","Win16","Win32","WinCE"].includes(Lr),xa=Lr.indexOf("Linux")>=0,Oc=/\bCrOS\b/.test(Pr),Tc=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,i=0,n=e.timeRemaining(),a=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),i=Math.max(t,i),a=e.timeRemaining(),i*1.5>a){n-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(n-t))}ms`),this._start();return}n=a}this.clear()}},Fg=class extends Tc{_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())}}},zg=class extends Tc{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},dn=!yn&&"requestIdleCallback"in window?zg:Fg,qg=class{constructor(){this._queue=new dn}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},Vo=class extends Ve{constructor(e,t,i,n,a,h,d,g,v){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=n,this._coreService=a,this._coreBrowserService=g,this._renderer=this._register(new Us),this._pausedResizeTask=new qg,this._observerDisposable=this._register(new Us),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 ee),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new ee),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new ee),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new ee),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new Dg((p,R)=>this._renderRows(p,R),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new Gg(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(vt(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(d.onResize(()=>this._fullRefresh())),this._register(d.buffers.onBufferActivate(()=>{var p;return(p=this._renderer.value)==null?void 0:p.clear()})),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(h.onDecorationRegistered(()=>this._fullRefresh())),this._register(h.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(d.cols,d.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(d.buffer.y,d.buffer.y,!0))),this._register(v.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(p=>this._registerIntersectionObserver(p,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(n=>this._handleIntersectionChange(n[n.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=vt(()=>i.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,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let n=this._syncOutputHandler.flush();n&&(e=Math.min(e,n.start),t=Math.max(t,n.end)),i||(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 i;return(i=this._renderer.value)==null?void 0:i.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,i){var n;this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,(n=this._renderer.value)==null||n.handleSelectionChanged(e,t,i)}handleCursorMove(){var e;(e=this._renderer.value)==null||e.handleCursorMove()}clear(){var e;(e=this._renderer.value)==null||e.clear()}};Vo=xt([de(2,Zt),de(3,vn),de(4,ps),de(5,Tr),de(6,Xt),de(7,Ii),de(8,Ws)],Vo);var Gg=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,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 jg(e,t,i,n){let a=i.buffer.x,h=i.buffer.y;if(!i.buffer.hasScrollback)return Kg(a,h,e,t,i,n)+Sn(h,t,i,n)+Yg(a,h,e,t,i,n);let d;if(h===t)return d=a>e?"D":"C",xr(Math.abs(a-e),Cr(d,n));d=h>t?"D":"C";let g=Math.abs(h-t),v=Vg(h>t?e:a,i)+(g-1)*i.cols+1+$g(h>t?a:e);return xr(v,Cr(d,n))}function $g(e,t){return e-1}function Vg(e,t){return t.cols-e}function Kg(e,t,i,n,a,h){return Sn(t,n,a,h).length===0?"":xr(Lc(e,t,e,t-gs(t,a),!1,a).length,Cr("D",h))}function Sn(e,t,i,n){let a=e-gs(e,i),h=t-gs(t,i),d=Math.abs(a-h)-Jg(e,t,i);return xr(d,Cr(Pc(e,t),n))}function Yg(e,t,i,n,a,h){let d;Sn(t,n,a,h).length>0?d=n-gs(n,a):d=t;let g=n,v=Xg(e,t,i,n,a,h);return xr(Lc(e,d,i,g,v==="C",a).length,Cr(v,h))}function Jg(e,t,i){var d;let n=0,a=e-gs(e,i),h=t-gs(t,i);for(let g=0;g<Math.abs(a-h);g++){let v=Pc(e,t)==="A"?-1:1;(d=i.buffer.lines.get(a+v*g))!=null&&d.isWrapped&&n++}return n}function gs(e,t){let i=0,n=t.buffer.lines.get(e),a=n==null?void 0:n.isWrapped;for(;a&&e>=0&&e<t.rows;)i++,n=t.buffer.lines.get(--e),a=n==null?void 0:n.isWrapped;return i}function Xg(e,t,i,n,a,h){let d;return Sn(i,n,a,h).length>0?d=n-gs(n,a):d=t,e<i&&d<=n||e>=i&&d<n?"C":"D"}function Pc(e,t){return e>t?"A":"B"}function Lc(e,t,i,n,a,h){let d=e,g=t,v="";for(;(d!==i||g!==n)&&g>=0&&g<h.buffer.lines.length;)d+=a?1:-1,a&&d>h.cols-1?(v+=h.buffer.translateBufferLineToString(g,!1,e,d),d=0,e=0,g++):!a&&d<0&&(v+=h.buffer.translateBufferLineToString(g,!1,0,e+1),d=h.cols-1,e=d,g--);return v+h.buffer.translateBufferLineToString(g,!1,e,d)}function Cr(e,t){let i=t?"O":"[";return V.ESC+i+e}function xr(e,t){e=Math.floor(e);let i="";for(let n=0;n<e;n++)i+=t;return i}var Zg=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 ah(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 to=50,Qg=15,ep=50,tp=500,ip=" ",sp=new RegExp(ip,"g"),Ko=class extends Ve{constructor(e,t,i,n,a,h,d,g,v){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=n,this._coreService=a,this._mouseService=h,this._optionsService=d,this._renderService=g,this._coreBrowserService=v,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new di,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new ee),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new ee),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new ee),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new ee),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=p=>this._handleMouseMove(p),this._mouseUpListener=p=>this._handleMouseUp(p),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(p=>this._handleTrim(p)),this._register(this._bufferService.buffers.onBufferActivate(p=>this._handleBufferActivate(p))),this.enable(),this._model=new Zg(this._bufferService),this._activeSelectionMode=0,this._register(vt(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(p=>{p.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 i=this._bufferService.buffer,n=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let a=e[0]<t[0]?e[0]:t[0],h=e[0]<t[0]?t[0]:e[0];for(let d=e[1];d<=t[1];d++){let g=i.translateBufferLineToString(d,!0,a,h);n.push(g)}}else{let a=e[1]===t[1]?t[0]:void 0;n.push(i.translateBufferLineToString(e[1],!0,e[0],a));for(let h=e[1]+1;h<=t[1]-1;h++){let d=i.lines.get(h),g=i.translateBufferLineToString(h,!0);d!=null&&d.isWrapped?n[n.length-1]+=g:n.push(g)}if(e[1]!==t[1]){let h=i.lines.get(t[1]),d=i.translateBufferLineToString(t[1],!0,0,t[0]);h&&h.isWrapped?n[n.length-1]+=d:n.push(d)}}return n.map(a=>a.replace(sp," ")).join(Mc?`\r
33
+ `))}},y_=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},S_=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},b_=0,Jn=class{constructor(e){this.value=e,this.id=b_++}},w_=2,C_,ee=class{constructor(e){var t,i,n,a;this._size=0,this._options=e,this._leakageMon=(t=this._options)!=null&&t.leakWarningThreshold?new m_((e==null?void 0:e.onListenerError)??en,((i=this._options)==null?void 0:i.leakWarningThreshold)??p_):void 0,this._perfMon=(n=this._options)!=null&&n._profName?new g_(this._options._profName):void 0,this._deliveryQueue=(a=this._options)==null?void 0:a.deliveryQueue}dispose(){var e,t,i,n;this._disposed||(this._disposed=!0,((e=this._deliveryQueue)==null?void 0:e.current)===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),(i=(t=this._options)==null?void 0:t.onDidRemoveLastListener)==null||i.call(t),(n=this._leakageMon)==null||n.dispose())}get event(){return this._event??(this._event=(e,t,i)=>{var d,g,v,m,R;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let k=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(k);let B=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],L=new S_(`${k}. HINT: Stack shows most frequent listener (${B[1]}-times)`,B[0]);return(((d=this._options)==null?void 0:d.onListenerError)||en)(L),Ve.None}if(this._disposed)return Ve.None;t&&(e=e.bind(t));let n=new Jn(e),a;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(n.stack=v_.create(),a=this._leakageMon.check(n.stack,this._size+1)),this._listeners?this._listeners instanceof Jn?(this._deliveryQueue??(this._deliveryQueue=new x_),this._listeners=[this._listeners,n]):this._listeners.push(n):((v=(g=this._options)==null?void 0:g.onWillAddFirstListener)==null||v.call(g,this),this._listeners=n,(R=(m=this._options)==null?void 0:m.onDidAddFirstListener)==null||R.call(m,this)),this._size++;let h=vt(()=>{a==null||a(),this._removeListener(n)});return i instanceof is?i.add(h):Array.isArray(i)&&i.push(h),h}),this._event}_removeListener(e){var a,h,d,g;if((h=(a=this._options)==null?void 0:a.onWillRemoveListener)==null||h.call(a,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(g=(d=this._options)==null?void 0:d.onDidRemoveLastListener)==null||g.call(d,this),this._size=0;return}let t=this._listeners,i=t.indexOf(e);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--,t[i]=void 0;let n=this._deliveryQueue.current===this;if(this._size*w_<=t.length){let v=0;for(let m=0;m<t.length;m++)t[m]?t[v++]=t[m]:n&&(this._deliveryQueue.end--,v<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=v}}_deliver(e,t){var n;if(!e)return;let i=((n=this._options)==null?void 0:n.onListenerError)||en;if(!i){e.value(t);return}try{e.value(t)}catch(a){i(a)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){var t,i,n,a;if((t=this._deliveryQueue)!=null&&t.current&&(this._deliverQueue(this._deliveryQueue),(i=this._perfMon)==null||i.stop()),(n=this._perfMon)==null||n.start(this._size),this._listeners)if(this._listeners instanceof Jn)this._deliver(this._listeners,e);else{let h=this._deliveryQueue;h.enqueue(this,e,this._listeners.length),this._deliverQueue(h)}(a=this._perfMon)==null||a.stop()}hasListeners(){return this._size>0}},x_=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Po=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new ee,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new ee,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,i){if(this.getZoomLevel(i)===t)return;let n=this.getWindowId(i);this.mapWindowIdToZoomLevel.set(n,t),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,i){this.mapWindowIdToZoomFactor.set(this.getWindowId(i),t)}setFullscreen(t,i){if(this.isFullscreen(i)===t)return;let n=this.getWindowId(i);this.mapWindowIdToFullScreen.set(n,t),this._onDidChangeFullscreen.fire(n)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};Po.INSTANCE=new Po;var ma=Po;function k_(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}ma.INSTANCE.onDidChangeZoomLevel;function E_(e){return ma.INSTANCE.getZoomFactor(e)}ma.INSTANCE.onDidChangeFullscreen;var Fs=typeof navigator=="object"?navigator.userAgent:"",Lo=Fs.indexOf("Firefox")>=0,R_=Fs.indexOf("AppleWebKit")>=0,va=Fs.indexOf("Chrome")>=0,A_=!va&&Fs.indexOf("Safari")>=0;Fs.indexOf("Electron/")>=0;Fs.indexOf("Android")>=0;var Xn=!1;if(typeof Bi.matchMedia=="function"){let e=Bi.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=Bi.matchMedia("(display-mode: fullscreen)");Xn=e.matches,k_(Bi,e,({matches:i})=>{Xn&&t.matches||(Xn=i)})}var Ds="en",Bo=!1,Io=!1,tn=!1,pc=!1,$r,sn=Ds,Gl=Ds,M_,mi,ds=globalThis,Wt,Nh;typeof ds.vscode<"u"&&typeof ds.vscode.process<"u"?Wt=ds.vscode.process:typeof process<"u"&&typeof((Nh=process==null?void 0:process.versions)==null?void 0:Nh.node)=="string"&&(Wt=process);var Hh,O_=typeof((Hh=Wt==null?void 0:Wt.versions)==null?void 0:Hh.electron)=="string",T_=O_&&(Wt==null?void 0:Wt.type)==="renderer",Uh;if(typeof Wt=="object"){Bo=Wt.platform==="win32",Io=Wt.platform==="darwin",tn=Wt.platform==="linux",tn&&Wt.env.SNAP&&Wt.env.SNAP_REVISION,Wt.env.CI||Wt.env.BUILD_ARTIFACTSTAGINGDIRECTORY,$r=Ds,sn=Ds;let e=Wt.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);$r=t.userLocale,Gl=t.osLocale,sn=t.resolvedLanguage||Ds,M_=(Uh=t.languagePack)==null?void 0:Uh.translationsConfigFile}catch{}pc=!0}else typeof navigator=="object"&&!T_?(mi=navigator.userAgent,Bo=mi.indexOf("Windows")>=0,Io=mi.indexOf("Macintosh")>=0,(mi.indexOf("Macintosh")>=0||mi.indexOf("iPad")>=0||mi.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,tn=mi.indexOf("Linux")>=0,(mi==null?void 0:mi.indexOf("Mobi"))>=0,sn=globalThis._VSCODE_NLS_LANGUAGE||Ds,$r=navigator.language.toLowerCase(),Gl=$r):console.error("Unable to resolve platform.");var mc=Bo,Ri=Io,P_=tn,jl=pc,Ai=mi,Xi=sn,L_;(e=>{function t(){return Xi}e.value=t;function i(){return Xi.length===2?Xi==="en":Xi.length>=3?Xi[0]==="e"&&Xi[1]==="n"&&Xi[2]==="-":!1}e.isDefaultVariant=i;function n(){return Xi==="en"}e.isDefault=n})(L_||(L_={}));var B_=typeof ds.postMessage=="function"&&!ds.importScripts;(()=>{if(B_){let e=[];ds.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let n=0,a=e.length;n<a;n++){let h=e[n];if(h.id===i.data.vscodeScheduleAsyncWork){e.splice(n,1),h.callback();return}}});let t=0;return i=>{let n=++t;e.push({id:n,callback:i}),ds.postMessage({vscodeScheduleAsyncWork:n},"*")}}return e=>setTimeout(e)})();var I_=!!(Ai&&Ai.indexOf("Chrome")>=0);Ai&&Ai.indexOf("Firefox")>=0;!I_&&Ai&&Ai.indexOf("Safari")>=0;Ai&&Ai.indexOf("Edg/")>=0;Ai&&Ai.indexOf("Android")>=0;var Ts=typeof navigator=="object"?navigator:{};jl||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ts&&Ts.clipboard&&Ts.clipboard.writeText,jl||Ts&&Ts.clipboard&&Ts.clipboard.readText;var ya=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}},Zn=new ya,$l=new ya,Vl=new ya,D_=new Array(230),vc;(e=>{function t(g){return Zn.keyCodeToStr(g)}e.toString=t;function i(g){return Zn.strToKeyCode(g)}e.fromString=i;function n(g){return $l.keyCodeToStr(g)}e.toUserSettingsUS=n;function a(g){return Vl.keyCodeToStr(g)}e.toUserSettingsGeneral=a;function h(g){return $l.strToKeyCode(g)||Vl.strToKeyCode(g)}e.fromUserSettings=h;function d(g){if(g>=98&&g<=113)return null;switch(g){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return Zn.keyCodeToStr(g)}e.toElectronAccelerator=d})(vc||(vc={}));var N_=class yc{constructor(t,i,n,a,h){this.ctrlKey=t,this.shiftKey=i,this.altKey=n,this.metaKey=a,this.keyCode=h}equals(t){return t instanceof yc&&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",i=this.shiftKey?"1":"0",n=this.altKey?"1":"0",a=this.metaKey?"1":"0";return`K${t}${i}${n}${a}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new H_([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},H_=class{constructor(e){if(e.length===0)throw h_("chords");this.chords=e}getHashCode(){let e="";for(let t=0,i=this.chords.length;t<i;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 U_(e){if(e.charCode){let i=String.fromCharCode(e.charCode).toUpperCase();return vc.fromString(i)}let t=e.keyCode;if(t===3)return 7;if(Lo)switch(t){case 59:return 85;case 60:if(P_)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(Ri)return 57;break}else if(R_&&(Ri&&t===93||!Ri&&t===92))return 57;return D_[t]||0}var W_=Ri?256:2048,F_=512,z_=1024,q_=Ri?2048:256,Kl=class{constructor(e){var i;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=(i=t.getModifierState)==null?void 0:i.call(t,"AltGraph"),this.keyCode=U_(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|=W_),this.altKey&&(t|=F_),this.shiftKey&&(t|=z_),this.metaKey&&(t|=q_),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new N_(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},Yl=new WeakMap;function G_(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,i=e.parent.location;if(t.origin!=="null"&&i.origin!=="null"&&t.origin!==i.origin)return null}catch{return null}return e.parent}var j_=class{static getSameOriginWindowChain(e){let t=Yl.get(e);if(!t){t=[],Yl.set(e,t);let i=e,n;do n=G_(i),n?t.push({window:new WeakRef(i),iframeElement:i.frameElement||null}):t.push({window:new WeakRef(i),iframeElement:null}),i=n;while(i)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let i=0,n=0,a=this.getSameOriginWindowChain(e);for(let h of a){let d=h.window.deref();if(i+=(d==null?void 0:d.scrollY)??0,n+=(d==null?void 0:d.scrollX)??0,d===t||!h.iframeElement)break;let g=h.iframeElement.getBoundingClientRect();i+=g.top,n+=g.left}return{top:i,left:n}}},Vr=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 i=j_.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=i.left,this.posy-=i.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},Jl=class{constructor(e,t=0,i=0){var a;this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=i,this.deltaX=t;let n=!1;if(va){let h=navigator.userAgent.match(/Chrome\/(\d+)/);n=(h?parseInt(h[1]):123)<=122}if(e){let h=e,d=e,g=((a=e.view)==null?void 0:a.devicePixelRatio)||1;if(typeof h.wheelDeltaY<"u")n?this.deltaY=h.wheelDeltaY/(120*g):this.deltaY=h.wheelDeltaY/120;else if(typeof d.VERTICAL_AXIS<"u"&&d.axis===d.VERTICAL_AXIS)this.deltaY=-d.detail/3;else if(e.type==="wheel"){let v=e;v.deltaMode===v.DOM_DELTA_LINE?Lo&&!Ri?this.deltaY=-e.deltaY/3:this.deltaY=-e.deltaY:this.deltaY=-e.deltaY/40}if(typeof h.wheelDeltaX<"u")A_&&mc?this.deltaX=-(h.wheelDeltaX/120):n?this.deltaX=h.wheelDeltaX/(120*g):this.deltaX=h.wheelDeltaX/120;else if(typeof d.HORIZONTAL_AXIS<"u"&&d.axis===d.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type==="wheel"){let v=e;v.deltaMode===v.DOM_DELTA_LINE?Lo&&!Ri?this.deltaX=-e.deltaX/3:this.deltaX=-e.deltaX:this.deltaX=-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(n?this.deltaY=e.wheelDelta/(120*g):this.deltaY=e.wheelDelta/120)}}preventDefault(){var e;(e=this.browserEvent)==null||e.preventDefault()}stopPropagation(){var e;(e=this.browserEvent)==null||e.stopPropagation()}},Sc=Object.freeze(function(e,t){let i=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(i)}}}),$_;(e=>{function t(i){return i===e.None||i===e.Cancelled||i instanceof V_?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Ft.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Sc})})($_||($_={}));var V_=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?Sc:(this._emitter||(this._emitter=new ee),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Sa=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 Ro("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Ro("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},K_=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,i=globalThis){if(this.isDisposed)throw new Ro("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let n=i.setInterval(()=>{e()},t);this.disposable=vt(()=>{i.clearInterval(n),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Y_;(e=>{async function t(n){let a,h=await Promise.all(n.map(d=>d.then(g=>g,g=>{a||(a=g)})));if(typeof a<"u")throw a;return h}e.settled=t;function i(n){return new Promise(async(a,h)=>{try{await n(a,h)}catch(d){h(d)}})}e.withAsyncBody=i})(Y_||(Y_={}));var Xl=class ci{static fromArray(t){return new ci(i=>{i.emitMany(t)})}static fromPromise(t){return new ci(async i=>{i.emitMany(await t)})}static fromPromises(t){return new ci(async i=>{await Promise.all(t.map(async n=>i.emitOne(await n)))})}static merge(t){return new ci(async i=>{await Promise.all(t.map(async n=>{for await(let a of n)i.emitOne(a)}))})}constructor(t,i){this._state=0,this._results=[],this._error=null,this._onReturn=i,this._onStateChanged=new ee,queueMicrotask(async()=>{let n={emitOne:a=>this.emitOne(a),emitMany:a=>this.emitMany(a),reject:a=>this.reject(a)};try{await Promise.resolve(t(n)),this.resolve()}catch(a){this.reject(a)}finally{n.emitOne=void 0,n.emitMany=void 0,n.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 Ft.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>{var i;return(i=this._onReturn)==null||i.call(this),{done:!0,value:void 0}}}}static map(t,i){return new ci(async n=>{for await(let a of t)n.emitOne(i(a))})}map(t){return ci.map(this,t)}static filter(t,i){return new ci(async n=>{for await(let a of t)i(a)&&n.emitOne(a)})}filter(t){return ci.filter(this,t)}static coalesce(t){return ci.filter(t,i=>!!i)}coalesce(){return ci.coalesce(this)}static async toPromise(t){let i=[];for await(let n of t)i.push(n);return i}toPromise(){return ci.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())}};Xl.EMPTY=Xl.fromArray([]);var{getWindow:Ei,getWindowId:J_,onDidRegisterWindow:X_}=(function(){let e=new Map,t={window:Bi,disposables:new is};e.set(Bi.vscodeWindowId,t);let i=new ee,n=new ee,a=new ee;function h(d,g){return(typeof d=="number"?e.get(d):void 0)??(g?t:void 0)}return{onDidRegisterWindow:i.event,onWillUnregisterWindow:a.event,onDidUnregisterWindow:n.event,registerWindow(d){if(e.has(d.vscodeWindowId))return Ve.None;let g=new is,v={window:d,disposables:g.add(new is)};return e.set(d.vscodeWindowId,v),g.add(vt(()=>{e.delete(d.vscodeWindowId),n.fire(d)})),g.add(Le(d,It.BEFORE_UNLOAD,()=>{a.fire(d)})),i.fire(v),g},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(d){return d.vscodeWindowId},hasWindow(d){return e.has(d)},getWindowById:h,getWindow(d){var m;let g=d;if((m=g==null?void 0:g.ownerDocument)!=null&&m.defaultView)return g.ownerDocument.defaultView.window;let v=d;return v!=null&&v.view?v.view.window:Bi},getDocument(d){return Ei(d).document}}})(),Z_=class{constructor(e,t,i,n){this._node=e,this._type=t,this._handler=i,this._options=n||!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 Le(e,t,i,n){return new Z_(e,t,i,n)}var Zl=function(e,t,i,n){return Le(e,t,i,n)},ba,Q_=class extends K_{constructor(e){super(),this.defaultTarget=e&&Ei(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Ql=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){en(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,n=new Map,a=h=>{i.set(h,!1);let d=e.get(h)??[];for(t.set(h,d),e.set(h,[]),n.set(h,!0);d.length>0;)d.sort(Ql.sort),d.shift().execute();n.set(h,!1)};ba=(h,d,g=0)=>{let v=J_(h),m=new Ql(d,g),R=e.get(v);return R||(R=[],e.set(v,R)),R.push(m),i.get(v)||(i.set(v,!0),h.requestAnimationFrame(()=>a(v))),m}})();function eg(e){let t=e.getBoundingClientRect(),i=Ei(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var It={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"},tg=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=ii(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=ii(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=ii(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=ii(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=ii(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=ii(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=ii(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=ii(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=ii(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=ii(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=ii(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=ii(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=ii(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=ii(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 ii(e){return typeof e=="number"?`${e}px`:e}function Sr(e){return new tg(e)}var bc=class{constructor(){this._hooks=new is,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 i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,n,a){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=n,this._onStopCallback=a;let h=e;try{e.setPointerCapture(t),this._hooks.add(vt(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{h=Ei(e)}this._hooks.add(Le(h,It.POINTER_MOVE,d=>{if(d.buttons!==i){this.stopMonitoring(!0);return}d.preventDefault(),this._pointerMoveCallback(d)})),this._hooks.add(Le(h,It.POINTER_UP,d=>this.stopMonitoring(!0)))}};function ig(e,t,i){let n=null,a=null;if(typeof i.value=="function"?(n="value",a=i.value,a.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof i.get=="function"&&(n="get",a=i.get),!a)throw new Error("not supported");let h=`$memoize$${t}`;i[n]=function(...d){return this.hasOwnProperty(h)||Object.defineProperty(this,h,{configurable:!1,enumerable:!1,writable:!1,value:a.apply(this,d)}),this[h]}}var ki;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(ki||(ki={}));var gr=class $t extends Ve{constructor(){super(),this.dispatched=!1,this.targets=new ql,this.ignoreTargets=new ql,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Ft.runAndSubscribe(X_,({window:t,disposables:i})=>{i.add(Le(t.document,"touchstart",n=>this.onTouchStart(n),{passive:!1})),i.add(Le(t.document,"touchend",n=>this.onTouchEnd(t,n))),i.add(Le(t.document,"touchmove",n=>this.onTouchMove(n),{passive:!1}))},{window:Bi,disposables:this._store}))}static addTarget(t){if(!$t.isTouchDevice())return Ve.None;$t.INSTANCE||($t.INSTANCE=new $t);let i=$t.INSTANCE.targets.push(t);return vt(i)}static ignoreTarget(t){if(!$t.isTouchDevice())return Ve.None;$t.INSTANCE||($t.INSTANCE=new $t);let i=$t.INSTANCE.ignoreTargets.push(t);return vt(i)}static isTouchDevice(){return"ontouchstart"in Bi||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let n=0,a=t.targetTouches.length;n<a;n++){let h=t.targetTouches.item(n);this.activeTouches[h.identifier]={id:h.identifier,initialTarget:h.target,initialTimeStamp:i,initialPageX:h.pageX,initialPageY:h.pageY,rollingTimestamps:[i],rollingPageX:[h.pageX],rollingPageY:[h.pageY]};let d=this.newGestureEvent(ki.Start,h.target);d.pageX=h.pageX,d.pageY=h.pageY,this.dispatchEvent(d)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}onTouchEnd(t,i){let n=Date.now(),a=Object.keys(this.activeTouches).length;for(let h=0,d=i.changedTouches.length;h<d;h++){let g=i.changedTouches.item(h);if(!this.activeTouches.hasOwnProperty(String(g.identifier))){console.warn("move of an UNKNOWN touch",g);continue}let v=this.activeTouches[g.identifier],m=Date.now()-v.initialTimeStamp;if(m<$t.HOLD_DELAY&&Math.abs(v.initialPageX-ri(v.rollingPageX))<30&&Math.abs(v.initialPageY-ri(v.rollingPageY))<30){let R=this.newGestureEvent(ki.Tap,v.initialTarget);R.pageX=ri(v.rollingPageX),R.pageY=ri(v.rollingPageY),this.dispatchEvent(R)}else if(m>=$t.HOLD_DELAY&&Math.abs(v.initialPageX-ri(v.rollingPageX))<30&&Math.abs(v.initialPageY-ri(v.rollingPageY))<30){let R=this.newGestureEvent(ki.Contextmenu,v.initialTarget);R.pageX=ri(v.rollingPageX),R.pageY=ri(v.rollingPageY),this.dispatchEvent(R)}else if(a===1){let R=ri(v.rollingPageX),k=ri(v.rollingPageY),B=ri(v.rollingTimestamps)-v.rollingTimestamps[0],L=R-v.rollingPageX[0],P=k-v.rollingPageY[0],U=[...this.targets].filter(Z=>v.initialTarget instanceof Node&&Z.contains(v.initialTarget));this.inertia(t,U,n,Math.abs(L)/B,L>0?1:-1,R,Math.abs(P)/B,P>0?1:-1,k)}this.dispatchEvent(this.newGestureEvent(ki.End,v.initialTarget)),delete this.activeTouches[g.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,i){let n=document.createEvent("CustomEvent");return n.initEvent(t,!1,!0),n.initialTarget=i,n.tapCount=0,n}dispatchEvent(t){if(t.type===ki.Tap){let i=new Date().getTime(),n=0;i-this._lastSetTapCountTime>$t.CLEAR_TAP_COUNT_TIME?n=1:n=2,this._lastSetTapCountTime=i,t.tapCount=n}else(t.type===ki.Change||t.type===ki.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let n of this.ignoreTargets)if(n.contains(t.initialTarget))return;let i=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let a=0,h=t.initialTarget;for(;h&&h!==n;)a++,h=h.parentElement;i.push([a,n])}i.sort((n,a)=>n[0]-a[0]);for(let[n,a]of i)a.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,n,a,h,d,g,v,m){this.handle=ba(t,()=>{let R=Date.now(),k=R-n,B=0,L=0,P=!0;a+=$t.SCROLL_FRICTION*k,g+=$t.SCROLL_FRICTION*k,a>0&&(P=!1,B=h*a*k),g>0&&(P=!1,L=v*g*k);let U=this.newGestureEvent(ki.Change);U.translationX=B,U.translationY=L,i.forEach(Z=>Z.dispatchEvent(U)),P||this.inertia(t,i,R,a,h,d+B,g,v,m+L)})}onTouchMove(t){let i=Date.now();for(let n=0,a=t.changedTouches.length;n<a;n++){let h=t.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(h.identifier))){console.warn("end of an UNKNOWN touch",h);continue}let d=this.activeTouches[h.identifier],g=this.newGestureEvent(ki.Change,d.initialTarget);g.translationX=h.pageX-ri(d.rollingPageX),g.translationY=h.pageY-ri(d.rollingPageY),g.pageX=h.pageX,g.pageY=h.pageY,this.dispatchEvent(g),d.rollingPageX.length>3&&(d.rollingPageX.shift(),d.rollingPageY.shift(),d.rollingTimestamps.shift()),d.rollingPageX.push(h.pageX),d.rollingPageY.push(h.pageY),d.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};gr.SCROLL_FRICTION=-.005,gr.HOLD_DELAY=700,gr.CLEAR_TAP_COUNT_TIME=400,xt([ig],gr,"isTouchDevice",1);var sg=gr,wa=class extends Ve{onclick(e,t){this._register(Le(e,It.CLICK,i=>t(new Vr(Ei(e),i))))}onmousedown(e,t){this._register(Le(e,It.MOUSE_DOWN,i=>t(new Vr(Ei(e),i))))}onmouseover(e,t){this._register(Le(e,It.MOUSE_OVER,i=>t(new Vr(Ei(e),i))))}onmouseleave(e,t){this._register(Le(e,It.MOUSE_LEAVE,i=>t(new Vr(Ei(e),i))))}onkeydown(e,t){this._register(Le(e,It.KEY_DOWN,i=>t(new Kl(i))))}onkeyup(e,t){this._register(Le(e,It.KEY_UP,i=>t(new Kl(i))))}oninput(e,t){this._register(Le(e,It.INPUT,t))}onblur(e,t){this._register(Le(e,It.BLUR,t))}onfocus(e,t){this._register(Le(e,It.FOCUS,t))}onchange(e,t){this._register(Le(e,It.CHANGE,t))}ignoreGesture(e){return sg.ignoreTarget(e)}},eh=11,rg=class extends wa{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=eh+"px",this.domNode.style.height=eh+"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 bc),this._register(Zl(this.bgDomNode,It.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(Zl(this.domNode,It.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new Q_),this._pointerdownScheduleRepeatTimer=this._register(new Sa)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Ei(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},ng=class Do{constructor(t,i,n,a,h,d,g){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,n=n|0,a=a|0,h=h|0,d=d|0,g=g|0),this.rawScrollLeft=a,this.rawScrollTop=g,i<0&&(i=0),a+i>n&&(a=n-i),a<0&&(a=0),h<0&&(h=0),g+h>d&&(g=d-h),g<0&&(g=0),this.width=i,this.scrollWidth=n,this.scrollLeft=a,this.height=h,this.scrollHeight=d,this.scrollTop=g}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,i){return new Do(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new Do(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,i){let n=this.width!==t.width,a=this.scrollWidth!==t.scrollWidth,h=this.scrollLeft!==t.scrollLeft,d=this.height!==t.height,g=this.scrollHeight!==t.scrollHeight,v=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,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:n,scrollWidthChanged:a,scrollLeftChanged:h,heightChanged:d,scrollHeightChanged:g,scrollTopChanged:v}}},og=class extends Ve{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new ee),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new ng(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 n;let i=this._state.withScrollDimensions(e,t);this._setState(i,!!this._smoothScrolling),(n=this._smoothScrolling)==null||n.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 i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let n;t?n=new ih(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):n=this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=n}else{let i=this._state.withScrollPosition(e);this._smoothScrolling=ih.start(this._state,i,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 i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},th=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function Qn(e,t){let i=t-e;return function(n){return e+i*hg(n)}}function ag(e,t,i){return function(n){return n<i?e(n/i):t((n-i)/(1-i))}}var ih=class No{constructor(t,i,n,a){this.from=t,this.to=i,this.duration=a,this.startTime=n,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,i,n){if(Math.abs(t-i)>2.5*n){let a,h;return t<i?(a=t+.75*n,h=i-.75*n):(a=t-.75*n,h=i+.75*n),ag(Qn(t,a),Qn(h,i),.33)}return Qn(t,i)}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 i=(t-this.startTime)/this.duration;if(i<1){let n=this.scrollLeft(i),a=this.scrollTop(i);return new th(n,a,!1)}return new th(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,i,n){return No.start(t,i,n)}static start(t,i,n){n=n+10;let a=Date.now()-10;return new No(t,i,a,n)}};function lg(e){return Math.pow(e,3)}function hg(e){return 1-lg(1-e)}var cg=class extends Ve{constructor(e,t,i){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=i,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new Sa)}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":"")))}},ug=140,wc=class extends wa{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 cg(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new bc),this._shouldRender=!0,this.domNode=Sr(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(Le(this.domNode.domNode,It.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new rg(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,n){this.slider=Sr(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof n=="number"&&this.slider.setHeight(n),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Le(this.slider.domNode,It.POINTER_DOWN,a=>{a.button===0&&(a.preventDefault(),this._sliderPointerDown(a))})),this.onclick(this.slider.domNode,a=>{a.leftButton&&a.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,i=t+this._scrollbarState.getSliderPosition(),n=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),a=this._sliderPointerPosition(e);i<=a&&a<=n?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,i=e.offsetY;else{let a=eg(this.domNode.domNode);t=e.pageX-a.left,i=e.pageY-a.top}let n=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(n):this._scrollbarState.getDesiredScrollPositionFromOffset(n)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),n=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,a=>{let h=this._sliderOrthogonalPointerPosition(a),d=Math.abs(h-i);if(mc&&d>ug){this._setDesiredScrollPositionNow(n.getScrollPosition());return}let g=this._sliderPointerPosition(a)-t;this._setDesiredScrollPositionNow(n.getDesiredScrollPositionFromDelta(g))},()=>{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()}},Cc=class Ho{constructor(t,i,n,a,h,d){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(t),this._visibleSize=a,this._scrollSize=h,this._scrollPosition=d,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new Ho(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,n,a,h){let d=Math.max(0,n-t),g=Math.max(0,d-2*i),v=a>0&&a>n;if(!v)return{computedAvailableSize:Math.round(d),computedIsNeeded:v,computedSliderSize:Math.round(g),computedSliderRatio:0,computedSliderPosition:0};let m=Math.round(Math.max(20,Math.floor(n*g/a))),R=(g-m)/(a-n),k=h*R;return{computedAvailableSize:Math.round(d),computedIsNeeded:v,computedSliderSize:Math.round(m),computedSliderRatio:R,computedSliderPosition:Math.round(k)}}_refreshComputedValues(){let t=Ho._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 i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,n=this._scrollPosition;return i<this._computedSliderPosition?n-=this._visibleSize:n+=this._visibleSize,n}getDesiredScrollPositionFromDelta(t){if(!this._computedIsNeeded)return 0;let i=this._computedSliderPosition+t;return Math.round(i/this._computedSliderRatio)}},dg=class extends wc{constructor(e,t,i){let n=e.getScrollDimensions(),a=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new Cc(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,n.width,n.scrollWidth,a.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}},fg=class extends wc{constructor(e,t,i){let n=e.getScrollDimensions(),a=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new Cc(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,n.height,n.scrollHeight,a.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}},_g=500,sh=50,gg=class{constructor(e,t,i){this.timestamp=e,this.deltaX=t,this.deltaY=i,this.score=0}},Uo=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,i=0,n=1,a=this._rear;do{let h=a===this._front?t:Math.pow(2,-n);if(t-=h,i+=this._memory[a].score*h,a===this._front)break;a=(this._capacity+a-1)%this._capacity,n++}while(!0);return i<=.5}acceptStandardWheelEvent(t){if(va){let i=Ei(t.browserEvent),n=E_(i);this.accept(Date.now(),t.deltaX*n,t.deltaY*n)}else this.accept(Date.now(),t.deltaX,t.deltaY)}accept(t,i,n){let a=null,h=new gg(t,i,n);this._front===-1&&this._rear===-1?(this._memory[0]=h,this._front=0,this._rear=0):(a=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]=h),h.score=this._computeScore(h,a)}_computeScore(t,i){if(Math.abs(t.deltaX)>0&&Math.abs(t.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(n+=.25),i){let a=Math.abs(t.deltaX),h=Math.abs(t.deltaY),d=Math.abs(i.deltaX),g=Math.abs(i.deltaY),v=Math.max(Math.min(a,d),1),m=Math.max(Math.min(h,g),1),R=Math.max(a,d),k=Math.max(h,g);R%v===0&&k%m===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};Uo.INSTANCE=new Uo;var pg=Uo,mg=class extends wa{constructor(e,t,i){super(),this._onScroll=this._register(new ee),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new ee),this.onWillScroll=this._onWillScroll.event,this._options=yg(t),this._scrollable=i,this._register(this._scrollable.onScroll(a=>{this._onWillScroll.fire(a),this._onDidScroll(a),this._onScroll.fire(a)}));let n={onMouseWheel:a=>this._onMouseWheel(a),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new fg(this._scrollable,this._options,n)),this._horizontalScrollbar=this._register(new dg(this._scrollable,this._options,n)),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=Sr(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Sr(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Sr(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,a=>this._onMouseOver(a)),this.onmouseleave(this._listenOnDomNode,a=>this._onMouseLeave(a)),this._hideTimeout=this._register(new Sa),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=_s(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,Ri&&(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 Jl(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=_s(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new Jl(i))};this._mouseWheelToDispose.push(Le(this._listenOnDomNode,It.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=pg.INSTANCE;t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let h=e.deltaY*this._options.mouseWheelScrollSensitivity,d=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&d+h===0?d=h=0:Math.abs(h)>=Math.abs(d)?d=0:h=0),this._options.flipAxes&&([h,d]=[d,h]);let g=!Ri&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||g)&&!d&&(d=h,h=0),e.browserEvent&&e.browserEvent.altKey&&(d=d*this._options.fastScrollSensitivity,h=h*this._options.fastScrollSensitivity);let v=this._scrollable.getFutureScrollPosition(),m={};if(h){let R=sh*h,k=v.scrollTop-(R<0?Math.floor(R):Math.ceil(R));this._verticalScrollbar.writeScrollPosition(m,k)}if(d){let R=sh*d,k=v.scrollLeft-(R<0?Math.floor(R):Math.ceil(R));this._horizontalScrollbar.writeScrollPosition(m,k)}m=this._scrollable.validateScrollPosition(m),(v.scrollLeft!==m.scrollLeft||v.scrollTop!==m.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(m):this._scrollable.setScrollPositionNow(m),i=!0)}let n=i;!n&&this._options.alwaysConsumeMouseWheel&&(n=!0),!n&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(n=!0),n&&(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,i=e.scrollLeft>0,n=i?" left":"",a=t?" top":"",h=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${n}`),this._topShadowDomNode.setClassName(`shadow${a}`),this._topLeftShadowDomNode.setClassName(`shadow${h}${a}${n}`)}}_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(),_g)}},vg=class extends mg{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function yg(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,Ri&&(t.className+=" mac"),t}var Wo=class extends Ve{constructor(e,t,i,n,a,h,d,g){super(),this._bufferService=i,this._optionsService=d,this._renderService=g,this._onRequestScrollLines=this._register(new ee),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let v=this._register(new og({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:m=>ba(n.window,m)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{v.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new vg(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},v)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(a.onProtocolChange(m=>{this._scrollableElement.updateOptions({handleMouseWheel:!(m&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Ft.runAndSubscribe(h.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=h.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(vt(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=n.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(vt(()=>this._styleElement.remove())),this._register(Ft.runAndSubscribe(h.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${h.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${h.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${h.colors.scrollbarSliderActiveBackground.css};`,"}"].join(`
34
+ `)})),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(m=>this._handleScroll(m)))}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),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};Wo=xt([de(2,Xt),de(3,Ii),de(4,sc),de(5,Ws),de(6,Zt),de(7,Di)],Wo);var Fo=class extends Ve{constructor(e,t,i,n,a){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=n,this._renderService=a,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(h=>this._removeDecoration(h))),this._register(vt(()=>{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 n;let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",((n=e==null?void 0:e.options)==null?void 0:n.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 i=e.options.x??0;return i&&i>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 i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=i?`${i*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()}};Fo=xt([de(1,Xt),de(2,Ii),de(3,Tr),de(4,Di)],Fo);var Sg=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,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},Ci={full:0,left:0,center:0,right:0},Zi={full:0,left:0,center:0,right:0},or={full:0,left:0,center:0,right:0},hn=class extends Ve{constructor(e,t,i,n,a,h,d,g){var m;super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=n,this._renderService=a,this._optionsService=h,this._themeService=d,this._coreBrowserService=g,this._colorZoneStore=new Sg,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(),(m=this._viewportElement.parentElement)==null||m.insertBefore(this._canvas,this._viewportElement),this._register(vt(()=>{var R;return(R=this._canvas)==null?void 0:R.remove()}));let v=this._canvas.getContext("2d");if(v)this._ctx=v;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);Zi.full=this._canvas.width,Zi.left=e,Zi.center=t,Zi.right=e,this._refreshDrawHeightConstants(),or.full=1,or.left=1,or.center=1+Zi.left,or.right=1+Zi.left+Zi.center}_refreshDrawHeightConstants(){Ci.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);Ci.left=t,Ci.center=t,Ci.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Ci.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Ci.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Ci.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Ci.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(or[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-Ci[e.position||"full"]/2),Zi[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+Ci[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}))}};hn=xt([de(2,Xt),de(3,Tr),de(4,Di),de(5,Zt),de(6,Ws),de(7,Ii)],hn);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=`
35
+ `,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 rn;(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="Ÿ"))(rn||(rn={}));var xc;(e=>e.ST=`${V.ESC}\\`)(xc||(xc={}));var zo=class{constructor(e,t,i,n,a,h){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=n,this._coreService=a,this._renderService=h,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 i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!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,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!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),i=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,a=t*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=a+"px",this._compositionView.style.top=n+"px",this._compositionView.style.height=i+"px",this._compositionView.style.lineHeight=i+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";let h=this._compositionView.getBoundingClientRect();this._textarea.style.left=a+"px",this._textarea.style.top=n+"px",this._textarea.style.width=Math.max(h.width,1)+"px",this._textarea.style.height=Math.max(h.height,1)+"px",this._textarea.style.lineHeight=h.height+"px"}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};zo=xt([de(2,Xt),de(3,Zt),de(4,ps),de(5,Di)],zo);var Dt=0,Nt=0,Ht=0,Ct=0,rh={css:"#00000000",rgba:0},At;(e=>{function t(a,h,d,g){return g!==void 0?`#${ls(a)}${ls(h)}${ls(d)}${ls(g)}`:`#${ls(a)}${ls(h)}${ls(d)}`}e.toCss=t;function i(a,h,d,g=255){return(a<<24|h<<16|d<<8|g)>>>0}e.toRgba=i;function n(a,h,d,g){return{css:e.toCss(a,h,d,g),rgba:e.toRgba(a,h,d,g)}}e.toColor=n})(At||(At={}));var pt;(e=>{function t(v,m){if(Ct=(m.rgba&255)/255,Ct===1)return{css:m.css,rgba:m.rgba};let R=m.rgba>>24&255,k=m.rgba>>16&255,B=m.rgba>>8&255,L=v.rgba>>24&255,P=v.rgba>>16&255,U=v.rgba>>8&255;Dt=L+Math.round((R-L)*Ct),Nt=P+Math.round((k-P)*Ct),Ht=U+Math.round((B-U)*Ct);let Z=At.toCss(Dt,Nt,Ht),_e=At.toRgba(Dt,Nt,Ht);return{css:Z,rgba:_e}}e.blend=t;function i(v){return(v.rgba&255)===255}e.isOpaque=i;function n(v,m,R){let k=nn.ensureContrastRatio(v.rgba,m.rgba,R);if(k)return At.toColor(k>>24&255,k>>16&255,k>>8&255)}e.ensureContrastRatio=n;function a(v){let m=(v.rgba|255)>>>0;return[Dt,Nt,Ht]=nn.toChannels(m),{css:At.toCss(Dt,Nt,Ht),rgba:m}}e.opaque=a;function h(v,m){return Ct=Math.round(m*255),[Dt,Nt,Ht]=nn.toChannels(v.rgba),{css:At.toCss(Dt,Nt,Ht,Ct),rgba:At.toRgba(Dt,Nt,Ht,Ct)}}e.opacity=h;function d(v,m){return Ct=v.rgba&255,h(v,Ct*m/255)}e.multiplyOpacity=d;function g(v){return[v.rgba>>24&255,v.rgba>>16&255,v.rgba>>8&255]}e.toColorRGB=g})(pt||(pt={}));var St;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let h=a.getContext("2d",{willReadFrequently:!0});h&&(t=h,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function n(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return Dt=parseInt(a.slice(1,2).repeat(2),16),Nt=parseInt(a.slice(2,3).repeat(2),16),Ht=parseInt(a.slice(3,4).repeat(2),16),At.toColor(Dt,Nt,Ht);case 5:return Dt=parseInt(a.slice(1,2).repeat(2),16),Nt=parseInt(a.slice(2,3).repeat(2),16),Ht=parseInt(a.slice(3,4).repeat(2),16),Ct=parseInt(a.slice(4,5).repeat(2),16),At.toColor(Dt,Nt,Ht,Ct);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let h=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(h)return Dt=parseInt(h[1]),Nt=parseInt(h[2]),Ht=parseInt(h[3]),Ct=Math.round((h[5]===void 0?1:parseFloat(h[5]))*255),At.toColor(Dt,Nt,Ht,Ct);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Dt,Nt,Ht,Ct]=t.getImageData(0,0,1,1).data,Ct!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:At.toRgba(Dt,Nt,Ht,Ct),css:a}}e.toColor=n})(St||(St={}));var Jt;(e=>{function t(n){return i(n>>16&255,n>>8&255,n&255)}e.relativeLuminance=t;function i(n,a,h){let d=n/255,g=a/255,v=h/255,m=d<=.03928?d/12.92:Math.pow((d+.055)/1.055,2.4),R=g<=.03928?g/12.92:Math.pow((g+.055)/1.055,2.4),k=v<=.03928?v/12.92:Math.pow((v+.055)/1.055,2.4);return m*.2126+R*.7152+k*.0722}e.relativeLuminance2=i})(Jt||(Jt={}));var nn;(e=>{function t(d,g){if(Ct=(g&255)/255,Ct===1)return g;let v=g>>24&255,m=g>>16&255,R=g>>8&255,k=d>>24&255,B=d>>16&255,L=d>>8&255;return Dt=k+Math.round((v-k)*Ct),Nt=B+Math.round((m-B)*Ct),Ht=L+Math.round((R-L)*Ct),At.toRgba(Dt,Nt,Ht)}e.blend=t;function i(d,g,v){let m=Jt.relativeLuminance(d>>8),R=Jt.relativeLuminance(g>>8);if(Pi(m,R)<v){if(R<m){let L=n(d,g,v),P=Pi(m,Jt.relativeLuminance(L>>8));if(P<v){let U=a(d,g,v),Z=Pi(m,Jt.relativeLuminance(U>>8));return P>Z?L:U}return L}let k=a(d,g,v),B=Pi(m,Jt.relativeLuminance(k>>8));if(B<v){let L=n(d,g,v),P=Pi(m,Jt.relativeLuminance(L>>8));return B>P?k:L}return k}}e.ensureContrastRatio=i;function n(d,g,v){let m=d>>24&255,R=d>>16&255,k=d>>8&255,B=g>>24&255,L=g>>16&255,P=g>>8&255,U=Pi(Jt.relativeLuminance2(B,L,P),Jt.relativeLuminance2(m,R,k));for(;U<v&&(B>0||L>0||P>0);)B-=Math.max(0,Math.ceil(B*.1)),L-=Math.max(0,Math.ceil(L*.1)),P-=Math.max(0,Math.ceil(P*.1)),U=Pi(Jt.relativeLuminance2(B,L,P),Jt.relativeLuminance2(m,R,k));return(B<<24|L<<16|P<<8|255)>>>0}e.reduceLuminance=n;function a(d,g,v){let m=d>>24&255,R=d>>16&255,k=d>>8&255,B=g>>24&255,L=g>>16&255,P=g>>8&255,U=Pi(Jt.relativeLuminance2(B,L,P),Jt.relativeLuminance2(m,R,k));for(;U<v&&(B<255||L<255||P<255);)B=Math.min(255,B+Math.ceil((255-B)*.1)),L=Math.min(255,L+Math.ceil((255-L)*.1)),P=Math.min(255,P+Math.ceil((255-P)*.1)),U=Pi(Jt.relativeLuminance2(B,L,P),Jt.relativeLuminance2(m,R,k));return(B<<24|L<<16|P<<8|255)>>>0}e.increaseLuminance=a;function h(d){return[d>>24&255,d>>16&255,d>>8&255,d&255]}e.toChannels=h})(nn||(nn={}));function ls(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Pi(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var bg=class extends Or{constructor(e,t,i){super(),this.content=0,this.combinedData="",this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=i}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()]}},cn=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new di}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 i=[],n=t.translateToString(!0),a=0,h=0,d=0,g=t.getFg(0),v=t.getBg(0);for(let m=0;m<t.getTrimmedLength();m++)if(t.loadCell(m,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==g||this._workCell.bg!==v){if(m-a>1){let R=this._getJoinedRanges(n,d,h,t,a);for(let k=0;k<R.length;k++)i.push(R[k])}a=m,d=h,g=this._workCell.fg,v=this._workCell.bg}h+=this._workCell.getChars().length||ts.length}if(this._bufferService.cols-a>1){let m=this._getJoinedRanges(n,d,h,t,a);for(let R=0;R<m.length;R++)i.push(m[R])}return i}_getJoinedRanges(e,t,i,n,a){let h=e.substring(t,i),d=[];try{d=this._characterJoiners[0].handler(h)}catch(g){console.error(g)}for(let g=1;g<this._characterJoiners.length;g++)try{let v=this._characterJoiners[g].handler(h);for(let m=0;m<v.length;m++)cn._mergeRanges(d,v[m])}catch(v){console.error(v)}return this._stringRangesToCellRanges(d,n,a),d}_stringRangesToCellRanges(e,t,i){let n=0,a=!1,h=0,d=e[n];if(d){for(let g=i;g<this._bufferService.cols;g++){let v=t.getWidth(g),m=t.getString(g).length||ts.length;if(v!==0){if(!a&&d[0]<=h&&(d[0]=g,a=!0),d[1]<=h){if(d[1]=g,d=e[++n],!d)break;d[0]<=h?(d[0]=g,a=!0):a=!1}h+=m}}d&&(d[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let i=!1;for(let n=0;n<e.length;n++){let a=e[n];if(i){if(t[1]<=a[0])return e[n-1][1]=t[1],e;if(t[1]<=a[1])return e[n-1][1]=Math.max(t[1],a[1]),e.splice(n,1),e;e.splice(n,1),n--}else{if(t[1]<=a[0])return e.splice(n,0,t),e;if(t[1]<=a[1])return a[0]=Math.min(t[0],a[0]),e;t[0]<a[1]&&(a[0]=Math.min(t[0],a[0]),i=!0);continue}}return i?e[e.length-1][1]=t[1]:e.push(t),e}};cn=xt([de(0,Xt)],cn);function wg(e){return 57508<=e&&e<=57558}function Cg(e){return 9472<=e&&e<=9631}function xg(e){return wg(e)||Cg(e)}function kg(){return{css:{canvas:Kr(),cell:Kr()},device:{canvas:Kr(),cell:Kr(),char:{width:0,height:0,left:0,top:0}}}}function Kr(){return{width:0,height:0}}var qo=class{constructor(e,t,i,n,a,h,d){this._document=e,this._characterJoinerService=t,this._optionsService=i,this._coreBrowserService=n,this._coreService=a,this._decorationService=h,this._themeService=d,this._workCell=new di,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,i){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=i}createRow(e,t,i,n,a,h,d,g,v,m,R){let k=[],B=this._characterJoinerService.getJoinedCharacters(t),L=this._themeService.colors,P=e.getNoBgTrimmedLength();i&&P<h+1&&(P=h+1);let U,Z=0,_e="",rt=0,Ne=0,H=0,W=0,E=!1,ae=0,be=!1,ze=0,Be=0,xe=[],ce=m!==-1&&R!==-1;for(let f=0;f<P;f++){e.loadCell(f,this._workCell);let re=this._workCell.getWidth();if(re===0)continue;let oe=!1,A=f>=Be,Se=f,te=this._workCell;if(B.length>0&&f===B[0][0]&&A){let et=B.shift(),_i=this._isCellInSelection(et[0],t);for(rt=et[0]+1;rt<et[1];rt++)A&&(A=_i===this._isCellInSelection(rt,t));A&&(A=!i||h<et[0]||h>=et[1]),A?(oe=!0,te=new bg(this._workCell,e.translateToString(!0,et[0],et[1]),et[1]-et[0]),Se=et[1]-1,re=te.getWidth()):Be=et[1]}let se=this._isCellInSelection(f,t),ct=i&&f===h,zt=ce&&f>=m&&f<=R,Mt=!1;this._decorationService.forEachDecorationAtCell(f,t,void 0,et=>{Mt=!0});let ut=te.getChars()||ts;if(ut===" "&&(te.isUnderline()||te.isOverline())&&(ut=" "),ze=re*g-v.get(ut,te.isBold(),te.isItalic()),!U)U=this._document.createElement("span");else if(Z&&(se&&be||!se&&!be&&te.bg===Ne)&&(se&&be&&L.selectionForeground||te.fg===H)&&te.extended.ext===W&&zt===E&&ze===ae&&!ct&&!oe&&!Mt&&A){te.isInvisible()?_e+=ts:_e+=ut,Z++;continue}else Z&&(U.textContent=_e),U=this._document.createElement("span"),Z=0,_e="";if(Ne=te.bg,H=te.fg,W=te.extended.ext,E=zt,ae=ze,be=se,oe&&h>=f&&h<=Se&&(h=f),!this._coreService.isCursorHidden&&ct&&this._coreService.isCursorInitialized){if(xe.push("xterm-cursor"),this._coreBrowserService.isFocused)d&&xe.push("xterm-cursor-blink"),xe.push(n==="bar"?"xterm-cursor-bar":n==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(a)switch(a){case"outline":xe.push("xterm-cursor-outline");break;case"block":xe.push("xterm-cursor-block");break;case"bar":xe.push("xterm-cursor-bar");break;case"underline":xe.push("xterm-cursor-underline");break}}if(te.isBold()&&xe.push("xterm-bold"),te.isItalic()&&xe.push("xterm-italic"),te.isDim()&&xe.push("xterm-dim"),te.isInvisible()?_e=ts:_e=te.getChars()||ts,te.isUnderline()&&(xe.push(`xterm-underline-${te.extended.underlineStyle}`),_e===" "&&(_e=" "),!te.isUnderlineColorDefault()))if(te.isUnderlineColorRGB())U.style.textDecorationColor=`rgb(${Or.toColorRGB(te.getUnderlineColor()).join(",")})`;else{let et=te.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&te.isBold()&&et<8&&(et+=8),U.style.textDecorationColor=L.ansi[et].css}te.isOverline()&&(xe.push("xterm-overline"),_e===" "&&(_e=" ")),te.isStrikethrough()&&xe.push("xterm-strikethrough"),zt&&(U.style.textDecoration="underline");let je=te.getFgColor(),Ae=te.getFgColorMode(),at=te.getBgColor(),oi=te.getBgColorMode(),Ni=!!te.isInverse();if(Ni){let et=je;je=at,at=et;let _i=Ae;Ae=oi,oi=_i}let qt,ai,fi=!1;this._decorationService.forEachDecorationAtCell(f,t,void 0,et=>{et.options.layer!=="top"&&fi||(et.backgroundColorRGB&&(oi=50331648,at=et.backgroundColorRGB.rgba>>8&16777215,qt=et.backgroundColorRGB),et.foregroundColorRGB&&(Ae=50331648,je=et.foregroundColorRGB.rgba>>8&16777215,ai=et.foregroundColorRGB),fi=et.options.layer==="top")}),!fi&&se&&(qt=this._coreBrowserService.isFocused?L.selectionBackgroundOpaque:L.selectionInactiveBackgroundOpaque,at=qt.rgba>>8&16777215,oi=50331648,fi=!0,L.selectionForeground&&(Ae=50331648,je=L.selectionForeground.rgba>>8&16777215,ai=L.selectionForeground)),fi&&xe.push("xterm-decoration-top");let Gt;switch(oi){case 16777216:case 33554432:Gt=L.ansi[at],xe.push(`xterm-bg-${at}`);break;case 50331648:Gt=At.toColor(at>>16,at>>8&255,at&255),this._addStyle(U,`background-color:#${nh((at>>>0).toString(16),"0",6)}`);break;case 0:default:Ni?(Gt=L.foreground,xe.push("xterm-bg-257")):Gt=L.background}switch(qt||te.isDim()&&(qt=pt.multiplyOpacity(Gt,.5)),Ae){case 16777216:case 33554432:te.isBold()&&je<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(je+=8),this._applyMinimumContrast(U,Gt,L.ansi[je],te,qt,void 0)||xe.push(`xterm-fg-${je}`);break;case 50331648:let et=At.toColor(je>>16&255,je>>8&255,je&255);this._applyMinimumContrast(U,Gt,et,te,qt,ai)||this._addStyle(U,`color:#${nh(je.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(U,Gt,L.foreground,te,qt,ai)||Ni&&xe.push("xterm-fg-257")}xe.length&&(U.className=xe.join(" "),xe.length=0),!ct&&!oe&&!Mt&&A?Z++:U.textContent=_e,ze!==this.defaultSpacing&&(U.style.letterSpacing=`${ze}px`),k.push(U),f=Se}return U&&Z&&(U.textContent=_e),k}_applyMinimumContrast(e,t,i,n,a,h){if(this._optionsService.rawOptions.minimumContrastRatio===1||xg(n.getCode()))return!1;let d=this._getContrastCache(n),g;if(!a&&!h&&(g=d.getColor(t.rgba,i.rgba)),g===void 0){let v=this._optionsService.rawOptions.minimumContrastRatio/(n.isDim()?2:1);g=pt.ensureContrastRatio(a||t,h||i,v),d.setColor((a||t).rgba,(h||i).rgba,g??null)}return g?(this._addStyle(e,`color:${g.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 i=this._selectionStart,n=this._selectionEnd;return!i||!n?!1:this._columnSelectMode?i[0]<=n[0]?e>=i[0]&&t>=i[1]&&e<n[0]&&t<=n[1]:e<i[0]&&t>=i[1]&&e>=n[0]&&t<=n[1]:t>i[1]&&t<n[1]||i[1]===n[1]&&t===i[1]&&e>=i[0]&&e<n[0]||i[1]<n[1]&&t===n[1]&&e<n[0]||i[1]<n[1]&&t===i[1]&&e>=i[0]}};qo=xt([de(1,oc),de(2,Zt),de(3,Ii),de(4,ps),de(5,Tr),de(6,Ws)],qo);function nh(e,t,i){for(;e.length<i;)e=t+e;return e}var Eg=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 i=e.createElement("span");i.classList.add("xterm-char-measure-element");let n=e.createElement("span");n.classList.add("xterm-char-measure-element"),n.style.fontWeight="bold";let a=e.createElement("span");a.classList.add("xterm-char-measure-element"),a.style.fontStyle="italic";let h=e.createElement("span");h.classList.add("xterm-char-measure-element"),h.style.fontWeight="bold",h.style.fontStyle="italic",this._measureElements=[i,n,a,h],this._container.appendChild(i),this._container.appendChild(n),this._container.appendChild(a),this._container.appendChild(h),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,i,n){e===this._font&&t===this._fontSize&&i===this._weight&&n===this._weightBold||(this._font=e,this._fontSize=t,this._weight=i,this._weightBold=n,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${i}`,this._measureElements[1].style.fontWeight=`${n}`,this._measureElements[2].style.fontWeight=`${i}`,this._measureElements[3].style.fontWeight=`${n}`,this.clear())}get(e,t,i){let n=0;if(!t&&!i&&e.length===1&&(n=e.charCodeAt(0))<256){if(this._flat[n]!==-9999)return this._flat[n];let d=this._measure(e,0);return d>0&&(this._flat[n]=d),d}let a=e;t&&(a+="B"),i&&(a+="I");let h=this._holey.get(a);if(h===void 0){let d=0;t&&(d|=1),i&&(d|=2),h=this._measure(e,d),h>0&&this._holey.set(a,h)}return h}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},Rg=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,i,n=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1]){this.clear();return}let a=e.buffers.active.ydisp,h=t[1]-a,d=i[1]-a,g=Math.max(h,0),v=Math.min(d,e.rows-1);if(g>=e.rows||v<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=n,this.viewportStartRow=h,this.viewportEndRow=d,this.viewportCappedStartRow=g,this.viewportCappedEndRow=v,this.startCol=t[0],this.endCol=i[0]}isCellSelected(e,t,i){return this.hasSelection?(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t<this.endCol&&i<=this.viewportCappedEndRow:t<this.startCol&&i>=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol):!1}};function Ag(){return new Rg}var eo="xterm-dom-renderer-owner-",hi="xterm-rows",Yr="xterm-fg-",oh="xterm-bg-",ar="xterm-focus",Jr="xterm-selection",Mg=1,Go=class extends Ve{constructor(e,t,i,n,a,h,d,g,v,m,R,k,B,L){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=n,this._viewportElement=a,this._helperContainer=h,this._linkifier2=d,this._charSizeService=v,this._optionsService=m,this._bufferService=R,this._coreService=k,this._coreBrowserService=B,this._themeService=L,this._terminalClass=Mg++,this._rowElements=[],this._selectionRenderModel=Ag(),this.onRequestRedraw=this._register(new ee).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(hi),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(Jr),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=kg(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(P=>this._injectCss(P))),this._injectCss(this._themeService.colors),this._rowFactory=g.createInstance(qo,document),this._element.classList.add(eo+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(P=>this._handleLinkHover(P))),this._register(this._linkifier2.onHideLinkUnderline(P=>this._handleLinkLeave(P))),this._register(vt(()=>{this._element.classList.remove(eo+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new Eg(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 i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${hi} 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} .${hi} { 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} .${hi} .xterm-dim { color: ${pt.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 i=`blink_underline_${this._terminalClass}`,n=`blink_bar_${this._terminalClass}`,a=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${n} { 50% { box-shadow: none; }}`,t+=`@keyframes ${a} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${hi}.${ar} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${hi}.${ar} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${hi}.${ar} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${a} 1s step-end infinite;}${this._terminalSelector} .${hi} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${hi} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${hi} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${hi} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${hi} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Jr} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Jr} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Jr} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[h,d]of e.ansi.entries())t+=`${this._terminalSelector} .${Yr}${h} { color: ${d.css}; }${this._terminalSelector} .${Yr}${h}.xterm-dim { color: ${pt.multiplyOpacity(d,.5).css}; }${this._terminalSelector} .${oh}${h} { background-color: ${d.css}; }`;t+=`${this._terminalSelector} .${Yr}257 { color: ${pt.opaque(e.background).css}; }${this._terminalSelector} .${Yr}257.xterm-dim { color: ${pt.multiplyOpacity(pt.opaque(e.background),.5).css}; }${this._terminalSelector} .${oh}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 i=this._rowElements.length;i<=t;i++){let n=this._document.createElement("div");this._rowContainer.appendChild(n),this._rowElements.push(n)}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(ar),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ar),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let n=this._selectionRenderModel.viewportStartRow,a=this._selectionRenderModel.viewportEndRow,h=this._selectionRenderModel.viewportCappedStartRow,d=this._selectionRenderModel.viewportCappedEndRow,g=this._document.createDocumentFragment();if(i){let v=e[0]>t[0];g.appendChild(this._createSelectionElement(h,v?t[0]:e[0],v?e[0]:t[0],d-h+1))}else{let v=n===h?e[0]:0,m=h===a?t[0]:this._bufferService.cols;g.appendChild(this._createSelectionElement(h,v,m));let R=d-h-1;if(g.appendChild(this._createSelectionElement(h+1,0,this._bufferService.cols,R)),h!==d){let k=a===d?t[0]:this._bufferService.cols;g.appendChild(this._createSelectionElement(d,0,k))}}this._selectionContainer.appendChild(g)}_createSelectionElement(e,t,i,n=1){let a=this._document.createElement("div"),h=t*this.dimensions.css.cell.width,d=this.dimensions.css.cell.width*(i-t);return h+d>this.dimensions.css.canvas.width&&(d=this.dimensions.css.canvas.width-h),a.style.height=`${n*this.dimensions.css.cell.height}px`,a.style.top=`${e*this.dimensions.css.cell.height}px`,a.style.left=`${h}px`,a.style.width=`${d}px`,a}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 i=this._bufferService.buffer,n=i.ybase+i.y,a=Math.min(i.x,this._bufferService.cols-1),h=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,d=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,g=this._optionsService.rawOptions.cursorInactiveStyle;for(let v=e;v<=t;v++){let m=v+i.ydisp,R=this._rowElements[v],k=i.lines.get(m);if(!R||!k)break;R.replaceChildren(...this._rowFactory.createRow(k,m,m===n,d,g,a,h,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${eo}${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,i,n,a,h){i<0&&(e=0),n<0&&(t=0);let d=this._bufferService.rows-1;i=Math.max(Math.min(i,d),0),n=Math.max(Math.min(n,d),0),a=Math.min(a,this._bufferService.cols);let g=this._bufferService.buffer,v=g.ybase+g.y,m=Math.min(g.x,a-1),R=this._optionsService.rawOptions.cursorBlink,k=this._optionsService.rawOptions.cursorStyle,B=this._optionsService.rawOptions.cursorInactiveStyle;for(let L=i;L<=n;++L){let P=L+g.ydisp,U=this._rowElements[L],Z=g.lines.get(P);if(!U||!Z)break;U.replaceChildren(...this._rowFactory.createRow(Z,P,P===v,k,B,m,R,this.dimensions.css.cell.width,this._widthCache,h?L===i?e:0:-1,h?(L===n?t:a)-1:-1))}}};Go=xt([de(7,ga),de(8,vn),de(9,Zt),de(10,Xt),de(11,ps),de(12,Ii),de(13,Ws)],Go);var jo=class extends Ve{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new ee),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new Tg(this._optionsService))}catch{this._measureStrategy=this._register(new Og(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())}};jo=xt([de(2,Zt)],jo);var kc=class extends Ve{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)}},Og=class extends kc{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,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}},Tg=class extends kc{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}},Pg=class extends Ve{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new Lg(this._window)),this._onDprChange=this._register(new ee),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new ee),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(n=>this._screenDprMonitor.setWindow(n))),this._register(Ft.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Le(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Le(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}},Lg=class extends Ve{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new Us),this._onDprChange=this._register(new ee),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(vt(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Le(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)}},Bg=class extends Ve{constructor(){super(),this.linkProviders=[],this._register(vt(()=>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 Ca(e,t,i){let n=i.getBoundingClientRect(),a=e.getComputedStyle(i),h=parseInt(a.getPropertyValue("padding-left")),d=parseInt(a.getPropertyValue("padding-top"));return[t.clientX-n.left-h,t.clientY-n.top-d]}function Ig(e,t,i,n,a,h,d,g,v){if(!h)return;let m=Ca(e,t,i);if(m)return m[0]=Math.ceil((m[0]+(v?d/2:0))/d),m[1]=Math.ceil(m[1]/g),m[0]=Math.min(Math.max(m[0],1),n+(v?1:0)),m[1]=Math.min(Math.max(m[1],1),a),m}var $o=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,n,a){return Ig(window,e,t,i,n,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,a)}getMouseReportCoords(e,t){let i=Ca(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};$o=xt([de(0,Di),de(1,vn)],$o);var Dg=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,i){this._rowCount=i,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=[]}},Ec={};$f(Ec,{getSafariVersion:()=>Hg,isChromeOS:()=>Oc,isFirefox:()=>Rc,isIpad:()=>Ug,isIphone:()=>Wg,isLegacyEdge:()=>Ng,isLinux:()=>xa,isMac:()=>un,isNode:()=>yn,isSafari:()=>Ac,isWindows:()=>Mc});var yn=typeof process<"u"&&"title"in process,Pr=yn?"node":navigator.userAgent,Lr=yn?"node":navigator.platform,Rc=Pr.includes("Firefox"),Ng=Pr.includes("Edge"),Ac=/^((?!chrome|android).)*safari/i.test(Pr);function Hg(){if(!Ac)return 0;let e=Pr.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var un=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Lr),Ug=Lr==="iPad",Wg=Lr==="iPhone",Mc=["Windows","Win16","Win32","WinCE"].includes(Lr),xa=Lr.indexOf("Linux")>=0,Oc=/\bCrOS\b/.test(Pr),Tc=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,i=0,n=e.timeRemaining(),a=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),i=Math.max(t,i),a=e.timeRemaining(),i*1.5>a){n-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(n-t))}ms`),this._start();return}n=a}this.clear()}},Fg=class extends Tc{_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())}}},zg=class extends Tc{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},dn=!yn&&"requestIdleCallback"in window?zg:Fg,qg=class{constructor(){this._queue=new dn}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},Vo=class extends Ve{constructor(e,t,i,n,a,h,d,g,v){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=n,this._coreService=a,this._coreBrowserService=g,this._renderer=this._register(new Us),this._pausedResizeTask=new qg,this._observerDisposable=this._register(new Us),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 ee),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new ee),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new ee),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new ee),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new Dg((m,R)=>this._renderRows(m,R),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new Gg(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(vt(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(d.onResize(()=>this._fullRefresh())),this._register(d.buffers.onBufferActivate(()=>{var m;return(m=this._renderer.value)==null?void 0:m.clear()})),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(h.onDecorationRegistered(()=>this._fullRefresh())),this._register(h.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(d.cols,d.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(d.buffer.y,d.buffer.y,!0))),this._register(v.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(m=>this._registerIntersectionObserver(m,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(n=>this._handleIntersectionChange(n[n.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=vt(()=>i.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,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let n=this._syncOutputHandler.flush();n&&(e=Math.min(e,n.start),t=Math.max(t,n.end)),i||(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 i;return(i=this._renderer.value)==null?void 0:i.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,i){var n;this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,(n=this._renderer.value)==null||n.handleSelectionChanged(e,t,i)}handleCursorMove(){var e;(e=this._renderer.value)==null||e.handleCursorMove()}clear(){var e;(e=this._renderer.value)==null||e.clear()}};Vo=xt([de(2,Zt),de(3,vn),de(4,ps),de(5,Tr),de(6,Xt),de(7,Ii),de(8,Ws)],Vo);var Gg=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,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 jg(e,t,i,n){let a=i.buffer.x,h=i.buffer.y;if(!i.buffer.hasScrollback)return Kg(a,h,e,t,i,n)+Sn(h,t,i,n)+Yg(a,h,e,t,i,n);let d;if(h===t)return d=a>e?"D":"C",xr(Math.abs(a-e),Cr(d,n));d=h>t?"D":"C";let g=Math.abs(h-t),v=Vg(h>t?e:a,i)+(g-1)*i.cols+1+$g(h>t?a:e);return xr(v,Cr(d,n))}function $g(e,t){return e-1}function Vg(e,t){return t.cols-e}function Kg(e,t,i,n,a,h){return Sn(t,n,a,h).length===0?"":xr(Lc(e,t,e,t-gs(t,a),!1,a).length,Cr("D",h))}function Sn(e,t,i,n){let a=e-gs(e,i),h=t-gs(t,i),d=Math.abs(a-h)-Jg(e,t,i);return xr(d,Cr(Pc(e,t),n))}function Yg(e,t,i,n,a,h){let d;Sn(t,n,a,h).length>0?d=n-gs(n,a):d=t;let g=n,v=Xg(e,t,i,n,a,h);return xr(Lc(e,d,i,g,v==="C",a).length,Cr(v,h))}function Jg(e,t,i){var d;let n=0,a=e-gs(e,i),h=t-gs(t,i);for(let g=0;g<Math.abs(a-h);g++){let v=Pc(e,t)==="A"?-1:1;(d=i.buffer.lines.get(a+v*g))!=null&&d.isWrapped&&n++}return n}function gs(e,t){let i=0,n=t.buffer.lines.get(e),a=n==null?void 0:n.isWrapped;for(;a&&e>=0&&e<t.rows;)i++,n=t.buffer.lines.get(--e),a=n==null?void 0:n.isWrapped;return i}function Xg(e,t,i,n,a,h){let d;return Sn(i,n,a,h).length>0?d=n-gs(n,a):d=t,e<i&&d<=n||e>=i&&d<n?"C":"D"}function Pc(e,t){return e>t?"A":"B"}function Lc(e,t,i,n,a,h){let d=e,g=t,v="";for(;(d!==i||g!==n)&&g>=0&&g<h.buffer.lines.length;)d+=a?1:-1,a&&d>h.cols-1?(v+=h.buffer.translateBufferLineToString(g,!1,e,d),d=0,e=0,g++):!a&&d<0&&(v+=h.buffer.translateBufferLineToString(g,!1,0,e+1),d=h.cols-1,e=d,g--);return v+h.buffer.translateBufferLineToString(g,!1,e,d)}function Cr(e,t){let i=t?"O":"[";return V.ESC+i+e}function xr(e,t){e=Math.floor(e);let i="";for(let n=0;n<e;n++)i+=t;return i}var Zg=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 ah(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 to=50,Qg=15,ep=50,tp=500,ip=" ",sp=new RegExp(ip,"g"),Ko=class extends Ve{constructor(e,t,i,n,a,h,d,g,v){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=n,this._coreService=a,this._mouseService=h,this._optionsService=d,this._renderService=g,this._coreBrowserService=v,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new di,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new ee),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new ee),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new ee),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new ee),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=m=>this._handleMouseMove(m),this._mouseUpListener=m=>this._handleMouseUp(m),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(m=>this._handleTrim(m)),this._register(this._bufferService.buffers.onBufferActivate(m=>this._handleBufferActivate(m))),this.enable(),this._model=new Zg(this._bufferService),this._activeSelectionMode=0,this._register(vt(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(m=>{m.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 i=this._bufferService.buffer,n=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let a=e[0]<t[0]?e[0]:t[0],h=e[0]<t[0]?t[0]:e[0];for(let d=e[1];d<=t[1];d++){let g=i.translateBufferLineToString(d,!0,a,h);n.push(g)}}else{let a=e[1]===t[1]?t[0]:void 0;n.push(i.translateBufferLineToString(e[1],!0,e[0],a));for(let h=e[1]+1;h<=t[1]-1;h++){let d=i.lines.get(h),g=i.translateBufferLineToString(h,!0);d!=null&&d.isWrapped?n[n.length-1]+=g:n.push(g)}if(e[1]!==t[1]){let h=i.lines.get(t[1]),d=i.translateBufferLineToString(t[1],!0,0,t[0]);h&&h.isWrapped?n[n.length-1]+=d:n.push(d)}}return n.map(a=>a.replace(sp," ")).join(Mc?`\r
36
36
  `:`
37
- `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),xa&&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),i=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!i||!n||!t?!1:this._areCoordsInSelection(t,i,n)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!i||!n?!1:this._areCoordsInSelection([e,t],i,n)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]<i[1]||t[1]===i[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<i[0]||t[1]<i[1]&&e[1]===i[1]&&e[0]<i[0]||t[1]<i[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){var a,h;let i=(h=(a=this._linkifier.currentLink)==null?void 0:a.link)==null?void 0:h.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=ah(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let n=this._getMouseBufferCoords(e);return n?(this._selectWordAt(n,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=Ca(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-to),to),t/=to,t/Math.abs(t)+Math.round(t*(Qg-1)))}shouldForceSelection(e){return un?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(),ep)}_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&&!(un&&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 i=this._bufferService.buffer;if(this._model.selectionEnd[1]<i.lines.length){let n=i.lines.get(this._model.selectionEnd[1]);n&&n.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<tp&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let i=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(i&&i[0]!==void 0&&i[1]!==void 0){let n=jg(i[0]-1,i[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(n,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,i=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);if(!i){this._oldHasSelection&&this._fireOnSelectionChange(e,t,i);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,i)}_fireOnSelectionChange(e,t,i){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=i,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(t=>this._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let n=0;t>=n;n++){let a=e.loadCell(n,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:a>1&&t!==n&&(i+=a-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,n=!0){if(e[0]>=this._bufferService.cols)return;let a=this._bufferService.buffer,h=a.lines.get(e[1]);if(!h)return;let d=a.translateBufferLineToString(e[1],!1),g=this._convertViewportColToCharacterIndex(h,e[0]),v=g,p=e[0]-g,R=0,k=0,B=0,L=0;if(d.charAt(g)===" "){for(;g>0&&d.charAt(g-1)===" ";)g--;for(;v<d.length&&d.charAt(v+1)===" ";)v++}else{let Z=e[0],_e=e[0];h.getWidth(Z)===0&&(R++,Z--),h.getWidth(_e)===2&&(k++,_e++);let rt=h.getString(_e).length;for(rt>1&&(L+=rt-1,v+=rt-1);Z>0&&g>0&&!this._isCharWordSeparator(h.loadCell(Z-1,this._workCell));){h.loadCell(Z-1,this._workCell);let Ne=this._workCell.getChars().length;this._workCell.getWidth()===0?(R++,Z--):Ne>1&&(B+=Ne-1,g-=Ne-1),g--,Z--}for(;_e<h.length&&v+1<d.length&&!this._isCharWordSeparator(h.loadCell(_e+1,this._workCell));){h.loadCell(_e+1,this._workCell);let Ne=this._workCell.getChars().length;this._workCell.getWidth()===2?(k++,_e++):Ne>1&&(L+=Ne-1,v+=Ne-1),v++,_e++}}v++;let P=g+p-R+B,U=Math.min(this._bufferService.cols,v-g+R+k-B-L);if(!(!t&&d.slice(g,v).trim()==="")){if(i&&P===0&&h.getCodePoint(0)!==32){let Z=a.lines.get(e[1]-1);if(Z&&h.isWrapped&&Z.getCodePoint(this._bufferService.cols-1)!==32){let _e=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(_e){let rt=this._bufferService.cols-_e.start;P-=rt,U+=rt}}}if(n&&P+U===this._bufferService.cols&&h.getCodePoint(this._bufferService.cols-1)!==32){let Z=a.lines.get(e[1]+1);if(Z!=null&&Z.isWrapped&&Z.getCodePoint(0)!==32){let _e=this._getWordAt([0,e[1]+1],!1,!1,!0);_e&&(U+=_e.length)}}return{start:P,length:U}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={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=ah(i,this._bufferService.cols)}};Ko=xt([de(3,Xt),de(4,ps),de(5,pa),de(6,Zt),de(7,Di),de(8,Ii)],Ko);var lh=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},hh=class{constructor(){this._color=new lh,this._css=new lh}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Tt=Object.freeze((()=>{let e=[St.toColor("#2e3436"),St.toColor("#cc0000"),St.toColor("#4e9a06"),St.toColor("#c4a000"),St.toColor("#3465a4"),St.toColor("#75507b"),St.toColor("#06989a"),St.toColor("#d3d7cf"),St.toColor("#555753"),St.toColor("#ef2929"),St.toColor("#8ae234"),St.toColor("#fce94f"),St.toColor("#729fcf"),St.toColor("#ad7fa8"),St.toColor("#34e2e2"),St.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let n=t[i/36%6|0],a=t[i/6%6|0],h=t[i%6];e.push({css:At.toCss(n,a,h),rgba:At.toRgba(n,a,h)})}for(let i=0;i<24;i++){let n=8+i*10;e.push({css:At.toCss(n,n,n),rgba:At.toRgba(n,n,n)})}return e})()),hs=St.toColor("#ffffff"),pr=St.toColor("#000000"),ch=St.toColor("#ffffff"),uh=pr,lr={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},rp=hs,Yo=class extends Ve{constructor(e){super(),this._optionsService=e,this._contrastCache=new hh,this._halfContrastCache=new hh,this._onChangeColors=this._register(new ee),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:hs,background:pr,cursor:ch,cursorAccent:uh,selectionForeground:void 0,selectionBackgroundTransparent:lr,selectionBackgroundOpaque:pt.blend(pr,lr),selectionInactiveBackgroundTransparent:lr,selectionInactiveBackgroundOpaque:pt.blend(pr,lr),scrollbarSliderBackground:pt.opacity(hs,.2),scrollbarSliderHoverBackground:pt.opacity(hs,.4),scrollbarSliderActiveBackground:pt.opacity(hs,.5),overviewRulerBorder:hs,ansi:Tt.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=ht(e.foreground,hs),t.background=ht(e.background,pr),t.cursor=pt.blend(t.background,ht(e.cursor,ch)),t.cursorAccent=pt.blend(t.background,ht(e.cursorAccent,uh)),t.selectionBackgroundTransparent=ht(e.selectionBackground,lr),t.selectionBackgroundOpaque=pt.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=ht(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=pt.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?ht(e.selectionForeground,rh):void 0,t.selectionForeground===rh&&(t.selectionForeground=void 0),pt.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=pt.opacity(t.selectionBackgroundTransparent,.3)),pt.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=pt.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=ht(e.scrollbarSliderBackground,pt.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=ht(e.scrollbarSliderHoverBackground,pt.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=ht(e.scrollbarSliderActiveBackground,pt.opacity(t.foreground,.5)),t.overviewRulerBorder=ht(e.overviewRulerBorder,rp),t.ansi=Tt.slice(),t.ansi[0]=ht(e.black,Tt[0]),t.ansi[1]=ht(e.red,Tt[1]),t.ansi[2]=ht(e.green,Tt[2]),t.ansi[3]=ht(e.yellow,Tt[3]),t.ansi[4]=ht(e.blue,Tt[4]),t.ansi[5]=ht(e.magenta,Tt[5]),t.ansi[6]=ht(e.cyan,Tt[6]),t.ansi[7]=ht(e.white,Tt[7]),t.ansi[8]=ht(e.brightBlack,Tt[8]),t.ansi[9]=ht(e.brightRed,Tt[9]),t.ansi[10]=ht(e.brightGreen,Tt[10]),t.ansi[11]=ht(e.brightYellow,Tt[11]),t.ansi[12]=ht(e.brightBlue,Tt[12]),t.ansi[13]=ht(e.brightMagenta,Tt[13]),t.ansi[14]=ht(e.brightCyan,Tt[14]),t.ansi[15]=ht(e.brightWhite,Tt[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let n=0;n<i;n++)t.ansi[n+16]=ht(e.extendedAnsi[n],Tt[n+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()}}};Yo=xt([de(0,Zt)],Yo);function ht(e,t){if(e!==void 0)try{return St.toColor(e)}catch{}return t}var np=class{constructor(...e){this._entries=new Map;for(let[t,i]of e)this.set(t,i)}set(e,t){let i=this._entries.get(e);return this._entries.set(e,t),i}forEach(e){for(let[t,i]of this._entries.entries())e(t,i)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},op=class{constructor(){this._services=new np,this._services.set(ga,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let i=Qf(e).sort((h,d)=>h.index-d.index),n=[];for(let h of i){let d=this._services.get(h.id);if(!d)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${h.id._id}.`);n.push(d)}let a=i.length>0?i[0].index:t.length;if(t.length!==a)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${a+1} conflicts with ${t.length} static arguments`);return new e(...t,...n)}},ap={trace:0,debug:1,info:2,warn:3,error:4,off:5},lp="xterm.js: ",Jo=class extends Ve{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=ap[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,i){this._evalLazyOptionalParams(i),e.call(console,(this._optionsService.options.logger?"":lp)+t,...i)}trace(e,...t){var i;this._logLevel<=0&&this._log(((i=this._optionsService.options.logger)==null?void 0:i.trace.bind(this._optionsService.options.logger))??console.log,e,t)}debug(e,...t){var i;this._logLevel<=1&&this._log(((i=this._optionsService.options.logger)==null?void 0:i.debug.bind(this._optionsService.options.logger))??console.log,e,t)}info(e,...t){var i;this._logLevel<=2&&this._log(((i=this._optionsService.options.logger)==null?void 0:i.info.bind(this._optionsService.options.logger))??console.info,e,t)}warn(e,...t){var i;this._logLevel<=3&&this._log(((i=this._optionsService.options.logger)==null?void 0:i.warn.bind(this._optionsService.options.logger))??console.warn,e,t)}error(e,...t){var i;this._logLevel<=4&&this._log(((i=this._optionsService.options.logger)==null?void 0:i.error.bind(this._optionsService.options.logger))??console.error,e,t)}};Jo=xt([de(0,Zt)],Jo);var dh=class extends Ve{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new ee),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new ee),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new ee),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 i=0;i<Math.min(e,this.length);i++)t[i]=this._array[this._getCyclicIndex(i)];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,...i){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let n=this._length-1;n>=e;n--)this._array[this._getCyclicIndex(n+i.length)]=this._array[this._getCyclicIndex(n)];for(let n=0;n<i.length;n++)this._array[this._getCyclicIndex(e+n)]=i[n];if(i.length&&this.onInsertEmitter.fire({index:e,amount:i.length}),this._length+i.length>this._maxLength){let n=this._length+i.length-this._maxLength;this._startIndex+=n,this._length=this._maxLength,this.onTrimEmitter.fire(n)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let a=t-1;a>=0;a--)this.set(e+a+i,this.get(e+a));let n=e+t+i-this._length;if(n>0)for(this._length+=n;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let n=0;n<t;n++)this.set(e+n+i,this.get(e+n))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},$e=3,Rt=Object.freeze(new Or),Xr=0,io=2,mr=class Bc{constructor(t,i,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(t*$e);let a=i||di.fromCharData([0,Qh,1,0]);for(let h=0;h<t;++h)this.setCell(h,a);this.length=t}get(t){let i=this._data[t*$e+0],n=i&2097151;return[this._data[t*$e+1],i&2097152?this._combined[t]:n?es(n):"",i>>22,i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):n]}set(t,i){this._data[t*$e+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*$e+0]=t|2097152|i[2]<<22):this._data[t*$e+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*$e+0]>>22}hasWidth(t){return this._data[t*$e+0]&12582912}getFg(t){return this._data[t*$e+1]}getBg(t){return this._data[t*$e+2]}hasContent(t){return this._data[t*$e+0]&4194303}getCodePoint(t){let i=this._data[t*$e+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*$e+0]&2097152}getString(t){let i=this._data[t*$e+0];return i&2097152?this._combined[t]:i&2097151?es(i&2097151):""}isProtected(t){return this._data[t*$e+2]&536870912}loadCell(t,i){return Xr=t*$e,i.content=this._data[Xr+0],i.fg=this._data[Xr+1],i.bg=this._data[Xr+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*$e+0]=i.content,this._data[t*$e+1]=i.fg,this._data[t*$e+2]=i.bg}setCellFromCodepoint(t,i,n,a){a.bg&268435456&&(this._extendedAttrs[t]=a.extended),this._data[t*$e+0]=i|n<<22,this._data[t*$e+1]=a.fg,this._data[t*$e+2]=a.bg}addCodepointToCell(t,i,n){let a=this._data[t*$e+0];a&2097152?this._combined[t]+=es(i):a&2097151?(this._combined[t]=es(a&2097151)+es(i),a&=-2097152,a|=2097152):a=i|1<<22,n&&(a&=-12582913,a|=n<<22),this._data[t*$e+0]=a}insertCells(t,i,n){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,n),i<this.length-t){let a=new di;for(let h=this.length-t-i-1;h>=0;--h)this.setCell(t+i+h,this.loadCell(t+h,a));for(let h=0;h<i;++h)this.setCell(t+h,n)}else for(let a=t;a<this.length;++a)this.setCell(a,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(t,i,n){if(t%=this.length,i<this.length-t){let a=new di;for(let h=0;h<this.length-t-i;++h)this.setCell(t+h,this.loadCell(t+i+h,a));for(let h=this.length-i;h<this.length;++h)this.setCell(h,n)}else for(let a=t;a<this.length;++a)this.setCell(a,n);t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,n),this.getWidth(t)===0&&!this.hasContent(t)&&this.setCellFromCodepoint(t,0,1,n)}replaceCells(t,i,n,a=!1){if(a){for(t&&this.getWidth(t-1)===2&&!this.isProtected(t-1)&&this.setCellFromCodepoint(t-1,0,1,n),i<this.length&&this.getWidth(i-1)===2&&!this.isProtected(i)&&this.setCellFromCodepoint(i,0,1,n);t<i&&t<this.length;)this.isProtected(t)||this.setCell(t,n),t++;return}for(t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,n),i<this.length&&this.getWidth(i-1)===2&&this.setCellFromCodepoint(i,0,1,n);t<i&&t<this.length;)this.setCell(t++,n)}resize(t,i){if(t===this.length)return this._data.length*4*io<this._data.buffer.byteLength;let n=t*$e;if(t>this.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let a=new Uint32Array(n);a.set(this._data),this._data=a}for(let a=this.length;a<t;++a)this.setCell(a,i)}else{this._data=this._data.subarray(0,n);let a=Object.keys(this._combined);for(let d=0;d<a.length;d++){let g=parseInt(a[d],10);g>=t&&delete this._combined[g]}let h=Object.keys(this._extendedAttrs);for(let d=0;d<h.length;d++){let g=parseInt(h[d],10);g>=t&&delete this._extendedAttrs[g]}}return this.length=t,n*4*io<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*io<this._data.buffer.byteLength){let t=new Uint32Array(this._data.length);return t.set(this._data),this._data=t,1}return 0}fill(t,i=!1){if(i){for(let n=0;n<this.length;++n)this.isProtected(n)||this.setCell(n,t);return}this._combined={},this._extendedAttrs={};for(let n=0;n<this.length;++n)this.setCell(n,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 i in t._combined)this._combined[i]=t._combined[i];this._extendedAttrs={};for(let i in t._extendedAttrs)this._extendedAttrs[i]=t._extendedAttrs[i];this.isWrapped=t.isWrapped}clone(){let t=new Bc(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let i in this._combined)t._combined[i]=this._combined[i];for(let i in this._extendedAttrs)t._extendedAttrs[i]=this._extendedAttrs[i];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*$e+0]&4194303)return t+(this._data[t*$e+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*$e+0]&4194303||this._data[t*$e+2]&50331648)return t+(this._data[t*$e+0]>>22);return 0}copyCellsFrom(t,i,n,a,h){let d=t._data;if(h)for(let v=a-1;v>=0;v--){for(let p=0;p<$e;p++)this._data[(n+v)*$e+p]=d[(i+v)*$e+p];d[(i+v)*$e+2]&268435456&&(this._extendedAttrs[n+v]=t._extendedAttrs[i+v])}else for(let v=0;v<a;v++){for(let p=0;p<$e;p++)this._data[(n+v)*$e+p]=d[(i+v)*$e+p];d[(i+v)*$e+2]&268435456&&(this._extendedAttrs[n+v]=t._extendedAttrs[i+v])}let g=Object.keys(t._combined);for(let v=0;v<g.length;v++){let p=parseInt(g[v],10);p>=i&&(this._combined[p-i+n]=t._combined[p])}}translateToString(t,i,n,a){i=i??0,n=n??this.length,t&&(n=Math.min(n,this.getTrimmedLength())),a&&(a.length=0);let h="";for(;i<n;){let d=this._data[i*$e+0],g=d&2097151,v=d&2097152?this._combined[i]:g?es(g):ts;if(h+=v,a)for(let p=0;p<v.length;++p)a.push(i);i+=d>>22||1}return a&&a.push(i),h}};function hp(e,t,i,n,a,h){let d=[];for(let g=0;g<e.length-1;g++){let v=g,p=e.get(++v);if(!p.isWrapped)continue;let R=[e.get(g)];for(;v<e.length&&p.isWrapped;)R.push(p),p=e.get(++v);if(!h&&n>=g&&n<v){g+=R.length-1;continue}let k=0,B=kr(R,k,t),L=1,P=0;for(;L<R.length;){let Z=kr(R,L,t),_e=Z-P,rt=i-B,Ne=Math.min(_e,rt);R[k].copyCellsFrom(R[L],P,B,Ne,!1),B+=Ne,B===i&&(k++,B=0),P+=Ne,P===Z&&(L++,P=0),B===0&&k!==0&&R[k-1].getWidth(i-1)===2&&(R[k].copyCellsFrom(R[k-1],i-1,B++,1,!1),R[k-1].setCell(i-1,a))}R[k].replaceCells(B,i,a);let U=0;for(let Z=R.length-1;Z>0&&(Z>k||R[Z].getTrimmedLength()===0);Z--)U++;U>0&&(d.push(g+R.length-U),d.push(U)),g+=R.length-1}return d}function cp(e,t){let i=[],n=0,a=t[n],h=0;for(let d=0;d<e.length;d++)if(a===d){let g=t[++n];e.onDeleteEmitter.fire({index:d-h,amount:g}),d+=g-1,h+=g,a=t[++n]}else i.push(d);return{layout:i,countRemoved:h}}function up(e,t){let i=[];for(let n=0;n<t.length;n++)i.push(e.get(t[n]));for(let n=0;n<i.length;n++)e.set(n,i[n]);e.length=t.length}function dp(e,t,i){let n=[],a=e.map((v,p)=>kr(e,p,t)).reduce((v,p)=>v+p),h=0,d=0,g=0;for(;g<a;){if(a-g<i){n.push(a-g);break}h+=i;let v=kr(e,d,t);h>v&&(h-=v,d++);let p=e[d].getWidth(h-1)===2;p&&h--;let R=p?i-1:i;n.push(R),g+=R}return n}function kr(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let n=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,a=e[t+1].getWidth(0)===2;return n&&a?i-1:i}var Ic=class Dc{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=Dc._nextId++,this._onDispose=this.register(new ee),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),_s(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};Ic._nextId=1;var fp=Ic,Lt={},cs=Lt.B;Lt[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:"≥","{":"π","|":"≠","}":"£","~":"·"};Lt.A={"#":"£"};Lt.B=void 0;Lt[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Lt.C=Lt[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Lt.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Lt.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Lt.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Lt.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Lt.E=Lt[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Lt.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Lt.H=Lt[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Lt["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var fh=4294967295,_h=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Rt.clone(),this.savedCharset=cs,this.markers=[],this._nullCell=di.fromCharData([0,Qh,1,0]),this._whitespaceCell=di.fromCharData([0,ts,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new dn,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new dh(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 ln),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 ln),this._whitespaceCell}getBlankLine(e,t){return new mr(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>fh?fh:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Rt);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 dh(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Rt),n=0,a=this._getCorrectBufferLength(t);if(a>this.lines.maxLength&&(this.lines.maxLength=a),this.lines.length>0){if(this._cols<e)for(let d=0;d<this.lines.length;d++)n+=+this.lines.get(d).resize(e,i);let h=0;if(this._rows<t)for(let d=this._rows;d<t;d++)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 mr(e,i)):this.ybase>0&&this.lines.length<=this.ybase+this.y+h+1?(this.ybase--,h++,this.ydisp>0&&this.ydisp--):this.lines.push(new mr(e,i)));else for(let d=this._rows;d>t;d--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(a<this.lines.maxLength){let d=this.lines.length-a;d>0&&(this.lines.trimStart(d),this.ybase=Math.max(this.ybase-d,0),this.ydisp=Math.max(this.ydisp-d,0),this.savedY=Math.max(this.savedY-d,0)),this.lines.maxLength=a}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),h&&(this.y+=h),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 h=0;h<this.lines.length;h++)n+=+this.lines.get(h).resize(e,i);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),n>.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 i=this._optionsService.rawOptions.reflowCursorLine,n=hp(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Rt),i);if(n.length>0){let a=cp(this.lines,n);up(this.lines,a.layout),this._reflowLargerAdjustViewport(e,t,a.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let n=this.getNullCell(Rt),a=i;for(;a-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new mr(e,n))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-i,0)}_reflowSmaller(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,n=this.getNullCell(Rt),a=[],h=0;for(let d=this.lines.length-1;d>=0;d--){let g=this.lines.get(d);if(!g||!g.isWrapped&&g.getTrimmedLength()<=e)continue;let v=[g];for(;g.isWrapped&&d>0;)g=this.lines.get(--d),v.unshift(g);if(!i){let Ne=this.ybase+this.y;if(Ne>=d&&Ne<d+v.length)continue}let p=v[v.length-1].getTrimmedLength(),R=dp(v,this._cols,e),k=R.length-v.length,B;this.ybase===0&&this.y!==this.lines.length-1?B=Math.max(0,this.y-this.lines.maxLength+k):B=Math.max(0,this.lines.length-this.lines.maxLength+k);let L=[];for(let Ne=0;Ne<k;Ne++){let H=this.getBlankLine(Rt,!0);L.push(H)}L.length>0&&(a.push({start:d+v.length+h,newLines:L}),h+=L.length),v.push(...L);let P=R.length-1,U=R[P];U===0&&(P--,U=R[P]);let Z=v.length-k-1,_e=p;for(;Z>=0;){let Ne=Math.min(_e,U);if(v[P]===void 0)break;if(v[P].copyCellsFrom(v[Z],_e-Ne,U-Ne,Ne,!0),U-=Ne,U===0&&(P--,U=R[P]),_e-=Ne,_e===0){Z--;let H=Math.max(Z,0);_e=kr(v,H,this._cols)}}for(let Ne=0;Ne<v.length;Ne++)R[Ne]<e&&v[Ne].setCell(R[Ne],n);let rt=k-B;for(;rt-- >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+h)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+k,this.ybase+t-1)}if(a.length>0){let d=[],g=[];for(let U=0;U<this.lines.length;U++)g.push(this.lines.get(U));let v=this.lines.length,p=v-1,R=0,k=a[R];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+h);let B=0;for(let U=Math.min(this.lines.maxLength-1,v+h-1);U>=0;U--)if(k&&k.start>p+B){for(let Z=k.newLines.length-1;Z>=0;Z--)this.lines.set(U--,k.newLines[Z]);U++,d.push({index:p+1,amount:k.newLines.length}),B+=k.newLines.length,k=a[++R]}else this.lines.set(U,g[p--]);let L=0;for(let U=d.length-1;U>=0;U--)d[U].index+=L,this.lines.onInsertEmitter.fire(d[U]),L+=d[U].amount;let P=Math.max(0,v+h-this.lines.maxLength);P>0&&this.lines.onTrimEmitter.fire(P)}}translateBufferLineToString(e,t,i=0,n){let a=this.lines.get(e);return a?a.translateToString(t,i,n):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+1<this.lines.length&&this.lines.get(i+1).isWrapped;)i++;return{first:t,last:i}}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 fp(e);return this.markers.push(t),t.register(this.lines.onTrim(i=>{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.line<i.index+i.amount&&t.dispose(),t.line>i.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},_p=class extends Ve{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new ee),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 _h(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new _h(!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)}},Nc=2,Hc=1,Xo=class extends Ve{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new ee),this.onResize=this._onResize.event,this._onScroll=this._register(new ee),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Nc),this.rows=Math.max(e.rawOptions.rows||0,Hc),this.buffers=this._register(new _p(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,n=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:n})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,n;n=this._cachedBlankLine,(!n||n.length!==this.cols||n.getFg(0)!==e.fg||n.getBg(0)!==e.bg)&&(n=i.getBlankLine(e,t),this._cachedBlankLine=n),n.isWrapped=t;let a=i.ybase+i.scrollTop,h=i.ybase+i.scrollBottom;if(i.scrollTop===0){let d=i.lines.isFull;h===i.lines.length-1?d?i.lines.recycle().copyFrom(n):i.lines.push(n.clone()):i.lines.splice(h+1,0,n.clone()),d?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let d=h-a+1;i.lines.shiftElements(a+1,d-1,-1),i.lines.set(h,n.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let n=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),n!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};Xo=xt([de(0,Zt)],Xo);var Ps={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:un,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},gp=["normal","bold","100","200","300","400","500","600","700","800","900"],pp=class extends Ve{constructor(e){super(),this._onOptionChange=this._register(new ee),this.onOptionChange=this._onOptionChange.event;let t={...Ps};for(let i in e)if(i in t)try{let n=e[i];t[i]=this._sanitizeAndValidateOption(i,n)}catch(n){console.error(n)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(vt(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in Ps))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,n)=>{if(!(i in Ps))throw new Error(`No option with key "${i}"`);n=this._sanitizeAndValidateOption(i,n),this.rawOptions[i]!==n&&(this.rawOptions[i]=n,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let n={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,n)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=Ps[e]),!mp(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Ps[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=gp.includes(t)?t:Ps[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 mp(e){return e==="block"||e==="underline"||e==="bar"}function vr(e,t=5){if(typeof e!="object")return e;let i=Array.isArray(e)?[]:{};for(let n in e)i[n]=t<=1?e[n]:e[n]&&vr(e[n],t-1);return i}var gh=Object.freeze({insertMode:!1}),ph=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),Zo=class extends Ve{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new ee),this.onData=this._onData.event,this._onUserInput=this._register(new ee),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new ee),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new ee),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=vr(gh),this.decPrivateModes=vr(ph)}reset(){this.modes=vr(gh),this.decPrivateModes=vr(ph)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(n=>n.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))}};Zo=xt([de(0,Xt),de(1,rc),de(2,Zt)],Zo);var mh={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 so(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}var ro=String.fromCharCode,vh={DEFAULT:e=>{let t=[so(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${ro(t[0])}${ro(t[1])}${ro(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${so(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${so(e,!0)};${e.x};${e.y}${t}`}},Qo=class extends Ve{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new ee),this.onProtocolChange=this._onProtocolChange.event;for(let n of Object.keys(mh))this.addProtocol(n,mh[n]);for(let n of Object.keys(vh))this.addEncoding(n,vh[n]);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,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let n=t/i,a=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(a/=n+0,Math.abs(e.deltaY)<50&&(a*=.3),this._wheelPartialScroll+=a,a=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(a*=this._bufferService.rows),a}_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,i){if(i){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)}};Qo=xt([de(0,Xt),de(1,ps),de(2,Zt)],Qo);var no=[[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]],vp=[[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]],Pt;function yp(e,t){let i=0,n=t.length-1,a;if(e<t[0][0]||e>t[n][1])return!1;for(;n>=i;)if(a=i+n>>1,e>t[a][1])i=a+1;else if(e<t[a][0])n=a-1;else return!0;return!1}var Sp=class{constructor(){if(this.version="6",!Pt){Pt=new Uint8Array(65536),Pt.fill(1),Pt[0]=0,Pt.fill(0,1,32),Pt.fill(0,127,160),Pt.fill(2,4352,4448),Pt[9001]=2,Pt[9002]=2,Pt.fill(2,11904,42192),Pt[12351]=1,Pt.fill(2,44032,55204),Pt.fill(2,63744,64256),Pt.fill(2,65040,65050),Pt.fill(2,65072,65136),Pt.fill(2,65280,65377),Pt.fill(2,65504,65511);for(let e=0;e<no.length;++e)Pt.fill(0,no[e][0],no[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?Pt[e]:yp(e,vp)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),n=i===0&&t!==0;if(n){let a=us.extractWidth(t);a===0?n=!1:a>i&&(i=a)}return us.createPropertyValue(0,i,n)}},us=class on{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new ee,this.onChange=this._onChange.event;let t=new Sp;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,i,n=!1){return(t&16777215)<<3|(i&3)<<1|(n?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 i=0,n=0,a=t.length;for(let h=0;h<a;++h){let d=t.charCodeAt(h);if(55296<=d&&d<=56319){if(++h>=a)return i+this.wcwidth(d);let p=t.charCodeAt(h);56320<=p&&p<=57343?d=(d-55296)*1024+p-56320+65536:i+=this.wcwidth(p)}let g=this.charProperties(d,n),v=on.extractWidth(g);on.extractShouldJoin(g)&&(v-=on.extractWidth(n)),i+=v,n=g}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},bp=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 yh(e){var n;let t=(n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1))==null?void 0:n.get(e.cols-1),i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);i&&t&&(i.isWrapped=t[3]!==0&&t[3]!==32)}var hr=2147483647,wp=256,Uc=class ea{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>wp)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new ea;if(!t.length)return i;for(let n=Array.isArray(t[0])?1:0;n<t.length;++n){let a=t[n];if(Array.isArray(a))for(let h=0;h<a.length;++h)i.addSubParam(a[h]);else i.addParam(a)}return i}clone(){let t=new ea(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 i=0;i<this.length;++i){t.push(this.params[i]);let n=this._subParamsIdx[i]>>8,a=this._subParamsIdx[i]&255;a-n>0&&t.push(Array.prototype.slice.call(this._subParams,n,a))}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>hr?hr: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>hr?hr:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,n=this._subParamsIdx[t]&255;return n-i>0?this._subParams.subarray(i,n):null}getSubParamsAll(){let t={};for(let i=0;i<this.length;++i){let n=this._subParamsIdx[i]>>8,a=this._subParamsIdx[i]&255;a-n>0&&(t[i]=this._subParams.slice(n,a))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,a=n[i-1];n[i-1]=~a?Math.min(a*10+t,hr):t}},cr=[],Cp=class{constructor(){this._state=0,this._active=cr,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 i=this._handlers[e];return i.push(t),{dispose:()=>{let n=i.indexOf(t);n!==-1&&i.splice(n,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=cr}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=cr,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||cr,!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,i){if(!this._active.length)this._handlerFb(this._id,"PUT",mn(e,t,i));else for(let n=this._active.length-1;n>=0;n--)this._active[n].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t<i;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+n-48}this._state===2&&i-t>0&&this._put(e,t,i)}}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 i=!1,n=this._active.length-1,a=!1;if(this._stack.paused&&(n=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;n>=0&&(i=this._active[n].end(e),i!==!0);n--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!1,i;n--}for(;n>=0;n--)if(i=this._active[n].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!0,i}this._active=cr,this._id=-1,this._state=0}}},ni=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=mn(e,t,i),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(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,t}},ur=[],xp=class{constructor(){this._handlers=Object.create(null),this._active=ur,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=ur}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let n=i.indexOf(t);n!==-1&&i.splice(n,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=ur,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||ur,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",mn(e,t,i));else for(let n=this._active.length-1;n>=0;n--)this._active[n].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let i=!1,n=this._active.length-1,a=!1;if(this._stack.paused&&(n=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;n>=0&&(i=this._active[n].unhook(e),i!==!0);n--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!1,i;n--}for(;n>=0;n--)if(i=this._active[n].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!0,i}this._active=ur,this._ident=0}},yr=new Uc;yr.addParam(0);var Sh=class{constructor(e){this._handler=e,this._data="",this._params=yr,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():yr,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=mn(e,t,i),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(i=>(this._params=yr,this._data="",this._hitLimit=!1,i));return this._params=yr,this._data="",this._hitLimit=!1,t}},kp=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,n){this.table[t<<8|e]=i<<4|n}addMany(e,t,i,n){for(let a=0;a<e.length;a++)this.table[t<<8|e[a]]=i<<4|n}},ui=160,Ep=(function(){let e=new kp(4095),t=Array.apply(null,Array(256)).map((g,v)=>v),i=(g,v)=>t.slice(g,v),n=i(32,127),a=i(0,24);a.push(25),a.push.apply(a,i(28,32));let h=i(0,14),d;e.setDefault(1,0),e.addMany(n,0,2,0);for(d in h)e.addMany([24,26,153,154],d,3,0),e.addMany(i(128,144),d,3,0),e.addMany(i(144,152),d,3,0),e.add(156,d,0,0),e.add(27,d,11,1),e.add(157,d,4,8),e.addMany([152,158,159],d,0,7),e.add(155,d,11,3),e.add(144,d,11,9);return e.addMany(a,0,3,0),e.addMany(a,1,3,1),e.add(127,1,0,1),e.addMany(a,8,0,8),e.addMany(a,3,3,3),e.add(127,3,0,3),e.addMany(a,4,3,4),e.add(127,4,0,4),e.addMany(a,6,3,6),e.addMany(a,5,3,5),e.add(127,5,0,5),e.addMany(a,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(n,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(n,7,0,7),e.addMany(a,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(a,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(a,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(a,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(a,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(a,13,13,13),e.addMany(n,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(ui,0,2,0),e.add(ui,8,5,8),e.add(ui,6,0,6),e.add(ui,11,0,11),e.add(ui,13,13,13),e})(),Rp=class extends Ve{constructor(e=Ep){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 Uc,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,i,n)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,i)=>{},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(vt(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new Cp),this._dcsParser=this._register(new xp),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>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 a=0;a<e.intermediates.length;++a){let h=e.intermediates.charCodeAt(a);if(32>h||h>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=h}}if(e.final.length!==1)throw new Error("final must be a single byte");let n=e.final.charCodeAt(0);if(t[0]>n||n>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=n,i}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 i=this._identifier(e,[48,126]);this._escHandlers[i]===void 0&&(this._escHandlers[i]=[]);let n=this._escHandlers[i];return n.push(t),{dispose:()=>{let a=n.indexOf(t);a!==-1&&n.splice(a,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 i=this._identifier(e);this._csiHandlers[i]===void 0&&(this._csiHandlers[i]=[]);let n=this._csiHandlers[i];return n.push(t),{dispose:()=>{let a=n.indexOf(t);a!==-1&&n.splice(a,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,i,n,a){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=n,this._parseStack.chunkPos=a}parse(e,t,i){let n=0,a=0,h=0,d;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,h=this._parseStack.chunkPos+1;else{if(i===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let g=this._parseStack.handlers,v=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(i===!1&&v>-1){for(;v>=0&&(d=g[v](this._params),d!==!0);v--)if(d instanceof Promise)return this._parseStack.handlerPos=v,d}this._parseStack.handlers=[];break;case 4:if(i===!1&&v>-1){for(;v>=0&&(d=g[v](),d!==!0);v--)if(d instanceof Promise)return this._parseStack.handlerPos=v,d}this._parseStack.handlers=[];break;case 6:if(n=e[this._parseStack.chunkPos],d=this._dcsParser.unhook(n!==24&&n!==26,i),d)return d;n===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(n=e[this._parseStack.chunkPos],d=this._oscParser.end(n!==24&&n!==26,i),d)return d;n===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,h=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let g=h;g<t;++g){switch(n=e[g],a=this._transitions.table[this.currentState<<8|(n<160?n:ui)],a>>4){case 2:for(let B=g+1;;++B){if(B>=t||(n=e[B])<32||n>126&&n<ui){this._printHandler(e,g,B),g=B-1;break}if(++B>=t||(n=e[B])<32||n>126&&n<ui){this._printHandler(e,g,B),g=B-1;break}if(++B>=t||(n=e[B])<32||n>126&&n<ui){this._printHandler(e,g,B),g=B-1;break}if(++B>=t||(n=e[B])<32||n>126&&n<ui){this._printHandler(e,g,B),g=B-1;break}}break;case 3:this._executeHandlers[n]?this._executeHandlers[n]():this._executeHandlerFb(n),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:g,code:n,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let v=this._csiHandlers[this._collect<<8|n],p=v?v.length-1:-1;for(;p>=0&&(d=v[p](this._params),d!==!0);p--)if(d instanceof Promise)return this._preserveStack(3,v,p,a,g),d;p<0&&this._csiHandlerFb(this._collect<<8|n,this._params),this.precedingJoinState=0;break;case 8:do switch(n){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(n-48)}while(++g<t&&(n=e[g])>47&&n<60);g--;break;case 9:this._collect<<=8,this._collect|=n;break;case 10:let R=this._escHandlers[this._collect<<8|n],k=R?R.length-1:-1;for(;k>=0&&(d=R[k](),d!==!0);k--)if(d instanceof Promise)return this._preserveStack(4,R,k,a,g),d;k<0&&this._escHandlerFb(this._collect<<8|n),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|n,this._params);break;case 13:for(let B=g+1;;++B)if(B>=t||(n=e[B])===24||n===26||n===27||n>127&&n<ui){this._dcsParser.put(e,g,B),g=B-1;break}break;case 14:if(d=this._dcsParser.unhook(n!==24&&n!==26),d)return this._preserveStack(6,[],0,a,g),d;n===27&&(a|=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 B=g+1;;B++)if(B>=t||(n=e[B])<32||n>127&&n<ui){this._oscParser.put(e,g,B),g=B-1;break}break;case 6:if(d=this._oscParser.end(n!==24&&n!==26),d)return this._preserveStack(5,[],0,a,g),d;n===27&&(a|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break}this.currentState=a&15}}},Ap=/^([\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})$/,Mp=/^[\da-f]+$/;function bh(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf("rgb:")===0){t=t.slice(4);let i=Ap.exec(t);if(i){let n=i[1]?15:i[4]?255:i[7]?4095:65535;return[Math.round(parseInt(i[1]||i[4]||i[7]||i[10],16)/n*255),Math.round(parseInt(i[2]||i[5]||i[8]||i[11],16)/n*255),Math.round(parseInt(i[3]||i[6]||i[9]||i[12],16)/n*255)]}}else if(t.indexOf("#")===0&&(t=t.slice(1),Mp.exec(t)&&[3,6,9,12].includes(t.length))){let i=t.length/3,n=[0,0,0];for(let a=0;a<3;++a){let h=parseInt(t.slice(i*a,i*a+i),16);n[a]=i===1?h<<4:i===2?h:i===3?h>>4:h>>8}return n}}function oo(e,t){let i=e.toString(16),n=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return n;case 12:return(n+n).slice(0,3);default:return n+n}}function Op(e,t=16){let[i,n,a]=e;return`rgb:${oo(i,t)}/${oo(n,t)}/${oo(a,t)}`}var Tp={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Qi=131072,wh=10;function Ch(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 xh=5e3,kh=0,Pp=class extends Ve{constructor(e,t,i,n,a,h,d,g,v=new Rp){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=n,this._optionsService=a,this._oscLinkService=h,this._coreMouseService=d,this._unicodeService=g,this._parser=v,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new Xf,this._utf8Decoder=new Zf,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Rt.clone(),this._eraseAttrDataInternal=Rt.clone(),this._onRequestBell=this._register(new ee),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new ee),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new ee),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new ee),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new ee),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new ee),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new ee),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new ee),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new ee),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new ee),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new ee),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new ee),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new ee),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 ta(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(p=>this._activeBuffer=p.activeBuffer)),this._parser.setCsiHandlerFallback((p,R)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(p),params:R.toArray()})}),this._parser.setEscHandlerFallback(p=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(p)})}),this._parser.setExecuteHandlerFallback(p=>{this._logService.debug("Unknown EXECUTE code: ",{code:p})}),this._parser.setOscHandlerFallback((p,R,k)=>{this._logService.debug("Unknown OSC code: ",{identifier:p,action:R,data:k})}),this._parser.setDcsHandlerFallback((p,R,k)=>{R==="HOOK"&&(k=k.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(p),action:R,payload:k})}),this._parser.setPrintHandler((p,R,k)=>this.print(p,R,k)),this._parser.registerCsiHandler({final:"@"},p=>this.insertChars(p)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},p=>this.scrollLeft(p)),this._parser.registerCsiHandler({final:"A"},p=>this.cursorUp(p)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},p=>this.scrollRight(p)),this._parser.registerCsiHandler({final:"B"},p=>this.cursorDown(p)),this._parser.registerCsiHandler({final:"C"},p=>this.cursorForward(p)),this._parser.registerCsiHandler({final:"D"},p=>this.cursorBackward(p)),this._parser.registerCsiHandler({final:"E"},p=>this.cursorNextLine(p)),this._parser.registerCsiHandler({final:"F"},p=>this.cursorPrecedingLine(p)),this._parser.registerCsiHandler({final:"G"},p=>this.cursorCharAbsolute(p)),this._parser.registerCsiHandler({final:"H"},p=>this.cursorPosition(p)),this._parser.registerCsiHandler({final:"I"},p=>this.cursorForwardTab(p)),this._parser.registerCsiHandler({final:"J"},p=>this.eraseInDisplay(p,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},p=>this.eraseInDisplay(p,!0)),this._parser.registerCsiHandler({final:"K"},p=>this.eraseInLine(p,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},p=>this.eraseInLine(p,!0)),this._parser.registerCsiHandler({final:"L"},p=>this.insertLines(p)),this._parser.registerCsiHandler({final:"M"},p=>this.deleteLines(p)),this._parser.registerCsiHandler({final:"P"},p=>this.deleteChars(p)),this._parser.registerCsiHandler({final:"S"},p=>this.scrollUp(p)),this._parser.registerCsiHandler({final:"T"},p=>this.scrollDown(p)),this._parser.registerCsiHandler({final:"X"},p=>this.eraseChars(p)),this._parser.registerCsiHandler({final:"Z"},p=>this.cursorBackwardTab(p)),this._parser.registerCsiHandler({final:"`"},p=>this.charPosAbsolute(p)),this._parser.registerCsiHandler({final:"a"},p=>this.hPositionRelative(p)),this._parser.registerCsiHandler({final:"b"},p=>this.repeatPrecedingCharacter(p)),this._parser.registerCsiHandler({final:"c"},p=>this.sendDeviceAttributesPrimary(p)),this._parser.registerCsiHandler({prefix:">",final:"c"},p=>this.sendDeviceAttributesSecondary(p)),this._parser.registerCsiHandler({final:"d"},p=>this.linePosAbsolute(p)),this._parser.registerCsiHandler({final:"e"},p=>this.vPositionRelative(p)),this._parser.registerCsiHandler({final:"f"},p=>this.hVPosition(p)),this._parser.registerCsiHandler({final:"g"},p=>this.tabClear(p)),this._parser.registerCsiHandler({final:"h"},p=>this.setMode(p)),this._parser.registerCsiHandler({prefix:"?",final:"h"},p=>this.setModePrivate(p)),this._parser.registerCsiHandler({final:"l"},p=>this.resetMode(p)),this._parser.registerCsiHandler({prefix:"?",final:"l"},p=>this.resetModePrivate(p)),this._parser.registerCsiHandler({final:"m"},p=>this.charAttributes(p)),this._parser.registerCsiHandler({final:"n"},p=>this.deviceStatus(p)),this._parser.registerCsiHandler({prefix:"?",final:"n"},p=>this.deviceStatusPrivate(p)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},p=>this.softReset(p)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},p=>this.setCursorStyle(p)),this._parser.registerCsiHandler({final:"r"},p=>this.setScrollRegion(p)),this._parser.registerCsiHandler({final:"s"},p=>this.saveCursor(p)),this._parser.registerCsiHandler({final:"t"},p=>this.windowOptions(p)),this._parser.registerCsiHandler({final:"u"},p=>this.restoreCursor(p)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},p=>this.insertColumns(p)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},p=>this.deleteColumns(p)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},p=>this.selectProtected(p)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},p=>this.requestMode(p,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},p=>this.requestMode(p,!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(rn.IND,()=>this.index()),this._parser.setExecuteHandler(rn.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(rn.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new ni(p=>(this.setTitle(p),this.setIconName(p),!0))),this._parser.registerOscHandler(1,new ni(p=>this.setIconName(p))),this._parser.registerOscHandler(2,new ni(p=>this.setTitle(p))),this._parser.registerOscHandler(4,new ni(p=>this.setOrReportIndexedColor(p))),this._parser.registerOscHandler(8,new ni(p=>this.setHyperlink(p))),this._parser.registerOscHandler(10,new ni(p=>this.setOrReportFgColor(p))),this._parser.registerOscHandler(11,new ni(p=>this.setOrReportBgColor(p))),this._parser.registerOscHandler(12,new ni(p=>this.setOrReportCursorColor(p))),this._parser.registerOscHandler(104,new ni(p=>this.restoreIndexedColor(p))),this._parser.registerOscHandler(110,new ni(p=>this.restoreFgColor(p))),this._parser.registerOscHandler(111,new ni(p=>this.restoreBgColor(p))),this._parser.registerOscHandler(112,new ni(p=>this.restoreCursorColor(p))),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 p in Lt)this._parser.registerEscHandler({intermediates:"(",final:p},()=>this.selectCharset("("+p)),this._parser.registerEscHandler({intermediates:")",final:p},()=>this.selectCharset(")"+p)),this._parser.registerEscHandler({intermediates:"*",final:p},()=>this.selectCharset("*"+p)),this._parser.registerEscHandler({intermediates:"+",final:p},()=>this.selectCharset("+"+p)),this._parser.registerEscHandler({intermediates:"-",final:p},()=>this.selectCharset("-"+p)),this._parser.registerEscHandler({intermediates:".",final:p},()=>this.selectCharset("."+p)),this._parser.registerEscHandler({intermediates:"/",final:p},()=>this.selectCharset("/"+p));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(p=>(this._logService.error("Parsing error: ",p),p)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Sh((p,R)=>this.requestStatusString(p,R)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,n){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=n}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,i)=>setTimeout(()=>i("#SLOW_TIMEOUT"),xh))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${xh} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,n=this._activeBuffer.x,a=this._activeBuffer.y,h=0,d=this._parseStack.paused;if(d){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;n=this._parseStack.cursorStartX,a=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Qi&&(h=this._parseStack.position+Qi)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,p=>String.fromCharCode(p)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(p=>p.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<Qi&&(this._parseBuffer=new Uint32Array(Math.min(e.length,Qi))),d||this._dirtyRowTracker.clearRange(),e.length>Qi)for(let p=h;p<e.length;p+=Qi){let R=p+Qi<e.length?p+Qi:e.length,k=typeof e=="string"?this._stringDecoder.decode(e.substring(p,R),this._parseBuffer):this._utf8Decoder.decode(e.subarray(p,R),this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,k))return this._preserveStack(n,a,k,p),this._logSlowResolvingAsync(i),i}else if(!d){let p=typeof e=="string"?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,p))return this._preserveStack(n,a,p,0),this._logSlowResolvingAsync(i),i}(this._activeBuffer.x!==n||this._activeBuffer.y!==a)&&this._onCursorMove.fire();let g=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),v=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);v<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(v,this._bufferService.rows-1),end:Math.min(g,this._bufferService.rows-1)})}print(e,t,i){let n,a,h=this._charsetService.charset,d=this._optionsService.rawOptions.screenReaderMode,g=this._bufferService.cols,v=this._coreService.decPrivateModes.wraparound,p=this._coreService.modes.insertMode,R=this._curAttrData,k=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&i-t>0&&k.getWidth(this._activeBuffer.x-1)===2&&k.setCellFromCodepoint(this._activeBuffer.x-1,0,1,R);let B=this._parser.precedingJoinState;for(let L=t;L<i;++L){if(n=e[L],n<127&&h){let _e=h[String.fromCharCode(n)];_e&&(n=_e.charCodeAt(0))}let P=this._unicodeService.charProperties(n,B);a=us.extractWidth(P);let U=us.extractShouldJoin(P),Z=U?us.extractWidth(B):0;if(B=P,d&&this._onA11yChar.fire(es(n)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+a-Z>g){if(v){let _e=k,rt=this._activeBuffer.x-Z;for(this._activeBuffer.x=Z,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),k=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),Z>0&&k instanceof mr&&k.copyCellsFrom(_e,rt,0,Z,!1);rt<g;)_e.setCellFromCodepoint(rt++,0,1,R)}else if(this._activeBuffer.x=g-1,a===2)continue}if(U&&this._activeBuffer.x){let _e=k.getWidth(this._activeBuffer.x-1)?1:2;k.addCodepointToCell(this._activeBuffer.x-_e,n,a);for(let rt=a-Z;--rt>=0;)k.setCellFromCodepoint(this._activeBuffer.x++,0,0,R);continue}if(p&&(k.insertCells(this._activeBuffer.x,a-Z,this._activeBuffer.getNullCell(R)),k.getWidth(g-1)===2&&k.setCellFromCodepoint(g-1,0,1,R)),k.setCellFromCodepoint(this._activeBuffer.x++,n,a,R),a>0)for(;--a;)k.setCellFromCodepoint(this._activeBuffer.x++,0,0,R)}this._parser.precedingJoinState=B,this._activeBuffer.x<g&&i-t>0&&k.getWidth(this._activeBuffer.x)===0&&!k.hasContent(this._activeBuffer.x)&&k.setCellFromCodepoint(this._activeBuffer.x,0,1,R),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,i=>Ch(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Sh(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new ni(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,i,n=!1,a=!1){let h=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);h.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),a),n&&(h.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){var n;this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i<this._bufferService.rows;i++)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(i);break;case 1:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!((n=this._activeBuffer.lines.get(this._activeBuffer.ybase+i))!=null&&n.getTrimmedLength()););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let a=this._activeBuffer.lines.length-this._bufferService.rows;a>0&&(this._activeBuffer.lines.trimStart(a),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-a,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-a,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 i=this._activeBuffer.ybase+this._activeBuffer.y,n=this._bufferService.rows-1-this._activeBuffer.scrollBottom,a=this._bufferService.rows-1+this._activeBuffer.ybase-n+1;for(;t--;)this._activeBuffer.lines.splice(a-1,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}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 i=this._activeBuffer.ybase+this._activeBuffer.y,n;for(n=this._bufferService.rows-1-this._activeBuffer.scrollBottom,n=this._bufferService.rows-1+this._activeBuffer.ybase-n;t--;)this._activeBuffer.lines.splice(i,1),this._activeBuffer.lines.splice(n,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(Rt));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 i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.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 i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.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 i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.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 i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.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 i=e.params[0]||1,n=us.extractWidth(t),a=this._activeBuffer.x-n,h=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(a),d=new Uint32Array(h.length*i),g=0;for(let p=0;p<h.length;){let R=h.codePointAt(p)||0;d[g++]=R,p+=R>65535?2:1}let v=g;for(let p=1;p<i;++p)d.copyWithin(v,0,g),v+=g;return this.print(d,0,v),!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,cs),this._charsetService.setgCharset(1,cs),this._charsetService.setgCharset(2,cs),this._charsetService.setgCharset(3,cs);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){(U=>(U[U.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",U[U.SET=1]="SET",U[U.RESET=2]="RESET",U[U.PERMANENTLY_SET=3]="PERMANENTLY_SET",U[U.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(void 0||(i={}));let n=this._coreService.decPrivateModes,{activeProtocol:a,activeEncoding:h}=this._coreMouseService,d=this._coreService,{buffers:g,cols:v}=this._bufferService,{active:p,alt:R}=g,k=this._optionsService.rawOptions,B=(U,Z)=>(d.triggerDataEvent(`${V.ESC}[${t?"":"?"}${U};${Z}$y`),!0),L=U=>U?1:2,P=e.params[0];return t?P===2?B(P,4):P===4?B(P,L(d.modes.insertMode)):P===12?B(P,3):P===20?B(P,L(k.convertEol)):B(P,0):P===1?B(P,L(n.applicationCursorKeys)):P===3?B(P,k.windowOptions.setWinLines?v===80?2:v===132?1:0:0):P===6?B(P,L(n.origin)):P===7?B(P,L(n.wraparound)):P===8?B(P,3):P===9?B(P,L(a==="X10")):P===12?B(P,L(k.cursorBlink)):P===25?B(P,L(!d.isCursorHidden)):P===45?B(P,L(n.reverseWraparound)):P===66?B(P,L(n.applicationKeypad)):P===67?B(P,4):P===1e3?B(P,L(a==="VT200")):P===1002?B(P,L(a==="DRAG")):P===1003?B(P,L(a==="ANY")):P===1004?B(P,L(n.sendFocus)):P===1005?B(P,4):P===1006?B(P,L(h==="SGR")):P===1015?B(P,4):P===1016?B(P,L(h==="SGR_PIXELS")):P===1048?B(P,1):P===47||P===1047||P===1049?B(P,L(p===R)):P===2004?B(P,L(n.bracketedPasteMode)):P===2026?B(P,L(n.synchronizedOutput)):B(P,0)}_updateAttrColor(e,t,i,n,a){return t===2?(e|=50331648,e&=-16777216,e|=Or.fromColorRGB([i,n,a])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let n=[0,0,-1,0,0,0],a=0,h=0;do{if(n[h+a]=e.params[t+h],e.hasSubParams(t+h)){let d=e.getSubParams(t+h),g=0;do n[1]===5&&(a=1),n[h+g+1+a]=d[g];while(++g<d.length&&g+h+1+a<n.length);break}if(n[1]===5&&h+a>=2||n[1]===2&&h+a>=5)break;n[1]&&(a=1)}while(++h+t<e.length&&h+a<n.length);for(let d=2;d<n.length;++d)n[d]===-1&&(n[d]=0);switch(n[0]){case 38:i.fg=this._updateAttrColor(i.fg,n[1],n[3],n[4],n[5]);break;case 48:i.bg=this._updateAttrColor(i.bg,n[1],n[3],n[4],n[5]);break;case 58:i.extended=i.extended.clone(),i.extended.underlineColor=this._updateAttrColor(i.extended.underlineColor,n[1],n[3],n[4],n[5])}return h}_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=Rt.fg,e.bg=Rt.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,i,n=this._curAttrData;for(let a=0;a<t;a++)i=e.params[a],i>=30&&i<=37?(n.fg&=-50331904,n.fg|=16777216|i-30):i>=40&&i<=47?(n.bg&=-50331904,n.bg|=16777216|i-40):i>=90&&i<=97?(n.fg&=-50331904,n.fg|=16777216|i-90|8):i>=100&&i<=107?(n.bg&=-50331904,n.bg|=16777216|i-100|8):i===0?this._processSGR0(n):i===1?n.fg|=134217728:i===3?n.bg|=67108864:i===4?(n.fg|=268435456,this._processUnderline(e.hasSubParams(a)?e.getSubParams(a)[0]:1,n)):i===5?n.fg|=536870912:i===7?n.fg|=67108864:i===8?n.fg|=1073741824:i===9?n.fg|=2147483648:i===2?n.bg|=134217728:i===21?this._processUnderline(2,n):i===22?(n.fg&=-134217729,n.bg&=-134217729):i===23?n.bg&=-67108865:i===24?(n.fg&=-268435457,this._processUnderline(0,n)):i===25?n.fg&=-536870913:i===27?n.fg&=-67108865:i===28?n.fg&=-1073741825:i===29?n.fg&=2147483647:i===39?(n.fg&=-67108864,n.fg|=Rt.fg&16777215):i===49?(n.bg&=-67108864,n.bg|=Rt.bg&16777215):i===38||i===48||i===58?a+=this._extractColor(e,a,n):i===53?n.bg|=1073741824:i===55?n.bg&=-1073741825:i===59?(n.extended=n.extended.clone(),n.extended.underlineColor=-1,n.updateExtended()):i===100?(n.fg&=-67108864,n.fg|=Rt.fg&16777215,n.bg&=-67108864,n.bg|=Rt.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);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,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${V.ESC}[${t};${i}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${V.ESC}[?${t};${i}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=Rt.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 i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Ch(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>wh&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>wh&&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=[],i=e.split(";");for(;i.length>1;){let n=i.shift(),a=i.shift();if(/^\d+$/.exec(n)){let h=parseInt(n);if(Eh(h))if(a==="?")t.push({type:0,index:h});else{let d=bh(a);d&&t.push({type:1,index:h,color:d})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let i=e.slice(0,t).trim(),n=e.slice(t+1);return n?this._createHyperlink(i,n):i.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i=e.split(":"),n,a=i.findIndex(h=>h.startsWith("id="));return a!==-1&&(n=i[a].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:n,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 i=e.split(";");for(let n=0;n<i.length&&!(t>=this._specialColors.length);++n,++t)if(i[n]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let a=bh(i[n]);a&&this._onColor.fire([{type:1,index:this._specialColors[t],color:a}])}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=[],i=e.split(";");for(let n=0;n<i.length;++n)if(/^\d+$/.exec(i[n])){let a=parseInt(i[n]);Eh(a)&&t.push({type:2,index:a})}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,cs),!0}selectCharset(e){return e.length!==2?(this.selectDefaultCharset(),!0):(e[0]==="/"||this._charsetService.setgCharset(Tp[e[0]],Lt[e[1]]||cs),!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=Rt.clone(),this._eraseAttrDataInternal=Rt.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 di;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 i=this._activeBuffer.ybase+this._activeBuffer.y+t,n=this._activeBuffer.lines.get(i);n&&(n.fill(e),n.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let i=d=>(this._coreService.triggerDataEvent(`${V.ESC}${d}${V.ESC}\\`),!0),n=this._bufferService.buffer,a=this._optionsService.rawOptions;return i(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${n.scrollTop+1};${n.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[a.cursorStyle]-(a.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},ta=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&&(kh=e,e=t,t=kh),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};ta=xt([de(0,Xt)],ta);function Eh(e){return 0<=e&&e<256}var Lp=5e7,Rh=12,Bp=50,Ip=class extends Ve{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 ee),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 i;for(;i=this._writeBuffer.shift();){this._action(i);let n=this._callbacks.shift();n&&n()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>Lp)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 i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let n=this._writeBuffer[this._bufferOffset],a=this._action(n,t);if(a){let d=g=>performance.now()-i>=Rh?setTimeout(()=>this._innerWrite(0,g)):this._innerWrite(i,g);a.catch(g=>(queueMicrotask(()=>{throw g}),Promise.resolve(!1))).then(d);return}let h=this._callbacks[this._bufferOffset];if(h&&h(),this._bufferOffset++,this._pendingData-=n.length,performance.now()-i>=Rh)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>Bp&&(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()}},ia=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 g=t.addMarker(t.ybase+t.y),v={data:e,id:this._nextId++,lines:[g]};return g.onDispose(()=>this._removeMarkerFromLink(v,g)),this._dataByLinkId.set(v.id,v),v.id}let i=e,n=this._getEntryIdKey(i),a=this._entriesWithId.get(n);if(a)return this.addLineToLink(a.id,t.ybase+t.y),a.id;let h=t.addMarker(t.ybase+t.y),d={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[h]};return h.onDispose(()=>this._removeMarkerFromLink(d,h)),this._entriesWithId.set(d.key,d),this._dataByLinkId.set(d.id,d),d.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(n=>n.line!==t)){let n=this._bufferService.buffer.addMarker(t);i.lines.push(n),n.onDispose(()=>this._removeMarkerFromLink(i,n))}}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 i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};ia=xt([de(0,Xt)],ia);var Ah=!1,Dp=class extends Ve{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new Us),this._onBinary=this._register(new ee),this.onBinary=this._onBinary.event,this._onData=this._register(new ee),this.onData=this._onData.event,this._onLineFeed=this._register(new ee),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new ee),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new ee),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new ee),this._instantiationService=new op,this.optionsService=this._register(new pp(e)),this._instantiationService.setService(Zt,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Xo)),this._instantiationService.setService(Xt,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(Jo)),this._instantiationService.setService(rc,this._logService),this.coreService=this._register(this._instantiationService.createInstance(Zo)),this._instantiationService.setService(ps,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Qo)),this._instantiationService.setService(sc,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(us)),this._instantiationService.setService(i_,this.unicodeService),this._charsetService=this._instantiationService.createInstance(bp),this._instantiationService.setService(t_,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(ia),this._instantiationService.setService(nc,this._oscLinkService),this._inputHandler=this._register(new Pp(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Ft.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Ft.forward(this._bufferService.onResize,this._onResize)),this._register(Ft.forward(this.coreService.onData,this._onData)),this._register(Ft.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 Ip((t,i)=>this._inputHandler.parse(t,i))),this._register(Ft.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new ee),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&&!Ah&&(this._logService.warn("writeSync is unreliable and will be removed soon."),Ah=!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,Nc),t=Math.max(t,Hc),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(yh.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(yh(this._bufferService),!1))),this._windowsWrappingHeuristics.value=vt(()=>{for(let t of e)t.dispose()})}}},Np={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 Hp(e,t,i,n){var d;let a={type:0,cancel:!1,key:void 0},h=(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?a.key=V.ESC+"OA":a.key=V.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?a.key=V.ESC+"OD":a.key=V.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?a.key=V.ESC+"OC":a.key=V.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?a.key=V.ESC+"OB":a.key=V.ESC+"[B");break;case 8:a.key=e.ctrlKey?"\b":V.DEL,e.altKey&&(a.key=V.ESC+a.key);break;case 9:if(e.shiftKey){a.key=V.ESC+"[Z";break}a.key=V.HT,a.cancel=!0;break;case 13:a.key=e.altKey?V.ESC+V.CR:V.CR,a.cancel=!0;break;case 27:a.key=V.ESC,e.altKey&&(a.key=V.ESC+V.ESC),a.cancel=!0;break;case 37:if(e.metaKey)break;h?a.key=V.ESC+"[1;"+(h+1)+"D":t?a.key=V.ESC+"OD":a.key=V.ESC+"[D";break;case 39:if(e.metaKey)break;h?a.key=V.ESC+"[1;"+(h+1)+"C":t?a.key=V.ESC+"OC":a.key=V.ESC+"[C";break;case 38:if(e.metaKey)break;h?a.key=V.ESC+"[1;"+(h+1)+"A":t?a.key=V.ESC+"OA":a.key=V.ESC+"[A";break;case 40:if(e.metaKey)break;h?a.key=V.ESC+"[1;"+(h+1)+"B":t?a.key=V.ESC+"OB":a.key=V.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(a.key=V.ESC+"[2~");break;case 46:h?a.key=V.ESC+"[3;"+(h+1)+"~":a.key=V.ESC+"[3~";break;case 36:h?a.key=V.ESC+"[1;"+(h+1)+"H":t?a.key=V.ESC+"OH":a.key=V.ESC+"[H";break;case 35:h?a.key=V.ESC+"[1;"+(h+1)+"F":t?a.key=V.ESC+"OF":a.key=V.ESC+"[F";break;case 33:e.shiftKey?a.type=2:e.ctrlKey?a.key=V.ESC+"[5;"+(h+1)+"~":a.key=V.ESC+"[5~";break;case 34:e.shiftKey?a.type=3:e.ctrlKey?a.key=V.ESC+"[6;"+(h+1)+"~":a.key=V.ESC+"[6~";break;case 112:h?a.key=V.ESC+"[1;"+(h+1)+"P":a.key=V.ESC+"OP";break;case 113:h?a.key=V.ESC+"[1;"+(h+1)+"Q":a.key=V.ESC+"OQ";break;case 114:h?a.key=V.ESC+"[1;"+(h+1)+"R":a.key=V.ESC+"OR";break;case 115:h?a.key=V.ESC+"[1;"+(h+1)+"S":a.key=V.ESC+"OS";break;case 116:h?a.key=V.ESC+"[15;"+(h+1)+"~":a.key=V.ESC+"[15~";break;case 117:h?a.key=V.ESC+"[17;"+(h+1)+"~":a.key=V.ESC+"[17~";break;case 118:h?a.key=V.ESC+"[18;"+(h+1)+"~":a.key=V.ESC+"[18~";break;case 119:h?a.key=V.ESC+"[19;"+(h+1)+"~":a.key=V.ESC+"[19~";break;case 120:h?a.key=V.ESC+"[20;"+(h+1)+"~":a.key=V.ESC+"[20~";break;case 121:h?a.key=V.ESC+"[21;"+(h+1)+"~":a.key=V.ESC+"[21~";break;case 122:h?a.key=V.ESC+"[23;"+(h+1)+"~":a.key=V.ESC+"[23~";break;case 123:h?a.key=V.ESC+"[24;"+(h+1)+"~":a.key=V.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?a.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?a.key=V.NUL:e.keyCode>=51&&e.keyCode<=55?a.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?a.key=V.DEL:e.keyCode===219?a.key=V.ESC:e.keyCode===220?a.key=V.FS:e.keyCode===221&&(a.key=V.GS);else if((!i||n)&&e.altKey&&!e.metaKey){let g=(d=Np[e.keyCode])==null?void 0:d[e.shiftKey?1:0];if(g)a.key=V.ESC+g;else if(e.keyCode>=65&&e.keyCode<=90){let v=e.ctrlKey?e.keyCode-64:e.keyCode+32,p=String.fromCharCode(v);e.shiftKey&&(p=p.toUpperCase()),a.key=V.ESC+p}else if(e.keyCode===32)a.key=V.ESC+(e.ctrlKey?V.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let v=e.code.slice(3,4);e.shiftKey||(v=v.toLowerCase()),a.key=V.ESC+v,a.cancel=!0}}else i&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(a.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?a.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(a.key=V.US),e.key==="@"&&(a.key=V.NUL));break}return a}var kt=0,Up=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new dn,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new dn,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((a,h)=>this._getKey(a)-this._getKey(h)),t=0,i=0,n=new Array(this._array.length+this._insertedValues.length);for(let a=0;a<n.length;a++)i>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(n[a]=e[t],t++):n[a]=this._array[i++];this._array=n,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||(kt=this._search(t),kt===-1)||this._getKey(this._array[kt])!==t)return!1;do if(this._array[kt]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(kt),!0;while(++kt<this._array.length&&this._getKey(this._array[kt])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((a,h)=>a-h),t=0,i=new Array(this._array.length-e.length),n=0;for(let a=0;a<this._array.length;a++)e[t]===a?t++:i[n++]=this._array[a];this._array=i,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&&(kt=this._search(e),!(kt<0||kt>=this._array.length)&&this._getKey(this._array[kt])===e))do yield this._array[kt];while(++kt<this._array.length&&this._getKey(this._array[kt])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(kt=this._search(e),!(kt<0||kt>=this._array.length)&&this._getKey(this._array[kt])===e))do t(this._array[kt]);while(++kt<this._array.length&&this._getKey(this._array[kt])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,i=this._array.length-1;for(;i>=t;){let n=t+i>>1,a=this._getKey(this._array[n]);if(a>e)i=n-1;else if(a<e)t=n+1;else{for(;n>0&&this._getKey(this._array[n-1])===e;)n--;return n}}return t}},ao=0,Mh=0,Wp=class extends Ve{constructor(){super(),this._decorations=new Up(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new ee),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new ee),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(vt(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new Fp(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.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,i){let n=0,a=0;for(let h of this._decorations.getKeyIterator(t))n=h.options.x??0,a=n+(h.options.width??1),e>=n&&e<a&&(!i||(h.options.layer??"bottom")===i)&&(yield h)}forEachDecorationAtCell(e,t,i,n){this._decorations.forEachByKey(t,a=>{ao=a.options.x??0,Mh=ao+(a.options.width??1),e>=ao&&e<Mh&&(!i||(a.options.layer??"bottom")===i)&&n(a)})}},Fp=class extends is{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new ee),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new ee),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=St.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=St.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},zp=1e3,qp=class{constructor(e,t=zp){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,i){this._rowCount=i,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 n=performance.now();if(n-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=n,this._innerRefresh();else if(!this._additionalRefreshRequested){let a=n-this._lastRefreshMs,h=this._debounceThresholdMS-a;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},h)}}_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)}},Oh=20,fn=class extends Ve{constructor(e,t,i,n){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=n,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let a=this._coreBrowserService.mainDocument;this._accessibilityContainer=a.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=a.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let h=0;h<this._terminal.rows;h++)this._rowElements[h]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[h]);if(this._topBoundaryFocusListener=h=>this._handleBoundaryFocus(h,0),this._bottomBoundaryFocusListener=h=>this._handleBoundaryFocus(h,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=a.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new qp(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(h=>this._handleResize(h.rows))),this._register(this._terminal.onRender(h=>this._refreshRows(h.start,h.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(h=>this._handleChar(h))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
37
+ `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),xa&&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),i=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!i||!n||!t?!1:this._areCoordsInSelection(t,i,n)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!i||!n?!1:this._areCoordsInSelection([e,t],i,n)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]<i[1]||t[1]===i[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<i[0]||t[1]<i[1]&&e[1]===i[1]&&e[0]<i[0]||t[1]<i[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){var a,h;let i=(h=(a=this._linkifier.currentLink)==null?void 0:a.link)==null?void 0:h.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=ah(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let n=this._getMouseBufferCoords(e);return n?(this._selectWordAt(n,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=Ca(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-to),to),t/=to,t/Math.abs(t)+Math.round(t*(Qg-1)))}shouldForceSelection(e){return un?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(),ep)}_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&&!(un&&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 i=this._bufferService.buffer;if(this._model.selectionEnd[1]<i.lines.length){let n=i.lines.get(this._model.selectionEnd[1]);n&&n.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<tp&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let i=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(i&&i[0]!==void 0&&i[1]!==void 0){let n=jg(i[0]-1,i[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(n,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,i=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);if(!i){this._oldHasSelection&&this._fireOnSelectionChange(e,t,i);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,i)}_fireOnSelectionChange(e,t,i){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=i,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(t=>this._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let n=0;t>=n;n++){let a=e.loadCell(n,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:a>1&&t!==n&&(i+=a-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,n=!0){if(e[0]>=this._bufferService.cols)return;let a=this._bufferService.buffer,h=a.lines.get(e[1]);if(!h)return;let d=a.translateBufferLineToString(e[1],!1),g=this._convertViewportColToCharacterIndex(h,e[0]),v=g,m=e[0]-g,R=0,k=0,B=0,L=0;if(d.charAt(g)===" "){for(;g>0&&d.charAt(g-1)===" ";)g--;for(;v<d.length&&d.charAt(v+1)===" ";)v++}else{let Z=e[0],_e=e[0];h.getWidth(Z)===0&&(R++,Z--),h.getWidth(_e)===2&&(k++,_e++);let rt=h.getString(_e).length;for(rt>1&&(L+=rt-1,v+=rt-1);Z>0&&g>0&&!this._isCharWordSeparator(h.loadCell(Z-1,this._workCell));){h.loadCell(Z-1,this._workCell);let Ne=this._workCell.getChars().length;this._workCell.getWidth()===0?(R++,Z--):Ne>1&&(B+=Ne-1,g-=Ne-1),g--,Z--}for(;_e<h.length&&v+1<d.length&&!this._isCharWordSeparator(h.loadCell(_e+1,this._workCell));){h.loadCell(_e+1,this._workCell);let Ne=this._workCell.getChars().length;this._workCell.getWidth()===2?(k++,_e++):Ne>1&&(L+=Ne-1,v+=Ne-1),v++,_e++}}v++;let P=g+m-R+B,U=Math.min(this._bufferService.cols,v-g+R+k-B-L);if(!(!t&&d.slice(g,v).trim()==="")){if(i&&P===0&&h.getCodePoint(0)!==32){let Z=a.lines.get(e[1]-1);if(Z&&h.isWrapped&&Z.getCodePoint(this._bufferService.cols-1)!==32){let _e=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(_e){let rt=this._bufferService.cols-_e.start;P-=rt,U+=rt}}}if(n&&P+U===this._bufferService.cols&&h.getCodePoint(this._bufferService.cols-1)!==32){let Z=a.lines.get(e[1]+1);if(Z!=null&&Z.isWrapped&&Z.getCodePoint(0)!==32){let _e=this._getWordAt([0,e[1]+1],!1,!1,!0);_e&&(U+=_e.length)}}return{start:P,length:U}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={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=ah(i,this._bufferService.cols)}};Ko=xt([de(3,Xt),de(4,ps),de(5,pa),de(6,Zt),de(7,Di),de(8,Ii)],Ko);var lh=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},hh=class{constructor(){this._color=new lh,this._css=new lh}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Tt=Object.freeze((()=>{let e=[St.toColor("#2e3436"),St.toColor("#cc0000"),St.toColor("#4e9a06"),St.toColor("#c4a000"),St.toColor("#3465a4"),St.toColor("#75507b"),St.toColor("#06989a"),St.toColor("#d3d7cf"),St.toColor("#555753"),St.toColor("#ef2929"),St.toColor("#8ae234"),St.toColor("#fce94f"),St.toColor("#729fcf"),St.toColor("#ad7fa8"),St.toColor("#34e2e2"),St.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let n=t[i/36%6|0],a=t[i/6%6|0],h=t[i%6];e.push({css:At.toCss(n,a,h),rgba:At.toRgba(n,a,h)})}for(let i=0;i<24;i++){let n=8+i*10;e.push({css:At.toCss(n,n,n),rgba:At.toRgba(n,n,n)})}return e})()),hs=St.toColor("#ffffff"),pr=St.toColor("#000000"),ch=St.toColor("#ffffff"),uh=pr,lr={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},rp=hs,Yo=class extends Ve{constructor(e){super(),this._optionsService=e,this._contrastCache=new hh,this._halfContrastCache=new hh,this._onChangeColors=this._register(new ee),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:hs,background:pr,cursor:ch,cursorAccent:uh,selectionForeground:void 0,selectionBackgroundTransparent:lr,selectionBackgroundOpaque:pt.blend(pr,lr),selectionInactiveBackgroundTransparent:lr,selectionInactiveBackgroundOpaque:pt.blend(pr,lr),scrollbarSliderBackground:pt.opacity(hs,.2),scrollbarSliderHoverBackground:pt.opacity(hs,.4),scrollbarSliderActiveBackground:pt.opacity(hs,.5),overviewRulerBorder:hs,ansi:Tt.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=ht(e.foreground,hs),t.background=ht(e.background,pr),t.cursor=pt.blend(t.background,ht(e.cursor,ch)),t.cursorAccent=pt.blend(t.background,ht(e.cursorAccent,uh)),t.selectionBackgroundTransparent=ht(e.selectionBackground,lr),t.selectionBackgroundOpaque=pt.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=ht(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=pt.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?ht(e.selectionForeground,rh):void 0,t.selectionForeground===rh&&(t.selectionForeground=void 0),pt.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=pt.opacity(t.selectionBackgroundTransparent,.3)),pt.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=pt.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=ht(e.scrollbarSliderBackground,pt.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=ht(e.scrollbarSliderHoverBackground,pt.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=ht(e.scrollbarSliderActiveBackground,pt.opacity(t.foreground,.5)),t.overviewRulerBorder=ht(e.overviewRulerBorder,rp),t.ansi=Tt.slice(),t.ansi[0]=ht(e.black,Tt[0]),t.ansi[1]=ht(e.red,Tt[1]),t.ansi[2]=ht(e.green,Tt[2]),t.ansi[3]=ht(e.yellow,Tt[3]),t.ansi[4]=ht(e.blue,Tt[4]),t.ansi[5]=ht(e.magenta,Tt[5]),t.ansi[6]=ht(e.cyan,Tt[6]),t.ansi[7]=ht(e.white,Tt[7]),t.ansi[8]=ht(e.brightBlack,Tt[8]),t.ansi[9]=ht(e.brightRed,Tt[9]),t.ansi[10]=ht(e.brightGreen,Tt[10]),t.ansi[11]=ht(e.brightYellow,Tt[11]),t.ansi[12]=ht(e.brightBlue,Tt[12]),t.ansi[13]=ht(e.brightMagenta,Tt[13]),t.ansi[14]=ht(e.brightCyan,Tt[14]),t.ansi[15]=ht(e.brightWhite,Tt[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let n=0;n<i;n++)t.ansi[n+16]=ht(e.extendedAnsi[n],Tt[n+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()}}};Yo=xt([de(0,Zt)],Yo);function ht(e,t){if(e!==void 0)try{return St.toColor(e)}catch{}return t}var np=class{constructor(...e){this._entries=new Map;for(let[t,i]of e)this.set(t,i)}set(e,t){let i=this._entries.get(e);return this._entries.set(e,t),i}forEach(e){for(let[t,i]of this._entries.entries())e(t,i)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},op=class{constructor(){this._services=new np,this._services.set(ga,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let i=Qf(e).sort((h,d)=>h.index-d.index),n=[];for(let h of i){let d=this._services.get(h.id);if(!d)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${h.id._id}.`);n.push(d)}let a=i.length>0?i[0].index:t.length;if(t.length!==a)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${a+1} conflicts with ${t.length} static arguments`);return new e(...t,...n)}},ap={trace:0,debug:1,info:2,warn:3,error:4,off:5},lp="xterm.js: ",Jo=class extends Ve{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=ap[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,i){this._evalLazyOptionalParams(i),e.call(console,(this._optionsService.options.logger?"":lp)+t,...i)}trace(e,...t){var i;this._logLevel<=0&&this._log(((i=this._optionsService.options.logger)==null?void 0:i.trace.bind(this._optionsService.options.logger))??console.log,e,t)}debug(e,...t){var i;this._logLevel<=1&&this._log(((i=this._optionsService.options.logger)==null?void 0:i.debug.bind(this._optionsService.options.logger))??console.log,e,t)}info(e,...t){var i;this._logLevel<=2&&this._log(((i=this._optionsService.options.logger)==null?void 0:i.info.bind(this._optionsService.options.logger))??console.info,e,t)}warn(e,...t){var i;this._logLevel<=3&&this._log(((i=this._optionsService.options.logger)==null?void 0:i.warn.bind(this._optionsService.options.logger))??console.warn,e,t)}error(e,...t){var i;this._logLevel<=4&&this._log(((i=this._optionsService.options.logger)==null?void 0:i.error.bind(this._optionsService.options.logger))??console.error,e,t)}};Jo=xt([de(0,Zt)],Jo);var dh=class extends Ve{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new ee),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new ee),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new ee),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 i=0;i<Math.min(e,this.length);i++)t[i]=this._array[this._getCyclicIndex(i)];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,...i){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let n=this._length-1;n>=e;n--)this._array[this._getCyclicIndex(n+i.length)]=this._array[this._getCyclicIndex(n)];for(let n=0;n<i.length;n++)this._array[this._getCyclicIndex(e+n)]=i[n];if(i.length&&this.onInsertEmitter.fire({index:e,amount:i.length}),this._length+i.length>this._maxLength){let n=this._length+i.length-this._maxLength;this._startIndex+=n,this._length=this._maxLength,this.onTrimEmitter.fire(n)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let a=t-1;a>=0;a--)this.set(e+a+i,this.get(e+a));let n=e+t+i-this._length;if(n>0)for(this._length+=n;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let n=0;n<t;n++)this.set(e+n+i,this.get(e+n))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},$e=3,Rt=Object.freeze(new Or),Xr=0,io=2,mr=class Bc{constructor(t,i,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(t*$e);let a=i||di.fromCharData([0,Qh,1,0]);for(let h=0;h<t;++h)this.setCell(h,a);this.length=t}get(t){let i=this._data[t*$e+0],n=i&2097151;return[this._data[t*$e+1],i&2097152?this._combined[t]:n?es(n):"",i>>22,i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):n]}set(t,i){this._data[t*$e+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*$e+0]=t|2097152|i[2]<<22):this._data[t*$e+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*$e+0]>>22}hasWidth(t){return this._data[t*$e+0]&12582912}getFg(t){return this._data[t*$e+1]}getBg(t){return this._data[t*$e+2]}hasContent(t){return this._data[t*$e+0]&4194303}getCodePoint(t){let i=this._data[t*$e+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*$e+0]&2097152}getString(t){let i=this._data[t*$e+0];return i&2097152?this._combined[t]:i&2097151?es(i&2097151):""}isProtected(t){return this._data[t*$e+2]&536870912}loadCell(t,i){return Xr=t*$e,i.content=this._data[Xr+0],i.fg=this._data[Xr+1],i.bg=this._data[Xr+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*$e+0]=i.content,this._data[t*$e+1]=i.fg,this._data[t*$e+2]=i.bg}setCellFromCodepoint(t,i,n,a){a.bg&268435456&&(this._extendedAttrs[t]=a.extended),this._data[t*$e+0]=i|n<<22,this._data[t*$e+1]=a.fg,this._data[t*$e+2]=a.bg}addCodepointToCell(t,i,n){let a=this._data[t*$e+0];a&2097152?this._combined[t]+=es(i):a&2097151?(this._combined[t]=es(a&2097151)+es(i),a&=-2097152,a|=2097152):a=i|1<<22,n&&(a&=-12582913,a|=n<<22),this._data[t*$e+0]=a}insertCells(t,i,n){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,n),i<this.length-t){let a=new di;for(let h=this.length-t-i-1;h>=0;--h)this.setCell(t+i+h,this.loadCell(t+h,a));for(let h=0;h<i;++h)this.setCell(t+h,n)}else for(let a=t;a<this.length;++a)this.setCell(a,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(t,i,n){if(t%=this.length,i<this.length-t){let a=new di;for(let h=0;h<this.length-t-i;++h)this.setCell(t+h,this.loadCell(t+i+h,a));for(let h=this.length-i;h<this.length;++h)this.setCell(h,n)}else for(let a=t;a<this.length;++a)this.setCell(a,n);t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,n),this.getWidth(t)===0&&!this.hasContent(t)&&this.setCellFromCodepoint(t,0,1,n)}replaceCells(t,i,n,a=!1){if(a){for(t&&this.getWidth(t-1)===2&&!this.isProtected(t-1)&&this.setCellFromCodepoint(t-1,0,1,n),i<this.length&&this.getWidth(i-1)===2&&!this.isProtected(i)&&this.setCellFromCodepoint(i,0,1,n);t<i&&t<this.length;)this.isProtected(t)||this.setCell(t,n),t++;return}for(t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,n),i<this.length&&this.getWidth(i-1)===2&&this.setCellFromCodepoint(i,0,1,n);t<i&&t<this.length;)this.setCell(t++,n)}resize(t,i){if(t===this.length)return this._data.length*4*io<this._data.buffer.byteLength;let n=t*$e;if(t>this.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let a=new Uint32Array(n);a.set(this._data),this._data=a}for(let a=this.length;a<t;++a)this.setCell(a,i)}else{this._data=this._data.subarray(0,n);let a=Object.keys(this._combined);for(let d=0;d<a.length;d++){let g=parseInt(a[d],10);g>=t&&delete this._combined[g]}let h=Object.keys(this._extendedAttrs);for(let d=0;d<h.length;d++){let g=parseInt(h[d],10);g>=t&&delete this._extendedAttrs[g]}}return this.length=t,n*4*io<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*io<this._data.buffer.byteLength){let t=new Uint32Array(this._data.length);return t.set(this._data),this._data=t,1}return 0}fill(t,i=!1){if(i){for(let n=0;n<this.length;++n)this.isProtected(n)||this.setCell(n,t);return}this._combined={},this._extendedAttrs={};for(let n=0;n<this.length;++n)this.setCell(n,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 i in t._combined)this._combined[i]=t._combined[i];this._extendedAttrs={};for(let i in t._extendedAttrs)this._extendedAttrs[i]=t._extendedAttrs[i];this.isWrapped=t.isWrapped}clone(){let t=new Bc(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let i in this._combined)t._combined[i]=this._combined[i];for(let i in this._extendedAttrs)t._extendedAttrs[i]=this._extendedAttrs[i];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*$e+0]&4194303)return t+(this._data[t*$e+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*$e+0]&4194303||this._data[t*$e+2]&50331648)return t+(this._data[t*$e+0]>>22);return 0}copyCellsFrom(t,i,n,a,h){let d=t._data;if(h)for(let v=a-1;v>=0;v--){for(let m=0;m<$e;m++)this._data[(n+v)*$e+m]=d[(i+v)*$e+m];d[(i+v)*$e+2]&268435456&&(this._extendedAttrs[n+v]=t._extendedAttrs[i+v])}else for(let v=0;v<a;v++){for(let m=0;m<$e;m++)this._data[(n+v)*$e+m]=d[(i+v)*$e+m];d[(i+v)*$e+2]&268435456&&(this._extendedAttrs[n+v]=t._extendedAttrs[i+v])}let g=Object.keys(t._combined);for(let v=0;v<g.length;v++){let m=parseInt(g[v],10);m>=i&&(this._combined[m-i+n]=t._combined[m])}}translateToString(t,i,n,a){i=i??0,n=n??this.length,t&&(n=Math.min(n,this.getTrimmedLength())),a&&(a.length=0);let h="";for(;i<n;){let d=this._data[i*$e+0],g=d&2097151,v=d&2097152?this._combined[i]:g?es(g):ts;if(h+=v,a)for(let m=0;m<v.length;++m)a.push(i);i+=d>>22||1}return a&&a.push(i),h}};function hp(e,t,i,n,a,h){let d=[];for(let g=0;g<e.length-1;g++){let v=g,m=e.get(++v);if(!m.isWrapped)continue;let R=[e.get(g)];for(;v<e.length&&m.isWrapped;)R.push(m),m=e.get(++v);if(!h&&n>=g&&n<v){g+=R.length-1;continue}let k=0,B=kr(R,k,t),L=1,P=0;for(;L<R.length;){let Z=kr(R,L,t),_e=Z-P,rt=i-B,Ne=Math.min(_e,rt);R[k].copyCellsFrom(R[L],P,B,Ne,!1),B+=Ne,B===i&&(k++,B=0),P+=Ne,P===Z&&(L++,P=0),B===0&&k!==0&&R[k-1].getWidth(i-1)===2&&(R[k].copyCellsFrom(R[k-1],i-1,B++,1,!1),R[k-1].setCell(i-1,a))}R[k].replaceCells(B,i,a);let U=0;for(let Z=R.length-1;Z>0&&(Z>k||R[Z].getTrimmedLength()===0);Z--)U++;U>0&&(d.push(g+R.length-U),d.push(U)),g+=R.length-1}return d}function cp(e,t){let i=[],n=0,a=t[n],h=0;for(let d=0;d<e.length;d++)if(a===d){let g=t[++n];e.onDeleteEmitter.fire({index:d-h,amount:g}),d+=g-1,h+=g,a=t[++n]}else i.push(d);return{layout:i,countRemoved:h}}function up(e,t){let i=[];for(let n=0;n<t.length;n++)i.push(e.get(t[n]));for(let n=0;n<i.length;n++)e.set(n,i[n]);e.length=t.length}function dp(e,t,i){let n=[],a=e.map((v,m)=>kr(e,m,t)).reduce((v,m)=>v+m),h=0,d=0,g=0;for(;g<a;){if(a-g<i){n.push(a-g);break}h+=i;let v=kr(e,d,t);h>v&&(h-=v,d++);let m=e[d].getWidth(h-1)===2;m&&h--;let R=m?i-1:i;n.push(R),g+=R}return n}function kr(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let n=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,a=e[t+1].getWidth(0)===2;return n&&a?i-1:i}var Ic=class Dc{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=Dc._nextId++,this._onDispose=this.register(new ee),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),_s(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};Ic._nextId=1;var fp=Ic,Lt={},cs=Lt.B;Lt[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:"≥","{":"π","|":"≠","}":"£","~":"·"};Lt.A={"#":"£"};Lt.B=void 0;Lt[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Lt.C=Lt[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Lt.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Lt.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Lt.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Lt.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Lt.E=Lt[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Lt.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Lt.H=Lt[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Lt["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var fh=4294967295,_h=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Rt.clone(),this.savedCharset=cs,this.markers=[],this._nullCell=di.fromCharData([0,Qh,1,0]),this._whitespaceCell=di.fromCharData([0,ts,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new dn,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new dh(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 ln),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 ln),this._whitespaceCell}getBlankLine(e,t){return new mr(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>fh?fh:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Rt);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 dh(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Rt),n=0,a=this._getCorrectBufferLength(t);if(a>this.lines.maxLength&&(this.lines.maxLength=a),this.lines.length>0){if(this._cols<e)for(let d=0;d<this.lines.length;d++)n+=+this.lines.get(d).resize(e,i);let h=0;if(this._rows<t)for(let d=this._rows;d<t;d++)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 mr(e,i)):this.ybase>0&&this.lines.length<=this.ybase+this.y+h+1?(this.ybase--,h++,this.ydisp>0&&this.ydisp--):this.lines.push(new mr(e,i)));else for(let d=this._rows;d>t;d--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(a<this.lines.maxLength){let d=this.lines.length-a;d>0&&(this.lines.trimStart(d),this.ybase=Math.max(this.ybase-d,0),this.ydisp=Math.max(this.ydisp-d,0),this.savedY=Math.max(this.savedY-d,0)),this.lines.maxLength=a}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),h&&(this.y+=h),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 h=0;h<this.lines.length;h++)n+=+this.lines.get(h).resize(e,i);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),n>.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 i=this._optionsService.rawOptions.reflowCursorLine,n=hp(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Rt),i);if(n.length>0){let a=cp(this.lines,n);up(this.lines,a.layout),this._reflowLargerAdjustViewport(e,t,a.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let n=this.getNullCell(Rt),a=i;for(;a-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new mr(e,n))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-i,0)}_reflowSmaller(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,n=this.getNullCell(Rt),a=[],h=0;for(let d=this.lines.length-1;d>=0;d--){let g=this.lines.get(d);if(!g||!g.isWrapped&&g.getTrimmedLength()<=e)continue;let v=[g];for(;g.isWrapped&&d>0;)g=this.lines.get(--d),v.unshift(g);if(!i){let Ne=this.ybase+this.y;if(Ne>=d&&Ne<d+v.length)continue}let m=v[v.length-1].getTrimmedLength(),R=dp(v,this._cols,e),k=R.length-v.length,B;this.ybase===0&&this.y!==this.lines.length-1?B=Math.max(0,this.y-this.lines.maxLength+k):B=Math.max(0,this.lines.length-this.lines.maxLength+k);let L=[];for(let Ne=0;Ne<k;Ne++){let H=this.getBlankLine(Rt,!0);L.push(H)}L.length>0&&(a.push({start:d+v.length+h,newLines:L}),h+=L.length),v.push(...L);let P=R.length-1,U=R[P];U===0&&(P--,U=R[P]);let Z=v.length-k-1,_e=m;for(;Z>=0;){let Ne=Math.min(_e,U);if(v[P]===void 0)break;if(v[P].copyCellsFrom(v[Z],_e-Ne,U-Ne,Ne,!0),U-=Ne,U===0&&(P--,U=R[P]),_e-=Ne,_e===0){Z--;let H=Math.max(Z,0);_e=kr(v,H,this._cols)}}for(let Ne=0;Ne<v.length;Ne++)R[Ne]<e&&v[Ne].setCell(R[Ne],n);let rt=k-B;for(;rt-- >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+h)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+k,this.ybase+t-1)}if(a.length>0){let d=[],g=[];for(let U=0;U<this.lines.length;U++)g.push(this.lines.get(U));let v=this.lines.length,m=v-1,R=0,k=a[R];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+h);let B=0;for(let U=Math.min(this.lines.maxLength-1,v+h-1);U>=0;U--)if(k&&k.start>m+B){for(let Z=k.newLines.length-1;Z>=0;Z--)this.lines.set(U--,k.newLines[Z]);U++,d.push({index:m+1,amount:k.newLines.length}),B+=k.newLines.length,k=a[++R]}else this.lines.set(U,g[m--]);let L=0;for(let U=d.length-1;U>=0;U--)d[U].index+=L,this.lines.onInsertEmitter.fire(d[U]),L+=d[U].amount;let P=Math.max(0,v+h-this.lines.maxLength);P>0&&this.lines.onTrimEmitter.fire(P)}}translateBufferLineToString(e,t,i=0,n){let a=this.lines.get(e);return a?a.translateToString(t,i,n):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+1<this.lines.length&&this.lines.get(i+1).isWrapped;)i++;return{first:t,last:i}}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 fp(e);return this.markers.push(t),t.register(this.lines.onTrim(i=>{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.line<i.index+i.amount&&t.dispose(),t.line>i.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},_p=class extends Ve{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new ee),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 _h(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new _h(!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)}},Nc=2,Hc=1,Xo=class extends Ve{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new ee),this.onResize=this._onResize.event,this._onScroll=this._register(new ee),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Nc),this.rows=Math.max(e.rawOptions.rows||0,Hc),this.buffers=this._register(new _p(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,n=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:n})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,n;n=this._cachedBlankLine,(!n||n.length!==this.cols||n.getFg(0)!==e.fg||n.getBg(0)!==e.bg)&&(n=i.getBlankLine(e,t),this._cachedBlankLine=n),n.isWrapped=t;let a=i.ybase+i.scrollTop,h=i.ybase+i.scrollBottom;if(i.scrollTop===0){let d=i.lines.isFull;h===i.lines.length-1?d?i.lines.recycle().copyFrom(n):i.lines.push(n.clone()):i.lines.splice(h+1,0,n.clone()),d?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let d=h-a+1;i.lines.shiftElements(a+1,d-1,-1),i.lines.set(h,n.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let n=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),n!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};Xo=xt([de(0,Zt)],Xo);var Ps={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:un,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},gp=["normal","bold","100","200","300","400","500","600","700","800","900"],pp=class extends Ve{constructor(e){super(),this._onOptionChange=this._register(new ee),this.onOptionChange=this._onOptionChange.event;let t={...Ps};for(let i in e)if(i in t)try{let n=e[i];t[i]=this._sanitizeAndValidateOption(i,n)}catch(n){console.error(n)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(vt(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in Ps))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,n)=>{if(!(i in Ps))throw new Error(`No option with key "${i}"`);n=this._sanitizeAndValidateOption(i,n),this.rawOptions[i]!==n&&(this.rawOptions[i]=n,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let n={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,n)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=Ps[e]),!mp(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Ps[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=gp.includes(t)?t:Ps[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 mp(e){return e==="block"||e==="underline"||e==="bar"}function vr(e,t=5){if(typeof e!="object")return e;let i=Array.isArray(e)?[]:{};for(let n in e)i[n]=t<=1?e[n]:e[n]&&vr(e[n],t-1);return i}var gh=Object.freeze({insertMode:!1}),ph=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),Zo=class extends Ve{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new ee),this.onData=this._onData.event,this._onUserInput=this._register(new ee),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new ee),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new ee),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=vr(gh),this.decPrivateModes=vr(ph)}reset(){this.modes=vr(gh),this.decPrivateModes=vr(ph)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(n=>n.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))}};Zo=xt([de(0,Xt),de(1,rc),de(2,Zt)],Zo);var mh={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 so(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}var ro=String.fromCharCode,vh={DEFAULT:e=>{let t=[so(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${ro(t[0])}${ro(t[1])}${ro(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${so(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${so(e,!0)};${e.x};${e.y}${t}`}},Qo=class extends Ve{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new ee),this.onProtocolChange=this._onProtocolChange.event;for(let n of Object.keys(mh))this.addProtocol(n,mh[n]);for(let n of Object.keys(vh))this.addEncoding(n,vh[n]);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,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let n=t/i,a=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(a/=n+0,Math.abs(e.deltaY)<50&&(a*=.3),this._wheelPartialScroll+=a,a=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(a*=this._bufferService.rows),a}_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,i){if(i){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)}};Qo=xt([de(0,Xt),de(1,ps),de(2,Zt)],Qo);var no=[[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]],vp=[[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]],Pt;function yp(e,t){let i=0,n=t.length-1,a;if(e<t[0][0]||e>t[n][1])return!1;for(;n>=i;)if(a=i+n>>1,e>t[a][1])i=a+1;else if(e<t[a][0])n=a-1;else return!0;return!1}var Sp=class{constructor(){if(this.version="6",!Pt){Pt=new Uint8Array(65536),Pt.fill(1),Pt[0]=0,Pt.fill(0,1,32),Pt.fill(0,127,160),Pt.fill(2,4352,4448),Pt[9001]=2,Pt[9002]=2,Pt.fill(2,11904,42192),Pt[12351]=1,Pt.fill(2,44032,55204),Pt.fill(2,63744,64256),Pt.fill(2,65040,65050),Pt.fill(2,65072,65136),Pt.fill(2,65280,65377),Pt.fill(2,65504,65511);for(let e=0;e<no.length;++e)Pt.fill(0,no[e][0],no[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?Pt[e]:yp(e,vp)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),n=i===0&&t!==0;if(n){let a=us.extractWidth(t);a===0?n=!1:a>i&&(i=a)}return us.createPropertyValue(0,i,n)}},us=class on{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new ee,this.onChange=this._onChange.event;let t=new Sp;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,i,n=!1){return(t&16777215)<<3|(i&3)<<1|(n?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 i=0,n=0,a=t.length;for(let h=0;h<a;++h){let d=t.charCodeAt(h);if(55296<=d&&d<=56319){if(++h>=a)return i+this.wcwidth(d);let m=t.charCodeAt(h);56320<=m&&m<=57343?d=(d-55296)*1024+m-56320+65536:i+=this.wcwidth(m)}let g=this.charProperties(d,n),v=on.extractWidth(g);on.extractShouldJoin(g)&&(v-=on.extractWidth(n)),i+=v,n=g}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},bp=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 yh(e){var n;let t=(n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1))==null?void 0:n.get(e.cols-1),i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);i&&t&&(i.isWrapped=t[3]!==0&&t[3]!==32)}var hr=2147483647,wp=256,Uc=class ea{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>wp)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new ea;if(!t.length)return i;for(let n=Array.isArray(t[0])?1:0;n<t.length;++n){let a=t[n];if(Array.isArray(a))for(let h=0;h<a.length;++h)i.addSubParam(a[h]);else i.addParam(a)}return i}clone(){let t=new ea(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 i=0;i<this.length;++i){t.push(this.params[i]);let n=this._subParamsIdx[i]>>8,a=this._subParamsIdx[i]&255;a-n>0&&t.push(Array.prototype.slice.call(this._subParams,n,a))}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>hr?hr: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>hr?hr:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,n=this._subParamsIdx[t]&255;return n-i>0?this._subParams.subarray(i,n):null}getSubParamsAll(){let t={};for(let i=0;i<this.length;++i){let n=this._subParamsIdx[i]>>8,a=this._subParamsIdx[i]&255;a-n>0&&(t[i]=this._subParams.slice(n,a))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,a=n[i-1];n[i-1]=~a?Math.min(a*10+t,hr):t}},cr=[],Cp=class{constructor(){this._state=0,this._active=cr,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 i=this._handlers[e];return i.push(t),{dispose:()=>{let n=i.indexOf(t);n!==-1&&i.splice(n,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=cr}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=cr,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||cr,!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,i){if(!this._active.length)this._handlerFb(this._id,"PUT",mn(e,t,i));else for(let n=this._active.length-1;n>=0;n--)this._active[n].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t<i;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+n-48}this._state===2&&i-t>0&&this._put(e,t,i)}}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 i=!1,n=this._active.length-1,a=!1;if(this._stack.paused&&(n=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;n>=0&&(i=this._active[n].end(e),i!==!0);n--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!1,i;n--}for(;n>=0;n--)if(i=this._active[n].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!0,i}this._active=cr,this._id=-1,this._state=0}}},ni=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=mn(e,t,i),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(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,t}},ur=[],xp=class{constructor(){this._handlers=Object.create(null),this._active=ur,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=ur}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let n=i.indexOf(t);n!==-1&&i.splice(n,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=ur,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||ur,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",mn(e,t,i));else for(let n=this._active.length-1;n>=0;n--)this._active[n].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let i=!1,n=this._active.length-1,a=!1;if(this._stack.paused&&(n=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;n>=0&&(i=this._active[n].unhook(e),i!==!0);n--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!1,i;n--}for(;n>=0;n--)if(i=this._active[n].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!0,i}this._active=ur,this._ident=0}},yr=new Uc;yr.addParam(0);var Sh=class{constructor(e){this._handler=e,this._data="",this._params=yr,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():yr,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=mn(e,t,i),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(i=>(this._params=yr,this._data="",this._hitLimit=!1,i));return this._params=yr,this._data="",this._hitLimit=!1,t}},kp=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,n){this.table[t<<8|e]=i<<4|n}addMany(e,t,i,n){for(let a=0;a<e.length;a++)this.table[t<<8|e[a]]=i<<4|n}},ui=160,Ep=(function(){let e=new kp(4095),t=Array.apply(null,Array(256)).map((g,v)=>v),i=(g,v)=>t.slice(g,v),n=i(32,127),a=i(0,24);a.push(25),a.push.apply(a,i(28,32));let h=i(0,14),d;e.setDefault(1,0),e.addMany(n,0,2,0);for(d in h)e.addMany([24,26,153,154],d,3,0),e.addMany(i(128,144),d,3,0),e.addMany(i(144,152),d,3,0),e.add(156,d,0,0),e.add(27,d,11,1),e.add(157,d,4,8),e.addMany([152,158,159],d,0,7),e.add(155,d,11,3),e.add(144,d,11,9);return e.addMany(a,0,3,0),e.addMany(a,1,3,1),e.add(127,1,0,1),e.addMany(a,8,0,8),e.addMany(a,3,3,3),e.add(127,3,0,3),e.addMany(a,4,3,4),e.add(127,4,0,4),e.addMany(a,6,3,6),e.addMany(a,5,3,5),e.add(127,5,0,5),e.addMany(a,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(n,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(n,7,0,7),e.addMany(a,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(a,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(a,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(a,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(a,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(a,13,13,13),e.addMany(n,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(ui,0,2,0),e.add(ui,8,5,8),e.add(ui,6,0,6),e.add(ui,11,0,11),e.add(ui,13,13,13),e})(),Rp=class extends Ve{constructor(e=Ep){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 Uc,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,i,n)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,i)=>{},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(vt(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new Cp),this._dcsParser=this._register(new xp),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>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 a=0;a<e.intermediates.length;++a){let h=e.intermediates.charCodeAt(a);if(32>h||h>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=h}}if(e.final.length!==1)throw new Error("final must be a single byte");let n=e.final.charCodeAt(0);if(t[0]>n||n>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=n,i}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 i=this._identifier(e,[48,126]);this._escHandlers[i]===void 0&&(this._escHandlers[i]=[]);let n=this._escHandlers[i];return n.push(t),{dispose:()=>{let a=n.indexOf(t);a!==-1&&n.splice(a,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 i=this._identifier(e);this._csiHandlers[i]===void 0&&(this._csiHandlers[i]=[]);let n=this._csiHandlers[i];return n.push(t),{dispose:()=>{let a=n.indexOf(t);a!==-1&&n.splice(a,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,i,n,a){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=n,this._parseStack.chunkPos=a}parse(e,t,i){let n=0,a=0,h=0,d;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,h=this._parseStack.chunkPos+1;else{if(i===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let g=this._parseStack.handlers,v=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(i===!1&&v>-1){for(;v>=0&&(d=g[v](this._params),d!==!0);v--)if(d instanceof Promise)return this._parseStack.handlerPos=v,d}this._parseStack.handlers=[];break;case 4:if(i===!1&&v>-1){for(;v>=0&&(d=g[v](),d!==!0);v--)if(d instanceof Promise)return this._parseStack.handlerPos=v,d}this._parseStack.handlers=[];break;case 6:if(n=e[this._parseStack.chunkPos],d=this._dcsParser.unhook(n!==24&&n!==26,i),d)return d;n===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(n=e[this._parseStack.chunkPos],d=this._oscParser.end(n!==24&&n!==26,i),d)return d;n===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,h=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let g=h;g<t;++g){switch(n=e[g],a=this._transitions.table[this.currentState<<8|(n<160?n:ui)],a>>4){case 2:for(let B=g+1;;++B){if(B>=t||(n=e[B])<32||n>126&&n<ui){this._printHandler(e,g,B),g=B-1;break}if(++B>=t||(n=e[B])<32||n>126&&n<ui){this._printHandler(e,g,B),g=B-1;break}if(++B>=t||(n=e[B])<32||n>126&&n<ui){this._printHandler(e,g,B),g=B-1;break}if(++B>=t||(n=e[B])<32||n>126&&n<ui){this._printHandler(e,g,B),g=B-1;break}}break;case 3:this._executeHandlers[n]?this._executeHandlers[n]():this._executeHandlerFb(n),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:g,code:n,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let v=this._csiHandlers[this._collect<<8|n],m=v?v.length-1:-1;for(;m>=0&&(d=v[m](this._params),d!==!0);m--)if(d instanceof Promise)return this._preserveStack(3,v,m,a,g),d;m<0&&this._csiHandlerFb(this._collect<<8|n,this._params),this.precedingJoinState=0;break;case 8:do switch(n){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(n-48)}while(++g<t&&(n=e[g])>47&&n<60);g--;break;case 9:this._collect<<=8,this._collect|=n;break;case 10:let R=this._escHandlers[this._collect<<8|n],k=R?R.length-1:-1;for(;k>=0&&(d=R[k](),d!==!0);k--)if(d instanceof Promise)return this._preserveStack(4,R,k,a,g),d;k<0&&this._escHandlerFb(this._collect<<8|n),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|n,this._params);break;case 13:for(let B=g+1;;++B)if(B>=t||(n=e[B])===24||n===26||n===27||n>127&&n<ui){this._dcsParser.put(e,g,B),g=B-1;break}break;case 14:if(d=this._dcsParser.unhook(n!==24&&n!==26),d)return this._preserveStack(6,[],0,a,g),d;n===27&&(a|=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 B=g+1;;B++)if(B>=t||(n=e[B])<32||n>127&&n<ui){this._oscParser.put(e,g,B),g=B-1;break}break;case 6:if(d=this._oscParser.end(n!==24&&n!==26),d)return this._preserveStack(5,[],0,a,g),d;n===27&&(a|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break}this.currentState=a&15}}},Ap=/^([\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})$/,Mp=/^[\da-f]+$/;function bh(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf("rgb:")===0){t=t.slice(4);let i=Ap.exec(t);if(i){let n=i[1]?15:i[4]?255:i[7]?4095:65535;return[Math.round(parseInt(i[1]||i[4]||i[7]||i[10],16)/n*255),Math.round(parseInt(i[2]||i[5]||i[8]||i[11],16)/n*255),Math.round(parseInt(i[3]||i[6]||i[9]||i[12],16)/n*255)]}}else if(t.indexOf("#")===0&&(t=t.slice(1),Mp.exec(t)&&[3,6,9,12].includes(t.length))){let i=t.length/3,n=[0,0,0];for(let a=0;a<3;++a){let h=parseInt(t.slice(i*a,i*a+i),16);n[a]=i===1?h<<4:i===2?h:i===3?h>>4:h>>8}return n}}function oo(e,t){let i=e.toString(16),n=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return n;case 12:return(n+n).slice(0,3);default:return n+n}}function Op(e,t=16){let[i,n,a]=e;return`rgb:${oo(i,t)}/${oo(n,t)}/${oo(a,t)}`}var Tp={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Qi=131072,wh=10;function Ch(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 xh=5e3,kh=0,Pp=class extends Ve{constructor(e,t,i,n,a,h,d,g,v=new Rp){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=n,this._optionsService=a,this._oscLinkService=h,this._coreMouseService=d,this._unicodeService=g,this._parser=v,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new Xf,this._utf8Decoder=new Zf,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Rt.clone(),this._eraseAttrDataInternal=Rt.clone(),this._onRequestBell=this._register(new ee),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new ee),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new ee),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new ee),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new ee),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new ee),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new ee),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new ee),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new ee),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new ee),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new ee),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new ee),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new ee),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 ta(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(m=>this._activeBuffer=m.activeBuffer)),this._parser.setCsiHandlerFallback((m,R)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(m),params:R.toArray()})}),this._parser.setEscHandlerFallback(m=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(m)})}),this._parser.setExecuteHandlerFallback(m=>{this._logService.debug("Unknown EXECUTE code: ",{code:m})}),this._parser.setOscHandlerFallback((m,R,k)=>{this._logService.debug("Unknown OSC code: ",{identifier:m,action:R,data:k})}),this._parser.setDcsHandlerFallback((m,R,k)=>{R==="HOOK"&&(k=k.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(m),action:R,payload:k})}),this._parser.setPrintHandler((m,R,k)=>this.print(m,R,k)),this._parser.registerCsiHandler({final:"@"},m=>this.insertChars(m)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},m=>this.scrollLeft(m)),this._parser.registerCsiHandler({final:"A"},m=>this.cursorUp(m)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},m=>this.scrollRight(m)),this._parser.registerCsiHandler({final:"B"},m=>this.cursorDown(m)),this._parser.registerCsiHandler({final:"C"},m=>this.cursorForward(m)),this._parser.registerCsiHandler({final:"D"},m=>this.cursorBackward(m)),this._parser.registerCsiHandler({final:"E"},m=>this.cursorNextLine(m)),this._parser.registerCsiHandler({final:"F"},m=>this.cursorPrecedingLine(m)),this._parser.registerCsiHandler({final:"G"},m=>this.cursorCharAbsolute(m)),this._parser.registerCsiHandler({final:"H"},m=>this.cursorPosition(m)),this._parser.registerCsiHandler({final:"I"},m=>this.cursorForwardTab(m)),this._parser.registerCsiHandler({final:"J"},m=>this.eraseInDisplay(m,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},m=>this.eraseInDisplay(m,!0)),this._parser.registerCsiHandler({final:"K"},m=>this.eraseInLine(m,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},m=>this.eraseInLine(m,!0)),this._parser.registerCsiHandler({final:"L"},m=>this.insertLines(m)),this._parser.registerCsiHandler({final:"M"},m=>this.deleteLines(m)),this._parser.registerCsiHandler({final:"P"},m=>this.deleteChars(m)),this._parser.registerCsiHandler({final:"S"},m=>this.scrollUp(m)),this._parser.registerCsiHandler({final:"T"},m=>this.scrollDown(m)),this._parser.registerCsiHandler({final:"X"},m=>this.eraseChars(m)),this._parser.registerCsiHandler({final:"Z"},m=>this.cursorBackwardTab(m)),this._parser.registerCsiHandler({final:"`"},m=>this.charPosAbsolute(m)),this._parser.registerCsiHandler({final:"a"},m=>this.hPositionRelative(m)),this._parser.registerCsiHandler({final:"b"},m=>this.repeatPrecedingCharacter(m)),this._parser.registerCsiHandler({final:"c"},m=>this.sendDeviceAttributesPrimary(m)),this._parser.registerCsiHandler({prefix:">",final:"c"},m=>this.sendDeviceAttributesSecondary(m)),this._parser.registerCsiHandler({final:"d"},m=>this.linePosAbsolute(m)),this._parser.registerCsiHandler({final:"e"},m=>this.vPositionRelative(m)),this._parser.registerCsiHandler({final:"f"},m=>this.hVPosition(m)),this._parser.registerCsiHandler({final:"g"},m=>this.tabClear(m)),this._parser.registerCsiHandler({final:"h"},m=>this.setMode(m)),this._parser.registerCsiHandler({prefix:"?",final:"h"},m=>this.setModePrivate(m)),this._parser.registerCsiHandler({final:"l"},m=>this.resetMode(m)),this._parser.registerCsiHandler({prefix:"?",final:"l"},m=>this.resetModePrivate(m)),this._parser.registerCsiHandler({final:"m"},m=>this.charAttributes(m)),this._parser.registerCsiHandler({final:"n"},m=>this.deviceStatus(m)),this._parser.registerCsiHandler({prefix:"?",final:"n"},m=>this.deviceStatusPrivate(m)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},m=>this.softReset(m)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},m=>this.setCursorStyle(m)),this._parser.registerCsiHandler({final:"r"},m=>this.setScrollRegion(m)),this._parser.registerCsiHandler({final:"s"},m=>this.saveCursor(m)),this._parser.registerCsiHandler({final:"t"},m=>this.windowOptions(m)),this._parser.registerCsiHandler({final:"u"},m=>this.restoreCursor(m)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},m=>this.insertColumns(m)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},m=>this.deleteColumns(m)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},m=>this.selectProtected(m)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},m=>this.requestMode(m,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},m=>this.requestMode(m,!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(rn.IND,()=>this.index()),this._parser.setExecuteHandler(rn.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(rn.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new ni(m=>(this.setTitle(m),this.setIconName(m),!0))),this._parser.registerOscHandler(1,new ni(m=>this.setIconName(m))),this._parser.registerOscHandler(2,new ni(m=>this.setTitle(m))),this._parser.registerOscHandler(4,new ni(m=>this.setOrReportIndexedColor(m))),this._parser.registerOscHandler(8,new ni(m=>this.setHyperlink(m))),this._parser.registerOscHandler(10,new ni(m=>this.setOrReportFgColor(m))),this._parser.registerOscHandler(11,new ni(m=>this.setOrReportBgColor(m))),this._parser.registerOscHandler(12,new ni(m=>this.setOrReportCursorColor(m))),this._parser.registerOscHandler(104,new ni(m=>this.restoreIndexedColor(m))),this._parser.registerOscHandler(110,new ni(m=>this.restoreFgColor(m))),this._parser.registerOscHandler(111,new ni(m=>this.restoreBgColor(m))),this._parser.registerOscHandler(112,new ni(m=>this.restoreCursorColor(m))),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 m in Lt)this._parser.registerEscHandler({intermediates:"(",final:m},()=>this.selectCharset("("+m)),this._parser.registerEscHandler({intermediates:")",final:m},()=>this.selectCharset(")"+m)),this._parser.registerEscHandler({intermediates:"*",final:m},()=>this.selectCharset("*"+m)),this._parser.registerEscHandler({intermediates:"+",final:m},()=>this.selectCharset("+"+m)),this._parser.registerEscHandler({intermediates:"-",final:m},()=>this.selectCharset("-"+m)),this._parser.registerEscHandler({intermediates:".",final:m},()=>this.selectCharset("."+m)),this._parser.registerEscHandler({intermediates:"/",final:m},()=>this.selectCharset("/"+m));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(m=>(this._logService.error("Parsing error: ",m),m)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Sh((m,R)=>this.requestStatusString(m,R)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,n){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=n}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,i)=>setTimeout(()=>i("#SLOW_TIMEOUT"),xh))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${xh} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,n=this._activeBuffer.x,a=this._activeBuffer.y,h=0,d=this._parseStack.paused;if(d){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;n=this._parseStack.cursorStartX,a=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Qi&&(h=this._parseStack.position+Qi)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,m=>String.fromCharCode(m)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(m=>m.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<Qi&&(this._parseBuffer=new Uint32Array(Math.min(e.length,Qi))),d||this._dirtyRowTracker.clearRange(),e.length>Qi)for(let m=h;m<e.length;m+=Qi){let R=m+Qi<e.length?m+Qi:e.length,k=typeof e=="string"?this._stringDecoder.decode(e.substring(m,R),this._parseBuffer):this._utf8Decoder.decode(e.subarray(m,R),this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,k))return this._preserveStack(n,a,k,m),this._logSlowResolvingAsync(i),i}else if(!d){let m=typeof e=="string"?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,m))return this._preserveStack(n,a,m,0),this._logSlowResolvingAsync(i),i}(this._activeBuffer.x!==n||this._activeBuffer.y!==a)&&this._onCursorMove.fire();let g=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),v=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);v<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(v,this._bufferService.rows-1),end:Math.min(g,this._bufferService.rows-1)})}print(e,t,i){let n,a,h=this._charsetService.charset,d=this._optionsService.rawOptions.screenReaderMode,g=this._bufferService.cols,v=this._coreService.decPrivateModes.wraparound,m=this._coreService.modes.insertMode,R=this._curAttrData,k=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&i-t>0&&k.getWidth(this._activeBuffer.x-1)===2&&k.setCellFromCodepoint(this._activeBuffer.x-1,0,1,R);let B=this._parser.precedingJoinState;for(let L=t;L<i;++L){if(n=e[L],n<127&&h){let _e=h[String.fromCharCode(n)];_e&&(n=_e.charCodeAt(0))}let P=this._unicodeService.charProperties(n,B);a=us.extractWidth(P);let U=us.extractShouldJoin(P),Z=U?us.extractWidth(B):0;if(B=P,d&&this._onA11yChar.fire(es(n)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+a-Z>g){if(v){let _e=k,rt=this._activeBuffer.x-Z;for(this._activeBuffer.x=Z,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),k=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),Z>0&&k instanceof mr&&k.copyCellsFrom(_e,rt,0,Z,!1);rt<g;)_e.setCellFromCodepoint(rt++,0,1,R)}else if(this._activeBuffer.x=g-1,a===2)continue}if(U&&this._activeBuffer.x){let _e=k.getWidth(this._activeBuffer.x-1)?1:2;k.addCodepointToCell(this._activeBuffer.x-_e,n,a);for(let rt=a-Z;--rt>=0;)k.setCellFromCodepoint(this._activeBuffer.x++,0,0,R);continue}if(m&&(k.insertCells(this._activeBuffer.x,a-Z,this._activeBuffer.getNullCell(R)),k.getWidth(g-1)===2&&k.setCellFromCodepoint(g-1,0,1,R)),k.setCellFromCodepoint(this._activeBuffer.x++,n,a,R),a>0)for(;--a;)k.setCellFromCodepoint(this._activeBuffer.x++,0,0,R)}this._parser.precedingJoinState=B,this._activeBuffer.x<g&&i-t>0&&k.getWidth(this._activeBuffer.x)===0&&!k.hasContent(this._activeBuffer.x)&&k.setCellFromCodepoint(this._activeBuffer.x,0,1,R),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,i=>Ch(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Sh(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new ni(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,i,n=!1,a=!1){let h=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);h.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),a),n&&(h.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){var n;this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i<this._bufferService.rows;i++)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(i);break;case 1:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!((n=this._activeBuffer.lines.get(this._activeBuffer.ybase+i))!=null&&n.getTrimmedLength()););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let a=this._activeBuffer.lines.length-this._bufferService.rows;a>0&&(this._activeBuffer.lines.trimStart(a),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-a,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-a,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 i=this._activeBuffer.ybase+this._activeBuffer.y,n=this._bufferService.rows-1-this._activeBuffer.scrollBottom,a=this._bufferService.rows-1+this._activeBuffer.ybase-n+1;for(;t--;)this._activeBuffer.lines.splice(a-1,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}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 i=this._activeBuffer.ybase+this._activeBuffer.y,n;for(n=this._bufferService.rows-1-this._activeBuffer.scrollBottom,n=this._bufferService.rows-1+this._activeBuffer.ybase-n;t--;)this._activeBuffer.lines.splice(i,1),this._activeBuffer.lines.splice(n,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(Rt));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 i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.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 i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.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 i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.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 i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.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 i=e.params[0]||1,n=us.extractWidth(t),a=this._activeBuffer.x-n,h=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(a),d=new Uint32Array(h.length*i),g=0;for(let m=0;m<h.length;){let R=h.codePointAt(m)||0;d[g++]=R,m+=R>65535?2:1}let v=g;for(let m=1;m<i;++m)d.copyWithin(v,0,g),v+=g;return this.print(d,0,v),!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,cs),this._charsetService.setgCharset(1,cs),this._charsetService.setgCharset(2,cs),this._charsetService.setgCharset(3,cs);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){(U=>(U[U.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",U[U.SET=1]="SET",U[U.RESET=2]="RESET",U[U.PERMANENTLY_SET=3]="PERMANENTLY_SET",U[U.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(void 0||(i={}));let n=this._coreService.decPrivateModes,{activeProtocol:a,activeEncoding:h}=this._coreMouseService,d=this._coreService,{buffers:g,cols:v}=this._bufferService,{active:m,alt:R}=g,k=this._optionsService.rawOptions,B=(U,Z)=>(d.triggerDataEvent(`${V.ESC}[${t?"":"?"}${U};${Z}$y`),!0),L=U=>U?1:2,P=e.params[0];return t?P===2?B(P,4):P===4?B(P,L(d.modes.insertMode)):P===12?B(P,3):P===20?B(P,L(k.convertEol)):B(P,0):P===1?B(P,L(n.applicationCursorKeys)):P===3?B(P,k.windowOptions.setWinLines?v===80?2:v===132?1:0:0):P===6?B(P,L(n.origin)):P===7?B(P,L(n.wraparound)):P===8?B(P,3):P===9?B(P,L(a==="X10")):P===12?B(P,L(k.cursorBlink)):P===25?B(P,L(!d.isCursorHidden)):P===45?B(P,L(n.reverseWraparound)):P===66?B(P,L(n.applicationKeypad)):P===67?B(P,4):P===1e3?B(P,L(a==="VT200")):P===1002?B(P,L(a==="DRAG")):P===1003?B(P,L(a==="ANY")):P===1004?B(P,L(n.sendFocus)):P===1005?B(P,4):P===1006?B(P,L(h==="SGR")):P===1015?B(P,4):P===1016?B(P,L(h==="SGR_PIXELS")):P===1048?B(P,1):P===47||P===1047||P===1049?B(P,L(m===R)):P===2004?B(P,L(n.bracketedPasteMode)):P===2026?B(P,L(n.synchronizedOutput)):B(P,0)}_updateAttrColor(e,t,i,n,a){return t===2?(e|=50331648,e&=-16777216,e|=Or.fromColorRGB([i,n,a])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let n=[0,0,-1,0,0,0],a=0,h=0;do{if(n[h+a]=e.params[t+h],e.hasSubParams(t+h)){let d=e.getSubParams(t+h),g=0;do n[1]===5&&(a=1),n[h+g+1+a]=d[g];while(++g<d.length&&g+h+1+a<n.length);break}if(n[1]===5&&h+a>=2||n[1]===2&&h+a>=5)break;n[1]&&(a=1)}while(++h+t<e.length&&h+a<n.length);for(let d=2;d<n.length;++d)n[d]===-1&&(n[d]=0);switch(n[0]){case 38:i.fg=this._updateAttrColor(i.fg,n[1],n[3],n[4],n[5]);break;case 48:i.bg=this._updateAttrColor(i.bg,n[1],n[3],n[4],n[5]);break;case 58:i.extended=i.extended.clone(),i.extended.underlineColor=this._updateAttrColor(i.extended.underlineColor,n[1],n[3],n[4],n[5])}return h}_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=Rt.fg,e.bg=Rt.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,i,n=this._curAttrData;for(let a=0;a<t;a++)i=e.params[a],i>=30&&i<=37?(n.fg&=-50331904,n.fg|=16777216|i-30):i>=40&&i<=47?(n.bg&=-50331904,n.bg|=16777216|i-40):i>=90&&i<=97?(n.fg&=-50331904,n.fg|=16777216|i-90|8):i>=100&&i<=107?(n.bg&=-50331904,n.bg|=16777216|i-100|8):i===0?this._processSGR0(n):i===1?n.fg|=134217728:i===3?n.bg|=67108864:i===4?(n.fg|=268435456,this._processUnderline(e.hasSubParams(a)?e.getSubParams(a)[0]:1,n)):i===5?n.fg|=536870912:i===7?n.fg|=67108864:i===8?n.fg|=1073741824:i===9?n.fg|=2147483648:i===2?n.bg|=134217728:i===21?this._processUnderline(2,n):i===22?(n.fg&=-134217729,n.bg&=-134217729):i===23?n.bg&=-67108865:i===24?(n.fg&=-268435457,this._processUnderline(0,n)):i===25?n.fg&=-536870913:i===27?n.fg&=-67108865:i===28?n.fg&=-1073741825:i===29?n.fg&=2147483647:i===39?(n.fg&=-67108864,n.fg|=Rt.fg&16777215):i===49?(n.bg&=-67108864,n.bg|=Rt.bg&16777215):i===38||i===48||i===58?a+=this._extractColor(e,a,n):i===53?n.bg|=1073741824:i===55?n.bg&=-1073741825:i===59?(n.extended=n.extended.clone(),n.extended.underlineColor=-1,n.updateExtended()):i===100?(n.fg&=-67108864,n.fg|=Rt.fg&16777215,n.bg&=-67108864,n.bg|=Rt.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);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,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${V.ESC}[${t};${i}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${V.ESC}[?${t};${i}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=Rt.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 i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Ch(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>wh&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>wh&&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=[],i=e.split(";");for(;i.length>1;){let n=i.shift(),a=i.shift();if(/^\d+$/.exec(n)){let h=parseInt(n);if(Eh(h))if(a==="?")t.push({type:0,index:h});else{let d=bh(a);d&&t.push({type:1,index:h,color:d})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let i=e.slice(0,t).trim(),n=e.slice(t+1);return n?this._createHyperlink(i,n):i.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i=e.split(":"),n,a=i.findIndex(h=>h.startsWith("id="));return a!==-1&&(n=i[a].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:n,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 i=e.split(";");for(let n=0;n<i.length&&!(t>=this._specialColors.length);++n,++t)if(i[n]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let a=bh(i[n]);a&&this._onColor.fire([{type:1,index:this._specialColors[t],color:a}])}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=[],i=e.split(";");for(let n=0;n<i.length;++n)if(/^\d+$/.exec(i[n])){let a=parseInt(i[n]);Eh(a)&&t.push({type:2,index:a})}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,cs),!0}selectCharset(e){return e.length!==2?(this.selectDefaultCharset(),!0):(e[0]==="/"||this._charsetService.setgCharset(Tp[e[0]],Lt[e[1]]||cs),!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=Rt.clone(),this._eraseAttrDataInternal=Rt.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 di;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 i=this._activeBuffer.ybase+this._activeBuffer.y+t,n=this._activeBuffer.lines.get(i);n&&(n.fill(e),n.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let i=d=>(this._coreService.triggerDataEvent(`${V.ESC}${d}${V.ESC}\\`),!0),n=this._bufferService.buffer,a=this._optionsService.rawOptions;return i(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${n.scrollTop+1};${n.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[a.cursorStyle]-(a.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},ta=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&&(kh=e,e=t,t=kh),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};ta=xt([de(0,Xt)],ta);function Eh(e){return 0<=e&&e<256}var Lp=5e7,Rh=12,Bp=50,Ip=class extends Ve{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 ee),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 i;for(;i=this._writeBuffer.shift();){this._action(i);let n=this._callbacks.shift();n&&n()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>Lp)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 i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let n=this._writeBuffer[this._bufferOffset],a=this._action(n,t);if(a){let d=g=>performance.now()-i>=Rh?setTimeout(()=>this._innerWrite(0,g)):this._innerWrite(i,g);a.catch(g=>(queueMicrotask(()=>{throw g}),Promise.resolve(!1))).then(d);return}let h=this._callbacks[this._bufferOffset];if(h&&h(),this._bufferOffset++,this._pendingData-=n.length,performance.now()-i>=Rh)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>Bp&&(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()}},ia=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 g=t.addMarker(t.ybase+t.y),v={data:e,id:this._nextId++,lines:[g]};return g.onDispose(()=>this._removeMarkerFromLink(v,g)),this._dataByLinkId.set(v.id,v),v.id}let i=e,n=this._getEntryIdKey(i),a=this._entriesWithId.get(n);if(a)return this.addLineToLink(a.id,t.ybase+t.y),a.id;let h=t.addMarker(t.ybase+t.y),d={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[h]};return h.onDispose(()=>this._removeMarkerFromLink(d,h)),this._entriesWithId.set(d.key,d),this._dataByLinkId.set(d.id,d),d.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(n=>n.line!==t)){let n=this._bufferService.buffer.addMarker(t);i.lines.push(n),n.onDispose(()=>this._removeMarkerFromLink(i,n))}}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 i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};ia=xt([de(0,Xt)],ia);var Ah=!1,Dp=class extends Ve{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new Us),this._onBinary=this._register(new ee),this.onBinary=this._onBinary.event,this._onData=this._register(new ee),this.onData=this._onData.event,this._onLineFeed=this._register(new ee),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new ee),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new ee),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new ee),this._instantiationService=new op,this.optionsService=this._register(new pp(e)),this._instantiationService.setService(Zt,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Xo)),this._instantiationService.setService(Xt,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(Jo)),this._instantiationService.setService(rc,this._logService),this.coreService=this._register(this._instantiationService.createInstance(Zo)),this._instantiationService.setService(ps,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Qo)),this._instantiationService.setService(sc,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(us)),this._instantiationService.setService(i_,this.unicodeService),this._charsetService=this._instantiationService.createInstance(bp),this._instantiationService.setService(t_,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(ia),this._instantiationService.setService(nc,this._oscLinkService),this._inputHandler=this._register(new Pp(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Ft.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Ft.forward(this._bufferService.onResize,this._onResize)),this._register(Ft.forward(this.coreService.onData,this._onData)),this._register(Ft.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 Ip((t,i)=>this._inputHandler.parse(t,i))),this._register(Ft.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new ee),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&&!Ah&&(this._logService.warn("writeSync is unreliable and will be removed soon."),Ah=!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,Nc),t=Math.max(t,Hc),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(yh.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(yh(this._bufferService),!1))),this._windowsWrappingHeuristics.value=vt(()=>{for(let t of e)t.dispose()})}}},Np={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 Hp(e,t,i,n){var d;let a={type:0,cancel:!1,key:void 0},h=(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?a.key=V.ESC+"OA":a.key=V.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?a.key=V.ESC+"OD":a.key=V.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?a.key=V.ESC+"OC":a.key=V.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?a.key=V.ESC+"OB":a.key=V.ESC+"[B");break;case 8:a.key=e.ctrlKey?"\b":V.DEL,e.altKey&&(a.key=V.ESC+a.key);break;case 9:if(e.shiftKey){a.key=V.ESC+"[Z";break}a.key=V.HT,a.cancel=!0;break;case 13:a.key=e.altKey?V.ESC+V.CR:V.CR,a.cancel=!0;break;case 27:a.key=V.ESC,e.altKey&&(a.key=V.ESC+V.ESC),a.cancel=!0;break;case 37:if(e.metaKey)break;h?a.key=V.ESC+"[1;"+(h+1)+"D":t?a.key=V.ESC+"OD":a.key=V.ESC+"[D";break;case 39:if(e.metaKey)break;h?a.key=V.ESC+"[1;"+(h+1)+"C":t?a.key=V.ESC+"OC":a.key=V.ESC+"[C";break;case 38:if(e.metaKey)break;h?a.key=V.ESC+"[1;"+(h+1)+"A":t?a.key=V.ESC+"OA":a.key=V.ESC+"[A";break;case 40:if(e.metaKey)break;h?a.key=V.ESC+"[1;"+(h+1)+"B":t?a.key=V.ESC+"OB":a.key=V.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(a.key=V.ESC+"[2~");break;case 46:h?a.key=V.ESC+"[3;"+(h+1)+"~":a.key=V.ESC+"[3~";break;case 36:h?a.key=V.ESC+"[1;"+(h+1)+"H":t?a.key=V.ESC+"OH":a.key=V.ESC+"[H";break;case 35:h?a.key=V.ESC+"[1;"+(h+1)+"F":t?a.key=V.ESC+"OF":a.key=V.ESC+"[F";break;case 33:e.shiftKey?a.type=2:e.ctrlKey?a.key=V.ESC+"[5;"+(h+1)+"~":a.key=V.ESC+"[5~";break;case 34:e.shiftKey?a.type=3:e.ctrlKey?a.key=V.ESC+"[6;"+(h+1)+"~":a.key=V.ESC+"[6~";break;case 112:h?a.key=V.ESC+"[1;"+(h+1)+"P":a.key=V.ESC+"OP";break;case 113:h?a.key=V.ESC+"[1;"+(h+1)+"Q":a.key=V.ESC+"OQ";break;case 114:h?a.key=V.ESC+"[1;"+(h+1)+"R":a.key=V.ESC+"OR";break;case 115:h?a.key=V.ESC+"[1;"+(h+1)+"S":a.key=V.ESC+"OS";break;case 116:h?a.key=V.ESC+"[15;"+(h+1)+"~":a.key=V.ESC+"[15~";break;case 117:h?a.key=V.ESC+"[17;"+(h+1)+"~":a.key=V.ESC+"[17~";break;case 118:h?a.key=V.ESC+"[18;"+(h+1)+"~":a.key=V.ESC+"[18~";break;case 119:h?a.key=V.ESC+"[19;"+(h+1)+"~":a.key=V.ESC+"[19~";break;case 120:h?a.key=V.ESC+"[20;"+(h+1)+"~":a.key=V.ESC+"[20~";break;case 121:h?a.key=V.ESC+"[21;"+(h+1)+"~":a.key=V.ESC+"[21~";break;case 122:h?a.key=V.ESC+"[23;"+(h+1)+"~":a.key=V.ESC+"[23~";break;case 123:h?a.key=V.ESC+"[24;"+(h+1)+"~":a.key=V.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?a.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?a.key=V.NUL:e.keyCode>=51&&e.keyCode<=55?a.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?a.key=V.DEL:e.keyCode===219?a.key=V.ESC:e.keyCode===220?a.key=V.FS:e.keyCode===221&&(a.key=V.GS);else if((!i||n)&&e.altKey&&!e.metaKey){let g=(d=Np[e.keyCode])==null?void 0:d[e.shiftKey?1:0];if(g)a.key=V.ESC+g;else if(e.keyCode>=65&&e.keyCode<=90){let v=e.ctrlKey?e.keyCode-64:e.keyCode+32,m=String.fromCharCode(v);e.shiftKey&&(m=m.toUpperCase()),a.key=V.ESC+m}else if(e.keyCode===32)a.key=V.ESC+(e.ctrlKey?V.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let v=e.code.slice(3,4);e.shiftKey||(v=v.toLowerCase()),a.key=V.ESC+v,a.cancel=!0}}else i&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(a.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?a.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(a.key=V.US),e.key==="@"&&(a.key=V.NUL));break}return a}var kt=0,Up=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new dn,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new dn,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((a,h)=>this._getKey(a)-this._getKey(h)),t=0,i=0,n=new Array(this._array.length+this._insertedValues.length);for(let a=0;a<n.length;a++)i>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(n[a]=e[t],t++):n[a]=this._array[i++];this._array=n,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||(kt=this._search(t),kt===-1)||this._getKey(this._array[kt])!==t)return!1;do if(this._array[kt]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(kt),!0;while(++kt<this._array.length&&this._getKey(this._array[kt])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((a,h)=>a-h),t=0,i=new Array(this._array.length-e.length),n=0;for(let a=0;a<this._array.length;a++)e[t]===a?t++:i[n++]=this._array[a];this._array=i,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&&(kt=this._search(e),!(kt<0||kt>=this._array.length)&&this._getKey(this._array[kt])===e))do yield this._array[kt];while(++kt<this._array.length&&this._getKey(this._array[kt])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(kt=this._search(e),!(kt<0||kt>=this._array.length)&&this._getKey(this._array[kt])===e))do t(this._array[kt]);while(++kt<this._array.length&&this._getKey(this._array[kt])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,i=this._array.length-1;for(;i>=t;){let n=t+i>>1,a=this._getKey(this._array[n]);if(a>e)i=n-1;else if(a<e)t=n+1;else{for(;n>0&&this._getKey(this._array[n-1])===e;)n--;return n}}return t}},ao=0,Mh=0,Wp=class extends Ve{constructor(){super(),this._decorations=new Up(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new ee),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new ee),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(vt(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new Fp(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.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,i){let n=0,a=0;for(let h of this._decorations.getKeyIterator(t))n=h.options.x??0,a=n+(h.options.width??1),e>=n&&e<a&&(!i||(h.options.layer??"bottom")===i)&&(yield h)}forEachDecorationAtCell(e,t,i,n){this._decorations.forEachByKey(t,a=>{ao=a.options.x??0,Mh=ao+(a.options.width??1),e>=ao&&e<Mh&&(!i||(a.options.layer??"bottom")===i)&&n(a)})}},Fp=class extends is{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new ee),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new ee),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=St.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=St.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},zp=1e3,qp=class{constructor(e,t=zp){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,i){this._rowCount=i,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 n=performance.now();if(n-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=n,this._innerRefresh();else if(!this._additionalRefreshRequested){let a=n-this._lastRefreshMs,h=this._debounceThresholdMS-a;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},h)}}_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)}},Oh=20,fn=class extends Ve{constructor(e,t,i,n){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=n,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let a=this._coreBrowserService.mainDocument;this._accessibilityContainer=a.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=a.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let h=0;h<this._terminal.rows;h++)this._rowElements[h]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[h]);if(this._topBoundaryFocusListener=h=>this._handleBoundaryFocus(h,0),this._bottomBoundaryFocusListener=h=>this._handleBoundaryFocus(h,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=a.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new qp(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(h=>this._handleResize(h.rows))),this._register(this._terminal.onRender(h=>this._refreshRows(h.start,h.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(h=>this._handleChar(h))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
38
38
  `))),this._register(this._terminal.onA11yTab(h=>this._handleTab(h))),this._register(this._terminal.onKey(h=>this._handleKey(h.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(Le(a,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(vt(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<Oh+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
39
- `&&(this._liveRegionLineCount++,this._liveRegionLineCount===Oh+1&&(this._liveRegion.textContent+=wo.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 i=this._terminal.buffer,n=i.lines.length.toString();for(let a=e;a<=t;a++){let h=i.lines.get(i.ydisp+a),d=[],g=(h==null?void 0:h.translateToString(!0,void 0,void 0,d))||"",v=(i.ydisp+a+1).toString(),p=this._rowElements[a];p&&(g.length===0?(p.textContent=" ",this._rowColumns.set(p,[0,1])):(p.textContent=g,this._rowColumns.set(p,d)),p.setAttribute("aria-posinset",v),p.setAttribute("aria-setsize",n),this._alignRowWidth(p))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i=e.target,n=this._rowElements[t===0?1:this._rowElements.length-2],a=i.getAttribute("aria-posinset"),h=t===0?"1":`${this._terminal.buffer.lines.length}`;if(a===h||e.relatedTarget!==n)return;let d,g;if(t===0?(d=i,g=this._rowElements.pop(),this._rowContainer.removeChild(g)):(d=this._rowElements.shift(),g=i,this._rowContainer.removeChild(d)),d.removeEventListener("focus",this._topBoundaryFocusListener),g.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let v=this._createAccessibilityTreeNode();this._rowElements.unshift(v),this._rowContainer.insertAdjacentElement("afterbegin",v)}else{let v=this._createAccessibilityTreeNode();this._rowElements.push(v),this._rowContainer.appendChild(v)}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 g;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},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,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 n=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(n)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:n,offset:((g=n.textContent)==null?void 0:g.length)??0}),!this._rowContainer.contains(i.node))return;let a=({node:v,offset:p})=>{let R=v instanceof Text?v.parentNode:v,k=parseInt(R==null?void 0:R.getAttribute("aria-posinset"),10)-1;if(isNaN(k))return console.warn("row is invalid. Race condition?"),null;let B=this._rowColumns.get(R);if(!B)return console.warn("columns is null. Race condition?"),null;let L=p<B.length?B[p]:B.slice(-1)[0]+1;return L>=this._terminal.cols&&(++k,L=0),{row:k,column:L}},h=a(t),d=a(i);if(!(!h||!d)){if(h.row>d.row||h.row===d.row&&h.column>=d.column)throw new Error("invalid range");this._terminal.select(h.column,h.row,(d.row-h.row)*this._terminal.cols-h.column+d.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 a,h;e.style.transform="";let t=e.getBoundingClientRect().width,i=(h=(a=this._rowColumns.get(e))==null?void 0:a.slice(-1))==null?void 0:h[0];if(!i)return;let n=i*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${n/t})`}};fn=xt([de(1,ga),de(2,Ii),de(3,Di)],fn);var sa=class extends Ve{constructor(e,t,i,n,a){super(),this._element=e,this._mouseService=t,this._renderService=i,this._bufferService=n,this._linkProviderService=a,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new ee),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new ee),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(vt(()=>{var h;_s(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(h=this._activeProviderReplies)==null||h.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Le(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Le(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Le(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Le(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 i=e.composedPath();for(let n=0;n<i.length;n++){let a=i[n];if(a.classList.contains("xterm"))break;if(a.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 n,a;(!this._activeProviderReplies||!t)&&((n=this._activeProviderReplies)==null||n.forEach(h=>{h==null||h.forEach(d=>{d.link.dispose&&d.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(let[h,d]of this._linkProviderService.linkProviders.entries())t?(a=this._activeProviderReplies)!=null&&a.get(h)&&(i=this._checkLinkProviderResult(h,e,i)):d.provideLinks(e.y,g=>{var p,R;if(this._isMouseOut)return;let v=g==null?void 0:g.map(k=>({link:k}));(p=this._activeProviderReplies)==null||p.set(h,v),i=this._checkLinkProviderResult(h,e,i),((R=this._activeProviderReplies)==null?void 0:R.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let n=0;n<t.size;n++){let a=t.get(n);if(a)for(let h=0;h<a.length;h++){let d=a[h],g=d.link.range.start.y<e?0:d.link.range.start.x,v=d.link.range.end.y>e?this._bufferService.cols:d.link.range.end.x;for(let p=g;p<=v;p++){if(i.has(p)){a.splice(h--,1);break}i.add(p)}}}}_checkLinkProviderResult(e,t,i){var h;if(!this._activeProviderReplies)return i;let n=this._activeProviderReplies.get(e),a=!1;for(let d=0;d<e;d++)(!this._activeProviderReplies.has(d)||this._activeProviderReplies.get(d))&&(a=!0);if(!a&&n){let d=n.find(g=>this._linkAtPosition(g.link,t));d&&(i=!0,this._handleNewLink(d))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let d=0;d<this._activeProviderReplies.size;d++){let g=(h=this._activeProviderReplies.get(d))==null?void 0:h.find(v=>this._linkAtPosition(v.link,t));if(g){i=!0,this._handleNewLink(g);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&Gp(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,_s(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 i,n;return(n=(i=this._currentLink)==null?void 0:i.state)==null?void 0:n.decorations.pointerCursor},set:i=>{var n;(n=this._currentLink)!=null&&n.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>{var i,n;return(n=(i=this._currentLink)==null?void 0:i.state)==null?void 0:n.decorations.underline},set:i=>{var n,a,h;(n=this._currentLink)!=null&&n.state&&((h=(a=this._currentLink)==null?void 0:a.state)==null?void 0:h.decorations.underline)!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let n=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,a=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=n&&this._currentLink.link.range.end.y<=a&&(this._clearCurrentLink(n,a),this._lastMouseEvent)){let h=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);h&&this._askForLink(h,!1)}})))}_linkHover(e,t,i){var n;(n=this._currentLink)!=null&&n.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(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,n=this._bufferService.buffer.ydisp,a=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-n-1,i.end.x,i.end.y-n-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(a)}_linkLeave(e,t,i){var n;(n=this._currentLink)!=null&&n.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(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,n=e.range.end.y*this._bufferService.cols+e.range.end.x,a=t.y*this._bufferService.cols+t.x;return i<=a&&a<=n}_positionFromMouseEvent(e,t,i){let n=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(n)return{x:n[0],y:n[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,n,a){return{x1:e,y1:t,x2:i,y2:n,cols:this._bufferService.cols,fg:a}}};sa=xt([de(1,pa),de(2,Di),de(3,Xt),de(4,ac)],sa);function Gp(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 jp=class extends Dp{constructor(e={}){super(e),this._linkifier=this._register(new Us),this.browser=Ec,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Us),this._onCursorMove=this._register(new ee),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new ee),this.onKey=this._onKey.event,this._onRender=this._register(new ee),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new ee),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new ee),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new ee),this.onBell=this._onBell.event,this._onFocus=this._register(new ee),this._onBlur=this._register(new ee),this._onA11yCharEmitter=this._register(new ee),this._onA11yTabEmitter=this._register(new ee),this._onWillOpen=this._register(new ee),this._setup(),this._decorationService=this._instantiationService.createInstance(Wp),this._instantiationService.setService(Tr,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(Bg),this._instantiationService.setService(ac,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(xo)),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(Ft.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Ft.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Ft.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Ft.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(vt(()=>{var t,i;this._customKeyEventHandler=void 0,(i=(t=this.element)==null?void 0:t.parentNode)==null||i.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 i,n="";switch(t.index){case 256:i="foreground",n="10";break;case 257:i="background",n="11";break;case 258:i="cursor",n="12";break;default:i="ansi",n="4;"+t.index}switch(t.type){case 0:let a=pt.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${V.ESC}]${n};${Op(a)}${xc.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(h=>h.ansi[t.index]=At.toColor(...t.color));else{let h=i;this._themeService.modifyColors(d=>d[h]=At.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(fn,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 i=Math.min(this.buffer.x,this.cols-1),n=this._renderService.dimensions.css.cell.height,a=t.getWidth(i),h=this._renderService.dimensions.css.cell.width*a,d=this.buffer.y*this._renderService.dimensions.css.cell.height,g=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=g+"px",this.textarea.style.top=d+"px",this.textarea.style.width=h+"px",this.textarea.style.height=n+"px",this.textarea.style.lineHeight=n+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(Le(this.element,"copy",t=>{this.hasSelection()&&Yf(t,this._selectionService)}));let e=t=>Jf(t,this.textarea,this.coreService,this.optionsService);this._register(Le(this.textarea,"paste",e)),this._register(Le(this.element,"paste",e)),Rc?this._register(Le(this.element,"mousedown",t=>{t.button===2&&Wl(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Le(this.element,"contextmenu",t=>{Wl(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),xa&&this._register(Le(this.element,"auxclick",t=>{t.button===1&&Zh(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Le(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Le(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Le(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Le(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Le(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Le(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Le(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){var a;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"),((a=this.element)==null?void 0:a.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(Le(this.screenElement,"mousemove",h=>this.updateCursorStyle(h))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",bo.get()),Oc||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",()=>i.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(Pg,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(Ii,this._coreBrowserService),this._register(Le(this.textarea,"focus",h=>this._handleTextAreaFocus(h))),this._register(Le(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(jo,this._document,this._helperContainer),this._instantiationService.setService(vn,this._charSizeService),this._themeService=this._instantiationService.createInstance(Yo),this._instantiationService.setService(Ws,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(cn),this._instantiationService.setService(oc,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Vo,this.rows,this.screenElement)),this._instantiationService.setService(Di,this._renderService),this._register(this._renderService.onRenderedViewportChange(h=>this._onRender.fire(h))),this.onResize(h=>this._renderService.resize(h.cols,h.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(zo,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance($o),this._instantiationService.setService(pa,this._mouseService);let n=this._linkifier.value=this._register(this._instantiationService.createInstance(sa,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(Wo,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(h=>{super.scrollLines(h,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(Ko,this.element,this.screenElement,n)),this._instantiationService.setService(r_,this._selectionService),this._register(this._selectionService.onRequestScrollLines(h=>this.scrollLines(h.amount,h.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(h=>this._renderService.handleSelectionChanged(h.start,h.end,h.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(h=>{this.textarea.value=h,this.textarea.focus(),this.textarea.select()})),this._register(Ft.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var h;this._selectionService.refresh(),(h=this._viewport)==null||h.queueSync()})),this._register(this._instantiationService.createInstance(Fo,this.screenElement)),this._register(Le(this.element,"mousedown",h=>this._selectionService.handleMouseDown(h))),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(fn,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",h=>this._handleScreenReaderModeOptionChange(h))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(hn,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",h=>{!this._overviewRulerRenderer&&h&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(hn,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(Go,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(h){var p,R,k,B,L;let d=e._mouseService.getMouseReportCoords(h,e.screenElement);if(!d)return!1;let g,v;switch(h.overrideType||h.type){case"mousemove":v=32,h.buttons===void 0?(g=3,h.button!==void 0&&(g=h.button<3?h.button:3)):g=h.buttons&1?0:h.buttons&4?1:h.buttons&2?2:3;break;case"mouseup":v=0,g=h.button<3?h.button:3;break;case"mousedown":v=1,g=h.button<3?h.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(h)===!1)return!1;let P=h.deltaY;if(P===0||e.coreMouseService.consumeWheelEvent(h,(B=(k=(R=(p=e._renderService)==null?void 0:p.dimensions)==null?void 0:R.device)==null?void 0:k.cell)==null?void 0:B.height,(L=e._coreBrowserService)==null?void 0:L.dpr)===0)return!1;v=P<0?0:1,g=4;break;default:return!1}return v===void 0||g===void 0||g>4?!1:e.coreMouseService.triggerMouseEvent({col:d.col,row:d.row,x:d.x,y:d.y,button:g,action:v,ctrl:h.ctrlKey,alt:h.altKey,shift:h.shiftKey})}let n={mouseup:null,wheel:null,mousedrag:null,mousemove:null},a={mouseup:h=>(i(h),h.buttons||(this._document.removeEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.removeEventListener("mousemove",n.mousedrag)),this.cancel(h)),wheel:h=>(i(h),this.cancel(h,!0)),mousedrag:h=>{h.buttons&&i(h)},mousemove:h=>{h.buttons||i(h)}};this._register(this.coreMouseService.onProtocolChange(h=>{h?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(h)),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()),h&8?n.mousemove||(t.addEventListener("mousemove",a.mousemove),n.mousemove=a.mousemove):(t.removeEventListener("mousemove",n.mousemove),n.mousemove=null),h&16?n.wheel||(t.addEventListener("wheel",a.wheel,{passive:!1}),n.wheel=a.wheel):(t.removeEventListener("wheel",n.wheel),n.wheel=null),h&2?n.mouseup||(n.mouseup=a.mouseup):(this._document.removeEventListener("mouseup",n.mouseup),n.mouseup=null),h&4?n.mousedrag||(n.mousedrag=a.mousedrag):(this._document.removeEventListener("mousemove",n.mousedrag),n.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Le(t,"mousedown",h=>{if(h.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(h)))return i(h),n.mouseup&&this._document.addEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.addEventListener("mousemove",n.mousedrag),this.cancel(h)})),this._register(Le(t,"wheel",h=>{var d,g,v,p,R;if(!n.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(h)===!1)return!1;if(!this.buffer.hasScrollback){if(h.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(h,(p=(v=(g=(d=e._renderService)==null?void 0:d.dimensions)==null?void 0:g.device)==null?void 0:v.cell)==null?void 0:p.height,(R=e._coreBrowserService)==null?void 0:R.dpr)===0)return this.cancel(h,!0);let k=V.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(h.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(k,!0),this.cancel(h,!0)}}},{passive:!1}))}refresh(e,t){var i;(i=this._renderService)==null||i.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){Xh(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,i){this._selectionService.setSelection(e,t,i)}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 i;(i=this._selectionService)==null||i.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 i=Hp(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),i.type===3||i.type===2){let n=this.rows-1;return this.scrollLines(i.type===2?-n:n),this.cancel(e,!0)}if(i.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.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((i.key===V.ETX||i.key===V.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let i=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"?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&($p(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 i;(i=this._charSizeService)==null||i.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(Rt));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),i=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${V.ESC}[4;${i};${t}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),a=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${V.ESC}[6;${a};${n}t`);break}}cancel(e,t){if(!(!this.options.cancelEvents&&!t))return e.preventDefault(),e.stopPropagation(),!1}};function $p(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var Vp=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i<this._addons.length;i++)if(this._addons[i]===e){t=i;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)}},Kp=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 di)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},Th=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 Kp(t)}getNullCell(){return new di}},Yp=class extends Ve{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new ee),this.onBufferChange=this._onBufferChange.event,this._normal=new Th(this._core.buffers.normal,"normal"),this._alternate=new Th(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)}},Jp=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,i=>t(i.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(i,n)=>t(i,n.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)}},Xp=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}},Zp=["cols","rows"],xi=0,Qp=class extends Ve{constructor(e){super(),this._core=this._register(new jp(e)),this._addonManager=this._register(new Vp),this._publicOptions={...this._core.options};let t=n=>this._core.options[n],i=(n,a)=>{this._checkReadonlyOptions(n),this._core.options[n]=a};for(let n in this._core.options){let a={get:t.bind(this,n),set:i.bind(this,n)};Object.defineProperty(this._publicOptions,n,a)}}_checkReadonlyOptions(e){if(Zp.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 Jp(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new Xp(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 Yp(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,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}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
39
+ `&&(this._liveRegionLineCount++,this._liveRegionLineCount===Oh+1&&(this._liveRegion.textContent+=wo.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 i=this._terminal.buffer,n=i.lines.length.toString();for(let a=e;a<=t;a++){let h=i.lines.get(i.ydisp+a),d=[],g=(h==null?void 0:h.translateToString(!0,void 0,void 0,d))||"",v=(i.ydisp+a+1).toString(),m=this._rowElements[a];m&&(g.length===0?(m.textContent=" ",this._rowColumns.set(m,[0,1])):(m.textContent=g,this._rowColumns.set(m,d)),m.setAttribute("aria-posinset",v),m.setAttribute("aria-setsize",n),this._alignRowWidth(m))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i=e.target,n=this._rowElements[t===0?1:this._rowElements.length-2],a=i.getAttribute("aria-posinset"),h=t===0?"1":`${this._terminal.buffer.lines.length}`;if(a===h||e.relatedTarget!==n)return;let d,g;if(t===0?(d=i,g=this._rowElements.pop(),this._rowContainer.removeChild(g)):(d=this._rowElements.shift(),g=i,this._rowContainer.removeChild(d)),d.removeEventListener("focus",this._topBoundaryFocusListener),g.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let v=this._createAccessibilityTreeNode();this._rowElements.unshift(v),this._rowContainer.insertAdjacentElement("afterbegin",v)}else{let v=this._createAccessibilityTreeNode();this._rowElements.push(v),this._rowContainer.appendChild(v)}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 g;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},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,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 n=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(n)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:n,offset:((g=n.textContent)==null?void 0:g.length)??0}),!this._rowContainer.contains(i.node))return;let a=({node:v,offset:m})=>{let R=v instanceof Text?v.parentNode:v,k=parseInt(R==null?void 0:R.getAttribute("aria-posinset"),10)-1;if(isNaN(k))return console.warn("row is invalid. Race condition?"),null;let B=this._rowColumns.get(R);if(!B)return console.warn("columns is null. Race condition?"),null;let L=m<B.length?B[m]:B.slice(-1)[0]+1;return L>=this._terminal.cols&&(++k,L=0),{row:k,column:L}},h=a(t),d=a(i);if(!(!h||!d)){if(h.row>d.row||h.row===d.row&&h.column>=d.column)throw new Error("invalid range");this._terminal.select(h.column,h.row,(d.row-h.row)*this._terminal.cols-h.column+d.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 a,h;e.style.transform="";let t=e.getBoundingClientRect().width,i=(h=(a=this._rowColumns.get(e))==null?void 0:a.slice(-1))==null?void 0:h[0];if(!i)return;let n=i*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${n/t})`}};fn=xt([de(1,ga),de(2,Ii),de(3,Di)],fn);var sa=class extends Ve{constructor(e,t,i,n,a){super(),this._element=e,this._mouseService=t,this._renderService=i,this._bufferService=n,this._linkProviderService=a,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new ee),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new ee),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(vt(()=>{var h;_s(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(h=this._activeProviderReplies)==null||h.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Le(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Le(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Le(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Le(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 i=e.composedPath();for(let n=0;n<i.length;n++){let a=i[n];if(a.classList.contains("xterm"))break;if(a.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 n,a;(!this._activeProviderReplies||!t)&&((n=this._activeProviderReplies)==null||n.forEach(h=>{h==null||h.forEach(d=>{d.link.dispose&&d.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(let[h,d]of this._linkProviderService.linkProviders.entries())t?(a=this._activeProviderReplies)!=null&&a.get(h)&&(i=this._checkLinkProviderResult(h,e,i)):d.provideLinks(e.y,g=>{var m,R;if(this._isMouseOut)return;let v=g==null?void 0:g.map(k=>({link:k}));(m=this._activeProviderReplies)==null||m.set(h,v),i=this._checkLinkProviderResult(h,e,i),((R=this._activeProviderReplies)==null?void 0:R.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let n=0;n<t.size;n++){let a=t.get(n);if(a)for(let h=0;h<a.length;h++){let d=a[h],g=d.link.range.start.y<e?0:d.link.range.start.x,v=d.link.range.end.y>e?this._bufferService.cols:d.link.range.end.x;for(let m=g;m<=v;m++){if(i.has(m)){a.splice(h--,1);break}i.add(m)}}}}_checkLinkProviderResult(e,t,i){var h;if(!this._activeProviderReplies)return i;let n=this._activeProviderReplies.get(e),a=!1;for(let d=0;d<e;d++)(!this._activeProviderReplies.has(d)||this._activeProviderReplies.get(d))&&(a=!0);if(!a&&n){let d=n.find(g=>this._linkAtPosition(g.link,t));d&&(i=!0,this._handleNewLink(d))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let d=0;d<this._activeProviderReplies.size;d++){let g=(h=this._activeProviderReplies.get(d))==null?void 0:h.find(v=>this._linkAtPosition(v.link,t));if(g){i=!0,this._handleNewLink(g);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&Gp(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,_s(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 i,n;return(n=(i=this._currentLink)==null?void 0:i.state)==null?void 0:n.decorations.pointerCursor},set:i=>{var n;(n=this._currentLink)!=null&&n.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>{var i,n;return(n=(i=this._currentLink)==null?void 0:i.state)==null?void 0:n.decorations.underline},set:i=>{var n,a,h;(n=this._currentLink)!=null&&n.state&&((h=(a=this._currentLink)==null?void 0:a.state)==null?void 0:h.decorations.underline)!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let n=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,a=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=n&&this._currentLink.link.range.end.y<=a&&(this._clearCurrentLink(n,a),this._lastMouseEvent)){let h=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);h&&this._askForLink(h,!1)}})))}_linkHover(e,t,i){var n;(n=this._currentLink)!=null&&n.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(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,n=this._bufferService.buffer.ydisp,a=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-n-1,i.end.x,i.end.y-n-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(a)}_linkLeave(e,t,i){var n;(n=this._currentLink)!=null&&n.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(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,n=e.range.end.y*this._bufferService.cols+e.range.end.x,a=t.y*this._bufferService.cols+t.x;return i<=a&&a<=n}_positionFromMouseEvent(e,t,i){let n=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(n)return{x:n[0],y:n[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,n,a){return{x1:e,y1:t,x2:i,y2:n,cols:this._bufferService.cols,fg:a}}};sa=xt([de(1,pa),de(2,Di),de(3,Xt),de(4,ac)],sa);function Gp(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 jp=class extends Dp{constructor(e={}){super(e),this._linkifier=this._register(new Us),this.browser=Ec,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Us),this._onCursorMove=this._register(new ee),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new ee),this.onKey=this._onKey.event,this._onRender=this._register(new ee),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new ee),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new ee),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new ee),this.onBell=this._onBell.event,this._onFocus=this._register(new ee),this._onBlur=this._register(new ee),this._onA11yCharEmitter=this._register(new ee),this._onA11yTabEmitter=this._register(new ee),this._onWillOpen=this._register(new ee),this._setup(),this._decorationService=this._instantiationService.createInstance(Wp),this._instantiationService.setService(Tr,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(Bg),this._instantiationService.setService(ac,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(xo)),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(Ft.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Ft.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Ft.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Ft.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(vt(()=>{var t,i;this._customKeyEventHandler=void 0,(i=(t=this.element)==null?void 0:t.parentNode)==null||i.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 i,n="";switch(t.index){case 256:i="foreground",n="10";break;case 257:i="background",n="11";break;case 258:i="cursor",n="12";break;default:i="ansi",n="4;"+t.index}switch(t.type){case 0:let a=pt.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${V.ESC}]${n};${Op(a)}${xc.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(h=>h.ansi[t.index]=At.toColor(...t.color));else{let h=i;this._themeService.modifyColors(d=>d[h]=At.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(fn,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 i=Math.min(this.buffer.x,this.cols-1),n=this._renderService.dimensions.css.cell.height,a=t.getWidth(i),h=this._renderService.dimensions.css.cell.width*a,d=this.buffer.y*this._renderService.dimensions.css.cell.height,g=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=g+"px",this.textarea.style.top=d+"px",this.textarea.style.width=h+"px",this.textarea.style.height=n+"px",this.textarea.style.lineHeight=n+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(Le(this.element,"copy",t=>{this.hasSelection()&&Yf(t,this._selectionService)}));let e=t=>Jf(t,this.textarea,this.coreService,this.optionsService);this._register(Le(this.textarea,"paste",e)),this._register(Le(this.element,"paste",e)),Rc?this._register(Le(this.element,"mousedown",t=>{t.button===2&&Wl(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Le(this.element,"contextmenu",t=>{Wl(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),xa&&this._register(Le(this.element,"auxclick",t=>{t.button===1&&Zh(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Le(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Le(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Le(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Le(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Le(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Le(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Le(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){var a;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"),((a=this.element)==null?void 0:a.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(Le(this.screenElement,"mousemove",h=>this.updateCursorStyle(h))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",bo.get()),Oc||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",()=>i.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(Pg,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(Ii,this._coreBrowserService),this._register(Le(this.textarea,"focus",h=>this._handleTextAreaFocus(h))),this._register(Le(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(jo,this._document,this._helperContainer),this._instantiationService.setService(vn,this._charSizeService),this._themeService=this._instantiationService.createInstance(Yo),this._instantiationService.setService(Ws,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(cn),this._instantiationService.setService(oc,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Vo,this.rows,this.screenElement)),this._instantiationService.setService(Di,this._renderService),this._register(this._renderService.onRenderedViewportChange(h=>this._onRender.fire(h))),this.onResize(h=>this._renderService.resize(h.cols,h.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(zo,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance($o),this._instantiationService.setService(pa,this._mouseService);let n=this._linkifier.value=this._register(this._instantiationService.createInstance(sa,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(Wo,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(h=>{super.scrollLines(h,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(Ko,this.element,this.screenElement,n)),this._instantiationService.setService(r_,this._selectionService),this._register(this._selectionService.onRequestScrollLines(h=>this.scrollLines(h.amount,h.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(h=>this._renderService.handleSelectionChanged(h.start,h.end,h.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(h=>{this.textarea.value=h,this.textarea.focus(),this.textarea.select()})),this._register(Ft.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var h;this._selectionService.refresh(),(h=this._viewport)==null||h.queueSync()})),this._register(this._instantiationService.createInstance(Fo,this.screenElement)),this._register(Le(this.element,"mousedown",h=>this._selectionService.handleMouseDown(h))),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(fn,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",h=>this._handleScreenReaderModeOptionChange(h))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(hn,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",h=>{!this._overviewRulerRenderer&&h&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(hn,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(Go,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(h){var m,R,k,B,L;let d=e._mouseService.getMouseReportCoords(h,e.screenElement);if(!d)return!1;let g,v;switch(h.overrideType||h.type){case"mousemove":v=32,h.buttons===void 0?(g=3,h.button!==void 0&&(g=h.button<3?h.button:3)):g=h.buttons&1?0:h.buttons&4?1:h.buttons&2?2:3;break;case"mouseup":v=0,g=h.button<3?h.button:3;break;case"mousedown":v=1,g=h.button<3?h.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(h)===!1)return!1;let P=h.deltaY;if(P===0||e.coreMouseService.consumeWheelEvent(h,(B=(k=(R=(m=e._renderService)==null?void 0:m.dimensions)==null?void 0:R.device)==null?void 0:k.cell)==null?void 0:B.height,(L=e._coreBrowserService)==null?void 0:L.dpr)===0)return!1;v=P<0?0:1,g=4;break;default:return!1}return v===void 0||g===void 0||g>4?!1:e.coreMouseService.triggerMouseEvent({col:d.col,row:d.row,x:d.x,y:d.y,button:g,action:v,ctrl:h.ctrlKey,alt:h.altKey,shift:h.shiftKey})}let n={mouseup:null,wheel:null,mousedrag:null,mousemove:null},a={mouseup:h=>(i(h),h.buttons||(this._document.removeEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.removeEventListener("mousemove",n.mousedrag)),this.cancel(h)),wheel:h=>(i(h),this.cancel(h,!0)),mousedrag:h=>{h.buttons&&i(h)},mousemove:h=>{h.buttons||i(h)}};this._register(this.coreMouseService.onProtocolChange(h=>{h?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(h)),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()),h&8?n.mousemove||(t.addEventListener("mousemove",a.mousemove),n.mousemove=a.mousemove):(t.removeEventListener("mousemove",n.mousemove),n.mousemove=null),h&16?n.wheel||(t.addEventListener("wheel",a.wheel,{passive:!1}),n.wheel=a.wheel):(t.removeEventListener("wheel",n.wheel),n.wheel=null),h&2?n.mouseup||(n.mouseup=a.mouseup):(this._document.removeEventListener("mouseup",n.mouseup),n.mouseup=null),h&4?n.mousedrag||(n.mousedrag=a.mousedrag):(this._document.removeEventListener("mousemove",n.mousedrag),n.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Le(t,"mousedown",h=>{if(h.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(h)))return i(h),n.mouseup&&this._document.addEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.addEventListener("mousemove",n.mousedrag),this.cancel(h)})),this._register(Le(t,"wheel",h=>{var d,g,v,m,R;if(!n.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(h)===!1)return!1;if(!this.buffer.hasScrollback){if(h.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(h,(m=(v=(g=(d=e._renderService)==null?void 0:d.dimensions)==null?void 0:g.device)==null?void 0:v.cell)==null?void 0:m.height,(R=e._coreBrowserService)==null?void 0:R.dpr)===0)return this.cancel(h,!0);let k=V.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(h.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(k,!0),this.cancel(h,!0)}}},{passive:!1}))}refresh(e,t){var i;(i=this._renderService)==null||i.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){Xh(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,i){this._selectionService.setSelection(e,t,i)}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 i;(i=this._selectionService)==null||i.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 i=Hp(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),i.type===3||i.type===2){let n=this.rows-1;return this.scrollLines(i.type===2?-n:n),this.cancel(e,!0)}if(i.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.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((i.key===V.ETX||i.key===V.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let i=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"?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&($p(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 i;(i=this._charSizeService)==null||i.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(Rt));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),i=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${V.ESC}[4;${i};${t}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),a=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${V.ESC}[6;${a};${n}t`);break}}cancel(e,t){if(!(!this.options.cancelEvents&&!t))return e.preventDefault(),e.stopPropagation(),!1}};function $p(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var Vp=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i<this._addons.length;i++)if(this._addons[i]===e){t=i;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)}},Kp=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 di)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},Th=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 Kp(t)}getNullCell(){return new di}},Yp=class extends Ve{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new ee),this.onBufferChange=this._onBufferChange.event,this._normal=new Th(this._core.buffers.normal,"normal"),this._alternate=new Th(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)}},Jp=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,i=>t(i.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(i,n)=>t(i,n.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)}},Xp=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}},Zp=["cols","rows"],xi=0,Qp=class extends Ve{constructor(e){super(),this._core=this._register(new jp(e)),this._addonManager=this._register(new Vp),this._publicOptions={...this._core.options};let t=n=>this._core.options[n],i=(n,a)=>{this._checkReadonlyOptions(n),this._core.options[n]=a};for(let n in this._core.options){let a={get:t.bind(this,n),set:i.bind(this,n)};Object.defineProperty(this._publicOptions,n,a)}}_checkReadonlyOptions(e){if(Zp.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 Jp(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new Xp(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 Yp(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,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}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
40
40
  `,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 bo.get()},set promptLabel(e){bo.set(e)},get tooMuchOutput(){return wo.get()},set tooMuchOutput(e){wo.set(e)}}}_verifyIntegers(...e){for(xi of e)if(xi===1/0||isNaN(xi)||xi%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(xi of e)if(xi&&(xi===1/0||isNaN(xi)||xi%1!==0||xi<0))throw new Error("This API only accepts positive integers")}};/**
41
41
  * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
42
42
  * @license MIT
@@ -48,5 +48,5 @@ WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){t
48
48
  * Fabrice Bellard's javascript vt100 for jslinux:
49
49
  * http://bellard.org/jslinux/
50
50
  * Copyright (c) 2011 Fabrice Bellard
51
- */var em=2,tm=1,im=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 k;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:((k=this._terminal.options.overviewRuler)==null?void 0:k.width)||14,i=window.getComputedStyle(this._terminal.element.parentElement),n=parseInt(i.getPropertyValue("height")),a=Math.max(0,parseInt(i.getPropertyValue("width"))),h=window.getComputedStyle(this._terminal.element),d={top:parseInt(h.getPropertyValue("padding-top")),bottom:parseInt(h.getPropertyValue("padding-bottom")),right:parseInt(h.getPropertyValue("padding-right")),left:parseInt(h.getPropertyValue("padding-left"))},g=d.top+d.bottom,v=d.right+d.left,p=n-g,R=a-v-t;return{cols:Math.max(em,Math.floor(R/e.css.cell.width)),rows:Math.max(tm,Math.floor(p/e.css.cell.height))}}};function Ei(e){console.log(e)}function sm(e){return e.replace(/\x1b\](10|11);rgb:[0-9a-f/]+\x07/g,"")}"serviceWorker"in navigator&&navigator.serviceWorker.register("./sw.js").then(e=>(e.active?Promise.resolve():new Promise(t=>{const i=e.installing??e.waiting;i?i.addEventListener("statechange",()=>{i.state==="activated"&&t()}):t()})).then(async()=>{const t=await caches.open("airloom-v4"),i=location.href.split("#")[0];await t.match(i)||await t.add(i).catch(()=>{});const h=performance.getEntriesByType("resource").map(d=>d.name).filter(d=>{try{return new URL(d).origin===location.origin}catch{return!1}});await Promise.all(h.map(d=>t.match(d).then(g=>{if(!g)return t.add(d).catch(()=>{})})))})).catch(()=>{});const Wc=document.getElementById("connectScreen"),ka=document.getElementById("terminalScreen"),rm=document.getElementById("scanBtn"),nm=document.getElementById("joinBtn"),fs=document.getElementById("codeInput"),ra=document.getElementById("relayInput"),na=document.getElementById("connectError"),oa=document.getElementById("connectStatus"),om=document.getElementById("disconnectBtn"),Ph=document.getElementById("terminalStatus"),Lh=document.getElementById("qrReader"),Bh=document.getElementById("terminalContainer"),Fc=document.getElementById("terminal"),am=document.getElementById("focusTerminalBtn"),lm=document.getElementById("ctrlCBtn"),hm=document.getElementById("escBtn"),cm=document.getElementById("tabBtn");let tt=null,Qe=null,Er=null,Ns=null,Rr=!1;function aa(e,t){try{localStorage.setItem("airloom:lastRelay",t)}catch{}}function zc(e){try{localStorage.setItem("airloom:lastSession",JSON.stringify(e))}catch{}}function qc(){try{const e=localStorage.getItem("airloom:lastSession");return e?JSON.parse(e):null}catch{return null}}function um(){try{localStorage.removeItem("airloom:lastSession")}catch{}}function Gc(){try{const e=localStorage.getItem("airloom:lastRelay");e&&!ra.value&&(ra.value=e)}catch{}}function Ih(){Qe||(Qe=new Qp({cursorBlink:!0,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:14,lineHeight:1.25,allowTransparency:!0,scrollback:5e3,theme:{background:"#05070c",foreground:"#e6edf3",cursor:"#7c8aff",cursorAccent:"#05070c",selectionBackground:"rgba(124,138,255,0.28)",black:"#0a0d14",red:"#ff7b72",green:"#3fb950",yellow:"#d29922",blue:"#7c8aff",magenta:"#bc8cff",cyan:"#39c5cf",white:"#c9d1d9",brightBlack:"#6e7681",brightRed:"#ffa198",brightGreen:"#56d364",brightYellow:"#e3b341",brightBlue:"#a5b4ff",brightMagenta:"#d2a8ff",brightCyan:"#56d4dd",brightWhite:"#f0f6fc"}}),Er=new im,Qe.loadAddon(Er),Qe.open(Fc),Qe.onData(e=>{if(!Rr||!tt)return;const t=e.replace(/\x1b\]\d+;[^\x07\x1b]*(?:\x07|\x1b\\)/g,"");t&&tt.send({type:"terminal_input",data:t})}),Bh.addEventListener("click",()=>Qe==null?void 0:Qe.focus()),Ns=new ResizeObserver(()=>Ea()),Ns.observe(Bh))}let la=0,ha=0;function Ea(e=!1){if(!Qe||!Er){Ei("[viewer] fitAndSyncTerminal: no term or fitAddon");return}if(Er.fit(),!tt||!Rr){Ei("[viewer] fitAndSyncTerminal: no channel or not ready");return}const t=Qe.cols,i=Qe.rows;if(!e&&t===la&&i===ha){Ei(`[viewer] Skipping resize: same dimensions (${t}x${i})`);return}la=t,ha=i;const n=e?{type:"terminal_open",cols:t,rows:i}:{type:"terminal_resize",cols:t,rows:i};Ei(`[viewer] Sending ${n.type} (${t}x${i})`),tt.send(n)}function lo(e,t="status-badge"){Ph.textContent=e,Ph.className=t}function Ls(e){Qe&&Qe.writeln(e.replace(/\n/g,`\r
52
- `))}function dm(){Rr=!1,la=0,ha=0,tt==null||tt.close(),tt=null,Ns==null||Ns.disconnect(),Ns=null,Qe==null||Qe.dispose(),Qe=null,Er=null,Fc.innerHTML="",ka.style.display="none",Wc.style.display="flex",Gc()}Gc();const Dh=document.getElementById("app");function ca(){if(!window.visualViewport)return;const e=window.visualViewport;Dh.style.height=`${e.height}px`,Dh.style.top=`${e.offsetTop}px`,ka.classList.toggle("landscape",e.width>e.height),Ea()}window.visualViewport&&(window.visualViewport.addEventListener("resize",ca),window.visualViewport.addEventListener("scroll",ca));window.addEventListener("orientationchange",()=>setTimeout(ca,300));fs.addEventListener("input",()=>{let e=fs.value.replace(/[^A-Za-z0-9]/g,"").toUpperCase();e.length>4&&(e=e.slice(0,4)+"-"+e.slice(4,8)),fs.value=e});nm.addEventListener("click",()=>jc());fs.addEventListener("keydown",e=>{e.key==="Enter"&&jc()});rm.addEventListener("click",async()=>{try{const{Html5Qrcode:e}=await Wh(async()=>{const{Html5Qrcode:i}=await import("./index-D3PxNxWB.js");return{Html5Qrcode:i}},[],import.meta.url);Lh.style.display="block";const t=new e("qrReader");await t.start({facingMode:"environment"},{fps:10,qrbox:{width:250,height:250}},async i=>{await t.stop(),Lh.style.display="none",$c(i)},()=>{})}catch{Ar("Camera access denied or not available")}});am.addEventListener("click",()=>Qe==null?void 0:Qe.focus());lm.addEventListener("click",()=>{Qe==null||Qe.focus(),tt==null||tt.send({type:"terminal_input",data:""})});hm.addEventListener("click",()=>{Qe==null||Qe.focus(),tt==null||tt.send({type:"terminal_input",data:"\x1B"})});cm.addEventListener("click",()=>{Qe==null||Qe.focus(),tt==null||tt.send({type:"terminal_input",data:" "})});om.addEventListener("click",()=>{tt==null||tt.send({type:"terminal_close"}),dm()});(async()=>{const e=location.hash.slice(1);if(e){history.replaceState(null,"",location.pathname+location.search);try{const a=atob(e.replace(/-/g,"+").replace(/_/g,"/"));await $c(a)}catch{}tt||gn();return}const t=qc();if(!t)return;ua("Reconnecting...");const i=Mr(new TextEncoder().encode("airloom-key:"+t.session)),n=_a(i);try{await _n(t.relay,t.session,n,t.transport,t.token,8e3)}catch{}tt||(um(),gn(),_m())})();async function jc(){const e=Df(fs.value);if(e.length!==8){Ar("Code must be 8 characters");return}const t=If(e),i=Mr(new TextEncoder().encode("airloom-key:"+t)),n=_a(i),a=qc(),h=[...new Set([location.origin,a==null?void 0:a.hostOrigin].filter(Boolean))];for(const g of h)try{const v=await fetch(`${g}/api/pair?session=${encodeURIComponent(t)}`);if(v.ok){const p=await v.json();aa(fs.value,p.relay),zc({session:t,token:p.token,transport:p.transport,relay:p.relay,hostOrigin:g}),await _n(p.relay,t,n,p.transport,p.token);return}}catch{}const d=ra.value.trim()||"ws://localhost:4500";aa(fs.value,d),await _n(d,t,n)}async function $c(e){try{const t=cf(e);aa(null,t.relay);const i=t.transport??"ws";zc({session:t.session,token:t.token,transport:i,relay:t.relay,hostOrigin:location.origin});const n=Mr(new TextEncoder().encode("airloom-key:"+t.session)),a=_a(n);await _n(t.relay,t.session,a,i,t.token)}catch(t){const i=t instanceof Error?t.message:"Unknown error";Ar("Invalid QR code: "+i)}}function fm(e){const t=e.meta;return(t==null?void 0:t.kind)==="terminal"}async function _n(e,t,i,n="ws",a,h=0){ua("Connecting..."),gn();try{let d;if(n==="ably"){if(!a){Ar("Ably transport requires a token");return}d=new Gf({token:a})}else d=new Wf(e);tt=new Uf({adapter:d,role:"viewer",encryptionKey:i});let g=null;h>0&&(g=setTimeout(()=>{if(!Rr){const v=tt;tt=null,v==null||v.close(),gn()}},h)),tt.on("ready",()=>{g&&(clearTimeout(g),g=null),Ei("[viewer] Channel ready"),Rr=!0,Wc.style.display="none",ka.style.display="flex",lo("Connected"),Ih(),Ei("[viewer] Terminal ensured, calling fitAndSyncTerminal(true)"),requestAnimationFrame(()=>{Ea(!0),Qe==null||Qe.focus()})}),tt.on("peer_left",()=>{lo("Disconnected","status-badge disconnected"),Ls(""),Ls("[host disconnected]")}),tt.on("message",v=>{if(!(!v||typeof v!="object"||!("type"in v))&&v.type==="terminal_exit"){const p=v,R=typeof p.exitCode=="number"?`exit ${p.exitCode}`:"terminated";Ls(""),Ls(`[terminal ${R}]`)}}),tt.on("stream",v=>{if(!fm(v)){Ei("[viewer] Non-terminal stream, ignoring");return}Ei("[viewer] Terminal stream received"),Ih(),v.on("data",p=>{const R=sm(p);R!==p&&Ei(`[viewer] Sanitized ${p.length-R.length} chars of OSC sequences`),Qe==null||Qe.write(R)}),v.on("end",()=>{Ei("[viewer] Stream ended"),Ls("[session closed]")})}),tt.on("error",v=>{console.error("Channel error:",v),Ls(`[error: ${v.message}]`)}),tt.on("disconnect",()=>lo("Reconnecting…","status-badge reconnecting")),await tt.connect(t),ua("Connected to relay, waiting for host...")}catch(d){const g=tt;tt=null;try{g==null||g.close()}catch{}const v=d instanceof Error?d.message:"Unknown error";Ar("Connection failed: "+v)}}function Ar(e){na.textContent=e,na.style.display="block"}function gn(){na.style.display="none"}function _m(){oa.style.display="none"}function ua(e){oa.textContent=e,oa.style.display="block"}export{Ki as c,sf as g};
51
+ */var em=2,tm=1,im=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 k;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:((k=this._terminal.options.overviewRuler)==null?void 0:k.width)||14,i=window.getComputedStyle(this._terminal.element.parentElement),n=parseInt(i.getPropertyValue("height")),a=Math.max(0,parseInt(i.getPropertyValue("width"))),h=window.getComputedStyle(this._terminal.element),d={top:parseInt(h.getPropertyValue("padding-top")),bottom:parseInt(h.getPropertyValue("padding-bottom")),right:parseInt(h.getPropertyValue("padding-right")),left:parseInt(h.getPropertyValue("padding-left"))},g=d.top+d.bottom,v=d.right+d.left,m=n-g,R=a-v-t;return{cols:Math.max(em,Math.floor(R/e.css.cell.width)),rows:Math.max(tm,Math.floor(m/e.css.cell.height))}}};function Li(e){console.log(e)}"serviceWorker"in navigator&&navigator.serviceWorker.register("./sw.js").then(e=>(e.active?Promise.resolve():new Promise(t=>{const i=e.installing??e.waiting;i?i.addEventListener("statechange",()=>{i.state==="activated"&&t()}):t()})).then(async()=>{const t=await caches.open("airloom-v4"),i=location.href.split("#")[0];await t.match(i)||await t.add(i).catch(()=>{});const h=performance.getEntriesByType("resource").map(d=>d.name).filter(d=>{try{return new URL(d).origin===location.origin}catch{return!1}});await Promise.all(h.map(d=>t.match(d).then(g=>{if(!g)return t.add(d).catch(()=>{})})))})).catch(()=>{});const Wc=document.getElementById("connectScreen"),ka=document.getElementById("terminalScreen"),sm=document.getElementById("scanBtn"),rm=document.getElementById("joinBtn"),fs=document.getElementById("codeInput"),ra=document.getElementById("relayInput"),na=document.getElementById("connectError"),oa=document.getElementById("connectStatus"),nm=document.getElementById("disconnectBtn"),Ph=document.getElementById("terminalStatus"),Lh=document.getElementById("qrReader"),Bh=document.getElementById("terminalContainer"),Fc=document.getElementById("terminal"),om=document.getElementById("focusTerminalBtn"),am=document.getElementById("ctrlCBtn"),lm=document.getElementById("escBtn"),hm=document.getElementById("tabBtn");let tt=null,Ze=null,Er=null,Ns=null,Rr=!1;function aa(e,t){try{localStorage.setItem("airloom:lastRelay",t)}catch{}}function zc(e){try{localStorage.setItem("airloom:lastSession",JSON.stringify(e))}catch{}}function qc(){try{const e=localStorage.getItem("airloom:lastSession");return e?JSON.parse(e):null}catch{return null}}function cm(){try{localStorage.removeItem("airloom:lastSession")}catch{}}function Gc(){try{const e=localStorage.getItem("airloom:lastRelay");e&&!ra.value&&(ra.value=e)}catch{}}function Ih(){if(!Ze){Ze=new Qp({cursorBlink:!0,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:14,lineHeight:1.25,allowTransparency:!0,scrollback:5e3,theme:{background:"#05070c",foreground:"#e6edf3",cursor:"#7c8aff",cursorAccent:"#05070c",selectionBackground:"rgba(124,138,255,0.28)",black:"#0a0d14",red:"#ff7b72",green:"#3fb950",yellow:"#d29922",blue:"#7c8aff",magenta:"#bc8cff",cyan:"#39c5cf",white:"#c9d1d9",brightBlack:"#6e7681",brightRed:"#ffa198",brightGreen:"#56d364",brightYellow:"#e3b341",brightBlue:"#a5b4ff",brightMagenta:"#d2a8ff",brightCyan:"#56d4dd",brightWhite:"#f0f6fc"}}),Er=new im,Ze.loadAddon(Er),Ze.open(Fc);for(const e of[4,10,11,12,17,19])Ze.parser.registerOscHandler(e,()=>!0);Ze.onData(e=>{!Rr||!tt||tt.send({type:"terminal_input",data:e})}),Bh.addEventListener("click",()=>Ze==null?void 0:Ze.focus()),Ns=new ResizeObserver(()=>Ea()),Ns.observe(Bh)}}let la=0,ha=0;function Ea(e=!1){if(!Ze||!Er){Li("[viewer] fitAndSyncTerminal: no term or fitAddon");return}if(Er.fit(),!tt||!Rr){Li("[viewer] fitAndSyncTerminal: no channel or not ready");return}const t=Ze.cols,i=Ze.rows;if(!e&&t===la&&i===ha){Li(`[viewer] Skipping resize: same dimensions (${t}x${i})`);return}la=t,ha=i;const n=e?{type:"terminal_open",cols:t,rows:i}:{type:"terminal_resize",cols:t,rows:i};Li(`[viewer] Sending ${n.type} (${t}x${i})`),tt.send(n)}function lo(e,t="status-badge"){Ph.textContent=e,Ph.className=t}function Ls(e){Ze&&Ze.writeln(e.replace(/\n/g,`\r
52
+ `))}function um(){Rr=!1,la=0,ha=0,tt==null||tt.close(),tt=null,Ns==null||Ns.disconnect(),Ns=null,Ze==null||Ze.dispose(),Ze=null,Er=null,Fc.innerHTML="",ka.style.display="none",Wc.style.display="flex",Gc()}Gc();const Dh=document.getElementById("app");function ca(){if(!window.visualViewport)return;const e=window.visualViewport;Dh.style.height=`${e.height}px`,Dh.style.top=`${e.offsetTop}px`,ka.classList.toggle("landscape",e.width>e.height),Ea()}window.visualViewport&&(window.visualViewport.addEventListener("resize",ca),window.visualViewport.addEventListener("scroll",ca));window.addEventListener("orientationchange",()=>setTimeout(ca,300));fs.addEventListener("input",()=>{let e=fs.value.replace(/[^A-Za-z0-9]/g,"").toUpperCase();e.length>4&&(e=e.slice(0,4)+"-"+e.slice(4,8)),fs.value=e});rm.addEventListener("click",()=>jc());fs.addEventListener("keydown",e=>{e.key==="Enter"&&jc()});sm.addEventListener("click",async()=>{try{const{Html5Qrcode:e}=await Wh(async()=>{const{Html5Qrcode:i}=await import("./index-Cg3W-pBy.js");return{Html5Qrcode:i}},[],import.meta.url);Lh.style.display="block";const t=new e("qrReader");await t.start({facingMode:"environment"},{fps:10,qrbox:{width:250,height:250}},async i=>{await t.stop(),Lh.style.display="none",$c(i)},()=>{})}catch{Ar("Camera access denied or not available")}});om.addEventListener("click",()=>Ze==null?void 0:Ze.focus());am.addEventListener("click",()=>{Ze==null||Ze.focus(),tt==null||tt.send({type:"terminal_input",data:""})});lm.addEventListener("click",()=>{Ze==null||Ze.focus(),tt==null||tt.send({type:"terminal_input",data:"\x1B"})});hm.addEventListener("click",()=>{Ze==null||Ze.focus(),tt==null||tt.send({type:"terminal_input",data:" "})});nm.addEventListener("click",()=>{tt==null||tt.send({type:"terminal_close"}),um()});(async()=>{const e=location.hash.slice(1);if(e){history.replaceState(null,"",location.pathname+location.search);try{const a=atob(e.replace(/-/g,"+").replace(/_/g,"/"));await $c(a)}catch{}tt||gn();return}const t=qc();if(!t)return;ua("Reconnecting...");const i=Mr(new TextEncoder().encode("airloom-key:"+t.session)),n=_a(i);try{await _n(t.relay,t.session,n,t.transport,t.token,8e3)}catch{}tt||(cm(),gn(),fm())})();async function jc(){const e=Df(fs.value);if(e.length!==8){Ar("Code must be 8 characters");return}const t=If(e),i=Mr(new TextEncoder().encode("airloom-key:"+t)),n=_a(i),a=qc(),h=[...new Set([location.origin,a==null?void 0:a.hostOrigin].filter(Boolean))];for(const g of h)try{const v=await fetch(`${g}/api/pair?session=${encodeURIComponent(t)}`);if(v.ok){const m=await v.json();aa(fs.value,m.relay),zc({session:t,token:m.token,transport:m.transport,relay:m.relay,hostOrigin:g}),await _n(m.relay,t,n,m.transport,m.token);return}}catch{}const d=ra.value.trim()||"ws://localhost:4500";aa(fs.value,d),await _n(d,t,n)}async function $c(e){try{const t=cf(e);aa(null,t.relay);const i=t.transport??"ws";zc({session:t.session,token:t.token,transport:i,relay:t.relay,hostOrigin:location.origin});const n=Mr(new TextEncoder().encode("airloom-key:"+t.session)),a=_a(n);await _n(t.relay,t.session,a,i,t.token)}catch(t){const i=t instanceof Error?t.message:"Unknown error";Ar("Invalid QR code: "+i)}}function dm(e){const t=e.meta;return(t==null?void 0:t.kind)==="terminal"}async function _n(e,t,i,n="ws",a,h=0){ua("Connecting..."),gn();try{let d;if(n==="ably"){if(!a){Ar("Ably transport requires a token");return}d=new Gf({token:a})}else d=new Wf(e);tt=new Uf({adapter:d,role:"viewer",encryptionKey:i});let g=null;h>0&&(g=setTimeout(()=>{if(!Rr){const v=tt;tt=null,v==null||v.close(),gn()}},h)),tt.on("ready",()=>{g&&(clearTimeout(g),g=null),Li("[viewer] Channel ready"),Rr=!0,Wc.style.display="none",ka.style.display="flex",lo("Connected"),Ih(),Li("[viewer] Terminal ensured, calling fitAndSyncTerminal(true)"),requestAnimationFrame(()=>{Ea(!0),Ze==null||Ze.focus()})}),tt.on("peer_left",()=>{lo("Disconnected","status-badge disconnected"),Ls(""),Ls("[host disconnected]")}),tt.on("message",v=>{if(!(!v||typeof v!="object"||!("type"in v))&&v.type==="terminal_exit"){const m=v,R=typeof m.exitCode=="number"?`exit ${m.exitCode}`:"terminated";Ls(""),Ls(`[terminal ${R}]`)}}),tt.on("stream",v=>{if(!dm(v)){Li("[viewer] Non-terminal stream, ignoring");return}Li("[viewer] Terminal stream received"),Ih(),v.on("data",m=>{Ze==null||Ze.write(m)}),v.on("end",()=>{Li("[viewer] Stream ended"),Ls("[session closed]")})}),tt.on("error",v=>{console.error("Channel error:",v),Ls(`[error: ${v.message}]`)}),tt.on("disconnect",()=>lo("Reconnecting…","status-badge reconnecting")),await tt.connect(t),ua("Connected to relay, waiting for host...")}catch(d){const g=tt;tt=null;try{g==null||g.close()}catch{}const v=d instanceof Error?d.message:"Unknown error";Ar("Connection failed: "+v)}}function Ar(e){na.textContent=e,na.style.display="block"}function gn(){na.style.display="none"}function fm(){oa.style.display="none"}function ua(e){oa.textContent=e,oa.style.display="block"}export{Ki as c,sf as g};