@hown/djinn 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,148 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __djinnCreateRequire } from "node:module"; const require = __djinnCreateRequire(import.meta.url);
3
+ var kh=Object.create;var si=Object.defineProperty;var Th=Object.getOwnPropertyDescriptor;var Ah=Object.getOwnPropertyNames;var Ih=Object.getPrototypeOf,Ph=Object.prototype.hasOwnProperty;var se=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Lh=(t,e)=>{for(var r in e)si(t,r,{get:e[r],enumerable:!0})},Rh=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ah(e))!Ph.call(t,i)&&i!==r&&si(t,i,{get:()=>e[i],enumerable:!(s=Th(e,i))||s.enumerable});return t};var Re=(t,e,r)=>(r=t!=null?kh(Ih(t)):{},Rh(e||!t||!t.__esModule?si(r,"default",{value:t,enumerable:!0}):r,t));var ni=q((Gg,Zn)=>{"use strict";Zn.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var Xe=q(_t=>{"use strict";var oi,Vh=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];_t.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};_t.getSymbolTotalCodewords=function(e){return Vh[e]};_t.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};_t.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');oi=e};_t.isKanjiModeEnabled=function(){return typeof oi<"u"};_t.toSJIS=function(e){return oi(e)}});var Zr=q(be=>{"use strict";be.L={bit:1};be.M={bit:0};be.Q={bit:3};be.H={bit:2};function Gh(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return be.L;case"m":case"medium":return be.M;case"q":case"quartile":return be.Q;case"h":case"high":return be.H;default:throw new Error("Unknown EC Level: "+t)}}be.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};be.from=function(e,r){if(be.isValid(e))return e;try{return Gh(e)}catch{return r}}});var Qn=q((Zg,Xn)=>{"use strict";function Kn(){this.buffer=[],this.length=0}Kn.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r<e;r++)this.putBit((t>>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};Xn.exports=Kn});var to=q((Kg,eo)=>{"use strict";function Sr(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}Sr.prototype.set=function(t,e,r,s){let i=t*this.size+e;this.data[i]=r,s&&(this.reservedBit[i]=!0)};Sr.prototype.get=function(t,e){return this.data[t*this.size+e]};Sr.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};Sr.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};eo.exports=Sr});var ro=q(Kr=>{"use strict";var Yh=Xe().getSymbolSize;Kr.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,s=Yh(e),i=s===145?26:Math.ceil((s-13)/(2*r-2))*2,o=[s-7];for(let a=1;a<r-1;a++)o[a]=o[a-1]-i;return o.push(6),o.reverse()};Kr.getPositions=function(e){let r=[],s=Kr.getRowColCoords(e),i=s.length;for(let o=0;o<i;o++)for(let a=0;a<i;a++)o===0&&a===0||o===0&&a===i-1||o===i-1&&a===0||r.push([s[o],s[a]]);return r}});var no=q(io=>{"use strict";var Jh=Xe().getSymbolSize,so=7;io.getPositions=function(e){let r=Jh(e);return[[0,0],[r-so,0],[0,r-so]]}});var oo=q(ae=>{"use strict";ae.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var mt={N1:3,N2:3,N3:40,N4:10};ae.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};ae.from=function(e){return ae.isValid(e)?parseInt(e,10):void 0};ae.getPenaltyN1=function(e){let r=e.size,s=0,i=0,o=0,a=null,n=null;for(let l=0;l<r;l++){i=o=0,a=n=null;for(let u=0;u<r;u++){let y=e.get(l,u);y===a?i++:(i>=5&&(s+=mt.N1+(i-5)),a=y,i=1),y=e.get(u,l),y===n?o++:(o>=5&&(s+=mt.N1+(o-5)),n=y,o=1)}i>=5&&(s+=mt.N1+(i-5)),o>=5&&(s+=mt.N1+(o-5))}return s};ae.getPenaltyN2=function(e){let r=e.size,s=0;for(let i=0;i<r-1;i++)for(let o=0;o<r-1;o++){let a=e.get(i,o)+e.get(i,o+1)+e.get(i+1,o)+e.get(i+1,o+1);(a===4||a===0)&&s++}return s*mt.N2};ae.getPenaltyN3=function(e){let r=e.size,s=0,i=0,o=0;for(let a=0;a<r;a++){i=o=0;for(let n=0;n<r;n++)i=i<<1&2047|e.get(a,n),n>=10&&(i===1488||i===93)&&s++,o=o<<1&2047|e.get(n,a),n>=10&&(o===1488||o===93)&&s++}return s*mt.N3};ae.getPenaltyN4=function(e){let r=0,s=e.data.length;for(let o=0;o<s;o++)r+=e.data[o];return Math.abs(Math.ceil(r*100/s/5)-10)*mt.N4};function Zh(t,e,r){switch(t){case ae.Patterns.PATTERN000:return(e+r)%2===0;case ae.Patterns.PATTERN001:return e%2===0;case ae.Patterns.PATTERN010:return r%3===0;case ae.Patterns.PATTERN011:return(e+r)%3===0;case ae.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(r/3))%2===0;case ae.Patterns.PATTERN101:return e*r%2+e*r%3===0;case ae.Patterns.PATTERN110:return(e*r%2+e*r%3)%2===0;case ae.Patterns.PATTERN111:return(e*r%3+(e+r)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}ae.applyMask=function(e,r){let s=r.size;for(let i=0;i<s;i++)for(let o=0;o<s;o++)r.isReserved(o,i)||r.xor(o,i,Zh(e,o,i))};ae.getBestMask=function(e,r){let s=Object.keys(ae.Patterns).length,i=0,o=1/0;for(let a=0;a<s;a++){r(a),ae.applyMask(a,e);let n=ae.getPenaltyN1(e)+ae.getPenaltyN2(e)+ae.getPenaltyN3(e)+ae.getPenaltyN4(e);ae.applyMask(a,e),n<o&&(o=n,i=a)}return i}});var ci=q(ai=>{"use strict";var Qe=Zr(),Xr=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],Qr=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];ai.getBlocksCount=function(e,r){switch(r){case Qe.L:return Xr[(e-1)*4+0];case Qe.M:return Xr[(e-1)*4+1];case Qe.Q:return Xr[(e-1)*4+2];case Qe.H:return Xr[(e-1)*4+3];default:return}};ai.getTotalCodewordsCount=function(e,r){switch(r){case Qe.L:return Qr[(e-1)*4+0];case Qe.M:return Qr[(e-1)*4+1];case Qe.Q:return Qr[(e-1)*4+2];case Qe.H:return Qr[(e-1)*4+3];default:return}}});var ao=q(ts=>{"use strict";var Cr=new Uint8Array(512),es=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)Cr[r]=e,es[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)Cr[r]=Cr[r-255]})();ts.log=function(e){if(e<1)throw new Error("log("+e+")");return es[e]};ts.exp=function(e){return Cr[e]};ts.mul=function(e,r){return e===0||r===0?0:Cr[es[e]+es[r]]}});var co=q(Er=>{"use strict";var li=ao();Er.mul=function(e,r){let s=new Uint8Array(e.length+r.length-1);for(let i=0;i<e.length;i++)for(let o=0;o<r.length;o++)s[i+o]^=li.mul(e[i],r[o]);return s};Er.mod=function(e,r){let s=new Uint8Array(e);for(;s.length-r.length>=0;){let i=s[0];for(let a=0;a<r.length;a++)s[a]^=li.mul(r[a],i);let o=0;for(;o<s.length&&s[o]===0;)o++;s=s.slice(o)}return s};Er.generateECPolynomial=function(e){let r=new Uint8Array([1]);for(let s=0;s<e;s++)r=Er.mul(r,new Uint8Array([1,li.exp(s)]));return r}});var uo=q((i0,ho)=>{"use strict";var lo=co();function hi(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}hi.prototype.initialize=function(e){this.degree=e,this.genPoly=lo.generateECPolynomial(this.degree)};hi.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(e.length+this.degree);r.set(e);let s=lo.mod(r,this.genPoly),i=this.degree-s.length;if(i>0){let o=new Uint8Array(this.degree);return o.set(s,i),o}return s};ho.exports=hi});var ui=q(fo=>{"use strict";fo.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var di=q(je=>{"use strict";var po="[0-9]+",Kh="[A-Z $%*+\\-./:]+",xr="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";xr=xr.replace(/u/g,"\\u");var Xh="(?:(?![A-Z0-9 $%*+\\-./:]|"+xr+`)(?:.|[\r
4
+ ]))+`;je.KANJI=new RegExp(xr,"g");je.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");je.BYTE=new RegExp(Xh,"g");je.NUMERIC=new RegExp(po,"g");je.ALPHANUMERIC=new RegExp(Kh,"g");var Qh=new RegExp("^"+xr+"$"),eu=new RegExp("^"+po+"$"),tu=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");je.testKanji=function(e){return Qh.test(e)};je.testNumeric=function(e){return eu.test(e)};je.testAlphanumeric=function(e){return tu.test(e)}});var et=q(le=>{"use strict";var ru=ui(),fi=di();le.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};le.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};le.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};le.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};le.MIXED={bit:-1};le.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!ru.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};le.getBestModeForData=function(e){return fi.testNumeric(e)?le.NUMERIC:fi.testAlphanumeric(e)?le.ALPHANUMERIC:fi.testKanji(e)?le.KANJI:le.BYTE};le.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};le.isValid=function(e){return e&&e.bit&&e.ccBits};function su(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return le.NUMERIC;case"alphanumeric":return le.ALPHANUMERIC;case"kanji":return le.KANJI;case"byte":return le.BYTE;default:throw new Error("Unknown mode: "+t)}}le.from=function(e,r){if(le.isValid(e))return e;try{return su(e)}catch{return r}}});var yo=q(gt=>{"use strict";var rs=Xe(),iu=ci(),_o=Zr(),tt=et(),pi=ui(),go=7973,mo=rs.getBCHDigit(go);function nu(t,e,r){for(let s=1;s<=40;s++)if(e<=gt.getCapacity(s,r,t))return s}function vo(t,e){return tt.getCharCountIndicator(t,e)+4}function ou(t,e){let r=0;return t.forEach(function(s){let i=vo(s.mode,e);r+=i+s.getBitsLength()}),r}function au(t,e){for(let r=1;r<=40;r++)if(ou(t,r)<=gt.getCapacity(r,e,tt.MIXED))return r}gt.from=function(e,r){return pi.isValid(e)?parseInt(e,10):r};gt.getCapacity=function(e,r,s){if(!pi.isValid(e))throw new Error("Invalid QR Code version");typeof s>"u"&&(s=tt.BYTE);let i=rs.getSymbolTotalCodewords(e),o=iu.getTotalCodewordsCount(e,r),a=(i-o)*8;if(s===tt.MIXED)return a;let n=a-vo(s,e);switch(s){case tt.NUMERIC:return Math.floor(n/10*3);case tt.ALPHANUMERIC:return Math.floor(n/11*2);case tt.KANJI:return Math.floor(n/13);case tt.BYTE:default:return Math.floor(n/8)}};gt.getBestVersionForData=function(e,r){let s,i=_o.from(r,_o.M);if(Array.isArray(e)){if(e.length>1)return au(e,i);if(e.length===0)return 1;s=e[0]}else s=e;return nu(s.mode,s.getLength(),i)};gt.getEncodedBits=function(e){if(!pi.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;rs.getBCHDigit(r)-mo>=0;)r^=go<<rs.getBCHDigit(r)-mo;return e<<12|r}});var Co=q(So=>{"use strict";var _i=Xe(),wo=1335,cu=21522,bo=_i.getBCHDigit(wo);So.getEncodedBits=function(e,r){let s=e.bit<<3|r,i=s<<10;for(;_i.getBCHDigit(i)-bo>=0;)i^=wo<<_i.getBCHDigit(i)-bo;return(s<<10|i)^cu}});var xo=q((h0,Eo)=>{"use strict";var lu=et();function Gt(t){this.mode=lu.NUMERIC,this.data=t.toString()}Gt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Gt.prototype.getLength=function(){return this.data.length};Gt.prototype.getBitsLength=function(){return Gt.getBitsLength(this.data.length)};Gt.prototype.write=function(e){let r,s,i;for(r=0;r+3<=this.data.length;r+=3)s=this.data.substr(r,3),i=parseInt(s,10),e.put(i,10);let o=this.data.length-r;o>0&&(s=this.data.substr(r),i=parseInt(s,10),e.put(i,o*3+1))};Eo.exports=Gt});var To=q((u0,ko)=>{"use strict";var hu=et(),mi=["0","1","2","3","4","5","6","7","8","9","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"," ","$","%","*","+","-",".","/",":"];function Yt(t){this.mode=hu.ALPHANUMERIC,this.data=t}Yt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Yt.prototype.getLength=function(){return this.data.length};Yt.prototype.getBitsLength=function(){return Yt.getBitsLength(this.data.length)};Yt.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let s=mi.indexOf(this.data[r])*45;s+=mi.indexOf(this.data[r+1]),e.put(s,11)}this.data.length%2&&e.put(mi.indexOf(this.data[r]),6)};ko.exports=Yt});var Io=q((d0,Ao)=>{"use strict";var uu=et();function Jt(t){this.mode=uu.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}Jt.getBitsLength=function(e){return e*8};Jt.prototype.getLength=function(){return this.data.length};Jt.prototype.getBitsLength=function(){return Jt.getBitsLength(this.data.length)};Jt.prototype.write=function(t){for(let e=0,r=this.data.length;e<r;e++)t.put(this.data[e],8)};Ao.exports=Jt});var Lo=q((f0,Po)=>{"use strict";var du=et(),fu=Xe();function Zt(t){this.mode=du.KANJI,this.data=t}Zt.getBitsLength=function(e){return e*13};Zt.prototype.getLength=function(){return this.data.length};Zt.prototype.getBitsLength=function(){return Zt.getBitsLength(this.data.length)};Zt.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let r=fu.toSJIS(this.data[e]);if(r>=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
5
+ Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};Po.exports=Zt});var Ro=q((p0,gi)=>{"use strict";var kr={single_source_shortest_paths:function(t,e,r){var s={},i={};i[e]=0;var o=kr.PriorityQueue.make();o.push(e,0);for(var a,n,l,u,y,h,_,d,p;!o.empty();){a=o.pop(),n=a.value,u=a.cost,y=t[n]||{};for(l in y)y.hasOwnProperty(l)&&(h=y[l],_=u+h,d=i[l],p=typeof i[l]>"u",(p||d>_)&&(i[l]=_,o.push(l,_),s[l]=n))}if(typeof r<"u"&&typeof i[r]>"u"){var b=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(b)}return s},extract_shortest_path_from_predecessor_list:function(t,e){for(var r=[],s=e,i;s;)r.push(s),i=t[s],s=t[s];return r.reverse(),r},find_path:function(t,e,r){var s=kr.single_source_shortest_paths(t,e,r);return kr.extract_shortest_path_from_predecessor_list(s,r)},PriorityQueue:{make:function(t){var e=kr.PriorityQueue,r={},s;t=t||{};for(s in e)e.hasOwnProperty(s)&&(r[s]=e[s]);return r.queue=[],r.sorter=t.sorter||e.default_sorter,r},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var r={value:t,cost:e};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof gi<"u"&&(gi.exports=kr)});var Fo=q(Kt=>{"use strict";var oe=et(),Do=xo(),Mo=To(),No=Io(),Ho=Lo(),Tr=di(),ss=Xe(),pu=Ro();function Bo(t){return unescape(encodeURIComponent(t)).length}function Ar(t,e,r){let s=[],i;for(;(i=t.exec(r))!==null;)s.push({data:i[0],index:i.index,mode:e,length:i[0].length});return s}function Uo(t){let e=Ar(Tr.NUMERIC,oe.NUMERIC,t),r=Ar(Tr.ALPHANUMERIC,oe.ALPHANUMERIC,t),s,i;return ss.isKanjiModeEnabled()?(s=Ar(Tr.BYTE,oe.BYTE,t),i=Ar(Tr.KANJI,oe.KANJI,t)):(s=Ar(Tr.BYTE_KANJI,oe.BYTE,t),i=[]),e.concat(r,s,i).sort(function(a,n){return a.index-n.index}).map(function(a){return{data:a.data,mode:a.mode,length:a.length}})}function vi(t,e){switch(e){case oe.NUMERIC:return Do.getBitsLength(t);case oe.ALPHANUMERIC:return Mo.getBitsLength(t);case oe.KANJI:return Ho.getBitsLength(t);case oe.BYTE:return No.getBitsLength(t)}}function _u(t){return t.reduce(function(e,r){let s=e.length-1>=0?e[e.length-1]:null;return s&&s.mode===r.mode?(e[e.length-1].data+=r.data,e):(e.push(r),e)},[])}function mu(t){let e=[];for(let r=0;r<t.length;r++){let s=t[r];switch(s.mode){case oe.NUMERIC:e.push([s,{data:s.data,mode:oe.ALPHANUMERIC,length:s.length},{data:s.data,mode:oe.BYTE,length:s.length}]);break;case oe.ALPHANUMERIC:e.push([s,{data:s.data,mode:oe.BYTE,length:s.length}]);break;case oe.KANJI:e.push([s,{data:s.data,mode:oe.BYTE,length:Bo(s.data)}]);break;case oe.BYTE:e.push([{data:s.data,mode:oe.BYTE,length:Bo(s.data)}])}}return e}function gu(t,e){let r={},s={start:{}},i=["start"];for(let o=0;o<t.length;o++){let a=t[o],n=[];for(let l=0;l<a.length;l++){let u=a[l],y=""+o+l;n.push(y),r[y]={node:u,lastCount:0},s[y]={};for(let h=0;h<i.length;h++){let _=i[h];r[_]&&r[_].node.mode===u.mode?(s[_][y]=vi(r[_].lastCount+u.length,u.mode)-vi(r[_].lastCount,u.mode),r[_].lastCount+=u.length):(r[_]&&(r[_].lastCount=u.length),s[_][y]=vi(u.length,u.mode)+4+oe.getCharCountIndicator(u.mode,e))}}i=n}for(let o=0;o<i.length;o++)s[i[o]].end=0;return{map:s,table:r}}function Oo(t,e){let r,s=oe.getBestModeForData(t);if(r=oe.from(e,s),r!==oe.BYTE&&r.bit<s.bit)throw new Error('"'+t+'" cannot be encoded with mode '+oe.toString(r)+`.
6
+ Suggested mode is: `+oe.toString(s));switch(r===oe.KANJI&&!ss.isKanjiModeEnabled()&&(r=oe.BYTE),r){case oe.NUMERIC:return new Do(t);case oe.ALPHANUMERIC:return new Mo(t);case oe.KANJI:return new Ho(t);case oe.BYTE:return new No(t)}}Kt.fromArray=function(e){return e.reduce(function(r,s){return typeof s=="string"?r.push(Oo(s,null)):s.data&&r.push(Oo(s.data,s.mode)),r},[])};Kt.fromString=function(e,r){let s=Uo(e,ss.isKanjiModeEnabled()),i=mu(s),o=gu(i,r),a=pu.find_path(o.map,"start","end"),n=[];for(let l=1;l<a.length-1;l++)n.push(o.table[a[l]].node);return Kt.fromArray(_u(n))};Kt.rawSplit=function(e){return Kt.fromArray(Uo(e,ss.isKanjiModeEnabled()))}});var Ei=q(jo=>{"use strict";var ns=Xe(),yi=Zr(),vu=Qn(),yu=to(),bu=ro(),wu=no(),Si=oo(),Ci=ci(),Su=uo(),is=yo(),Cu=Co(),Eu=et(),bi=Fo();function xu(t,e){let r=t.size,s=wu.getPositions(e);for(let i=0;i<s.length;i++){let o=s[i][0],a=s[i][1];for(let n=-1;n<=7;n++)if(!(o+n<=-1||r<=o+n))for(let l=-1;l<=7;l++)a+l<=-1||r<=a+l||(n>=0&&n<=6&&(l===0||l===6)||l>=0&&l<=6&&(n===0||n===6)||n>=2&&n<=4&&l>=2&&l<=4?t.set(o+n,a+l,!0,!0):t.set(o+n,a+l,!1,!0))}}function ku(t){let e=t.size;for(let r=8;r<e-8;r++){let s=r%2===0;t.set(r,6,s,!0),t.set(6,r,s,!0)}}function Tu(t,e){let r=bu.getPositions(e);for(let s=0;s<r.length;s++){let i=r[s][0],o=r[s][1];for(let a=-2;a<=2;a++)for(let n=-2;n<=2;n++)a===-2||a===2||n===-2||n===2||a===0&&n===0?t.set(i+a,o+n,!0,!0):t.set(i+a,o+n,!1,!0)}}function Au(t,e){let r=t.size,s=is.getEncodedBits(e),i,o,a;for(let n=0;n<18;n++)i=Math.floor(n/3),o=n%3+r-8-3,a=(s>>n&1)===1,t.set(i,o,a,!0),t.set(o,i,a,!0)}function wi(t,e,r){let s=t.size,i=Cu.getEncodedBits(e,r),o,a;for(o=0;o<15;o++)a=(i>>o&1)===1,o<6?t.set(o,8,a,!0):o<8?t.set(o+1,8,a,!0):t.set(s-15+o,8,a,!0),o<8?t.set(8,s-o-1,a,!0):o<9?t.set(8,15-o-1+1,a,!0):t.set(8,15-o-1,a,!0);t.set(s-8,8,1,!0)}function Iu(t,e){let r=t.size,s=-1,i=r-1,o=7,a=0;for(let n=r-1;n>0;n-=2)for(n===6&&n--;;){for(let l=0;l<2;l++)if(!t.isReserved(i,n-l)){let u=!1;a<e.length&&(u=(e[a]>>>o&1)===1),t.set(i,n-l,u),o--,o===-1&&(a++,o=7)}if(i+=s,i<0||r<=i){i-=s,s=-s;break}}}function Pu(t,e,r){let s=new vu;r.forEach(function(l){s.put(l.mode.bit,4),s.put(l.getLength(),Eu.getCharCountIndicator(l.mode,t)),l.write(s)});let i=ns.getSymbolTotalCodewords(t),o=Ci.getTotalCodewordsCount(t,e),a=(i-o)*8;for(s.getLengthInBits()+4<=a&&s.put(0,4);s.getLengthInBits()%8!==0;)s.putBit(0);let n=(a-s.getLengthInBits())/8;for(let l=0;l<n;l++)s.put(l%2?17:236,8);return Lu(s,t,e)}function Lu(t,e,r){let s=ns.getSymbolTotalCodewords(e),i=Ci.getTotalCodewordsCount(e,r),o=s-i,a=Ci.getBlocksCount(e,r),n=s%a,l=a-n,u=Math.floor(s/a),y=Math.floor(o/a),h=y+1,_=u-y,d=new Su(_),p=0,b=new Array(a),c=new Array(a),v=0,g=new Uint8Array(t.buffer);for(let k=0;k<a;k++){let A=k<l?y:h;b[k]=g.slice(p,p+A),c[k]=d.encode(b[k]),p+=A,v=Math.max(v,A)}let f=new Uint8Array(s),m=0,w,C;for(w=0;w<v;w++)for(C=0;C<a;C++)w<b[C].length&&(f[m++]=b[C][w]);for(w=0;w<_;w++)for(C=0;C<a;C++)f[m++]=c[C][w];return f}function Ru(t,e,r,s){let i;if(Array.isArray(t))i=bi.fromArray(t);else if(typeof t=="string"){let u=e;if(!u){let y=bi.rawSplit(t);u=is.getBestVersionForData(y,r)}i=bi.fromString(t,u||40)}else throw new Error("Invalid data");let o=is.getBestVersionForData(i,r);if(!o)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=o;else if(e<o)throw new Error(`
7
+ The chosen QR Code version cannot contain this amount of data.
8
+ Minimum version required to store current data is: `+o+`.
9
+ `);let a=Pu(e,r,i),n=ns.getSymbolSize(e),l=new yu(n);return xu(l,e),ku(l),Tu(l,e),wi(l,r,0),e>=7&&Au(l,e),Iu(l,a),isNaN(s)&&(s=Si.getBestMask(l,wi.bind(null,l,r))),Si.applyMask(s,l),wi(l,r,s),{modules:l,version:e,errorCorrectionLevel:r,maskPattern:s,segments:i}}jo.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let s=yi.M,i,o;return typeof r<"u"&&(s=yi.from(r.errorCorrectionLevel,yi.M),i=is.from(r.version),o=Si.from(r.maskPattern),r.toSJISFunc&&ns.setToSJISFunction(r.toSJISFunc)),Ru(e,i,s,o)}});var xi=q((g0,qo)=>{"use strict";var Bu=se("util"),Wo=se("stream"),Ie=qo.exports=function(){Wo.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Bu.inherits(Ie,Wo);Ie.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};Ie.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let r;return Buffer.isBuffer(t)?r=t:r=Buffer.from(t,e||this._encoding),this._buffers.push(r),this._buffered+=r.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};Ie.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};Ie.prototype.destroySoon=Ie.prototype.end;Ie.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Ie.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Ie.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};Ie.prototype._processRead=function(t){this._reads.shift();let e=0,r=0,s=Buffer.alloc(t.length);for(;e<t.length;){let i=this._buffers[r++],o=Math.min(i.length,t.length-e);i.copy(s,e,0,o),e+=o,o!==i.length&&(this._buffers[--r]=i.slice(o))}r>0&&this._buffers.splice(0,r),this._buffered-=t.length,t.func.call(this,s)};Ie.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var Ti=q(ki=>{"use strict";var rt=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];ki.getImagePasses=function(t,e){let r=[],s=t%8,i=e%8,o=(t-s)/8,a=(e-i)/8;for(let n=0;n<rt.length;n++){let l=rt[n],u=o*l.x.length,y=a*l.y.length;for(let h=0;h<l.x.length&&l.x[h]<s;h++)u++;for(let h=0;h<l.y.length&&l.y[h]<i;h++)y++;u>0&&y>0&&r.push({width:u,height:y,index:n})}return r};ki.getInterlaceIterator=function(t){return function(e,r,s){let i=e%rt[s].x.length,o=(e-i)/rt[s].x.length*8+rt[s].x[i],a=r%rt[s].y.length,n=(r-a)/rt[s].y.length*8+rt[s].y[a];return o*4+n*t*4}}});var Ai=q((y0,$o)=>{"use strict";$o.exports=function(e,r,s){let i=e+r-s,o=Math.abs(i-e),a=Math.abs(i-r),n=Math.abs(i-s);return o<=a&&o<=n?e:a<=n?r:s}});var Ii=q((b0,Vo)=>{"use strict";var Ou=Ti(),Du=Ai();function zo(t,e,r){let s=t*e;return r!==8&&(s=Math.ceil(s/(8/r))),s}var Xt=Vo.exports=function(t,e){let r=t.width,s=t.height,i=t.interlace,o=t.bpp,a=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],i){let n=Ou.getImagePasses(r,s);for(let l=0;l<n.length;l++)this._images.push({byteWidth:zo(n[l].width,o,a),height:n[l].height,lineIndex:0})}else this._images.push({byteWidth:zo(r,o,a),height:s,lineIndex:0});a===8?this._xComparison=o:a===16?this._xComparison=o*2:this._xComparison=1};Xt.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Xt.prototype._unFilterType1=function(t,e,r){let s=this._xComparison,i=s-1;for(let o=0;o<r;o++){let a=t[1+o],n=o>i?e[o-s]:0;e[o]=a+n}};Xt.prototype._unFilterType2=function(t,e,r){let s=this._lastLine;for(let i=0;i<r;i++){let o=t[1+i],a=s?s[i]:0;e[i]=o+a}};Xt.prototype._unFilterType3=function(t,e,r){let s=this._xComparison,i=s-1,o=this._lastLine;for(let a=0;a<r;a++){let n=t[1+a],l=o?o[a]:0,u=a>i?e[a-s]:0,y=Math.floor((u+l)/2);e[a]=n+y}};Xt.prototype._unFilterType4=function(t,e,r){let s=this._xComparison,i=s-1,o=this._lastLine;for(let a=0;a<r;a++){let n=t[1+a],l=o?o[a]:0,u=a>i?e[a-s]:0,y=a>i&&o?o[a-s]:0,h=Du(u,l,y);e[a]=n+h}};Xt.prototype._reverseFilterLine=function(t){let e=t[0],r,s=this._images[this._imageIndex],i=s.byteWidth;if(e===0)r=t.slice(1,i+1);else switch(r=Buffer.alloc(i),e){case 1:this._unFilterType1(t,r,i);break;case 2:this._unFilterType2(t,r,i);break;case 3:this._unFilterType3(t,r,i);break;case 4:this._unFilterType4(t,r,i);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(r),s.lineIndex++,s.lineIndex>=s.height?(this._lastLine=null,this._imageIndex++,s=this._images[this._imageIndex]):this._lastLine=r,s?this.read(s.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Jo=q((w0,Yo)=>{"use strict";var Mu=se("util"),Go=xi(),Nu=Ii(),Hu=Yo.exports=function(t){Go.call(this);let e=[],r=this;this._filter=new Nu(t,{read:this.read.bind(this),write:function(s){e.push(s)},complete:function(){r.emit("complete",Buffer.concat(e))}}),this._filter.start()};Mu.inherits(Hu,Go)});var Qt=q((S0,Zo)=>{"use strict";Zo.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var Ri=q((C0,Ko)=>{"use strict";var Pi=[];(function(){for(let t=0;t<256;t++){let e=t;for(let r=0;r<8;r++)e&1?e=3988292384^e>>>1:e=e>>>1;Pi[t]=e}})();var Li=Ko.exports=function(){this._crc=-1};Li.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Pi[(this._crc^t[e])&255]^this._crc>>>8;return!0};Li.prototype.crc32=function(){return this._crc^-1};Li.crc32=function(t){let e=-1;for(let r=0;r<t.length;r++)e=Pi[(e^t[r])&255]^e>>>8;return e^-1}});var Bi=q((E0,Xo)=>{"use strict";var he=Qt(),Uu=Ri(),ue=Xo.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[he.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[he.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[he.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[he.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[he.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[he.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};ue.prototype.start=function(){this.read(he.PNG_SIGNATURE.length,this._parseSignature.bind(this))};ue.prototype._parseSignature=function(t){let e=he.PNG_SIGNATURE;for(let r=0;r<e.length;r++)if(t[r]!==e[r]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};ue.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),r=t.readUInt32BE(4),s="";for(let o=4;o<8;o++)s+=String.fromCharCode(t[o]);let i=!!(t[4]&32);if(!this._hasIHDR&&r!==he.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Uu,this._crc.write(Buffer.from(s)),this._chunks[r])return this._chunks[r](e);if(!i){this.error(new Error("Unsupported critical chunk type "+s));return}this.read(e+4,this._skipChunk.bind(this))};ue.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};ue.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};ue.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),r=this._crc.crc32();if(this._options.checkCRC&&r!==e){this.error(new Error("Crc error - "+e+" - "+r));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};ue.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};ue.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),r=t.readUInt32BE(4),s=t[8],i=t[9],o=t[10],a=t[11],n=t[12];if(s!==8&&s!==4&&s!==2&&s!==1&&s!==16){this.error(new Error("Unsupported bit depth "+s));return}if(!(i in he.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(o!==0){this.error(new Error("Unsupported compression method"));return}if(a!==0){this.error(new Error("Unsupported filter method"));return}if(n!==0&&n!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=i;let l=he.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:r,depth:s,interlace:!!n,palette:!!(i&he.COLORTYPE_PALETTE),color:!!(i&he.COLORTYPE_COLOR),alpha:!!(i&he.COLORTYPE_ALPHA),bpp:l,colorType:i}),this._handleChunkEnd()};ue.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};ue.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let r=0;r<e;r++)this._palette.push([t[r*3],t[r*3+1],t[r*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};ue.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};ue.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===he.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===he.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===he.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};ue.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};ue.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/he.GAMMA_DIVISION),this._handleChunkEnd()};ue.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};ue.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===he.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let r=t-e.length;r>0?this._handleIDAT(r):this._handleChunkEnd()};ue.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};ue.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Oi=q(ea=>{"use strict";var Qo=Ti(),Fu=[function(){},function(t,e,r,s){if(s===e.length)throw new Error("Ran out of data");let i=e[s];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=255},function(t,e,r,s){if(s+1>=e.length)throw new Error("Ran out of data");let i=e[s];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=e[s+1]},function(t,e,r,s){if(s+2>=e.length)throw new Error("Ran out of data");t[r]=e[s],t[r+1]=e[s+1],t[r+2]=e[s+2],t[r+3]=255},function(t,e,r,s){if(s+3>=e.length)throw new Error("Ran out of data");t[r]=e[s],t[r+1]=e[s+1],t[r+2]=e[s+2],t[r+3]=e[s+3]}],ju=[function(){},function(t,e,r,s){let i=e[0];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=s},function(t,e,r){let s=e[0];t[r]=s,t[r+1]=s,t[r+2]=s,t[r+3]=e[1]},function(t,e,r,s){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=s},function(t,e,r){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=e[3]}];function Wu(t,e){let r=[],s=0;function i(){if(s===t.length)throw new Error("Ran out of data");let o=t[s];s++;let a,n,l,u,y,h,_,d;switch(e){default:throw new Error("unrecognised depth");case 16:_=t[s],s++,r.push((o<<8)+_);break;case 4:_=o&15,d=o>>4,r.push(d,_);break;case 2:y=o&3,h=o>>2&3,_=o>>4&3,d=o>>6&3,r.push(d,_,h,y);break;case 1:a=o&1,n=o>>1&1,l=o>>2&1,u=o>>3&1,y=o>>4&1,h=o>>5&1,_=o>>6&1,d=o>>7&1,r.push(d,_,h,y,u,l,n,a);break}}return{get:function(o){for(;r.length<o;)i();let a=r.slice(0,o);return r=r.slice(o),a},resetAfterLine:function(){r.length=0},end:function(){if(s!==t.length)throw new Error("extra data found")}}}function qu(t,e,r,s,i,o){let a=t.width,n=t.height,l=t.index;for(let u=0;u<n;u++)for(let y=0;y<a;y++){let h=r(y,u,l);Fu[s](e,i,h,o),o+=s}return o}function $u(t,e,r,s,i,o){let a=t.width,n=t.height,l=t.index;for(let u=0;u<n;u++){for(let y=0;y<a;y++){let h=i.get(s),_=r(y,u,l);ju[s](e,h,_,o)}i.resetAfterLine()}}ea.dataToBitMap=function(t,e){let r=e.width,s=e.height,i=e.depth,o=e.bpp,a=e.interlace,n;i!==8&&(n=Wu(t,i));let l;i<=8?l=Buffer.alloc(r*s*4):l=new Uint16Array(r*s*4);let u=Math.pow(2,i)-1,y=0,h,_;if(a)h=Qo.getImagePasses(r,s),_=Qo.getInterlaceIterator(r,s);else{let d=0;_=function(){let p=d;return d+=4,p},h=[{width:r,height:s}]}for(let d=0;d<h.length;d++)i===8?y=qu(h[d],l,_,o,t,y):$u(h[d],l,_,o,n,u);if(i===8){if(y!==t.length)throw new Error("extra data found")}else n.end();return l}});var Di=q((k0,ta)=>{"use strict";function zu(t,e,r,s,i){let o=0;for(let a=0;a<s;a++)for(let n=0;n<r;n++){let l=i[t[o]];if(!l)throw new Error("index "+t[o]+" not in palette");for(let u=0;u<4;u++)e[o+u]=l[u];o+=4}}function Vu(t,e,r,s,i){let o=0;for(let a=0;a<s;a++)for(let n=0;n<r;n++){let l=!1;if(i.length===1?i[0]===t[o]&&(l=!0):i[0]===t[o]&&i[1]===t[o+1]&&i[2]===t[o+2]&&(l=!0),l)for(let u=0;u<4;u++)e[o+u]=0;o+=4}}function Gu(t,e,r,s,i){let o=255,a=Math.pow(2,i)-1,n=0;for(let l=0;l<s;l++)for(let u=0;u<r;u++){for(let y=0;y<4;y++)e[n+y]=Math.floor(t[n+y]*o/a+.5);n+=4}}ta.exports=function(t,e){let r=e.depth,s=e.width,i=e.height,o=e.colorType,a=e.transColor,n=e.palette,l=t;return o===3?zu(t,l,s,i,n):(a&&Vu(t,l,s,i,a),r!==8&&(r===16&&(l=Buffer.alloc(s*i*4)),Gu(t,l,s,i,r))),l}});var ia=q((T0,sa)=>{"use strict";var Yu=se("util"),Mi=se("zlib"),ra=xi(),Ju=Jo(),Zu=Bi(),Ku=Oi(),Xu=Di(),Be=sa.exports=function(t){ra.call(this),this._parser=new Zu(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};Yu.inherits(Be,ra);Be.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};Be.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Mi.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let r=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,s=Math.max(r,Mi.Z_MIN_CHUNK);this._inflate=Mi.createInflate({chunkSize:s});let i=r,o=this.emit.bind(this,"error");this._inflate.on("error",function(n){i&&o(n)}),this._filter.on("complete",this._complete.bind(this));let a=this._filter.write.bind(this._filter);this._inflate.on("data",function(n){i&&(n.length>i&&(n=n.slice(0,i)),i-=n.length,a(n))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};Be.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Ju(this._bitmapInfo)};Be.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};Be.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};Be.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Be.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Be.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};Be.prototype._complete=function(t){if(this.errord)return;let e;try{let r=Ku.dataToBitMap(t,this._bitmapInfo);e=Xu(r,this._bitmapInfo),r=null}catch(r){this._handleError(r);return}this.emit("parsed",e)}});var oa=q((A0,na)=>{"use strict";var we=Qt();na.exports=function(t,e,r,s){let i=[we.COLORTYPE_COLOR_ALPHA,we.COLORTYPE_ALPHA].indexOf(s.colorType)!==-1;if(s.colorType===s.inputColorType){let p=(function(){let b=new ArrayBuffer(2);return new DataView(b).setInt16(0,256,!0),new Int16Array(b)[0]!==256})();if(s.bitDepth===8||s.bitDepth===16&&p)return t}let o=s.bitDepth!==16?t:new Uint16Array(t.buffer),a=255,n=we.COLORTYPE_TO_BPP_MAP[s.inputColorType];n===4&&!s.inputHasAlpha&&(n=3);let l=we.COLORTYPE_TO_BPP_MAP[s.colorType];s.bitDepth===16&&(a=65535,l*=2);let u=Buffer.alloc(e*r*l),y=0,h=0,_=s.bgColor||{};_.red===void 0&&(_.red=a),_.green===void 0&&(_.green=a),_.blue===void 0&&(_.blue=a);function d(){let p,b,c,v=a;switch(s.inputColorType){case we.COLORTYPE_COLOR_ALPHA:v=o[y+3],p=o[y],b=o[y+1],c=o[y+2];break;case we.COLORTYPE_COLOR:p=o[y],b=o[y+1],c=o[y+2];break;case we.COLORTYPE_ALPHA:v=o[y+1],p=o[y],b=p,c=p;break;case we.COLORTYPE_GRAYSCALE:p=o[y],b=p,c=p;break;default:throw new Error("input color type:"+s.inputColorType+" is not supported at present")}return s.inputHasAlpha&&(i||(v/=a,p=Math.min(Math.max(Math.round((1-v)*_.red+v*p),0),a),b=Math.min(Math.max(Math.round((1-v)*_.green+v*b),0),a),c=Math.min(Math.max(Math.round((1-v)*_.blue+v*c),0),a))),{red:p,green:b,blue:c,alpha:v}}for(let p=0;p<r;p++)for(let b=0;b<e;b++){let c=d(o,y);switch(s.colorType){case we.COLORTYPE_COLOR_ALPHA:case we.COLORTYPE_COLOR:s.bitDepth===8?(u[h]=c.red,u[h+1]=c.green,u[h+2]=c.blue,i&&(u[h+3]=c.alpha)):(u.writeUInt16BE(c.red,h),u.writeUInt16BE(c.green,h+2),u.writeUInt16BE(c.blue,h+4),i&&u.writeUInt16BE(c.alpha,h+6));break;case we.COLORTYPE_ALPHA:case we.COLORTYPE_GRAYSCALE:{let v=(c.red+c.green+c.blue)/3;s.bitDepth===8?(u[h]=v,i&&(u[h+1]=c.alpha)):(u.writeUInt16BE(v,h),i&&u.writeUInt16BE(c.alpha,h+2));break}default:throw new Error("unrecognised color Type "+s.colorType)}y+=n,h+=l}return u}});var la=q((I0,ca)=>{"use strict";var aa=Ai();function Qu(t,e,r,s,i){for(let o=0;o<r;o++)s[i+o]=t[e+o]}function ed(t,e,r){let s=0,i=e+r;for(let o=e;o<i;o++)s+=Math.abs(t[o]);return s}function td(t,e,r,s,i,o){for(let a=0;a<r;a++){let n=a>=o?t[e+a-o]:0,l=t[e+a]-n;s[i+a]=l}}function rd(t,e,r,s){let i=0;for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,n=t[e+o]-a;i+=Math.abs(n)}return i}function sd(t,e,r,s,i){for(let o=0;o<r;o++){let a=e>0?t[e+o-r]:0,n=t[e+o]-a;s[i+o]=n}}function id(t,e,r){let s=0,i=e+r;for(let o=e;o<i;o++){let a=e>0?t[o-r]:0,n=t[o]-a;s+=Math.abs(n)}return s}function nd(t,e,r,s,i,o){for(let a=0;a<r;a++){let n=a>=o?t[e+a-o]:0,l=e>0?t[e+a-r]:0,u=t[e+a]-(n+l>>1);s[i+a]=u}}function od(t,e,r,s){let i=0;for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,n=e>0?t[e+o-r]:0,l=t[e+o]-(a+n>>1);i+=Math.abs(l)}return i}function ad(t,e,r,s,i,o){for(let a=0;a<r;a++){let n=a>=o?t[e+a-o]:0,l=e>0?t[e+a-r]:0,u=e>0&&a>=o?t[e+a-(r+o)]:0,y=t[e+a]-aa(n,l,u);s[i+a]=y}}function cd(t,e,r,s){let i=0;for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,n=e>0?t[e+o-r]:0,l=e>0&&o>=s?t[e+o-(r+s)]:0,u=t[e+o]-aa(a,n,l);i+=Math.abs(u)}return i}var ld={0:Qu,1:td,2:sd,3:nd,4:ad},hd={0:ed,1:rd,2:id,3:od,4:cd};ca.exports=function(t,e,r,s,i){let o;if(!("filterType"in s)||s.filterType===-1)o=[0,1,2,3,4];else if(typeof s.filterType=="number")o=[s.filterType];else throw new Error("unrecognised filter types");s.bitDepth===16&&(i*=2);let a=e*i,n=0,l=0,u=Buffer.alloc((a+1)*r),y=o[0];for(let h=0;h<r;h++){if(o.length>1){let _=1/0;for(let d=0;d<o.length;d++){let p=hd[o[d]](t,l,a,i);p<_&&(y=o[d],_=p)}}u[n]=y,n++,ld[y](t,l,a,u,n,i),n+=a,l+=a}return u}});var Ni=q((P0,ha)=>{"use strict";var pe=Qt(),ud=Ri(),dd=oa(),fd=la(),pd=se("zlib"),st=ha.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||pd.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:pe.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:pe.COLORTYPE_COLOR_ALPHA,[pe.COLORTYPE_GRAYSCALE,pe.COLORTYPE_COLOR,pe.COLORTYPE_COLOR_ALPHA,pe.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([pe.COLORTYPE_GRAYSCALE,pe.COLORTYPE_COLOR,pe.COLORTYPE_COLOR_ALPHA,pe.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};st.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};st.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};st.prototype.filterData=function(t,e,r){let s=dd(t,e,r,this._options),i=pe.COLORTYPE_TO_BPP_MAP[this._options.colorType];return fd(s,e,r,this._options,i)};st.prototype._packChunk=function(t,e){let r=e?e.length:0,s=Buffer.alloc(r+12);return s.writeUInt32BE(r,0),s.writeUInt32BE(t,4),e&&e.copy(s,8),s.writeInt32BE(ud.crc32(s.slice(4,s.length-4)),s.length-4),s};st.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*pe.GAMMA_DIVISION),0),this._packChunk(pe.TYPE_gAMA,e)};st.prototype.packIHDR=function(t,e){let r=Buffer.alloc(13);return r.writeUInt32BE(t,0),r.writeUInt32BE(e,4),r[8]=this._options.bitDepth,r[9]=this._options.colorType,r[10]=0,r[11]=0,r[12]=0,this._packChunk(pe.TYPE_IHDR,r)};st.prototype.packIDAT=function(t){return this._packChunk(pe.TYPE_IDAT,t)};st.prototype.packIEND=function(){return this._packChunk(pe.TYPE_IEND,null)}});var pa=q((L0,fa)=>{"use strict";var _d=se("util"),ua=se("stream"),md=Qt(),gd=Ni(),da=fa.exports=function(t){ua.call(this);let e=t||{};this._packer=new gd(e),this._deflate=this._packer.createDeflate(),this.readable=!0};_d.inherits(da,ua);da.prototype.pack=function(t,e,r,s){this.emit("data",Buffer.from(md.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,r)),s&&this.emit("data",this._packer.packGAMA(s));let i=this._packer.filterData(t,e,r);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var ba=q((Ir,ya)=>{"use strict";var _a=se("assert").ok,er=se("zlib"),vd=se("util"),ma=se("buffer").kMaxLength;function vt(t){if(!(this instanceof vt))return new vt(t);t&&t.chunkSize<er.Z_MIN_CHUNK&&(t.chunkSize=er.Z_MIN_CHUNK),er.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function yd(t){return new vt(t)}function ga(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}vt.prototype._processChunk=function(t,e,r){if(typeof r=="function")return er.Inflate._processChunk.call(this,t,e,r);let s=this,i=t&&t.length,o=this._chunkSize-this._offset,a=this._maxLength,n=0,l=[],u=0,y;this.on("error",function(p){y=p});function h(p,b){if(s._hadError)return;let c=o-b;if(_a(c>=0,"have should not go down"),c>0){let v=s._buffer.slice(s._offset,s._offset+c);if(s._offset+=c,v.length>a&&(v=v.slice(0,a)),l.push(v),u+=v.length,a-=v.length,a===0)return!1}return(b===0||s._offset>=s._chunkSize)&&(o=s._chunkSize,s._offset=0,s._buffer=Buffer.allocUnsafe(s._chunkSize)),b===0?(n+=i-p,i=p,!0):!1}_a(this._handle,"zlib binding closed");let _;do _=this._handle.writeSync(e,t,n,i,this._buffer,this._offset,o),_=_||this._writeState;while(!this._hadError&&h(_[0],_[1]));if(this._hadError)throw y;if(u>=ma)throw ga(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+ma.toString(16)+" bytes");let d=Buffer.concat(l,u);return ga(this),d};vd.inherits(vt,er.Inflate);function bd(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let r=t._finishFlushFlag;return r==null&&(r=er.Z_FINISH),t._processChunk(e,r)}function va(t,e){return bd(new vt(e),t)}ya.exports=Ir=va;Ir.Inflate=vt;Ir.createInflate=yd;Ir.inflateSync=va});var Hi=q((R0,Sa)=>{"use strict";var wa=Sa.exports=function(t){this._buffer=t,this._reads=[]};wa.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};wa.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)return new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)return new Error("unrecognised content at end of stream")}});var Ea=q(Ca=>{"use strict";var wd=Hi(),Sd=Ii();Ca.process=function(t,e){let r=[],s=new wd(t);return new Sd(e,{read:s.read.bind(s),write:function(o){r.push(o)},complete:function(){}}).start(),s.process(),Buffer.concat(r)}});var Aa=q((O0,Ta)=>{"use strict";var xa=!0,ka=se("zlib"),Cd=ba();ka.deflateSync||(xa=!1);var Ed=Hi(),xd=Ea(),kd=Bi(),Td=Oi(),Ad=Di();Ta.exports=function(t,e){if(!xa)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r;function s(m){r=m}let i;function o(m){i=m}function a(m){i.transColor=m}function n(m){i.palette=m}function l(){i.alpha=!0}let u;function y(m){u=m}let h=[];function _(m){h.push(m)}let d=new Ed(t);if(new kd(e,{read:d.read.bind(d),error:s,metadata:o,gamma:y,palette:n,transColor:a,inflateData:_,simpleTransparency:l}).start(),d.process(),r)throw r;let b=Buffer.concat(h);h.length=0;let c;if(i.interlace)c=ka.inflateSync(b);else{let w=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;c=Cd(b,{chunkSize:w,maxLength:w})}if(b=null,!c||!c.length)throw new Error("bad png - invalid inflate data response");let v=xd.process(c,i);b=null;let g=Td.dataToBitMap(v,i);v=null;let f=Ad(g,i);return i.data=f,i.gamma=u||0,i}});var Ra=q((D0,La)=>{"use strict";var Ia=!0,Pa=se("zlib");Pa.deflateSync||(Ia=!1);var Id=Qt(),Pd=Ni();La.exports=function(t,e){if(!Ia)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=e||{},s=new Pd(r),i=[];i.push(Buffer.from(Id.PNG_SIGNATURE)),i.push(s.packIHDR(t.width,t.height)),t.gamma&&i.push(s.packGAMA(t.gamma));let o=s.filterData(t.data,t.width,t.height),a=Pa.deflateSync(o,s.getDeflateOptions());if(o=null,!a||!a.length)throw new Error("bad png - invalid compressed data response");return i.push(s.packIDAT(a)),i.push(s.packIEND()),Buffer.concat(i)}});var Ba=q(Ui=>{"use strict";var Ld=Aa(),Rd=Ra();Ui.read=function(t,e){return Ld(t,e||{})};Ui.write=function(t,e){return Rd(t,e)}});var Ma=q(Da=>{"use strict";var Bd=se("util"),Oa=se("stream"),Od=ia(),Dd=pa(),Md=Ba(),me=Da.PNG=function(t){Oa.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new Od(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new Dd(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};Bd.inherits(me,Oa);me.sync=Md;me.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};me.prototype.parse=function(t,e){if(e){let r,s;r=function(i){this.removeListener("error",s),this.data=i,e(null,this)}.bind(this),s=function(i){this.removeListener("parsed",r),e(i,null)}.bind(this),this.once("parsed",r),this.once("error",s)}return this.end(t),this};me.prototype.write=function(t){return this._parser.write(t),!0};me.prototype.end=function(t){this._parser.end(t)};me.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};me.prototype._gamma=function(t){this.gamma=t};me.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};me.bitblt=function(t,e,r,s,i,o,a,n){if(r|=0,s|=0,i|=0,o|=0,a|=0,n|=0,r>t.width||s>t.height||r+i>t.width||s+o>t.height)throw new Error("bitblt reading outside image");if(a>e.width||n>e.height||a+i>e.width||n+o>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<o;l++)t.data.copy(e.data,(n+l)*e.width+a<<2,(s+l)*t.width+r<<2,(s+l)*t.width+r+i<<2)};me.prototype.bitblt=function(t,e,r,s,i,o,a){return me.bitblt(this,t,e,r,s,i,o,a),this};me.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let r=0;r<t.width;r++){let s=t.width*e+r<<2;for(let i=0;i<3;i++){let o=t.data[s+i]/255;o=Math.pow(o,1/2.2/t.gamma),t.data[s+i]=Math.round(o*255)}}t.gamma=0}};me.prototype.adjustGamma=function(){me.adjustGamma(this)}});var Pr=q(yt=>{"use strict";function Na(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(s){return[s,s]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}yt.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,s=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:s,scale:s?4:i,margin:r,color:{dark:Na(e.color.dark||"#000000ff"),light:Na(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};yt.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};yt.getImageWidth=function(e,r){let s=yt.getScale(e,r);return Math.floor((e+r.margin*2)*s)};yt.qrToImageData=function(e,r,s){let i=r.modules.size,o=r.modules.data,a=yt.getScale(i,s),n=Math.floor((i+s.margin*2)*a),l=s.margin*a,u=[s.color.light,s.color.dark];for(let y=0;y<n;y++)for(let h=0;h<n;h++){let _=(y*n+h)*4,d=s.color.light;if(y>=l&&h>=l&&y<n-l&&h<n-l){let p=Math.floor((y-l)/a),b=Math.floor((h-l)/a);d=u[o[p*i+b]?1:0]}e[_++]=d.r,e[_++]=d.g,e[_++]=d.b,e[_]=d.a}}});var Ha=q(Oe=>{"use strict";var Nd=se("fs"),Hd=Ma().PNG,Fi=Pr();Oe.render=function(e,r){let s=Fi.getOptions(r),i=s.rendererOpts,o=Fi.getImageWidth(e.modules.size,s);i.width=o,i.height=o;let a=new Hd(i);return Fi.qrToImageData(a.data,e,s),a};Oe.renderToDataURL=function(e,r,s){typeof s>"u"&&(s=r,r=void 0),Oe.renderToBuffer(e,r,function(i,o){i&&s(i);let a="data:image/png;base64,";a+=o.toString("base64"),s(null,a)})};Oe.renderToBuffer=function(e,r,s){typeof s>"u"&&(s=r,r=void 0);let i=Oe.render(e,r),o=[];i.on("error",s),i.on("data",function(a){o.push(a)}),i.on("end",function(){s(null,Buffer.concat(o))}),i.pack()};Oe.renderToFile=function(e,r,s,i){typeof i>"u"&&(i=s,s=void 0);let o=!1,a=(...l)=>{o||(o=!0,i.apply(null,l))},n=Nd.createWriteStream(e);n.on("error",a),n.on("close",a),Oe.renderToFileStream(n,r,s)};Oe.renderToFileStream=function(e,r,s){Oe.render(r,s).pack().pipe(e)}});var Ua=q(os=>{"use strict";var Ud=Pr(),Fd={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},jd={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function Wd(t,e,r){return t&&e?r.BB:t&&!e?r.BW:!t&&e?r.WB:r.WW}os.render=function(t,e,r){let s=Ud.getOptions(e),i=Fd;(s.color.dark.hex==="#ffffff"||s.color.light.hex==="#000000")&&(i=jd);let o=t.modules.size,a=t.modules.data,n="",l=Array(o+s.margin*2+1).join(i.WW);l=Array(s.margin/2+1).join(l+`
10
+ `);let u=Array(s.margin+1).join(i.WW);n+=l;for(let y=0;y<o;y+=2){n+=u;for(let h=0;h<o;h++){let _=a[y*o+h],d=a[(y+1)*o+h];n+=Wd(_,d,i)}n+=u+`
11
+ `}return n+=l.slice(0,-1),typeof r=="function"&&r(null,n),n};os.renderToFile=function(e,r,s,i){typeof i>"u"&&(i=s,s=void 0);let o=se("fs"),a=os.render(r,s);o.writeFile(e,a,i)}});var ja=q(Fa=>{"use strict";Fa.render=function(t,e,r){let s=t.modules.size,i=t.modules.data,o="\x1B[40m \x1B[0m",a="\x1B[47m \x1B[0m",n="",l=Array(s+3).join(a),u=Array(2).join(a);n+=l+`
12
+ `;for(let y=0;y<s;++y){n+=a;for(let h=0;h<s;h++)n+=i[y*s+h]?o:a;n+=u+`
13
+ `}return n+=l+`
14
+ `,typeof r=="function"&&r(null,n),n}});var za=q($a=>{"use strict";var qd="\x1B[47m",$d="\x1B[40m",ji="\x1B[37m",Wi="\x1B[30m",bt="\x1B[0m",zd=qd+Wi,Vd=$d+ji,Gd=function(t,e,r){return{"00":bt+" "+t,"01":bt+e+"\u2584"+t,"02":bt+r+"\u2584"+t,10:bt+e+"\u2580"+t,11:" ",12:"\u2584",20:bt+r+"\u2580"+t,21:"\u2580",22:"\u2588"}},Wa=function(t,e,r,s){let i=e+1;if(r>=i||s>=i||s<-1||r<-1)return"0";if(r>=e||s>=e||s<0||r<0)return"1";let o=s*e+r;return t[o]?"2":"1"},qa=function(t,e,r,s){return Wa(t,e,r,s)+Wa(t,e,r,s+1)};$a.render=function(t,e,r){let s=t.modules.size,i=t.modules.data,o=!!(e&&e.inverse),a=e&&e.inverse?Vd:zd,u=Gd(a,o?Wi:ji,o?ji:Wi),y=bt+`
15
+ `+a,h=a;for(let _=-1;_<s+1;_+=2){for(let d=-1;d<s;d++)h+=u[qa(i,s,d,_)];h+=u[qa(i,s,s,_)]+y}return h+=bt,typeof r=="function"&&r(null,h),h}});var Ga=q(Va=>{"use strict";var Yd=ja(),Jd=za();Va.render=function(t,e,r){return e&&e.small?Jd.render(t,e,r):Yd.render(t,e,r)}});var $i=q(Ja=>{"use strict";var Zd=Pr();function Ya(t,e){let r=t.a/255,s=e+'="'+t.hex+'"';return r<1?s+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':s}function qi(t,e,r){let s=t+e;return typeof r<"u"&&(s+=" "+r),s}function Kd(t,e,r){let s="",i=0,o=!1,a=0;for(let n=0;n<t.length;n++){let l=Math.floor(n%e),u=Math.floor(n/e);!l&&!o&&(o=!0),t[n]?(a++,n>0&&l>0&&t[n-1]||(s+=o?qi("M",l+r,.5+u+r):qi("m",i,0),i=0,o=!1),l+1<e&&t[n+1]||(s+=qi("h",a),a=0)):i++}return s}Ja.render=function(e,r,s){let i=Zd.getOptions(r),o=e.modules.size,a=e.modules.data,n=o+i.margin*2,l=i.color.light.a?"<path "+Ya(i.color.light,"fill")+' d="M0 0h'+n+"v"+n+'H0z"/>':"",u="<path "+Ya(i.color.dark,"stroke")+' d="'+Kd(a,o,i.margin)+'"/>',y='viewBox="0 0 '+n+" "+n+'"',_='<svg xmlns="http://www.w3.org/2000/svg" '+(i.width?'width="'+i.width+'" height="'+i.width+'" ':"")+y+' shape-rendering="crispEdges">'+l+u+`</svg>
16
+ `;return typeof s=="function"&&s(null,_),_}});var Za=q(as=>{"use strict";var Xd=$i();as.render=Xd.render;as.renderToFile=function(e,r,s,i){typeof i>"u"&&(i=s,s=void 0);let o=se("fs"),n='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+as.render(r,s);o.writeFile(e,n,i)}});var Ka=q(cs=>{"use strict";var zi=Pr();function Qd(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function ef(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}cs.render=function(e,r,s){let i=s,o=r;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),r||(o=ef()),i=zi.getOptions(i);let a=zi.getImageWidth(e.modules.size,i),n=o.getContext("2d"),l=n.createImageData(a,a);return zi.qrToImageData(l.data,e,i),Qd(n,o,a),n.putImageData(l,0,0),o};cs.renderToDataURL=function(e,r,s){let i=s;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),i||(i={});let o=cs.render(e,r,i),a=i.type||"image/png",n=i.rendererOpts||{};return o.toDataURL(a,n.quality)}});var Qa=q(Lr=>{"use strict";var tf=ni(),Vi=Ei(),Xa=Ka(),rf=$i();function Gi(t,e,r,s,i){let o=[].slice.call(arguments,1),a=o.length,n=typeof o[a-1]=="function";if(!n&&!tf())throw new Error("Callback required as last argument");if(n){if(a<2)throw new Error("Too few arguments provided");a===2?(i=r,r=e,e=s=void 0):a===3&&(e.getContext&&typeof i>"u"?(i=s,s=void 0):(i=s,s=r,r=e,e=void 0))}else{if(a<1)throw new Error("Too few arguments provided");return a===1?(r=e,e=s=void 0):a===2&&!e.getContext&&(s=r,r=e,e=void 0),new Promise(function(l,u){try{let y=Vi.create(r,s);l(t(y,e,s))}catch(y){u(y)}})}try{let l=Vi.create(r,s);i(null,t(l,e,s))}catch(l){i(l)}}Lr.create=Vi.create;Lr.toCanvas=Gi.bind(null,Xa.render);Lr.toDataURL=Gi.bind(null,Xa.renderToDataURL);Lr.toString=Gi.bind(null,function(t,e,r){return rf.render(t,r)})});var sc=q(it=>{"use strict";var ec=ni(),Yi=Ei(),sf=Ha(),tc=Ua(),nf=Ga(),rc=Za();function Rr(t,e,r){if(typeof t>"u")throw new Error("String required as first argument");if(typeof r>"u"&&(r=e,e={}),typeof r!="function")if(ec())e=r||{},r=null;else throw new Error("Callback required as last argument");return{opts:e,cb:r}}function of(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function ls(t){switch(t){case"svg":return rc;case"txt":case"utf8":return tc;default:return sf}}function af(t){switch(t){case"svg":return rc;case"terminal":return nf;default:return tc}}function Br(t,e,r){if(!r.cb)return new Promise(function(s,i){try{let o=Yi.create(e,r.opts);return t(o,r.opts,function(a,n){return a?i(a):s(n)})}catch(o){i(o)}});try{let s=Yi.create(e,r.opts);return t(s,r.opts,r.cb)}catch(s){r.cb(s)}}it.create=Yi.create;it.toCanvas=Qa().toCanvas;it.toString=function(e,r,s){let i=Rr(e,r,s),o=i.opts?i.opts.type:void 0,a=af(o);return Br(a.render,e,i)};it.toDataURL=function(e,r,s){let i=Rr(e,r,s),o=ls(i.opts.type);return Br(o.renderToDataURL,e,i)};it.toBuffer=function(e,r,s){let i=Rr(e,r,s),o=ls(i.opts.type);return Br(o.renderToBuffer,e,i)};it.toFile=function(e,r,s,i){if(typeof e!="string"||!(typeof r=="string"||typeof r=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!ec())throw new Error("Too few arguments provided");let o=Rr(r,s,i),a=o.opts.type||of(e),l=ls(a).renderToFile.bind(null,e);return Br(l,r,o)};it.toFileStream=function(e,r,s){if(arguments.length<2)throw new Error("Too few arguments provided");let i=Rr(r,s,e.emit.bind(e,"error")),a=ls("png").renderToFileStream.bind(null,e);Br(a,r,i)}});var nc=q((J0,ic)=>{"use strict";ic.exports=sc()});var Ge=q((Fy,jc)=>{"use strict";var Uc=["nodebuffer","arraybuffer","fragments"],Fc=typeof Blob<"u";Fc&&Uc.push("blob");jc.exports={BINARY_TYPES:Uc,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Fc,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Wr=q((jy,As)=>{"use strict";var{EMPTY_BUFFER:L_}=Ge(),hn=Buffer[Symbol.species];function R_(t,e){if(t.length===0)return L_;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),s=0;for(let i=0;i<t.length;i++){let o=t[i];r.set(o,s),s+=o.length}return s<e?new hn(r.buffer,r.byteOffset,s):r}function Wc(t,e,r,s,i){for(let o=0;o<i;o++)r[s+o]=t[o]^e[o&3]}function qc(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function B_(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function un(t){if(un.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new hn(t):ArrayBuffer.isView(t)?e=new hn(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),un.readOnly=!1),e}As.exports={concat:R_,mask:Wc,toArrayBuffer:B_,toBuffer:un,unmask:qc};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=se("bufferutil");As.exports.mask=function(e,r,s,i,o){o<48?Wc(e,r,s,i,o):t.mask(e,r,s,i,o)},As.exports.unmask=function(e,r){e.length<32?qc(e,r):t.unmask(e,r)}}catch{}});var Vc=q((Wy,zc)=>{"use strict";var $c=Symbol("kDone"),dn=Symbol("kRun"),fn=class{constructor(e){this[$c]=()=>{this.pending--,this[dn]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[dn]()}[dn](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[$c])}}};zc.exports=fn});var _r=q((qy,Zc)=>{"use strict";var qr=se("zlib"),Gc=Wr(),O_=Vc(),{kStatusCode:Yc}=Ge(),D_=Buffer[Symbol.species],M_=Buffer.from([0,0,255,255]),Ps=Symbol("permessage-deflate"),Ye=Symbol("total-length"),fr=Symbol("callback"),dt=Symbol("buffers"),pr=Symbol("error"),Is,pn=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Is){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Is=new O_(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[fr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,s=e.find(i=>!(r.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>i.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(s.server_no_context_takeover=!0),r.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(s.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?s.client_max_window_bits=r.clientMaxWindowBits:(s.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(s=>{let i=r[s];if(i.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(i=i[0],s==="client_max_window_bits"){if(i!==!0){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${s}": ${i}`);i=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${i}`)}else if(s==="server_max_window_bits"){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${s}": ${i}`);i=o}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${i}`)}else throw new Error(`Unknown parameter "${s}"`);r[s]=i})}),e}decompress(e,r,s){Is.add(i=>{this._decompress(e,r,(o,a)=>{i(),s(o,a)})})}compress(e,r,s){Is.add(i=>{this._compress(e,r,(o,a)=>{i(),s(o,a)})})}_decompress(e,r,s){let i=this._isServer?"client":"server";if(!this._inflate){let o=`${i}_max_window_bits`,a=typeof this.params[o]!="number"?qr.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=qr.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[Ps]=this,this._inflate[Ye]=0,this._inflate[dt]=[],this._inflate.on("error",H_),this._inflate.on("data",Jc)}this._inflate[fr]=s,this._inflate.write(e),r&&this._inflate.write(M_),this._inflate.flush(()=>{let o=this._inflate[pr];if(o){this._inflate.close(),this._inflate=null,s(o);return}let a=Gc.concat(this._inflate[dt],this._inflate[Ye]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ye]=0,this._inflate[dt]=[],r&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),s(null,a)})}_compress(e,r,s){let i=this._isServer?"server":"client";if(!this._deflate){let o=`${i}_max_window_bits`,a=typeof this.params[o]!="number"?qr.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=qr.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[Ye]=0,this._deflate[dt]=[],this._deflate.on("data",N_)}this._deflate[fr]=s,this._deflate.write(e),this._deflate.flush(qr.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=Gc.concat(this._deflate[dt],this._deflate[Ye]);r&&(o=new D_(o.buffer,o.byteOffset,o.length-4)),this._deflate[fr]=null,this._deflate[Ye]=0,this._deflate[dt]=[],r&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),s(null,o)})}};Zc.exports=pn;function N_(t){this[dt].push(t),this[Ye]+=t.length}function Jc(t){if(this[Ye]+=t.length,this[Ps]._maxPayload<1||this[Ye]<=this[Ps]._maxPayload){this[dt].push(t);return}this[pr]=new RangeError("Max payload size exceeded"),this[pr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[pr][Yc]=1009,this.removeListener("data",Jc),this.reset()}function H_(t){if(this[Ps]._inflate=null,this[pr]){this[fr](this[pr]);return}t[Yc]=1007,this[fr](t)}});var mr=q(($y,Ls)=>{"use strict";var{isUtf8:Kc}=se("buffer"),{hasBlob:U_}=Ge(),F_=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function j_(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function _n(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function W_(t){return U_&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ls.exports={isBlob:W_,isValidStatusCode:j_,isValidUTF8:_n,tokenChars:F_};if(Kc)Ls.exports.isValidUTF8=function(t){return t.length<24?_n(t):Kc(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=se("utf-8-validate");Ls.exports.isValidUTF8=function(e){return e.length<32?_n(e):t(e)}}catch{}});var bn=q((zy,il)=>{"use strict";var{Writable:q_}=se("stream"),Xc=_r(),{BINARY_TYPES:$_,EMPTY_BUFFER:Qc,kStatusCode:z_,kWebSocket:V_}=Ge(),{concat:mn,toArrayBuffer:G_,unmask:Y_}=Wr(),{isValidStatusCode:J_,isValidUTF8:el}=mr(),Rs=Buffer[Symbol.species],xe=0,tl=1,rl=2,sl=3,gn=4,vn=5,Bs=6,yn=class extends q_{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||$_[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[V_]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=xe}_write(e,r,s){if(this._opcode===8&&this._state==xe)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let s=this._buffers[0];return this._buffers[0]=new Rs(s.buffer,s.byteOffset+e,s.length-e),new Rs(s.buffer,s.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let s=this._buffers[0],i=r.length-e;e>=s.length?r.set(this._buffers.shift(),i):(r.set(new Uint8Array(s.buffer,s.byteOffset,e),i),this._buffers[0]=new Rs(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case xe:this.getInfo(e);break;case tl:this.getPayloadLength16(e);break;case rl:this.getPayloadLength64(e);break;case sl:this.getMask();break;case gn:this.getData(e);break;case vn:case Bs:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let s=(r[0]&64)===64;if(s&&!this._extensions[Xc.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(s){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(s){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=tl:this._payloadLength===127?this._state=rl:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),s=r.readUInt32BE(0);if(s>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=s*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=sl:this._state=gn}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=gn}getData(e){let r=Qc;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Y_(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=vn,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[Xc.extensionName].decompress(e,this._fin,(i,o)=>{if(i)return r(i);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(a);return}this._fragments.push(o)}this.dataMessage(r),this._state===xe&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=xe;return}let r=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=mn(s,r):this._binaryType==="arraybuffer"?i=G_(mn(s,r)):this._binaryType==="blob"?i=new Blob(s):i=s,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=xe):(this._state=Bs,setImmediate(()=>{this.emit("message",i,!0),this._state=xe,this.startLoop(e)}))}else{let i=mn(s,r);if(!this._skipUTF8Validation&&!el(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===vn||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=xe):(this._state=Bs,setImmediate(()=>{this.emit("message",i,!1),this._state=xe,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Qc),this.end();else{let s=e.readUInt16BE(0);if(!J_(s)){let o=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(o);return}let i=new Rs(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!el(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(o);return}this._loop=!1,this.emit("conclude",s,i),this.end()}this._state=xe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=xe):(this._state=Bs,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=xe,this.startLoop(r)}))}createError(e,r,s,i,o){this._loop=!1,this._errored=!0;let a=new e(s?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(a,this.createError),a.code=o,a[z_]=i,a}};il.exports=yn});var Cn=q((Gy,al)=>{"use strict";var{Duplex:Vy}=se("stream"),{randomFillSync:Z_}=se("crypto"),nl=_r(),{EMPTY_BUFFER:K_,kWebSocket:X_,NOOP:Q_}=Ge(),{isBlob:gr,isValidStatusCode:em}=mr(),{mask:ol,toBuffer:Ft}=Wr(),ke=Symbol("kByteLength"),tm=Buffer.alloc(4),Os=8*1024,jt,vr=Os,Le=0,rm=1,sm=2,wn=class t{constructor(e,r,s){this._extensions=r||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Le,this.onerror=Q_,this[X_]=void 0}static frame(e,r){let s,i=!1,o=2,a=!1;r.mask&&(s=r.maskBuffer||tm,r.generateMask?r.generateMask(s):(vr===Os&&(jt===void 0&&(jt=Buffer.alloc(Os)),Z_(jt,0,Os),vr=0),s[0]=jt[vr++],s[1]=jt[vr++],s[2]=jt[vr++],s[3]=jt[vr++]),a=(s[0]|s[1]|s[2]|s[3])===0,o=6);let n;typeof e=="string"?(!r.mask||a)&&r[ke]!==void 0?n=r[ke]:(e=Buffer.from(e),n=e.length):(n=e.length,i=r.mask&&r.readOnly&&!a);let l=n;n>=65536?(o+=8,l=127):n>125&&(o+=2,l=126);let u=Buffer.allocUnsafe(i?n+o:o);return u[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(u[0]|=64),u[1]=l,l===126?u.writeUInt16BE(n,2):l===127&&(u[2]=u[3]=0,u.writeUIntBE(n,4,6)),r.mask?(u[1]|=128,u[o-4]=s[0],u[o-3]=s[1],u[o-2]=s[2],u[o-1]=s[3],a?[u,e]:i?(ol(e,s,u,o,n),[u]):(ol(e,s,e,0,n),[u,e])):[u,e]}close(e,r,s,i){let o;if(e===void 0)o=K_;else{if(typeof e!="number"||!em(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let n=Buffer.byteLength(r);if(n>123)throw new RangeError("The message must not be greater than 123 bytes");o=Buffer.allocUnsafe(2+n),o.writeUInt16BE(e,0),typeof r=="string"?o.write(r,2):o.set(r,2)}}let a={[ke]:o.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Le?this.enqueue([this.dispatch,o,!1,a,i]):this.sendFrame(t.frame(o,a),i)}ping(e,r,s){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):gr(e)?(i=e.size,o=!1):(e=Ft(e),i=e.length,o=Ft.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[ke]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};gr(e)?this._state!==Le?this.enqueue([this.getBlobData,e,!1,a,s]):this.getBlobData(e,!1,a,s):this._state!==Le?this.enqueue([this.dispatch,e,!1,a,s]):this.sendFrame(t.frame(e,a),s)}pong(e,r,s){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):gr(e)?(i=e.size,o=!1):(e=Ft(e),i=e.length,o=Ft.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[ke]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};gr(e)?this._state!==Le?this.enqueue([this.getBlobData,e,!1,a,s]):this.getBlobData(e,!1,a,s):this._state!==Le?this.enqueue([this.dispatch,e,!1,a,s]):this.sendFrame(t.frame(e,a),s)}send(e,r,s){let i=this._extensions[nl.extensionName],o=r.binary?2:1,a=r.compress,n,l;typeof e=="string"?(n=Buffer.byteLength(e),l=!1):gr(e)?(n=e.size,l=!1):(e=Ft(e),n=e.length,l=Ft.readOnly),this._firstFragment?(this._firstFragment=!1,a&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=n>=i._threshold),this._compress=a):(a=!1,o=0),r.fin&&(this._firstFragment=!0);let u={[ke]:n,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:l,rsv1:a};gr(e)?this._state!==Le?this.enqueue([this.getBlobData,e,this._compress,u,s]):this.getBlobData(e,this._compress,u,s):this._state!==Le?this.enqueue([this.dispatch,e,this._compress,u,s]):this.dispatch(e,this._compress,u,s)}getBlobData(e,r,s,i){this._bufferedBytes+=s[ke],this._state=sm,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let n=new Error("The socket was closed while the blob was being read");process.nextTick(Sn,this,n,i);return}this._bufferedBytes-=s[ke];let a=Ft(o);r?this.dispatch(a,r,s,i):(this._state=Le,this.sendFrame(t.frame(a,s),i),this.dequeue())}).catch(o=>{process.nextTick(im,this,o,i)})}dispatch(e,r,s,i){if(!r){this.sendFrame(t.frame(e,s),i);return}let o=this._extensions[nl.extensionName];this._bufferedBytes+=s[ke],this._state=rm,o.compress(e,s.fin,(a,n)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Sn(this,l,i);return}this._bufferedBytes-=s[ke],this._state=Le,s.readOnly=!1,this.sendFrame(t.frame(n,s),i),this.dequeue()})}dequeue(){for(;this._state===Le&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ke],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ke],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};al.exports=wn;function Sn(t,e,r){typeof r=="function"&&r(e);for(let s=0;s<t._queue.length;s++){let i=t._queue[s],o=i[i.length-1];typeof o=="function"&&o(e)}}function im(t,e,r){Sn(t,e,r),t.onerror(e)}});var ml=q((Yy,_l)=>{"use strict";var{kForOnEventAttribute:$r,kListener:En}=Ge(),cl=Symbol("kCode"),ll=Symbol("kData"),hl=Symbol("kError"),ul=Symbol("kMessage"),dl=Symbol("kReason"),yr=Symbol("kTarget"),fl=Symbol("kType"),pl=Symbol("kWasClean"),Je=class{constructor(e){this[yr]=null,this[fl]=e}get target(){return this[yr]}get type(){return this[fl]}};Object.defineProperty(Je.prototype,"target",{enumerable:!0});Object.defineProperty(Je.prototype,"type",{enumerable:!0});var Wt=class extends Je{constructor(e,r={}){super(e),this[cl]=r.code===void 0?0:r.code,this[dl]=r.reason===void 0?"":r.reason,this[pl]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[cl]}get reason(){return this[dl]}get wasClean(){return this[pl]}};Object.defineProperty(Wt.prototype,"code",{enumerable:!0});Object.defineProperty(Wt.prototype,"reason",{enumerable:!0});Object.defineProperty(Wt.prototype,"wasClean",{enumerable:!0});var br=class extends Je{constructor(e,r={}){super(e),this[hl]=r.error===void 0?null:r.error,this[ul]=r.message===void 0?"":r.message}get error(){return this[hl]}get message(){return this[ul]}};Object.defineProperty(br.prototype,"error",{enumerable:!0});Object.defineProperty(br.prototype,"message",{enumerable:!0});var zr=class extends Je{constructor(e,r={}){super(e),this[ll]=r.data===void 0?null:r.data}get data(){return this[ll]}};Object.defineProperty(zr.prototype,"data",{enumerable:!0});var nm={addEventListener(t,e,r={}){for(let i of this.listeners(t))if(!r[$r]&&i[En]===e&&!i[$r])return;let s;if(t==="message")s=function(o,a){let n=new zr("message",{data:a?o:o.toString()});n[yr]=this,Ds(e,this,n)};else if(t==="close")s=function(o,a){let n=new Wt("close",{code:o,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[yr]=this,Ds(e,this,n)};else if(t==="error")s=function(o){let a=new br("error",{error:o,message:o.message});a[yr]=this,Ds(e,this,a)};else if(t==="open")s=function(){let o=new Je("open");o[yr]=this,Ds(e,this,o)};else return;s[$r]=!!r[$r],s[En]=e,r.once?this.once(t,s):this.on(t,s)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[En]===e&&!r[$r]){this.removeListener(t,r);break}}};_l.exports={CloseEvent:Wt,ErrorEvent:br,Event:Je,EventTarget:nm,MessageEvent:zr};function Ds(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Ms=q((Jy,gl)=>{"use strict";var{tokenChars:Vr}=mr();function Ue(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function om(t){let e=Object.create(null),r=Object.create(null),s=!1,i=!1,o=!1,a,n,l=-1,u=-1,y=-1,h=0;for(;h<t.length;h++)if(u=t.charCodeAt(h),a===void 0)if(y===-1&&Vr[u]===1)l===-1&&(l=h);else if(h!==0&&(u===32||u===9))y===-1&&l!==-1&&(y=h);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);y===-1&&(y=h);let d=t.slice(l,y);u===44?(Ue(e,d,r),r=Object.create(null)):a=d,l=y=-1}else throw new SyntaxError(`Unexpected character at index ${h}`);else if(n===void 0)if(y===-1&&Vr[u]===1)l===-1&&(l=h);else if(u===32||u===9)y===-1&&l!==-1&&(y=h);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);y===-1&&(y=h),Ue(r,t.slice(l,y),!0),u===44&&(Ue(e,a,r),r=Object.create(null),a=void 0),l=y=-1}else if(u===61&&l!==-1&&y===-1)n=t.slice(l,h),l=y=-1;else throw new SyntaxError(`Unexpected character at index ${h}`);else if(i){if(Vr[u]!==1)throw new SyntaxError(`Unexpected character at index ${h}`);l===-1?l=h:s||(s=!0),i=!1}else if(o)if(Vr[u]===1)l===-1&&(l=h);else if(u===34&&l!==-1)o=!1,y=h;else if(u===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${h}`);else if(u===34&&t.charCodeAt(h-1)===61)o=!0;else if(y===-1&&Vr[u]===1)l===-1&&(l=h);else if(l!==-1&&(u===32||u===9))y===-1&&(y=h);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);y===-1&&(y=h);let d=t.slice(l,y);s&&(d=d.replace(/\\/g,""),s=!1),Ue(r,n,d),u===44&&(Ue(e,a,r),r=Object.create(null),a=void 0),n=void 0,l=y=-1}else throw new SyntaxError(`Unexpected character at index ${h}`);if(l===-1||o||u===32||u===9)throw new SyntaxError("Unexpected end of input");y===-1&&(y=h);let _=t.slice(l,y);return a===void 0?Ue(e,_,r):(n===void 0?Ue(r,_,!0):s?Ue(r,n,_.replace(/\\/g,"")):Ue(r,n,_),Ue(e,a,r)),e}function am(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(s=>[e].concat(Object.keys(s).map(i=>{let o=s[i];return Array.isArray(o)||(o=[o]),o.map(a=>a===!0?i:`${i}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}gl.exports={format:am,parse:om}});var Fs=q((Xy,Il)=>{"use strict";var cm=se("events"),lm=se("https"),hm=se("http"),bl=se("net"),um=se("tls"),{randomBytes:dm,createHash:fm}=se("crypto"),{Duplex:Zy,Readable:Ky}=se("stream"),{URL:xn}=se("url"),ft=_r(),pm=bn(),_m=Cn(),{isBlob:mm}=mr(),{BINARY_TYPES:vl,CLOSE_TIMEOUT:gm,EMPTY_BUFFER:Ns,GUID:vm,kForOnEventAttribute:kn,kListener:ym,kStatusCode:bm,kWebSocket:de,NOOP:wl}=Ge(),{EventTarget:{addEventListener:wm,removeEventListener:Sm}}=ml(),{format:Cm,parse:Em}=Ms(),{toBuffer:xm}=Wr(),Sl=Symbol("kAborted"),Tn=[8,13],Ze=["CONNECTING","OPEN","CLOSING","CLOSED"],km=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ce=class t extends cm{constructor(e,r,s){super(),this._binaryType=vl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ns,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(s=r,r=[]):r=[r]),Cl(this,e,r,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){vl.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,s){let i=new pm({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),o=new _m(e,this._extensions,s.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[de]=this,o[de]=this,e[de]=this,i.on("conclude",Im),i.on("drain",Pm),i.on("error",Lm),i.on("message",Rm),i.on("ping",Bm),i.on("pong",Om),o.onerror=Dm,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",kl),e.on("data",Us),e.on("end",Tl),e.on("error",Al),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ft.extensionName]&&this._extensions[ft.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ye(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),xl(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){An(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Ns,r,s)}pong(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){An(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Ns,r,s)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(s=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){An(this,e,s);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[ft.extensionName]||(i.compress=!1),this._sender.send(e||Ns,i,s)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ye(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(ce,"CONNECTING",{enumerable:!0,value:Ze.indexOf("CONNECTING")});Object.defineProperty(ce.prototype,"CONNECTING",{enumerable:!0,value:Ze.indexOf("CONNECTING")});Object.defineProperty(ce,"OPEN",{enumerable:!0,value:Ze.indexOf("OPEN")});Object.defineProperty(ce.prototype,"OPEN",{enumerable:!0,value:Ze.indexOf("OPEN")});Object.defineProperty(ce,"CLOSING",{enumerable:!0,value:Ze.indexOf("CLOSING")});Object.defineProperty(ce.prototype,"CLOSING",{enumerable:!0,value:Ze.indexOf("CLOSING")});Object.defineProperty(ce,"CLOSED",{enumerable:!0,value:Ze.indexOf("CLOSED")});Object.defineProperty(ce.prototype,"CLOSED",{enumerable:!0,value:Ze.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ce.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ce.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[kn])return e[ym];return null},set(e){for(let r of this.listeners(t))if(r[kn]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[kn]:!0})}})});ce.prototype.addEventListener=wm;ce.prototype.removeEventListener=Sm;Il.exports=ce;function Cl(t,e,r,s){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:gm,protocolVersion:Tn[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!Tn.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Tn.join(", ")})`);let o;if(e instanceof xn)o=e;else try{o=new xn(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let a=o.protocol==="wss:",n=o.protocol==="ws+unix:",l;if(o.protocol!=="ws:"&&!a&&!n?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:n&&!o.pathname?l="The URL's pathname is empty":o.hash&&(l="The URL contains a fragment identifier"),l){let b=new SyntaxError(l);if(t._redirects===0)throw b;Hs(t,b);return}let u=a?443:80,y=dm(16).toString("base64"),h=a?lm.request:hm.request,_=new Set,d;if(i.createConnection=i.createConnection||(a?Am:Tm),i.defaultPort=i.defaultPort||u,i.port=o.port||u,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":y,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(d=new ft({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=Cm({[ft.extensionName]:d.offer()})),r.length){for(let b of r){if(typeof b!="string"||!km.test(b)||_.has(b))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(b)}i.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),n){let b=i.path.split(":");i.socketPath=b[0],i.path=b[1]}let p;if(i.followRedirects){if(t._redirects===0){t._originalIpc=n,t._originalSecure=a,t._originalHostOrSocketPath=n?i.socketPath:o.host;let b=s&&s.headers;if(s={...s,headers:{}},b)for(let[c,v]of Object.entries(b))s.headers[c.toLowerCase()]=v}else if(t.listenerCount("redirect")===0){let b=n?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!b||t._originalSecure&&!a)&&(delete i.headers.authorization,delete i.headers.cookie,b||delete i.headers.host,i.auth=void 0)}i.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),p=t._req=h(i),t._redirects&&t.emit("redirect",t.url,p)}else p=t._req=h(i);i.timeout&&p.on("timeout",()=>{ye(t,p,"Opening handshake has timed out")}),p.on("error",b=>{p===null||p[Sl]||(p=t._req=null,Hs(t,b))}),p.on("response",b=>{let c=b.headers.location,v=b.statusCode;if(c&&i.followRedirects&&v>=300&&v<400){if(++t._redirects>i.maxRedirects){ye(t,p,"Maximum redirects exceeded");return}p.abort();let g;try{g=new xn(c,e)}catch{let m=new SyntaxError(`Invalid URL: ${c}`);Hs(t,m);return}Cl(t,g,r,s)}else t.emit("unexpected-response",p,b)||ye(t,p,`Unexpected server response: ${b.statusCode}`)}),p.on("upgrade",(b,c,v)=>{if(t.emit("upgrade",b),t.readyState!==ce.CONNECTING)return;p=t._req=null;let g=b.headers.upgrade;if(g===void 0||g.toLowerCase()!=="websocket"){ye(t,c,"Invalid Upgrade header");return}let f=fm("sha1").update(y+vm).digest("base64");if(b.headers["sec-websocket-accept"]!==f){ye(t,c,"Invalid Sec-WebSocket-Accept header");return}let m=b.headers["sec-websocket-protocol"],w;if(m!==void 0?_.size?_.has(m)||(w="Server sent an invalid subprotocol"):w="Server sent a subprotocol but none was requested":_.size&&(w="Server sent no subprotocol"),w){ye(t,c,w);return}m&&(t._protocol=m);let C=b.headers["sec-websocket-extensions"];if(C!==void 0){if(!d){ye(t,c,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let k;try{k=Em(C)}catch{ye(t,c,"Invalid Sec-WebSocket-Extensions header");return}let A=Object.keys(k);if(A.length!==1||A[0]!==ft.extensionName){ye(t,c,"Server indicated an extension that was not requested");return}try{d.accept(k[ft.extensionName])}catch{ye(t,c,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[ft.extensionName]=d}t.setSocket(c,v,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(p,t):p.end()}function Hs(t,e){t._readyState=ce.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Tm(t){return t.path=t.socketPath,bl.connect(t)}function Am(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=bl.isIP(t.host)?"":t.host),um.connect(t)}function ye(t,e,r){t._readyState=ce.CLOSING;let s=new Error(r);Error.captureStackTrace(s,ye),e.setHeader?(e[Sl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Hs,t,s)):(e.destroy(s),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function An(t,e,r){if(e){let s=mm(e)?e.size:xm(e).length;t._socket?t._sender._bufferedBytes+=s:t._bufferedAmount+=s}if(r){let s=new Error(`WebSocket is not open: readyState ${t.readyState} (${Ze[t.readyState]})`);process.nextTick(r,s)}}function Im(t,e){let r=this[de];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[de]!==void 0&&(r._socket.removeListener("data",Us),process.nextTick(El,r._socket),t===1005?r.close():r.close(t,e))}function Pm(){let t=this[de];t.isPaused||t._socket.resume()}function Lm(t){let e=this[de];e._socket[de]!==void 0&&(e._socket.removeListener("data",Us),process.nextTick(El,e._socket),e.close(t[bm])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function yl(){this[de].emitClose()}function Rm(t,e){this[de].emit("message",t,e)}function Bm(t){let e=this[de];e._autoPong&&e.pong(t,!this._isServer,wl),e.emit("ping",t)}function Om(t){this[de].emit("pong",t)}function El(t){t.resume()}function Dm(t){let e=this[de];e.readyState!==ce.CLOSED&&(e.readyState===ce.OPEN&&(e._readyState=ce.CLOSING,xl(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function xl(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function kl(){let t=this[de];if(this.removeListener("close",kl),this.removeListener("data",Us),this.removeListener("end",Tl),t._readyState=ce.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[de]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",yl),t._receiver.on("finish",yl))}function Us(t){this[de]._receiver.write(t)||this.pause()}function Tl(){let t=this[de];t._readyState=ce.CLOSING,t._receiver.end(),this.end()}function Al(){let t=this[de];this.removeListener("error",Al),this.on("error",wl),t&&(t._readyState=ce.CLOSING,this.destroy())}});var Bl=q((e1,Rl)=>{"use strict";var Qy=Fs(),{Duplex:Mm}=se("stream");function Pl(t){t.emit("close")}function Nm(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ll(t){this.removeListener("error",Ll),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Hm(t,e){let r=!0,s=new Mm({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,a){let n=!a&&s._readableState.objectMode?o.toString():o;s.push(n)||t.pause()}),t.once("error",function(o){s.destroyed||(r=!1,s.destroy(o))}),t.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(i,o){if(t.readyState===t.CLOSED){o(i),process.nextTick(Pl,s);return}let a=!1;t.once("error",function(l){a=!0,o(l)}),t.once("close",function(){a||o(i),process.nextTick(Pl,s)}),r&&t.terminate()},s._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){s._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),s._readableState.endEmitted&&s.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},s._read=function(){t.isPaused&&t.resume()},s._write=function(i,o,a){if(t.readyState===t.CONNECTING){t.once("open",function(){s._write(i,o,a)});return}t.send(i,a)},s.on("end",Nm),s.on("error",Ll),s}Rl.exports=Hm});var In=q((t1,Ol)=>{"use strict";var{tokenChars:Um}=mr();function Fm(t){let e=new Set,r=-1,s=-1,i=0;for(i;i<t.length;i++){let a=t.charCodeAt(i);if(s===-1&&Um[a]===1)r===-1&&(r=i);else if(i!==0&&(a===32||a===9))s===-1&&r!==-1&&(s=i);else if(a===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${i}`);s===-1&&(s=i);let n=t.slice(r,s);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);e.add(n),r=s=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(r===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(r,i);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}Ol.exports={parse:Fm}});var jl=q((s1,Fl)=>{"use strict";var jm=se("events"),js=se("http"),{Duplex:r1}=se("stream"),{createHash:Wm}=se("crypto"),Dl=Ms(),qt=_r(),qm=In(),$m=Fs(),{CLOSE_TIMEOUT:zm,GUID:Vm,kWebSocket:Gm}=Ge(),Ym=/^[+/0-9A-Za-z]{22}==$/,Ml=0,Nl=1,Ul=2,Pn=class extends jm{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:zm,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:$m,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=js.createServer((s,i)=>{let o=js.STATUS_CODES[426];i.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),i.end(o)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=Jm(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,o,a)=>{this.handleUpgrade(i,o,a,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ml}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Ul){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Gr,this);return}if(e&&this.once("close",e),this._state!==Nl)if(this._state=Nl,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Gr,this):process.nextTick(Gr,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Gr(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,s,i){r.on("error",Hl);let o=e.headers["sec-websocket-key"],a=e.headers.upgrade,n=+e.headers["sec-websocket-version"];if(e.method!=="GET"){$t(this,e,r,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){$t(this,e,r,400,"Invalid Upgrade header");return}if(o===void 0||!Ym.test(o)){$t(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(n!==13&&n!==8){$t(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Yr(r,400);return}let l=e.headers["sec-websocket-protocol"],u=new Set;if(l!==void 0)try{u=qm.parse(l)}catch{$t(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let y=e.headers["sec-websocket-extensions"],h={};if(this.options.perMessageDeflate&&y!==void 0){let _=new qt({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let d=Dl.parse(y);d[qt.extensionName]&&(_.accept(d[qt.extensionName]),h[qt.extensionName]=_)}catch{$t(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let _={origin:e.headers[`${n===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(_,(d,p,b,c)=>{if(!d)return Yr(r,p||401,b,c);this.completeUpgrade(h,o,u,e,r,s,i)});return}if(!this.options.verifyClient(_))return Yr(r,401)}this.completeUpgrade(h,o,u,e,r,s,i)}completeUpgrade(e,r,s,i,o,a,n){if(!o.readable||!o.writable)return o.destroy();if(o[Gm])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ml)return Yr(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Wm("sha1").update(r+Vm).digest("base64")}`],y=new this.options.WebSocket(null,void 0,this.options);if(s.size){let h=this.options.handleProtocols?this.options.handleProtocols(s,i):s.values().next().value;h&&(u.push(`Sec-WebSocket-Protocol: ${h}`),y._protocol=h)}if(e[qt.extensionName]){let h=e[qt.extensionName].params,_=Dl.format({[qt.extensionName]:[h]});u.push(`Sec-WebSocket-Extensions: ${_}`),y._extensions=e}this.emit("headers",u,i),o.write(u.concat(`\r
17
+ `).join(`\r
18
+ `)),o.removeListener("error",Hl),y.setSocket(o,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(y),y.on("close",()=>{this.clients.delete(y),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Gr,this)})),n(y,i)}};Fl.exports=Pn;function Jm(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let s of Object.keys(e))t.removeListener(s,e[s])}}function Gr(t){t._state=Ul,t.emit("close")}function Hl(){this.destroy()}function Yr(t,e,r,s){r=r||js.STATUS_CODES[e],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${js.STATUS_CODES[e]}\r
19
+ `+Object.keys(s).map(i=>`${i}: ${s[i]}`).join(`\r
20
+ `)+`\r
21
+ \r
22
+ `+r)}function $t(t,e,r,s,i,o){if(t.listenerCount("wsClientError")){let a=new Error(i);Error.captureStackTrace(a,$t),t.emit("wsClientError",a,r,e)}else Yr(r,s,i,o)}});var ph=q(fh=>{"use strict";(()=>{"use strict";var t={5639:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CircularList=void 0;let u=l(7150),y=l(802);class h extends u.Disposable{constructor(d){super(),this._maxLength=d,this.onDeleteEmitter=this._register(new y.Emitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new y.Emitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new y.Emitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(d){if(this._maxLength===d)return;let p=new Array(d);for(let b=0;b<Math.min(d,this.length);b++)p[b]=this._array[this._getCyclicIndex(b)];this._array=p,this._maxLength=d,this._startIndex=0}get length(){return this._length}set length(d){if(d>this._length)for(let p=this._length;p<d;p++)this._array[p]=void 0;this._length=d}get(d){return this._array[this._getCyclicIndex(d)]}set(d,p){this._array[this._getCyclicIndex(d)]=p}push(d){this._array[this._getCyclicIndex(this._length)]=d,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(d,p,...b){if(p){for(let c=d;c<this._length-p;c++)this._array[this._getCyclicIndex(c)]=this._array[this._getCyclicIndex(c+p)];this._length-=p,this.onDeleteEmitter.fire({index:d,amount:p})}for(let c=this._length-1;c>=d;c--)this._array[this._getCyclicIndex(c+b.length)]=this._array[this._getCyclicIndex(c)];for(let c=0;c<b.length;c++)this._array[this._getCyclicIndex(d+c)]=b[c];if(b.length&&this.onInsertEmitter.fire({index:d,amount:b.length}),this._length+b.length>this._maxLength){let c=this._length+b.length-this._maxLength;this._startIndex+=c,this._length=this._maxLength,this.onTrimEmitter.fire(c)}else this._length+=b.length}trimStart(d){d>this._length&&(d=this._length),this._startIndex+=d,this._length-=d,this.onTrimEmitter.fire(d)}shiftElements(d,p,b){if(!(p<=0)){if(d<0||d>=this._length)throw new Error("start argument out of range");if(d+b<0)throw new Error("Cannot shift elements in list beyond index 0");if(b>0){for(let v=p-1;v>=0;v--)this.set(d+v+b,this.get(d+v));let c=d+p+b-this._length;if(c>0)for(this._length+=c;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let c=0;c<p;c++)this.set(d+c+b,this.get(d+c))}}_getCyclicIndex(d){return(this._startIndex+d)%this._maxLength}}n.CircularList=h},7453:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.clone=function l(u,y=5){if(typeof u!="object")return u;let h=Array.isArray(u)?[]:{};for(let _ in u)h[_]=y<=1?u[_]:u[_]&&l(u[_],y-1);return h}},5777:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CoreTerminal=void 0;let u=l(6501),y=l(6025),h=l(7276),_=l(9640),d=l(56),p=l(4071),b=l(7792),c=l(6415),v=l(5746),g=l(5882),f=l(2486),m=l(3562),w=l(8811),C=l(802),k=l(7150),A=!1;class D extends k.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new C.Emitter),this._onScroll.event((L=>{this._onScrollApi?.fire(L.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(L){for(let R in L)this.optionsService.options[R]=L[R]}constructor(L){super(),this._windowsWrappingHeuristics=this._register(new k.MutableDisposable),this._onBinary=this._register(new C.Emitter),this.onBinary=this._onBinary.event,this._onData=this._register(new C.Emitter),this.onData=this._onData.event,this._onLineFeed=this._register(new C.Emitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new C.Emitter),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new C.Emitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new C.Emitter),this._instantiationService=new y.InstantiationService,this.optionsService=this._register(new d.OptionsService(L)),this._instantiationService.setService(u.IOptionsService,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(_.BufferService)),this._instantiationService.setService(u.IBufferService,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(h.LogService)),this._instantiationService.setService(u.ILogService,this._logService),this.coreService=this._register(this._instantiationService.createInstance(p.CoreService)),this._instantiationService.setService(u.ICoreService,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(b.CoreMouseService)),this._instantiationService.setService(u.ICoreMouseService,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(c.UnicodeService)),this._instantiationService.setService(u.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(v.CharsetService),this._instantiationService.setService(u.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(w.OscLinkService),this._instantiationService.setService(u.IOscLinkService,this._oscLinkService),this._inputHandler=this._register(new f.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(C.Event.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(C.Event.forward(this._bufferService.onResize,this._onResize)),this._register(C.Event.forward(this.coreService.onData,this._onData)),this._register(C.Event.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 m.WriteBuffer(((R,P)=>this._inputHandler.parse(R,P)))),this._register(C.Event.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(L,R){this._writeBuffer.write(L,R)}writeSync(L,R){this._logService.logLevel<=u.LogLevelEnum.WARN&&!A&&(this._logService.warn("writeSync is unreliable and will be removed soon."),A=!0),this._writeBuffer.writeSync(L,R)}input(L,R=!0){this.coreService.triggerDataEvent(L,R)}resize(L,R){isNaN(L)||isNaN(R)||(L=Math.max(L,_.MINIMUM_COLS),R=Math.max(R,_.MINIMUM_ROWS),this._bufferService.resize(L,R))}scroll(L,R=!1){this._bufferService.scroll(L,R)}scrollLines(L,R){this._bufferService.scrollLines(L,R)}scrollPages(L){this.scrollLines(L*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(L){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(L){let R=L-this._bufferService.buffer.ydisp;R!==0&&this.scrollLines(R)}registerEscHandler(L,R){return this._inputHandler.registerEscHandler(L,R)}registerDcsHandler(L,R){return this._inputHandler.registerDcsHandler(L,R)}registerCsiHandler(L,R){return this._inputHandler.registerCsiHandler(L,R)}registerOscHandler(L,R){return this._inputHandler.registerOscHandler(L,R)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let L=!1,R=this.optionsService.rawOptions.windowsPty;R&&R.buildNumber!==void 0&&R.buildNumber!==void 0?L=R.backend==="conpty"&&R.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(L=!0),L?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let L=[];L.push(this.onLineFeed(g.updateWindowsModeWrappedState.bind(null,this._bufferService))),L.push(this.registerCsiHandler({final:"H"},(()=>((0,g.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,k.toDisposable)((()=>{for(let R of L)R.dispose()}))}}}n.CoreTerminal=D},2486:function(a,n,l){var u=this&&this.__decorate||function(j,S,T,E){var x,M=arguments.length,N=M<3?S:E===null?E=Object.getOwnPropertyDescriptor(S,T):E;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(j,S,T,E);else for(var U=j.length-1;U>=0;U--)(x=j[U])&&(N=(M<3?x(N):M>3?x(S,T,N):x(S,T))||N);return M>3&&N&&Object.defineProperty(S,T,N),N},y=this&&this.__param||function(j,S){return function(T,E){S(T,E,j)}};Object.defineProperty(n,"__esModule",{value:!0}),n.InputHandler=n.WindowsOptionsReportType=void 0,n.isValidColorIndex=Y;let h=l(3534),_=l(6760),d=l(6717),p=l(7150),b=l(726),c=l(6107),v=l(8938),g=l(3055),f=l(5451),m=l(6501),w=l(6415),C=l(1346),k=l(9823),A=l(8693),D=l(802),O={"(":0,")":1,"*":2,"+":3,"-":1,".":2},L=131072;function R(j,S){if(j>24)return S.setWinLines||!1;switch(j){case 1:return!!S.restoreWin;case 2:return!!S.minimizeWin;case 3:return!!S.setWinPosition;case 4:return!!S.setWinSizePixels;case 5:return!!S.raiseWin;case 6:return!!S.lowerWin;case 7:return!!S.refreshWin;case 8:return!!S.setWinSizeChars;case 9:return!!S.maximizeWin;case 10:return!!S.fullscreenWin;case 11:return!!S.getWinState;case 13:return!!S.getWinPosition;case 14:return!!S.getWinSizePixels;case 15:return!!S.getScreenSizePixels;case 16:return!!S.getCellSizePixels;case 18:return!!S.getWinSizeChars;case 19:return!!S.getScreenSizeChars;case 20:return!!S.getIconTitle;case 21:return!!S.getWinTitle;case 22:return!!S.pushTitle;case 23:return!!S.popTitle;case 24:return!!S.setWinLines}return!1}var P;(function(j){j[j.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",j[j.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(P||(n.WindowsOptionsReportType=P={}));let F=0;class V extends p.Disposable{getAttrData(){return this._curAttrData}constructor(S,T,E,x,M,N,U,z,ne=new d.EscapeSequenceParser){super(),this._bufferService=S,this._charsetService=T,this._coreService=E,this._logService=x,this._optionsService=M,this._oscLinkService=N,this._coreMouseService=U,this._unicodeService=z,this._parser=ne,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new b.StringToUtf32,this._utf8Decoder=new b.Utf8ToUtf32,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=c.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=c.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this._register(new D.Emitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new D.Emitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new D.Emitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new D.Emitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new D.Emitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new D.Emitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new D.Emitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new D.Emitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new D.Emitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new D.Emitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new D.Emitter),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new D.Emitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new D.Emitter),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 Z(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate((I=>this._activeBuffer=I.activeBuffer))),this._parser.setCsiHandlerFallback(((I,Q)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(I),params:Q.toArray()})})),this._parser.setEscHandlerFallback((I=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(I)})})),this._parser.setExecuteHandlerFallback((I=>{this._logService.debug("Unknown EXECUTE code: ",{code:I})})),this._parser.setOscHandlerFallback(((I,Q,J)=>{this._logService.debug("Unknown OSC code: ",{identifier:I,action:Q,data:J})})),this._parser.setDcsHandlerFallback(((I,Q,J)=>{Q==="HOOK"&&(J=J.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(I),action:Q,payload:J})})),this._parser.setPrintHandler(((I,Q,J)=>this.print(I,Q,J))),this._parser.registerCsiHandler({final:"@"},(I=>this.insertChars(I))),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(I=>this.scrollLeft(I))),this._parser.registerCsiHandler({final:"A"},(I=>this.cursorUp(I))),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(I=>this.scrollRight(I))),this._parser.registerCsiHandler({final:"B"},(I=>this.cursorDown(I))),this._parser.registerCsiHandler({final:"C"},(I=>this.cursorForward(I))),this._parser.registerCsiHandler({final:"D"},(I=>this.cursorBackward(I))),this._parser.registerCsiHandler({final:"E"},(I=>this.cursorNextLine(I))),this._parser.registerCsiHandler({final:"F"},(I=>this.cursorPrecedingLine(I))),this._parser.registerCsiHandler({final:"G"},(I=>this.cursorCharAbsolute(I))),this._parser.registerCsiHandler({final:"H"},(I=>this.cursorPosition(I))),this._parser.registerCsiHandler({final:"I"},(I=>this.cursorForwardTab(I))),this._parser.registerCsiHandler({final:"J"},(I=>this.eraseInDisplay(I,!1))),this._parser.registerCsiHandler({prefix:"?",final:"J"},(I=>this.eraseInDisplay(I,!0))),this._parser.registerCsiHandler({final:"K"},(I=>this.eraseInLine(I,!1))),this._parser.registerCsiHandler({prefix:"?",final:"K"},(I=>this.eraseInLine(I,!0))),this._parser.registerCsiHandler({final:"L"},(I=>this.insertLines(I))),this._parser.registerCsiHandler({final:"M"},(I=>this.deleteLines(I))),this._parser.registerCsiHandler({final:"P"},(I=>this.deleteChars(I))),this._parser.registerCsiHandler({final:"S"},(I=>this.scrollUp(I))),this._parser.registerCsiHandler({final:"T"},(I=>this.scrollDown(I))),this._parser.registerCsiHandler({final:"X"},(I=>this.eraseChars(I))),this._parser.registerCsiHandler({final:"Z"},(I=>this.cursorBackwardTab(I))),this._parser.registerCsiHandler({final:"`"},(I=>this.charPosAbsolute(I))),this._parser.registerCsiHandler({final:"a"},(I=>this.hPositionRelative(I))),this._parser.registerCsiHandler({final:"b"},(I=>this.repeatPrecedingCharacter(I))),this._parser.registerCsiHandler({final:"c"},(I=>this.sendDeviceAttributesPrimary(I))),this._parser.registerCsiHandler({prefix:">",final:"c"},(I=>this.sendDeviceAttributesSecondary(I))),this._parser.registerCsiHandler({final:"d"},(I=>this.linePosAbsolute(I))),this._parser.registerCsiHandler({final:"e"},(I=>this.vPositionRelative(I))),this._parser.registerCsiHandler({final:"f"},(I=>this.hVPosition(I))),this._parser.registerCsiHandler({final:"g"},(I=>this.tabClear(I))),this._parser.registerCsiHandler({final:"h"},(I=>this.setMode(I))),this._parser.registerCsiHandler({prefix:"?",final:"h"},(I=>this.setModePrivate(I))),this._parser.registerCsiHandler({final:"l"},(I=>this.resetMode(I))),this._parser.registerCsiHandler({prefix:"?",final:"l"},(I=>this.resetModePrivate(I))),this._parser.registerCsiHandler({final:"m"},(I=>this.charAttributes(I))),this._parser.registerCsiHandler({final:"n"},(I=>this.deviceStatus(I))),this._parser.registerCsiHandler({prefix:"?",final:"n"},(I=>this.deviceStatusPrivate(I))),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(I=>this.softReset(I))),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(I=>this.setCursorStyle(I))),this._parser.registerCsiHandler({final:"r"},(I=>this.setScrollRegion(I))),this._parser.registerCsiHandler({final:"s"},(I=>this.saveCursor(I))),this._parser.registerCsiHandler({final:"t"},(I=>this.windowOptions(I))),this._parser.registerCsiHandler({final:"u"},(I=>this.restoreCursor(I))),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(I=>this.insertColumns(I))),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(I=>this.deleteColumns(I))),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(I=>this.selectProtected(I))),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(I=>this.requestMode(I,!0))),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(I=>this.requestMode(I,!1))),this._parser.setExecuteHandler(h.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(h.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(h.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(h.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(h.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(h.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(h.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(h.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(h.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(h.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(h.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(h.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new C.OscHandler((I=>(this.setTitle(I),this.setIconName(I),!0)))),this._parser.registerOscHandler(1,new C.OscHandler((I=>this.setIconName(I)))),this._parser.registerOscHandler(2,new C.OscHandler((I=>this.setTitle(I)))),this._parser.registerOscHandler(4,new C.OscHandler((I=>this.setOrReportIndexedColor(I)))),this._parser.registerOscHandler(8,new C.OscHandler((I=>this.setHyperlink(I)))),this._parser.registerOscHandler(10,new C.OscHandler((I=>this.setOrReportFgColor(I)))),this._parser.registerOscHandler(11,new C.OscHandler((I=>this.setOrReportBgColor(I)))),this._parser.registerOscHandler(12,new C.OscHandler((I=>this.setOrReportCursorColor(I)))),this._parser.registerOscHandler(104,new C.OscHandler((I=>this.restoreIndexedColor(I)))),this._parser.registerOscHandler(110,new C.OscHandler((I=>this.restoreFgColor(I)))),this._parser.registerOscHandler(111,new C.OscHandler((I=>this.restoreBgColor(I)))),this._parser.registerOscHandler(112,new C.OscHandler((I=>this.restoreCursorColor(I)))),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 I in _.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:I},(()=>this.selectCharset("("+I))),this._parser.registerEscHandler({intermediates:")",final:I},(()=>this.selectCharset(")"+I))),this._parser.registerEscHandler({intermediates:"*",final:I},(()=>this.selectCharset("*"+I))),this._parser.registerEscHandler({intermediates:"+",final:I},(()=>this.selectCharset("+"+I))),this._parser.registerEscHandler({intermediates:"-",final:I},(()=>this.selectCharset("-"+I))),this._parser.registerEscHandler({intermediates:".",final:I},(()=>this.selectCharset("."+I))),this._parser.registerEscHandler({intermediates:"/",final:I},(()=>this.selectCharset("/"+I)));this._parser.registerEscHandler({intermediates:"#",final:"8"},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((I=>(this._logService.error("Parsing error: ",I),I))),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new k.DcsHandler(((I,Q)=>this.requestStatusString(I,Q))))}_preserveStack(S,T,E,x){this._parseStack.paused=!0,this._parseStack.cursorStartX=S,this._parseStack.cursorStartY=T,this._parseStack.decodedLength=E,this._parseStack.position=x}_logSlowResolvingAsync(S){this._logService.logLevel<=m.LogLevelEnum.WARN&&Promise.race([S,new Promise(((T,E)=>setTimeout((()=>E("#SLOW_TIMEOUT")),5e3)))]).catch((T=>{if(T!=="#SLOW_TIMEOUT")throw T;console.warn("async parser handler taking longer than 5000 ms")}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(S,T){let E,x=this._activeBuffer.x,M=this._activeBuffer.y,N=0,U=this._parseStack.paused;if(U){if(E=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,T))return this._logSlowResolvingAsync(E),E;x=this._parseStack.cursorStartX,M=this._parseStack.cursorStartY,this._parseStack.paused=!1,S.length>L&&(N=this._parseStack.position+L)}if(this._logService.logLevel<=m.LogLevelEnum.DEBUG&&this._logService.debug("parsing data "+(typeof S=="string"?` "${S}"`:` "${Array.prototype.map.call(S,(I=>String.fromCharCode(I))).join("")}"`)),this._logService.logLevel===m.LogLevelEnum.TRACE&&this._logService.trace("parsing data (codes)",typeof S=="string"?S.split("").map((I=>I.charCodeAt(0))):S),this._parseBuffer.length<S.length&&this._parseBuffer.length<L&&(this._parseBuffer=new Uint32Array(Math.min(S.length,L))),U||this._dirtyRowTracker.clearRange(),S.length>L)for(let I=N;I<S.length;I+=L){let Q=I+L<S.length?I+L:S.length,J=typeof S=="string"?this._stringDecoder.decode(S.substring(I,Q),this._parseBuffer):this._utf8Decoder.decode(S.subarray(I,Q),this._parseBuffer);if(E=this._parser.parse(this._parseBuffer,J))return this._preserveStack(x,M,J,I),this._logSlowResolvingAsync(E),E}else if(!U){let I=typeof S=="string"?this._stringDecoder.decode(S,this._parseBuffer):this._utf8Decoder.decode(S,this._parseBuffer);if(E=this._parser.parse(this._parseBuffer,I))return this._preserveStack(x,M,I,0),this._logSlowResolvingAsync(E),E}this._activeBuffer.x===x&&this._activeBuffer.y===M||this._onCursorMove.fire();let z=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),ne=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);ne<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(ne,this._bufferService.rows-1),end:Math.min(z,this._bufferService.rows-1)})}print(S,T,E){let x,M,N=this._charsetService.charset,U=this._optionsService.rawOptions.screenReaderMode,z=this._bufferService.cols,ne=this._coreService.decPrivateModes.wraparound,I=this._coreService.modes.insertMode,Q=this._curAttrData,J=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&E-T>0&&J.getWidth(this._activeBuffer.x-1)===2&&J.setCellFromCodepoint(this._activeBuffer.x-1,0,1,Q);let te=this._parser.precedingJoinState;for(let Te=T;Te<E;++Te){if(x=S[Te],x<127&&N){let pt=N[String.fromCharCode(x)];pt&&(x=pt.charCodeAt(0))}let Ae=this._unicodeService.charProperties(x,te);M=w.UnicodeService.extractWidth(Ae);let Vt=w.UnicodeService.extractShouldJoin(Ae),Fe=Vt?w.UnicodeService.extractWidth(te):0;if(te=Ae,U&&this._onA11yChar.fire((0,b.stringFromCodePoint)(x)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+M-Fe>z){if(ne){let pt=J,wr=this._activeBuffer.x-Fe;for(this._activeBuffer.x=Fe,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),J=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),Fe>0&&J instanceof c.BufferLine&&J.copyCellsFrom(pt,wr,0,Fe,!1);wr<z;)pt.setCellFromCodepoint(wr++,0,1,Q)}else if(this._activeBuffer.x=z-1,M===2)continue}if(Vt&&this._activeBuffer.x){let pt=J.getWidth(this._activeBuffer.x-1)?1:2;J.addCodepointToCell(this._activeBuffer.x-pt,x,M);for(let wr=M-Fe;--wr>=0;)J.setCellFromCodepoint(this._activeBuffer.x++,0,0,Q)}else if(I&&(J.insertCells(this._activeBuffer.x,M-Fe,this._activeBuffer.getNullCell(Q)),J.getWidth(z-1)===2&&J.setCellFromCodepoint(z-1,v.NULL_CELL_CODE,v.NULL_CELL_WIDTH,Q)),J.setCellFromCodepoint(this._activeBuffer.x++,x,M,Q),M>0)for(;--M;)J.setCellFromCodepoint(this._activeBuffer.x++,0,0,Q)}this._parser.precedingJoinState=te,this._activeBuffer.x<z&&E-T>0&&J.getWidth(this._activeBuffer.x)===0&&!J.hasContent(this._activeBuffer.x)&&J.setCellFromCodepoint(this._activeBuffer.x,0,1,Q),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(S,T){return S.final!=="t"||S.prefix||S.intermediates?this._parser.registerCsiHandler(S,T):this._parser.registerCsiHandler(S,(E=>!R(E.params[0],this._optionsService.rawOptions.windowOptions)||T(E)))}registerDcsHandler(S,T){return this._parser.registerDcsHandler(S,new k.DcsHandler(T))}registerEscHandler(S,T){return this._parser.registerEscHandler(S,T)}registerOscHandler(S,T){return this._parser.registerOscHandler(S,new C.OscHandler(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(){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&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let S=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);S.hasWidth(this._activeBuffer.x)&&!S.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let S=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-S),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(S=this._bufferService.cols-1){this._activeBuffer.x=Math.min(S,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(S,T){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=S,this._activeBuffer.y=this._activeBuffer.scrollTop+T):(this._activeBuffer.x=S,this._activeBuffer.y=T),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(S,T){this._restrictCursor(),this._setCursor(this._activeBuffer.x+S,this._activeBuffer.y+T)}cursorUp(S){let T=this._activeBuffer.y-this._activeBuffer.scrollTop;return T>=0?this._moveCursor(0,-Math.min(T,S.params[0]||1)):this._moveCursor(0,-(S.params[0]||1)),!0}cursorDown(S){let T=this._activeBuffer.scrollBottom-this._activeBuffer.y;return T>=0?this._moveCursor(0,Math.min(T,S.params[0]||1)):this._moveCursor(0,S.params[0]||1),!0}cursorForward(S){return this._moveCursor(S.params[0]||1,0),!0}cursorBackward(S){return this._moveCursor(-(S.params[0]||1),0),!0}cursorNextLine(S){return this.cursorDown(S),this._activeBuffer.x=0,!0}cursorPrecedingLine(S){return this.cursorUp(S),this._activeBuffer.x=0,!0}cursorCharAbsolute(S){return this._setCursor((S.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(S){return this._setCursor(S.length>=2?(S.params[1]||1)-1:0,(S.params[0]||1)-1),!0}charPosAbsolute(S){return this._setCursor((S.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(S){return this._moveCursor(S.params[0]||1,0),!0}linePosAbsolute(S){return this._setCursor(this._activeBuffer.x,(S.params[0]||1)-1),!0}vPositionRelative(S){return this._moveCursor(0,S.params[0]||1),!0}hVPosition(S){return this.cursorPosition(S),!0}tabClear(S){let T=S.params[0];return T===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:T===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(S){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let T=S.params[0]||1;for(;T--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(S){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let T=S.params[0]||1;for(;T--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(S){let T=S.params[0];return T===1&&(this._curAttrData.bg|=536870912),T!==2&&T!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(S,T,E,x=!1,M=!1){let N=this._activeBuffer.lines.get(this._activeBuffer.ybase+S);N.replaceCells(T,E,this._activeBuffer.getNullCell(this._eraseAttrData()),M),x&&(N.isWrapped=!1)}_resetBufferLine(S,T=!1){let E=this._activeBuffer.lines.get(this._activeBuffer.ybase+S);E&&(E.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),T),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+S),E.isWrapped=!1)}eraseInDisplay(S,T=!1){let E;switch(this._restrictCursor(this._bufferService.cols),S.params[0]){case 0:for(E=this._activeBuffer.y,this._dirtyRowTracker.markDirty(E),this._eraseInBufferLine(E++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,T);E<this._bufferService.rows;E++)this._resetBufferLine(E,T);this._dirtyRowTracker.markDirty(E);break;case 1:for(E=this._activeBuffer.y,this._dirtyRowTracker.markDirty(E),this._eraseInBufferLine(E,0,this._activeBuffer.x+1,!0,T),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(E+1).isWrapped=!1);E--;)this._resetBufferLine(E,T);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(E=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,E-1);E--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+E)?.getTrimmedLength(););for(;E>=0;E--)this._bufferService.scroll(this._eraseAttrData())}else{for(E=this._bufferService.rows,this._dirtyRowTracker.markDirty(E-1);E--;)this._resetBufferLine(E,T);this._dirtyRowTracker.markDirty(0)}break;case 3:let x=this._activeBuffer.lines.length-this._bufferService.rows;x>0&&(this._activeBuffer.lines.trimStart(x),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-x,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-x,0),this._onScroll.fire(0))}return!0}eraseInLine(S,T=!1){switch(this._restrictCursor(this._bufferService.cols),S.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)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(S){this._restrictCursor();let T=S.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let E=this._activeBuffer.ybase+this._activeBuffer.y,x=this._bufferService.rows-1-this._activeBuffer.scrollBottom,M=this._bufferService.rows-1+this._activeBuffer.ybase-x+1;for(;T--;)this._activeBuffer.lines.splice(M-1,1),this._activeBuffer.lines.splice(E,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(S){this._restrictCursor();let T=S.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let E=this._activeBuffer.ybase+this._activeBuffer.y,x;for(x=this._bufferService.rows-1-this._activeBuffer.scrollBottom,x=this._bufferService.rows-1+this._activeBuffer.ybase-x;T--;)this._activeBuffer.lines.splice(E,1),this._activeBuffer.lines.splice(x,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(S){this._restrictCursor();let T=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return T&&(T.insertCells(this._activeBuffer.x,S.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(S){this._restrictCursor();let T=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return T&&(T.deleteCells(this._activeBuffer.x,S.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(S){let T=S.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(S){let T=S.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(c.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(S){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let T=S.params[0]||1;for(let E=this._activeBuffer.scrollTop;E<=this._activeBuffer.scrollBottom;++E){let x=this._activeBuffer.lines.get(this._activeBuffer.ybase+E);x.deleteCells(0,T,this._activeBuffer.getNullCell(this._eraseAttrData())),x.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(S){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let T=S.params[0]||1;for(let E=this._activeBuffer.scrollTop;E<=this._activeBuffer.scrollBottom;++E){let x=this._activeBuffer.lines.get(this._activeBuffer.ybase+E);x.insertCells(0,T,this._activeBuffer.getNullCell(this._eraseAttrData())),x.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(S){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let T=S.params[0]||1;for(let E=this._activeBuffer.scrollTop;E<=this._activeBuffer.scrollBottom;++E){let x=this._activeBuffer.lines.get(this._activeBuffer.ybase+E);x.insertCells(this._activeBuffer.x,T,this._activeBuffer.getNullCell(this._eraseAttrData())),x.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(S){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let T=S.params[0]||1;for(let E=this._activeBuffer.scrollTop;E<=this._activeBuffer.scrollBottom;++E){let x=this._activeBuffer.lines.get(this._activeBuffer.ybase+E);x.deleteCells(this._activeBuffer.x,T,this._activeBuffer.getNullCell(this._eraseAttrData())),x.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(S){this._restrictCursor();let T=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return T&&(T.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(S.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(S){let T=this._parser.precedingJoinState;if(!T)return!0;let E=S.params[0]||1,x=w.UnicodeService.extractWidth(T),M=this._activeBuffer.x-x,N=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(M),U=new Uint32Array(N.length*E),z=0;for(let I=0;I<N.length;){let Q=N.codePointAt(I)||0;U[z++]=Q,I+=Q>65535?2:1}let ne=z;for(let I=1;I<E;++I)U.copyWithin(ne,0,z),ne+=z;return this.print(U,0,ne),!0}sendDeviceAttributesPrimary(S){return S.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(h.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(h.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(S){return S.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(h.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(h.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(S.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(h.C0.ESC+"[>83;40003;0c")),!0}_is(S){return(this._optionsService.rawOptions.termName+"").indexOf(S)===0}setMode(S){for(let T=0;T<S.length;T++)switch(S.params[T]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(S){for(let T=0;T<S.length;T++)switch(S.params[T]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,_.DEFAULT_CHARSET),this._charsetService.setgCharset(1,_.DEFAULT_CHARSET),this._charsetService.setgCharset(2,_.DEFAULT_CHARSET),this._charsetService.setgCharset(3,_.DEFAULT_CHARSET);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}return!0}resetMode(S){for(let T=0;T<S.length;T++)switch(S.params[T]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(S){for(let T=0;T<S.length;T++)switch(S.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:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),S.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)}return!0}requestMode(S,T){let E=this._coreService.decPrivateModes,{activeProtocol:x,activeEncoding:M}=this._coreMouseService,N=this._coreService,{buffers:U,cols:z}=this._bufferService,{active:ne,alt:I}=U,Q=this._optionsService.rawOptions,J=Vt=>Vt?1:2,te=S.params[0];return Te=te,Ae=T?te===2?4:te===4?J(N.modes.insertMode):te===12?3:te===20?J(Q.convertEol):0:te===1?J(E.applicationCursorKeys):te===3?Q.windowOptions.setWinLines?z===80?2:z===132?1:0:0:te===6?J(E.origin):te===7?J(E.wraparound):te===8?3:te===9?J(x==="X10"):te===12?J(Q.cursorBlink):te===25?J(!N.isCursorHidden):te===45?J(E.reverseWraparound):te===66?J(E.applicationKeypad):te===67?4:te===1e3?J(x==="VT200"):te===1002?J(x==="DRAG"):te===1003?J(x==="ANY"):te===1004?J(E.sendFocus):te===1005?4:te===1006?J(M==="SGR"):te===1015?4:te===1016?J(M==="SGR_PIXELS"):te===1048?1:te===47||te===1047||te===1049?J(ne===I):te===2004?J(E.bracketedPasteMode):te===2026?J(E.synchronizedOutput):0,N.triggerDataEvent(`${h.C0.ESC}[${T?"":"?"}${Te};${Ae}$y`),!0;var Te,Ae}_updateAttrColor(S,T,E,x,M){return T===2?(S|=50331648,S&=-16777216,S|=f.AttributeData.fromColorRGB([E,x,M])):T===5&&(S&=-50331904,S|=33554432|255&E),S}_extractColor(S,T,E){let x=[0,0,-1,0,0,0],M=0,N=0;do{if(x[N+M]=S.params[T+N],S.hasSubParams(T+N)){let U=S.getSubParams(T+N),z=0;do x[1]===5&&(M=1),x[N+z+1+M]=U[z];while(++z<U.length&&z+N+1+M<x.length);break}if(x[1]===5&&N+M>=2||x[1]===2&&N+M>=5)break;x[1]&&(M=1)}while(++N+T<S.length&&N+M<x.length);for(let U=2;U<x.length;++U)x[U]===-1&&(x[U]=0);switch(x[0]){case 38:E.fg=this._updateAttrColor(E.fg,x[1],x[3],x[4],x[5]);break;case 48:E.bg=this._updateAttrColor(E.bg,x[1],x[3],x[4],x[5]);break;case 58:E.extended=E.extended.clone(),E.extended.underlineColor=this._updateAttrColor(E.extended.underlineColor,x[1],x[3],x[4],x[5])}return N}_processUnderline(S,T){T.extended=T.extended.clone(),(!~S||S>5)&&(S=1),T.extended.underlineStyle=S,T.fg|=268435456,S===0&&(T.fg&=-268435457),T.updateExtended()}_processSGR0(S){S.fg=c.DEFAULT_ATTR_DATA.fg,S.bg=c.DEFAULT_ATTR_DATA.bg,S.extended=S.extended.clone(),S.extended.underlineStyle=0,S.extended.underlineColor&=-67108864,S.updateExtended()}charAttributes(S){if(S.length===1&&S.params[0]===0)return this._processSGR0(this._curAttrData),!0;let T=S.length,E,x=this._curAttrData;for(let M=0;M<T;M++)E=S.params[M],E>=30&&E<=37?(x.fg&=-50331904,x.fg|=16777216|E-30):E>=40&&E<=47?(x.bg&=-50331904,x.bg|=16777216|E-40):E>=90&&E<=97?(x.fg&=-50331904,x.fg|=16777224|E-90):E>=100&&E<=107?(x.bg&=-50331904,x.bg|=16777224|E-100):E===0?this._processSGR0(x):E===1?x.fg|=134217728:E===3?x.bg|=67108864:E===4?(x.fg|=268435456,this._processUnderline(S.hasSubParams(M)?S.getSubParams(M)[0]:1,x)):E===5?x.fg|=536870912:E===7?x.fg|=67108864:E===8?x.fg|=1073741824:E===9?x.fg|=2147483648:E===2?x.bg|=134217728:E===21?this._processUnderline(2,x):E===22?(x.fg&=-134217729,x.bg&=-134217729):E===23?x.bg&=-67108865:E===24?(x.fg&=-268435457,this._processUnderline(0,x)):E===25?x.fg&=-536870913:E===27?x.fg&=-67108865:E===28?x.fg&=-1073741825:E===29?x.fg&=2147483647:E===39?(x.fg&=-67108864,x.fg|=16777215&c.DEFAULT_ATTR_DATA.fg):E===49?(x.bg&=-67108864,x.bg|=16777215&c.DEFAULT_ATTR_DATA.bg):E===38||E===48||E===58?M+=this._extractColor(S,M,x):E===53?x.bg|=1073741824:E===55?x.bg&=-1073741825:E===59?(x.extended=x.extended.clone(),x.extended.underlineColor=-1,x.updateExtended()):E===100?(x.fg&=-67108864,x.fg|=16777215&c.DEFAULT_ATTR_DATA.fg,x.bg&=-67108864,x.bg|=16777215&c.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",E);return!0}deviceStatus(S){switch(S.params[0]){case 5:this._coreService.triggerDataEvent(`${h.C0.ESC}[0n`);break;case 6:let T=this._activeBuffer.y+1,E=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${h.C0.ESC}[${T};${E}R`)}return!0}deviceStatusPrivate(S){if(S.params[0]===6){let T=this._activeBuffer.y+1,E=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${h.C0.ESC}[?${T};${E}R`)}return!0}softReset(S){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=c.DEFAULT_ATTR_DATA.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(S){let T=S.length===0?1:S.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"}let E=T%2==1;this._coreService.decPrivateModes.cursorBlink=E}return!0}setScrollRegion(S){let T=S.params[0]||1,E;return(S.length<2||(E=S.params[1])>this._bufferService.rows||E===0)&&(E=this._bufferService.rows),E>T&&(this._activeBuffer.scrollTop=T-1,this._activeBuffer.scrollBottom=E-1,this._setCursor(0,0)),!0}windowOptions(S){if(!R(S.params[0],this._optionsService.rawOptions.windowOptions))return!0;let T=S.length>1?S.params[1]:0;switch(S.params[0]){case 14:T!==2&&this._onRequestWindowsOptionsReport.fire(P.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(P.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${h.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:T!==0&&T!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),T!==0&&T!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&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())}return!0}saveCursor(S){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(S){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(S){return this._windowTitle=S,this._onTitleChange.fire(S),!0}setIconName(S){return this._iconName=S,!0}setOrReportIndexedColor(S){let T=[],E=S.split(";");for(;E.length>1;){let x=E.shift(),M=E.shift();if(/^\d+$/.exec(x)){let N=parseInt(x);if(Y(N))if(M==="?")T.push({type:0,index:N});else{let U=(0,A.parseColor)(M);U&&T.push({type:1,index:N,color:U})}}}return T.length&&this._onColor.fire(T),!0}setHyperlink(S){let T=S.indexOf(";");if(T===-1)return!0;let E=S.slice(0,T).trim(),x=S.slice(T+1);return x?this._createHyperlink(E,x):!E.trim()&&this._finishHyperlink()}_createHyperlink(S,T){this._getCurrentLinkId()&&this._finishHyperlink();let E=S.split(":"),x,M=E.findIndex((N=>N.startsWith("id=")));return M!==-1&&(x=E[M].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:x,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(S,T){let E=S.split(";");for(let x=0;x<E.length&&!(T>=this._specialColors.length);++x,++T)if(E[x]==="?")this._onColor.fire([{type:0,index:this._specialColors[T]}]);else{let M=(0,A.parseColor)(E[x]);M&&this._onColor.fire([{type:1,index:this._specialColors[T],color:M}])}return!0}setOrReportFgColor(S){return this._setOrReportSpecialColor(S,0)}setOrReportBgColor(S){return this._setOrReportSpecialColor(S,1)}setOrReportCursorColor(S){return this._setOrReportSpecialColor(S,2)}restoreIndexedColor(S){if(!S)return this._onColor.fire([{type:2}]),!0;let T=[],E=S.split(";");for(let x=0;x<E.length;++x)if(/^\d+$/.exec(E[x])){let M=parseInt(E[x]);Y(M)&&T.push({type:2,index:M})}return T.length&&this._onColor.fire(T),!0}restoreFgColor(S){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(S){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(S){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,_.DEFAULT_CHARSET),!0}selectCharset(S){return S.length!==2?(this.selectDefaultCharset(),!0):(S[0]==="/"||this._charsetService.setgCharset(O[S[0]],_.CHARSETS[S[1]]||_.DEFAULT_CHARSET),!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 S=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,S,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=c.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=c.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(S){return this._charsetService.setgLevel(S),!0}screenAlignmentPattern(){let S=new g.CellData;S.content=4194373,S.fg=this._curAttrData.fg,S.bg=this._curAttrData.bg,this._setCursor(0,0);for(let T=0;T<this._bufferService.rows;++T){let E=this._activeBuffer.ybase+this._activeBuffer.y+T,x=this._activeBuffer.lines.get(E);x&&(x.fill(S),x.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(S,T){let E=this._bufferService.buffer,x=this._optionsService.rawOptions;return(M=>(this._coreService.triggerDataEvent(`${h.C0.ESC}${M}${h.C0.ESC}\\`),!0))(S==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:S==='"p'?'P1$r61;1"p':S==="r"?`P1$r${E.scrollTop+1};${E.scrollBottom+1}r`:S==="m"?"P1$r0m":S===" q"?`P1$r${{block:2,underline:4,bar:6}[x.cursorStyle]-(x.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(S,T){this._dirtyRowTracker.markRangeDirty(S,T)}}n.InputHandler=V;let Z=class{constructor(j){this._bufferService=j,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(j){j<this.start?this.start=j:j>this.end&&(this.end=j)}markRangeDirty(j,S){j>S&&(F=j,j=S,S=F),j<this.start&&(this.start=j),S>this.end&&(this.end=S)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function Y(j){return 0<=j&&j<256}Z=u([y(0,m.IBufferService)],Z)},701:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.isChromeOS=n.isLinux=n.isWindows=n.isIphone=n.isIpad=n.isMac=n.isSafari=n.isLegacyEdge=n.isFirefox=n.isNode=void 0,n.getSafariVersion=function(){if(!n.isSafari)return 0;let y=l.match(/Version\/(\d+)/);return y===null||y.length<2?0:parseInt(y[1])},n.isNode=typeof process<"u"&&"title"in process;let l=n.isNode?"node":navigator.userAgent,u=n.isNode?"node":navigator.platform;n.isFirefox=l.includes("Firefox"),n.isLegacyEdge=l.includes("Edge"),n.isSafari=/^((?!chrome|android).)*safari/i.test(l),n.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(u),n.isIpad=u==="iPad",n.isIphone=u==="iPhone",n.isWindows=["Windows","Win16","Win32","WinCE"].includes(u),n.isLinux=u.indexOf("Linux")>=0,n.isChromeOS=/\bCrOS\b/.test(l)},6168:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DebouncedIdleTask=n.IdleTaskQueue=n.PriorityTaskQueue=void 0;let u=l(701);class y{constructor(){this._tasks=[],this._i=0}enqueue(d){this._tasks.push(d),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(d){this._idleCallback=void 0;let p=0,b=0,c=d.timeRemaining(),v=0;for(;this._i<this._tasks.length;){if(p=performance.now(),this._tasks[this._i]()||this._i++,p=Math.max(1,performance.now()-p),b=Math.max(p,b),v=d.timeRemaining(),1.5*b>v)return c-p<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(c-p))}ms`),void this._start();c=v}this.clear()}}class h extends y{_requestCallback(d){return setTimeout((()=>d(this._createDeadline(16))))}_cancelCallback(d){clearTimeout(d)}_createDeadline(d){let p=performance.now()+d;return{timeRemaining:()=>Math.max(0,p-performance.now())}}}n.PriorityTaskQueue=h,n.IdleTaskQueue=!u.isNode&&"requestIdleCallback"in window?class extends y{_requestCallback(_){return requestIdleCallback(_)}_cancelCallback(_){cancelIdleCallback(_)}}:h,n.DebouncedIdleTask=class{constructor(){this._queue=new n.IdleTaskQueue}set(_){this._queue.clear(),this._queue.enqueue(_)}flush(){this._queue.flush()}}},5882:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.updateWindowsModeWrappedState=function(y){let h=y.buffer.lines.get(y.buffer.ybase+y.buffer.y-1),_=h?.get(y.cols-1),d=y.buffer.lines.get(y.buffer.ybase+y.buffer.y);d&&_&&(d.isWrapped=_[u.CHAR_DATA_CODE_INDEX]!==u.NULL_CELL_CODE&&_[u.CHAR_DATA_CODE_INDEX]!==u.WHITESPACE_CELL_CODE)};let u=l(8938)},5451:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ExtendedAttrs=n.AttributeData=void 0;class l{constructor(){this.fg=0,this.bg=0,this.extended=new u}static toColorRGB(h){return[h>>>16&255,h>>>8&255,255&h]}static fromColorRGB(h){return(255&h[0])<<16|(255&h[1])<<8|255&h[2]}clone(){let h=new l;return h.fg=this.fg,h.bg=this.bg,h.extended=this.extended.clone(),h}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return!(50331648&~this.fg)}isBgRGB(){return!(50331648&~this.bg)}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return!(50331648&this.fg)}isBgDefault(){return!(50331648&this.bg)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&~this.extended.underlineColor):this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&this.extended.underlineColor):this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}n.AttributeData=l;class u{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(h){this._ext=h}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(h){this._ext&=-469762049,this._ext|=h<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(h){this._ext&=-67108864,this._ext|=67108863&h}get urlId(){return this._urlId}set urlId(h){this._urlId=h}get underlineVariantOffset(){let h=(3758096384&this._ext)>>29;return h<0?4294967288^h:h}set underlineVariantOffset(h){this._ext&=536870911,this._ext|=h<<29&3758096384}constructor(h=0,_=0){this._ext=0,this._urlId=0,this._ext=h,this._urlId=_}clone(){return new u(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}n.ExtendedAttrs=u},1073:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Buffer=n.MAX_BUFFER_SIZE=void 0;let u=l(5639),y=l(6168),h=l(5451),_=l(6107),d=l(732),p=l(3055),b=l(8938),c=l(8158),v=l(6760);n.MAX_BUFFER_SIZE=4294967295,n.Buffer=class{constructor(g,f,m){this._hasScrollback=g,this._optionsService=f,this._bufferService=m,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=_.DEFAULT_ATTR_DATA.clone(),this.savedCharset=v.DEFAULT_CHARSET,this.markers=[],this._nullCell=p.CellData.fromCharData([0,b.NULL_CELL_CHAR,b.NULL_CELL_WIDTH,b.NULL_CELL_CODE]),this._whitespaceCell=p.CellData.fromCharData([0,b.WHITESPACE_CELL_CHAR,b.WHITESPACE_CELL_WIDTH,b.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new y.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new u.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(g){return g?(this._nullCell.fg=g.fg,this._nullCell.bg=g.bg,this._nullCell.extended=g.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new h.ExtendedAttrs),this._nullCell}getWhitespaceCell(g){return g?(this._whitespaceCell.fg=g.fg,this._whitespaceCell.bg=g.bg,this._whitespaceCell.extended=g.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new h.ExtendedAttrs),this._whitespaceCell}getBlankLine(g,f){return new _.BufferLine(this._bufferService.cols,this.getNullCell(g),f)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let g=this.ybase+this.y-this.ydisp;return g>=0&&g<this._rows}_getCorrectBufferLength(g){if(!this._hasScrollback)return g;let f=g+this._optionsService.rawOptions.scrollback;return f>n.MAX_BUFFER_SIZE?n.MAX_BUFFER_SIZE:f}fillViewportRows(g){if(this.lines.length===0){g===void 0&&(g=_.DEFAULT_ATTR_DATA);let f=this._rows;for(;f--;)this.lines.push(this.getBlankLine(g))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new u.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(g,f){let m=this.getNullCell(_.DEFAULT_ATTR_DATA),w=0,C=this._getCorrectBufferLength(f);if(C>this.lines.maxLength&&(this.lines.maxLength=C),this.lines.length>0){if(this._cols<g)for(let A=0;A<this.lines.length;A++)w+=+this.lines.get(A).resize(g,m);let k=0;if(this._rows<f)for(let A=this._rows;A<f;A++)this.lines.length<f+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new _.BufferLine(g,m)):this.ybase>0&&this.lines.length<=this.ybase+this.y+k+1?(this.ybase--,k++,this.ydisp>0&&this.ydisp--):this.lines.push(new _.BufferLine(g,m)));else for(let A=this._rows;A>f;A--)this.lines.length>f+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(C<this.lines.maxLength){let A=this.lines.length-C;A>0&&(this.lines.trimStart(A),this.ybase=Math.max(this.ybase-A,0),this.ydisp=Math.max(this.ydisp-A,0),this.savedY=Math.max(this.savedY-A,0)),this.lines.maxLength=C}this.x=Math.min(this.x,g-1),this.y=Math.min(this.y,f-1),k&&(this.y+=k),this.savedX=Math.min(this.savedX,g-1),this.scrollTop=0}if(this.scrollBottom=f-1,this._isReflowEnabled&&(this._reflow(g,f),this._cols>g))for(let k=0;k<this.lines.length;k++)w+=+this.lines.get(k).resize(g,m);this._cols=g,this._rows=f,this._memoryCleanupQueue.clear(),w>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let g=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,g=!1);let f=0;for(;this._memoryCleanupPosition<this.lines.length;)if(f+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),f>100)return!0;return g}get _isReflowEnabled(){let g=this._optionsService.rawOptions.windowsPty;return g&&g.buildNumber?this._hasScrollback&&g.backend==="conpty"&&g.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(g,f){this._cols!==g&&(g>this._cols?this._reflowLarger(g,f):this._reflowSmaller(g,f))}_reflowLarger(g,f){let m=this._optionsService.rawOptions.reflowCursorLine,w=(0,d.reflowLargerGetLinesToRemove)(this.lines,this._cols,g,this.ybase+this.y,this.getNullCell(_.DEFAULT_ATTR_DATA),m);if(w.length>0){let C=(0,d.reflowLargerCreateNewLayout)(this.lines,w);(0,d.reflowLargerApplyNewLayout)(this.lines,C.layout),this._reflowLargerAdjustViewport(g,f,C.countRemoved)}}_reflowLargerAdjustViewport(g,f,m){let w=this.getNullCell(_.DEFAULT_ATTR_DATA),C=m;for(;C-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<f&&this.lines.push(new _.BufferLine(g,w))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-m,0)}_reflowSmaller(g,f){let m=this._optionsService.rawOptions.reflowCursorLine,w=this.getNullCell(_.DEFAULT_ATTR_DATA),C=[],k=0;for(let A=this.lines.length-1;A>=0;A--){let D=this.lines.get(A);if(!D||!D.isWrapped&&D.getTrimmedLength()<=g)continue;let O=[D];for(;D.isWrapped&&A>0;)D=this.lines.get(--A),O.unshift(D);if(!m){let E=this.ybase+this.y;if(E>=A&&E<A+O.length)continue}let L=O[O.length-1].getTrimmedLength(),R=(0,d.reflowSmallerGetNewLineLengths)(O,this._cols,g),P=R.length-O.length,F;F=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+P):Math.max(0,this.lines.length-this.lines.maxLength+P);let V=[];for(let E=0;E<P;E++){let x=this.getBlankLine(_.DEFAULT_ATTR_DATA,!0);V.push(x)}V.length>0&&(C.push({start:A+O.length+k,newLines:V}),k+=V.length),O.push(...V);let Z=R.length-1,Y=R[Z];Y===0&&(Z--,Y=R[Z]);let j=O.length-P-1,S=L;for(;j>=0;){let E=Math.min(S,Y);if(O[Z]===void 0)break;if(O[Z].copyCellsFrom(O[j],S-E,Y-E,E,!0),Y-=E,Y===0&&(Z--,Y=R[Z]),S-=E,S===0){j--;let x=Math.max(j,0);S=(0,d.getWrappedLineTrimmedLength)(O,x,this._cols)}}for(let E=0;E<O.length;E++)R[E]<g&&O[E].setCell(R[E],w);let T=P-F;for(;T-- >0;)this.ybase===0?this.y<f-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+k)-f&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+P,this.ybase+f-1)}if(C.length>0){let A=[],D=[];for(let Y=0;Y<this.lines.length;Y++)D.push(this.lines.get(Y));let O=this.lines.length,L=O-1,R=0,P=C[R];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+k);let F=0;for(let Y=Math.min(this.lines.maxLength-1,O+k-1);Y>=0;Y--)if(P&&P.start>L+F){for(let j=P.newLines.length-1;j>=0;j--)this.lines.set(Y--,P.newLines[j]);Y++,A.push({index:L+1,amount:P.newLines.length}),F+=P.newLines.length,P=C[++R]}else this.lines.set(Y,D[L--]);let V=0;for(let Y=A.length-1;Y>=0;Y--)A[Y].index+=V,this.lines.onInsertEmitter.fire(A[Y]),V+=A[Y].amount;let Z=Math.max(0,O+k-this.lines.maxLength);Z>0&&this.lines.onTrimEmitter.fire(Z)}}translateBufferLineToString(g,f,m=0,w){let C=this.lines.get(g);return C?C.translateToString(f,m,w):""}getWrappedRangeForLine(g){let f=g,m=g;for(;f>0&&this.lines.get(f).isWrapped;)f--;for(;m+1<this.lines.length&&this.lines.get(m+1).isWrapped;)m++;return{first:f,last:m}}setupTabStops(g){for(g!=null?this.tabs[g]||(g=this.prevStop(g)):(this.tabs={},g=0);g<this._cols;g+=this._optionsService.rawOptions.tabStopWidth)this.tabs[g]=!0}prevStop(g){for(g==null&&(g=this.x);!this.tabs[--g]&&g>0;);return g>=this._cols?this._cols-1:g<0?0:g}nextStop(g){for(g==null&&(g=this.x);!this.tabs[++g]&&g<this._cols;);return g>=this._cols?this._cols-1:g<0?0:g}clearMarkers(g){this._isClearing=!0;for(let f=0;f<this.markers.length;f++)this.markers[f].line===g&&(this.markers[f].dispose(),this.markers.splice(f--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let g=0;g<this.markers.length;g++)this.markers[g].dispose();this.markers.length=0,this._isClearing=!1}addMarker(g){let f=new c.Marker(g);return this.markers.push(f),f.register(this.lines.onTrim((m=>{f.line-=m,f.line<0&&f.dispose()}))),f.register(this.lines.onInsert((m=>{f.line>=m.index&&(f.line+=m.amount)}))),f.register(this.lines.onDelete((m=>{f.line>=m.index&&f.line<m.index+m.amount&&f.dispose(),f.line>m.index&&(f.line-=m.amount)}))),f.register(f.onDispose((()=>this._removeMarker(f)))),f}_removeMarker(g){this._isClearing||this.markers.splice(this.markers.indexOf(g),1)}}},6107:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferLine=n.DEFAULT_ATTR_DATA=void 0;let u=l(5451),y=l(3055),h=l(8938),_=l(726);n.DEFAULT_ATTR_DATA=Object.freeze(new u.AttributeData);let d=0;class p{constructor(c,v,g=!1){this.isWrapped=g,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*c);let f=v||y.CellData.fromCharData([0,h.NULL_CELL_CHAR,h.NULL_CELL_WIDTH,h.NULL_CELL_CODE]);for(let m=0;m<c;++m)this.setCell(m,f);this.length=c}get(c){let v=this._data[3*c+0],g=2097151&v;return[this._data[3*c+1],2097152&v?this._combined[c]:g?(0,_.stringFromCodePoint)(g):"",v>>22,2097152&v?this._combined[c].charCodeAt(this._combined[c].length-1):g]}set(c,v){this._data[3*c+1]=v[h.CHAR_DATA_ATTR_INDEX],v[h.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[c]=v[1],this._data[3*c+0]=2097152|c|v[h.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*c+0]=v[h.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|v[h.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(c){return this._data[3*c+0]>>22}hasWidth(c){return 12582912&this._data[3*c+0]}getFg(c){return this._data[3*c+1]}getBg(c){return this._data[3*c+2]}hasContent(c){return 4194303&this._data[3*c+0]}getCodePoint(c){let v=this._data[3*c+0];return 2097152&v?this._combined[c].charCodeAt(this._combined[c].length-1):2097151&v}isCombined(c){return 2097152&this._data[3*c+0]}getString(c){let v=this._data[3*c+0];return 2097152&v?this._combined[c]:2097151&v?(0,_.stringFromCodePoint)(2097151&v):""}isProtected(c){return 536870912&this._data[3*c+2]}loadCell(c,v){return d=3*c,v.content=this._data[d+0],v.fg=this._data[d+1],v.bg=this._data[d+2],2097152&v.content&&(v.combinedData=this._combined[c]),268435456&v.bg&&(v.extended=this._extendedAttrs[c]),v}setCell(c,v){2097152&v.content&&(this._combined[c]=v.combinedData),268435456&v.bg&&(this._extendedAttrs[c]=v.extended),this._data[3*c+0]=v.content,this._data[3*c+1]=v.fg,this._data[3*c+2]=v.bg}setCellFromCodepoint(c,v,g,f){268435456&f.bg&&(this._extendedAttrs[c]=f.extended),this._data[3*c+0]=v|g<<22,this._data[3*c+1]=f.fg,this._data[3*c+2]=f.bg}addCodepointToCell(c,v,g){let f=this._data[3*c+0];2097152&f?this._combined[c]+=(0,_.stringFromCodePoint)(v):2097151&f?(this._combined[c]=(0,_.stringFromCodePoint)(2097151&f)+(0,_.stringFromCodePoint)(v),f&=-2097152,f|=2097152):f=v|4194304,g&&(f&=-12582913,f|=g<<22),this._data[3*c+0]=f}insertCells(c,v,g){if((c%=this.length)&&this.getWidth(c-1)===2&&this.setCellFromCodepoint(c-1,0,1,g),v<this.length-c){let f=new y.CellData;for(let m=this.length-c-v-1;m>=0;--m)this.setCell(c+v+m,this.loadCell(c+m,f));for(let m=0;m<v;++m)this.setCell(c+m,g)}else for(let f=c;f<this.length;++f)this.setCell(f,g);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,g)}deleteCells(c,v,g){if(c%=this.length,v<this.length-c){let f=new y.CellData;for(let m=0;m<this.length-c-v;++m)this.setCell(c+m,this.loadCell(c+v+m,f));for(let m=this.length-v;m<this.length;++m)this.setCell(m,g)}else for(let f=c;f<this.length;++f)this.setCell(f,g);c&&this.getWidth(c-1)===2&&this.setCellFromCodepoint(c-1,0,1,g),this.getWidth(c)!==0||this.hasContent(c)||this.setCellFromCodepoint(c,0,1,g)}replaceCells(c,v,g,f=!1){if(f)for(c&&this.getWidth(c-1)===2&&!this.isProtected(c-1)&&this.setCellFromCodepoint(c-1,0,1,g),v<this.length&&this.getWidth(v-1)===2&&!this.isProtected(v)&&this.setCellFromCodepoint(v,0,1,g);c<v&&c<this.length;)this.isProtected(c)||this.setCell(c,g),c++;else for(c&&this.getWidth(c-1)===2&&this.setCellFromCodepoint(c-1,0,1,g),v<this.length&&this.getWidth(v-1)===2&&this.setCellFromCodepoint(v,0,1,g);c<v&&c<this.length;)this.setCell(c++,g)}resize(c,v){if(c===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let g=3*c;if(c>this.length){if(this._data.buffer.byteLength>=4*g)this._data=new Uint32Array(this._data.buffer,0,g);else{let f=new Uint32Array(g);f.set(this._data),this._data=f}for(let f=this.length;f<c;++f)this.setCell(f,v)}else{this._data=this._data.subarray(0,g);let f=Object.keys(this._combined);for(let w=0;w<f.length;w++){let C=parseInt(f[w],10);C>=c&&delete this._combined[C]}let m=Object.keys(this._extendedAttrs);for(let w=0;w<m.length;w++){let C=parseInt(m[w],10);C>=c&&delete this._extendedAttrs[C]}}return this.length=c,4*g*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let c=new Uint32Array(this._data.length);return c.set(this._data),this._data=c,1}return 0}fill(c,v=!1){if(v)for(let g=0;g<this.length;++g)this.isProtected(g)||this.setCell(g,c);else{this._combined={},this._extendedAttrs={};for(let g=0;g<this.length;++g)this.setCell(g,c)}}copyFrom(c){this.length!==c.length?this._data=new Uint32Array(c._data):this._data.set(c._data),this.length=c.length,this._combined={};for(let v in c._combined)this._combined[v]=c._combined[v];this._extendedAttrs={};for(let v in c._extendedAttrs)this._extendedAttrs[v]=c._extendedAttrs[v];this.isWrapped=c.isWrapped}clone(){let c=new p(0);c._data=new Uint32Array(this._data),c.length=this.length;for(let v in this._combined)c._combined[v]=this._combined[v];for(let v in this._extendedAttrs)c._extendedAttrs[v]=this._extendedAttrs[v];return c.isWrapped=this.isWrapped,c}getTrimmedLength(){for(let c=this.length-1;c>=0;--c)if(4194303&this._data[3*c+0])return c+(this._data[3*c+0]>>22);return 0}getNoBgTrimmedLength(){for(let c=this.length-1;c>=0;--c)if(4194303&this._data[3*c+0]||50331648&this._data[3*c+2])return c+(this._data[3*c+0]>>22);return 0}copyCellsFrom(c,v,g,f,m){let w=c._data;if(m)for(let k=f-1;k>=0;k--){for(let A=0;A<3;A++)this._data[3*(g+k)+A]=w[3*(v+k)+A];268435456&w[3*(v+k)+2]&&(this._extendedAttrs[g+k]=c._extendedAttrs[v+k])}else for(let k=0;k<f;k++){for(let A=0;A<3;A++)this._data[3*(g+k)+A]=w[3*(v+k)+A];268435456&w[3*(v+k)+2]&&(this._extendedAttrs[g+k]=c._extendedAttrs[v+k])}let C=Object.keys(c._combined);for(let k=0;k<C.length;k++){let A=parseInt(C[k],10);A>=v&&(this._combined[A-v+g]=c._combined[A])}}translateToString(c,v,g,f){v=v??0,g=g??this.length,c&&(g=Math.min(g,this.getTrimmedLength())),f&&(f.length=0);let m="";for(;v<g;){let w=this._data[3*v+0],C=2097151&w,k=2097152&w?this._combined[v]:C?(0,_.stringFromCodePoint)(C):h.WHITESPACE_CELL_CHAR;if(m+=k,f)for(let A=0;A<k.length;++A)f.push(v);v+=w>>22||1}return f&&f.push(v),m}}n.BufferLine=p},732:(a,n)=>{function l(u,y,h){if(y===u.length-1)return u[y].getTrimmedLength();let _=!u[y].hasContent(h-1)&&u[y].getWidth(h-1)===1,d=u[y+1].getWidth(0)===2;return _&&d?h-1:h}Object.defineProperty(n,"__esModule",{value:!0}),n.reflowLargerGetLinesToRemove=function(u,y,h,_,d,p){let b=[];for(let c=0;c<u.length-1;c++){let v=c,g=u.get(++v);if(!g.isWrapped)continue;let f=[u.get(c)];for(;v<u.length&&g.isWrapped;)f.push(g),g=u.get(++v);if(!p&&_>=c&&_<v){c+=f.length-1;continue}let m=0,w=l(f,m,y),C=1,k=0;for(;C<f.length;){let D=l(f,C,y),O=D-k,L=h-w,R=Math.min(O,L);f[m].copyCellsFrom(f[C],k,w,R,!1),w+=R,w===h&&(m++,w=0),k+=R,k===D&&(C++,k=0),w===0&&m!==0&&f[m-1].getWidth(h-1)===2&&(f[m].copyCellsFrom(f[m-1],h-1,w++,1,!1),f[m-1].setCell(h-1,d))}f[m].replaceCells(w,h,d);let A=0;for(let D=f.length-1;D>0&&(D>m||f[D].getTrimmedLength()===0);D--)A++;A>0&&(b.push(c+f.length-A),b.push(A)),c+=f.length-1}return b},n.reflowLargerCreateNewLayout=function(u,y){let h=[],_=0,d=y[_],p=0;for(let b=0;b<u.length;b++)if(d===b){let c=y[++_];u.onDeleteEmitter.fire({index:b-p,amount:c}),b+=c-1,p+=c,d=y[++_]}else h.push(b);return{layout:h,countRemoved:p}},n.reflowLargerApplyNewLayout=function(u,y){let h=[];for(let _=0;_<y.length;_++)h.push(u.get(y[_]));for(let _=0;_<h.length;_++)u.set(_,h[_]);u.length=y.length},n.reflowSmallerGetNewLineLengths=function(u,y,h){let _=[],d=u.map(((v,g)=>l(u,g,y))).reduce(((v,g)=>v+g)),p=0,b=0,c=0;for(;c<d;){if(d-c<h){_.push(d-c);break}p+=h;let v=l(u,b,y);p>v&&(p-=v,b++);let g=u[b].getWidth(p-1)===2;g&&p--;let f=g?h-1:h;_.push(f),c+=f}return _},n.getWrappedLineTrimmedLength=l},4097:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferSet=void 0;let u=l(7150),y=l(1073),h=l(802);class _ extends u.Disposable{constructor(p,b){super(),this._optionsService=p,this._bufferService=b,this._onBufferActivate=this._register(new h.Emitter),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 y.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new y.Buffer(!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(p){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(p),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(p,b){this._normal.resize(p,b),this._alt.resize(p,b),this.setupTabStops(p)}setupTabStops(p){this._normal.setupTabStops(p),this._alt.setupTabStops(p)}}n.BufferSet=_},3055:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CellData=void 0;let u=l(726),y=l(8938),h=l(5451);class _ extends h.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new h.ExtendedAttrs,this.combinedData=""}static fromCharData(p){let b=new _;return b.setFromCharData(p),b}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,u.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(p){this.fg=p[y.CHAR_DATA_ATTR_INDEX],this.bg=0;let b=!1;if(p[y.CHAR_DATA_CHAR_INDEX].length>2)b=!0;else if(p[y.CHAR_DATA_CHAR_INDEX].length===2){let c=p[y.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=c&&c<=56319){let v=p[y.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=v&&v<=57343?this.content=1024*(c-55296)+v-56320+65536|p[y.CHAR_DATA_WIDTH_INDEX]<<22:b=!0}else b=!0}else this.content=p[y.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|p[y.CHAR_DATA_WIDTH_INDEX]<<22;b&&(this.combinedData=p[y.CHAR_DATA_CHAR_INDEX],this.content=2097152|p[y.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}n.CellData=_},8938:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WHITESPACE_CELL_CODE=n.WHITESPACE_CELL_WIDTH=n.WHITESPACE_CELL_CHAR=n.NULL_CELL_CODE=n.NULL_CELL_WIDTH=n.NULL_CELL_CHAR=n.CHAR_DATA_CODE_INDEX=n.CHAR_DATA_WIDTH_INDEX=n.CHAR_DATA_CHAR_INDEX=n.CHAR_DATA_ATTR_INDEX=n.DEFAULT_EXT=n.DEFAULT_ATTR=n.DEFAULT_COLOR=void 0,n.DEFAULT_COLOR=0,n.DEFAULT_ATTR=n.DEFAULT_COLOR<<9|256,n.DEFAULT_EXT=0,n.CHAR_DATA_ATTR_INDEX=0,n.CHAR_DATA_CHAR_INDEX=1,n.CHAR_DATA_WIDTH_INDEX=2,n.CHAR_DATA_CODE_INDEX=3,n.NULL_CELL_CHAR="",n.NULL_CELL_WIDTH=1,n.NULL_CELL_CODE=0,n.WHITESPACE_CELL_CHAR=" ",n.WHITESPACE_CELL_WIDTH=1,n.WHITESPACE_CELL_CODE=32},8158:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Marker=void 0;let u=l(802),y=l(7150);class h{get id(){return this._id}constructor(d){this.line=d,this.isDisposed=!1,this._disposables=[],this._id=h._nextId++,this._onDispose=this.register(new u.Emitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,y.dispose)(this._disposables),this._disposables.length=0)}register(d){return this._disposables.push(d),d}}n.Marker=h,h._nextId=1},6760:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DEFAULT_CHARSET=n.CHARSETS=void 0,n.CHARSETS={},n.DEFAULT_CHARSET=n.CHARSETS.B,n.CHARSETS[0]={"`":"\u25C6",a:"\u2592",b:"\u2409",c:"\u240C",d:"\u240D",e:"\u240A",f:"\xB0",g:"\xB1",h:"\u2424",i:"\u240B",j:"\u2518",k:"\u2510",l:"\u250C",m:"\u2514",n:"\u253C",o:"\u23BA",p:"\u23BB",q:"\u2500",r:"\u23BC",s:"\u23BD",t:"\u251C",u:"\u2524",v:"\u2534",w:"\u252C",x:"\u2502",y:"\u2264",z:"\u2265","{":"\u03C0","|":"\u2260","}":"\xA3","~":"\xB7"},n.CHARSETS.A={"#":"\xA3"},n.CHARSETS.B=void 0,n.CHARSETS[4]={"#":"\xA3","@":"\xBE","[":"ij","\\":"\xBD","]":"|","{":"\xA8","|":"f","}":"\xBC","~":"\xB4"},n.CHARSETS.C=n.CHARSETS[5]={"[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"},n.CHARSETS.R={"#":"\xA3","@":"\xE0","[":"\xB0","\\":"\xE7","]":"\xA7","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xA8"},n.CHARSETS.Q={"@":"\xE0","[":"\xE2","\\":"\xE7","]":"\xEA","^":"\xEE","`":"\xF4","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xFB"},n.CHARSETS.K={"@":"\xA7","[":"\xC4","\\":"\xD6","]":"\xDC","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xDF"},n.CHARSETS.Y={"#":"\xA3","@":"\xA7","[":"\xB0","\\":"\xE7","]":"\xE9","`":"\xF9","{":"\xE0","|":"\xF2","}":"\xE8","~":"\xEC"},n.CHARSETS.E=n.CHARSETS[6]={"@":"\xC4","[":"\xC6","\\":"\xD8","]":"\xC5","^":"\xDC","`":"\xE4","{":"\xE6","|":"\xF8","}":"\xE5","~":"\xFC"},n.CHARSETS.Z={"#":"\xA3","@":"\xA7","[":"\xA1","\\":"\xD1","]":"\xBF","{":"\xB0","|":"\xF1","}":"\xE7"},n.CHARSETS.H=n.CHARSETS[7]={"@":"\xC9","[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"},n.CHARSETS["="]={"#":"\xF9","@":"\xE0","[":"\xE9","\\":"\xE7","]":"\xEA","^":"\xEE",_:"\xE8","`":"\xF4","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xFB"}},3534:(a,n)=>{var l,u,y;Object.defineProperty(n,"__esModule",{value:!0}),n.C1_ESCAPED=n.C1=n.C0=void 0,(function(h){h.NUL="\0",h.SOH="",h.STX="",h.ETX="",h.EOT="",h.ENQ="",h.ACK="",h.BEL="\x07",h.BS="\b",h.HT=" ",h.LF=`
23
+ `,h.VT="\v",h.FF="\f",h.CR="\r",h.SO="",h.SI="",h.DLE="",h.DC1="",h.DC2="",h.DC3="",h.DC4="",h.NAK="",h.SYN="",h.ETB="",h.CAN="",h.EM="",h.SUB="",h.ESC="\x1B",h.FS="",h.GS="",h.RS="",h.US="",h.SP=" ",h.DEL="\x7F"})(l||(n.C0=l={})),(function(h){h.PAD="\x80",h.HOP="\x81",h.BPH="\x82",h.NBH="\x83",h.IND="\x84",h.NEL="\x85",h.SSA="\x86",h.ESA="\x87",h.HTS="\x88",h.HTJ="\x89",h.VTS="\x8A",h.PLD="\x8B",h.PLU="\x8C",h.RI="\x8D",h.SS2="\x8E",h.SS3="\x8F",h.DCS="\x90",h.PU1="\x91",h.PU2="\x92",h.STS="\x93",h.CCH="\x94",h.MW="\x95",h.SPA="\x96",h.EPA="\x97",h.SOS="\x98",h.SGCI="\x99",h.SCI="\x9A",h.CSI="\x9B",h.ST="\x9C",h.OSC="\x9D",h.PM="\x9E",h.APC="\x9F"})(u||(n.C1=u={})),(function(h){h.ST=`${l.ESC}\\`})(y||(n.C1_ESCAPED=y={}))},726:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Utf8ToUtf32=n.StringToUtf32=void 0,n.stringFromCodePoint=function(l){return l>65535?(l-=65536,String.fromCharCode(55296+(l>>10))+String.fromCharCode(l%1024+56320)):String.fromCharCode(l)},n.utf32ToString=function(l,u=0,y=l.length){let h="";for(let _=u;_<y;++_){let d=l[_];d>65535?(d-=65536,h+=String.fromCharCode(55296+(d>>10))+String.fromCharCode(d%1024+56320)):h+=String.fromCharCode(d)}return h},n.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(l,u){let y=l.length;if(!y)return 0;let h=0,_=0;if(this._interim){let d=l.charCodeAt(_++);56320<=d&&d<=57343?u[h++]=1024*(this._interim-55296)+d-56320+65536:(u[h++]=this._interim,u[h++]=d),this._interim=0}for(let d=_;d<y;++d){let p=l.charCodeAt(d);if(55296<=p&&p<=56319){if(++d>=y)return this._interim=p,h;let b=l.charCodeAt(d);56320<=b&&b<=57343?u[h++]=1024*(p-55296)+b-56320+65536:(u[h++]=p,u[h++]=b)}else p!==65279&&(u[h++]=p)}return h}},n.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(l,u){let y=l.length;if(!y)return 0;let h,_,d,p,b=0,c=0,v=0;if(this.interim[0]){let m=!1,w=this.interim[0];w&=(224&w)==192?31:(240&w)==224?15:7;let C,k=0;for(;(C=63&this.interim[++k])&&k<4;)w<<=6,w|=C;let A=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,D=A-k;for(;v<D;){if(v>=y)return 0;if(C=l[v++],(192&C)!=128){v--,m=!0;break}this.interim[k++]=C,w<<=6,w|=63&C}m||(A===2?w<128?v--:u[b++]=w:A===3?w<2048||w>=55296&&w<=57343||w===65279||(u[b++]=w):w<65536||w>1114111||(u[b++]=w)),this.interim.fill(0)}let g=y-4,f=v;for(;f<y;){for(;!(!(f<g)||128&(h=l[f])||128&(_=l[f+1])||128&(d=l[f+2])||128&(p=l[f+3]));)u[b++]=h,u[b++]=_,u[b++]=d,u[b++]=p,f+=4;if(h=l[f++],h<128)u[b++]=h;else if((224&h)==192){if(f>=y)return this.interim[0]=h,b;if(_=l[f++],(192&_)!=128){f--;continue}if(c=(31&h)<<6|63&_,c<128){f--;continue}u[b++]=c}else if((240&h)==224){if(f>=y)return this.interim[0]=h,b;if(_=l[f++],(192&_)!=128){f--;continue}if(f>=y)return this.interim[0]=h,this.interim[1]=_,b;if(d=l[f++],(192&d)!=128){f--;continue}if(c=(15&h)<<12|(63&_)<<6|63&d,c<2048||c>=55296&&c<=57343||c===65279)continue;u[b++]=c}else if((248&h)==240){if(f>=y)return this.interim[0]=h,b;if(_=l[f++],(192&_)!=128){f--;continue}if(f>=y)return this.interim[0]=h,this.interim[1]=_,b;if(d=l[f++],(192&d)!=128){f--;continue}if(f>=y)return this.interim[0]=h,this.interim[1]=_,this.interim[2]=d,b;if(p=l[f++],(192&p)!=128){f--;continue}if(c=(7&h)<<18|(63&_)<<12|(63&d)<<6|63&p,c<65536||c>1114111)continue;u[b++]=c}}return b}}},7428:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeV6=void 0;let u=l(6415),y=[[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]],h=[[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]],_;n.UnicodeV6=class{constructor(){if(this.version="6",!_){_=new Uint8Array(65536),_.fill(1),_[0]=0,_.fill(0,1,32),_.fill(0,127,160),_.fill(2,4352,4448),_[9001]=2,_[9002]=2,_.fill(2,11904,42192),_[12351]=1,_.fill(2,44032,55204),_.fill(2,63744,64256),_.fill(2,65040,65050),_.fill(2,65072,65136),_.fill(2,65280,65377),_.fill(2,65504,65511);for(let d=0;d<y.length;++d)_.fill(0,y[d][0],y[d][1]+1)}}wcwidth(d){return d<32?0:d<127?1:d<65536?_[d]:(function(p,b){let c,v=0,g=b.length-1;if(p<b[0][0]||p>b[g][1])return!1;for(;g>=v;)if(c=v+g>>1,p>b[c][1])v=c+1;else{if(!(p<b[c][0]))return!0;g=c-1}return!1})(d,h)?0:d>=131072&&d<=196605||d>=196608&&d<=262141?2:1}charProperties(d,p){let b=this.wcwidth(d),c=b===0&&p!==0;if(c){let v=u.UnicodeService.extractWidth(p);v===0?c=!1:v>b&&(b=v)}return u.UnicodeService.createPropertyValue(0,b,c)}}},3562:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WriteBuffer=void 0;let u=l(7150),y=l(802);class h extends u.Disposable{constructor(d){super(),this._action=d,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new y.Emitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(d,p){if(p!==void 0&&this._syncCalls>p)return void(this._syncCalls=0);if(this._pendingData+=d.length,this._writeBuffer.push(d),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let b;for(this._isSyncWriting=!0;b=this._writeBuffer.shift();){this._action(b);let c=this._callbacks.shift();c&&c()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(d,p){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=d.length,this._writeBuffer.push(d),this._callbacks.push(p),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=d.length,this._writeBuffer.push(d),this._callbacks.push(p)}_innerWrite(d=0,p=!0){let b=d||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let c=this._writeBuffer[this._bufferOffset],v=this._action(c,p);if(v){let f=m=>performance.now()-b>=12?setTimeout((()=>this._innerWrite(0,m))):this._innerWrite(b,m);return void v.catch((m=>(queueMicrotask((()=>{throw m})),Promise.resolve(!1)))).then(f)}let g=this._callbacks[this._bufferOffset];if(g&&g(),this._bufferOffset++,this._pendingData-=c.length,performance.now()-b>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(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()}}n.WriteBuffer=h},8693:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseColor=function(h){if(!h)return;let _=h.toLowerCase();if(_.indexOf("rgb:")===0){_=_.slice(4);let d=l.exec(_);if(d){let p=d[1]?15:d[4]?255:d[7]?4095:65535;return[Math.round(parseInt(d[1]||d[4]||d[7]||d[10],16)/p*255),Math.round(parseInt(d[2]||d[5]||d[8]||d[11],16)/p*255),Math.round(parseInt(d[3]||d[6]||d[9]||d[12],16)/p*255)]}}else if(_.indexOf("#")===0&&(_=_.slice(1),u.exec(_)&&[3,6,9,12].includes(_.length))){let d=_.length/3,p=[0,0,0];for(let b=0;b<3;++b){let c=parseInt(_.slice(d*b,d*b+d),16);p[b]=d===1?c<<4:d===2?c:d===3?c>>4:c>>8}return p}},n.toRgbString=function(h,_=16){let[d,p,b]=h;return`rgb:${y(d,_)}/${y(p,_)}/${y(b,_)}`};let l=/^([\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})$/,u=/^[\da-f]+$/;function y(h,_){let d=h.toString(16),p=d.length<2?"0"+d:d;switch(_){case 4:return d[0];case 8:return p;case 12:return(p+p).slice(0,3);default:return p+p}}},1263:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.PAYLOAD_LIMIT=void 0,n.PAYLOAD_LIMIT=1e7},9823:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DcsHandler=n.DcsParser=void 0;let u=l(726),y=l(7262),h=l(1263),_=[];n.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=_,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=_}registerHandler(p,b){this._handlers[p]===void 0&&(this._handlers[p]=[]);let c=this._handlers[p];return c.push(b),{dispose:()=>{let v=c.indexOf(b);v!==-1&&c.splice(v,1)}}}clearHandler(p){this._handlers[p]&&delete this._handlers[p]}setHandlerFallback(p){this._handlerFb=p}reset(){if(this._active.length)for(let p=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;p>=0;--p)this._active[p].unhook(!1);this._stack.paused=!1,this._active=_,this._ident=0}hook(p,b){if(this.reset(),this._ident=p,this._active=this._handlers[p]||_,this._active.length)for(let c=this._active.length-1;c>=0;c--)this._active[c].hook(b);else this._handlerFb(this._ident,"HOOK",b)}put(p,b,c){if(this._active.length)for(let v=this._active.length-1;v>=0;v--)this._active[v].put(p,b,c);else this._handlerFb(this._ident,"PUT",(0,u.utf32ToString)(p,b,c))}unhook(p,b=!0){if(this._active.length){let c=!1,v=this._active.length-1,g=!1;if(this._stack.paused&&(v=this._stack.loopPosition-1,c=b,g=this._stack.fallThrough,this._stack.paused=!1),!g&&c===!1){for(;v>=0&&(c=this._active[v].unhook(p),c!==!0);v--)if(c instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=v,this._stack.fallThrough=!1,c;v--}for(;v>=0;v--)if(c=this._active[v].unhook(!1),c instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=v,this._stack.fallThrough=!0,c}else this._handlerFb(this._ident,"UNHOOK",p);this._active=_,this._ident=0}};let d=new y.Params;d.addParam(0),n.DcsHandler=class{constructor(p){this._handler=p,this._data="",this._params=d,this._hitLimit=!1}hook(p){this._params=p.length>1||p.params[0]?p.clone():d,this._data="",this._hitLimit=!1}put(p,b,c){this._hitLimit||(this._data+=(0,u.utf32ToString)(p,b,c),this._data.length>h.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(p){let b=!1;if(this._hitLimit)b=!1;else if(p&&(b=this._handler(this._data,this._params),b instanceof Promise))return b.then((c=>(this._params=d,this._data="",this._hitLimit=!1,c)));return this._params=d,this._data="",this._hitLimit=!1,b}}},6717:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.EscapeSequenceParser=n.VT500_TRANSITION_TABLE=n.TransitionTable=void 0;let u=l(7150),y=l(7262),h=l(1346),_=l(9823);class d{constructor(v){this.table=new Uint8Array(v)}setDefault(v,g){this.table.fill(v<<4|g)}add(v,g,f,m){this.table[g<<8|v]=f<<4|m}addMany(v,g,f,m){for(let w=0;w<v.length;w++)this.table[g<<8|v[w]]=f<<4|m}}n.TransitionTable=d;let p=160;n.VT500_TRANSITION_TABLE=(function(){let c=new d(4095),v=Array.apply(null,Array(256)).map(((k,A)=>A)),g=(k,A)=>v.slice(k,A),f=g(32,127),m=g(0,24);m.push(25),m.push.apply(m,g(28,32));let w=g(0,14),C;for(C in c.setDefault(1,0),c.addMany(f,0,2,0),w)c.addMany([24,26,153,154],C,3,0),c.addMany(g(128,144),C,3,0),c.addMany(g(144,152),C,3,0),c.add(156,C,0,0),c.add(27,C,11,1),c.add(157,C,4,8),c.addMany([152,158,159],C,0,7),c.add(155,C,11,3),c.add(144,C,11,9);return c.addMany(m,0,3,0),c.addMany(m,1,3,1),c.add(127,1,0,1),c.addMany(m,8,0,8),c.addMany(m,3,3,3),c.add(127,3,0,3),c.addMany(m,4,3,4),c.add(127,4,0,4),c.addMany(m,6,3,6),c.addMany(m,5,3,5),c.add(127,5,0,5),c.addMany(m,2,3,2),c.add(127,2,0,2),c.add(93,1,4,8),c.addMany(f,8,5,8),c.add(127,8,5,8),c.addMany([156,27,24,26,7],8,6,0),c.addMany(g(28,32),8,0,8),c.addMany([88,94,95],1,0,7),c.addMany(f,7,0,7),c.addMany(m,7,0,7),c.add(156,7,0,0),c.add(127,7,0,7),c.add(91,1,11,3),c.addMany(g(64,127),3,7,0),c.addMany(g(48,60),3,8,4),c.addMany([60,61,62,63],3,9,4),c.addMany(g(48,60),4,8,4),c.addMany(g(64,127),4,7,0),c.addMany([60,61,62,63],4,0,6),c.addMany(g(32,64),6,0,6),c.add(127,6,0,6),c.addMany(g(64,127),6,0,0),c.addMany(g(32,48),3,9,5),c.addMany(g(32,48),5,9,5),c.addMany(g(48,64),5,0,6),c.addMany(g(64,127),5,7,0),c.addMany(g(32,48),4,9,5),c.addMany(g(32,48),1,9,2),c.addMany(g(32,48),2,9,2),c.addMany(g(48,127),2,10,0),c.addMany(g(48,80),1,10,0),c.addMany(g(81,88),1,10,0),c.addMany([89,90,92],1,10,0),c.addMany(g(96,127),1,10,0),c.add(80,1,11,9),c.addMany(m,9,0,9),c.add(127,9,0,9),c.addMany(g(28,32),9,0,9),c.addMany(g(32,48),9,9,12),c.addMany(g(48,60),9,8,10),c.addMany([60,61,62,63],9,9,10),c.addMany(m,11,0,11),c.addMany(g(32,128),11,0,11),c.addMany(g(28,32),11,0,11),c.addMany(m,10,0,10),c.add(127,10,0,10),c.addMany(g(28,32),10,0,10),c.addMany(g(48,60),10,8,10),c.addMany([60,61,62,63],10,0,11),c.addMany(g(32,48),10,9,12),c.addMany(m,12,0,12),c.add(127,12,0,12),c.addMany(g(28,32),12,0,12),c.addMany(g(32,48),12,9,12),c.addMany(g(48,64),12,0,11),c.addMany(g(64,127),12,12,13),c.addMany(g(64,127),10,12,13),c.addMany(g(64,127),9,12,13),c.addMany(m,13,13,13),c.addMany(f,13,13,13),c.add(127,13,0,13),c.addMany([27,156,24,26],13,14,0),c.add(p,0,2,0),c.add(p,8,5,8),c.add(p,6,0,6),c.add(p,11,0,11),c.add(p,13,13,13),c})();class b extends u.Disposable{constructor(v=n.VT500_TRANSITION_TABLE){super(),this._transitions=v,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new y.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(g,f,m)=>{},this._executeHandlerFb=g=>{},this._csiHandlerFb=(g,f)=>{},this._escHandlerFb=g=>{},this._errorHandlerFb=g=>g,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register((0,u.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this._register(new h.OscParser),this._dcsParser=this._register(new _.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},(()=>!0))}_identifier(v,g=[64,126]){let f=0;if(v.prefix){if(v.prefix.length>1)throw new Error("only one byte as prefix supported");if(f=v.prefix.charCodeAt(0),f&&60>f||f>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(v.intermediates){if(v.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let w=0;w<v.intermediates.length;++w){let C=v.intermediates.charCodeAt(w);if(32>C||C>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");f<<=8,f|=C}}if(v.final.length!==1)throw new Error("final must be a single byte");let m=v.final.charCodeAt(0);if(g[0]>m||m>g[1])throw new Error(`final must be in range ${g[0]} .. ${g[1]}`);return f<<=8,f|=m,f}identToString(v){let g=[];for(;v;)g.push(String.fromCharCode(255&v)),v>>=8;return g.reverse().join("")}setPrintHandler(v){this._printHandler=v}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(v,g){let f=this._identifier(v,[48,126]);this._escHandlers[f]===void 0&&(this._escHandlers[f]=[]);let m=this._escHandlers[f];return m.push(g),{dispose:()=>{let w=m.indexOf(g);w!==-1&&m.splice(w,1)}}}clearEscHandler(v){this._escHandlers[this._identifier(v,[48,126])]&&delete this._escHandlers[this._identifier(v,[48,126])]}setEscHandlerFallback(v){this._escHandlerFb=v}setExecuteHandler(v,g){this._executeHandlers[v.charCodeAt(0)]=g}clearExecuteHandler(v){this._executeHandlers[v.charCodeAt(0)]&&delete this._executeHandlers[v.charCodeAt(0)]}setExecuteHandlerFallback(v){this._executeHandlerFb=v}registerCsiHandler(v,g){let f=this._identifier(v);this._csiHandlers[f]===void 0&&(this._csiHandlers[f]=[]);let m=this._csiHandlers[f];return m.push(g),{dispose:()=>{let w=m.indexOf(g);w!==-1&&m.splice(w,1)}}}clearCsiHandler(v){this._csiHandlers[this._identifier(v)]&&delete this._csiHandlers[this._identifier(v)]}setCsiHandlerFallback(v){this._csiHandlerFb=v}registerDcsHandler(v,g){return this._dcsParser.registerHandler(this._identifier(v),g)}clearDcsHandler(v){this._dcsParser.clearHandler(this._identifier(v))}setDcsHandlerFallback(v){this._dcsParser.setHandlerFallback(v)}registerOscHandler(v,g){return this._oscParser.registerHandler(v,g)}clearOscHandler(v){this._oscParser.clearHandler(v)}setOscHandlerFallback(v){this._oscParser.setHandlerFallback(v)}setErrorHandler(v){this._errorHandler=v}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(v,g,f,m,w){this._parseStack.state=v,this._parseStack.handlers=g,this._parseStack.handlerPos=f,this._parseStack.transition=m,this._parseStack.chunkPos=w}parse(v,g,f){let m,w=0,C=0,k=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,k=this._parseStack.chunkPos+1;else{if(f===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let A=this._parseStack.handlers,D=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(f===!1&&D>-1){for(;D>=0&&(m=A[D](this._params),m!==!0);D--)if(m instanceof Promise)return this._parseStack.handlerPos=D,m}this._parseStack.handlers=[];break;case 4:if(f===!1&&D>-1){for(;D>=0&&(m=A[D](),m!==!0);D--)if(m instanceof Promise)return this._parseStack.handlerPos=D,m}this._parseStack.handlers=[];break;case 6:if(w=v[this._parseStack.chunkPos],m=this._dcsParser.unhook(w!==24&&w!==26,f),m)return m;w===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(w=v[this._parseStack.chunkPos],m=this._oscParser.end(w!==24&&w!==26,f),m)return m;w===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,k=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let A=k;A<g;++A){switch(w=v[A],C=this._transitions.table[this.currentState<<8|(w<160?w:p)],C>>4){case 2:for(let P=A+1;;++P){if(P>=g||(w=v[P])<32||w>126&&w<p){this._printHandler(v,A,P),A=P-1;break}if(++P>=g||(w=v[P])<32||w>126&&w<p){this._printHandler(v,A,P),A=P-1;break}if(++P>=g||(w=v[P])<32||w>126&&w<p){this._printHandler(v,A,P),A=P-1;break}if(++P>=g||(w=v[P])<32||w>126&&w<p){this._printHandler(v,A,P),A=P-1;break}}break;case 3:this._executeHandlers[w]?this._executeHandlers[w]():this._executeHandlerFb(w),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:A,code:w,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let D=this._csiHandlers[this._collect<<8|w],O=D?D.length-1:-1;for(;O>=0&&(m=D[O](this._params),m!==!0);O--)if(m instanceof Promise)return this._preserveStack(3,D,O,C,A),m;O<0&&this._csiHandlerFb(this._collect<<8|w,this._params),this.precedingJoinState=0;break;case 8:do switch(w){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(w-48)}while(++A<g&&(w=v[A])>47&&w<60);A--;break;case 9:this._collect<<=8,this._collect|=w;break;case 10:let L=this._escHandlers[this._collect<<8|w],R=L?L.length-1:-1;for(;R>=0&&(m=L[R](),m!==!0);R--)if(m instanceof Promise)return this._preserveStack(4,L,R,C,A),m;R<0&&this._escHandlerFb(this._collect<<8|w),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|w,this._params);break;case 13:for(let P=A+1;;++P)if(P>=g||(w=v[P])===24||w===26||w===27||w>127&&w<p){this._dcsParser.put(v,A,P),A=P-1;break}break;case 14:if(m=this._dcsParser.unhook(w!==24&&w!==26),m)return this._preserveStack(6,[],0,C,A),m;w===27&&(C|=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 P=A+1;;P++)if(P>=g||(w=v[P])<32||w>127&&w<p){this._oscParser.put(v,A,P),A=P-1;break}break;case 6:if(m=this._oscParser.end(w!==24&&w!==26),m)return this._preserveStack(5,[],0,C,A),m;w===27&&(C|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&C}}}n.EscapeSequenceParser=b},1346:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.OscHandler=n.OscParser=void 0;let u=l(1263),y=l(726),h=[];n.OscParser=class{constructor(){this._state=0,this._active=h,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(_,d){this._handlers[_]===void 0&&(this._handlers[_]=[]);let p=this._handlers[_];return p.push(d),{dispose:()=>{let b=p.indexOf(d);b!==-1&&p.splice(b,1)}}}clearHandler(_){this._handlers[_]&&delete this._handlers[_]}setHandlerFallback(_){this._handlerFb=_}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=h}reset(){if(this._state===2)for(let _=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;_>=0;--_)this._active[_].end(!1);this._stack.paused=!1,this._active=h,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||h,this._active.length)for(let _=this._active.length-1;_>=0;_--)this._active[_].start();else this._handlerFb(this._id,"START")}_put(_,d,p){if(this._active.length)for(let b=this._active.length-1;b>=0;b--)this._active[b].put(_,d,p);else this._handlerFb(this._id,"PUT",(0,y.utf32ToString)(_,d,p))}start(){this.reset(),this._state=1}put(_,d,p){if(this._state!==3){if(this._state===1)for(;d<p;){let b=_[d++];if(b===59){this._state=2,this._start();break}if(b<48||57<b)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+b-48}this._state===2&&p-d>0&&this._put(_,d,p)}}end(_,d=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let p=!1,b=this._active.length-1,c=!1;if(this._stack.paused&&(b=this._stack.loopPosition-1,p=d,c=this._stack.fallThrough,this._stack.paused=!1),!c&&p===!1){for(;b>=0&&(p=this._active[b].end(_),p!==!0);b--)if(p instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=b,this._stack.fallThrough=!1,p;b--}for(;b>=0;b--)if(p=this._active[b].end(!1),p instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=b,this._stack.fallThrough=!0,p}else this._handlerFb(this._id,"END",_);this._active=h,this._id=-1,this._state=0}}},n.OscHandler=class{constructor(_){this._handler=_,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(_,d,p){this._hitLimit||(this._data+=(0,y.utf32ToString)(_,d,p),this._data.length>u.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(_){let d=!1;if(this._hitLimit)d=!1;else if(_&&(d=this._handler(this._data),d instanceof Promise))return d.then((p=>(this._data="",this._hitLimit=!1,p)));return this._data="",this._hitLimit=!1,d}}},7262:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Params=void 0;let l=2147483647;class u{static fromArray(h){let _=new u;if(!h.length)return _;for(let d=Array.isArray(h[0])?1:0;d<h.length;++d){let p=h[d];if(Array.isArray(p))for(let b=0;b<p.length;++b)_.addSubParam(p[b]);else _.addParam(p)}return _}constructor(h=32,_=32){if(this.maxLength=h,this.maxSubParamsLength=_,_>256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(h),this.length=0,this._subParams=new Int32Array(_),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(h),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){let h=new u(this.maxLength,this.maxSubParamsLength);return h.params.set(this.params),h.length=this.length,h._subParams.set(this._subParams),h._subParamsLength=this._subParamsLength,h._subParamsIdx.set(this._subParamsIdx),h._rejectDigits=this._rejectDigits,h._rejectSubDigits=this._rejectSubDigits,h._digitIsSub=this._digitIsSub,h}toArray(){let h=[];for(let _=0;_<this.length;++_){h.push(this.params[_]);let d=this._subParamsIdx[_]>>8,p=255&this._subParamsIdx[_];p-d>0&&h.push(Array.prototype.slice.call(this._subParams,d,p))}return h}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(h){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(h<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=h>l?l:h}}addSubParam(h){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(h<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=h>l?l:h,this._subParamsIdx[this.length-1]++}}hasSubParams(h){return(255&this._subParamsIdx[h])-(this._subParamsIdx[h]>>8)>0}getSubParams(h){let _=this._subParamsIdx[h]>>8,d=255&this._subParamsIdx[h];return d-_>0?this._subParams.subarray(_,d):null}getSubParamsAll(){let h={};for(let _=0;_<this.length;++_){let d=this._subParamsIdx[_]>>8,p=255&this._subParamsIdx[_];p-d>0&&(h[_]=this._subParams.slice(d,p))}return h}addDigit(h){let _;if(this._rejectDigits||!(_=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let d=this._digitIsSub?this._subParams:this.params,p=d[_-1];d[_-1]=~p?Math.min(10*p+h,l):h}}n.Params=u},3027:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.AddonManager=void 0,n.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let l=this._addons.length-1;l>=0;l--)this._addons[l].instance.dispose()}loadAddon(l,u){let y={instance:u,dispose:u.dispose,isDisposed:!1};this._addons.push(y),u.dispose=()=>this._wrappedAddonDispose(y),u.activate(l)}_wrappedAddonDispose(l){if(l.isDisposed)return;let u=-1;for(let y=0;y<this._addons.length;y++)if(this._addons[y]===l){u=y;break}if(u===-1)throw new Error("Could not dispose an addon that has not been loaded");l.isDisposed=!0,l.dispose.apply(l.instance),this._addons.splice(u,1)}}},3235:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferApiView=void 0;let u=l(793),y=l(3055);n.BufferApiView=class{constructor(h,_){this._buffer=h,this.type=_}init(h){return this._buffer=h,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(h){let _=this._buffer.lines.get(h);if(_)return new u.BufferLineApiView(_)}getNullCell(){return new y.CellData}}},793:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferLineApiView=void 0;let u=l(3055);n.BufferLineApiView=class{constructor(y){this._line=y}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(y,h){if(!(y<0||y>=this._line.length))return h?(this._line.loadCell(y,h),h):this._line.loadCell(y,new u.CellData)}translateToString(y,h,_){return this._line.translateToString(y,h,_)}}},5101:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferNamespaceApi=void 0;let u=l(3235),y=l(7150),h=l(802);class _ extends y.Disposable{constructor(p){super(),this._core=p,this._onBufferChange=this._register(new h.Emitter),this.onBufferChange=this._onBufferChange.event,this._normal=new u.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new u.BufferApiView(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)}}n.BufferNamespaceApi=_},6097:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ParserApi=void 0,n.ParserApi=class{constructor(l){this._core=l}registerCsiHandler(l,u){return this._core.registerCsiHandler(l,(y=>u(y.toArray())))}addCsiHandler(l,u){return this.registerCsiHandler(l,u)}registerDcsHandler(l,u){return this._core.registerDcsHandler(l,((y,h)=>u(y,h.toArray())))}addDcsHandler(l,u){return this.registerDcsHandler(l,u)}registerEscHandler(l,u){return this._core.registerEscHandler(l,u)}addEscHandler(l,u){return this.registerEscHandler(l,u)}registerOscHandler(l,u){return this._core.registerOscHandler(l,u)}addOscHandler(l,u){return this.registerOscHandler(l,u)}}},4335:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeApi=void 0,n.UnicodeApi=class{constructor(l){this._core=l}register(l){this._core.unicodeService.register(l)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(l){this._core.unicodeService.activeVersion=l}}},9640:function(a,n,l){var u=this&&this.__decorate||function(c,v,g,f){var m,w=arguments.length,C=w<3?v:f===null?f=Object.getOwnPropertyDescriptor(v,g):f;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(c,v,g,f);else for(var k=c.length-1;k>=0;k--)(m=c[k])&&(C=(w<3?m(C):w>3?m(v,g,C):m(v,g))||C);return w>3&&C&&Object.defineProperty(v,g,C),C},y=this&&this.__param||function(c,v){return function(g,f){v(g,f,c)}};Object.defineProperty(n,"__esModule",{value:!0}),n.BufferService=n.MINIMUM_ROWS=n.MINIMUM_COLS=void 0;let h=l(7150),_=l(4097),d=l(6501),p=l(802);n.MINIMUM_COLS=2,n.MINIMUM_ROWS=1;let b=class extends h.Disposable{get buffer(){return this.buffers.active}constructor(c){super(),this.isUserScrolling=!1,this._onResize=this._register(new p.Emitter),this.onResize=this._onResize.event,this._onScroll=this._register(new p.Emitter),this.onScroll=this._onScroll.event,this.cols=Math.max(c.rawOptions.cols||0,n.MINIMUM_COLS),this.rows=Math.max(c.rawOptions.rows||0,n.MINIMUM_ROWS),this.buffers=this._register(new _.BufferSet(c,this)),this._register(this.buffers.onBufferActivate((v=>{this._onScroll.fire(v.activeBuffer.ydisp)})))}resize(c,v){let g=this.cols!==c,f=this.rows!==v;this.cols=c,this.rows=v,this.buffers.resize(c,v),this._onResize.fire({cols:c,rows:v,colsChanged:g,rowsChanged:f})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(c,v=!1){let g=this.buffer,f;f=this._cachedBlankLine,f&&f.length===this.cols&&f.getFg(0)===c.fg&&f.getBg(0)===c.bg||(f=g.getBlankLine(c,v),this._cachedBlankLine=f),f.isWrapped=v;let m=g.ybase+g.scrollTop,w=g.ybase+g.scrollBottom;if(g.scrollTop===0){let C=g.lines.isFull;w===g.lines.length-1?C?g.lines.recycle().copyFrom(f):g.lines.push(f.clone()):g.lines.splice(w+1,0,f.clone()),C?this.isUserScrolling&&(g.ydisp=Math.max(g.ydisp-1,0)):(g.ybase++,this.isUserScrolling||g.ydisp++)}else{let C=w-m+1;g.lines.shiftElements(m+1,C-1,-1),g.lines.set(w,f.clone())}this.isUserScrolling||(g.ydisp=g.ybase),this._onScroll.fire(g.ydisp)}scrollLines(c,v){let g=this.buffer;if(c<0){if(g.ydisp===0)return;this.isUserScrolling=!0}else c+g.ydisp>=g.ybase&&(this.isUserScrolling=!1);let f=g.ydisp;g.ydisp=Math.max(Math.min(g.ydisp+c,g.ybase),0),f!==g.ydisp&&(v||this._onScroll.fire(g.ydisp))}};n.BufferService=b,n.BufferService=b=u([y(0,d.IOptionsService)],b)},5746:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CharsetService=void 0,n.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(l){this.glevel=l,this.charset=this._charsets[l]}setgCharset(l,u){this._charsets[l]=u,this.glevel===l&&(this.charset=u)}}},7792:function(a,n,l){var u=this&&this.__decorate||function(f,m,w,C){var k,A=arguments.length,D=A<3?m:C===null?C=Object.getOwnPropertyDescriptor(m,w):C;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")D=Reflect.decorate(f,m,w,C);else for(var O=f.length-1;O>=0;O--)(k=f[O])&&(D=(A<3?k(D):A>3?k(m,w,D):k(m,w))||D);return A>3&&D&&Object.defineProperty(m,w,D),D},y=this&&this.__param||function(f,m){return function(w,C){m(w,C,f)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CoreMouseService=void 0;let h=l(6501),_=l(7150),d=l(802),p={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:f=>f.button!==4&&f.action===1&&(f.ctrl=!1,f.alt=!1,f.shift=!1,!0)},VT200:{events:19,restrict:f=>f.action!==32},DRAG:{events:23,restrict:f=>f.action!==32||f.button!==3},ANY:{events:31,restrict:f=>!0}};function b(f,m){let w=(f.ctrl?16:0)|(f.shift?4:0)|(f.alt?8:0);return f.button===4?(w|=64,w|=f.action):(w|=3&f.button,4&f.button&&(w|=64),8&f.button&&(w|=128),f.action===32?w|=32:f.action!==0||m||(w|=3)),w}let c=String.fromCharCode,v={DEFAULT:f=>{let m=[b(f,!1)+32,f.col+32,f.row+32];return m[0]>255||m[1]>255||m[2]>255?"":`\x1B[M${c(m[0])}${c(m[1])}${c(m[2])}`},SGR:f=>{let m=f.action===0&&f.button!==4?"m":"M";return`\x1B[<${b(f,!0)};${f.col};${f.row}${m}`},SGR_PIXELS:f=>{let m=f.action===0&&f.button!==4?"m":"M";return`\x1B[<${b(f,!0)};${f.x};${f.y}${m}`}},g=class extends _.Disposable{constructor(f,m,w){super(),this._bufferService=f,this._coreService=m,this._optionsService=w,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new d.Emitter),this.onProtocolChange=this._onProtocolChange.event;for(let C of Object.keys(p))this.addProtocol(C,p[C]);for(let C of Object.keys(v))this.addEncoding(C,v[C]);this.reset()}addProtocol(f,m){this._protocols[f]=m}addEncoding(f,m){this._encodings[f]=m}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(f){if(!this._protocols[f])throw new Error(`unknown protocol "${f}"`);this._activeProtocol=f,this._onProtocolChange.fire(this._protocols[f].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(f){if(!this._encodings[f])throw new Error(`unknown encoding "${f}"`);this._activeEncoding=f}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(f,m,w){if(f.deltaY===0||f.shiftKey||m===void 0||w===void 0)return 0;let C=m/w,k=this._applyScrollModifier(f.deltaY,f);return f.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(k/=C+0,Math.abs(f.deltaY)<50&&(k*=.3),this._wheelPartialScroll+=k,k=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):f.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(k*=this._bufferService.rows),k}_applyScrollModifier(f,m){return m.altKey||m.ctrlKey||m.shiftKey?f*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:f*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(f){if(f.col<0||f.col>=this._bufferService.cols||f.row<0||f.row>=this._bufferService.rows||f.button===4&&f.action===32||f.button===3&&f.action!==32||f.button!==4&&(f.action===2||f.action===3)||(f.col++,f.row++,f.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,f,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(f))return!1;let m=this._encodings[this._activeEncoding](f);return m&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(m):this._coreService.triggerDataEvent(m,!0)),this._lastEvent=f,!0}explainEvents(f){return{down:!!(1&f),up:!!(2&f),drag:!!(4&f),move:!!(8&f),wheel:!!(16&f)}}_equalEvents(f,m,w){if(w){if(f.x!==m.x||f.y!==m.y)return!1}else if(f.col!==m.col||f.row!==m.row)return!1;return f.button===m.button&&f.action===m.action&&f.ctrl===m.ctrl&&f.alt===m.alt&&f.shift===m.shift}};n.CoreMouseService=g,n.CoreMouseService=g=u([y(0,h.IBufferService),y(1,h.ICoreService),y(2,h.IOptionsService)],g)},4071:function(a,n,l){var u=this&&this.__decorate||function(g,f,m,w){var C,k=arguments.length,A=k<3?f:w===null?w=Object.getOwnPropertyDescriptor(f,m):w;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(g,f,m,w);else for(var D=g.length-1;D>=0;D--)(C=g[D])&&(A=(k<3?C(A):k>3?C(f,m,A):C(f,m))||A);return k>3&&A&&Object.defineProperty(f,m,A),A},y=this&&this.__param||function(g,f){return function(m,w){f(m,w,g)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CoreService=void 0;let h=l(7453),_=l(7150),d=l(6501),p=l(802),b=Object.freeze({insertMode:!1}),c=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),v=class extends _.Disposable{constructor(g,f,m){super(),this._bufferService=g,this._logService=f,this._optionsService=m,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new p.Emitter),this.onData=this._onData.event,this._onUserInput=this._register(new p.Emitter),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new p.Emitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new p.Emitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,h.clone)(b),this.decPrivateModes=(0,h.clone)(c)}reset(){this.modes=(0,h.clone)(b),this.decPrivateModes=(0,h.clone)(c)}triggerDataEvent(g,f=!1){if(this._optionsService.rawOptions.disableStdin)return;let m=this._bufferService.buffer;f&&this._optionsService.rawOptions.scrollOnUserInput&&m.ybase!==m.ydisp&&this._onRequestScrollToBottom.fire(),f&&this._onUserInput.fire(),this._logService.debug(`sending data "${g}"`),this._logService.trace("sending data (codes)",(()=>g.split("").map((w=>w.charCodeAt(0))))),this._onData.fire(g)}triggerBinaryEvent(g){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${g}"`),this._logService.trace("sending binary (codes)",(()=>g.split("").map((f=>f.charCodeAt(0))))),this._onBinary.fire(g))}};n.CoreService=v,n.CoreService=v=u([y(0,d.IBufferService),y(1,d.ILogService),y(2,d.IOptionsService)],v)},6025:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.InstantiationService=n.ServiceCollection=void 0;let u=l(6501),y=l(6201);class h{constructor(...d){this._entries=new Map;for(let[p,b]of d)this.set(p,b)}set(d,p){let b=this._entries.get(d);return this._entries.set(d,p),b}forEach(d){for(let[p,b]of this._entries.entries())d(p,b)}has(d){return this._entries.has(d)}get(d){return this._entries.get(d)}}n.ServiceCollection=h,n.InstantiationService=class{constructor(){this._services=new h,this._services.set(u.IInstantiationService,this)}setService(_,d){this._services.set(_,d)}getService(_){return this._services.get(_)}createInstance(_,...d){let p=(0,y.getServiceDependencies)(_).sort(((v,g)=>v.index-g.index)),b=[];for(let v of p){let g=this._services.get(v.id);if(!g)throw new Error(`[createInstance] ${_.name} depends on UNKNOWN service ${v.id._id}.`);b.push(g)}let c=p.length>0?p[0].index:d.length;if(d.length!==c)throw new Error(`[createInstance] First service dependency of ${_.name} at position ${c+1} conflicts with ${d.length} static arguments`);return new _(...d,...b)}}},7276:function(a,n,l){var u=this&&this.__decorate||function(c,v,g,f){var m,w=arguments.length,C=w<3?v:f===null?f=Object.getOwnPropertyDescriptor(v,g):f;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(c,v,g,f);else for(var k=c.length-1;k>=0;k--)(m=c[k])&&(C=(w<3?m(C):w>3?m(v,g,C):m(v,g))||C);return w>3&&C&&Object.defineProperty(v,g,C),C},y=this&&this.__param||function(c,v){return function(g,f){v(g,f,c)}};Object.defineProperty(n,"__esModule",{value:!0}),n.LogService=void 0,n.setTraceLogger=function(c){p=c},n.traceCall=function(c,v,g){if(typeof g.value!="function")throw new Error("not supported");let f=g.value;g.value=function(...m){if(p.logLevel!==_.LogLevelEnum.TRACE)return f.apply(this,m);p.trace(`GlyphRenderer#${f.name}(${m.map((C=>JSON.stringify(C))).join(", ")})`);let w=f.apply(this,m);return p.trace(`GlyphRenderer#${f.name} return`,w),w}};let h=l(7150),_=l(6501),d={trace:_.LogLevelEnum.TRACE,debug:_.LogLevelEnum.DEBUG,info:_.LogLevelEnum.INFO,warn:_.LogLevelEnum.WARN,error:_.LogLevelEnum.ERROR,off:_.LogLevelEnum.OFF},p,b=class extends h.Disposable{get logLevel(){return this._logLevel}constructor(c){super(),this._optionsService=c,this._logLevel=_.LogLevelEnum.OFF,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",(()=>this._updateLogLevel()))),p=this}_updateLogLevel(){this._logLevel=d[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(c){for(let v=0;v<c.length;v++)typeof c[v]=="function"&&(c[v]=c[v]())}_log(c,v,g){this._evalLazyOptionalParams(g),c.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+v,...g)}trace(c,...v){this._logLevel<=_.LogLevelEnum.TRACE&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,c,v)}debug(c,...v){this._logLevel<=_.LogLevelEnum.DEBUG&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,c,v)}info(c,...v){this._logLevel<=_.LogLevelEnum.INFO&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,c,v)}warn(c,...v){this._logLevel<=_.LogLevelEnum.WARN&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,c,v)}error(c,...v){this._logLevel<=_.LogLevelEnum.ERROR&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,c,v)}};n.LogService=b,n.LogService=b=u([y(0,_.IOptionsService)],b)},56:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.OptionsService=n.DEFAULT_OPTIONS=void 0;let u=l(7150),y=l(701),h=l(802);n.DEFAULT_OPTIONS={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:y.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}};let _=["normal","bold","100","200","300","400","500","600","700","800","900"];class d extends u.Disposable{constructor(b){super(),this._onOptionChange=this._register(new h.Emitter),this.onOptionChange=this._onOptionChange.event;let c={...n.DEFAULT_OPTIONS};for(let v in b)if(v in c)try{let g=b[v];c[v]=this._sanitizeAndValidateOption(v,g)}catch(g){console.error(g)}this.rawOptions=c,this.options={...c},this._setupOptions(),this._register((0,u.toDisposable)((()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null})))}onSpecificOptionChange(b,c){return this.onOptionChange((v=>{v===b&&c(this.rawOptions[b])}))}onMultipleOptionChange(b,c){return this.onOptionChange((v=>{b.indexOf(v)!==-1&&c()}))}_setupOptions(){let b=v=>{if(!(v in n.DEFAULT_OPTIONS))throw new Error(`No option with key "${v}"`);return this.rawOptions[v]},c=(v,g)=>{if(!(v in n.DEFAULT_OPTIONS))throw new Error(`No option with key "${v}"`);g=this._sanitizeAndValidateOption(v,g),this.rawOptions[v]!==g&&(this.rawOptions[v]=g,this._onOptionChange.fire(v))};for(let v in this.rawOptions){let g={get:b.bind(this,v),set:c.bind(this,v)};Object.defineProperty(this.options,v,g)}}_sanitizeAndValidateOption(b,c){switch(b){case"cursorStyle":if(c||(c=n.DEFAULT_OPTIONS[b]),!(function(v){return v==="block"||v==="underline"||v==="bar"})(c))throw new Error(`"${c}" is not a valid value for ${b}`);break;case"wordSeparator":c||(c=n.DEFAULT_OPTIONS[b]);break;case"fontWeight":case"fontWeightBold":if(typeof c=="number"&&1<=c&&c<=1e3)break;c=_.includes(c)?c:n.DEFAULT_OPTIONS[b];break;case"cursorWidth":c=Math.floor(c);case"lineHeight":case"tabStopWidth":if(c<1)throw new Error(`${b} cannot be less than 1, value: ${c}`);break;case"minimumContrastRatio":c=Math.max(1,Math.min(21,Math.round(10*c)/10));break;case"scrollback":if((c=Math.min(c,4294967295))<0)throw new Error(`${b} cannot be less than 0, value: ${c}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(c<=0)throw new Error(`${b} cannot be less than or equal to 0, value: ${c}`);break;case"rows":case"cols":if(!c&&c!==0)throw new Error(`${b} must be numeric, value: ${c}`);break;case"windowsPty":c=c??{}}return c}}n.OptionsService=d},8811:function(a,n,l){var u=this&&this.__decorate||function(d,p,b,c){var v,g=arguments.length,f=g<3?p:c===null?c=Object.getOwnPropertyDescriptor(p,b):c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")f=Reflect.decorate(d,p,b,c);else for(var m=d.length-1;m>=0;m--)(v=d[m])&&(f=(g<3?v(f):g>3?v(p,b,f):v(p,b))||f);return g>3&&f&&Object.defineProperty(p,b,f),f},y=this&&this.__param||function(d,p){return function(b,c){p(b,c,d)}};Object.defineProperty(n,"__esModule",{value:!0}),n.OscLinkService=void 0;let h=l(6501),_=class{constructor(d){this._bufferService=d,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(d){let p=this._bufferService.buffer;if(d.id===void 0){let m=p.addMarker(p.ybase+p.y),w={data:d,id:this._nextId++,lines:[m]};return m.onDispose((()=>this._removeMarkerFromLink(w,m))),this._dataByLinkId.set(w.id,w),w.id}let b=d,c=this._getEntryIdKey(b),v=this._entriesWithId.get(c);if(v)return this.addLineToLink(v.id,p.ybase+p.y),v.id;let g=p.addMarker(p.ybase+p.y),f={id:this._nextId++,key:this._getEntryIdKey(b),data:b,lines:[g]};return g.onDispose((()=>this._removeMarkerFromLink(f,g))),this._entriesWithId.set(f.key,f),this._dataByLinkId.set(f.id,f),f.id}addLineToLink(d,p){let b=this._dataByLinkId.get(d);if(b&&b.lines.every((c=>c.line!==p))){let c=this._bufferService.buffer.addMarker(p);b.lines.push(c),c.onDispose((()=>this._removeMarkerFromLink(b,c)))}}getLinkData(d){return this._dataByLinkId.get(d)?.data}_getEntryIdKey(d){return`${d.id};;${d.uri}`}_removeMarkerFromLink(d,p){let b=d.lines.indexOf(p);b!==-1&&(d.lines.splice(b,1),d.lines.length===0&&(d.data.id!==void 0&&this._entriesWithId.delete(d.key),this._dataByLinkId.delete(d.id)))}};n.OscLinkService=_,n.OscLinkService=_=u([y(0,h.IBufferService)],_)},6201:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.serviceRegistry=void 0,n.getServiceDependencies=function(y){return y[u]||[]},n.createDecorator=function(y){if(n.serviceRegistry.has(y))return n.serviceRegistry.get(y);let h=function(_,d,p){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");(function(b,c,v){c[l]===c?c[u].push({id:b,index:v}):(c[u]=[{id:b,index:v}],c[l]=c)})(h,_,p)};return h._id=y,n.serviceRegistry.set(y,h),h};let l="di$target",u="di$dependencies";n.serviceRegistry=new Map},6501:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.IDecorationService=n.IUnicodeService=n.IOscLinkService=n.IOptionsService=n.ILogService=n.LogLevelEnum=n.IInstantiationService=n.ICharsetService=n.ICoreService=n.ICoreMouseService=n.IBufferService=void 0;let u=l(6201);var y;n.IBufferService=(0,u.createDecorator)("BufferService"),n.ICoreMouseService=(0,u.createDecorator)("CoreMouseService"),n.ICoreService=(0,u.createDecorator)("CoreService"),n.ICharsetService=(0,u.createDecorator)("CharsetService"),n.IInstantiationService=(0,u.createDecorator)("InstantiationService"),(function(h){h[h.TRACE=0]="TRACE",h[h.DEBUG=1]="DEBUG",h[h.INFO=2]="INFO",h[h.WARN=3]="WARN",h[h.ERROR=4]="ERROR",h[h.OFF=5]="OFF"})(y||(n.LogLevelEnum=y={})),n.ILogService=(0,u.createDecorator)("LogService"),n.IOptionsService=(0,u.createDecorator)("OptionsService"),n.IOscLinkService=(0,u.createDecorator)("OscLinkService"),n.IUnicodeService=(0,u.createDecorator)("UnicodeService"),n.IDecorationService=(0,u.createDecorator)("DecorationService")},6415:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeService=void 0;let u=l(7428),y=l(802);class h{static extractShouldJoin(d){return!!(1&d)}static extractWidth(d){return d>>1&3}static extractCharKind(d){return d>>3}static createPropertyValue(d,p,b=!1){return(16777215&d)<<3|(3&p)<<1|(b?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new y.Emitter,this.onChange=this._onChange.event;let d=new u.UnicodeV6;this.register(d),this._active=d.version,this._activeProvider=d}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(d){if(!this._providers[d])throw new Error(`unknown Unicode version "${d}"`);this._active=d,this._activeProvider=this._providers[d],this._onChange.fire(d)}register(d){this._providers[d.version]=d}wcwidth(d){return this._activeProvider.wcwidth(d)}getStringCellWidth(d){let p=0,b=0,c=d.length;for(let v=0;v<c;++v){let g=d.charCodeAt(v);if(55296<=g&&g<=56319){if(++v>=c)return p+this.wcwidth(g);let w=d.charCodeAt(v);56320<=w&&w<=57343?g=1024*(g-55296)+w-56320+65536:p+=this.wcwidth(w)}let f=this.charProperties(g,b),m=h.extractWidth(f);h.extractShouldJoin(f)&&(m-=h.extractWidth(b)),p+=m,b=f}return p}charProperties(d,p){return this._activeProvider.charProperties(d,p)}}n.UnicodeService=h},5856:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Terminal=void 0;let u=l(6107),y=l(5777),h=l(802);class _ extends y.CoreTerminal{constructor(p={}){super(p),this._onBell=this._register(new h.Emitter),this.onBell=this._onBell.event,this._onCursorMove=this._register(new h.Emitter),this.onCursorMove=this._onCursorMove.event,this._onTitleChange=this._register(new h.Emitter),this.onTitleChange=this._onTitleChange.event,this._onA11yCharEmitter=this._register(new h.Emitter),this.onA11yChar=this._onA11yCharEmitter.event,this._onA11yTabEmitter=this._register(new h.Emitter),this.onA11yTab=this._onA11yTabEmitter.event,this._setup(),this._register(this._inputHandler.onRequestBell((()=>this.bell()))),this._register(this._inputHandler.onRequestReset((()=>this.reset()))),this._register(h.Event.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(h.Event.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(h.Event.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(h.Event.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter))}get buffer(){return this.buffers.active}get markers(){return this.buffer.markers}addMarker(p){if(this.buffer===this.buffers.normal)return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+p)}bell(){this._onBell.fire()}input(p,b=!0){this.coreService.triggerDataEvent(p,b)}resize(p,b){p===this.cols&&b===this.rows||super.resize(p,b)}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){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 p=1;p<this.rows;p++)this.buffer.lines.push(this.buffer.getBlankLine(u.DEFAULT_ATTR_DATA));this._onScroll.fire({position:this.buffer.ydisp})}}reset(){this.options.rows=this.rows,this.options.cols=this.cols,this._setup(),super.reset()}}n.Terminal=_},3058:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Permutation=n.CallbackIterable=n.ArrayQueue=n.booleanComparator=n.numberComparator=n.CompareResult=void 0,n.tail=function(m,w=0){return m[m.length-(1+w)]},n.tail2=function(m){if(m.length===0)throw new Error("Invalid tail call");return[m.slice(0,m.length-1),m[m.length-1]]},n.equals=function(m,w,C=(k,A)=>k===A){if(m===w)return!0;if(!m||!w||m.length!==w.length)return!1;for(let k=0,A=m.length;k<A;k++)if(!C(m[k],w[k]))return!1;return!0},n.removeFastWithoutKeepingOrder=function(m,w){let C=m.length-1;w<C&&(m[w]=m[C]),m.pop()},n.binarySearch=function(m,w,C){return h(m.length,(k=>C(m[k],w)))},n.binarySearch2=h,n.quickSelect=function m(w,C,k){if((w|=0)>=C.length)throw new TypeError("invalid index");let A=C[Math.floor(C.length*Math.random())],D=[],O=[],L=[];for(let R of C){let P=k(R,A);P<0?D.push(R):P>0?O.push(R):L.push(R)}return w<D.length?m(w,D,k):w<D.length+L.length?L[0]:m(w-(D.length+L.length),O,k)},n.groupBy=function(m,w){let C=[],k;for(let A of m.slice(0).sort(w))k&&w(k[0],A)===0?k.push(A):(k=[A],C.push(k));return C},n.groupAdjacentBy=function*(m,w){let C,k;for(let A of m)k!==void 0&&w(k,A)?C.push(A):(C&&(yield C),C=[A]),k=A;C&&(yield C)},n.forEachAdjacent=function(m,w){for(let C=0;C<=m.length;C++)w(C===0?void 0:m[C-1],C===m.length?void 0:m[C])},n.forEachWithNeighbors=function(m,w){for(let C=0;C<m.length;C++)w(C===0?void 0:m[C-1],m[C],C+1===m.length?void 0:m[C+1])},n.sortedDiff=_,n.delta=function(m,w,C){let k=_(m,w,C),A=[],D=[];for(let O of k)A.push(...m.slice(O.start,O.start+O.deleteCount)),D.push(...O.toInsert);return{removed:A,added:D}},n.top=function(m,w,C){if(C===0)return[];let k=m.slice(0,C).sort(w);return d(m,w,k,C,m.length),k},n.topAsync=function(m,w,C,k,A){return C===0?Promise.resolve([]):new Promise(((D,O)=>{(async()=>{let L=m.length,R=m.slice(0,C).sort(w);for(let P=C,F=Math.min(C+k,L);P<L;P=F,F=Math.min(F+k,L)){if(P>C&&await new Promise((V=>setTimeout(V))),A&&A.isCancellationRequested)throw new u.CancellationError;d(m,w,R,P,F)}return R})().then(D,O)}))},n.coalesce=function(m){return m.filter((w=>!!w))},n.coalesceInPlace=function(m){let w=0;for(let C=0;C<m.length;C++)m[C]&&(m[w]=m[C],w+=1);m.length=w},n.move=function(m,w,C){m.splice(C,0,m.splice(w,1)[0])},n.isFalsyOrEmpty=function(m){return!Array.isArray(m)||m.length===0},n.isNonEmptyArray=function(m){return Array.isArray(m)&&m.length>0},n.distinct=function(m,w=C=>C){let C=new Set;return m.filter((k=>{let A=w(k);return!C.has(A)&&(C.add(A),!0)}))},n.uniqueFilter=function(m){let w=new Set;return C=>{let k=m(C);return!w.has(k)&&(w.add(k),!0)}},n.firstOrDefault=function(m,w){return m.length>0?m[0]:w},n.lastOrDefault=function(m,w){return m.length>0?m[m.length-1]:w},n.commonPrefixLength=function(m,w,C=(k,A)=>k===A){let k=0;for(let A=0,D=Math.min(m.length,w.length);A<D&&C(m[A],w[A]);A++)k++;return k},n.range=function(m,w){let C=typeof w=="number"?m:0;typeof w=="number"?C=m:(C=0,w=m);let k=[];if(C<=w)for(let A=C;A<w;A++)k.push(A);else for(let A=C;A>w;A--)k.push(A);return k},n.index=function(m,w,C){return m.reduce(((k,A)=>(k[w(A)]=C?C(A):A,k)),Object.create(null))},n.insert=function(m,w){return m.push(w),()=>p(m,w)},n.remove=p,n.arrayInsert=function(m,w,C){let k=m.slice(0,w),A=m.slice(w);return k.concat(C,A)},n.shuffle=function(m,w){let C;if(typeof w=="number"){let k=w;C=()=>{let A=179426549*Math.sin(k++);return A-Math.floor(A)}}else C=Math.random;for(let k=m.length-1;k>0;k-=1){let A=Math.floor(C()*(k+1)),D=m[k];m[k]=m[A],m[A]=D}},n.pushToStart=function(m,w){let C=m.indexOf(w);C>-1&&(m.splice(C,1),m.unshift(w))},n.pushToEnd=function(m,w){let C=m.indexOf(w);C>-1&&(m.splice(C,1),m.push(w))},n.pushMany=function(m,w){for(let C of w)m.push(C)},n.mapArrayOrNot=function(m,w){return Array.isArray(m)?m.map(w):w(m)},n.asArray=function(m){return Array.isArray(m)?m:[m]},n.getRandomElement=function(m){return m[Math.floor(Math.random()*m.length)]},n.insertInto=b,n.splice=function(m,w,C,k){let A=c(m,w),D=m.splice(A,C);return D===void 0&&(D=[]),b(m,A,k),D},n.compareBy=function(m,w){return(C,k)=>w(m(C),m(k))},n.tieBreakComparators=function(...m){return(w,C)=>{for(let k of m){let A=k(w,C);if(!v.isNeitherLessOrGreaterThan(A))return A}return v.neitherLessOrGreaterThan}},n.reverseOrder=function(m){return(w,C)=>-m(w,C)};let u=l(9807),y=l(8297);function h(m,w){let C=0,k=m-1;for(;C<=k;){let A=(C+k)/2|0,D=w(A);if(D<0)C=A+1;else{if(!(D>0))return A;k=A-1}}return-(C+1)}function _(m,w,C){let k=[];function A(L,R,P){if(R===0&&P.length===0)return;let F=k[k.length-1];F&&F.start+F.deleteCount===L?(F.deleteCount+=R,F.toInsert.push(...P)):k.push({start:L,deleteCount:R,toInsert:P})}let D=0,O=0;for(;;){if(D===m.length){A(D,0,w.slice(O));break}if(O===w.length){A(D,m.length-D,[]);break}let L=m[D],R=w[O],P=C(L,R);P===0?(D+=1,O+=1):P<0?(A(D,1,[]),D+=1):P>0&&(A(D,0,[R]),O+=1)}return k}function d(m,w,C,k,A){for(let D=C.length;k<A;k++){let O=m[k];if(w(O,C[D-1])<0){C.pop();let L=(0,y.findFirstIdxMonotonousOrArrLen)(C,(R=>w(O,R)<0));C.splice(L,0,O)}}}function p(m,w){let C=m.indexOf(w);if(C>-1)return m.splice(C,1),w}function b(m,w,C){let k=c(m,w),A=m.length,D=C.length;m.length=A+D;for(let O=A-1;O>=k;O--)m[O+D]=m[O];for(let O=0;O<D;O++)m[O+k]=C[O]}function c(m,w){return w<0?Math.max(w+m.length,0):Math.min(w,m.length)}var v;(function(m){m.isLessThan=function(w){return w<0},m.isLessThanOrEqual=function(w){return w<=0},m.isGreaterThan=function(w){return w>0},m.isNeitherLessOrGreaterThan=function(w){return w===0},m.greaterThan=1,m.lessThan=-1,m.neitherLessOrGreaterThan=0})(v||(n.CompareResult=v={})),n.numberComparator=(m,w)=>m-w,n.booleanComparator=(m,w)=>(0,n.numberComparator)(m?1:0,w?1:0),n.ArrayQueue=class{constructor(m){this.items=m,this.firstIdx=0,this.lastIdx=this.items.length-1}get length(){return this.lastIdx-this.firstIdx+1}takeWhile(m){let w=this.firstIdx;for(;w<this.items.length&&m(this.items[w]);)w++;let C=w===this.firstIdx?null:this.items.slice(this.firstIdx,w);return this.firstIdx=w,C}takeFromEndWhile(m){let w=this.lastIdx;for(;w>=0&&m(this.items[w]);)w--;let C=w===this.lastIdx?null:this.items.slice(w+1,this.lastIdx+1);return this.lastIdx=w,C}peek(){if(this.length!==0)return this.items[this.firstIdx]}peekLast(){if(this.length!==0)return this.items[this.lastIdx]}dequeue(){let m=this.items[this.firstIdx];return this.firstIdx++,m}removeLast(){let m=this.items[this.lastIdx];return this.lastIdx--,m}takeCount(m){let w=this.items.slice(this.firstIdx,this.firstIdx+m);return this.firstIdx+=m,w}};class g{static{this.empty=new g((w=>{}))}constructor(w){this.iterate=w}forEach(w){this.iterate((C=>(w(C),!0)))}toArray(){let w=[];return this.iterate((C=>(w.push(C),!0))),w}filter(w){return new g((C=>this.iterate((k=>!w(k)||C(k)))))}map(w){return new g((C=>this.iterate((k=>C(w(k))))))}some(w){let C=!1;return this.iterate((k=>(C=w(k),!C))),C}findFirst(w){let C;return this.iterate((k=>!w(k)||(C=k,!1))),C}findLast(w){let C;return this.iterate((k=>(w(k)&&(C=k),!0))),C}findLastMaxBy(w){let C,k=!0;return this.iterate((A=>((k||v.isGreaterThan(w(A,C)))&&(k=!1,C=A),!0))),C}}n.CallbackIterable=g;class f{constructor(w){this._indexMap=w}static createSortPermutation(w,C){let k=Array.from(w.keys()).sort(((A,D)=>C(w[A],w[D])));return new f(k)}apply(w){return w.map(((C,k)=>w[this._indexMap[k]]))}inverse(){let w=this._indexMap.slice();for(let C=0;C<this._indexMap.length;C++)w[this._indexMap[C]]=C;return new f(w)}}n.Permutation=f},8297:(a,n)=>{function l(d,p,b=d.length-1){for(let c=b;c>=0;c--)if(p(d[c]))return c;return-1}function u(d,p,b=0,c=d.length){let v=b,g=c;for(;v<g;){let f=Math.floor((v+g)/2);p(d[f])?v=f+1:g=f}return v-1}function y(d,p,b=0,c=d.length){let v=b,g=c;for(;v<g;){let f=Math.floor((v+g)/2);p(d[f])?g=f:v=f+1}return v}Object.defineProperty(n,"__esModule",{value:!0}),n.MonotonousArray=void 0,n.findLast=function(d,p){let b=l(d,p);if(b!==-1)return d[b]},n.findLastIdx=l,n.findLastMonotonous=function(d,p){let b=u(d,p);return b===-1?void 0:d[b]},n.findLastIdxMonotonous=u,n.findFirstMonotonous=function(d,p){let b=y(d,p);return b===d.length?void 0:d[b]},n.findFirstIdxMonotonousOrArrLen=y,n.findFirstIdxMonotonous=function(d,p,b=0,c=d.length){let v=y(d,p,b,c);return v===d.length?-1:v},n.findFirstMax=_,n.findLastMax=function(d,p){if(d.length===0)return;let b=d[0];for(let c=1;c<d.length;c++){let v=d[c];p(v,b)>=0&&(b=v)}return b},n.findFirstMin=function(d,p){return _(d,((b,c)=>-p(b,c)))},n.findMaxIdx=function(d,p){if(d.length===0)return-1;let b=0;for(let c=1;c<d.length;c++)p(d[c],d[b])>0&&(b=c);return b},n.mapFindFirst=function(d,p){for(let b of d){let c=p(b);if(c!==void 0)return c}};class h{static{this.assertInvariants=!1}constructor(p){this._array=p,this._findLastMonotonousLastIdx=0}findLastMonotonous(p){if(h.assertInvariants){if(this._prevFindLastPredicate){for(let c of this._array)if(this._prevFindLastPredicate(c)&&!p(c))throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.")}this._prevFindLastPredicate=p}let b=u(this._array,p,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=b+1,b===-1?void 0:this._array[b]}}function _(d,p){if(d.length===0)return;let b=d[0];for(let c=1;c<d.length;c++){let v=d[c];p(v,b)>0&&(b=v)}return b}n.MonotonousArray=h},9087:(a,n)=>{var l;Object.defineProperty(n,"__esModule",{value:!0}),n.SetWithKey=void 0,n.groupBy=function(y,h){let _=Object.create(null);for(let d of y){let p=h(d),b=_[p];b||(b=_[p]=[]),b.push(d)}return _},n.diffSets=function(y,h){let _=[],d=[];for(let p of y)h.has(p)||_.push(p);for(let p of h)y.has(p)||d.push(p);return{removed:_,added:d}},n.diffMaps=function(y,h){let _=[],d=[];for(let[p,b]of y)h.has(p)||_.push(b);for(let[p,b]of h)y.has(p)||d.push(b);return{removed:_,added:d}},n.intersection=function(y,h){let _=new Set;for(let d of h)y.has(d)&&_.add(d);return _};class u{static{l=Symbol.toStringTag}constructor(h,_){this.toKey=_,this._map=new Map,this[l]="SetWithKey";for(let d of h)this.add(d)}get size(){return this._map.size}add(h){let _=this.toKey(h);return this._map.set(_,h),this}delete(h){return this._map.delete(this.toKey(h))}has(h){return this._map.has(this.toKey(h))}*entries(){for(let h of this._map.values())yield[h,h]}keys(){return this.values()}*values(){for(let h of this._map.values())yield h}clear(){this._map.clear()}forEach(h,_){this._map.forEach((d=>h.call(_,d,d,this)))}[Symbol.iterator](){return this.values()}}n.SetWithKey=u},9807:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BugIndicatingError=n.ErrorNoTelemetry=n.ExpectedError=n.NotSupportedError=n.NotImplementedError=n.ReadonlyError=n.CancellationError=n.errorHandler=n.ErrorHandler=void 0,n.setUnexpectedErrorHandler=function(g){n.errorHandler.setUnexpectedErrorHandler(g)},n.isSigPipeError=function(g){if(!g||typeof g!="object")return!1;let f=g;return f.code==="EPIPE"&&f.syscall?.toUpperCase()==="WRITE"},n.onUnexpectedError=function(g){y(g)||n.errorHandler.onUnexpectedError(g)},n.onUnexpectedExternalError=function(g){y(g)||n.errorHandler.onUnexpectedExternalError(g)},n.transformErrorForSerialization=function(g){if(g instanceof Error){let{name:f,message:m}=g;return{$isError:!0,name:f,message:m,stack:g.stacktrace||g.stack,noTelemetry:c.isErrorNoTelemetry(g)}}return g},n.transformErrorFromSerialization=function(g){let f;return g.noTelemetry?f=new c:(f=new Error,f.name=g.name),f.message=g.message,f.stack=g.stack,f},n.isCancellationError=y,n.canceled=function(){let g=new Error(u);return g.name=g.message,g},n.illegalArgument=function(g){return g?new Error(`Illegal argument: ${g}`):new Error("Illegal argument")},n.illegalState=function(g){return g?new Error(`Illegal state: ${g}`):new Error("Illegal state")},n.getErrorMessage=function(g){return g?g.message?g.message:g.stack?g.stack.split(`
24
+ `)[0]:String(g):"Error"};class l{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(f){setTimeout((()=>{throw f.stack?c.isErrorNoTelemetry(f)?new c(f.message+`
25
+
26
+ `+f.stack):new Error(f.message+`
27
+
28
+ `+f.stack):f}),0)}}addListener(f){return this.listeners.push(f),()=>{this._removeListener(f)}}emit(f){this.listeners.forEach((m=>{m(f)}))}_removeListener(f){this.listeners.splice(this.listeners.indexOf(f),1)}setUnexpectedErrorHandler(f){this.unexpectedErrorHandler=f}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(f){this.unexpectedErrorHandler(f),this.emit(f)}onUnexpectedExternalError(f){this.unexpectedErrorHandler(f)}}n.ErrorHandler=l,n.errorHandler=new l;let u="Canceled";function y(g){return g instanceof h||g instanceof Error&&g.name===u&&g.message===u}class h extends Error{constructor(){super(u),this.name=this.message}}n.CancellationError=h;class _ extends TypeError{constructor(f){super(f?`${f} is read-only and cannot be changed`:"Cannot change read-only property")}}n.ReadonlyError=_;class d extends Error{constructor(f){super("NotImplemented"),f&&(this.message=f)}}n.NotImplementedError=d;class p extends Error{constructor(f){super("NotSupported"),f&&(this.message=f)}}n.NotSupportedError=p;class b extends Error{constructor(){super(...arguments),this.isExpected=!0}}n.ExpectedError=b;class c extends Error{constructor(f){super(f),this.name="CodeExpectedError"}static fromError(f){if(f instanceof c)return f;let m=new c;return m.message=f.message,m.stack=f.stack,m}static isErrorNoTelemetry(f){return f.name==="CodeExpectedError"}}n.ErrorNoTelemetry=c;class v extends Error{constructor(f){super(f||"An unexpected bug occurred."),Object.setPrototypeOf(this,v.prototype)}}n.BugIndicatingError=v},802:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ValueWithChangeEvent=n.Relay=n.EventBufferer=n.DynamicListEventMultiplexer=n.EventMultiplexer=n.MicrotaskEmitter=n.DebounceEmitter=n.PauseableEmitter=n.AsyncEmitter=n.createEventDeliveryQueue=n.Emitter=n.ListenerRefusalError=n.ListenerLeakError=n.EventProfiling=n.Event=void 0,n.setGlobalLeakWarningThreshold=function(R){let P=c;return c=R,{dispose(){c=P}}};let u=l(9807),y=l(8841),h=l(7150),_=l(6317),d=l(9725);var p;(function(R){function P(E){return(x,M=null,N)=>{let U,z=!1;return U=E((ne=>{if(!z)return U?U.dispose():z=!0,x.call(M,ne)}),null,N),z&&U.dispose(),U}}function F(E,x,M){return Z(((N,U=null,z)=>E((ne=>N.call(U,x(ne))),null,z)),M)}function V(E,x,M){return Z(((N,U=null,z)=>E((ne=>x(ne)&&N.call(U,ne)),null,z)),M)}function Z(E,x){let M,N=new k({onWillAddFirstListener(){M=E(N.fire,N)},onDidRemoveLastListener(){M?.dispose()}});return x?.add(N),N.event}function Y(E,x,M=100,N=!1,U=!1,z,ne){let I,Q,J,te,Te=0,Ae=new k({leakWarningThreshold:z,onWillAddFirstListener(){I=E((Vt=>{Te++,Q=x(Q,Vt),N&&!J&&(Ae.fire(Q),Q=void 0),te=()=>{let Fe=Q;Q=void 0,J=void 0,(!N||Te>1)&&Ae.fire(Fe),Te=0},typeof M=="number"?(clearTimeout(J),J=setTimeout(te,M)):J===void 0&&(J=0,queueMicrotask(te))}))},onWillRemoveListener(){U&&Te>0&&te?.()},onDidRemoveLastListener(){te=void 0,I.dispose()}});return ne?.add(Ae),Ae.event}R.None=()=>h.Disposable.None,R.defer=function(E,x){return Y(E,(()=>{}),0,void 0,!0,void 0,x)},R.once=P,R.map=F,R.forEach=function(E,x,M){return Z(((N,U=null,z)=>E((ne=>{x(ne),N.call(U,ne)}),null,z)),M)},R.filter=V,R.signal=function(E){return E},R.any=function(...E){return(x,M=null,N)=>{return U=(0,h.combinedDisposable)(...E.map((ne=>ne((I=>x.call(M,I)))))),(z=N)instanceof Array?z.push(U):z&&z.add(U),U;var U,z}},R.reduce=function(E,x,M,N){let U=M;return F(E,(z=>(U=x(U,z),U)),N)},R.debounce=Y,R.accumulate=function(E,x=0,M){return R.debounce(E,((N,U)=>N?(N.push(U),N):[U]),x,void 0,!0,void 0,M)},R.latch=function(E,x=(N,U)=>N===U,M){let N,U=!0;return V(E,(z=>{let ne=U||!x(z,N);return U=!1,N=z,ne}),M)},R.split=function(E,x,M){return[R.filter(E,x,M),R.filter(E,(N=>!x(N)),M)]},R.buffer=function(E,x=!1,M=[],N){let U=M.slice(),z=E((Q=>{U?U.push(Q):I.fire(Q)}));N&&N.add(z);let ne=()=>{U?.forEach((Q=>I.fire(Q))),U=null},I=new k({onWillAddFirstListener(){z||(z=E((Q=>I.fire(Q))),N&&N.add(z))},onDidAddFirstListener(){U&&(x?setTimeout(ne):ne())},onDidRemoveLastListener(){z&&z.dispose(),z=null}});return N&&N.add(I),I.event},R.chain=function(E,x){return(M,N,U)=>{let z=x(new S);return E((function(ne){let I=z.evaluate(ne);I!==j&&M.call(N,I)}),void 0,U)}};let j=Symbol("HaltChainable");class S{constructor(){this.steps=[]}map(x){return this.steps.push(x),this}forEach(x){return this.steps.push((M=>(x(M),M))),this}filter(x){return this.steps.push((M=>x(M)?M:j)),this}reduce(x,M){let N=M;return this.steps.push((U=>(N=x(N,U),N))),this}latch(x=(M,N)=>M===N){let M,N=!0;return this.steps.push((U=>{let z=N||!x(U,M);return N=!1,M=U,z?U:j})),this}evaluate(x){for(let M of this.steps)if((x=M(x))===j)break;return x}}R.fromNodeEventEmitter=function(E,x,M=N=>N){let N=(...z)=>U.fire(M(...z)),U=new k({onWillAddFirstListener:()=>E.on(x,N),onDidRemoveLastListener:()=>E.removeListener(x,N)});return U.event},R.fromDOMEventEmitter=function(E,x,M=N=>N){let N=(...z)=>U.fire(M(...z)),U=new k({onWillAddFirstListener:()=>E.addEventListener(x,N),onDidRemoveLastListener:()=>E.removeEventListener(x,N)});return U.event},R.toPromise=function(E){return new Promise((x=>P(E)(x)))},R.fromPromise=function(E){let x=new k;return E.then((M=>{x.fire(M)}),(()=>{x.fire(void 0)})).finally((()=>{x.dispose()})),x.event},R.forward=function(E,x){return E((M=>x.fire(M)))},R.runAndSubscribe=function(E,x,M){return x(M),E((N=>x(N)))};class T{constructor(x,M){this._observable=x,this._counter=0,this._hasChanged=!1;let N={onWillAddFirstListener:()=>{x.addObserver(this)},onDidRemoveLastListener:()=>{x.removeObserver(this)}};this.emitter=new k(N),M&&M.add(this.emitter)}beginUpdate(x){this._counter++}handlePossibleChange(x){}handleChange(x,M){this._hasChanged=!0}endUpdate(x){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}R.fromObservable=function(E,x){return new T(E,x).emitter.event},R.fromObservableLight=function(E){return(x,M,N)=>{let U=0,z=!1,ne={beginUpdate(){U++},endUpdate(){U--,U===0&&(E.reportChanges(),z&&(z=!1,x.call(M)))},handlePossibleChange(){},handleChange(){z=!0}};E.addObserver(ne),E.reportChanges();let I={dispose(){E.removeObserver(ne)}};return N instanceof h.DisposableStore?N.add(I):Array.isArray(N)&&N.push(I),I}}})(p||(n.Event=p={}));class b{static{this.all=new Set}static{this._idPool=0}constructor(P){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${P}_${b._idPool++}`,b.all.add(this)}start(P){this._stopWatch=new d.StopWatch,this.listenerCount=P}stop(){if(this._stopWatch){let P=this._stopWatch.elapsed();this.durations.push(P),this.elapsedOverall+=P,this.invocationCount+=1,this._stopWatch=void 0}}}n.EventProfiling=b;let c=-1;class v{static{this._idPool=1}constructor(P,F,V=(v._idPool++).toString(16).padStart(3,"0")){this._errorHandler=P,this.threshold=F,this.name=V,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(P,F){let V=this.threshold;if(V<=0||F<V)return;this._stacks||(this._stacks=new Map);let Z=this._stacks.get(P.value)||0;if(this._stacks.set(P.value,Z+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=.5*V;let[Y,j]=this.getMostFrequentStack(),S=`[${this.name}] potential listener LEAK detected, having ${F} listeners already. MOST frequent listener (${j}):`;console.warn(S),console.warn(Y);let T=new f(S,Y);this._errorHandler(T)}return()=>{let Y=this._stacks.get(P.value)||0;this._stacks.set(P.value,Y-1)}}getMostFrequentStack(){if(!this._stacks)return;let P,F=0;for(let[V,Z]of this._stacks)(!P||F<Z)&&(P=[V,Z],F=Z);return P}}class g{static create(){let P=new Error;return new g(P.stack??"")}constructor(P){this.value=P}print(){console.warn(this.value.split(`
29
+ `).slice(2).join(`
30
+ `))}}class f extends Error{constructor(P,F){super(P),this.name="ListenerLeakError",this.stack=F}}n.ListenerLeakError=f;class m extends Error{constructor(P,F){super(P),this.name="ListenerRefusalError",this.stack=F}}n.ListenerRefusalError=m;let w=0;class C{constructor(P){this.value=P,this.id=w++}}class k{constructor(P){this._size=0,this._options=P,this._leakageMon=c>0||this._options?.leakWarningThreshold?new v(P?.onListenerError??u.onUnexpectedError,this._options?.leakWarningThreshold??c):void 0,this._perfMon=this._options?._profName?new b(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(P,F,V)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let S=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(S);let T=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],E=new m(`${S}. HINT: Stack shows most frequent listener (${T[1]}-times)`,T[0]);return(this._options?.onListenerError||u.onUnexpectedError)(E),h.Disposable.None}if(this._disposed)return h.Disposable.None;F&&(P=P.bind(F));let Z=new C(P),Y;this._leakageMon&&this._size>=Math.ceil(.2*this._leakageMon.threshold)&&(Z.stack=g.create(),Y=this._leakageMon.check(Z.stack,this._size+1)),this._listeners?this._listeners instanceof C?(this._deliveryQueue??=new A,this._listeners=[this._listeners,Z]):this._listeners.push(Z):(this._options?.onWillAddFirstListener?.(this),this._listeners=Z,this._options?.onDidAddFirstListener?.(this)),this._size++;let j=(0,h.toDisposable)((()=>{Y?.(),this._removeListener(Z)}));return V instanceof h.DisposableStore?V.add(j):Array.isArray(V)&&V.push(j),j},this._event}_removeListener(P){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1)return this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),void(this._size=0);let F=this._listeners,V=F.indexOf(P);if(V===-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--,F[V]=void 0;let Z=this._deliveryQueue.current===this;if(2*this._size<=F.length){let Y=0;for(let j=0;j<F.length;j++)F[j]?F[Y++]=F[j]:Z&&(this._deliveryQueue.end--,Y<this._deliveryQueue.i&&this._deliveryQueue.i--);F.length=Y}}_deliver(P,F){if(!P)return;let V=this._options?.onListenerError||u.onUnexpectedError;if(V)try{P.value(F)}catch(Z){V(Z)}else P.value(F)}_deliverQueue(P){let F=P.current._listeners;for(;P.i<P.end;)this._deliver(F[P.i++],P.value);P.reset()}fire(P){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof C)this._deliver(this._listeners,P);else{let F=this._deliveryQueue;F.enqueue(this,P,this._listeners.length),this._deliverQueue(F)}this._perfMon?.stop()}hasListeners(){return this._size>0}}n.Emitter=k,n.createEventDeliveryQueue=()=>new A;class A{constructor(){this.i=-1,this.end=0}enqueue(P,F,V){this.i=0,this.end=V,this.current=P,this.value=F}reset(){this.i=this.end,this.current=void 0,this.value=void 0}}n.AsyncEmitter=class extends k{async fireAsync(R,P,F){if(this._listeners)for(this._asyncDeliveryQueue||(this._asyncDeliveryQueue=new _.LinkedList),((V,Z)=>{if(V instanceof C)Z(V);else for(let Y=0;Y<V.length;Y++){let j=V[Y];j&&Z(j)}})(this._listeners,(V=>this._asyncDeliveryQueue.push([V.value,R])));this._asyncDeliveryQueue.size>0&&!P.isCancellationRequested;){let[V,Z]=this._asyncDeliveryQueue.shift(),Y=[],j={...Z,token:P,waitUntil:S=>{if(Object.isFrozen(Y))throw new Error("waitUntil can NOT be called asynchronous");F&&(S=F(S,V)),Y.push(S)}};try{V(j)}catch(S){(0,u.onUnexpectedError)(S);continue}Object.freeze(Y),await Promise.allSettled(Y).then((S=>{for(let T of S)T.status==="rejected"&&(0,u.onUnexpectedError)(T.reason)}))}}};class D extends k{get isPaused(){return this._isPaused!==0}constructor(P){super(P),this._isPaused=0,this._eventQueue=new _.LinkedList,this._mergeFn=P?.merge}pause(){this._isPaused++}resume(){if(this._isPaused!==0&&--this._isPaused==0)if(this._mergeFn){if(this._eventQueue.size>0){let P=Array.from(this._eventQueue);this._eventQueue.clear(),super.fire(this._mergeFn(P))}}else for(;!this._isPaused&&this._eventQueue.size!==0;)super.fire(this._eventQueue.shift())}fire(P){this._size&&(this._isPaused!==0?this._eventQueue.push(P):super.fire(P))}}n.PauseableEmitter=D,n.DebounceEmitter=class extends D{constructor(R){super(R),this._delay=R.delay??100}fire(R){this._handle||(this.pause(),this._handle=setTimeout((()=>{this._handle=void 0,this.resume()}),this._delay)),super.fire(R)}},n.MicrotaskEmitter=class extends k{constructor(R){super(R),this._queuedEvents=[],this._mergeFn=R?.merge}fire(R){this.hasListeners()&&(this._queuedEvents.push(R),this._queuedEvents.length===1&&queueMicrotask((()=>{this._mergeFn?super.fire(this._mergeFn(this._queuedEvents)):this._queuedEvents.forEach((P=>super.fire(P))),this._queuedEvents=[]})))}};class O{constructor(){this.hasListeners=!1,this.events=[],this.emitter=new k({onWillAddFirstListener:()=>this.onFirstListenerAdd(),onDidRemoveLastListener:()=>this.onLastListenerRemove()})}get event(){return this.emitter.event}add(P){let F={event:P,listener:null};return this.events.push(F),this.hasListeners&&this.hook(F),(0,h.toDisposable)((0,y.createSingleCallFunction)((()=>{this.hasListeners&&this.unhook(F);let V=this.events.indexOf(F);this.events.splice(V,1)})))}onFirstListenerAdd(){this.hasListeners=!0,this.events.forEach((P=>this.hook(P)))}onLastListenerRemove(){this.hasListeners=!1,this.events.forEach((P=>this.unhook(P)))}hook(P){P.listener=P.event((F=>this.emitter.fire(F)))}unhook(P){P.listener?.dispose(),P.listener=null}dispose(){this.emitter.dispose();for(let P of this.events)P.listener?.dispose();this.events=[]}}n.EventMultiplexer=O,n.DynamicListEventMultiplexer=class{constructor(R,P,F,V){this._store=new h.DisposableStore;let Z=this._store.add(new O),Y=this._store.add(new h.DisposableMap);function j(S){Y.set(S,Z.add(V(S)))}for(let S of R)j(S);this._store.add(P((S=>{j(S)}))),this._store.add(F((S=>{Y.deleteAndDispose(S)}))),this.event=Z.event}dispose(){this._store.dispose()}},n.EventBufferer=class{constructor(){this.data=[]}wrapEvent(R,P,F){return(V,Z,Y)=>R((j=>{let S=this.data[this.data.length-1];if(!P)return void(S?S.buffers.push((()=>V.call(Z,j))):V.call(Z,j));let T=S;T?(T.items??=[],T.items.push(j),T.buffers.length===0&&S.buffers.push((()=>{T.reducedResult??=F?T.items.reduce(P,F):T.items.reduce(P),V.call(Z,T.reducedResult)}))):V.call(Z,P(F,j))}),void 0,Y)}bufferEvents(R){let P={buffers:new Array};this.data.push(P);let F=R();return this.data.pop(),P.buffers.forEach((V=>V())),F}},n.Relay=class{constructor(){this.listening=!1,this.inputEvent=p.None,this.inputEventListener=h.Disposable.None,this.emitter=new k({onDidAddFirstListener:()=>{this.listening=!0,this.inputEventListener=this.inputEvent(this.emitter.fire,this.emitter)},onDidRemoveLastListener:()=>{this.listening=!1,this.inputEventListener.dispose()}}),this.event=this.emitter.event}set input(R){this.inputEvent=R,this.listening&&(this.inputEventListener.dispose(),this.inputEventListener=R(this.emitter.fire,this.emitter))}dispose(){this.inputEventListener.dispose(),this.emitter.dispose()}},n.ValueWithChangeEvent=class{static const(R){return new L(R)}constructor(R){this._value=R,this._onDidChange=new k,this.onDidChange=this._onDidChange.event}get value(){return this._value}set value(R){R!==this._value&&(this._value=R,this._onDidChange.fire(void 0))}};class L{constructor(P){this.value=P,this.onDidChange=p.None}}},8841:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createSingleCallFunction=function(l,u){let y=this,h,_=!1;return function(){if(_)return h;if(_=!0,u)try{h=l.apply(y,arguments)}finally{u()}else h=l.apply(y,arguments);return h}}},4218:(a,n)=>{var l;Object.defineProperty(n,"__esModule",{value:!0}),n.Iterable=void 0,(function(u){function y(d){return d&&typeof d=="object"&&typeof d[Symbol.iterator]=="function"}u.is=y;let h=Object.freeze([]);function*_(d){yield d}u.empty=function(){return h},u.single=_,u.wrap=function(d){return y(d)?d:_(d)},u.from=function(d){return d||h},u.reverse=function*(d){for(let p=d.length-1;p>=0;p--)yield d[p]},u.isEmpty=function(d){return!d||d[Symbol.iterator]().next().done===!0},u.first=function(d){return d[Symbol.iterator]().next().value},u.some=function(d,p){let b=0;for(let c of d)if(p(c,b++))return!0;return!1},u.find=function(d,p){for(let b of d)if(p(b))return b},u.filter=function*(d,p){for(let b of d)p(b)&&(yield b)},u.map=function*(d,p){let b=0;for(let c of d)yield p(c,b++)},u.flatMap=function*(d,p){let b=0;for(let c of d)yield*p(c,b++)},u.concat=function*(...d){for(let p of d)yield*p},u.reduce=function(d,p,b){let c=b;for(let v of d)c=p(c,v);return c},u.slice=function*(d,p,b=d.length){for(p<0&&(p+=d.length),b<0?b+=d.length:b>d.length&&(b=d.length);p<b;p++)yield d[p]},u.consume=function(d,p=Number.POSITIVE_INFINITY){let b=[];if(p===0)return[b,d];let c=d[Symbol.iterator]();for(let v=0;v<p;v++){let g=c.next();if(g.done)return[b,u.empty()];b.push(g.value)}return[b,{[Symbol.iterator]:()=>c}]},u.asyncToArray=async function(d){let p=[];for await(let b of d)p.push(b);return Promise.resolve(p)}})(l||(n.Iterable=l={}))},7150:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DisposableMap=n.ImmortalReference=n.AsyncReferenceCollection=n.ReferenceCollection=n.SafeDisposable=n.RefCountedDisposable=n.MandatoryMutableDisposable=n.MutableDisposable=n.Disposable=n.DisposableStore=n.DisposableTracker=void 0,n.setDisposableTracker=function(O){p=O},n.trackDisposable=c,n.markAsDisposed=v,n.markAsSingleton=function(O){return p?.markAsSingleton(O),O},n.isDisposable=f,n.dispose=m,n.disposeIfDisposable=function(O){for(let L of O)f(L)&&L.dispose();return[]},n.combinedDisposable=function(...O){let L=w((()=>m(O)));return(function(R,P){if(p)for(let F of R)p.setParent(F,P)})(O,L),L},n.toDisposable=w,n.disposeOnReturn=function(O){let L=new C;try{O(L)}finally{L.dispose()}};let u=l(3058),y=l(9087),h=l(2608),_=l(8841),d=l(4218),p=null;class b{constructor(){this.livingDisposables=new Map}static{this.idx=0}getDisposableData(L){let R=this.livingDisposables.get(L);return R||(R={parent:null,source:null,isSingleton:!1,value:L,idx:b.idx++},this.livingDisposables.set(L,R)),R}trackDisposable(L){let R=this.getDisposableData(L);R.source||(R.source=new Error().stack)}setParent(L,R){this.getDisposableData(L).parent=R}markAsDisposed(L){this.livingDisposables.delete(L)}markAsSingleton(L){this.getDisposableData(L).isSingleton=!0}getRootParent(L,R){let P=R.get(L);if(P)return P;let F=L.parent?this.getRootParent(this.getDisposableData(L.parent),R):L;return R.set(L,F),F}getTrackedDisposables(){let L=new Map;return[...this.livingDisposables.entries()].filter((([,R])=>R.source!==null&&!this.getRootParent(R,L).isSingleton)).flatMap((([R])=>R))}computeLeakingDisposables(L=10,R){let P;if(R)P=R;else{let j=new Map,S=[...this.livingDisposables.values()].filter((E=>E.source!==null&&!this.getRootParent(E,j).isSingleton));if(S.length===0)return;let T=new Set(S.map((E=>E.value)));if(P=S.filter((E=>!(E.parent&&T.has(E.parent)))),P.length===0)throw new Error("There are cyclic diposable chains!")}if(!P)return;function F(j){let S=j.source.split(`
31
+ `).map((T=>T.trim().replace("at ",""))).filter((T=>T!==""));return(function(T,E){for(;T.length>0&&E.some((x=>typeof x=="string"?x===T[0]:T[0].match(x)));)T.shift()})(S,["Error",/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),S.reverse()}let V=new h.SetMap;for(let j of P){let S=F(j);for(let T=0;T<=S.length;T++)V.add(S.slice(0,T).join(`
32
+ `),j)}P.sort((0,u.compareBy)((j=>j.idx),u.numberComparator));let Z="",Y=0;for(let j of P.slice(0,L)){Y++;let S=F(j),T=[];for(let E=0;E<S.length;E++){let x=S[E];x=`(shared with ${V.get(S.slice(0,E+1).join(`
33
+ `)).size}/${P.length} leaks) at ${x}`;let M=V.get(S.slice(0,E).join(`
34
+ `)),N=(0,y.groupBy)([...M].map((U=>F(U)[E])),(U=>U));delete N[S[E]];for(let[U,z]of Object.entries(N))T.unshift(` - stacktraces of ${z.length} other leaks continue with ${U}`);T.unshift(x)}Z+=`
35
+
36
+
37
+ ==================== Leaking disposable ${Y}/${P.length}: ${j.value.constructor.name} ====================
38
+ ${T.join(`
39
+ `)}
40
+ ============================================================
41
+
42
+ `}return P.length>L&&(Z+=`
43
+
44
+
45
+ ... and ${P.length-L} more leaking disposables
46
+
47
+ `),{leaks:P,details:Z}}}function c(O){return p?.trackDisposable(O),O}function v(O){p?.markAsDisposed(O)}function g(O,L){p?.setParent(O,L)}function f(O){return typeof O=="object"&&O!==null&&typeof O.dispose=="function"&&O.dispose.length===0}function m(O){if(d.Iterable.is(O)){let L=[];for(let R of O)if(R)try{R.dispose()}catch(P){L.push(P)}if(L.length===1)throw L[0];if(L.length>1)throw new AggregateError(L,"Encountered errors while disposing of store");return Array.isArray(O)?[]:O}if(O)return O.dispose(),O}function w(O){let L=c({dispose:(0,_.createSingleCallFunction)((()=>{v(L),O()}))});return L}n.DisposableTracker=b;class C{static{this.DISABLE_DISPOSED_WARNING=!1}constructor(){this._toDispose=new Set,this._isDisposed=!1,c(this)}dispose(){this._isDisposed||(v(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{m(this._toDispose)}finally{this._toDispose.clear()}}add(L){if(!L)return L;if(L===this)throw new Error("Cannot register a disposable on itself!");return g(L,this),this._isDisposed?C.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(L),L}delete(L){if(L){if(L===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(L),L.dispose()}}deleteAndLeak(L){L&&this._toDispose.has(L)&&(this._toDispose.delete(L),g(L,null))}}n.DisposableStore=C;class k{static{this.None=Object.freeze({dispose(){}})}constructor(){this._store=new C,c(this),g(this._store,this)}dispose(){v(this),this._store.dispose()}_register(L){if(L===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(L)}}n.Disposable=k;class A{constructor(){this._isDisposed=!1,c(this)}get value(){return this._isDisposed?void 0:this._value}set value(L){this._isDisposed||L===this._value||(this._value?.dispose(),L&&g(L,this),this._value=L)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,v(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let L=this._value;return this._value=void 0,L&&g(L,null),L}}n.MutableDisposable=A,n.MandatoryMutableDisposable=class{constructor(O){this._disposable=new A,this._isDisposed=!1,this._disposable.value=O}get value(){return this._disposable.value}set value(O){this._isDisposed||O===this._disposable.value||(this._disposable.value=O)}dispose(){this._isDisposed=!0,this._disposable.dispose()}},n.RefCountedDisposable=class{constructor(O){this._disposable=O,this._counter=1}acquire(){return this._counter++,this}release(){return--this._counter==0&&this._disposable.dispose(),this}},n.SafeDisposable=class{constructor(){this.dispose=()=>{},this.unset=()=>{},this.isset=()=>!1,c(this)}set(O){let L=O;return this.unset=()=>L=void 0,this.isset=()=>L!==void 0,this.dispose=()=>{L&&(L(),L=void 0,v(this))},this}},n.ReferenceCollection=class{constructor(){this.references=new Map}acquire(O,...L){let R=this.references.get(O);R||(R={counter:0,object:this.createReferencedObject(O,...L)},this.references.set(O,R));let{object:P}=R,F=(0,_.createSingleCallFunction)((()=>{--R.counter==0&&(this.destroyReferencedObject(O,R.object),this.references.delete(O))}));return R.counter++,{object:P,dispose:F}}},n.AsyncReferenceCollection=class{constructor(O){this.referenceCollection=O}async acquire(O,...L){let R=this.referenceCollection.acquire(O,...L);try{return{object:await R.object,dispose:()=>R.dispose()}}catch(P){throw R.dispose(),P}}},n.ImmortalReference=class{constructor(O){this.object=O}dispose(){}};class D{constructor(){this._store=new Map,this._isDisposed=!1,c(this)}dispose(){v(this),this._isDisposed=!0,this.clearAndDisposeAll()}clearAndDisposeAll(){if(this._store.size)try{m(this._store.values())}finally{this._store.clear()}}has(L){return this._store.has(L)}get size(){return this._store.size}get(L){return this._store.get(L)}set(L,R,P=!1){this._isDisposed&&console.warn(new Error("Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!").stack),P||this._store.get(L)?.dispose(),this._store.set(L,R)}deleteAndDispose(L){this._store.get(L)?.dispose(),this._store.delete(L)}deleteAndLeak(L){let R=this._store.get(L);return this._store.delete(L),R}keys(){return this._store.keys()}values(){return this._store.values()}[Symbol.iterator](){return this._store[Symbol.iterator]()}}n.DisposableMap=D},6317:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.LinkedList=void 0;class l{static{this.Undefined=new l(void 0)}constructor(h){this.element=h,this.next=l.Undefined,this.prev=l.Undefined}}class u{constructor(){this._first=l.Undefined,this._last=l.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===l.Undefined}clear(){let h=this._first;for(;h!==l.Undefined;){let _=h.next;h.prev=l.Undefined,h.next=l.Undefined,h=_}this._first=l.Undefined,this._last=l.Undefined,this._size=0}unshift(h){return this._insert(h,!1)}push(h){return this._insert(h,!0)}_insert(h,_){let d=new l(h);if(this._first===l.Undefined)this._first=d,this._last=d;else if(_){let b=this._last;this._last=d,d.prev=b,b.next=d}else{let b=this._first;this._first=d,d.next=b,b.prev=d}this._size+=1;let p=!1;return()=>{p||(p=!0,this._remove(d))}}shift(){if(this._first!==l.Undefined){let h=this._first.element;return this._remove(this._first),h}}pop(){if(this._last!==l.Undefined){let h=this._last.element;return this._remove(this._last),h}}_remove(h){if(h.prev!==l.Undefined&&h.next!==l.Undefined){let _=h.prev;_.next=h.next,h.next.prev=_}else h.prev===l.Undefined&&h.next===l.Undefined?(this._first=l.Undefined,this._last=l.Undefined):h.next===l.Undefined?(this._last=this._last.prev,this._last.next=l.Undefined):h.prev===l.Undefined&&(this._first=this._first.next,this._first.prev=l.Undefined);this._size-=1}*[Symbol.iterator](){let h=this._first;for(;h!==l.Undefined;)yield h.element,h=h.next}}n.LinkedList=u},2608:(a,n)=>{var l;Object.defineProperty(n,"__esModule",{value:!0}),n.SetMap=n.BidirectionalMap=n.CounterSet=n.Touch=void 0,n.getOrSet=function(u,y,h){let _=u.get(y);return _===void 0&&(_=h,u.set(y,_)),_},n.mapToString=function(u){let y=[];return u.forEach(((h,_)=>{y.push(`${_} => ${h}`)})),`Map(${u.size}) {${y.join(", ")}}`},n.setToString=function(u){let y=[];return u.forEach((h=>{y.push(h)})),`Set(${u.size}) {${y.join(", ")}}`},n.mapsStrictEqualIgnoreOrder=function(u,y){if(u===y)return!0;if(u.size!==y.size)return!1;for(let[h,_]of u)if(!y.has(h)||y.get(h)!==_)return!1;for(let[h]of y)if(!u.has(h))return!1;return!0},(function(u){u[u.None=0]="None",u[u.AsOld=1]="AsOld",u[u.AsNew=2]="AsNew"})(l||(n.Touch=l={})),n.CounterSet=class{constructor(){this.map=new Map}add(u){return this.map.set(u,(this.map.get(u)||0)+1),this}delete(u){let y=this.map.get(u)||0;return y!==0&&(y--,y===0?this.map.delete(u):this.map.set(u,y),!0)}has(u){return this.map.has(u)}},n.BidirectionalMap=class{constructor(u){if(this._m1=new Map,this._m2=new Map,u)for(let[y,h]of u)this.set(y,h)}clear(){this._m1.clear(),this._m2.clear()}set(u,y){this._m1.set(u,y),this._m2.set(y,u)}get(u){return this._m1.get(u)}getKey(u){return this._m2.get(u)}delete(u){let y=this._m1.get(u);return y!==void 0&&(this._m1.delete(u),this._m2.delete(y),!0)}forEach(u,y){this._m1.forEach(((h,_)=>{u.call(y,h,_,this)}))}keys(){return this._m1.keys()}values(){return this._m1.values()}},n.SetMap=class{constructor(){this.map=new Map}add(u,y){let h=this.map.get(u);h||(h=new Set,this.map.set(u,h)),h.add(y)}delete(u,y){let h=this.map.get(u);h&&(h.delete(y),h.size===0&&this.map.delete(u))}forEach(u,y){let h=this.map.get(u);h&&h.forEach(y)}get(u){return this.map.get(u)||new Set}}},9725:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.StopWatch=void 0;let l=globalThis.performance&&typeof globalThis.performance.now=="function";class u{static create(h){return new u(h)}constructor(h){this._now=l&&h===!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}}n.StopWatch=u}},e={};function r(a){var n=e[a];if(n!==void 0)return n.exports;var l=e[a]={exports:{}};return t[a].call(l.exports,l,l.exports,r),l.exports}var s={};(()=>{var a=s;Object.defineProperty(a,"__esModule",{value:!0}),a.Terminal=void 0;let n=r(5101),l=r(6097),u=r(4335),y=r(5856),h=r(3027),_=r(7150),d=["cols","rows"];class p extends _.Disposable{constructor(c){super(),this._core=this._register(new y.Terminal(c)),this._addonManager=this._register(new h.AddonManager),this._publicOptions={...this._core.options};let v=f=>this._core.options[f],g=(f,m)=>{this._checkReadonlyOptions(f),this._core.options[f]=m};for(let f in this._core.options){Object.defineProperty(this._publicOptions,f,{get:()=>this._core.options[f],set:w=>{this._checkReadonlyOptions(f),this._core.options[f]=w}});let m={get:v.bind(this,f),set:g.bind(this,f)};Object.defineProperty(this._publicOptions,f,m)}}_checkReadonlyOptions(c){if(d.includes(c))throw new Error(`Option "${c}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.options.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 onLineFeed(){return this._core.onLineFeed}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get parser(){return this._checkProposedApi(),this._parser||(this._parser=new l.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new u.UnicodeApi(this._core)}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._checkProposedApi(),this._buffer||(this._buffer=this._register(new n.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let c=this._core.coreService.decPrivateModes,v="none";switch(this._core.coreMouseService.activeProtocol){case"X10":v="x10";break;case"VT200":v="vt200";break;case"DRAG":v="drag";break;case"ANY":v="any"}return{applicationCursorKeysMode:c.applicationCursorKeys,applicationKeypadMode:c.applicationKeypad,bracketedPasteMode:c.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:v,originMode:c.origin,reverseWraparoundMode:c.reverseWraparound,sendFocusMode:c.sendFocus,synchronizedOutputMode:c.synchronizedOutput,wraparoundMode:c.wraparound}}get options(){return this._publicOptions}set options(c){for(let v in c)this._publicOptions[v]=c[v]}input(c,v=!0){this._core.input(c,v)}resize(c,v){this._verifyIntegers(c,v),this._core.resize(c,v)}registerMarker(c=0){return this._checkProposedApi(),this._verifyIntegers(c),this._core.addMarker(c)}addMarker(c){return this.registerMarker(c)}dispose(){super.dispose()}scrollLines(c){this._verifyIntegers(c),this._core.scrollLines(c)}scrollPages(c){this._verifyIntegers(c),this._core.scrollPages(c)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(c){this._verifyIntegers(c),this._core.scrollToLine(c)}clear(){this._core.clear()}write(c,v){this._core.write(c,v)}writeln(c,v){this._core.write(c),this._core.write(`\r
48
+ `,v)}reset(){this._core.reset()}loadAddon(c){this._addonManager.loadAddon(this,c)}_verifyIntegers(...c){for(let v of c)if(v===1/0||isNaN(v)||v%1!=0)throw new Error("This API only accepts integers")}}a.Terminal=p})();var i=fh;for(var o in s)i[o]=s[o];s.__esModule&&Object.defineProperty(i,"__esModule",{value:!0})})()});import{realpathSync as Lg}from"fs";import{hostname as Rg}from"os";import{resolve as Eh}from"path";import{pathToFileURL as xh}from"url";var Bh="wss://unit00.top/djinn/relay";function zn(t=process.argv,e=process.env){let r=t[2],s=t.slice(3);switch(r){case"start":throw new Error("`djinn start` has been removed. Use `djinn new` instead.");case"pair":return{command:"pair",config:Uh(s)};case"new":return{command:"new",config:Dh(s,e)};case"attach":return{command:"attach",config:{sessionId:Oh(s[0],"attach <sessionId>")}};case"ls":return{command:"ls",config:{}};case"project":return{command:"project",config:Mh(s)};case"daemon":return{command:"daemon",config:{action:Nh(s[0])}};case"__worker":return{command:"__worker",config:Hh(s)};default:throw new Error(`Unknown command: ${r??"(none)"}. Try: djinn new | attach | ls | pair | project | daemon`)}}function Oh(t,e){if(!t)throw new Error(`missing argument: djinn ${e}`);return t}function Dh(t,e){let r=t.indexOf("--"),s=r>=0?t.slice(0,r):t,i=r>=0?t.slice(r+1):[],o=l=>{let u=s.indexOf(l);return u>=0?s[u+1]:void 0},a=o("--adapter")??"claude-code",n=s.includes("--detach")||s.includes("-d");return{adapterId:a,detach:n,aiCliArgs:i,cwd:process.cwd(),server:o("--server")??e.DJINN_SERVER_URL??Bh,invite:o("--invite")??e.DJINN_INVITE}}function Mh(t){let e=t[0];if(e!=="add"&&e!=="ls"&&e!=="rm")throw new Error("djinn project <add|ls|rm> [path]");if((e==="add"||e==="rm")&&!t[1])throw new Error(`djinn project ${e} <path>`);return e==="ls"?{action:e}:{action:e,path:t[1]}}function Nh(t){if(t==="run"||t==="run-detached"||t==="status"||t==="stop"||t==="install"||t==="uninstall")return t;throw new Error("djinn daemon <run|status|stop|install|uninstall>")}function Hh(t){let e=y=>{let h=t.indexOf(y);return h>=0?t[h+1]:void 0},r=t.indexOf("--"),s=r>=0?t.slice(r+1):[],i=e("--session-id"),o=e("--cwd"),a=e("--adapter"),n=e("--mode");if(!i||!o||!a||n!=="new"&&n!=="resume")throw new Error("djinn __worker requires --session-id --cwd --adapter --mode <new|resume>");let l=e("--origin");if(l!==void 0&&l!=="local"&&l!=="remote")throw new Error("djinn __worker --origin must be <local|remote>");return{sessionId:i,cwd:o,adapterId:a,mode:n,origin:l??"local",aiCliArgs:s}}function Uh(t){if(t.includes("--terminal")||t.includes("--no-png"))return{png:!1};let e=t.indexOf("--png");if(e!==-1){let r=t[e+1];if(r!==void 0&&!r.startsWith("--"))return{png:!0,pngPath:r}}return{png:!0}}import{existsSync as Fh,mkdirSync as jh,readFileSync as Wh,writeFileSync as qh}from"fs";import{homedir as $h}from"os";import{join as Vn}from"path";function Gn(){return Vn($h(),".djinn")}function Yn(t){return Vn(t,"identity.json")}function Ke(t){let e=Yn(t);if(!Fh(e))return;let r=Wh(e,"utf8");return JSON.parse(r)}function zh(t,e){jh(t,{recursive:!0,mode:448}),qh(Yn(t),JSON.stringify(e,null,2),{mode:384})}async function Jn(t){let e=Ke(t.dir);if(e)return e;if(!t.invite)throw new Error("No identity found. Pass --invite <CODE> (or DJINN_INVITE) to register this machine.");if(!t.serverUrl)throw new Error("First-run registration needs --server <url> (or DJINN_SERVER_URL).");let r=t.fetchImpl??fetch,s=ii(t.serverUrl),i=await r(`${s}/v1/register`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({invite_code:t.invite,label:t.label})});if(!i.ok)throw i.status===409?new Error("Registration failed: invite code is invalid or already used."):new Error(`Registration failed with status ${i.status}.`);let o=await i.json(),a={ownerId:o.owner_id,deviceId:o.device_id,token:o.token,serverUrl:o.server_url||t.serverUrl};return zh(t.dir,a),a}function ii(t){return t.replace(/^ws/,"http").replace(/\/$/,"")}var Zi=Re(nc(),1);import{join as hf}from"path";import{createHash as cf,randomBytes as K0,timingSafeEqual as X0}from"crypto";var lf="sha256:";function Ji(t){return`${lf}${cf("sha256").update(t).digest("hex")}`}function uf(t,e){return Buffer.from(JSON.stringify({v:1,url:t,code:e}),"utf8").toString("base64url")}var oc=t=>new Promise(e=>setTimeout(e,t));async function df(t){return Zi.default.toString(t,{type:"terminal",small:!1})}function ff(t,e){return Zi.default.toFile(e,t,{type:"png",width:600,margin:4,errorCorrectionLevel:"M"})}async function pf(t){let{platform:e}=process,[r,s]=e==="darwin"?["open",[t]]:e==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let{spawn:i}=await import("child_process");await new Promise(o=>{let a=i(r,s,{stdio:"ignore",detached:!0});a.on("error",()=>o()),a.on("spawn",()=>{a.unref(),o()})})}catch{}}async function ac(t){let e=t.out??(p=>process.stderr.write(`${p}
49
+ `)),r=t.fetchImpl??fetch,s=t.printQr??df,i=t.writeQrPng??ff,o=t.openFile??pf,a=t.pollIntervalMs??1500,n=Ke(t.dir);if(!n)return e("\u672A\u627E\u5230\u8EAB\u4EFD\u3002\u8BF7\u5148\u8FD0\u884C djinn start --invite <CODE> \u6CE8\u518C\u672C\u673A\u3002"),1;let l=ii(n.serverUrl),u;try{u=await r(`${l}/v1/pairing`,{method:"POST",headers:{authorization:`Bearer ${n.token}`}})}catch(p){return e(`\u53D1\u8D77\u914D\u5BF9\u5931\u8D25\uFF1A\u65E0\u6CD5\u8FDE\u63A5 ${l}\uFF08${p instanceof Error?p.message:String(p)}\uFF09`),1}if(!u.ok)return e(`\u53D1\u8D77\u914D\u5BF9\u5931\u8D25\uFF1AHTTP ${u.status}`),1;let{code:y,expires_at_ms:h}=await u.json(),_=uf(l,y);if(t.png){let p=t.pngPath??hf(process.cwd(),"djinn-pair-qr.png");await i(_,p);try{await o(p)}catch{}e(`\u4E8C\u7EF4\u7801\u5DF2\u4FDD\u5B58\u5230 ${p} \u5E76\u5C1D\u8BD5\u6253\u5F00\uFF0C\u8BF7\u7528\u624B\u673A djinn PWA \u626B\u7801\uFF0860 \u79D2\u5185\u6709\u6548\uFF09\u3002`),e("\uFF08\u82E5\u56FE\u7247\u6CA1\u81EA\u52A8\u6253\u5F00\uFF0C\u53EF\u626B\u63CF\u4E0B\u65B9\u7EC8\u7AEF\u4E8C\u7EF4\u7801\uFF0C\u6216\u7528 djinn pair --terminal \u53EA\u663E\u793A\u7EC8\u7AEF\u7801\u3002\uFF09"),e(await s(_))}else e(await s(_)),e("\u7528\u624B\u673A djinn PWA \u626B\u7801\uFF0860 \u79D2\u5185\u6709\u6548\uFF09\u3002");let d=encodeURIComponent(Ji(y));for(;;){if(Date.now()>=h)return e("\u914D\u5BF9\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C djinn pair\u3002"),1;let p;try{p=await r(`${l}/v1/pairing/${d}/status`,{headers:{authorization:`Bearer ${n.token}`}})}catch{await oc(a);continue}if(p.status===404)return e("\u914D\u5BF9\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C djinn pair\u3002"),1;if(!p.ok)return e(`\u8F6E\u8BE2\u914D\u5BF9\u72B6\u6001\u5931\u8D25\uFF1AHTTP ${p.status}`),1;let{status:b}=await p.json();if(b==="consumed")return e("\u2713 \u624B\u673A\u5DF2\u914D\u5BF9\u3002"),0;if(b==="expired")return e("\u914D\u5BF9\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C djinn pair\u3002"),1;await oc(a)}}import{spawn as Rf}from"child_process";import{connect as Bf}from"net";import{chmodSync as _f,existsSync as mf,lstatSync as gf,mkdirSync as vf,statSync as yf}from"fs";import{join as De}from"path";function tr(t){return De(t,"run")}function hs(t,e){return De(tr(t),`${e}.json`)}function Or(t,e){return De(tr(t),`${e}.sock`)}function rr(t){return De(t,"sessions")}function Ki(t,e){return De(rr(t),`${e}.json`)}function We(t){return De(t,"daemon.sock")}function Xi(t){return De(t,"daemon.pid")}function cc(t){return De(t,"daemon.log")}function lc(t,e){return De(tr(t),`${e}.log`)}function Qi(t){return De(t,"projects.json")}function nt(t){for(let e of[t,tr(t),rr(t)]){Dr(e),vf(e,{recursive:!0,mode:448}),_f(e,448);let r=yf(e).mode&511;if(r!==448)throw new Error(`state dir ${e} could not be tightened to 0700 (got ${r.toString(8)})`)}}function Dr(t){if(mf(t)&&gf(t).isSymbolicLink())throw new Error(`refusing to use ${t}: it is a symlink`)}function us(){return!0}import{spawn as Ef}from"child_process";import{openSync as xf,closeSync as kf}from"fs";import{randomUUID as Tf}from"crypto";import{readFileSync as hc,writeFileSync as bf,renameSync as wf,readdirSync as Sf,existsSync as uc,rmSync as Cf}from"fs";function dc(t,e){nt(t);let r=hs(t,e.sessionId),s=`${r}.${process.pid}.tmp`;bf(s,JSON.stringify(e,null,2),{mode:384}),wf(s,r)}function wt(t,e){let r=hs(t,e);if(uc(r))return JSON.parse(hc(r,"utf8"))}function en(t){let e=tr(t);return uc(e)?Sf(e).filter(r=>r.endsWith(".json")).map(r=>JSON.parse(hc(`${e}/${r}`,"utf8"))):[]}function ds(t,e){Cf(hs(t,e),{force:!0})}function St(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Af(t){let e=["__worker","--session-id",t.sessionId,"--cwd",t.cwd,"--adapter",t.adapterId,"--mode",t.mode,"--origin",t.origin];return t.aiCliArgs.length>0&&e.push("--",...t.aiCliArgs),e}var If=2500,Pf=50;function Lf(t){return new Promise(e=>setTimeout(e,t))}function sr(t,e){let r=[...process.execArgv],s=r.some(i=>i.includes("tsx"));return t.endsWith(".ts")&&!s&&r.push("--import","tsx"),[...r,t,...e]}async function tn(t,e){let r=e.sessionId??Tf(),s=Af({sessionId:r,cwd:e.cwd,adapterId:e.adapterId,mode:e.mode,origin:e.origin,aiCliArgs:e.aiCliArgs}),i=t.timeoutMs??If,o=Date.now(),a=xf(lc(t.dir,r),"a"),n;try{n=Ef(process.execPath,sr(t.entry,s),{detached:!0,stdio:["ignore",a,a],env:process.env}),n.unref()}finally{kf(a)}let l,u=y=>{l=y};n.on("exit",u);try{let y=o+i;for(;;){if(l!==void 0)throw new Error(`worker exited during startup (code ${l})`);let h=wt(t.dir,r);if(h&&h.pid===n.pid&&h.startedAtMs>=o)return{sessionId:r};if(Date.now()>=y)return process.stderr.write(`[djinn] forkWorker: worker ${r} readiness unverified after ${i}ms (best-effort, treating as started)
50
+ `),{sessionId:r};await Lf(Pf)}}finally{n.off("exit",u)}}function fc(t){return new Promise(e=>{let r=Bf(We(t)),s=i=>{r.destroy(),e(i)};r.on("connect",()=>r.write(JSON.stringify({cmd:"ping"})+`
51
+ `)),r.on("data",()=>s(!0)),r.on("error",()=>s(!1)),setTimeout(()=>s(!1),300)})}async function fs(t,e){if(await fc(t))return;Rf(process.execPath,sr(e,["daemon","run-detached"]),{detached:!0,stdio:"ignore",env:process.env}).unref();let s=Date.now()+5e3;for(;Date.now()<s;)if(await new Promise(i=>setTimeout(i,150)),await fc(t))return;throw new Error("daemon did not become ready in time")}import{createServer as C_,connect as E_}from"net";import{rmSync as Ts,writeFileSync as x_}from"fs";import{connect as $p}from"net";var B={};Lh(B,{BRAND:()=>np,DIRTY:()=>Ct,EMPTY_PATH:()=>Nf,INVALID:()=>K,NEVER:()=>qp,OK:()=>_e,ParseStatus:()=>fe,Schema:()=>re,ZodAny:()=>ct,ZodArray:()=>Ve,ZodBigInt:()=>xt,ZodBoolean:()=>kt,ZodBranded:()=>Nr,ZodCatch:()=>Nt,ZodDate:()=>Tt,ZodDefault:()=>Mt,ZodDiscriminatedUnion:()=>ms,ZodEffects:()=>Ee,ZodEnum:()=>Ot,ZodError:()=>ge,ZodFirstPartyTypeKind:()=>X,ZodFunction:()=>vs,ZodIntersection:()=>Lt,ZodIssueCode:()=>H,ZodLazy:()=>Rt,ZodLiteral:()=>Bt,ZodMap:()=>lr,ZodNaN:()=>ur,ZodNativeEnum:()=>Dt,ZodNever:()=>Pe,ZodNull:()=>It,ZodNullable:()=>He,ZodNumber:()=>Et,ZodObject:()=>ve,ZodOptional:()=>Se,ZodParsedType:()=>$,ZodPipeline:()=>Hr,ZodPromise:()=>lt,ZodReadonly:()=>Ht,ZodRecord:()=>gs,ZodSchema:()=>re,ZodSet:()=>hr,ZodString:()=>at,ZodSymbol:()=>ar,ZodTransformer:()=>Ee,ZodTuple:()=>Ne,ZodType:()=>re,ZodUndefined:()=>At,ZodUnion:()=>Pt,ZodUnknown:()=>ze,ZodVoid:()=>cr,addIssueToContext:()=>W,any:()=>pp,array:()=>vp,bigint:()=>lp,boolean:()=>Ec,coerce:()=>Wp,custom:()=>wc,date:()=>hp,datetimeRegex:()=>yc,defaultErrorMap:()=>qe,discriminatedUnion:()=>Sp,effect:()=>Op,enum:()=>Lp,function:()=>Ap,getErrorMap:()=>ir,getParsedType:()=>Me,instanceof:()=>ap,intersection:()=>Cp,isAborted:()=>ps,isAsync:()=>nr,isDirty:()=>_s,isValid:()=>ot,late:()=>op,lazy:()=>Ip,literal:()=>Pp,makeIssue:()=>Mr,map:()=>kp,nan:()=>cp,nativeEnum:()=>Rp,never:()=>mp,null:()=>fp,nullable:()=>Mp,number:()=>Cc,object:()=>yp,objectUtil:()=>rn,oboolean:()=>jp,onumber:()=>Fp,optional:()=>Dp,ostring:()=>Up,pipeline:()=>Hp,preprocess:()=>Np,promise:()=>Bp,quotelessJson:()=>Of,record:()=>xp,set:()=>Tp,setErrorMap:()=>Mf,strictObject:()=>bp,string:()=>Sc,symbol:()=>up,transformer:()=>Op,tuple:()=>Ep,undefined:()=>dp,union:()=>wp,unknown:()=>_p,util:()=>ie,void:()=>gp});var ie;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let o={};for(let a of i)o[a]=a;return o},t.getValidEnumValues=i=>{let o=t.objectKeys(i).filter(n=>typeof i[i[n]]!="number"),a={};for(let n of o)a[n]=i[n];return t.objectValues(a)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&o.push(a);return o},t.find=(i,o)=>{for(let a of i)if(o(a))return a},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function s(i,o=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}t.joinValues=s,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(ie||(ie={}));var rn;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(rn||(rn={}));var $=ie.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Me=t=>{switch(typeof t){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(t)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":return Array.isArray(t)?$.array:t===null?$.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?$.promise:typeof Map<"u"&&t instanceof Map?$.map:typeof Set<"u"&&t instanceof Set?$.set:typeof Date<"u"&&t instanceof Date?$.date:$.object;default:return $.unknown}};var H=ie.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Of=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ge=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},s={_errors:[]},i=o=>{for(let a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)s._errors.push(r(a));else{let n=s,l=0;for(;l<a.path.length;){let u=a.path[l];l===a.path.length-1?(n[u]=n[u]||{_errors:[]},n[u]._errors.push(r(a))):n[u]=n[u]||{_errors:[]},n=n[u],l++}}};return i(this),s}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ie.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},s=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else s.push(e(i));return{formErrors:s,fieldErrors:r}}get formErrors(){return this.flatten()}};ge.create=t=>new ge(t);var Df=(t,e)=>{let r;switch(t.code){case H.invalid_type:t.received===$.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case H.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ie.jsonStringifyReplacer)}`;break;case H.unrecognized_keys:r=`Unrecognized key(s) in object: ${ie.joinValues(t.keys,", ")}`;break;case H.invalid_union:r="Invalid input";break;case H.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ie.joinValues(t.options)}`;break;case H.invalid_enum_value:r=`Invalid enum value. Expected ${ie.joinValues(t.options)}, received '${t.received}'`;break;case H.invalid_arguments:r="Invalid function arguments";break;case H.invalid_return_type:r="Invalid function return type";break;case H.invalid_date:r="Invalid date";break;case H.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ie.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case H.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case H.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case H.custom:r="Invalid input";break;case H.invalid_intersection_types:r="Intersection results could not be merged";break;case H.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case H.not_finite:r="Number must be finite";break;default:r=e.defaultError,ie.assertNever(t)}return{message:r}},qe=Df;var pc=qe;function Mf(t){pc=t}function ir(){return pc}var Mr=t=>{let{data:e,path:r,errorMaps:s,issueData:i}=t,o=[...r,...i.path||[]],a={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let n="",l=s.filter(u=>!!u).slice().reverse();for(let u of l)n=u(a,{data:e,defaultError:n}).message;return{...i,path:o,message:n}},Nf=[];function W(t,e){let r=ir(),s=Mr({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===qe?void 0:qe].filter(i=>!!i)});t.common.issues.push(s)}var fe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let s=[];for(let i of r){if(i.status==="aborted")return K;i.status==="dirty"&&e.dirty(),s.push(i.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,r){let s=[];for(let i of r){let o=await i.key,a=await i.value;s.push({key:o,value:a})}return t.mergeObjectSync(e,s)}static mergeObjectSync(e,r){let s={};for(let i of r){let{key:o,value:a}=i;if(o.status==="aborted"||a.status==="aborted")return K;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(s[o.value]=a.value)}return{status:e.value,value:s}}},K=Object.freeze({status:"aborted"}),Ct=t=>({status:"dirty",value:t}),_e=t=>({status:"valid",value:t}),ps=t=>t.status==="aborted",_s=t=>t.status==="dirty",ot=t=>t.status==="valid",nr=t=>typeof Promise<"u"&&t instanceof Promise;var G;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(G||(G={}));var Ce=class{constructor(e,r,s,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=s,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},_c=(t,e)=>{if(ot(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new ge(t.common.issues);return this._error=r,this._error}}};function ee(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:s,description:i}=t;if(e&&(r||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(a,n)=>{let{message:l}=t;return a.code==="invalid_enum_value"?{message:l??n.defaultError}:typeof n.data>"u"?{message:l??s??n.defaultError}:a.code!=="invalid_type"?{message:n.defaultError}:{message:l??r??n.defaultError}},description:i}}var re=class{get description(){return this._def.description}_getType(e){return Me(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Me(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new fe,ctx:{common:e.parent.common,data:e.data,parsedType:Me(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(nr(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let s=this.safeParse(e,r);if(s.success)return s.data;throw s.error}safeParse(e,r){let s={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Me(e)},i=this._parseSync({data:e,path:s.path,parent:s});return _c(s,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Me(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:r});return ot(s)?{value:s.value}:{issues:r.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(s=>ot(s)?{value:s.value}:{issues:r.common.issues})}async parseAsync(e,r){let s=await this.safeParseAsync(e,r);if(s.success)return s.data;throw s.error}async safeParseAsync(e,r){let s={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Me(e)},i=this._parse({data:e,path:s.path,parent:s}),o=await(nr(i)?i:Promise.resolve(i));return _c(s,o)}refine(e,r){let s=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let a=e(i),n=()=>o.addIssue({code:H.custom,...s(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(n(),!1)):a?!0:(n(),!1)})}refinement(e,r){return this._refinement((s,i)=>e(s)?!0:(i.addIssue(typeof r=="function"?r(s,i):r),!1))}_refinement(e){return new Ee({schema:this,typeName:X.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Se.create(this,this._def)}nullable(){return He.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ve.create(this)}promise(){return lt.create(this,this._def)}or(e){return Pt.create([this,e],this._def)}and(e){return Lt.create(this,e,this._def)}transform(e){return new Ee({...ee(this._def),schema:this,typeName:X.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Mt({...ee(this._def),innerType:this,defaultValue:r,typeName:X.ZodDefault})}brand(){return new Nr({typeName:X.ZodBranded,type:this,...ee(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Nt({...ee(this._def),innerType:this,catchValue:r,typeName:X.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Hr.create(this,e)}readonly(){return Ht.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Hf=/^c[^\s-]{8,}$/i,Uf=/^[0-9a-z]+$/,Ff=/^[0-9A-HJKMNP-TV-Z]{26}$/i,jf=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Wf=/^[a-z0-9_-]{21}$/i,qf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,$f=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,zf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Vf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",sn,Gf=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Yf=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Jf=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Zf=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Kf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Xf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gc="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Qf=new RegExp(`^${gc}$`);function vc(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function ep(t){return new RegExp(`^${vc(t)}$`)}function yc(t){let e=`${gc}T${vc(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function tp(t,e){return!!((e==="v4"||!e)&&Gf.test(t)||(e==="v6"||!e)&&Jf.test(t))}function rp(t,e){if(!qf.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(s));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function sp(t,e){return!!((e==="v4"||!e)&&Yf.test(t)||(e==="v6"||!e)&&Zf.test(t))}var at=class t extends re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==$.string){let o=this._getOrReturnCtx(e);return W(o,{code:H.invalid_type,expected:$.string,received:o.parsedType}),K}let s=new fe,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),W(i,{code:H.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),s.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),W(i,{code:H.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),s.dirty());else if(o.kind==="length"){let a=e.data.length>o.value,n=e.data.length<o.value;(a||n)&&(i=this._getOrReturnCtx(e,i),a?W(i,{code:H.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):n&&W(i,{code:H.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),s.dirty())}else if(o.kind==="email")zf.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"email",code:H.invalid_string,message:o.message}),s.dirty());else if(o.kind==="emoji")sn||(sn=new RegExp(Vf,"u")),sn.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"emoji",code:H.invalid_string,message:o.message}),s.dirty());else if(o.kind==="uuid")jf.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"uuid",code:H.invalid_string,message:o.message}),s.dirty());else if(o.kind==="nanoid")Wf.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"nanoid",code:H.invalid_string,message:o.message}),s.dirty());else if(o.kind==="cuid")Hf.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"cuid",code:H.invalid_string,message:o.message}),s.dirty());else if(o.kind==="cuid2")Uf.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"cuid2",code:H.invalid_string,message:o.message}),s.dirty());else if(o.kind==="ulid")Ff.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"ulid",code:H.invalid_string,message:o.message}),s.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),W(i,{validation:"url",code:H.invalid_string,message:o.message}),s.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"regex",code:H.invalid_string,message:o.message}),s.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),W(i,{code:H.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),s.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),W(i,{code:H.invalid_string,validation:{startsWith:o.value},message:o.message}),s.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),W(i,{code:H.invalid_string,validation:{endsWith:o.value},message:o.message}),s.dirty()):o.kind==="datetime"?yc(o).test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{code:H.invalid_string,validation:"datetime",message:o.message}),s.dirty()):o.kind==="date"?Qf.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{code:H.invalid_string,validation:"date",message:o.message}),s.dirty()):o.kind==="time"?ep(o).test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{code:H.invalid_string,validation:"time",message:o.message}),s.dirty()):o.kind==="duration"?$f.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"duration",code:H.invalid_string,message:o.message}),s.dirty()):o.kind==="ip"?tp(e.data,o.version)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"ip",code:H.invalid_string,message:o.message}),s.dirty()):o.kind==="jwt"?rp(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"jwt",code:H.invalid_string,message:o.message}),s.dirty()):o.kind==="cidr"?sp(e.data,o.version)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"cidr",code:H.invalid_string,message:o.message}),s.dirty()):o.kind==="base64"?Kf.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"base64",code:H.invalid_string,message:o.message}),s.dirty()):o.kind==="base64url"?Xf.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"base64url",code:H.invalid_string,message:o.message}),s.dirty()):ie.assertNever(o);return{status:s.value,value:e.data}}_regex(e,r,s){return this.refinement(i=>e.test(i),{validation:r,code:H.invalid_string,...G.errToObj(s)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...G.errToObj(e)})}url(e){return this._addCheck({kind:"url",...G.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...G.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...G.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...G.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...G.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...G.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...G.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...G.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...G.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...G.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...G.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...G.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...G.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...G.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...G.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...G.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...G.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...G.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...G.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...G.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...G.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...G.errToObj(r)})}nonempty(e){return this.min(1,G.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};at.create=t=>new at({checks:[],typeName:X.ZodString,coerce:t?.coerce??!1,...ee(t)});function ip(t,e){let r=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,i=r>s?r:s,o=Number.parseInt(t.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return o%a/10**i}var Et=class t extends re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==$.number){let o=this._getOrReturnCtx(e);return W(o,{code:H.invalid_type,expected:$.number,received:o.parsedType}),K}let s,i=new fe;for(let o of this._def.checks)o.kind==="int"?ie.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{code:H.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(s=this._getOrReturnCtx(e,s),W(s,{code:H.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(s=this._getOrReturnCtx(e,s),W(s,{code:H.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?ip(e.data,o.value)!==0&&(s=this._getOrReturnCtx(e,s),W(s,{code:H.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{code:H.not_finite,message:o.message}),i.dirty()):ie.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,s,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:G.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:G.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:G.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ie.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(r===null||s.value>r)&&(r=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Et.create=t=>new Et({checks:[],typeName:X.ZodNumber,coerce:t?.coerce||!1,...ee(t)});var xt=class t extends re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==$.bigint)return this._getInvalidInput(e);let s,i=new fe;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(s=this._getOrReturnCtx(e,s),W(s,{code:H.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(s=this._getOrReturnCtx(e,s),W(s,{code:H.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),W(s,{code:H.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):ie.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return W(r,{code:H.invalid_type,expected:$.bigint,received:r.parsedType}),K}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,s,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:G.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};xt.create=t=>new xt({checks:[],typeName:X.ZodBigInt,coerce:t?.coerce??!1,...ee(t)});var kt=class extends re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==$.boolean){let s=this._getOrReturnCtx(e);return W(s,{code:H.invalid_type,expected:$.boolean,received:s.parsedType}),K}return _e(e.data)}};kt.create=t=>new kt({typeName:X.ZodBoolean,coerce:t?.coerce||!1,...ee(t)});var Tt=class t extends re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==$.date){let o=this._getOrReturnCtx(e);return W(o,{code:H.invalid_type,expected:$.date,received:o.parsedType}),K}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return W(o,{code:H.invalid_date}),K}let s=new fe,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),W(i,{code:H.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),s.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),W(i,{code:H.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),s.dirty()):ie.assertNever(o);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:G.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:G.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Tt.create=t=>new Tt({checks:[],coerce:t?.coerce||!1,typeName:X.ZodDate,...ee(t)});var ar=class extends re{_parse(e){if(this._getType(e)!==$.symbol){let s=this._getOrReturnCtx(e);return W(s,{code:H.invalid_type,expected:$.symbol,received:s.parsedType}),K}return _e(e.data)}};ar.create=t=>new ar({typeName:X.ZodSymbol,...ee(t)});var At=class extends re{_parse(e){if(this._getType(e)!==$.undefined){let s=this._getOrReturnCtx(e);return W(s,{code:H.invalid_type,expected:$.undefined,received:s.parsedType}),K}return _e(e.data)}};At.create=t=>new At({typeName:X.ZodUndefined,...ee(t)});var It=class extends re{_parse(e){if(this._getType(e)!==$.null){let s=this._getOrReturnCtx(e);return W(s,{code:H.invalid_type,expected:$.null,received:s.parsedType}),K}return _e(e.data)}};It.create=t=>new It({typeName:X.ZodNull,...ee(t)});var ct=class extends re{constructor(){super(...arguments),this._any=!0}_parse(e){return _e(e.data)}};ct.create=t=>new ct({typeName:X.ZodAny,...ee(t)});var ze=class extends re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _e(e.data)}};ze.create=t=>new ze({typeName:X.ZodUnknown,...ee(t)});var Pe=class extends re{_parse(e){let r=this._getOrReturnCtx(e);return W(r,{code:H.invalid_type,expected:$.never,received:r.parsedType}),K}};Pe.create=t=>new Pe({typeName:X.ZodNever,...ee(t)});var cr=class extends re{_parse(e){if(this._getType(e)!==$.undefined){let s=this._getOrReturnCtx(e);return W(s,{code:H.invalid_type,expected:$.void,received:s.parsedType}),K}return _e(e.data)}};cr.create=t=>new cr({typeName:X.ZodVoid,...ee(t)});var Ve=class t extends re{_parse(e){let{ctx:r,status:s}=this._processInputParams(e),i=this._def;if(r.parsedType!==$.array)return W(r,{code:H.invalid_type,expected:$.array,received:r.parsedType}),K;if(i.exactLength!==null){let a=r.data.length>i.exactLength.value,n=r.data.length<i.exactLength.value;(a||n)&&(W(r,{code:a?H.too_big:H.too_small,minimum:n?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),s.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(W(r,{code:H.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),s.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(W(r,{code:H.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),s.dirty()),r.common.async)return Promise.all([...r.data].map((a,n)=>i.type._parseAsync(new Ce(r,a,r.path,n)))).then(a=>fe.mergeArray(s,a));let o=[...r.data].map((a,n)=>i.type._parseSync(new Ce(r,a,r.path,n)));return fe.mergeArray(s,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:G.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:G.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:G.toString(r)}})}nonempty(e){return this.min(1,e)}};Ve.create=(t,e)=>new Ve({type:t,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...ee(e)});function or(t){if(t instanceof ve){let e={};for(let r in t.shape){let s=t.shape[r];e[r]=Se.create(or(s))}return new ve({...t._def,shape:()=>e})}else return t instanceof Ve?new Ve({...t._def,type:or(t.element)}):t instanceof Se?Se.create(or(t.unwrap())):t instanceof He?He.create(or(t.unwrap())):t instanceof Ne?Ne.create(t.items.map(e=>or(e))):t}var ve=class t extends re{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ie.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==$.object){let u=this._getOrReturnCtx(e);return W(u,{code:H.invalid_type,expected:$.object,received:u.parsedType}),K}let{status:s,ctx:i}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),n=[];if(!(this._def.catchall instanceof Pe&&this._def.unknownKeys==="strip"))for(let u in i.data)a.includes(u)||n.push(u);let l=[];for(let u of a){let y=o[u],h=i.data[u];l.push({key:{status:"valid",value:u},value:y._parse(new Ce(i,h,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Pe){let u=this._def.unknownKeys;if(u==="passthrough")for(let y of n)l.push({key:{status:"valid",value:y},value:{status:"valid",value:i.data[y]}});else if(u==="strict")n.length>0&&(W(i,{code:H.unrecognized_keys,keys:n}),s.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let y of n){let h=i.data[y];l.push({key:{status:"valid",value:y},value:u._parse(new Ce(i,h,i.path,y)),alwaysSet:y in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let y of l){let h=await y.key,_=await y.value;u.push({key:h,value:_,alwaysSet:y.alwaysSet})}return u}).then(u=>fe.mergeObjectSync(s,u)):fe.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return G.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,s)=>{let i=this._def.errorMap?.(r,s).message??s.defaultError;return r.code==="unrecognized_keys"?{message:G.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:X.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let s of ie.objectKeys(e))e[s]&&this.shape[s]&&(r[s]=this.shape[s]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let s of ie.objectKeys(this.shape))e[s]||(r[s]=this.shape[s]);return new t({...this._def,shape:()=>r})}deepPartial(){return or(this)}partial(e){let r={};for(let s of ie.objectKeys(this.shape)){let i=this.shape[s];e&&!e[s]?r[s]=i:r[s]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let s of ie.objectKeys(this.shape))if(e&&!e[s])r[s]=this.shape[s];else{let o=this.shape[s];for(;o instanceof Se;)o=o._def.innerType;r[s]=o}return new t({...this._def,shape:()=>r})}keyof(){return bc(ie.objectKeys(this.shape))}};ve.create=(t,e)=>new ve({shape:()=>t,unknownKeys:"strip",catchall:Pe.create(),typeName:X.ZodObject,...ee(e)});ve.strictCreate=(t,e)=>new ve({shape:()=>t,unknownKeys:"strict",catchall:Pe.create(),typeName:X.ZodObject,...ee(e)});ve.lazycreate=(t,e)=>new ve({shape:t,unknownKeys:"strip",catchall:Pe.create(),typeName:X.ZodObject,...ee(e)});var Pt=class extends re{_parse(e){let{ctx:r}=this._processInputParams(e),s=this._def.options;function i(o){for(let n of o)if(n.result.status==="valid")return n.result;for(let n of o)if(n.result.status==="dirty")return r.common.issues.push(...n.ctx.common.issues),n.result;let a=o.map(n=>new ge(n.ctx.common.issues));return W(r,{code:H.invalid_union,unionErrors:a}),K}if(r.common.async)return Promise.all(s.map(async o=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(i);{let o,a=[];for(let l of s){let u={...r,common:{...r.common,issues:[]},parent:null},y=l._parseSync({data:r.data,path:r.path,parent:u});if(y.status==="valid")return y;y.status==="dirty"&&!o&&(o={result:y,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let n=a.map(l=>new ge(l));return W(r,{code:H.invalid_union,unionErrors:n}),K}}get options(){return this._def.options}};Pt.create=(t,e)=>new Pt({options:t,typeName:X.ZodUnion,...ee(e)});var $e=t=>t instanceof Rt?$e(t.schema):t instanceof Ee?$e(t.innerType()):t instanceof Bt?[t.value]:t instanceof Ot?t.options:t instanceof Dt?ie.objectValues(t.enum):t instanceof Mt?$e(t._def.innerType):t instanceof At?[void 0]:t instanceof It?[null]:t instanceof Se?[void 0,...$e(t.unwrap())]:t instanceof He?[null,...$e(t.unwrap())]:t instanceof Nr||t instanceof Ht?$e(t.unwrap()):t instanceof Nt?$e(t._def.innerType):[],ms=class t extends re{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.object)return W(r,{code:H.invalid_type,expected:$.object,received:r.parsedType}),K;let s=this.discriminator,i=r.data[s],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(W(r,{code:H.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),K)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,s){let i=new Map;for(let o of r){let a=$e(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let n of a){if(i.has(n))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(n)}`);i.set(n,o)}}return new t({typeName:X.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...ee(s)})}};function nn(t,e){let r=Me(t),s=Me(e);if(t===e)return{valid:!0,data:t};if(r===$.object&&s===$.object){let i=ie.objectKeys(e),o=ie.objectKeys(t).filter(n=>i.indexOf(n)!==-1),a={...t,...e};for(let n of o){let l=nn(t[n],e[n]);if(!l.valid)return{valid:!1};a[n]=l.data}return{valid:!0,data:a}}else if(r===$.array&&s===$.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let o=0;o<t.length;o++){let a=t[o],n=e[o],l=nn(a,n);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return r===$.date&&s===$.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Lt=class extends re{_parse(e){let{status:r,ctx:s}=this._processInputParams(e),i=(o,a)=>{if(ps(o)||ps(a))return K;let n=nn(o.value,a.value);return n.valid?((_s(o)||_s(a))&&r.dirty(),{status:r.value,value:n.data}):(W(s,{code:H.invalid_intersection_types}),K)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([o,a])=>i(o,a)):i(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};Lt.create=(t,e,r)=>new Lt({left:t,right:e,typeName:X.ZodIntersection,...ee(r)});var Ne=class t extends re{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==$.array)return W(s,{code:H.invalid_type,expected:$.array,received:s.parsedType}),K;if(s.data.length<this._def.items.length)return W(s,{code:H.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),K;!this._def.rest&&s.data.length>this._def.items.length&&(W(s,{code:H.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...s.data].map((a,n)=>{let l=this._def.items[n]||this._def.rest;return l?l._parse(new Ce(s,a,s.path,n)):null}).filter(a=>!!a);return s.common.async?Promise.all(o).then(a=>fe.mergeArray(r,a)):fe.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Ne.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ne({items:t,typeName:X.ZodTuple,rest:null,...ee(e)})};var gs=class t extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==$.object)return W(s,{code:H.invalid_type,expected:$.object,received:s.parsedType}),K;let i=[],o=this._def.keyType,a=this._def.valueType;for(let n in s.data)i.push({key:o._parse(new Ce(s,n,s.path,n)),value:a._parse(new Ce(s,s.data[n],s.path,n)),alwaysSet:n in s.data});return s.common.async?fe.mergeObjectAsync(r,i):fe.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,s){return r instanceof re?new t({keyType:e,valueType:r,typeName:X.ZodRecord,...ee(s)}):new t({keyType:at.create(),valueType:e,typeName:X.ZodRecord,...ee(r)})}},lr=class extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==$.map)return W(s,{code:H.invalid_type,expected:$.map,received:s.parsedType}),K;let i=this._def.keyType,o=this._def.valueType,a=[...s.data.entries()].map(([n,l],u)=>({key:i._parse(new Ce(s,n,s.path,[u,"key"])),value:o._parse(new Ce(s,l,s.path,[u,"value"]))}));if(s.common.async){let n=new Map;return Promise.resolve().then(async()=>{for(let l of a){let u=await l.key,y=await l.value;if(u.status==="aborted"||y.status==="aborted")return K;(u.status==="dirty"||y.status==="dirty")&&r.dirty(),n.set(u.value,y.value)}return{status:r.value,value:n}})}else{let n=new Map;for(let l of a){let u=l.key,y=l.value;if(u.status==="aborted"||y.status==="aborted")return K;(u.status==="dirty"||y.status==="dirty")&&r.dirty(),n.set(u.value,y.value)}return{status:r.value,value:n}}}};lr.create=(t,e,r)=>new lr({valueType:e,keyType:t,typeName:X.ZodMap,...ee(r)});var hr=class t extends re{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==$.set)return W(s,{code:H.invalid_type,expected:$.set,received:s.parsedType}),K;let i=this._def;i.minSize!==null&&s.data.size<i.minSize.value&&(W(s,{code:H.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&s.data.size>i.maxSize.value&&(W(s,{code:H.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function a(l){let u=new Set;for(let y of l){if(y.status==="aborted")return K;y.status==="dirty"&&r.dirty(),u.add(y.value)}return{status:r.value,value:u}}let n=[...s.data.values()].map((l,u)=>o._parse(new Ce(s,l,s.path,u)));return s.common.async?Promise.all(n).then(l=>a(l)):a(n)}min(e,r){return new t({...this._def,minSize:{value:e,message:G.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:G.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};hr.create=(t,e)=>new hr({valueType:t,minSize:null,maxSize:null,typeName:X.ZodSet,...ee(e)});var vs=class t extends re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.function)return W(r,{code:H.invalid_type,expected:$.function,received:r.parsedType}),K;function s(n,l){return Mr({data:n,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ir(),qe].filter(u=>!!u),issueData:{code:H.invalid_arguments,argumentsError:l}})}function i(n,l){return Mr({data:n,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ir(),qe].filter(u=>!!u),issueData:{code:H.invalid_return_type,returnTypeError:l}})}let o={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof lt){let n=this;return _e(async function(...l){let u=new ge([]),y=await n._def.args.parseAsync(l,o).catch(d=>{throw u.addIssue(s(l,d)),u}),h=await Reflect.apply(a,this,y);return await n._def.returns._def.type.parseAsync(h,o).catch(d=>{throw u.addIssue(i(h,d)),u})})}else{let n=this;return _e(function(...l){let u=n._def.args.safeParse(l,o);if(!u.success)throw new ge([s(l,u.error)]);let y=Reflect.apply(a,this,u.data),h=n._def.returns.safeParse(y,o);if(!h.success)throw new ge([i(y,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Ne.create(e).rest(ze.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,s){return new t({args:e||Ne.create([]).rest(ze.create()),returns:r||ze.create(),typeName:X.ZodFunction,...ee(s)})}},Rt=class extends re{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Rt.create=(t,e)=>new Rt({getter:t,typeName:X.ZodLazy,...ee(e)});var Bt=class extends re{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return W(r,{received:r.data,code:H.invalid_literal,expected:this._def.value}),K}return{status:"valid",value:e.data}}get value(){return this._def.value}};Bt.create=(t,e)=>new Bt({value:t,typeName:X.ZodLiteral,...ee(e)});function bc(t,e){return new Ot({values:t,typeName:X.ZodEnum,...ee(e)})}var Ot=class t extends re{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),s=this._def.values;return W(r,{expected:ie.joinValues(s),received:r.parsedType,code:H.invalid_type}),K}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),s=this._def.values;return W(r,{received:r.data,code:H.invalid_enum_value,options:s}),K}return _e(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(s=>!e.includes(s)),{...this._def,...r})}};Ot.create=bc;var Dt=class extends re{_parse(e){let r=ie.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==$.string&&s.parsedType!==$.number){let i=ie.objectValues(r);return W(s,{expected:ie.joinValues(i),received:s.parsedType,code:H.invalid_type}),K}if(this._cache||(this._cache=new Set(ie.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=ie.objectValues(r);return W(s,{received:s.data,code:H.invalid_enum_value,options:i}),K}return _e(e.data)}get enum(){return this._def.values}};Dt.create=(t,e)=>new Dt({values:t,typeName:X.ZodNativeEnum,...ee(e)});var lt=class extends re{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.promise&&r.common.async===!1)return W(r,{code:H.invalid_type,expected:$.promise,received:r.parsedType}),K;let s=r.parsedType===$.promise?r.data:Promise.resolve(r.data);return _e(s.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};lt.create=(t,e)=>new lt({type:t,typeName:X.ZodPromise,...ee(e)});var Ee=class extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:s}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:a=>{W(s,a),a.fatal?r.abort():r.dirty()},get path(){return s.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let a=i.transform(s.data,o);if(s.common.async)return Promise.resolve(a).then(async n=>{if(r.value==="aborted")return K;let l=await this._def.schema._parseAsync({data:n,path:s.path,parent:s});return l.status==="aborted"?K:l.status==="dirty"?Ct(l.value):r.value==="dirty"?Ct(l.value):l});{if(r.value==="aborted")return K;let n=this._def.schema._parseSync({data:a,path:s.path,parent:s});return n.status==="aborted"?K:n.status==="dirty"?Ct(n.value):r.value==="dirty"?Ct(n.value):n}}if(i.type==="refinement"){let a=n=>{let l=i.refinement(n,o);if(s.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return n};if(s.common.async===!1){let n=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?K:(n.status==="dirty"&&r.dirty(),a(n.value),{status:r.value,value:n.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(n=>n.status==="aborted"?K:(n.status==="dirty"&&r.dirty(),a(n.value).then(()=>({status:r.value,value:n.value}))))}if(i.type==="transform")if(s.common.async===!1){let a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!ot(a))return K;let n=i.transform(a.value,o);if(n instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:n}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>ot(a)?Promise.resolve(i.transform(a.value,o)).then(n=>({status:r.value,value:n})):K);ie.assertNever(i)}};Ee.create=(t,e,r)=>new Ee({schema:t,typeName:X.ZodEffects,effect:e,...ee(r)});Ee.createWithPreprocess=(t,e,r)=>new Ee({schema:e,effect:{type:"preprocess",transform:t},typeName:X.ZodEffects,...ee(r)});var Se=class extends re{_parse(e){return this._getType(e)===$.undefined?_e(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Se.create=(t,e)=>new Se({innerType:t,typeName:X.ZodOptional,...ee(e)});var He=class extends re{_parse(e){return this._getType(e)===$.null?_e(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};He.create=(t,e)=>new He({innerType:t,typeName:X.ZodNullable,...ee(e)});var Mt=class extends re{_parse(e){let{ctx:r}=this._processInputParams(e),s=r.data;return r.parsedType===$.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Mt.create=(t,e)=>new Mt({innerType:t,typeName:X.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ee(e)});var Nt=class extends re{_parse(e){let{ctx:r}=this._processInputParams(e),s={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return nr(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ge(s.common.issues)},input:s.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ge(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};Nt.create=(t,e)=>new Nt({innerType:t,typeName:X.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ee(e)});var ur=class extends re{_parse(e){if(this._getType(e)!==$.nan){let s=this._getOrReturnCtx(e);return W(s,{code:H.invalid_type,expected:$.nan,received:s.parsedType}),K}return{status:"valid",value:e.data}}};ur.create=t=>new ur({typeName:X.ZodNaN,...ee(t)});var np=Symbol("zod_brand"),Nr=class extends re{_parse(e){let{ctx:r}=this._processInputParams(e),s=r.data;return this._def.type._parse({data:s,path:r.path,parent:r})}unwrap(){return this._def.type}},Hr=class t extends re{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?K:o.status==="dirty"?(r.dirty(),Ct(o.value)):this._def.out._parseAsync({data:o.value,path:s.path,parent:s})})();{let i=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?K:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:s.path,parent:s})}}static create(e,r){return new t({in:e,out:r,typeName:X.ZodPipeline})}},Ht=class extends re{_parse(e){let r=this._def.innerType._parse(e),s=i=>(ot(i)&&(i.value=Object.freeze(i.value)),i);return nr(r)?r.then(i=>s(i)):s(r)}unwrap(){return this._def.innerType}};Ht.create=(t,e)=>new Ht({innerType:t,typeName:X.ZodReadonly,...ee(e)});function mc(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function wc(t,e={},r){return t?ct.create().superRefine((s,i)=>{let o=t(s);if(o instanceof Promise)return o.then(a=>{if(!a){let n=mc(e,s),l=n.fatal??r??!0;i.addIssue({code:"custom",...n,fatal:l})}});if(!o){let a=mc(e,s),n=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:n})}}):ct.create()}var op={object:ve.lazycreate},X;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(X||(X={}));var ap=(t,e={message:`Input not instance of ${t.name}`})=>wc(r=>r instanceof t,e),Sc=at.create,Cc=Et.create,cp=ur.create,lp=xt.create,Ec=kt.create,hp=Tt.create,up=ar.create,dp=At.create,fp=It.create,pp=ct.create,_p=ze.create,mp=Pe.create,gp=cr.create,vp=Ve.create,yp=ve.create,bp=ve.strictCreate,wp=Pt.create,Sp=ms.create,Cp=Lt.create,Ep=Ne.create,xp=gs.create,kp=lr.create,Tp=hr.create,Ap=vs.create,Ip=Rt.create,Pp=Bt.create,Lp=Ot.create,Rp=Dt.create,Bp=lt.create,Op=Ee.create,Dp=Se.create,Mp=He.create,Np=Ee.createWithPreprocess,Hp=Hr.create,Up=()=>Sc().optional(),Fp=()=>Cc().optional(),jp=()=>Ec().optional(),Wp={string:(t=>at.create({...t,coerce:!0})),number:(t=>Et.create({...t,coerce:!0})),boolean:(t=>kt.create({...t,coerce:!0})),bigint:(t=>xt.create({...t,coerce:!0})),date:(t=>Tt.create({...t,coerce:!0}))};var qp=K;var xc=B.discriminatedUnion("cmd",[B.object({cmd:B.literal("ping")}).strict(),B.object({cmd:B.literal("new"),adapterId:B.string(),cwd:B.string(),aiCliArgs:B.array(B.string())}).strict(),B.object({cmd:B.literal("ls")}).strict(),B.object({cmd:B.literal("attach-info"),sessionId:B.string()}).strict(),B.object({cmd:B.literal("status")}).strict(),B.object({cmd:B.literal("stop")}).strict(),B.object({cmd:B.literal("project"),action:B.enum(["add","ls","rm"]),path:B.string().optional()}).strict()]),zp=B.union([B.object({ok:B.literal(!0),data:B.unknown().optional()}).strict(),B.object({ok:B.literal(!1),code:B.string(),message:B.string()}).strict()]);function ht(t,e,r=5e3){return new Promise((s,i)=>{let o=$p(We(t)),a="",n=setTimeout(()=>{o.destroy(),i(new Error("daemon command timeout"))},r);o.on("connect",()=>o.write(JSON.stringify(e)+`
52
+ `)),o.on("data",l=>{a+=l.toString();let u=a.indexOf(`
53
+ `);if(u>=0){clearTimeout(n),o.destroy();try{s(zp.parse(JSON.parse(a.slice(0,u))))}catch(y){i(y)}}}),o.on("error",l=>{clearTimeout(n),i(l)})})}import{readFileSync as kc,writeFileSync as Vp,renameSync as Gp,readdirSync as Yp,existsSync as Tc}from"fs";function ys(t,e){nt(t);let r=Ki(t,e.sessionId),s=`${r}.${process.pid}.tmp`;Vp(s,JSON.stringify(e,null,2),{mode:384}),Gp(s,r)}function ut(t,e){let r=Ki(t,e);if(Tc(r))return JSON.parse(kc(r,"utf8"))}function Ac(t){let e=rr(t);return Tc(e)?Yp(e).filter(r=>r.endsWith(".json")).map(r=>JSON.parse(kc(`${e}/${r}`,"utf8"))):[]}import{readFileSync as Jp,writeFileSync as Zp,renameSync as Kp,existsSync as Xp,realpathSync as Qp}from"fs";import{resolve as e_}from"path";function on(t){let e=e_(t);try{return Qp(e)}catch{return e}}function bs(t){let e=Qi(t);return Xp(e)?JSON.parse(Jp(e,"utf8")).projects??[]:[]}function Ic(t,e){nt(t);let r=Qi(t),s=`${r}.${process.pid}.tmp`;Zp(s,JSON.stringify({projects:e},null,2),{mode:384}),Kp(s,r)}function ws(t){return bs(t)}function Pc(t,e,r){let s=on(e),i=bs(t);i.some(o=>o.path===s)||Ic(t,[...i,{path:s,label:r}])}function Lc(t,e){let r=on(e);Ic(t,bs(t).filter(s=>s.path!==r))}function an(t,e){let r=on(e);return bs(t).some(s=>s.path===r)}import{spawn as t_}from"child_process";import{createHash as r_}from"crypto";import{constants as s_}from"fs";import{access as i_}from"fs/promises";import{delimiter as n_,join as o_}from"path";var Rc=1e3,a_=50;async function cn(t){await new Promise(e=>setTimeout(e,t))}async function Ss(t){for(let e of(process.env.PATH??"").split(n_)){if(!e)continue;let r=o_(e,t);try{return await i_(r,s_.X_OK),r}catch{}}}function Cs(t,e,r){let s=r.replace(/\u001b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"").replace(/\s+/g," ").trim(),i=r_("sha256").update(`${t}:${e}:${s}`).digest("hex");return`appr_${t}_${i.slice(0,16)}`}function dr(t){return{type:"terminal.output",stream:t.stream??"pty",text:t.text}}function ln(t){let e=t.replace(/(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),r=e.trimEnd();if(!r)return{kind:"none"};let s=r.split(`
54
+ `),i=s[s.length-1].trim(),o=/^[>❯›\$]\s*$/.test(i),a=s.filter(u=>u.trim().length>0).length>3,n=s.slice(0,-1).some(u=>/^\s*>/.test(u)||/^(diff|npm|Installing|Compiling)/i.test(u.trim()));return o&&!a&&!n?{kind:"waiting_input",reason:"prompt",confidence:"high"}:/how can i help/i.test(e)&&o?{kind:"waiting_input",reason:"prompt",confidence:"high"}:{kind:"none"}}function Es(t){return/\b(no|not|without)\s+(approval|permission)\b/i.test(t)||/\bnot required\b/i.test(t)}function xs(t){let e=t.replace(/\s+/g," ").trim(),r=/\b(permission|approval)\b/i.test(e),s=/\bneeds (?:your )?permission to\b.+\ballow\?/i.test(e),i=/\bdo you want to allow\b/i.test(e),o=/\brequesting approval before\b.+\bapprove\?/i.test(e);if(r&&(s||i||o))return!0;let a=c_(t).replace(/\s+/g,"").toLowerCase(),n=a.includes("doyouwanttoproceed?"),l=/\d+\.yes/.test(a),u=/\d+\.no/.test(a);return!!(n&&l&&u)}function c_(t){return t.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\x1b[@-Z\\-_]/g,"")}function ks(t,e={}){let r=t_(t,e.args??[],{cwd:e.cwd,env:e.env,stdio:["pipe","pipe","pipe"]}),s=[],i=[],o=!1,a=l=>{s.push(l),s.length>Rc&&s.splice(0,s.length-Rc)},n=(l,u)=>{o||(o=!0,a({type:"session.status",status:"exited",exitCode:l,signal:u,message:`Process exited with code ${l??"null"}${u?` and signal ${u}`:""}`}))};return r.stdout?.on("data",l=>{a(dr({text:l.toString(),stream:"stdout"}))}),r.stderr?.on("data",l=>{a(dr({text:l.toString(),stream:"stderr"}))}),r.on("error",l=>{a({type:"error.reported",code:l.code??"PROCESS_ERROR",message:l.message,recoverable:!1})}),r.on("exit",n),r.on("close",n),{pid:r.pid,writes:i,async read(){return s.splice(0,s.length)},async write(l){if(!r.stdin||r.stdin.destroyed||r.stdin.writableEnded||!r.stdin.writable||o)throw new Error("Child process stdin is not writable because it is closed or destroyed");await new Promise((u,y)=>{r.stdin.write(l,h=>{if(h){y(h);return}i.push(l),u()})})},async stop(){r.killed||(r.kill("SIGTERM"),await cn(a_),o||r.kill("SIGKILL"))}}}var l_={approve:`y
55
+ `,deny:`n
56
+ `},h_=500;function u_(t){if(t.textToWrite!==void 0)return[t.textToWrite];let e=t.text.split(`
57
+ `).flatMap((r,s,i)=>s===i.length-1&&r===""&&t.text.endsWith(`
58
+ `)?[]:r?[r,"\r"]:["\r"]);return e.length>0?e:["\r"]}function Bc(t,e){return{type:"approval.requested",requestId:Cs("claude_code",t,e),title:t,rawText:e,choices:["approve","deny"],risk:"unknown"}}var d_=8e3;function Oc(){let t="",e=!1;return{id:"claude_code",displayName:"Claude Code",async detect(){let r=await Ss("claude");return r?{available:!0,command:"claude",path:r}:{available:!1,command:"claude",reason:"claude executable not found on PATH"}},async spawn(r={}){return ks(r.command??"claude",r)},parseOutput(r){let s=[dr(r)],i=this.classifyPrompt(r.text);if(i.kind==="approval")return t="",e||(e=!0,s.push(Bc(i.title,r.text))),s;t=(t+r.text).slice(-d_);let o=this.classifyPrompt(t);return o.kind==="approval"?e||(e=!0,s.push(Bc(o.title,t))):e=!1,s},classifyPrompt(r){return Es(r)?{kind:"none",confidence:"low"}:xs(r)?{kind:"approval",confidence:"high",title:"Claude Code approval required",risk:"unknown"}:{kind:"none",confidence:"low"}},resolveApprovalInput(r,s,i){return i!==void 0?{text:i,textToWrite:i}:{text:l_[s]}},async writeInput(r,s){let i=u_(s);for(let[o,a]of i.entries())a==="\r"&&o>0&&await cn(h_),await r.write(a)},async stop(r){await r.stop()}}}var Ut=Oc();import{constants as f_}from"fs";import{access as p_}from"fs/promises";var __={approve:`
59
+ `,deny:"\x1B"};function m_(t,e){return{type:"approval.requested",requestId:Cs("cursor",t,e),title:t,rawText:e,choices:["approve","deny"],risk:"unknown"}}var Ur={id:"cursor",displayName:"Cursor",async detect(){let t=process.env.DJINN_CURSOR_EXECUTABLE;if(t)try{return await p_(t,f_.X_OK),{available:!0,command:t,path:t}}catch{return{available:!1,command:t,reason:"configured cursor executable is not executable"}}let e=await Ss("cursor");return e?{available:!0,command:"cursor",path:e}:{available:!1,command:"cursor",reason:"cursor executable not found on PATH"}},async spawn(t={}){return ks(t.command??process.env.DJINN_CURSOR_EXECUTABLE??"cursor",t)},parseOutput(t){let e=[dr(t)],r=this.classifyPrompt(t.text);return r.kind==="approval"&&e.push(m_(r.title,t.text)),e},classifyPrompt(t){return Es(t)?{kind:"none",confidence:"low"}:xs(t)?{kind:"approval",confidence:"high",title:"Cursor approval required",risk:"unknown"}:{kind:"none",confidence:"low"}},resolveApprovalInput(t,e,r){return r!==void 0?{text:r,textToWrite:r}:{text:__[e]}},async writeInput(t,e){await t.write(e.text)},async stop(t){await t.stop()}};import{createHash as g_}from"crypto";var v_=[{type:"output",text:`fake adapter ready
60
+ `},{type:"approval",title:"Allow fake action?",rawText:"Fake adapter requests approval for smoke testing",description:"Used by the local MVP smoke test.",risk:"low"}];function y_(t,e,r){let s=g_("sha256").update(`${t}:${e}:${r}`).digest("hex");return`appr_${t}_${s.slice(0,16)}`}function b_(t){let e=t.rawText??t.title;return{type:"approval.requested",requestId:y_("fake",t.title,e),title:t.title,description:t.description,rawText:e,choices:["approve","deny"],risk:t.risk??"unknown"}}function w_(t){return t==="approve"?`approve
61
+ `:`deny
62
+ `}function Dc(t={}){let e=t.script??v_,r=[...t.expectedInputs??[]],s;return{id:"fake",displayName:"Fake Adapter",get lastSpawnOptions(){return s},async detect(){return{available:!0,command:"fake"}},async spawn(i){s=i;let o=0,a=[];return{writes:a,async read(){let n=e[o++];return n?n.type==="output"?[{type:"terminal.output",stream:n.stream??"pty",text:n.text}]:[b_(n)]:[]},async write(n){let l=r.shift();if(l!==void 0&&l!==n)throw new Error(`Unexpected fake input: expected ${JSON.stringify(l)}, got ${JSON.stringify(n)}`);a.push(n)},async stop(){}}},parseOutput(i){return[{type:"terminal.output",stream:i.stream??"pty",text:i.text}]},classifyPrompt(i){return{kind:"none",confidence:"low"}},resolveApprovalInput(i,o,a){return a!==void 0?{text:a,textToWrite:a}:{text:w_(o)}},async writeInput(i,o){await i.write(o.text)},async stop(i){await i.stop()}}}var Fr=Dc();var S_={"claude-code":Ut,claude_code:Ut,cursor:Ur,fake:Fr};async function jr(t,e){let r=S_[t];if(!r&&!e?.detect)return{ok:!1,reason:`unknown adapter: ${t}`};let i=await(e?.detect??(()=>r.detect()))();return i.available===!1?{ok:!1,reason:i.reason??`${t} executable not found on PATH. Install it and ensure it is on your PATH.`}:{ok:!0}}async function Hc(t){nt(t.dir);let e=We(t.dir),r,s=async()=>{r?.(),await new Promise(n=>o.close(()=>n())),Ts(e,{force:!0}),Ts(Xi(t.dir),{force:!0})},i={...t,onStop:s},o=C_(n=>I_(n,i));await k_(o,e),A_(t.dir),x_(Xi(t.dir),String(process.pid),{mode:384});let a=t.onStarted?.({stop:s});return a&&typeof a.cleanup=="function"&&(r=a.cleanup),{stop:s}}async function k_(t,e){Dr(e);try{await Mc(t,e);return}catch(s){if(s.code!=="EADDRINUSE")throw s}if(await T_(e))throw new Error("daemon already running");Ts(e,{force:!0}),await Mc(t,e)}function Mc(t,e){return new Promise((r,s)=>{let i=o=>s(o);t.once("error",i),t.listen(e,()=>{t.removeListener("error",i),r()})})}function T_(t){return new Promise(e=>{let r=E_(t),s=i=>{r.destroy(),e(i)};r.on("connect",()=>{r.write(JSON.stringify({cmd:"ping"})+`
63
+ `)}),r.on("data",()=>s(!0)),r.on("error",()=>s(!1)),setTimeout(()=>s(!1),500)})}function A_(t){for(let e of en(t))if(!St(e.pid)){let r=ut(t,e.sessionId);r&&r.status==="running"&&ys(t,{...r,status:"exited",lastExitAtMs:Date.now()}),ds(t,e.sessionId),Ts(Or(t,e.sessionId),{force:!0})}}function I_(t,e){if(!us()){t.destroy();return}let r="";t.on("data",async s=>{r+=s.toString();let i=r.indexOf(`
64
+ `);if(i<0)return;let o=r.slice(0,i),a;try{let n=xc.parse(JSON.parse(o));a=await P_(n,e)}catch(n){a={ok:!1,code:"bad_request",message:n instanceof Error?n.message:String(n)}}t.write(JSON.stringify(a)+`
65
+ `),t.end()})}async function P_(t,e){switch(t.cmd){case"ping":return{ok:!0};case"ls":return{ok:!0,data:{sessions:Nc(e.dir)}};case"attach-info":{let r=wt(e.dir,t.sessionId);return!r||!St(r.pid)?{ok:!1,code:"not_found",message:"no live worker for session"}:{ok:!0,data:{socketPath:r.controlSocketPath}}}case"new":{let r=await jr(t.adapterId);if(!r.ok)return{ok:!1,code:"spawn_failed",message:r.reason};let{sessionId:s}=await e.forkWorker({adapterId:t.adapterId,cwd:t.cwd,aiCliArgs:t.aiCliArgs,mode:"new",origin:"local"});return{ok:!0,data:{sessionId:s}}}case"status":return{ok:!0,data:{pid:process.pid,sessions:Nc(e.dir).length}};case"stop":return setImmediate(()=>{e.onStop?.()}),{ok:!0};case"project":return t.action==="add"?(Pc(e.dir,t.path),{ok:!0}):t.action==="rm"?(Lc(e.dir,t.path),{ok:!0}):{ok:!0,data:{projects:ws(e.dir)}};default:return{ok:!1,code:"bad_request",message:"unknown cmd"}}}function Nc(t){let e=new Map(en(t).filter(s=>St(s.pid)).map(s=>[s.sessionId,s])),r=[];for(let s of Ac(t)){let i=e.has(s.sessionId);r.push({sessionId:s.sessionId,adapterId:s.adapterId,cwd:s.cwd,status:i?"running":s.status,origin:s.origin})}return r}import{readdirSync as og,readFileSync as ag}from"fs";var Zm=Re(Bl(),1),Km=Re(Ms(),1),Xm=Re(_r(),1),Qm=Re(bn(),1),eg=Re(Cn(),1),tg=Re(In(),1),Wl=Re(Fs(),1),rg=Re(jl(),1);var zt=Wl.default;var Ln=B.enum(["cli","pwa","server"]),ql=B.enum(["starting","running","waiting_approval","exited","error"]),$l=B.object({type:B.literal("session.started"),adapterId:B.string().optional(),command:B.array(B.string()).optional(),cwd:B.string().optional(),pid:B.number().int().positive().optional(),termSize:B.object({cols:B.number(),rows:B.number()}).optional()}).strict(),zl=B.object({type:B.literal("session.status"),status:ql,exitCode:B.number().int().nullable().optional(),signal:B.string().nullable().optional(),message:B.string().optional()}).strict(),Vl=B.object({type:B.literal("terminal.output"),stream:B.enum(["pty","stdout","stderr"]),text:B.string()}).strict(),Gl=B.object({type:B.literal("user.input"),text:B.string(),requestId:B.string().optional(),textToWrite:B.string().optional()}).strict(),Yl=B.object({type:B.literal("approval.requested"),requestId:B.string(),title:B.string(),description:B.string().optional(),rawText:B.string().optional(),choices:B.array(B.enum(["approve","deny"])),risk:B.enum(["low","medium","high","unknown"]).optional()}).strict(),Jl=B.object({type:B.literal("approval.resolved"),requestId:B.string(),decision:B.enum(["approve","deny"]),reason:B.string().optional(),textToWrite:B.string().optional()}).strict(),Zl=B.object({type:B.literal("error.reported"),code:B.string(),message:B.string(),recoverable:B.boolean().optional()}).strict(),Kl=B.object({type:B.literal("terminal.resize"),cols:B.number(),rows:B.number()}).strict(),Xl=B.object({type:B.literal("terminal.reset"),generationId:B.string(),cols:B.number().int().positive(),rows:B.number().int().positive()}).strict(),Ql=B.object({type:B.literal("heartbeat"),status:B.enum(["connected","reconnecting"]),message:B.string().optional()}).strict(),eh=B.object({type:B.literal("agent.waiting_for_input"),reason:B.enum(["prompt","quiet-window"]),confidence:B.enum(["high","medium"])}).strict(),Rn=B.discriminatedUnion("type",[$l,zl,Vl,Gl,Yl,Jl,Zl,Kl,Xl,Ql,eh]);var th=B.object({t:B.enum(["plain","encrypted"]),value:B.string()}).strict(),Bn=B.object({id:B.string(),seq:B.number().int().positive(),sessionId:B.string(),source:Ln,createdAt:B.number().int().nonnegative(),payload:Rn,content:th.optional()}).strict();var rh=B.object({path:B.string().min(1),label:B.string().optional()}).strict(),Ws=B.object({sessionId:B.string().min(1),cwd:B.string().min(1),adapterId:B.string().min(1),status:B.enum(["running","exited","crashed"]),lastMode:B.enum(["new","resume"]),alive:B.boolean(),createdAtMs:B.number(),lastExitAtMs:B.number().optional(),label:B.string().optional()}).strict(),On=B.discriminatedUnion("type",[B.object({type:B.literal("new_session"),commandId:B.string().min(1),cwd:B.string().min(1),adapterId:B.string().min(1)}).strict(),B.object({type:B.literal("wake_session"),commandId:B.string().min(1),sessionId:B.string().min(1)}).strict(),B.object({type:B.literal("list_projects"),commandId:B.string().min(1)}).strict(),B.object({type:B.literal("list_sessions"),commandId:B.string().min(1)}).strict()]),sh=B.enum(["project_not_allowed","daemon_offline","daemon_replaced","spawn_failed","unknown_session","already_running"]),sg=B.discriminatedUnion("ok",[B.object({commandId:B.string().min(1),ok:B.literal(!0),sessionId:B.string().min(1).optional(),projects:B.array(rh).optional(),sessions:B.array(Ws).optional()}).strict(),B.object({commandId:B.string().min(1),ok:B.literal(!1),code:sh,message:B.string()}).strict()]);import ig from"tls";var ng=new Set(["UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","CERT_UNTRUSTED","SELF_SIGNED_CERT_IN_CHAIN"]);function qs(t){let e=t?.code;return typeof e=="string"&&ng.has(e)}function $s(){return[...ig.rootCertificates]}function zs(t){return t.DJINN_TLS_BUNDLED_CA_FALLBACK!=="0"}function Vs(t){let e,r=!1,s=()=>{e&&(clearInterval(e),e=void 0)};return{start(){r=!1,s(),e=setInterval(()=>{if(r){t.log(`[djinn] ${t.label}: pong timeout; terminating dead connection`),t.terminate();return}r=!0,t.ping()},t.intervalMs),e.unref?.()},stop(){s(),r=!1},onPong(){r=!1}}}function Gs(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?r:e}var Ys=new Map;function cg(t,e){let s=(Ys.get(t)??Promise.resolve()).catch(()=>{}).then(e),i=s.catch(()=>{});return Ys.set(t,i),i.finally(()=>{Ys.get(t)===i&&Ys.delete(t)}),s}var Dn=new Set;async function lg(t,e){try{return await hg(t,e)}catch(r){return{commandId:e.commandId,ok:!1,code:"spawn_failed",message:r instanceof Error?r.message:String(r)}}}async function hg(t,e){if(e.type==="list_projects")return{commandId:e.commandId,ok:!0,projects:ws(t.dir)};if(e.type==="new_session"){if(!an(t.dir,e.cwd))return{commandId:e.commandId,ok:!1,code:"project_not_allowed",message:"\u8BE5 owner \u5C1A\u672A\u767B\u8BB0\u8BE5\u76EE\u5F55\uFF0C\u8BF7\u5728\u7535\u8111\u7AEF\u8FD0\u884C djinn project add <path>"};let r=await jr(e.adapterId);if(!r.ok)return{commandId:e.commandId,ok:!1,code:"spawn_failed",message:r.reason};try{let{sessionId:s}=await t.forkWorker({adapterId:e.adapterId,cwd:e.cwd,aiCliArgs:[],mode:"new",origin:"remote"});return{commandId:e.commandId,ok:!0,sessionId:s}}catch(s){return{commandId:e.commandId,ok:!1,code:"spawn_failed",message:s instanceof Error?s.message:String(s)}}}if(e.type==="list_sessions"){let r=rr(t.dir),s;try{s=og(r).filter(o=>o.endsWith(".json"))}catch{s=[]}let i=[];for(let o of s){let a;try{a=JSON.parse(ag(`${r}/${o}`,"utf8"))}catch{continue}let n=a,l=typeof n?.sessionId=="string"?n.sessionId:void 0;if(!l)continue;let u=!1;try{let _=wt(t.dir,l);u=!!_&&St(_.pid)}catch{u=!1}let y={sessionId:l,cwd:n.cwd,adapterId:n.adapterId,status:n.status,lastMode:n.lastMode,alive:u,createdAtMs:n.createdAtMs,lastExitAtMs:n.lastExitAtMs,label:n.label},h=Ws.safeParse(y);if(!h.success){process.stderr.write(`[djinn] list_sessions: skipping malformed session record ${o}
66
+ `);continue}i.push(h.data)}return{commandId:e.commandId,ok:!0,sessions:i}}return cg(e.sessionId,async()=>{let r=(t.readSessionCwd??(a=>ut(t.dir,a)?.cwd))(e.sessionId),s=ut(t.dir,e.sessionId);if(!r||!s)return{commandId:e.commandId,ok:!1,code:"unknown_session",message:"no such session"};let i=wt(t.dir,e.sessionId);if(Dn.has(e.sessionId)||i&&St(i.pid))return{commandId:e.commandId,ok:!1,code:"already_running",message:"session already running"};if(!an(t.dir,r))return{commandId:e.commandId,ok:!1,code:"project_not_allowed",message:"\u5386\u53F2\u76EE\u5F55\u5DF2\u4E0D\u5728\u767D\u540D\u5355\uFF0C\u5524\u9192\u88AB\u62D2\u7EDD"};let o=await jr(s.adapterId);if(!o.ok)return{commandId:e.commandId,ok:!1,code:"spawn_failed",message:o.reason};try{let{sessionId:a}=await t.forkWorker({adapterId:s.adapterId,cwd:r,aiCliArgs:[],mode:"resume",sessionId:e.sessionId,origin:"remote"});return Dn.add(e.sessionId),setTimeout(()=>Dn.delete(e.sessionId),3e4).unref?.(),{commandId:e.commandId,ok:!0,sessionId:a}}catch(a){return{commandId:e.commandId,ok:!1,code:"spawn_failed",message:a instanceof Error?a.message:String(a)}}})}function ih(t){let e=t.log??(_=>process.stderr.write(_+`
67
+ `)),r=t.env??process.env,s=t.pingIntervalMs??Gs(r.DJINN_CONTROL_PING_MS,2e4),i=!1,o,a=500,n=!1,l,u,y=t.serverUrl.replace(/^http/,"ws").replace(/\/$/,"")+"/v1/control",h=()=>{let _,d={headers:{authorization:`Bearer ${t.token}`}};n&&(d.ca=[...$s()]),o=new zt(y,d),e(`[djinn] control channel connecting to ${y}${n?" (bundled CA)":""}`),o.on("message",async p=>{let b;try{b=On.parse(JSON.parse(p.toString()))}catch{return}let c=await lg(t.deps,b);o?.readyState===zt.OPEN&&o.send(JSON.stringify(c))}),o.on("open",()=>{a=500,e(`[djinn] control channel connected to ${y}`);let p=o;u?.stop(),_=Vs({ping:()=>p?.ping(),terminate:()=>p?.terminate(),log:e,intervalMs:s,label:"control channel"}),u=_,_.start()}),o.on("pong",()=>_?.onPong()),o.on("close",p=>{if(_?.stop(),i){e("[djinn] control channel closed by client");return}e(`[djinn] control channel closed (code=${p}); reconnecting in ${a}ms`),l=setTimeout(()=>{l=void 0,i||h()},a),l.unref?.(),a=Math.min(a*2,3e4)}),o.on("error",p=>{e(`[djinn] control channel error: ${p.message}`),!n&&qs(p)&&(zs(r)?(n=!0,e("[djinn] control channel: cert chain error; falling back to bundled CA roots on next reconnect")):e("[djinn] control channel: cert chain error; bundled-CA fallback disabled (DJINN_TLS_BUNDLED_CA_FALLBACK=0)"))})};return h(),{close:()=>{i=!0,u?.stop(),l&&(clearTimeout(l),l=void 0),o?.close()}}}import{appendFileSync as ug}from"fs";function Mn(t){return e=>{try{ug(cc(t),e+`
68
+ `)}catch{}}}import{homedir as oh,userInfo as dg}from"os";import{join as Nn}from"path";import{connect as fg}from"net";import{existsSync as pg}from"fs";var Jr="top.unit00.djinn.daemon",Ks="djinn-daemon.service";function Js(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function nh(t){return/^[A-Za-z0-9_./:=-]+$/.test(t)?t:`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`}function _g(t){let r=[t.execPath,...sr(t.entry,["daemon","run"])].map(s=>` <string>${Js(s)}</string>`).join(`
69
+ `);return`<?xml version="1.0" encoding="UTF-8"?>
70
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
71
+ <plist version="1.0">
72
+ <dict>
73
+ <key>Label</key>
74
+ <string>${Jr}</string>
75
+ <key>ProgramArguments</key>
76
+ <array>
77
+ ${r}
78
+ </array>
79
+ <key>EnvironmentVariables</key>
80
+ <dict>
81
+ <key>PATH</key>
82
+ <string>${Js(t.path)}</string>
83
+ </dict>
84
+ <key>RunAtLoad</key>
85
+ <true/>
86
+ <key>KeepAlive</key>
87
+ <dict>
88
+ <key>SuccessfulExit</key>
89
+ <false/>
90
+ </dict>
91
+ <key>StandardOutPath</key>
92
+ <string>${Js(t.logPath)}</string>
93
+ <key>StandardErrorPath</key>
94
+ <string>${Js(t.logPath)}</string>
95
+ </dict>
96
+ </plist>
97
+ `}function mg(t){let r=[t.execPath,...sr(t.entry,["daemon","run"])].map(nh).join(" ");return`[Unit]
98
+ Description=Djinn daemon
99
+ StartLimitIntervalSec=0
100
+
101
+ [Service]
102
+ Environment=${nh(`PATH=${t.path}`)}
103
+ ExecStart=${r}
104
+ Restart=on-failure
105
+
106
+ [Install]
107
+ WantedBy=default.target
108
+ `}function ah(){return Nn(oh(),"Library","LaunchAgents",`${Jr}.plist`)}function ch(){return Nn(oh(),".config","systemd","user",Ks)}async function lh(t){if(t.platform!=="darwin"&&t.platform!=="linux")throw new Error(`unsupported platform for daemon install: ${t.platform}`);if(!t.loadIdentity())throw new Error("no identity found; run `djinn new --invite <CODE> --server <wss>` first");if(await t.pingDaemon()&&(await t.stopDaemon().catch(()=>{}),!await t.waitForSocketGone()))throw new Error("daemon socket did not disappear after stop; aborting install (please stop the daemon manually)");let e=process.env.PATH??"";if(t.platform==="darwin"){let r=ah();await t.writeConfig(r,_g({execPath:t.execPath,entry:t.entry,logPath:Nn(t.dir,"daemon.log"),path:e}));let s=process.getuid?.()??0;await t.runCommand("launchctl",["bootout",`gui/${s}/${Jr}`]).catch(()=>{}),await t.runCommand("launchctl",["bootstrap",`gui/${s}`,r])}else{let r=ch();await t.writeConfig(r,mg({execPath:t.execPath,entry:t.entry,path:e})),await t.runCommand("systemctl",["--user","daemon-reload"]),await t.runCommand("systemctl",["--user","enable","--now",Ks]),await t.runCommand("loginctl",["enable-linger",dg().username]).catch(()=>{})}if(!await t.verifySupervisorActive())throw new Error("daemon did not come up under the OS supervisor (a competing daemon may have grabbed the socket); please re-run `djinn daemon install`")}async function hh(t){if(t.platform==="darwin"){let e=process.getuid?.()??0;await t.runCommand("launchctl",["bootout",`gui/${e}/${Jr}`]).catch(()=>{}),await t.removeConfig(ah())}else if(t.platform==="linux")await t.runCommand("systemctl",["--user","disable","--now",Ks]).catch(()=>{}),await t.removeConfig(ch()),await t.runCommand("systemctl",["--user","daemon-reload"]).catch(()=>{});else throw new Error(`unsupported platform for daemon uninstall: ${t.platform}`)}function Zs(t){return new Promise(e=>{let r=fg(We(t)),s,i=o=>{clearTimeout(s),r.destroy(),e(o)};s=setTimeout(()=>i(!1),300),r.on("connect",()=>r.write(JSON.stringify({cmd:"ping"})+`
109
+ `)),r.on("data",()=>i(!0)),r.on("error",()=>i(!1))})}async function uh(t,e=3e3){let r=Date.now()+e;for(;Date.now()<r;){if(!pg(We(t))&&!await Zs(t))return!0;await new Promise(s=>setTimeout(s,150))}return!await Zs(t)}async function dh(t,e){let r=e.timeoutMs??3e3,s=e.sleep??(a=>new Promise(n=>setTimeout(n,a))),i=Date.now()+r,o=async()=>{if(t==="linux")return(await e.exec("systemctl",["--user","is-active","--quiet",Ks])).ok;if(t==="darwin"){let a=await e.exec("launchctl",["print",`gui/${e.uid}/${Jr}`]);return a.ok&&/\bpid = \d+/.test(a.stdout)}return!1};for(;Date.now()<i;){if(await o())return!0;await s(150)}return o()}import{randomUUID as jn}from"crypto";var Xs=class{opts;quietTimer=null;pendingApprovals=new Set;userInputAt=0;lastEmitAt=0;lastOutputText="";disposed=!1;constructor(e){this.opts=e}onTerminalOutput(e){this.disposed||(this.lastOutputText=e,this.resetTimer())}onUserInput(){this.disposed||(this.userInputAt=Date.now(),this.lastEmitAt=0,this.pendingApprovals.clear(),this.clearTimer())}onApprovalRequested(e){this.pendingApprovals.add(e),this.clearTimer()}onApprovalResolved(e){this.pendingApprovals.delete(e)}dispose(){this.disposed=!0,this.clearTimer()}resetTimer(){this.clearTimer(),!(this.pendingApprovals.size>0)&&(this.quietTimer=setTimeout(()=>{this.checkAndEmit()},this.opts.quietWindowMs))}clearTimer(){this.quietTimer!==null&&(clearTimeout(this.quietTimer),this.quietTimer=null)}checkAndEmit(){if(this.disposed||this.pendingApprovals.size>0)return;let e=Date.now();if(e-this.userInputAt<this.opts.userInputCooldownMs||this.lastEmitAt>0&&e-this.lastEmitAt<this.opts.eventCooldownMs)return;let r=ln(this.lastOutputText);r.kind==="waiting_input"?(this.lastEmitAt=e,this.opts.onWaitingForInput(r.reason,r.confidence)):(this.lastEmitAt=e,this.opts.onWaitingForInput("quiet-window","medium"))}};var Qs=class{constructor(e){this.options=e;e.waitingDetector&&(this.detector=new Xs({...e.waitingDetector,onWaitingForInput:(r,s)=>{this.options.relay.send({type:"agent.waiting_for_input",reason:r,confidence:s})}}))}options;pendingApprovals=new Map;resolvedApprovalRequestIds=new Set;pendingRemoteEvents=[];runningSession;detector;async start(){this.options.relay.onEvent(e=>this.handleRemoteEvent(e)),await this.options.relay.connect?.(),this.runningSession=await this.options.adapter.spawn({args:this.options.args,cwd:this.options.cwd,env:this.options.env,command:this.options.command}),await this.options.relay.send({type:"session.started",adapterId:this.options.adapter.id,command:[this.options.command??this.options.adapter.id,...this.options.args??[]],cwd:this.options.cwd,pid:this.runningSession.pid,termSize:this.runningSession.cols&&this.runningSession.rows?{cols:this.runningSession.cols,rows:this.runningSession.rows}:void 0}),this.runningSession.onResize?.((e,r)=>{this.options.relay.send({type:"terminal.resize",cols:e,rows:r})}),await this.flushPendingRemoteEvents()}async pollOnce(){let r=await this.requireSession().read();for(let s of r)await this.forwardLocalEvent(s)}observeLocalEvents(e){for(let r of e)r.type==="approval.requested"?(this.pendingApprovals.set(r.requestId,r),this.detector?.onApprovalRequested(r.requestId)):r.type==="terminal.output"&&this.detector?.onTerminalOutput(r.text)}async handleRemoteEvent(e){let r="payload"in e?e:void 0,s=r?r.payload:e;if(!this.runningSession&&this.isSessionBoundRemoteEvent(s)){this.pendingRemoteEvents.push(r??s);return}if(s.type==="user.input"){this.detector?.onUserInput(),await this.options.adapter.writeInput(this.requireSession(),{text:s.text,textToWrite:s.textToWrite}),r&&this.options.onRemoteApplied?.(r);return}if(s.type==="approval.resolved"){await this.handleApprovalResolved(s)&&r&&this.options.onRemoteApplied?.(r);return}if(s.type==="terminal.resize"){if(!this.runningSession)return;r&&r.source==="pwa"&&this.options.resizeSession?.(s.cols,s.rows);return}}async stop(){this.detector?.dispose(),this.runningSession&&await this.options.adapter.stop(this.runningSession),await this.options.relay.close?.()}async forwardLocalEvent(e){e.type==="approval.requested"&&(this.pendingApprovals.set(e.requestId,e),this.detector?.onApprovalRequested(e.requestId)),e.type==="terminal.output"&&this.detector?.onTerminalOutput(e.text),await this.options.relay.send(e)}async handleApprovalResolved(e){if(this.resolvedApprovalRequestIds.has(e.requestId))return await this.reportRecoverableError("approval.already_resolved",`Approval request ${e.requestId} was already resolved`),!1;let r=this.pendingApprovals.get(e.requestId);if(!r)return await this.reportRecoverableError("approval.unknown_request",`Approval request ${e.requestId} is not pending`),!1;let s=this.options.adapter.resolveApprovalInput(r,e.decision,e.textToWrite);return this.resolvedApprovalRequestIds.add(e.requestId),this.pendingApprovals.delete(e.requestId),this.detector?.onApprovalResolved(e.requestId),await this.options.adapter.writeInput(this.requireSession(),s),!0}async flushPendingRemoteEvents(){for(;this.pendingRemoteEvents.length>0;){let e=this.pendingRemoteEvents.shift();e&&await this.handleRemoteEvent(e)}}isSessionBoundRemoteEvent(e){return e.type==="user.input"||e.type==="approval.resolved"}async reportRecoverableError(e,r){await this.options.relay.send({type:"error.reported",code:e,message:r,recoverable:!0})}requireSession(){if(!this.runningSession)throw new Error("Session engine has not been started");return this.runningSession}};var ei=class{constructor(e){this.options=e;this.reconnectDelayMs=e.reconnectDelayMs??500,this.nextReconnectDelayMs=this.reconnectDelayMs,this.lastHandledSeq=e.initialAfterSeq??0,this.log=e.log??(r=>process.stderr.write(r+`
110
+ `)),this.env=e.env??process.env,this.pingIntervalMs=e.pingIntervalMs??Gs(this.env.DJINN_SESSION_PING_MS,3e4)}options;eventHandlers=new Set;reconnectDelayMs;socket;keepalive;closed=!1;lastHandledSeq;processing=Promise.resolve();nextReconnectDelayMs;reconnectTimer;useBundledCa=!1;log;env;pingIntervalMs;async connect(){this.closed=!1;try{await this.openSocket()}catch{this.scheduleReconnect()}}async send(e,r){let s=this.socket;if(!s||s.readyState!==zt.OPEN)throw new Error("Relay websocket is not connected");let i=r?.id?{id:r.id,...e}:e;await new Promise((o,a)=>{s.send(JSON.stringify(i),n=>{if(n){a(n);return}o()})})}onEvent(e){this.eventHandlers.add(e)}async close(){this.closed=!0,this.keepalive?.stop(),clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0,this.socket?.close()}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;let e=this.nextReconnectDelayMs;this.nextReconnectDelayMs=Math.min(this.nextReconnectDelayMs*2,3e4),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.openSocket().catch(()=>{})},e)}async openSocket(){if(this.closed)return;let e={headers:{authorization:`Bearer ${this.options.token}`}};this.useBundledCa&&(e.ca=[...$s()]);let r=new zt(this.streamUrl(),e);this.socket=r;let s;this.log(`[djinn] session stream connecting to ${this.streamUrl()}${this.useBundledCa?" (bundled CA)":""}`),r.on("error",i=>{this.log(`[djinn] session stream error: ${i.message}`),!this.useBundledCa&&qs(i)&&(zs(this.env)?(this.useBundledCa=!0,this.log("[djinn] session stream: cert chain error; falling back to bundled CA roots on next reconnect")):this.log("[djinn] session stream: cert chain error; bundled-CA fallback disabled (DJINN_TLS_BUNDLED_CA_FALLBACK=0)"))}),r.on("pong",()=>s?.onPong()),r.on("message",i=>{let o=this.parseEnvelope(i);o&&this.enqueueEnvelope(o)}),r.on("close",i=>{if(s?.stop(),this.socket===r){if(this.closed){this.log("[djinn] session stream closed by client");return}if(i===4e3){this.log("[djinn] session stream closed (code=4000, replaced by newer cli); not reconnecting"),this.closed=!0;return}this.log(`[djinn] session stream closed (code=${i}); reconnecting`),this.enqueueEnvelope({id:`local-reconnecting-${Date.now()}`,seq:this.lastHandledSeq,sessionId:this.options.sessionId,source:"server",createdAt:Date.now(),payload:{type:"heartbeat",status:"reconnecting"}}),this.scheduleReconnect()}}),await new Promise((i,o)=>{r.once("open",()=>{this.log(`[djinn] session stream connected to ${this.streamUrl()}`),this.options.onConnected?.(),i()}),r.once("error",o)}),this.nextReconnectDelayMs=this.reconnectDelayMs,s=Vs({ping:()=>{r.readyState===zt.OPEN&&r.ping()},terminate:()=>r.terminate(),log:this.log,intervalMs:this.pingIntervalMs,label:"session stream"}),this.keepalive=s,s.start()}streamUrl(){let e=new URL(this.options.serverUrl),r=e.pathname.replace(/\/$/,"");return e.pathname=`${r}/v1/sessions/${encodeURIComponent(this.options.sessionId)}/stream`,e.searchParams.set("role","cli"),e.searchParams.set("afterSeq",String(this.lastHandledSeq)),e.toString()}async handleEnvelope(e){try{await Promise.all([...this.eventHandlers].map(r=>r(e))),this.lastHandledSeq=Math.max(this.lastHandledSeq,e.seq)}catch(r){let s=r instanceof Error?r.message:String(r);process.stderr.write(`Relay handler failed for seq ${e.seq} ${e.payload.type}: ${s}
111
+ `)}}parseEnvelope(e){try{let r=JSON.parse(e.toString());return Bn.parse(r)}catch(r){let s=r instanceof Error?r.message:String(r);process.stderr.write(`Relay received invalid envelope: ${s}
112
+ `);return}}enqueueEnvelope(e){this.processing=this.processing.then(()=>this.handleEnvelope(e),()=>this.handleEnvelope(e))}};function Hn(t){let e=(r,s)=>{let i=Number(r);return Number.isFinite(i)&&i>0?i:s};return{quietWindowMs:e(t.DJINN_WAITING_QUIET_MS,2e4),userInputCooldownMs:e(t.DJINN_WAITING_USER_COOLDOWN_MS,1e4),eventCooldownMs:e(t.DJINN_WAITING_EVENT_COOLDOWN_MS,3e5)}}var gg=Re(ph(),1),_h=gg,mh=_h.Terminal??_h.default?.Terminal;if(!mh)throw new Error("@xterm/headless: Terminal export not found");var vg=mh;function yg(t){let e=[];if(t.isBold()&&e.push(1),t.isDim()&&e.push(2),t.isItalic()&&e.push(3),t.isUnderline()&&e.push(4),t.isInverse()&&e.push(7),!t.isFgDefault()){if(t.isFgPalette()){let r=t.getFgColor();r<=7?e.push(30+r):r<=15?e.push(90+(r-8)):e.push(38,5,r)}else if(t.isFgRGB()){let r=t.getFgColor();e.push(38,2,r>>16&255,r>>8&255,r&255)}}if(!t.isBgDefault()){if(t.isBgPalette()){let r=t.getBgColor();r<=7?e.push(40+r):r<=15?e.push(100+(r-8)):e.push(48,5,r)}else if(t.isBgRGB()){let r=t.getBgColor();e.push(48,2,r>>16&255,r>>8&255,r&255)}}return e.length?`\x1B[${e.join(";")}m`:""}var ti=class{constructor(e,r){this.cols=e;this.rows=r;this.term=new vg({cols:e,rows:r,allowProposedApi:!0,scrollback:0})}cols;rows;term;currentSgr=[];inAltBuffer=!1;async feed(e){let r=e.toString("utf8");this.trackModes(r),await new Promise(s=>this.term.write(r,s))}async resize(e,r){this.cols=e,this.rows=r,this.term.resize(e,r),await new Promise(s=>this.term.write("",s))}async snapshot(){await new Promise(i=>this.term.write("",i));let e=[];this.inAltBuffer&&e.push("\x1B[?1049h"),e.push("\x1B[2J\x1B[H");let r=this.term.buffer.active,s=r.getNullCell();for(let i=0;i<this.rows;i++){let o=r.getLine(i);if(!o)continue;let a=[],n=-1;for(let l=0;l<this.cols;l++){let u=o.getCell(l,s);if(!u){a.push(" ");continue}let y=u.getWidth();if(y===0)continue;let h=u.getChars(),_=yg(u);a.push(`\x1B[0m${_}${h||" "}`),_===""&&(h===""||h===" ")||(n=a.length-1),y===2&&(l+=1)}if(!(n<0)){e.push(`\x1B[${i+1};1H`);for(let l=0;l<=n;l++)e.push(a[l]);e.push("\x1B[0m")}}return e.push(`\x1B[${r.cursorY+1};${r.cursorX+1}H`),e.push("\x1B[0m"),this.currentSgr.length&&e.push(`\x1B[${this.currentSgr.join(";")}m`),Buffer.from(e.join(""),"utf8")}trackModes(e){e.includes("\x1B[?1049h")&&(this.inAltBuffer=!0),e.includes("\x1B[?1049l")&&(this.inAltBuffer=!1);let r=/\x1b\[([0-9;]*)m/g,s;for(;(s=r.exec(e))!==null;){let i=s[1]===""?["0"]:s[1].split(";");for(let o of i)o==="0"||o===""?this.currentSgr=[]:this.currentSgr.push(o)}}};import*as vh from"node-pty";var bg=new Set(["CLAUDECODE","CLAUDE_CODE_CHILD_SESSION","CLAUDE_CODE_SESSION_ID","CLAUDE_CODE_ENTRYPOINT","AI_AGENT"]);function gh(t){let e={};for(let[r,s]of Object.entries(t))bg.has(r)||(e[r]=s);return e}async function wg(t,e,r){return e.command?e.command:(await t.detect()).command??r}async function yh(t){let e=t.adapter.id==="fake"||t.adapterId==="fake",r=[],s,i=t.cols,o=t.rows,a=_=>{if(r.length===0){s=_;return}for(let d of r)d(_)},n=_=>{if(r.push(_),s&&r.length===1){let d=s;s=void 0,queueMicrotask(()=>_(d))}};if(e){let _=await t.adapter.spawn({args:t.args,cwd:t.cwd,env:t.env});return{pid:_.pid,cols:t.cols,rows:t.rows,get currentCols(){return i},get currentRows(){return o},writes:_.writes,async read(){let d=await _.read();for(let p of d)if(p.type==="terminal.output"){let b=Buffer.from(p.text,"utf8");t.screen.feed(b),t.onAttachBytes(b)}return d},async write(d){await _.write(d)},async stop(){await _.stop()},resize(d,p){i=d,o=p,t.screen.resize(d,p)},onExit(d){n(d)}}}let l=await wg(t.adapter,{command:t.command},t.adapterId),u=[],y=[],h=vh.spawn(l,t.args,{cwd:t.cwd,env:gh(t.env),name:"xterm-256color",cols:t.cols,rows:t.rows});return h.onData(_=>{let d=Buffer.from(_,"utf8");u.push(...t.adapter.parseOutput({text:_,stream:"pty"})),t.screen.feed(d),t.onAttachBytes(d)}),h.onExit(({exitCode:_,signal:d})=>{a({exitCode:_,signal:d?String(d):null})}),{pid:h.pid,cols:h.cols,rows:h.rows,get currentCols(){return i},get currentRows(){return o},writes:y,async read(){return u.splice(0,u.length)},async write(_){y.push(_),h.write(_)},async stop(){h.kill()},resize(_,d){i=_,o=d,h.resize(_,d),t.screen.resize(_,d)},onExit(_){n(_)}}}import{createServer as Sg}from"net";import{rmSync as bh}from"fs";var Un=0,wh=1,Cg=1<<20;function Fn(t,e){let r=Buffer.alloc(5);return r.writeUInt8(t,0),r.writeUInt32BE(e.length,1),Buffer.concat([r,e])}function Sh(t,e){let r=Buffer.alloc(8);return r.writeUInt32BE(t,0),r.writeUInt32BE(e,4),Fn(wh,r)}var ri=class{constructor(e){this.opts=e}opts;server;conns=new Set;async listen(){Dr(this.opts.socketPath),bh(this.opts.socketPath,{force:!0}),this.server=Sg(e=>this.onConnection(e)),await new Promise((e,r)=>{let s=i=>r(i);this.server.once("error",s),this.server.listen(this.opts.socketPath,()=>{this.server.removeListener("error",s),this.server.on("error",i=>{process.stderr.write(`attach server error: ${i instanceof Error?i.message:String(i)}
113
+ `)}),e()})})}onConnection(e){if(!us()){e.destroy();return}let r={socket:e,ready:!1,backlog:[],inbuf:Buffer.alloc(0)};this.conns.add(r),e.on("data",i=>this.consumeInbound(r,i));let s=()=>{this.conns.delete(r)};e.on("close",s),e.on("error",s),this.opts.snapshot().then(i=>{if(!this.conns.has(r)||!e.writable){this.conns.delete(r);return}e.write(i);for(let o of r.backlog)e.write(o);r.backlog=[],r.ready=!0}).catch(()=>this.conns.delete(r))}broadcast(e){for(let r of this.conns)r.socket.writable&&(r.ready?r.socket.write(e):r.backlog.push(e))}consumeInbound(e,r){for(e.inbuf=Buffer.concat([e.inbuf,r]);e.inbuf.length>=5;){let s=e.inbuf.readUInt8(0),i=e.inbuf.readUInt32BE(1);if(i>Cg){e.socket.destroy(),this.conns.delete(e);return}if(e.inbuf.length<5+i)break;let o=e.inbuf.subarray(5,5+i);e.inbuf=e.inbuf.subarray(5+i);try{s===Un?this.opts.onInput(Buffer.from(o)):s===wh&&o.length===8&&this.opts.onResize?.(o.readUInt32BE(0),o.readUInt32BE(4))}catch(a){process.stderr.write(`attach input handler error: ${a instanceof Error?a.message:String(a)}
114
+ `)}}}get connectionCount(){return this.conns.size}async close(){for(let e of this.conns)e.socket.destroy();this.conns.clear(),this.server&&(await new Promise(e=>this.server.close(()=>e())),bh(this.opts.socketPath,{force:!0}))}};var Eg={"claude-code":Ut,claude_code:Ut,cursor:Ur,fake:Fr};function xg(t,e,r){return[...t==="new"?["--session-id",e]:["--resume",e],...r]}async function Ch(t){let e=Ke(t.dir);if(!e)throw new Error("no identity; cannot start worker");let r=Eg[t.adapterId];if(!r)throw new Error(`unknown adapter: ${t.adapterId}`);let s=ut(t.dir,t.sessionId),i=t.mode==="resume"&&s?s.appliedSeq:0,o=xg(t.mode,t.sessionId,t.aiCliArgs),a=new ti(80,24),n=jn(),l=jn(),u=i,y=!1,h=()=>t.mode==="resume"&&!y,_=new Wn,d=(t.relayFactory??kg)({serverUrl:e.serverUrl,sessionId:t.sessionId,token:e.token,initialAfterSeq:i,onConnected:()=>{_.resendStarted(),_.resendReset()}});_.attach(d);let p=D=>{let O=ut(t.dir,t.sessionId)??{sessionId:t.sessionId,cwd:t.cwd,adapterId:t.adapterId,origin:t.origin??"local",lastMode:t.mode,appliedSeq:u,createdAtMs:Date.now(),status:"running"};ys(t.dir,{...O,...D})},b,c,v=new ri({socketPath:Or(t.dir,t.sessionId),snapshot:()=>a.snapshot(),onInput:D=>{b.write(D.toString("utf8"))},onResize:(D,O)=>{c("cli",D,O)}});b=await(t.spawnPty?t.spawnPty(o):yh({adapter:r,adapterId:t.adapterId,args:o,cwd:t.cwd,env:t.env??process.env,cols:80,rows:24,screen:a,onAttachBytes:D=>v.broadcast(D)})),await v.listen(),c=(D,O,L)=>{O===b.currentCols&&L===b.currentRows||(b.resize(O,L),_.send({type:"terminal.resize",cols:O,rows:L}))};let g={...r,spawn:async()=>b},f=new Qs({sessionId:t.sessionId,adapter:g,relay:_,args:o,cwd:t.cwd,env:t.env??process.env,waitingDetector:Hn(t.env??process.env),onRemoteApplied:D=>{D.payload.type==="user.input"&&(y=!0),D.seq>u&&(u=D.seq,p({appliedSeq:u}))},resizeSession:(D,O)=>{c("pwa",D,O)}});p({status:"running",appliedSeq:u,lastMode:t.mode,lastExitAtMs:void 0}),dc(t.dir,{pid:process.pid,controlSocketPath:Or(t.dir,t.sessionId),sessionId:t.sessionId,cwd:t.cwd,adapterId:t.adapterId,claudeSessionId:t.sessionId,mode:t.mode,origin:t.origin??"local",startedAtMs:Date.now()}),await f.start();let m={type:"terminal.reset",generationId:n,cols:b.currentCols,rows:b.currentRows};_.rememberReset(m,l),await _.send(m,{id:l}),b.onExit(D=>{A(D)});let w,C=new Promise(D=>{w=D}),k=!1;async function A(D){if(k)return;k=!0;let O=D?.exitCode??0,L=D?.signal??null,R=O!==0||L?"crashed":"exited";await _.sendConfirmed({type:"session.status",status:"exited",exitCode:O,signal:L},2e3),p({status:R,lastExitAtMs:Date.now(),appliedSeq:u}),await v.close(),await _.close(),ds(t.dir,t.sessionId),w()}return{async pumpOnce(){let D=await b.read(),O=h()?D.filter(L=>L.type!=="approval.requested"):D;f.observeLocalEvents(O);for(let L of O)await _.send(L)},shutdown:A,done:C,applyResize:c}}function kg(t){return new ei(t)}var Wn=class{engineHandlers=new Set;pendingConfirm=new Map;startedPayload;resetPayload;resetId;underlying;attach(e){this.underlying=e,e.onEvent(async r=>{r.id&&this.pendingConfirm.has(r.id)&&(this.pendingConfirm.get(r.id)(),this.pendingConfirm.delete(r.id)),await Promise.all([...this.engineHandlers].map(s=>s(r)))})}onEvent(e){this.engineHandlers.add(e)}async connect(){try{await this.underlying?.connect?.()}catch{}}async close(){await this.underlying?.close?.()}resendStarted(){this.startedPayload&&this.send(this.startedPayload)}rememberReset(e,r){this.resetPayload=e,this.resetId=r}resendReset(){this.resetPayload&&this.resetId&&this.send(this.resetPayload,{id:this.resetId})}async send(e,r){e.type==="session.started"&&(this.startedPayload=e);try{await this.underlying?.send(e,r)}catch{}}async sendConfirmed(e,r){let s=jn(),i=new Promise(o=>{this.pendingConfirm.set(s,o),setTimeout(()=>{this.pendingConfirm.delete(s),o()},r)});try{await this.underlying?.send(e,{id:s})}catch{}await i}};import{connect as Tg}from"net";var qn="\x1B";function Ag(){return`${qn}[?1049l${qn}[0m${qn}[?25h`}function Ig(t,e){return e.armed?t.length===1&&t[0]===100?{armed:!1,detach:!0}:{armed:!1,detach:!1}:t.length===1&&t[0]===1?{armed:!0,detach:!1}:{armed:!1,detach:!1}}async function Pg(t,e,r=5e3){let s=Date.now()+r;for(;Date.now()<s;){let i=await ht(t,{cmd:"attach-info",sessionId:e});if(i.ok)return i.data.socketPath;await new Promise(o=>setTimeout(o,150))}}async function $n(t,e){let r=await Pg(t,e);if(!r)return process.stderr.write(`cannot attach: worker for ${e} not ready
115
+ `),1;let s=Tg(r),i=()=>{process.stdout.isTTY&&process.stdout.write(Ag()),process.stdin.isTTY&&process.stdin.setRawMode(!1)},o={armed:!1},a=()=>{process.stdout.isTTY&&s.write(Sh(process.stdout.columns||80,process.stdout.rows||24))},n=()=>a();return new Promise(l=>{let u=y=>{i(),process.stdin.pause(),process.stdout.off("resize",n),s.destroy(),l(y)};s.on("connect",()=>{process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.resume()),a(),process.stdout.on("resize",n),process.stdin.on("data",y=>{let h=Ig(y,o);if(o={armed:h.armed},h.detach){u(0);return}h.armed||s.write(Fn(Un,y))})}),s.on("data",y=>process.stdout.write(y)),s.on("close",()=>u(0)),s.on("error",()=>u(1));for(let y of["SIGINT","SIGTERM","SIGHUP"])process.once(y,()=>u(0))})}async function Bg(t,e){switch(t.command){case"new":return e.handlers.newSession(t.config,e);case"attach":return e.handlers.attach(t.config,e);case"ls":return e.handlers.ls(e);case"daemon":return e.handlers.daemon(t.config,e);case"__worker":return e.handlers.worker(t.config,e);case"pair":return e.handlers.pair(t.config,e);case"project":return e.handlers.project(t.config,e)}}function Og(t){if(t.length===0)return`no sessions
116
+ `;let r=[{sessionId:"SESSION",adapterId:"ADAPTER",cwd:"CWD",status:"STATUS",origin:"ORIGIN"},...t],s={sessionId:Math.max(...r.map(o=>o.sessionId.length)),adapterId:Math.max(...r.map(o=>o.adapterId.length)),status:Math.max(...r.map(o=>o.status.length)),origin:Math.max(...r.map(o=>o.origin.length))},i=(o,a)=>o.padEnd(a);return r.map(o=>[i(o.sessionId,s.sessionId),i(o.adapterId,s.adapterId),i(o.status,s.status),i(o.origin,s.origin),o.cwd].join(" ")).join(`
117
+ `)+`
118
+ `}var Dg={async worker(t,e){let r=await Ch({dir:e.dir,sessionId:t.sessionId,cwd:t.cwd,adapterId:t.adapterId,mode:t.mode,aiCliArgs:t.aiCliArgs,origin:t.origin}),s=setInterval(()=>{r.pumpOnce().catch(a=>process.stderr.write(`worker pump error: ${a}
119
+ `))},150),i=()=>{clearInterval(s),process.exit(0)};r.done.then(i);let o=()=>{r.shutdown()};return process.once("SIGTERM",o),process.once("SIGINT",o),new Promise(()=>{})},async daemon(t,e){if(t.action==="run"||t.action==="run-detached"){let s=Ke(e.dir),i;try{i=await Hc({dir:e.dir,forkWorker:o=>Promise.resolve(tn({dir:e.dir,entry:e.entry},o)),onStarted:()=>{if(!s){Mn(e.dir)("[djinn] control channel disabled: no identity (run `djinn new --invite ...` to register)");return}let o=ih({serverUrl:s.serverUrl,token:s.token,deps:{dir:e.dir,forkWorker:a=>Promise.resolve(tn({dir:e.dir,entry:e.entry},a))},log:Mn(e.dir)});return{cleanup:()=>o.close()}}})}catch(o){return o instanceof Error&&/daemon already running/i.test(o.message)?(process.stdout.write(`[djinn] daemon already running; yielding
120
+ `),0):(process.stderr.write(`[djinn] daemon failed to start: ${o instanceof Error?o.message:String(o)}
121
+ `),1)}return process.once("SIGTERM",()=>{i.stop().finally(()=>process.exit(0))}),process.once("SIGINT",()=>{i.stop().finally(()=>process.exit(0))}),new Promise(()=>{})}if(t.action==="install"||t.action==="uninstall"){let s={platform:process.platform,dir:e.dir,execPath:process.execPath,entry:e.entry,loadIdentity:()=>Ke(e.dir),pingDaemon:()=>Zs(e.dir),stopDaemon:async()=>{await ht(e.dir,{cmd:"stop"})},waitForSocketGone:()=>uh(e.dir),verifySupervisorActive:()=>dh(process.platform,{uid:process.getuid?.()??0,exec:async(i,o)=>{let{execFile:a}=await import("child_process"),{promisify:n}=await import("util");try{let{stdout:l}=await n(a)(i,o);return{ok:!0,stdout:l}}catch(l){return{ok:!1,stdout:l.stdout??""}}}}),writeConfig:async(i,o)=>{let{mkdir:a,writeFile:n}=await import("fs/promises"),{dirname:l}=await import("path");await a(l(i),{recursive:!0}),await n(i,o,{mode:420})},removeConfig:async i=>{let{rm:o}=await import("fs/promises");await o(i,{force:!0})},runCommand:async(i,o)=>{let{execFile:a}=await import("child_process"),{promisify:n}=await import("util");await n(a)(i,o)}};try{return t.action==="install"?(await lh(s),process.stdout.write(`djinn daemon installed
122
+ `)):(await hh(s),process.stdout.write(`djinn daemon uninstalled
123
+ `)),0}catch(i){return process.stderr.write(`${i instanceof Error?i.message:String(i)}
124
+ `),1}}let r=await ht(e.dir,{cmd:t.action});return process.stdout.write(`${JSON.stringify(r)}
125
+ `),r.ok?0:1},async newSession(t,e){try{await Jn({dir:e.dir,serverUrl:t.server,invite:t.invite,label:Rg()})}catch(i){return process.stderr.write(`${i instanceof Error?i.message:String(i)}
126
+ `),1}await fs(e.dir,e.entry);let r=await ht(e.dir,{cmd:"new",adapterId:t.adapterId,cwd:t.cwd,aiCliArgs:t.aiCliArgs});if(!r.ok)return process.stderr.write(`${r.message}
127
+ `),1;let s=r.data.sessionId;return t.detach?(process.stdout.write(`${s}
128
+ `),0):$n(e.dir,s)},async attach(t,e){return $n(e.dir,t.sessionId)},async ls(t){await fs(t.dir,t.entry);let e=await ht(t.dir,{cmd:"ls"});if(!e.ok)return process.stderr.write(`${e.message}
129
+ `),1;let r=e.data.sessions;return process.stdout.write(Og(r)),0},async pair(t,e){try{return await ac({dir:e.dir,png:t.png,pngPath:t.pngPath})}catch(r){return process.stderr.write(`${r instanceof Error?r.message:String(r)}
130
+ `),1}},async project(t,e){await fs(e.dir,e.entry);let r=await ht(e.dir,{cmd:"project",action:t.action,path:t.path});if(r.ok&&t.action==="ls"){let s=r.data?.projects??[];if(s.length===0)process.stdout.write(`no projects
131
+ `);else for(let i of s)process.stdout.write(`${i.label?`${i.label} `:""}${i.path}
132
+ `)}else process.stdout.write(`${JSON.stringify(r)}
133
+ `);return r.ok?0:1}},Mg=`djinn \u2014 remote control for AI programming CLIs
134
+
135
+ Usage: djinn <command> [options]
136
+
137
+ Commands:
138
+ new [--adapter <id>] [--server <wss>] [--invite <CODE>] [--detach] [-- <aiCliArgs>]
139
+ attach <sessionId>
140
+ ls
141
+ pair
142
+ project <add|rm|ls> [path]
143
+ daemon <run|run-detached|status|stop|install|uninstall>
144
+
145
+ Adapter defaults to claude-code; server defaults to wss://unit00.top/djinn/relay.
146
+ `;function Ng(t){let e=t[2];return e===void 0||e==="--help"||e==="-h"?"help":e==="--version"||e==="-V"?"version":"command"}var Hg="0.1.0";async function Ug(t=process.argv,e=process.env,r=Gn()){let s=Ng(t);if(s==="help"){process.stdout.write(Mg);return}if(s==="version"){process.stdout.write(`${Hg}
147
+ `);return}let i;try{i=zn(t,e)}catch(n){process.stderr.write(`${n instanceof Error?n.message:String(n)}
148
+ `),process.exitCode=1;return}let o=process.argv[1]??"",a=await Bg(i,{dir:r,entry:o,handlers:Dg});a!==0&&(process.exitCode=a)}function Fg(){let t=process.argv[1];if(!t)return!1;if(t.includes("index.ts"))return!0;try{let e=Lg(t);if(import.meta.url===xh(Eh(e)).href)return!0}catch{}return import.meta.url===xh(Eh(t)).href}Fg()&&Ug();export{Bg as dispatchCommand,Ug as main,Hn as readWaitingDetectorConfig,Dg as realHandlers,Ng as resolveTopLevel};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __djinnCreateRequire } from "node:module"; const require = __djinnCreateRequire(import.meta.url);
2
+ import{createRequire as t}from"module";import{chmodSync as c,existsSync as i}from"fs";import{dirname as n,join as p}from"path";function s(){try{let o=t(import.meta.url).resolve("node-pty/package.json"),e=n(o),r=p(e,"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");i(r)&&c(r,493)}catch{}}s();
package/package.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "@hown/djinn",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "bin": { "djinn": "dist/index.js" },
6
+ "files": ["dist"],
7
+ "engines": { "node": ">=18" },
8
+ "os": ["darwin"],
9
+ "scripts": { "postinstall": "node dist/postinstall.js" },
10
+ "dependencies": {
11
+ "node-pty": "^1.1.0",
12
+ "@xterm/headless": "^6.0.0",
13
+ "ws": "^8.18.3",
14
+ "qrcode": "^1.5.4",
15
+ "zod": "^3.23.8",
16
+ "commander": "^12.1.0"
17
+ },
18
+ "publishConfig": { "access": "public" }
19
+ }